/loxihart-ai:instrumenting-agent-telemetryfrom loxihart-ai
Instruments AI agents to produce observable telemetry — what to log at each agent step, which metrics signal health vs. degradation, how to wire PostHog (MCP connected) for agent-specific observability, and how to detect behavioral drift before it reaches users. Datadog is NOT connected — all Datadog steps including statsd custom metrics and monitor creation are static reference guides only, clearly labeled, and not executable via MCP. Use when setting up monitoring for an AI agent, wiring an agent to PostHog, figuring out what to log in agent interactions, detecting when an agent is getting worse, building dashboards for agent health, or setting alert thresholds for agent failure rates. Also triggers on: agent monitoring, agent observability, agent drift, agent performance tracking, LLM cost monitoring, tool call logging, agent latency, agent dashboard, agent metrics, is my agent getting worse, PostHog agent events.
Ships in loxihart-ai. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Agents are black boxes by default. This skill makes them transparent.
Live operational path: PostHog MCP ✅ Datadog: ❌ NOT connected — [STATIC REFERENCE] sections are manual setup guides only.
The distinction from application monitoring: standard APM tells you about infrastructure (CPU, memory, latency). Agent telemetry tells you about behavior — whether the agent is making the right decisions, calling the right tools, and producing quality outcomes over time.
| Tool | Status | Operational Path | Notes |
|---|---|---|---|
| PostHog | MCP ✅ CONNECTED | Live event queries, insight creation, alert config, session analysis | Primary agent observability path |
| Supabase | MCP ✅ CONNECTED | Structured agent event logging, durable backup store | Ask before write ops |
| n8n | MCP ✅ CONNECTED | Agent workflow execution status | |
| Datadog | ❌ NOT_CONNECTED | Static reference only — no MCP execution | from datadog import statsd requires Datadog agent running locally — not available here |
Rule: Any step in a [STATIC REFERENCE] section requires manual Datadog setup. Do not execute Datadog API calls, statsd emits, monitor creation, or dashboard operations in a Claude session — Datadog is not connected. Any claimed result would be fabricated.
from datadog import statsd or statsd.increment() as a live operational step — this requires a Datadog agent running locally, which is not available.posthog-node in client-side code or posthog-js in server-side code — the SDK choice is environment-specific."Just do it" override: if the user requests immediate setup, proceed with the PostHog-only live path, label Datadog steps as manual follow-ups, and continue without asking for clarification.
Should trigger:
Should NOT trigger:
Every agent interaction must emit at least one structured log entry. This is a ship gate — no agent goes to production without it.
{
"event": "agent_interaction",
"agent_id": "flashfusion-intake-agent",
"session_id": "uuid-anonymized",
"timestamp": "ISO-8601",
"input_tokens": 1240,
"output_tokens": 387,
"total_cost_usd": 0.0048,
"tools_called": ["search_kb", "create_ticket"],
"tool_errors": [],
"turns": 3,
"latency_ms": 2840,
"outcome": "completed | failed | escalated | timed_out",
"outcome_detail": "string — sanitized summary, no PII"
}
{
"event": "tool_call",
"session_id": "uuid-anonymized",
"tool_name": "create_ticket",
"input_hash": "sha256 of sanitized input — not raw input",
"success": true,
"error": null,
"duration_ms": 340
}
Do not log full tool inputs/outputs by default. They frequently contain PII or sensitive context. Log hashes or sanitized summaries. Full inputs only in an explicit debug mode with data handling controls in place.
| Metric | Healthy range | Alert threshold |
|---|---|---|
| Task completion rate | >92% | <85% |
| Tool call success rate | >97% | <90% |
| P95 latency | <8s | >15s |
| Error rate (unhandled) | <2% | >5% |
| Escalation rate | <10% | >20% |
These are starting-point thresholds. Calibrate against your agent's actual 1-week baseline before finalizing.
| Metric | Alert condition |
|---|---|
| Cost per session | >2× 7-day rolling average |
| Total daily cost | >$X (set per-agent budget ceiling) |
| Input token growth | >50% week-over-week |
| Sessions with >10 turns | >15% of total sessions |
High turn counts signal either a stuck agent loop or a user who is struggling — both are quality problems, not just cost ones.
PostHog is the live operational path for agent behavioral observability. Use it for funnels, session patterns, outcome trends, and cost analysis.
// server-side ONLY — posthog-node package
// posthog-js is for browser clients; never use it server-side for agent events
import { PostHog } from 'posthog-node'
// Loaded from environment variable — never hardcoded
const ph = new PostHog(process.env.POSTHOG_SERVER_KEY!)
// Emit after each agent session completes
ph.capture({
distinctId: sessionId, // anonymized UUID — not user email, not user name
event: 'agent_session_completed',
properties: {
agent_id: 'flashfusion-intake-agent',
outcome: 'completed', // completed | failed | escalated | timed_out
turns: 3,
tools_used: ['search_kb', 'create_ticket'],
tool_error_count: 0,
cost_usd: 0.0048,
input_tokens: 1240,
output_tokens: 387,
session_duration_ms: 2840,
// NEVER include: message_content, user_email, user_name, auth_token
}
})
// Emit per tool call for tool-level granularity
ph.capture({
distinctId: sessionId,
event: 'agent_tool_call',
properties: {
agent_id: 'flashfusion-intake-agent',
tool_name: 'create_ticket',
success: true,
duration_ms: 340,
error: null
}
})
agent_session_completed breakdown by outcome — percentage complete vs. escalate vs. fail vs. timed_outagent_session_completed sum cost_usd by dayagent_session_completed percentile on session_duration_msagent_tool_call where success = false as percentage of totalagent_session_completed where turns > 10 as percentage of totalagent_session_completed sum cost_usd breakdown by agent_idUse PostHog MCP to query insights in session:
"Pull agent_session_completed events from the last 7 days, breakdown by outcome, trend by day"
Create these four alerts in PostHog (Insights → Alerts):
agent_session_completed where outcome = completed falls below 85% of hourly sessions → alertsum(cost_usd) per hour exceeds 2× same-hour average from the prior 7 days → alertagent_session_completed where outcome = failed exceeds 5% over 15 minutes → alertavg(session_duration_ms) exceeds 15,000ms over a 10-minute window → alert⚠️ Datadog is NOT connected via MCP. The steps below require manual Datadog configuration and a Datadog agent running in your infrastructure. Do not execute these in a Claude session — they cannot be verified and any claimed result would be fabricated.
DD_LOGS_CONFIG_CONTAINER_COLLECT_ALL=true or equivalent)service:flashfusion-agentoutcome, agent_id, tool_name as indexed facets# Requires: pip install datadog
# Requires: Datadog agent running at DD_AGENT_HOST
# DD_AGENT_HOST loaded from environment variable — never hardcoded
from datadog import statsd
# Emit after each agent interaction
statsd.increment('agent.interactions.total', tags=[f'agent:{agent_id}', f'outcome:{outcome}'])
statsd.gauge('agent.latency_ms', latency_ms, tags=[f'agent:{agent_id}'])
statsd.gauge('agent.cost_usd', cost_usd, tags=[f'agent:{agent_id}'])
statsd.increment('agent.tool_calls.total', tags=[f'tool:{tool_name}', f'success:{success}'])
outcome:completed rate < 85% → alertagent.cost_usd sum > 2× same-hour yesterday → alertoutcome:failed rate > 5% → alertagent.latency_ms > 15,000ms → alertWhen Datadog connects via MCP: promote these steps to the live operational section, remove this [STATIC REFERENCE] block, and update DEPENDENCY_DECLARATION.
Pull these two reports weekly:
agent_tool_call breakdown by tool_name — compare this week vs. last weekagent_session_completed breakdown by outcome — this week vs. 30-day baselinePostHog MCP queries to run:
"Show me agent_tool_call events from the last 14 days, breakdown by tool_name, compare week-over-week" "Show me agent_session_completed events from the last 30 days, breakdown by outcome, trend by week"
If either report shows >10% relative change without a corresponding code or prompt change, investigate before assuming it is noise.
evaluating-ai-agents skill)If PostHog is unavailable or you need a durable structured store for agent events, write to Supabase:
CREATE TABLE agent_events (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
agent_id text NOT NULL,
session_id text NOT NULL,
event_type text NOT NULL, -- 'session_completed' | 'tool_call'
outcome text,
turns int,
cost_usd numeric(10,6),
latency_ms int,
tools_used text[],
tool_name text,
tool_success boolean,
created_at timestamptz DEFAULT now()
);
-- Restrict reads to service role; no user-facing query of raw agent events
ALTER TABLE agent_events ENABLE ROW LEVEL SECURITY;
CREATE POLICY "service_role_only" ON agent_events FOR ALL USING (false);
Query this table via Supabase MCP for ad-hoc analysis when PostHog is unavailable.
agent_session_completed events flowing to PostHog — FAIL if no events appear in PostHog Live Events after a test agent runagent_tool_call events emitted per tool call — FAIL if tool call granularity is absentCLAIMS
COUNTEREXAMPLE
CONTRADICTIONS
from datadog import statsd and four Datadog monitor creation steps as live operational steps. Datadog is NOT connected — those steps cannot execute via MCP and would require the Datadog agent running locally. The live path is PostHog. All Datadog content is now clearly labeled [STATIC REFERENCE].POSTHOG_SERVER_KEY rotation. Must be rotated per managing-credential-lifecycle schedule. No auto-rotation mechanism is in place.from datadog import statsd appears only inside a [STATIC REFERENCE] block, clearly marked as requiring manual setup and not executable via MCP. All four Datadog monitor creation steps likewise moved to [STATIC REFERENCE]. PostHog is the sole live operational path. All keys use environment variables. DEPENDENCY_DECLARATION and FAIL_IF blocks added. Version bumped to 2.0.0 (major — Datadog removed from live path, gate logic changed).What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub krosebrook/loxihart-skills --plugin loxihart-ai37 skills in this plugin
/ai-agents-workflowBuilds and implements AI agents, automation workflows, and tool integrations — MCP servers (2025 async, OAuth, stateless spec), LangChain and CrewAI agents, multi-LLM orchestration, and no-code platforms. Use when the user mentions: MCP server, build an agent, tool integration, API orchestration, multi-LLM routing, OAuth flow, webhook, connect services, deploy a workflow, integrate external APIs. Not for conceptual architecture overviews (use orchestrating-ai- agents), not for production n8n incident ops (use operating-n8n-production), and not for pure no-code platform wiring (use workflow-automation).
/ai-solution-architectureDesign pre-sales technical architectures for AI/ML solutions targeting B2B enterprise clients. Use when scoping AI implementations, designing reference architectures, mapping integration patterns, estimating infrastructure requirements, or preparing technical proposals. Triggers on solution design, AI architecture, technical scoping, integration mapping, infrastructure sizing, pre-sales engineering for AI projects./applying-adversarial-reviewApplies Kyle's adversarial review methodology to consequential outputs. Forces every recommendation, audit, plan, or claim through three checks before shipping: a CLAIMS / COUNTEREXAMPLE / CONTRADICTIONS footer, [SOURCED] vs [GENERATED] provenance labeling, and an agreement-streak flag at three consecutive consequential agreements. Use when finishing an audit, writing a recommendation, delivering a plan, drafting a decision memo, or producing any high-stakes deliverable. Also triggers when explicitly asked to pressure-test, stress-test, steelman, play devil's advocate, fight an idea, or check for blind spots. Triggers on: adversarial review, anti-sycophancy, claims footer, stress test this, steelman this, pressure test, devil's advocate, am I missing anything, what could go wrong, sourced vs generated, agreement streak, push back on this, where am I wrong, review this PR, pull request review, code review, PR feedback.
Other plugins' skills for the same job