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): restore intent capture and tools-list analytics on the hono server (#64586)

Lucas Faria8fce37cd6f90
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2e0f2e689c84..7e23157c7c7d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -460,7 +460,7 @@ importers:
'@storybook/react-webpack5':
specifier: ^8.6.14
'@storybook/test-runner':
specifier: ^0.19.1
@@ -514,7 +514,7 @@ importers:
version: 2.0.0([email protected])
webpack:
specifier: ^5.94.0
webpack-cli:
specifier: ^5.1.4
version: 5.1.4([email protected])
@@ -4280,8 +4280,8 @@ importers:
specifier: ^1.29.0
version: 1.29.0(@cfworker/[email protected])([email protected])
'@posthog/mcp-analytics':
- specifier: npm:@posthog/[email protected]
- version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
+ specifier: npm:@posthog/[email protected]
+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
'@posthog/quill':
specifier: workspace:*
version: link:../../packages/quill/packages/quill
@@ -9495,9 +9495,6 @@ packages:
'@posthog/[email protected]':
resolution: {integrity: sha512-GViD5mOv/mcbZcyzz3z9CS0R79JzxVaqEz4sP5Dsea178M/j3ZWe6gaHDZB9yuyGfcmIMQ/8K14yv+7QrK4sQQ==}
- '@posthog/[email protected]':
- resolution: {integrity: sha512-vwOEMfZvGv5XxNWV7p9I52NSmvFNMhyW2IHpIoUHW5jLkgUrknzJW1H/qxVGSIrNNVQkfsoaDFzDhJdg10pgrA==}
-
'@posthog/[email protected]':
resolution: {integrity: sha512-2a9JgJgR+Ow8lrUQHVZYXH9EgXskYDlpbgNW6UvtsVxp8pEEFD8PxjZMnzq73Dx3NhAwNUrnVpb8KeZzHAtoSA==}
@@ -9535,8 +9532,8 @@ packages:
react: 18.3.1
react-dom: 18.3.1
- '@posthog/[email protected]':
- resolution: {integrity: sha512-G3+CuVSkm77wpuZlqcbLEaffezsIR4oJrR2ufctHnk1RcqJchU/0FzV5LA02oRuqj2mmB0bzd8F0BXSqBxbLug==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-5k5q4On86ISHKczYUgHC4KxA3XNIN/6mbgXHEaF1cNo2xI+gxBJxivDVlzcU1h2F++WYJP5AGEj3lxffjLXG7Q==}
engines: {node: ^20.20.0 || >=22.22.0}
peerDependencies:
'@modelcontextprotocol/sdk': ^1.29.0
@@ -9555,9 +9552,6 @@ packages:
'@posthog/[email protected]':
resolution: {integrity: sha512-JUFk57H89fOnHpF62FDyFGw4uXeHAX20OPfkLL8/iqg/xrVp5Q21LvJUDijmS5wt0avgUwXF2bxYgaZ5iWRmAg==}
- '@posthog/[email protected]':
- resolution: {integrity: sha512-LqJoiQi2eyWn7rCUgnn+D+F3Efp6+04o72bjSX6kWHx0nFaYNC/nJuAIRliDTY/X7GPIUAaHAcSjbMI/9wfX1Q==}
-
'@posthog/[email protected]':
resolution: {integrity: sha512-zMjK6nrUWhAlL8ECrM4WldvgawqdoAE5B0ys7eA0lCoWuyzfFoSyh6zYtEuBSDRyN7fQLSfNCK+mQH4ngOl7Zw==}
@@ -29807,10 +29801,6 @@ snapshots:
dependencies:
cross-spawn: 7.0.6
- '@posthog/[email protected]':
- dependencies:
- '@posthog/types': 1.386.3
-
'@posthog/[email protected]':
dependencies:
'@posthog/types': 1.390.0
@@ -29852,10 +29842,10 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
- '@posthog/core': 1.32.3
+ '@posthog/core': 1.35.1
posthog-node: 5.25.0
@@ -29867,8 +29857,6 @@ snapshots:
'@posthog/[email protected]': {}
- '@posthog/[email protected]': {}
-
'@posthog/[email protected]': {}
'@protobufjs/[email protected]': {}
@@ -31364,7 +31352,7 @@ snapshots:
ts-dedent: 2.2.0
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
'@types/semver': 7.7.1
@@ -31382,12 +31370,12 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
style-loader: 3.3.3([email protected])
ts-dedent: 2.2.0
url: 0.11.1
util: 0.12.5
util-deprecate: 1.0.2
webpack-dev-middleware: 6.1.3([email protected])
webpack-hot-middleware: 2.25.4
webpack-virtual-modules: 0.6.2
@@ -31481,7 +31469,7 @@ snapshots:
dependencies:
storybook: 8.6.18([email protected])
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
@@ -31496,7 +31484,7 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
tsconfig-paths: 4.2.0
optionalDependencies:
typescript: 6.0.3
transitivePeerDependencies:
@@ -31530,7 +31518,7 @@ snapshots:
react-docgen-typescript: 2.2.2([email protected])
tslib: 2.8.1
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -31568,10 +31556,10 @@ snapshots:
- supports-color
- typescript
dependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
@@ -33934,17 +33922,17 @@ snapshots:
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
'@xmldom/[email protected]': {}
@@ -34466,7 +34454,7 @@ snapshots:
loader-utils: 2.0.4
make-dir: 3.1.0
schema-utils: 2.7.1
dependencies:
@@ -35520,7 +35508,7 @@ snapshots:
postcss-value-parser: 4.2.0
schema-utils: 2.7.1
semver: 6.3.1
dependencies:
@@ -35532,7 +35520,7 @@ snapshots:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
semver: 7.8.0
dependencies:
@@ -37113,7 +37101,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
@@ -37232,7 +37220,7 @@ snapshots:
semver: 7.8.0
tapable: 2.3.3
typescript: 6.0.3
dependencies:
@@ -37894,7 +37882,7 @@ snapshots:
dependencies:
html-webpack-plugin: 5.5.3([email protected])
dependencies:
@@ -37903,7 +37891,7 @@ snapshots:
lodash: 4.18.1
pretty-error: 4.0.0
tapable: 2.2.1
dependencies:
@@ -40317,7 +40305,7 @@ snapshots:
less: 4.2.2
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -42573,7 +42561,7 @@ snapshots:
postcss: 8.5.15
schema-utils: 3.3.0
semver: 7.7.0
dependencies:
@@ -43337,7 +43325,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -44373,7 +44361,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
semver: 7.7.0
optionalDependencies:
sass: 1.56.0
@@ -45033,11 +45021,11 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -45404,30 +45392,28 @@ snapshots:
ansi-escapes: 4.3.2
supports-hyperlinks: 2.3.0
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
'@swc/core': 1.15.18
cssnano: 7.0.6([email protected])
- esbuild: 0.25.12
+ esbuild: 0.28.0
postcss: 8.5.15
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
- '@swc/core': 1.15.18
cssnano: 7.0.6([email protected])
- esbuild: 0.28.0
postcss: 8.5.15
@@ -46579,7 +46565,7 @@ snapshots:
import-local: 3.1.0
interpret: 3.1.1
rechoir: 0.8.0
webpack-merge: 5.8.0
@@ -46590,7 +46576,7 @@ snapshots:
range-parser: 1.2.1
schema-utils: 4.3.3
optionalDependencies:
dependencies:
@@ -46609,7 +46595,7 @@ snapshots:
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.8
@@ -46633,11 +46619,9 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.0
watchpack: 2.5.1
webpack-sources: 3.3.4
- optionalDependencies:
- webpack-cli: 5.1.4([email protected])
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
@@ -46652,7 +46636,7 @@ snapshots:
- postcss
- uglify-js
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.8
@@ -46676,9 +46660,11 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.0
watchpack: 2.5.1
webpack-sources: 3.3.4
+ optionalDependencies:
+ webpack-cli: 5.1.4([email protected])
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 187471441984..cb5bd47be666 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -45,7 +45,7 @@
"@hono/node-server": "^2.0.2",
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
- "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
"@posthog/quill": "workspace:*",
"@posthog/quill-charts": "workspace:*",
"@toon-format/toon": "^2.1.0",
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
index 3b688acb8d7f..7365d0ad343f 100644
--- a/services/mcp/src/hono/analytics.ts
+++ b/services/mcp/src/hono/analytics.ts
@@ -1,3 +1,5 @@
+import type { MCPAnalyticsIntentSource } from '@posthog/mcp-analytics'
+
import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'
import { getPostHogClient } from '@/lib/posthog'
import {
@@ -55,7 +57,7 @@ function buildBaseProperties(
export async function trackInitEvent(state: ResolvedState): Promise<void> {
try {
- const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
const requestContext = state.requestContext
const initDurationMs = requestContext.requestStartTime
? Date.now() - requestContext.requestStartTime
@@ -109,15 +111,23 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {
}
}
+export interface ToolCallIntentMeta {
+ /** The agent's stated intent (the injected `context` arg) → `$mcp_intent`. */
+ intent?: string
+ /** Where it came from → `$mcp_intent_source`. */
+ intentSource?: MCPAnalyticsIntentSource
+}
+
export async function trackToolCall(
toolName: string,
durationMs: number,
isError: boolean,
state: ResolvedState,
- extraProperties?: Record<string, unknown>
+ extraProperties?: Record<string, unknown>,
+ intentMeta?: ToolCallIntentMeta
): Promise<void> {
try {
- const analyticsContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
const requestContext = state.requestContext
const sessionUuid = requestContext.sessionId
? await state.reqCtx.getSessionUuid(requestContext.sessionId)
@@ -136,8 +146,11 @@ export async function trackToolCall(
// Emits `$mcp_tool_call` (+ `$mcp_is_error`). The SDK maps `toolName` →
// `$mcp_tool_name`, `durationMs` → `$mcp_duration_ms`, `isError` →
- // `$mcp_is_error`, and `sessionId` → `$session_id`. `$exception` fan-out
- // is disabled on the client, so an errored call stays a single event.
+ // `$mcp_is_error`, `intent` → `$mcp_intent`, and `sessionId` →
+ // `$session_id`. `$exception` fan-out is disabled on the client, so an
+ // errored call stays a single event. The intent pipeline reads
+ // `$mcp_intent` off this canonical event, so it only needs to land here
+ // (not on the legacy dual-emit below).
getPostHogClient().captureToolCall({
toolName,
durationMs,
@@ -145,6 +158,8 @@ export async function trackToolCall(
distinctId: state.distinctId,
groups,
...(sessionUuid ? { sessionId: sessionUuid } : {}),
+ ...(intentMeta?.intent ? { intent: intentMeta.intent } : {}),
+ ...(intentMeta?.intentSource ? { intentSource: intentMeta.intentSource } : {}),
properties: {
...properties,
tool_name: toolName,
@@ -176,3 +191,31 @@ export async function trackToolCall(
// never break the request for analytics
}
}
+
+export async function trackToolsList(toolNames: string[], state: ResolvedState): Promise<void> {
+ try {
+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
+ const requestContext = state.requestContext
+ const sessionUuid = requestContext.sessionId
+ ? await state.reqCtx.getSessionUuid(requestContext.sessionId)
+ : undefined
+
+ const { properties, groups } = buildBaseProperties(state, analyticsContext)
+
+ // Emits `$mcp_tools_list`. The SDK maps `toolNames` → `$mcp_listed_tool_names`,
+ // which powers "advertised but never called" analysis. No legacy dual-emit:
+ // `mcp_tools_list` has had no consumers since the cutover.
+ getPostHogClient().captureToolsList({
+ toolNames,
+ distinctId: state.distinctId,
+ groups,
+ ...(sessionUuid ? { sessionId: sessionUuid } : {}),
+ properties: {
+ ...properties,
+ tool_count: toolNames.length,
+ },
+ })
+ } catch {
+ // never break the request for analytics
+ }
+}
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 24fe56eeb6d1..9f2a922b8dea 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -153,7 +153,7 @@ export class RequestContext {
getDistinctId: () => this.getDistinctId(),
}
const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {
- const analyticsContext = await this.getAnalyticsContextSafe(partialContext)
+ const analyticsContext = await this.safelyGetAnalyticsContext(partialContext)
const distinctId = await this.getDistinctId()
await this.trackEvent(event, properties, analyticsContext, undefined, distinctId)
}
@@ -165,7 +165,7 @@ export class RequestContext {
this.sessionContext = sessionContext
}
- async getAnalyticsContextSafe(context: Pick<Context, 'stateManager'>): Promise<MCPAnalyticsContext | undefined> {
+ async safelyGetAnalyticsContext(context: Pick<Context, 'stateManager'>): Promise<MCPAnalyticsContext | undefined> {
try {
return await context.stateManager.getAnalyticsContext()
} catch {
@@ -178,7 +178,7 @@ export class RequestContext {
context: Context,
previousContext: MCPAnalyticsContext | undefined
): Promise<void> {
- const resolvedContext = await this.getAnalyticsContextSafe(context)
+ const resolvedContext = await this.safelyGetAnalyticsContext(context)
if (!resolvedContext) {
return
}
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 7175d38356eb..dbb61d276bd6 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -115,7 +115,7 @@ export class RequestStateResolver {
// the rendering prompt section on it (like `mcp-feedback-tool`).
const allFlagKeys = [...toolFlagKeys, RENDER_UI_FEATURE_FLAG]
- const flagAnalyticsContext = await reqCtx.getAnalyticsContextSafe(context)
+ const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)
const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
const [allFlags, _apiKey, distinctId] = await Promise.all([
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 390939fde341..f8d48a684005 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -17,13 +17,14 @@ import {
findRecoverableApiError,
} from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
+import { getPostHogClient } from '@/lib/posthog'
import { AnalyticsEvent } from '@/lib/posthog/analytics'
import { createExecTool, formatInputValidationError, type ExecInnerCallTracker } from '@/tools/exec'
import { createRenderUiTool } from '@/tools/render-ui'
import { getToolCategory } from '@/tools/toolDefinitions'
import type { Context, ZodObjectAny } from '@/tools/types'
-import { trackToolCall } from './analytics'
+import { trackToolCall, trackToolsList, type ToolCallIntentMeta } from './analytics'
import type { InstructionsBuilder } from './instructions'
import { getEffectiveMCPClientContext } from './mcp-context'
import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'
@@ -51,24 +52,44 @@ export class ToolExecutor {
}
async handleToolsList(state: ResolvedState): Promise<ListToolsResult> {
+ const tools = this.injectContext(this.buildAdvertisedTools(state))
+
+ void trackToolsList(
+ tools.map((t) => t.name),
+ state
+ )
+
+ return { tools }
+ }
+
+ // Inject the `context` argument into every advertised tool so agents can state
+ // what they're trying to do (`handleToolCall` strips it before validation and
+ // surfaces it as `$mcp_intent` — the same injection `instrument()` does for
+ // SDK-wrapped servers). Guarded: analytics must never break `tools/list`, so
+ // any failure falls back to the un-augmented tools.
+ private injectContext(tools: ListToolsResult['tools']): ListToolsResult['tools'] {
+ try {
+ return getPostHogClient().prepareToolList(tools)
+ } catch {
+ return tools
+ }
+ }
+
+ private buildAdvertisedTools(state: ResolvedState): ListToolsResult['tools'] {
if (state.useSingleExec) {
const renderUiEntry = state.renderUiEnabled ? this.instructionsBuilder.buildRenderUiToolEntry(state) : null
- return {
- tools: [this.instructionsBuilder.buildExecToolEntry(state), ...(renderUiEntry ? [renderUiEntry] : [])],
- }
+ return [this.instructionsBuilder.buildExecToolEntry(state), ...(renderUiEntry ? [renderUiEntry] : [])]
}
const nameSet = new Set(state.allTools.map((t) => t.name))
const filteredTools = this.catalog.getPreBuiltEntries().filter((e) => nameSet.has(e.name))
- const withSqlDescription = filteredTools.map((entry) => {
+ return filteredTools.map((entry) => {
if (entry.name === 'execute-sql') {
return { ...entry, description: this.instructionsBuilder.formatExecuteSqlDescription() }
}
return entry
})
-
- return { tools: withSqlDescription }
}
async handleToolCall(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {
@@ -77,8 +98,11 @@ export class ToolExecutor {
return { content: [{ type: 'text', text: 'Missing tool name' }], isError: true }
}
+ const { intentMeta, args } = this.extractIntent(toolName, (params?.arguments ?? {}) as Record<string, unknown>)
+ const callParams = { ...params, arguments: args }
+
if (toolName === 'exec') {
- return this.callExecTool(params, state)
+ return this.callExecTool(callParams, state, intentMeta)
}
if (toolName === 'render-ui') {
@@ -87,7 +111,7 @@ export class ToolExecutor {
toolCallsTotal.inc({ tool: toolName, status: 'error' })
return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }
}
- return this.callRenderUiTool(params, state)
+ return this.callRenderUiTool(callParams, state, intentMeta)
}
if (!state.allTools.some((t) => t.name === toolName)) {
@@ -108,15 +132,37 @@ export class ToolExecutor {
handler: (ctx, args) => preBuilt.base.handler(ctx, args),
_meta: preBuilt.base._meta,
},
- params,
- state
+ callParams,
+ state,
+ intentMeta
)
}
+ // Pull the agent's stated intent off the injected `context` arg and strip it so
+ // tool schemas/handlers never see it (validation is `.strict()` in places). The
+ // intent rides through to `$mcp_intent` on the captured event. Guarded: analytics
+ // must never break `tools/call`, so on failure we fall back to the raw args —
+ // safe because `context` is only present when the matching injection succeeded.
+ private extractIntent(
+ toolName: string,
+ rawArgs: Record<string, unknown>
+ ): { intentMeta: ToolCallIntentMeta; args: Record<string, unknown> } {
+ try {
+ const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs)
+ return {
+ intentMeta: { intent: prepared.intent, intentSource: prepared.intentSource },
+ args: prepared.args ?? rawArgs,
+ }
+ } catch {
+ return { intentMeta: {}, args: rawArgs }
+ }
+ }
+
private async callTool(
tool: ResolvedTool,
params: Record<string, unknown> | undefined,
- state: ResolvedState
+ state: ResolvedState,
+ intentMeta?: ToolCallIntentMeta
): Promise<unknown> {
const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>
const validation = tool.schema.safeParse(toolArgs, { reportInput: true })
@@ -134,7 +180,7 @@ export class ToolExecutor {
try {
const isContextSwitch = tool.name === 'switch-project' || tool.name === 'switch-organization'
const previousContext = isContextSwitch
- ? await state.reqCtx.getAnalyticsContextSafe(state.context)
+ ? await state.reqCtx.safelyGetAnalyticsContext(state.context)
: undefined
const handlerResult = await tool.handler(state.context, validation.data)
@@ -166,10 +212,17 @@ export class ToolExecutor {
})
}
- void trackToolCall(tool.name, duration, false, state, {
- input_tokens: estimateTokens(validation.data),
- output_tokens: estimateResponseTokens(response),
- })
+ void trackToolCall(
+ tool.name,
+ duration,
+ false,
+ state,
+ {
+ input_tokens: estimateTokens(validation.data),
+ output_tokens: estimateResponseTokens(response),
+ },
+ intentMeta
+ )
return response
} catch (error: unknown) {
@@ -177,14 +230,18 @@ export class ToolExecutor {
stop({ status: 'error' })
classifyToolError(error, tool.name)
- void trackToolCall(tool.name, Date.now() - startMs, true, state)
+ void trackToolCall(tool.name, Date.now() - startMs, true, state, undefined, intentMeta)
const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
return handleToolError(error, tool.name, state.distinctId, sessionUuid)
}
}
- private async callExecTool(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {
+ private async callExecTool(
+ params: Record<string, unknown> | undefined,
+ state: ResolvedState,
+ intentMeta?: ToolCallIntentMeta
+ ): Promise<unknown> {
const execMetrics: ExecMetricState = { innerToolName: undefined }
const resolved = this.resolveExecTool(state, execMetrics)
@@ -215,10 +272,17 @@ export class ToolExecutor {
distinctId: undefined,
})
- void trackToolCall('exec', duration, false, state, {
- input_tokens: estimateTokens(validation.data),
- output_tokens: estimateResponseTokens(response),
- })
+ void trackToolCall(
+ 'exec',
+ duration,
+ false,
+ state,
+ {
+ input_tokens: estimateTokens(validation.data),
+ output_tokens: estimateResponseTokens(response),
+ },
+ intentMeta
+ )
return response
} catch (error: unknown) {
@@ -228,7 +292,7 @@ export class ToolExecutor {
}
classifyToolError(error, metricTool)
- void trackToolCall('exec', Date.now() - startMs, true, state)
+ void trackToolCall('exec', Date.now() - startMs, true, state, undefined, intentMeta)
const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
// Attribute the failure to the inner tool that actually ran (e.g. `query-logs`),
@@ -258,7 +322,7 @@ export class ToolExecutor {
const toolCategory = getToolCategory(toolName)
void (async () => {
- const freshContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
+ const freshContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)
await state.reqCtx.trackEvent(
AnalyticsEvent.MCP_TOOL_CALL,
{
@@ -294,7 +358,8 @@ export class ToolExecutor {
private async callRenderUiTool(
params: Record<string, unknown> | undefined,
- state: ResolvedState
+ state: ResolvedState,
+ intentMeta?: ToolCallIntentMeta
): Promise<unknown> {
const renderUiTool = createRenderUiTool(state.allTools, state.context)
if (!renderUiTool) {
@@ -317,14 +382,14 @@ export class ToolExecutor {
const handlerResult = await renderUiTool.handler(state.context, validation.data)
toolCallsTotal.inc({ tool: 'render-ui', status: 'success' })
stop({ status: 'success' })
- void trackToolCall('render-ui', Date.now() - startMs, false, state)
+ void trackToolCall('render-ui', Date.now() - startMs, false, state, undefined, intentMeta)
// The handler always returns an exec-built payload (UI resourceUri + structuredContent).
return handlerResult
} catch (error: unknown) {
toolCallsTotal.inc({ tool: 'render-ui', status: 'error' })
stop({ status: 'error' })
classifyToolError(error, 'render-ui')
- void trackToolCall('render-ui', Date.now() - startMs, true, state)
+ void trackToolCall('render-ui', Date.now() - startMs, true, state, undefined, intentMeta)
const sessionUuid = await state.reqCtx.getSessionUuid(state.requestContext.sessionId)
return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)
}
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index a481e7ee9d4c..2807a4bd1bff 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -21,7 +21,7 @@ import type { ResolvedState } from '@/hono/request-state-resolver'
function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
return {
reqCtx: {
- getAnalyticsContextSafe: vi.fn(async () => undefined),
+ safelyGetAnalyticsContext: vi.fn(async () => undefined),
getSessionUuid: vi.fn(async () => 'session-uuid'),
} as any,
context: {
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index 7bca5273645c..909f8c47feae 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -57,7 +57,7 @@ vi.mock('@/hono/request-context', () => {
getAiConsentGiven: vi.fn(async () => undefined),
},
})),
- getAnalyticsContextSafe: vi.fn(async () => undefined),
+ safelyGetAnalyticsContext: vi.fn(async () => undefined),
getDistinctId: vi.fn(async () => 'distinct-id'),
setMcpContexts: vi.fn(),
}
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
new file mode 100644
index 000000000000..da786f42ce53
--- /dev/null
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -0,0 +1,170 @@
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/resources/internals', () => ({
+ fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
+ filterValidEntries: vi.fn().mockReturnValue([]),
+ loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
+ clearResourceCache: vi.fn(),
+}))
+
+vi.mock('@/resources', () => ({
+ getPromptsFromManifest: vi.fn().mockResolvedValue([]),
+}))
+
+// Replace the project's PostHog client with a real (but disabled, no-network)
+// PostHogMCP so `prepareToolList` / `prepareToolCall` run the actual SDK injection
+// and extraction logic — this proves dotcom's wiring against real SDK behavior,
+// not a stub.
+vi.mock('@/lib/posthog', async () => {
+ const { PostHogMCP } = await import('@posthog/mcp-analytics')
+ const client = new PostHogMCP('phc_test', { disabled: true })
+ return { getPostHogClient: () => client }
+})
+
+import { InstructionsBuilder } from '@/hono/instructions'
+import type { ResolvedState } from '@/hono/request-state-resolver'
+import { ToolCatalog } from '@/hono/tool-catalog'
+import { ToolExecutor } from '@/hono/tool-executor'
+import { getPostHogClient } from '@/lib/posthog'
+
+function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
+ return {
+ reqCtx: {
+ cache: { get: vi.fn(), set: vi.fn() },
+ safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
+ trackEvent: vi.fn(),
+ getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ } as any,
+ context: {
+ api: {},
+ cache: {},
+ env: {},
+ stateManager: {},
+ sessionManager: {},
+ getDistinctId: vi.fn(),
+ trackEvent: vi.fn(),
+ } as any,
+ useSingleExec: false,
+ toolFeatureFlags: undefined,
+ apiKeyScopes: [],
+ clientProfile: {
+ capabilities: { supportsInstructions: true },
+ isCliModeEnabled: vi.fn(() => false),
+ } as any,
+ requestContext: {
+ sessionId: 'sess-1',
+ mcpClientName: 'test',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ },
+ sessionContext: null,
+ allTools: tools as any,
+ scopeGatedTools: [],
+ distinctId: 'test-distinct-id',
+ renderUiEnabled: false,
+ ...overrides,
+ }
+}
+
+describe('ToolExecutor intent capture', () => {
+ let catalog: ToolCatalog
+ let executor: ToolExecutor
+
+ beforeAll(async () => {
+ catalog = new ToolCatalog()
+ await catalog.warmup()
+ executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
+ })
+
+ it('injects the context argument into advertised tools', async () => {
+ const state = makeState([], { useSingleExec: true })
+
+ const result = await executor.handleToolsList(state)
+
+ const execEntry = result.tools.find((t) => t.name === 'exec')!
+ const properties = execEntry.inputSchema.properties as Record<string, unknown>
+ // The SDK injects `context` (required, to nudge the agent to state intent)
+ // while leaving the existing `command` arg untouched.
+ expect(properties).toHaveProperty('context')
+ expect(properties).toHaveProperty('command')
+ expect(execEntry.inputSchema.required).toContain('context')
+ })
+
+ it.each([
+ {
+ label: 'forwards the agent intent and strips context before the handler',
+ args: { command: 'tools', context: 'investigating signup drop' },
+ expectedIntent: 'investigating signup drop',
+ expectedSource: 'context_parameter',
+ },
+ {
+ label: 'captures no intent when the agent omits context',
+ args: { command: 'tools' },
+ expectedIntent: undefined,
+ expectedSource: undefined,
+ },
+ ])('exec call $label', async ({ args, expectedIntent, expectedSource }) => {
+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
+
+ const filteredTools = catalog
+ .getFilteredTools({ scopes: ['*'] })
+ .filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')
+
+ const result = (await executor.handleToolCall(
+ { name: 'exec', arguments: args },
+ makeState(filteredTools, { useSingleExec: false })
+ )) as any
+
+ // context (when present) must not break exec validation — proves it was stripped.
+ expect(result.isError).toBeFalsy()
+
+ expect(captureSpy).toHaveBeenCalledTimes(1)
+ const arg = captureSpy.mock.calls[0]![0]
+ expect(arg.toolName).toBe('exec')
+ expect(arg.intent).toBe(expectedIntent)
+ expect(arg.intentSource).toBe(expectedSource)
+
+ captureSpy.mockRestore()
+ })
+
+ // A native (non-exec) tool call with context: proves the native callTool path
+ // strips context and forwards intent. captureToolCall only fires *after*
+ // validation passes (the validation-error path returns before tracking), so its
+ // being called with the intent proves context was stripped before validation.
+ // (projects-get hits the API, which the harness can't fulfill, so we assert on
+ // the captured analytics, not the tool's own result.)
+ it('strips context before a native tool validates and still forwards intent', async () => {
+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
+
+ await executor.handleToolCall(
+ { name: 'projects-get', arguments: { context: 'looking up the current user' } },
+ makeState([{ name: 'projects-get' }])
+ )
+
+ expect(captureSpy).toHaveBeenCalledTimes(1)
+ expect(captureSpy.mock.calls[0]![0].toolName).toBe('projects-get')
+ expect(captureSpy.mock.calls[0]![0].intent).toBe('looking up the current user')
+
+ captureSpy.mockRestore()
+ })
+
+ // Old-schema / old-client compatibility: an agent that doesn't know about the
+ // injected context arg calls with just the tool's own args. The call is handled
+ // exactly as before (a graceful result, never a thrown error) and no intent is
+ // captured.
+ it('handles a native call with no context (old-schema clients) gracefully', async () => {
+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
+
+ const result = (await executor.handleToolCall(
+ { name: 'projects-get', arguments: {} },
+ makeState([{ name: 'projects-get' }])
+ )) as any
+
+ expect(result.content).toBeTruthy()
+ expect(captureSpy).toHaveBeenCalledTimes(1)
+ expect(captureSpy.mock.calls[0]![0].intent).toBeUndefined()
+
+ captureSpy.mockRestore()
+ })
+})
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index c5b599e209a4..ffa5114dc2f0 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -46,7 +46,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
return {
reqCtx: {
cache: { get: vi.fn(), set: vi.fn() },
- getAnalyticsContextSafe: vi.fn().mockResolvedValue(undefined),
+ safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
trackEvent: vi.fn(),
trackContextSwitchEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index bb464547b624..1bac87227589 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -29,7 +29,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
return {
reqCtx: {
cache: { get: vi.fn(), set: vi.fn() },
- getAnalyticsContextSafe: vi.fn().mockResolvedValue(undefined),
+ safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
trackEvent: vi.fn(),
trackContextSwitchEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 528a0af88cb1..639fb8314df1 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -28,7 +28,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
return {
reqCtx: {
cache: { get: vi.fn(), set: vi.fn() },
- getAnalyticsContextSafe: vi.fn().mockResolvedValue(undefined),
+ safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
trackEvent: vi.fn(),
getSessionUuid: vi.fn().mockResolvedValue(undefined),
} as any,