
exploring-apm-traces
Investigates distributed application performance using PostHog APM (OpenTelemetry span) data via MCP. Use when the user asks about service traces, slow HTTP/database spans, error spans, error-rate trends or spikes, latency distributions, trace IDs, or span attributes — not AI observability traces or product logs. Uses posthog:apm-service-health, posthog:query-apm-spans, posthog:apm-trace-get, posthog:apm-spans-sparkline, posthog:apm-services-list, posthog:apm-attributes-list, and posthog:apm-attribute-values-list.
- Installs
- 197
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/posthog/ai-plugin --skill exploring-apm-traces- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads exploring-apm-traces automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Exploring APM traces (OpenTelemetry spans)
PostHog captures distributed traces from OpenTelemetry. Each trace is a tree of spans representing a request's path through services.
Disambiguation: This skill is for APM / OpenTelemetry traces. Do not confuse with AI observability traces (agent/model $ai_* events) or logs (posthog:query-logs, posthog:logs-*).
Governed metric first
When the question asks for SLO burn, call posthog:metric-list before the APM tools and look for slo_explicit_burn_by_operation. Run an approved, non-drifted match with posthog:data-catalog-metric-run for the canonical headline. If the user also asks which operation drives the burn, answer the headline first, then use the aggregate and trace workflows below for a noncanonical breakdown. If no governed metric matches, say so and label the derived measure noncanonical.
Available tools
| Tool | Purpose |
|---|---|
posthog:apm-service-health | Status per service against a baseline: start here |
posthog:query-apm-spans | Search and filter spans (compact list view) |
posthog:apm-trace-get | Get the full span list for one hex trace_id |
posthog:apm-spans-aggregate | Per-operation aggregates (count, p50/p95, errors) |
posthog:apm-spans-tree | Call-tree aggregates per (parent, child) edge |
posthog:apm-spans-count | Scalar span count — cheap filter pre-flight |
posthog:apm-spans-sparkline | Span counts over time (zero-filled time series) |
posthog:apm-spans-duration-histogram | Trace counts per log-scale duration bucket |
posthog:apm-attribute-breakdown | Span counts grouped by one attribute's value |
posthog:apm-services-list | List distinct service names |
posthog:apm-attributes-list | List span or resource attribute keys |
posthog:apm-attribute-values-list | List values for a specific attribute key |
See references/spans-and-fields.md for the response schema and the kind/status_code enums.
Workflow: debug a trace from a URL
Step 1 — Fetch the trace
posthog:apm-trace-get
{
"trace_id": "<hex_trace_id>"
}
The response is { results: [span, span, …], _posthogUrl: "…" } — a flat list of every span in the trace.
The list can be very large for fan-out request flows; when it exceeds the inline limit, Claude Code auto-persists it to a file.
From the result you get:
- Every span with
name,service_name,kind,status_code,parent_span_id,duration_nano,is_root_span - The
_posthogUrl— a deep link to this trace in the tracing UI; always include this in your response so the user can click through
Step 2 — Parse large results with scripts
When the result is persisted to a file (traces with hundreds of spans across services), use the parsing scripts to explore it.
Start with the summary to get the full picture, then drill into specifics:
# 1. Overview: services, span count, slowest spans, errors
python3 scripts/print_summary.py /path/to/persisted-file.json
# 2. Indented chronological tree (DFS by parent_span_id)
python3 scripts/print_timeline.py /path/to/persisted-file.json
# 3. Drill into a specific span by name
SPAN="HTTP GET /api/users" python3 scripts/extract_span.py /path/to/persisted-file.json
# 4. Search for a keyword across span names, services, IDs
SEARCH="keyword" python3 scripts/search_spans.py /path/to/persisted-file.json
# 5. When the JSON shape looks unfamiliar
python3 scripts/show_structure.py /path/to/persisted-file.json
All scripts support MAX_LEN=N env var to control truncation (0 = unlimited).
Tree reconstruction (parent_span_id → span_id)
The flat span list is a tree. Each span carries:
trace_id— same on every span in the tracespan_id— this span's unique hex IDparent_span_id— points to the parent'sspan_id(zero-padded hex000…000for the root)is_root_span— convenience flag for the trace entry
To rebuild the tree:
- Spans where
is_root_spanis true (orparent_span_id == "00000000…") are root spans. - Every other span is a child of the span whose
span_idmatches itsparent_span_id. - Group by
parent_span_id, walk from each root downward.
scripts/print_timeline.py does this for you and prints a DFS-indented tree.
Investigation patterns
"How healthy are my services?" (start here)
apm-service-healthscores every service in one call: requests, error rate, p50/p95/p99, the change from a baseline window, and astatus(silent,regressed,degraded,new,recovered,improved,ok) with areason. Rows come worst first.- Pick the baseline with
compare:previous_period(default),previous_day,previous_week, or an explicitbaselineDateRangenext toquery. Scope withenvironmentandserviceNames. - Run the calls in
next. They are prefilled:apm-spans-aggregatefor the operations behind the regressed and degraded services,apm-spans-sparklinefor when a silent service stopped,query-apm-spansfor error spans. - Do not build a service summary from
apm-spans-aggregaterows or from oneapm-spans-countcall per service. Percentiles of operation rows do not add up to a service percentile.
Daily service health report
apm-service-healthwithdateRange: {"date_from": "-24h"}, andcompare: "previous_day". Follow itsnextcalls to the operations behind each unhealthy service.logs-patterns-difffor new error patterns in the services that are notok.logs-alerts-listfor alerts that fired in the window.
"Where is time going?"
- Every span from
apm-trace-getcarriesself_time_nano— duration not covered by children. Sort by it: the top span is where wall-clock actually went. A parent with largeself_time_nanois an uninstrumented gap (the work happened inside it, not in any recorded child). - Run
print_summary.py— it surfaces the top-5 slowest spans byduration_nano. - For a noisy trace, run
print_timeline.pyand scan the indented durations — you can see whether time is dominated by one child span or fan-out across many. - To dig into one slow span,
SPAN="<name>" python3 scripts/extract_span.py FILE. - For aggregate "which child dominates" questions use
apm-spans-treeand readcalls_per_parent_invocation— it separates a child that's slow per call from one that merely runs 20× per parent.
"Where did the error happen?"
print_summary.pylists every span withstatus_code == 2(Error). Each entry shows service, span name, and parent context.- Walk up the tree from an error span via
parent_span_idto see what request path led there. - Error detail lives in each span's
attributesmap (e.g.exception.message,exception.type), which is returned in the trace payload — read it directly off the error span.apm-attribute-values-listis for discovering values across spans, not a prerequisite for reading one span's attributes.
"Did the request hit service X?"
- Run
print_summary.py— it prints the set of services involved in the trace. - If service X is missing, the request never reached it (or instrumentation is missing — check
apm-service-healthwithserviceNames: ["X"]to see whether X emitted spans recently, and when it stopped).
"What's different about the bad spans?" (over-represented values)
- Scope to the bad population:
filterGroupwithstatus_code = Error, or adurationthreshold. - Discover candidate keys with
apm-attributes-list— typical suspects:server.address,http.response.status_code,db.system, resource keys likek8s.pod.name/service.version. - Run
apm-attribute-breakdownper candidate key on the bad set. A value owning most of thecountis the signature. - Confirm over-representation: re-run without the bad-set filter (or compare
error_count / countper row). A value at 95% of errors but 10% of traffic is the culprit; one at 95% of both is just volume.
"When did it spike?" (trends over time)
apm-spans-sparklinewith your filters → total counts per time bucket (zero-filled, ~50 adaptive buckets per window).- The same call with
statusCodes: [2]→ error counts per bucket. - Error rate per bucket = errors / total; the bucket where the ratio jumps is when the spike started.
- Zoom in: re-run with a narrower
dateRangearound that bucket, then pull raw spans viaquery-apm-spans.
"What does the latency distribution look like?"
apm-spans-duration-histogram→ trace counts per log-scale (1-2-5 series) duration bucket of the ROOT span.- A second hump or a fat tail = a distinct slow population; note its
bucket_nsrange. - Fetch the actual slow traces with
query-apm-spansusing adurationfilter (nanoseconds) andorderBy: "duration".
"Did the fan-out look right?"
print_timeline.pyshows the indentation — wide trees mean parallel calls, deep trees mean sequential dependencies.- Look for spans of kind
Client(3) followed by matchingServer(2) spans on the called service — that's a synchronous downstream call.
Searching by attribute (e.g. http.method=POST)
Each span carries an attributes map (span-level OTel attributes like http.method, db.statement) in the payload — so for a span you already have, just read it. Resource attributes (k8s labels, service.version) are not in the payload. To filter the whole dataset by an attribute:
- Use
apm-attributes-list/apm-attribute-values-listto discover keys and values (resource attributes especially). - Re-issue
query-apm-spanswith afilterGroupentry of typespan_attributeorspan_resource_attribute.
Constructing UI links
apm-trace-get returns a _posthogUrl deep link that opens the trace in the tracing UI — always surface this to the user so they can verify in the PostHog UI.
query-apm-spans does not return _posthogUrl.
To link a trace found via the query tool, feed its trace_id to apm-trace-get and surface the _posthogUrl from that response.
Never hand-construct PostHog URLs.
Finding traces
Use posthog:query-apm-spans to search and filter spans. Note this returns spans, not a tree — pass query.traceId or grab a trace_id from the results and feed it to apm-trace-get for the tree.
Discover before filtering
Before constructing filters, discover what's actually in the project:
- Confirm services exist — call
apm-services-listto see which services have emitted spans. - Find filterable attributes — call
apm-attributes-listwithattribute_type: "span"or"resource". - Get actual values — call
apm-attribute-values-listwith a key to see the real values in use.
Only then construct query-apm-spans filters. Custom attributes vary per project and cannot be guessed.
By filters
posthog:query-apm-spans
{
"query": {
"serviceNames": ["api-gateway"],
"dateRange": {"date_from": "-1h"},
"filterGroup": [
{"key": "http.status_code", "operator": "gt", "type": "span_attribute", "value": "499"}
]
}
}
By trace ID (when known)
posthog:apm-trace-get
{
"trace_id": "0123456789abcdef0123456789abcdef"
}
Common gotchas
- Durations are nanoseconds. 1 second =
1_000_000_000. Filter values inquery-apm-spansfordurationare also nanoseconds. status_code == 2is Error.0is Unset,1is OK. UseOKto match{0, 1}in the UI filter.kindis an integer 0–5: 0 Unspecified, 1 Internal, 2 Server, 3 Client, 4 Producer, 5 Consumer.parent_span_idof a root span is"0000000000000000"(16 zero hex chars, matching the 8-byte span ID width — not the 16-byte trace ID width), not null.
Parsing large trace results
Trace tool results are JSON. When too large to read inline, Claude Code persists them to a file.
Persisted file format
[{ "type": "text", "text": "{\"results\": [...], \"_posthogUrl\": \"...\"}" }]
Every script in scripts/ unwraps this envelope before parsing.
Trace JSON structure
results (array of span dicts)
└── each span:
├── uuid, trace_id, span_id, parent_span_id (hex strings)
├── name, kind (int 0–5), service_name
├── status_code (int 0–2), is_root_span (bool)
├── timestamp, end_time (ISO 8601)
├── duration_nano (int, nanoseconds)
├── attributes (map of span-level OTel attributes, e.g. db.statement, http.url)
└── matched_filter (0/1 — 1 if this span matched the query-apm-spans filter, 0 if it
only shares a trace with a match; always present, only meaningful from query-apm-spans)
Available scripts
| Script | Purpose | Usage |
|---|---|---|
print_summary.py | Trace metadata, services, slowest spans, errors | python3 scripts/print_summary.py FILE |
print_timeline.py | DFS-indented tree from parent_span_id walk | python3 scripts/print_timeline.py FILE |
extract_span.py | Full row + parent/children for spans matching a name | SPAN="name" python3 scripts/extract_span.py FILE |
search_spans.py | Find a keyword across name, service_name, IDs | SEARCH="kw" python3 scripts/search_spans.py FILE |
show_structure.py | Show JSON keys and types without values | python3 scripts/show_structure.py FILE |
Tips
- Always set
dateRangeonquery-apm-spans— queries without a time range are slow. Default is-1h; widen only when needed. - Always include the
_posthogUrlfromapm-trace-getin your response so the user can click through to the trace. - Span-level attributes are in the
apm-trace-get/query-apm-spanspayload (each span'sattributesmap). Resource attributes are not — useapm-attributes-list(typeresource) andapm-attribute-values-listfor those. is_root_spanis the cheap way to find the trace entry — don't string-match00000000….- For aggregates (p95 by operation, slowest children of a span), use
apm-spans-aggregatefor a flat view orapm-spans-treefor parent→child edges — don't reach for SQL.
FAQ
What does the exploring-apm-traces skill do?
Investigates distributed application performance using PostHog APM (OpenTelemetry span) data via MCP. Use when the user asks about service traces, slow HTTP/database spans, error spans, error-rate trends or spikes, latency distributions, trace IDs, or span attributes — not AI observability traces or product logs. Uses posthog:apm-service-health, posthog:query-apm-spans, posthog:apm-trace-get, posthog:apm-spans-sparkline, posthog:apm-services-list, posthog:apm-attributes-list, and posthog:apm-attribute-values-list.
How do I install exploring-apm-traces?
Run npx skills add https://github.com/posthog/ai-plugin --skill exploring-apm-traces in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/exploring-apm-traces/ (personal) or .claude/skills/exploring-apm-traces/ (project).
Which AI agents can use exploring-apm-traces?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is exploring-apm-traces safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains exploring-apm-traces?
It is published by posthog in posthog/ai-plugin, and it is an official skill from the maker of the technology it covers. It has 197 recorded installs.
More from posthog/ai-plugin
instrument-product-analytics
posthog/ai-plugin
Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.
instrument-feature-flags
posthog/ai-plugin
Open the skill to read its SKILL.md instructions.
cleaning-up-stale-feature-flags
posthog/ai-plugin
Identify stale feature flags in a PostHog project and clean up the code that checks them. Use when the user wants to find, audit, or remove unused, fully rolled out, or abandoned feature flags, run a feature flag hygiene review or a weekly cleanup, reduce feature flag tech debt, or asks "which flags can I remove?". When the agent can read and edit a repository it performs the code cleanup itself: tested local changes, and one draft PR per flag when the user authorizes publishing. Agents without repository access generate a tailored cleanup prompt instead. Covers staleness detection, dependency checking, retained-path rules, and the code-first ordering. This skill does not archive or otherwise change a flag in PostHog.
auditing-experiments-flags
posthog/ai-plugin
Audit PostHog experiments and feature flags for configuration issues, staleness, and best-practice violations. Read when the user asks to audit, health-check, or review experiments or feature flags, check flag hygiene, or verify experiment setup.
querying-posthog-data
posthog/ai-plugin
Explains how to query PostHog data, defaulting to typed runners for supported product analytics. Read it before you write HogQL/SQL. Also read it before you call execute-sql against PostHog. Use it to find or aggregate PostHog entities. These entities include insights, dashboards, cohorts, feature flags, experiments, surveys, hog flows, warehouse data, and persons. Use it for trends, funnels, retention, lifecycle, paths, stickiness, web analytics, error tracking, logs, sessions, and LLM traces. Before you calculate a governed business or telemetry measure, check system.informationschema.metrics for an approved definition. Examples include MRR, activation, billable usage, active organizations, and failure rates. Use the approved definition before you derive a measure from raw events or use a typed domain tool. It also covers HogQL differences, system table schemas, functions, query examples, and schema discovery.
creating-experiments
posthog/ai-plugin
Guides agents through experiment creation: reading the project's setup with experiment-setup-context, defining the hypothesis, configuring rollout and bucketing, setting up analytics and running time, and reporting which choices are guesses. Delegates rollout decisions to configuring-experiment-rollout and metric setup to configuring-experiment-analytics. TRIGGER when: user asks to create a new experiment or A/B test, OR when you are about to call experiment-create. DO NOT TRIGGER when: user is updating an existing experiment, managing lifecycle, or only browsing experiments.
Popular data & databases skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-client-api
prisma/skills
Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
prisma-database-setup
prisma/skills
Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.
prisma-cli
prisma/skills
Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.
prisma-postgres
prisma/skills
Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.
prisma-driver-adapter-implementation
prisma/skills
Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.