Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): record which skill a skill-* read fetched (#88843)

Daniel Viscac86295e66bcb
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 86ccd94ed8b6..62d688b004ef 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -2336,6 +2336,22 @@
"description": "Transport-level session handle the MCP SDK observed for this request (e.g. MCP `extra.sessionId` or a framework session cookie). Rotates per process restart, reconnect, or framework boundary \u2014 use $mcp_conversation_id when you need a stable identifier across reconnects.",
"label": "MCP session ID"
},
+ "$mcp_skill_body_offset": {
+ "description": "Where in a skill's body a `skill-get` started reading. Long bodies come back in slices, so one skill load is several calls that differ only by this offset. Count calls at offset 0 for loads, or all calls for pages read. Set only on reads that succeeded, like `$mcp_skill_name`. Absent when the caller asked for the whole body, and never set on `skill-file-get`, which does not paginate.",
+ "examples": [
+ "0",
+ "5000"
+ ],
+ "label": "MCP skill body offset"
+ },
+ "$mcp_skill_name": {
+ "description": "The stored skill a skill-* read tool returned, on `skill-get` and `skill-file-get` (and their `llma-skill-*` aliases). Present only when the read succeeded, so counting these events counts skills that were actually delivered. A failed read carries no skill name, which stops a deleted skill that agents keep requesting from reading as a popular one. Recorded only when the value matches the shape the skills store enforces at creation, so a name the agent invented is left off rather than echoed. Skill writes are not stamped here; those emit `llma skill *` from the skills API.",
+ "examples": [
+ "prove-the-change",
+ "pr-shepherd"
+ ],
+ "label": "MCP skill name"
+ },
"$mcp_source": {
"description": "Constant identifier for the analytics SDK that emitted the event. Lets you separate events from different SDK versions or unrelated MCP servers.",
"examples": [
@@ -4096,6 +4112,10 @@
"ignored_in_assistant": true,
"label": "Set person properties"
},
+ "$slack_message_received": {
+ "description": "Fires when a message is posted in a Slack channel PostHog is connected to.",
+ "label": "Slack message received"
+ },
"$snapshot": {
"description": "Carries session replay data to the backend. These events do not contribute to event counts.",
"ignored_in_assistant": true,
@@ -4501,6 +4521,22 @@
"description": "Transport-level session handle the MCP SDK observed for this request (e.g. MCP `extra.sessionId` or a framework session cookie). Rotates per process restart, reconnect, or framework boundary \u2014 use $mcp_conversation_id when you need a stable identifier across reconnects.",
"label": "MCP session ID"
},
+ "$mcp_skill_body_offset": {
+ "description": "Where in a skill's body a `skill-get` started reading. Long bodies come back in slices, so one skill load is several calls that differ only by this offset. Count calls at offset 0 for loads, or all calls for pages read. Set only on reads that succeeded, like `$mcp_skill_name`. Absent when the caller asked for the whole body, and never set on `skill-file-get`, which does not paginate.",
+ "examples": [
+ "0",
+ "5000"
+ ],
+ "label": "MCP skill body offset"
+ },
+ "$mcp_skill_name": {
+ "description": "The stored skill a skill-* read tool returned, on `skill-get` and `skill-file-get` (and their `llma-skill-*` aliases). Present only when the read succeeded, so counting these events counts skills that were actually delivered. A failed read carries no skill name, which stops a deleted skill that agents keep requesting from reading as a popular one. Recorded only when the value matches the shape the skills store enforces at creation, so a name the agent invented is left off rather than echoed. Skill writes are not stamped here; those emit `llma skill *` from the skills API.",
+ "examples": [
+ "prove-the-change",
+ "pr-shepherd"
+ ],
+ "label": "MCP skill name"
+ },
"$mcp_source": {
"description": "Constant identifier for the analytics SDK that emitted the event. Lets you separate events from different SDK versions or unrelated MCP servers.",
"examples": [
@@ -7260,6 +7296,22 @@
"description": "Transport-level session handle the MCP SDK observed for this request (e.g. MCP `extra.sessionId` or a framework session cookie). Rotates per process restart, reconnect, or framework boundary \u2014 use $mcp_conversation_id when you need a stable identifier across reconnects.",
"label": "MCP session ID"
},
+ "$mcp_skill_body_offset": {
+ "description": "Where in a skill's body a `skill-get` started reading. Long bodies come back in slices, so one skill load is several calls that differ only by this offset. Count calls at offset 0 for loads, or all calls for pages read. Set only on reads that succeeded, like `$mcp_skill_name`. Absent when the caller asked for the whole body, and never set on `skill-file-get`, which does not paginate.",
+ "examples": [
+ "0",
+ "5000"
+ ],
+ "label": "MCP skill body offset"
+ },
+ "$mcp_skill_name": {
+ "description": "The stored skill a skill-* read tool returned, on `skill-get` and `skill-file-get` (and their `llma-skill-*` aliases). Present only when the read succeeded, so counting these events counts skills that were actually delivered. A failed read carries no skill name, which stops a deleted skill that agents keep requesting from reading as a popular one. Recorded only when the value matches the shape the skills store enforces at creation, so a name the agent invented is left off rather than echoed. Skill writes are not stamped here; those emit `llma skill *` from the skills API.",
+ "examples": [
+ "prove-the-change",
+ "pr-shepherd"
+ ],
+ "label": "MCP skill name"
+ },
"$mcp_source": {
"description": "Constant identifier for the analytics SDK that emitted the event. Lets you separate events from different SDK versions or unrelated MCP servers.",
"examples": [
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 0d7947daa273..d25cae2a69ef 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2714,6 +2714,16 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"Fetch the trace referenced by an AI observability URL.",
],
},
+ "$mcp_skill_name": {
+ "label": "MCP skill name",
+ "description": "The stored skill a skill-* read tool returned, on `skill-get` and `skill-file-get` (and their `llma-skill-*` aliases). Present only when the read succeeded, so counting these events counts skills that were actually delivered. A failed read carries no skill name, which stops a deleted skill that agents keep requesting from reading as a popular one. Recorded only when the value matches the shape the skills store enforces at creation, so a name the agent invented is left off rather than echoed. Skill writes are not stamped here; those emit `llma skill *` from the skills API.",
+ "examples": ["prove-the-change", "pr-shepherd"],
+ },
+ "$mcp_skill_body_offset": {
+ "label": "MCP skill body offset",
+ "description": "Where in a skill's body a `skill-get` started reading. Long bodies come back in slices, so one skill load is several calls that differ only by this offset. Count calls at offset 0 for loads, or all calls for pages read. Set only on reads that succeeded, like `$mcp_skill_name`. Absent when the caller asked for the whole body, and never set on `skill-file-get`, which does not paginate.",
+ "examples": ["0", "5000"],
+ },
"$mcp_resource_name": {
"label": "MCP resource name",
"description": "The name of the MCP resource, prompt, or tool the event refers to.",
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 1ce2716ee0b6..bb88f6c8b77b 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -26,11 +26,14 @@ import {
describeExecCommand,
describeValidationError,
formatInputValidationError,
+ parseExecCallInnerArgs,
+ parseExecCallInnerToolName,
type ExecCommandMeta,
type ExecInnerCallTracker,
} from '@/tools/exec'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
import { createRenderUiTool } from '@/tools/render-ui'
+import { skillAnalyticsProperties } from '@/tools/skills/analytics'
import type { Context, Tool, ZodObjectAny } from '@/tools/types'
import {
@@ -229,6 +232,12 @@ export class ToolExecutor {
const stop = toolCallDurationSeconds.startTimer({ tool: tool.name })
const startMs = Date.now()
+ // Which stored skill a skill-* read returned. Empty for every other tool, and
+ // stamped only on success: a read that failed delivered no skill, so counting
+ // it would let a deleted skill agents keep requesting read as a popular one.
+ // The exec path stamps the same properties from its command string.
+ const skillShape = skillAnalyticsProperties(tool.name, validation.data)
+
try {
const isContextSwitch = tool.name === 'switch-project' || tool.name === 'switch-organization'
const previousContext = isContextSwitch
@@ -270,6 +279,7 @@ export class ToolExecutor {
false,
state,
{
+ ...skillShape,
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
},
@@ -371,6 +381,9 @@ export class ToolExecutor {
// one opaque `exec` bucket and an `info <tool>` can be linked to the
// `call <tool>` that follows it.
const execShape = execCommandAnalyticsProperties(validation.data, state)
+ // Which stored skill an exec-routed read returned. Success only, unlike the
+ // verb above: that records what the agent attempted, this records what it got.
+ const execSkillShape = execSkillAnalyticsProperties(validation.data)
try {
const handlerResult = await resolved.handler(state.context, validation.data)
@@ -394,6 +407,7 @@ export class ToolExecutor {
state,
{
...execShape,
+ ...execSkillShape,
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
...execMetrics.commandMeta,
@@ -817,3 +831,19 @@ function execCommandAnalyticsProperties(execArgs: unknown, state: ResolvedState)
...(targetTool !== undefined ? { $mcp_exec_target_tool: targetTool } : {}),
}
}
+
+/**
+ * The skill properties for an exec-routed read, recovered from the command string.
+ *
+ * In single-exec mode the inner tool's arguments never arrive as tool arguments —
+ * they are JSON inside `command` — so the direct-mode wiring alone would miss the
+ * skill reads that arrive this way, which is nearly all of them. Reads the command with the
+ * dispatcher's own parsers so analytics sees exactly the arguments the handler runs.
+ */
+function execSkillAnalyticsProperties(execArgs: unknown): Record<string, unknown> {
+ const command = (execArgs as { command?: unknown } | undefined)?.command
+ if (typeof command !== 'string') {
+ return {}
+ }
+ return skillAnalyticsProperties(parseExecCallInnerToolName(command), parseExecCallInnerArgs(command))
+}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index a9a222418c54..a8a826fc8f30 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -175,6 +175,38 @@ export function parseExecCallInnerToolName(command: string): string | undefined
return innerName || undefined
}
+// Extracts the inner tool's JSON arguments from an exec `call` command, e.g.
+// `call skill-get {"skill_name":"x"}` → `{ skill_name: 'x' }`. Sibling of
+// parseExecCallInnerToolName, and deliberately mirrors how the `call` handler
+// below reads the same command — a body-less call is `{}` there, so it is `{}`
+// here. Returns undefined when no inner arguments exist to read: another verb,
+// or a body that is not a JSON object. Analytics uses this because in
+// single-exec mode the arguments never arrive as tool arguments, so a property
+// derived only from those would miss nearly every skill read.
+export function parseExecCallInnerArgs(command: string): Record<string, unknown> | undefined {
+ const { verb, rest } = parseCommand(command)
+ if (verb !== 'call' || !rest) {
+ return
+ }
+ const callArgs = parseCallFlags(rest).rest
+ if (!callArgs) {
+ return
+ }
+ const { rest: jsonBody } = parseCommand(callArgs)
+ if (!jsonBody) {
+ return {}
+ }
+ try {
+ const parsed: unknown = JSON.parse(jsonBody)
+ // Arrays and `null` are typeof 'object'; only a plain object holds arguments.
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : undefined
+ } catch {
+ return
+ }
+}
+
/** Verbs the dispatcher grammar accepts. A verb outside this set is what the
* `unknown_command` rejection fires on, and is recorded as unrecognized. */
const KNOWN_EXEC_VERBS = new Set(['learn', 'tools', 'search', 'info', 'schema', 'call'])
diff --git a/services/mcp/src/tools/skills/analytics.ts b/services/mcp/src/tools/skills/analytics.ts
new file mode 100644
index 000000000000..9fbe3f1182ba
--- /dev/null
+++ b/services/mcp/src/tools/skills/analytics.ts
@@ -0,0 +1,79 @@
+/**
+ * Analytics properties identifying which stored skill a skill-* read touched.
+ *
+ * Reading a stored skill is one of the most common MCP tool calls, but until now
+ * `$mcp_tool_call` recorded only that *a* skill was read, never which one — so
+ * "which skills does anyone actually use" was unanswerable, and the skills
+ * product had to fall back on publish-recency and version churn as a proxy.
+ *
+ * Scope is deliberately narrow:
+ *
+ * - **Reads only.** Writes already emit `llma skill *` server-side from
+ * `products/skills/backend/api/skills.py`; stamping them here would give two
+ * disagreeing sources for the same fact.
+ * - **No file path.** `$mcp_tool_name` already distinguishes a body read from a
+ * bundled-file read, which is the signal that matters (did progressive
+ * disclosure get exercised). The path itself buys nothing yet.
+ * - **Value-free by construction**, the rule `execCommandAnalyticsProperties`
+ * states: a name is recorded only if it matches the shape the store enforces
+ * at creation. Anything else is the agent's own text and is dropped rather
+ * than echoed into analytics.
+ */
+
+/** The store's own constraint: lowercase alphanumerics and hyphens, max 64 chars.
+ * Enforced at skill creation, so a value outside it never named a real skill. */
+const RECORDABLE_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/
+
+/** Read tools that name a single skill. The `llma-skill-*` entries are the
+ * deprecated aliases from `deprecatedAliases.ts`, which reach analytics under
+ * their own name and would otherwise be a silent hole in the data. */
+const SKILL_READ_TOOLS = new Set(['skill-get', 'skill-file-get', 'llma-skill-get', 'llma-skill-file-get'])
+
+/** Only `skill-get` pages a body; the offset is meaningless on the others. */
+const BODY_PAGINATED_TOOLS = new Set(['skill-get', 'llma-skill-get'])
+
+function recordableSkillName(value: unknown): string | undefined {
+ return typeof value === 'string' && RECORDABLE_SKILL_NAME.test(value) ? value : undefined
+}
+
+/** A whole, non-negative offset — anything else says more about a malformed call
+ * than about paging, and a wrong number here would be read as a real page. */
+function recordableBodyOffset(value: unknown): number | undefined {
+ if (typeof value !== 'number' && typeof value !== 'string') {
+ return
+ }
+ const offset = Number(value)
+ return Number.isSafeInteger(offset) && offset >= 0 ? offset : undefined
+}
+
+/**
+ * Properties describing the skill a read tool targeted: `$mcp_skill_name`, plus
+ * `$mcp_skill_body_offset` on the paginated body read.
+ *
+ * The offset exists so paging does not read as usage. `skill-get` returns a body
+ * in slices, and an agent reading one skill emits several calls that differ only
+ * by offset — so `count()` overstates loads several-fold. With the offset stamped,
+ * first-page calls are the load count and the rest are visibly continuations.
+ *
+ * `args` is whatever the caller has: parsed tool arguments in direct mode, or the
+ * output of `parseExecCallInnerArgs` in single-exec mode. Malformed input yields
+ * no properties rather than throwing — analytics must never break a tool call.
+ */
+export function skillAnalyticsProperties(toolName: string | undefined, args: unknown): Record<string, unknown> {
+ if (!toolName || !SKILL_READ_TOOLS.has(toolName)) {
+ return {}
+ }
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {
+ return {}
+ }
+ const { skill_name: skillNameArg, body_offset: bodyOffsetArg } = args as Record<string, unknown>
+ const skillName = recordableSkillName(skillNameArg)
+ if (!skillName) {
+ return {}
+ }
+ const bodyOffset = BODY_PAGINATED_TOOLS.has(toolName) ? recordableBodyOffset(bodyOffsetArg) : undefined
+ return {
+ $mcp_skill_name: skillName,
+ ...(bodyOffset !== undefined ? { $mcp_skill_body_offset: bodyOffset } : {}),
+ }
+}
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index b03bbc66b78c..8fb0f090062c 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -582,5 +582,133 @@ describe('ToolExecutor metrics', () => {
$mcp_error_message: 'Exec command rejected: missing_scope',
})
})
+
+ // Reading a stored skill is one of the most common tool calls, and nearly all of
+ // them arrive here, as JSON inside a command string rather than as tool arguments.
+ // Without this the event records that *a* skill was read but never which one.
+ describe('skill reads', () => {
+ function lastExtras(): Record<string, unknown> {
+ return (mockTrackToolCall.mock.calls.at(-1)?.[4] ?? {}) as Record<string, unknown>
+ }
+
+ /** A context whose skill fetch resolves, so the success path runs. */
+ function contextThatServes(): any {
+ return {
+ api: { request: vi.fn().mockResolvedValue({ name: 'conductor', body: 'skill body' }) },
+ cache: {},
+ env: {},
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('2') },
+ sessionManager: {},
+ getDistinctId: vi.fn(),
+ trackEvent: vi.fn(),
+ }
+ }
+
+ /** A context whose skill fetch 404s — a deleted, renamed, or unreadable skill. */
+ function contextThatRejects(): any {
+ return {
+ ...contextThatServes(),
+ api: {
+ request: vi.fn().mockRejectedValue(
+ new PostHogApiError({
+ status: 404,
+ statusText: 'Not Found',
+ body: '{"detail":"Not found."}',
+ url: 'https://us.posthog.com/api/projects/2/llm_skills/name/conductor/',
+ method: 'GET',
+ })
+ ),
+ },
+ }
+ }
+
+ function execStateWith(context: any): ResolvedState {
+ return { ...execState(), context }
+ }
+
+ it.each([
+ ['a body read', 'call skill-get {"skill_name":"conductor"}', { $mcp_skill_name: 'conductor' }],
+ [
+ 'a paged continuation',
+ 'call skill-get {"skill_name":"conductor","body_offset":5000}',
+ { $mcp_skill_name: 'conductor', $mcp_skill_body_offset: 5000 },
+ ],
+ [
+ 'a bundled-file read',
+ 'call skill-file-get {"skill_name":"conductor","file_path":"references/x.md"}',
+ { $mcp_skill_name: 'conductor' },
+ ],
+ ])('records the skill when %s succeeds', async (_label, command, expected) => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command } },
+ execStateWith(contextThatServes())
+ )
+
+ expect(lastExtras()).toMatchObject(expected)
+ })
+
+ // A skill that was never delivered is not usage. Stamping it would let a
+ // deleted skill that agents keep requesting read as popular.
+ it.each([
+ ['a body read', 'call skill-get {"skill_name":"conductor","body_offset":5000}'],
+ ['a bundled-file read', 'call skill-file-get {"skill_name":"conductor","file_path":"x.md"}'],
+ ])('records no skill when %s fails', async (_label, command) => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command } },
+ execStateWith(contextThatRejects())
+ )
+
+ expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')
+ expect(lastExtras()).not.toHaveProperty('$mcp_skill_body_offset')
+ })
+
+ // Dropping the skill must not take the exec properties with it — those are
+ // stamped on failures by design, and are the only record of what was tried.
+ it('keeps the exec verb and target when a skill read fails', async () => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'call skill-get {"skill_name":"conductor"}' } },
+ execStateWith(contextThatRejects())
+ )
+
+ expect(lastExtras()).toMatchObject({
+ $mcp_exec_verb: 'call',
+ $mcp_exec_target_tool: 'skill-get',
+ })
+ })
+
+ it.each([
+ // The agent's text, not a skill that could exist — same rule the exec
+ // verb and target follow.
+ ['a skill name outside the store’s own shape', 'call skill-get {"skill_name":"../../etc/passwd"}'],
+ ['a non-skill tool', 'call docs-search {"query":"skill_name"}'],
+ ])('records no skill for %s', async (_label, command) => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command } },
+ execStateWith(contextThatServes())
+ )
+
+ expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')
+ })
+
+ it('records the skill in direct tools mode too', async () => {
+ const tools = catalog.getPreBuiltEntries().map((entry) => {
+ const preBuilt = catalog.getToolByName(entry.name)!
+ return {
+ ...preBuilt.base,
+ title: entry.title,
+ description: entry.description ?? '',
+ annotations: entry.annotations,
+ scopes: [],
+ }
+ })
+
+ await executor.handleToolCall(
+ { name: 'skill-get', arguments: { skill_name: 'conductor' } },
+ makeState(tools as any, { context: contextThatServes() })
+ )
+
+ expect(trackToolCallExtras('skill-get')).toMatchObject({ $mcp_skill_name: 'conductor' })
+ })
+ })
})
})
diff --git a/services/mcp/tests/integration/skill-analytics.integration.test.ts b/services/mcp/tests/integration/skill-analytics.integration.test.ts
new file mode 100644
index 000000000000..bfce36b15fc8
--- /dev/null
+++ b/services/mcp/tests/integration/skill-analytics.integration.test.ts
@@ -0,0 +1,189 @@
+import http from 'node:http'
+import { gunzipSync } from 'node:zlib'
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+/**
+ * End-to-end proof that a real skill read reaches PostHog carrying the skill's name.
+ *
+ * Only the destination is substituted: a local HTTP sink stands in for ingestion so
+ * the outbound payload can be read. Everything upstream is real — the real
+ * ToolExecutor, the real `exec` dispatcher, the real `skill-get` handler fetching a
+ * real skill over HTTPS, and the real analytics client serializing the event.
+ *
+ * POSTHOG_PERSONAL_API_KEY=... npx vitest run \
+ * tests/integration/skill-analytics.integration.test.ts \
+ * --config vitest.integration.config.mts
+ *
+ * Run by hand, not by CI. It reads `POSTHOG_PERSONAL_API_KEY` rather than the
+ * `TEST_`-prefixed variables the CI integration job supplies, so it always skips
+ * there. That is deliberate: it names one skill on one real instance, which is a
+ * fact about that project rather than about this code, so asserting it in CI would
+ * fail against the e2e stack and add a network dependency to a suite that has none.
+ * The wiring itself is covered by the unit and hono suites, which do run in CI.
+ */
+
+const API_TOKEN = process.env.POSTHOG_PERSONAL_API_KEY
+const API_HOST = process.env.POSTHOG_API_HOST ?? 'https://us.posthog.com'
+const PROJECT_ID = process.env.POSTHOG_PROJECT_ID ?? '2'
+// A skill that exists in the target project. Override when running elsewhere.
+const SKILL = process.env.E2E_SKILL_NAME ?? 'conductor'
+
+const captured: any[] = []
+let sink: http.Server
+let sinkPort: number
+
+describe.skipIf(!API_TOKEN)('skill read reaches PostHog with $mcp_skill_name', () => {
+ beforeAll(async () => {
+ sink = http.createServer((req, res) => {
+ const chunks: Buffer[] = []
+ req.on('data', (c: Buffer) => chunks.push(c))
+ req.on('end', () => {
+ try {
+ const raw = Buffer.concat(chunks)
+ // posthog-node gzips the batch before POSTing it to /batch/.
+ const json = req.headers['content-encoding'] === 'gzip' ? gunzipSync(raw) : raw
+ const body = JSON.parse(json.toString())
+ for (const item of body.batch ?? [body]) {
+ captured.push(item)
+ }
+ } catch {
+ // non-JSON probe; ignore
+ }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end('{"status":1}')
+ })
+ })
+ await new Promise<void>((resolve) => sink.listen(0, '127.0.0.1', resolve))
+ sinkPort = (sink.address() as { port: number }).port
+
+ // Set before the analytics client is imported — it is a module-level singleton.
+ process.env.POSTHOG_ANALYTICS_API_KEY = 'phc_e2e_local_sink'
+ process.env.POSTHOG_ANALYTICS_HOST = `http://127.0.0.1:${sinkPort}`
+ })
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => sink?.close(() => resolve()))
+ })
+
+ it('fetches the real skill and emits an event naming it', async () => {
+ const [{ ApiClient }, { ToolCatalog }, { ToolExecutor }, { InstructionsBuilder }, { getPostHogClient }] =
+ await Promise.all([
+ import('@/api/client'),
+ import('@/hono/tool-catalog'),
+ import('@/hono/tool-executor'),
+ import('@/hono/instructions'),
+ import('@/lib/posthog/client'),
+ ])
+
+ const api = new ApiClient({ apiToken: API_TOKEN!, baseUrl: API_HOST })
+ const catalog = new ToolCatalog()
+ await catalog.warmup()
+ const executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
+
+ const tools = catalog.getPreBuiltEntries().map((entry) => {
+ const preBuilt = catalog.getToolByName(entry.name)!
+ return {
+ ...preBuilt.base,
+ title: entry.title,
+ description: entry.description ?? '',
+ annotations: entry.annotations,
+ scopes: [],
+ }
+ })
+
+ const state: any = {
+ reqCtx: {
+ cache: { get: async () => undefined, set: async () => undefined },
+ safelyGetAnalyticsContext: async () => undefined,
+ trackEvent: () => {},
+ trackContextSwitchEvent: () => {},
+ getSessionUuid: async () => 'e2e-session',
+ getEffectiveSessionUuid: async () => 'e2e-session',
+ },
+ context: {
+ api,
+ cache: {},
+ env: {},
+ stateManager: { getProjectId: async () => PROJECT_ID },
+ sessionManager: {},
+ getDistinctId: () => 'e2e-distinct-id',
+ trackEvent: () => {},
+ },
+ useSingleExec: true,
+ toolFeatureFlags: undefined,
+ apiKeyScopes: [],
+ oauthClientId: undefined,
+ clientProfile: {
+ capabilities: { supportsInstructions: true },
+ isCliModeEnabled: () => true,
+ isClaudeUiHost: () => false,
+ isInlineExecUiHost: () => false,
+ isClaudeChatHost: () => false,
+ },
+ requestContext: {
+ authMethod: 'personal_api_key',
+ sessionId: 'e2e-session',
+ mcpClientName: 'e2e-harness',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ },
+ sessionContext: null,
+ allTools: tools,
+ scopeGatedTools: [],
+ gatewayToolsEnabled: false,
+ distinctId: 'e2e-distinct-id',
+ renderUiEnabled: false,
+ }
+
+ // Exactly the shape an agent sends: single-exec mode, skill name inside the command.
+ const command = `call skill-get {"skill_name":"${SKILL}","body_offset":0}`
+ console.info(`\n→ MCP tools/call exec ${command}`)
+
+ const result: any = await executor.handleToolCall({ name: 'exec', arguments: { command } }, state)
+ const text: string = result?.content?.[0]?.text ?? ''
+
+ console.info(`← ${API_HOST} returned ${text.length} chars, isError=${result?.isError ?? false}`)
+
+ // `trackToolCall` is fired with `void` and awaits async context lookups, so the
+ // capture lands after the handler returns. Let it settle before flushing.
+ await new Promise((r) => setTimeout(r, 1500))
+ await getPostHogClient().flush()
+ await new Promise((r) => setTimeout(r, 1000))
+ console.info(` sink received ${captured.length} event(s): ${captured.map((e) => e.event).join(', ')}`)
+
+ const toolCall = captured.find((e) => e.event === '$mcp_tool_call')
+ const props = toolCall?.properties ?? {}
+
+ console.info('\n── $mcp_tool_call as PostHog ingestion would receive it ──')
+ console.info(
+ JSON.stringify(
+ Object.fromEntries(
+ Object.entries(props).filter(([k]) =>
+ [
+ '$mcp_skill_name',
+ '$mcp_skill_body_offset',
+ '$mcp_tool_name',
+ '$mcp_exec_verb',
+ '$mcp_exec_target_tool',
+ '$mcp_is_error',
+ ].includes(k)
+ )
+ ),
+ null,
+ 2
+ )
+ )
+ console.info(`\n✓ $mcp_skill_name = ${JSON.stringify(props.$mcp_skill_name)}\n`)
+
+ // The skill really came back from the API, not from a fixture or an error path.
+ expect(result?.isError ?? false).toBe(false)
+ expect(text.length).toBeGreaterThan(500)
+
+ expect(toolCall).not.toBeUndefined()
+ expect(props.$mcp_tool_name).toBe('skill-get')
+ expect(props.$mcp_skill_name).toBe(SKILL)
+ expect(props.$mcp_skill_body_offset).toBe(0)
+ })
+})
diff --git a/services/mcp/tests/unit/skill-analytics.test.ts b/services/mcp/tests/unit/skill-analytics.test.ts
new file mode 100644
index 000000000000..0ecc07159eb8
--- /dev/null
+++ b/services/mcp/tests/unit/skill-analytics.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseExecCallInnerArgs } from '@/tools/exec'
+import { skillAnalyticsProperties } from '@/tools/skills/analytics'
+
+/**
+ * These lock in three regressions: a skill read that records no skill (the whole
+ * point), an agent-supplied string reaching analytics unvalidated, and a paged
+ * continuation counted as a fresh load.
+ */
+describe('skillAnalyticsProperties', () => {
+ it.each([
+ ['skill-get', { skill_name: 'conductor' }, 'conductor'],
+ ['skill-file-get', { skill_name: 'conductor', file_path: 'references/x.md' }, 'conductor'],
+ // The deprecated aliases reach analytics under their own name, so a set that
+ // lists only the canonical names is a silent hole.
+ ['llma-skill-get', { skill_name: 'conductor' }, 'conductor'],
+ ['llma-skill-file-get', { skill_name: 'conductor' }, 'conductor'],
+ // Digits and internal hyphens are legal in a stored name.
+ ['skill-get', { skill_name: 'signals-scout-v2' }, 'signals-scout-v2'],
+ ['skill-get', { skill_name: 'a'.repeat(64) }, 'a'.repeat(64)],
+ ])('identifies the skill %s read', (tool, args, expected) => {
+ expect(skillAnalyticsProperties(tool, args)).toMatchObject({ $mcp_skill_name: expected })
+ })
+
+ it.each([
+ // Stamping a non-skill tool would put caller text on unrelated events.
+ ['a non-skill tool', 'execute-sql', { skill_name: 'conductor' }],
+ ['skill-list, which reads no single skill', 'skill-list', { search: 'conductor' }],
+ // Writes already emit `llma skill *` server-side; stamping here too would
+ // give two sources that disagree.
+ ['a write tool', 'skill-update', { skill_name: 'conductor' }],
+ ['an unresolved tool name', undefined, { skill_name: 'conductor' }],
+ ])('records nothing for %s', (_label, tool, args) => {
+ expect(skillAnalyticsProperties(tool, args)).toEqual({})
+ })
+
+ // The rule `execCommandAnalyticsProperties` states: recorded values are value-free
+ // by construction. A name is recordable only if it matches the shape the store
+ // enforces at creation — anything else is the agent's own text.
+ it.each([
+ ['spaces', 'my skill'],
+ ['uppercase', 'Conductor'],
+ ['path traversal', '../../etc/passwd'],
+ ['a url', 'https://example.com/x'],
+ ['empty', ''],
+ ['a leading hyphen', '-conductor'],
+ ['over 64 characters', 'a'.repeat(65)],
+ ['sql-ish text', "conductor'; DROP TABLE--"],
+ ['newlines', 'conductor\nsecond'],
+ ['a non-string', 42],
+ ['null', null],
+ ['an object', { nested: true }],
+ ])('drops a skill name that is %s', (_label, value) => {
+ expect(skillAnalyticsProperties('skill-get', { skill_name: value })).toEqual({})
+ })
+
+ // Analytics must never break a tool call, so malformed input yields no properties
+ // rather than throwing.
+ it.each([
+ ['undefined', undefined],
+ ['null', null],
+ ['a string', 'skill_name=conductor'],
+ ['an empty object', {}],
+ ])('returns empty for %s args', (_label, args) => {
+ expect(skillAnalyticsProperties('skill-get', args)).toEqual({})
+ })
+
+ describe('body offset', () => {
+ // skill-get returns a body in slices, so one skill load is several calls that
+ // differ only by offset. Without this, count() overstates loads several-fold.
+ it.each([
+ ['the first page', 0, 0],
+ ['a continuation', 5000, 5000],
+ ['a numeric string', '5000', 5000],
+ ])('records %s', (_label, input, expected) => {
+ expect(skillAnalyticsProperties('skill-get', { skill_name: 'conductor', body_offset: input })).toEqual({
+ $mcp_skill_name: 'conductor',
+ $mcp_skill_body_offset: expected,
+ })
+ })
+
+ it.each([
+ ['absent', undefined],
+ ['negative', -1],
+ ['not a number', 'later'],
+ ['NaN', Number.NaN],
+ ['infinite', Number.POSITIVE_INFINITY],
+ ['fractional', 1.5],
+ ])('omits an offset that is %s, so its absence means "whole body"', (_label, value) => {
+ expect(skillAnalyticsProperties('skill-get', { skill_name: 'conductor', body_offset: value })).toEqual({
+ $mcp_skill_name: 'conductor',
+ })
+ })
+
+ it('omits the offset for skill-file-get, which does not paginate a body', () => {
+ expect(skillAnalyticsProperties('skill-file-get', { skill_name: 'conductor', body_offset: 10 })).toEqual({
+ $mcp_skill_name: 'conductor',
+ })
+ })
+ })
+})
+
+/**
+ * Nearly all skill reads arrive through the single `exec` dispatcher, where arguments
+ * live inside a command string. A property derived only from tool arguments would
+ * miss all of them.
+ */
+describe('parseExecCallInnerArgs', () => {
+ it.each([
+ ['a call command', 'call skill-get {"skill_name":"conductor"}', { skill_name: 'conductor' }],
+ ['a --json flag', 'call --json skill-get {"skill_name":"conductor"}', { skill_name: 'conductor' }],
+ ['a --confirm flag', 'call --confirm skill-get {"skill_name":"conductor"}', { skill_name: 'conductor' }],
+ [
+ 'extra whitespace and more keys',
+ 'call skill-get {"skill_name":"conductor","version":4}',
+ { skill_name: 'conductor', version: 4 },
+ ],
+ // The dispatcher treats a body-less call as `{}`; this must match it.
+ ['no JSON body', 'call skill-list', {}],
+ ])('extracts inner arguments from %s', (_label, command, expected) => {
+ expect(parseExecCallInnerArgs(command)).toEqual(expected)
+ })
+
+ it.each([
+ ['a non-call verb', 'info skill-get'],
+ ['an empty command', ''],
+ ['invalid JSON', 'call skill-get {not json}'],
+ ['a JSON scalar', 'call skill-get 5'],
+ ['a JSON array', 'call skill-get ["conductor"]'],
+ ['JSON null', 'call skill-get null'],
+ ])('returns undefined for %s', (_label, command) => {
+ expect(parseExecCallInnerArgs(command)).toBeUndefined()
+ })
+})