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): capture estimated tokens on tool calls (#62433)

Georgiy Tarasov54c64662d860
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 5681b314ccdc..61f6144f6578 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -1,6 +1,11 @@
import type { ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
-import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
+import {
+ buildToolResultPayload,
+ estimateResponseTokens,
+ isToolCallPayload,
+ type ToolResultPayload,
+} from '@/lib/build-tool-result'
import {
handleToolError,
MissingOrganizationContextError,
@@ -11,6 +16,7 @@ import {
findPostHogPermissionError,
findRecoverableApiError,
} from '@/lib/errors'
+import { estimateTokens } from '@/lib/estimate-tokens'
import { AnalyticsEvent } from '@/lib/posthog/analytics'
import { createExecTool, formatInputValidationError, type ExecInnerCallTracker } from '@/tools/exec'
import { createRenderUiTool } from '@/tools/render-ui'
@@ -140,24 +146,32 @@ export class ToolExecutor {
toolCallsTotal.inc({ tool: tool.name, status: 'success' })
stop({ status: 'success' })
- void trackToolCall(tool.name, Date.now() - startMs, false, state)
+ const duration = Date.now() - startMs
+ let response: ToolResultPayload
if (isToolCallPayload(handlerResult)) {
- return handlerResult
+ response = handlerResult
+ } else {
+ const hasUiResource = !!tool._meta?.ui?.resourceUri
+ const needsDistinctId = hasUiResource && typeof handlerResult !== 'string'
+ const distinctId = needsDistinctId ? state.distinctId : undefined
+
+ response = buildToolResultPayload({
+ handlerResult,
+ toolMeta: tool._meta,
+ toolName: tool.name,
+ params: validation.data,
+ suppressStructuredContentForFormattedResults: state.clientProfile.isCliModeEnabled(),
+ distinctId,
+ })
}
- const hasUiResource = !!tool._meta?.ui?.resourceUri
- const needsDistinctId = hasUiResource && typeof handlerResult !== 'string'
- const distinctId = needsDistinctId ? state.distinctId : undefined
-
- return buildToolResultPayload({
- handlerResult,
- toolMeta: tool._meta,
- toolName: tool.name,
- params: validation.data,
- suppressStructuredContentForFormattedResults: state.clientProfile.isCliModeEnabled(),
- distinctId,
+ void trackToolCall(tool.name, duration, false, state, {
+ input_tokens: estimateTokens(validation.data),
+ output_tokens: estimateResponseTokens(response),
})
+
+ return response
} catch (error: unknown) {
toolCallsTotal.inc({ tool: tool.name, status: 'error' })
stop({ status: 'error' })
@@ -188,21 +202,25 @@ export class ToolExecutor {
try {
const handlerResult = await resolved.handler(state.context, validation.data)
-
- void trackToolCall('exec', Date.now() - startMs, false, state)
-
- if (isToolCallPayload(handlerResult)) {
- return handlerResult
- }
-
- return buildToolResultPayload({
- handlerResult,
- toolMeta: resolved._meta,
- toolName: 'exec',
- params: validation.data,
- suppressStructuredContentForFormattedResults: state.clientProfile.isCliModeEnabled(),
- distinctId: undefined,
+ const duration = Date.now() - startMs
+
+ const response = isToolCallPayload(handlerResult)
+ ? handlerResult
+ : buildToolResultPayload({
+ handlerResult,
+ toolMeta: resolved._meta,
+ toolName: 'exec',
+ params: validation.data,
+ suppressStructuredContentForFormattedResults: state.clientProfile.isCliModeEnabled(),
+ distinctId: undefined,
+ })
+
+ void trackToolCall('exec', duration, false, state, {
+ input_tokens: estimateTokens(validation.data),
+ output_tokens: estimateResponseTokens(response),
})
+
+ return response
} catch (error: unknown) {
const metricTool = execMetrics.innerToolName ?? 'exec'
if (!execMetrics.innerToolName) {
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index 54d015b77bde..b1e44a713243 100644
--- a/services/mcp/src/lib/build-tool-result.ts
+++ b/services/mcp/src/lib/build-tool-result.ts
@@ -1,5 +1,6 @@
import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
+import { estimateTokens } from '@/lib/estimate-tokens'
import { formatResponse } from '@/lib/response'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'
import type { AnalyticsMetadata, WithAnalytics } from '@/ui-apps/types'
@@ -66,6 +67,17 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {
return { ...payload, [EXEC_BUILT_PAYLOAD]: true }
}
+/**
+ * Estimate output tokens from the text actually returned to the client — the
+ * serialized TOON/JSON/formatted string, not the raw handler object. TOON is
+ * materially smaller than JSON for tabular results, so measuring the raw object
+ * would over-count. `structuredContent` is deliberately excluded: it duplicates
+ * the text for UI tools, so counting it would double-bill those calls.
+ */
+export function estimateResponseTokens(response: ToolResultPayload): number {
+ return estimateTokens(response.content.map((part) => part.text).join(''))
+}
+
/**
* Assembles the MCP tool-call response payload.
*
diff --git a/services/mcp/src/lib/estimate-tokens.ts b/services/mcp/src/lib/estimate-tokens.ts
new file mode 100644
index 000000000000..b4a4505056ca
--- /dev/null
+++ b/services/mcp/src/lib/estimate-tokens.ts
@@ -0,0 +1,24 @@
+/**
+ * Approximate token count for a tool call's input or output, using the
+ * ~4-chars-per-token heuristic the MCP performance dashboard tracks. The server
+ * does not capture LLM-observability spans, so token usage is estimated from the
+ * serialized size of the value rather than read from a generation/trace payload.
+ */
+export function estimateTokens(value: unknown): number {
+ if (value === undefined || value === null) {
+ return 0
+ }
+ let text: string
+ if (typeof value === 'string') {
+ text = value
+ } else {
+ try {
+ text = JSON.stringify(value) ?? ''
+ } catch {
+ // Non-serializable value (circular refs, BigInt, ...) — never break
+ // the request for an analytics estimate.
+ return 0
+ }
+ }
+ return Math.ceil(text.length / 4)
+}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 89a5f7e6e840..863770eb9b86 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -1,9 +1,10 @@
import { stringify as stringifyYaml } from 'yaml'
import { z } from 'zod'
-import { markExecPayload, buildToolResultPayload } from '@/lib/build-tool-result'
+import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'
import { isPostHogCodeConsumer } from '@/lib/client-detection'
import { ToolInputValidationError } from '@/lib/errors'
+import { estimateTokens } from '@/lib/estimate-tokens'
import { formatResponse } from '@/lib/response'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
@@ -29,6 +30,12 @@ export interface ExecInnerCallProperties {
error_message?: string
/** Input rejected by the tool's schema before dispatch — no handler ran. */
validation_error?: boolean
+ /**
+ * Estimated input/output tokens for the inner tool call. Carried so single-exec
+ * mode attributes token usage to the real tool rather than the `exec` wrapper.
+ */
+ input_tokens?: number
+ output_tokens?: number
}
export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void
@@ -377,12 +384,7 @@ export function createExecTool(
if (tool._meta?.ui?.resourceUri && isPostHogCodeConsumer(mcpConsumer)) {
const isStringResult = typeof result === 'string'
const distinctId = isStringResult ? undefined : await context.getDistinctId()
- trackInnerCall?.(tool.name, {
- duration_ms: durationMs,
- success: true,
- output_format: 'structured',
- })
- return markExecPayload(
+ const payload = markExecPayload(
buildToolResultPayload({
handlerResult: result,
toolMeta: tool._meta,
@@ -396,30 +398,41 @@ export function createExecTool(
includeUiResponseMeta: true,
})
)
+ trackInnerCall?.(tool.name, {
+ duration_ms: durationMs,
+ success: true,
+ output_format: 'structured',
+ input_tokens: estimateTokens(input),
+ output_tokens: estimateResponseTokens(payload),
+ })
+ return payload
}
+ // Serialize once so the token estimate measures the exact text
+ // returned to the client, not the raw object.
+ let outputText: string
+ if (useJson) {
+ outputText = JSON.stringify(result)
+ } else {
+ // Optimized mode: when the handler attached a backend-formatted table
+ // via `__formatted_results_override`, return ONLY that string. The raw
+ // `results`/`_posthogUrl` payload would otherwise duplicate the table
+ // and crowd it out — buildToolResultPayload makes the same choice for
+ // the non-exec path, this keeps exec consistent.
+ const formattedOverride =
+ result !== null && typeof result === 'object'
+ ? (result as Record<string, unknown>)[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]
+ : undefined
+ outputText = typeof formattedOverride === 'string' ? formattedOverride : formatResponse(result)
+ }
trackInnerCall?.(tool.name, {
duration_ms: durationMs,
success: true,
output_format: useJson ? 'json' : 'text',
+ input_tokens: estimateTokens(input),
+ output_tokens: estimateTokens(outputText),
})
- if (useJson) {
- return JSON.stringify(result)
- }
- // Optimized mode: when the handler attached a backend-formatted table
- // via `__formatted_results_override`, return ONLY that string. The raw
- // `results`/`_posthogUrl` payload would otherwise duplicate the table
- // and crowd it out — buildToolResultPayload makes the same choice for
- // the non-exec path, this keeps exec consistent.
- if (result !== null && typeof result === 'object') {
- const formattedOverride = (result as Record<string, unknown>)[
- POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY
- ]
- if (typeof formattedOverride === 'string') {
- return formattedOverride
- }
- }
- return formatResponse(result)
+ return outputText
}
default:
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
new file mode 100644
index 000000000000..bb464547b624
--- /dev/null
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -0,0 +1,189 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { mockTrackToolCall } = vi.hoisted(() => ({ mockTrackToolCall: vi.fn() }))
+
+vi.mock('@/hono/analytics', () => ({
+ trackToolCall: mockTrackToolCall,
+}))
+
+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([]),
+}))
+
+import { z } from 'zod'
+
+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 { estimateTokens } from '@/lib/estimate-tokens'
+
+function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
+ return {
+ reqCtx: {
+ cache: { get: vi.fn(), set: vi.fn() },
+ getAnalyticsContextSafe: vi.fn().mockResolvedValue(undefined),
+ trackEvent: vi.fn(),
+ trackContextSwitchEvent: 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,
+ }
+}
+
+function makeFakeTool(
+ name: string,
+ handler: () => Promise<unknown> = async () => 'ok',
+ _meta?: { ui?: { resourceUri?: string } }
+): {
+ name: string
+ base: {
+ schema: z.ZodObject<Record<string, never>>
+ handler: ReturnType<typeof vi.fn>
+ _meta?: { ui?: { resourceUri?: string } }
+ }
+} {
+ return {
+ name,
+ base: {
+ schema: z.object({}),
+ handler: vi.fn().mockImplementation(handler),
+ _meta,
+ },
+ }
+}
+
+function joinedText(response: { content: Array<{ text: string }> }): string {
+ return response.content.map((part) => part.text).join('')
+}
+
+describe('ToolExecutor token estimates', () => {
+ let catalog: ToolCatalog
+ let executor: ToolExecutor
+
+ beforeEach(async () => {
+ mockTrackToolCall.mockClear()
+ catalog = new ToolCatalog()
+ await catalog.warmup()
+ executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
+ })
+
+ describe('direct tool calls', () => {
+ it('measures output tokens from the returned text, not the re-serialized payload', async () => {
+ const handlerResult = {
+ rows: [
+ { id: 1, name: 'alpha' },
+ { id: 2, name: 'beta' },
+ ],
+ }
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('my-tool', async () => handlerResult) as any
+ )
+
+ const response = (await executor.handleToolCall(
+ { name: 'my-tool', arguments: {} },
+ makeState([{ name: 'my-tool' }])
+ )) as any
+
+ const [toolName, , isError, , extra] = mockTrackToolCall.mock.calls[0]!
+ expect(toolName).toBe('my-tool')
+ expect(isError).toBe(false)
+ expect(extra.input_tokens).toBe(estimateTokens({}))
+ expect(extra.output_tokens).toBe(estimateTokens(joinedText(response)))
+ // Regression: the estimate must not measure JSON.stringify of the whole
+ // payload — the {content:[...]} wrapper and escaping inflate the count.
+ expect(extra.output_tokens).not.toBe(estimateTokens(response))
+ })
+
+ it('excludes structuredContent from the output estimate for UI tools', async () => {
+ const handlerResult = {
+ rows: [
+ { id: 1, name: 'alpha' },
+ { id: 2, name: 'beta' },
+ ],
+ }
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('ui-tool', async () => handlerResult, { ui: { resourceUri: 'ui://test-app' } }) as any
+ )
+
+ const response = (await executor.handleToolCall(
+ { name: 'ui-tool', arguments: {} },
+ makeState([{ name: 'ui-tool' }])
+ )) as any
+
+ // structuredContent rides along for UI tools but must not be double-billed.
+ expect(response.structuredContent).not.toBeUndefined()
+ const [, , , , extra] = mockTrackToolCall.mock.calls[0]!
+ expect(extra.output_tokens).toBe(estimateTokens(joinedText(response)))
+ })
+
+ it('omits token estimates on error', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw new Error('boom')
+ }) as any
+ )
+
+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+
+ const [toolName, , isError, , extra] = mockTrackToolCall.mock.calls[0]!
+ expect(toolName).toBe('fail-tool')
+ expect(isError).toBe(true)
+ expect(extra).toBeUndefined()
+ })
+ })
+
+ describe('exec wrapper event', () => {
+ it('measures output tokens from the text returned by exec', async () => {
+ const tools = catalog
+ .getFilteredTools({ scopes: ['*'] })
+ .filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')
+
+ const response = (await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'tools' } },
+ makeState(tools, { useSingleExec: true })
+ )) as any
+
+ const execCall = mockTrackToolCall.mock.calls.find((call) => call[0] === 'exec')!
+ expect(execCall[2]).toBe(false)
+ expect(execCall[4].input_tokens).toBe(estimateTokens({ command: 'tools' }))
+ expect(execCall[4].output_tokens).toBe(estimateTokens(joinedText(response)))
+ expect(execCall[4].output_tokens).not.toBe(estimateTokens(response))
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/estimate-tokens.test.ts b/services/mcp/tests/unit/estimate-tokens.test.ts
new file mode 100644
index 000000000000..b9143ceb406f
--- /dev/null
+++ b/services/mcp/tests/unit/estimate-tokens.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+
+import { estimateTokens } from '@/lib/estimate-tokens'
+
+describe('estimateTokens', () => {
+ const cases: Array<[string, unknown, number]> = [
+ ['null', null, 0],
+ ['undefined', undefined, 0],
+ ['empty string', '', 0],
+ ['4-char string', 'abcd', 1],
+ ['5-char string rounds up', 'abcde', 2],
+ ['empty object', {}, 1],
+ ['serialized object', { a: 'x' }, 3],
+ ['number', 1234, 1],
+ ]
+
+ it.each(cases)('estimates %s', (_label, value, expected) => {
+ expect(estimateTokens(value)).toBe(expected)
+ })
+
+ it('returns 0 for non-serializable values instead of throwing', () => {
+ const circular: Record<string, unknown> = {}
+ circular.self = circular
+ expect(estimateTokens(circular)).toBe(0)
+ expect(estimateTokens(10n)).toBe(0)
+ })
+})
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 22d73c5d1417..d71d8634c0e9 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -4,6 +4,7 @@ import { parse as parseYaml } from 'yaml'
import { z } from 'zod'
import { ToolInputValidationError } from '@/lib/errors'
+import { estimateTokens } from '@/lib/estimate-tokens'
import { buildQueryToolsBlock, buildToolDomainsBlock } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
import { SessionManager } from '@/lib/SessionManager'
@@ -206,6 +207,32 @@ describe('exec tool', () => {
expect(calls[0]!.properties.success).toBe(true)
expect(calls[0]!.properties.output_format).toBe('json')
expect(typeof calls[0]!.properties.duration_ms).toBe('number')
+ expect(calls[0]!.properties.input_tokens).toBeGreaterThan(0)
+ expect(calls[0]!.properties.output_tokens).toBeGreaterThan(0)
+ })
+
+ it('estimates inner output tokens from the serialized output (TOON vs JSON)', async () => {
+ const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []
+ const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {
+ calls.push({ toolName, properties })
+ }
+ const exec = createExecTool(
+ [makeMockTool()],
+ mockContext,
+ 'test description',
+ 'test command reference',
+ undefined,
+ tracker
+ )
+
+ const toonOutput = await exec.handler(mockContext, { command: 'call mock-tool' })
+ const jsonOutput = await exec.handler(mockContext, { command: 'call --json mock-tool' })
+
+ // Each estimate matches the text actually returned, not a re-stringified object.
+ expect(calls[0]!.properties.output_tokens).toBe(estimateTokens(toonOutput))
+ expect(calls[1]!.properties.output_tokens).toBe(estimateTokens(jsonOutput))
+ // TOON and JSON serialize to different sizes — the estimate tracks the wire format.
+ expect(calls[0]!.properties.output_tokens).not.toBe(calls[1]!.properties.output_tokens)
})
it('passes inline JSON arguments to the inner tool', async () => {
@@ -328,6 +355,9 @@ describe('exec tool', () => {
expect(calls[0]!.properties.success).toBe(false)
expect(calls[0]!.properties.error_message).toBe('boom')
expect(calls[0]!.properties.output_format).toBe('text')
+ // Token estimates are success-only — nothing useful to measure on a throw.
+ expect(calls[0]!.properties.input_tokens).toBeUndefined()
+ expect(calls[0]!.properties.output_tokens).toBeUndefined()
})
it('invokes the inner-call tracker with validation_error=true when input fails validation', async () => {