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.

fix(mcp): report inner tool when using exec to grafana (#59884)

Joshua Snyderefd596e30f18
diff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.ts
index 57ecf2ab7ab6..b7b84bba6bc9 100644
--- a/services/mcp/src/hono/app.ts
+++ b/services/mcp/src/hono/app.ts
@@ -1,47 +1,47 @@
-import { Hono } from "hono";
+import { Hono } from 'hono'
-import { httpMetrics, securityHeaders } from "./middleware";
-import { registerPublicRoutes } from "./public-routes";
-import { StreamableMcpHandler } from "./streamable-handler";
-import type { HonoCtx, RedisWithPing } from "./types";
+import { httpMetrics, securityHeaders } from './middleware'
+import { registerPublicRoutes } from './public-routes'
+import { StreamableMcpHandler } from './streamable-handler'
+import type { HonoCtx, RedisWithPing } from './types'
-export type Lifecycle = { shuttingDown: boolean };
+export type Lifecycle = { shuttingDown: boolean }
export type App = {
- app: Hono;
- lifecycle: Lifecycle;
- warmup: () => Promise<void>;
-};
+ app: Hono
+ lifecycle: Lifecycle
+ warmup: () => Promise<void>
+}
const sseRedirect = (c: HonoCtx): Response => {
- const target = new URL(c.req.url);
- target.pathname = "/mcp" + target.pathname.slice("/sse".length);
- target.searchParams.set("_deprecated", "sse");
- return c.redirect(target.toString(), 308) as unknown as Response;
-};
+ const target = new URL(c.req.url)
+ target.pathname = '/mcp' + target.pathname.slice('/sse'.length)
+ target.searchParams.set('_deprecated', 'sse')
+ return c.redirect(target.toString(), 308) as unknown as Response
+}
export function createApp(redis: RedisWithPing): App {
- const app = new Hono();
- const lifecycle: Lifecycle = { shuttingDown: false };
+ const app = new Hono()
+ const lifecycle: Lifecycle = { shuttingDown: false }
- app.use("*", securityHeaders);
- app.use("*", httpMetrics);
+ app.use('*', securityHeaders)
+ app.use('*', httpMetrics)
- registerPublicRoutes(app, redis, lifecycle);
+ registerPublicRoutes(app, redis, lifecycle)
- app.all("/sse", sseRedirect);
- app.all("/sse/*", sseRedirect);
+ app.all('/sse', sseRedirect)
+ app.all('/sse/*', sseRedirect)
- const streamable = new StreamableMcpHandler(redis, lifecycle);
+ const streamable = new StreamableMcpHandler(redis, lifecycle)
- app.all("/mcp", streamable.fetch);
- app.all("/mcp/*", streamable.fetch);
+ app.all('/mcp', streamable.fetch)
+ app.all('/mcp/*', streamable.fetch)
- app.all("*", (c) => c.notFound());
+ app.all('*', (c) => c.notFound())
return {
app,
lifecycle,
warmup: () => streamable.warmup(),
- };
+ }
}
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.ts
index 4a9dc1a52a4d..ad43b1925cfb 100644
--- a/services/mcp/src/hono/instructions.ts
+++ b/services/mcp/src/hono/instructions.ts
@@ -21,7 +21,9 @@ export class InstructionsBuilder {
async build(props: RequestProperties, state: ResolvedState): Promise<string> {
const supportsInstructions = state.clientProfile.capabilities.supportsInstructions
- if (!supportsInstructions) {return ''}
+ if (!supportsInstructions) {
+ return ''
+ }
const { projectId } = props
const resolvedProjectId = projectId || (await state.reqCtx.cache.get('projectId'))
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 6f5555a5eb13..45b37fb91943 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -75,7 +75,9 @@ export class RequestContext {
}
async getSessionUuid(sessionId: string | undefined): Promise<string | undefined> {
- if (!sessionId) {return undefined}
+ if (!sessionId) {
+ return undefined
+ }
return this.sessionManager.getSessionUuid(sessionId)
}
@@ -88,7 +90,9 @@ export class RequestContext {
private async resolveDistinctId(): Promise<string> {
const cached = await this.cache.get('distinctId')
- if (cached) {return cached}
+ if (cached) {
+ return cached
+ }
const userResult = await (await this.api()).users().me()
if (!userResult.success) {
throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)
@@ -116,9 +120,7 @@ export class RequestContext {
return { ...partialContext, trackEvent }
}
- async getAnalyticsContextSafe(
- context: Pick<Context, 'stateManager'>
- ): Promise<MCPAnalyticsContext | undefined> {
+ async getAnalyticsContextSafe(context: Pick<Context, 'stateManager'>): Promise<MCPAnalyticsContext | undefined> {
try {
return await context.stateManager.getAnalyticsContext()
} catch {
@@ -132,7 +134,9 @@ export class RequestContext {
previousContext: MCPAnalyticsContext | undefined
): Promise<void> {
const resolvedContext = await this.getAnalyticsContextSafe(context)
- if (!resolvedContext) {return}
+ if (!resolvedContext) {
+ return
+ }
const event =
toolName === 'switch-project'
@@ -140,7 +144,9 @@ export class RequestContext {
: toolName === 'switch-organization'
? AnalyticsEvent.MCP_ORGANIZATION_SWITCHED
: undefined
- if (!event) {return}
+ if (!event) {
+ return
+ }
const distinctId = await this.getDistinctId()
await this.trackEvent(event, {}, resolvedContext, previousContext, distinctId, this.props)
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 8cd4cdab3b47..b6bd08d77371 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -91,13 +91,18 @@ export class RequestStateResolver {
])
const flagVersion = allFlags['mcp-version-2'] ? 2 : undefined
- const toolFeatureFlags = toolFlagKeys.length > 0
- ? Object.fromEntries(toolFlagKeys.map((k) => [k, !!allFlags[k]]))
- : undefined
+ const toolFeatureFlags =
+ toolFlagKeys.length > 0 ? Object.fromEntries(toolFlagKeys.map((k) => [k, !!allFlags[k]])) : undefined
const oauthClientName = (await reqCtx.cache.get('clientName')) || undefined
const mcpClientName = props.mcpClientName || (await reqCtx.cache.get('mcpClientName')) || undefined
const mcpClientVersion = props.mcpClientVersion || (await reqCtx.cache.get('mcpClientVersion')) || undefined
+ const mcpProtocolVersion =
+ props.mcpProtocolVersion || (await reqCtx.cache.get('mcpProtocolVersion')) || undefined
+
+ props.mcpClientName = mcpClientName
+ props.mcpClientVersion = mcpClientVersion
+ props.mcpProtocolVersion = mcpProtocolVersion
const clientProfile = new MCPClientProfile({
clientName: mcpClientName,
clientVersion: mcpClientVersion,
@@ -112,6 +117,10 @@ export class RequestStateResolver {
clientVersion,
})
+ if (!props.mode) {
+ props.mode = useSingleExec ? 'cli' : 'tools'
+ }
+
const apiKeyScopes = _apiKey?.scopes ?? []
const aiConsentGiven = await context.stateManager.getAiConsentGiven()
@@ -151,7 +160,9 @@ export class RequestStateResolver {
flagKeys: string[],
groups?: FlagGroups
): Promise<Record<string, boolean>> {
- if (flagKeys.length === 0) {return {}}
+ if (flagKeys.length === 0) {
+ return {}
+ }
try {
const distinctId = await reqCtx.getDistinctId()
return await evaluateFeatureFlags(flagKeys, distinctId, groups)
diff --git a/services/mcp/src/hono/resource-catalog.ts b/services/mcp/src/hono/resource-catalog.ts
index 7e38eba6316f..49cba952ac98 100644
--- a/services/mcp/src/hono/resource-catalog.ts
+++ b/services/mcp/src/hono/resource-catalog.ts
@@ -1,7 +1,20 @@
import { RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server'
-import type { GetPromptResult, ListPromptsResult, ListResourcesResult, Prompt, ReadResourceResult, Resource, TextResourceContents } from '@modelcontextprotocol/sdk/types.js'
-
-import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive, clearResourceCache } from '@/resources/internals'
+import type {
+ GetPromptResult,
+ ListPromptsResult,
+ ListResourcesResult,
+ Prompt,
+ ReadResourceResult,
+ Resource,
+ TextResourceContents,
+} from '@modelcontextprotocol/sdk/types.js'
+
+import {
+ fetchContextMillResources,
+ filterValidEntries,
+ loadManifestFromArchive,
+ clearResourceCache,
+} from '@/resources/internals'
import { getPromptsFromManifest } from '@/resources'
import { UI_APPS } from '@/resources/ui-apps.generated'
import { buildAppStubHtml } from '@/resources/ui-apps'
@@ -109,7 +122,9 @@ export class ResourceCatalog {
private async warmupUiApps(): Promise<void> {
const baseUrl = this.env.MCP_APPS_BASE_URL
- if (!baseUrl) {return}
+ if (!baseUrl) {
+ return
+ }
const analyticsBaseUrl = this.env.POSTHOG_MCP_APPS_ANALYTICS_BASE_URL
diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.ts
index d233f0127631..f709389c341a 100644
--- a/services/mcp/src/hono/tool-catalog.ts
+++ b/services/mcp/src/hono/tool-catalog.ts
@@ -84,7 +84,9 @@ export class ToolCatalog {
for (const [name, preBuilt] of this._preBuilt) {
const def = preBuilt.definitions.v1 ?? preBuilt.definitions.v2
- if (!def) {continue}
+ if (!def) {
+ continue
+ }
let jsonSchema: Record<string, unknown>
try {
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index f486b6ea4164..57d8f835907e 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -28,6 +28,10 @@ interface ResolvedTool {
_meta?: { ui?: { resourceUri?: string }; [key: string]: unknown } | undefined
}
+interface ExecMetricState {
+ innerToolName: string | undefined
+}
+
export class ToolExecutor {
private readonly catalog: ToolCatalog
private readonly instructionsBuilder: InstructionsBuilder
@@ -68,7 +72,7 @@ export class ToolExecutor {
}
if (state.useSingleExec && toolName === 'exec') {
- return this.callTool(this.resolveExecTool(state, props), params, props, state)
+ return this.callExecTool(params, props, state)
}
if (!state.allTools.some((t) => t.name === toolName)) {
@@ -147,7 +151,6 @@ export class ToolExecutor {
} catch (error: unknown) {
toolCallsTotal.inc({ tool: tool.name, status: 'error' })
stop({ status: 'error' })
-
classifyToolError(error, tool.name)
void trackToolCall(tool.name, Date.now() - startMs, true, props, state)
@@ -157,10 +160,67 @@ export class ToolExecutor {
}
}
- private resolveExecTool(state: ResolvedState, props: RequestProperties): ResolvedTool {
+ private async callExecTool(
+ params: Record<string, unknown> | undefined,
+ props: RequestProperties,
+ state: ResolvedState
+ ): Promise<unknown> {
+ const execMetrics: ExecMetricState = { innerToolName: undefined }
+ const resolved = this.resolveExecTool(state, props, execMetrics)
+
+ const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>
+ const validation = resolved.schema.safeParse(toolArgs)
+ if (!validation.success) {
+ toolCallsTotal.inc({ tool: 'exec', status: 'validation_error' })
+ return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }
+ }
+
+ const startMs = Date.now()
+
+ try {
+ const handlerResult = await resolved.handler(state.context, validation.data)
+
+ void trackToolCall('exec', Date.now() - startMs, false, props, state)
+
+ if (isToolCallPayload(handlerResult)) {
+ return handlerResult
+ }
+
+ return buildToolResultPayload({
+ handlerResult,
+ toolMeta: resolved._meta,
+ toolName: 'exec',
+ params: validation.data,
+ clientName: props.mcpClientName,
+ distinctId: undefined,
+ })
+ } catch (error: unknown) {
+ const metricTool = execMetrics.innerToolName ?? 'exec'
+ if (!execMetrics.innerToolName) {
+ toolCallsTotal.inc({ tool: 'exec', status: 'error' })
+ }
+ classifyToolError(error, metricTool)
+
+ void trackToolCall('exec', Date.now() - startMs, true, props, state)
+
+ const sessionUuid = await state.reqCtx.getSessionUuid(props.sessionId)
+ return handleToolError(error, 'exec', state.distinctId, sessionUuid)
+ }
+ }
+
+ private resolveExecTool(
+ state: ResolvedState,
+ props: RequestProperties,
+ execMetrics: ExecMetricState
+ ): ResolvedTool {
const commandReference = this.instructionsBuilder.buildExecCommandReference(state)
const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {
+ execMetrics.innerToolName = toolName
+ const status = properties.success ? 'success' : 'error'
+ toolCallsTotal.inc({ tool: toolName, status })
+ toolCallDurationSeconds.observe({ tool: toolName, status }, properties.duration_ms / 1000)
+
void (async () => {
const freshContext = await state.reqCtx.getAnalyticsContextSafe(state.context)
await state.reqCtx.trackEvent(
diff --git a/services/mcp/tests/hono/dispatcher-profile.perf.ts b/services/mcp/tests/hono/dispatcher-profile.perf.ts
index 4a48e2c81c16..4c018500ddbc 100644
--- a/services/mcp/tests/hono/dispatcher-profile.perf.ts
+++ b/services/mcp/tests/hono/dispatcher-profile.perf.ts
@@ -72,10 +72,15 @@ function createMockFetch(): typeof fetch {
const path = new URL(url).pathname
let body: unknown = {}
- if (path.includes('/api/users/@me')) {body = mockUserResponse}
- else if (path.includes('/api/organizations')) {body = mockOrgsResponse}
- else if (path.includes('/api/projects') || path.includes('/api/environments')) {body = mockProjectsResponse}
- else if (path.includes('/decide')) {body = { featureFlags: {} }}
+ if (path.includes('/api/users/@me')) {
+ body = mockUserResponse
+ } else if (path.includes('/api/organizations')) {
+ body = mockOrgsResponse
+ } else if (path.includes('/api/projects') || path.includes('/api/environments')) {
+ body = mockProjectsResponse
+ } else if (path.includes('/decide')) {
+ body = { featureFlags: {} }
+ }
return new Response(JSON.stringify(body), {
status: 200,
@@ -125,9 +130,13 @@ function makeRequest(body: string): Request {
}
function _fmt(bytes: number): string {
- if (Math.abs(bytes) < 1024) {return `${bytes} B`}
+ if (Math.abs(bytes) < 1024) {
+ return `${bytes} B`
+ }
const kb = bytes / 1024
- if (Math.abs(kb) < 1024) {return `${kb.toFixed(1)} KB`}
+ if (Math.abs(kb) < 1024) {
+ return `${kb.toFixed(1)} KB`
+ }
return `${(kb / 1024).toFixed(2)} MB`
}
@@ -180,10 +189,7 @@ describe('McpDispatcher profiling', () => {
await dispatcher.warmup()
// Prime the warm cache
- await dispatcher.handleRequest(
- makeRequest(makeJsonRpcBody('tools/list')),
- makeProps()
- )
+ await dispatcher.handleRequest(makeRequest(makeJsonRpcBody('tools/list')), makeProps())
})
afterAll(() => {
@@ -192,13 +198,11 @@ describe('McpDispatcher profiling', () => {
it('reports warmup stats', () => {
const entries = catalog.getPreBuiltEntries()
-
+
expect(entries.length).toBeGreaterThan(0)
})
it('measures cold cache init latency', async () => {
-
-
const coldTimings: number[] = []
const coldFetchCounts: number[] = []
@@ -219,15 +223,9 @@ describe('McpDispatcher profiling', () => {
const _s = stats(coldTimings)
const _avgFetches = coldFetchCounts.reduce((a, b) => a + b, 0) / coldFetchCounts.length
-
-
-
-
}, 30_000)
it('measures warm cache request latency', async () => {
-
-
for (const [_label, method, params] of [
['initialize', 'initialize', INIT_PARAMS],
['tools/list', 'tools/list', undefined],
@@ -254,13 +252,10 @@ describe('McpDispatcher profiling', () => {
}
const _s = stats(timings)
-
}
}, 120_000)
it('measures cold vs warm fetch overhead', async () => {
-
-
// Cold: new userHash
const coldBefore = fetchCallCount
await dispatcher.handleRequest(
@@ -276,14 +271,9 @@ describe('McpDispatcher profiling', () => {
makeProps()
)
const _warmFetches = fetchCallCount - warmBefore
-
-
-
-
}, 15_000)
it('measures per-request memory (cold cache)', async () => {
-
for (const N of [1, 10, 50]) {
gc()
await new Promise((r) => setTimeout(r, 30))
@@ -375,12 +365,7 @@ describe('McpDispatcher profiling', () => {
jsonrpc: '2.0' as const,
id: i + 1,
method: i === 0 ? 'initialize' : i === 1 ? 'tools/list' : 'tools/call',
- params:
- i === 0
- ? INIT_PARAMS
- : i === 1
- ? {}
- : { name: 'user-get', arguments: {} },
+ params: i === 0 ? INIT_PARAMS : i === 1 ? {} : { name: 'user-get', arguments: {} },
}))
const resp = await dispatcher.handleRequest(
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
index 535fa23648ad..a08d2a8613ec 100644
--- a/services/mcp/tests/hono/mcp-protocol.test.ts
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -7,6 +7,7 @@ import type { RedisLike } from '@/hono/cache/RedisCache'
import {
defineAuthTests,
defineCatalogFilterTests,
+ defineExecModeTests,
defineHttpRouteTests,
defineJsonRpcEdgeCaseTests,
defineMcpProtocolTests,
@@ -83,3 +84,4 @@ defineJsonRpcEdgeCaseTests('Hono', harness)
defineSessionLifecycleTests('Hono', harness)
defineResourceCatalogTests('Hono', harness)
defineCatalogFilterTests('Hono', harness)
+defineExecModeTests('Hono', harness)
diff --git a/services/mcp/tests/hono/resource-catalog.test.ts b/services/mcp/tests/hono/resource-catalog.test.ts
index 217a9dcd9dec..2a57e02bb2f7 100644
--- a/services/mcp/tests/hono/resource-catalog.test.ts
+++ b/services/mcp/tests/hono/resource-catalog.test.ts
@@ -23,7 +23,10 @@ const mockEnv = {
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,
} as any
-function makeContextMillEntry(name: string, uri: string): { name: string; uri: string; resource: { mimeType: string; description: string; text: string } } {
+function makeContextMillEntry(
+ name: string,
+ uri: string
+): { name: string; uri: string; resource: { mimeType: string; description: string; text: string } } {
return {
name,
uri,
@@ -50,7 +53,12 @@ describe('ResourceCatalog', () => {
vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
vi.mocked(filterValidEntries).mockReturnValue(entries as any)
vi.mocked(getPromptsFromManifest).mockResolvedValue([
- { name: 'greet', title: 'Greet', description: 'A greeting', messages: [{ role: 'user', content: { type: 'text', text: 'hi' } }] },
+ {
+ name: 'greet',
+ title: 'Greet',
+ description: 'A greeting',
+ messages: [{ role: 'user', content: { type: 'text', text: 'hi' } }],
+ },
] as any)
const catalog = new ResourceCatalog(mockEnv)
@@ -115,7 +123,12 @@ describe('ResourceCatalog', () => {
vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)
vi.mocked(filterValidEntries).mockReturnValue([])
vi.mocked(getPromptsFromManifest).mockResolvedValue([
- { name: 'test-prompt', title: 'T', description: 'D', messages: [{ role: 'user', content: { type: 'text', text: 'hello' } }] },
+ {
+ name: 'test-prompt',
+ title: 'T',
+ description: 'D',
+ messages: [{ role: 'user', content: { type: 'text', text: 'hello' } }],
+ },
] as any)
const catalog = new ResourceCatalog(mockEnv)
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
new file mode 100644
index 000000000000..85182879dcfd
--- /dev/null
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -0,0 +1,241 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { mockToolCallsInc, mockToolDurationObserve, mockToolDurationStartTimer, mockToolErrorsInc } = vi.hoisted(() => {
+ const mockStop = vi.fn()
+ return {
+ mockToolCallsInc: vi.fn(),
+ mockToolDurationObserve: vi.fn(),
+ mockToolDurationStartTimer: vi.fn(() => mockStop),
+ mockToolErrorsInc: vi.fn(),
+ }
+})
+
+vi.mock('@/hono/metrics', () => ({
+ toolCallsTotal: { inc: mockToolCallsInc },
+ toolCallDurationSeconds: {
+ observe: mockToolDurationObserve,
+ startTimer: mockToolDurationStartTimer,
+ },
+ toolErrorsTotal: { inc: mockToolErrorsInc },
+}))
+
+vi.mock('@/hono/analytics', () => ({
+ trackToolCall: vi.fn(),
+}))
+
+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 type { ResolvedState } from '@/hono/request-state-resolver'
+import { ToolCatalog } from '@/hono/tool-catalog'
+import { ToolExecutor } from '@/hono/tool-executor'
+import { InstructionsBuilder } from '@/hono/instructions'
+import type { RequestProperties } from '@/lib/request-properties'
+
+function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
+ return {
+ userHash: 'test-user',
+ apiToken: 'phx_test',
+ sessionId: 'sess-1',
+ mcpClientName: 'test',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ requestStartTime: Date.now(),
+ ...overrides,
+ }
+}
+
+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,
+ version: 1,
+ useSingleExec: false,
+ toolFeatureFlags: undefined,
+ apiKeyScopes: [],
+ clientProfile: { capabilities: { supportsInstructions: true } } as any,
+ allTools: tools as any,
+ distinctId: 'test-distinct-id',
+ ...overrides,
+ }
+}
+
+function makeFakeTool(
+ name: string,
+ handler: () => Promise<unknown> = async () => 'ok'
+): {
+ name: string
+ base: { schema: z.ZodObject<Record<string, never>>; handler: ReturnType<typeof vi.fn>; _meta: undefined }
+} {
+ return {
+ name,
+ base: {
+ schema: z.object({}),
+ handler: vi.fn().mockImplementation(handler),
+ _meta: undefined,
+ },
+ }
+}
+
+function callsFor(mock: ReturnType<typeof vi.fn>, tool: string): any[] {
+ return mock.mock.calls.filter((c: any[]) => c[0]?.tool === tool).map((c: any[]) => c[0])
+}
+
+describe('ToolExecutor metrics', () => {
+ let catalog: ToolCatalog
+ let executor: ToolExecutor
+
+ beforeEach(async () => {
+ mockToolCallsInc.mockClear()
+ mockToolDurationObserve.mockClear()
+ mockToolDurationStartTimer.mockClear()
+ mockToolErrorsInc.mockClear()
+
+ catalog = new ToolCatalog()
+ await catalog.warmup()
+ executor = new ToolExecutor(catalog, new InstructionsBuilder(''))
+ })
+
+ describe('direct tool calls', () => {
+ it('records success counter and duration timer', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)
+
+ await executor.handleToolCall(
+ { name: 'my-tool', arguments: {} },
+ makeProps(),
+ makeState([{ name: 'my-tool' }])
+ )
+
+ expect(mockToolDurationStartTimer).toHaveBeenCalledWith({ tool: 'my-tool' })
+ expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'my-tool', status: 'success' })
+ expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'success' })
+ })
+
+ it('records error counter, duration timer, and error classification on failure', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw new Error('boom')
+ }) as any
+ )
+
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeProps(),
+ makeState([{ name: 'fail-tool' }])
+ )
+
+ expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'fail-tool', status: 'error' })
+ expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'fail-tool', error_type: 'internal' })
+ expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'error' })
+ })
+
+ it('records validation_error without starting a timer', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({
+ name: 'strict-tool',
+ base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
+ } as any)
+
+ await executor.handleToolCall(
+ { name: 'strict-tool', arguments: {} },
+ makeProps(),
+ makeState([{ name: 'strict-tool' }])
+ )
+
+ expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'strict-tool', status: 'validation_error' })
+ expect(mockToolDurationStartTimer).not.toHaveBeenCalled()
+ })
+
+ it('records error for unknown tool', async () => {
+ await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeProps(), makeState([]))
+
+ expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'nonexistent', status: 'error' })
+ })
+ })
+
+ describe('single-exec mode', () => {
+ function execState(): ResolvedState {
+ return makeState(
+ catalog.getPreBuiltEntries().map((e) => ({ name: e.name })),
+ { useSingleExec: true, version: 2 }
+ )
+ }
+
+ it('emits no exec-labelled counter or timer on success', async () => {
+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, makeProps(), execState())
+
+ expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)
+ expect(callsFor(mockToolDurationStartTimer, 'exec')).toHaveLength(0)
+ })
+
+ it('emits inner tool name for counter and duration on inner tool call', async () => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
+ makeProps(),
+ execState()
+ )
+
+ const innerCounts = callsFor(mockToolCallsInc, 'docs-search')
+ expect(innerCounts.length).toBeGreaterThan(0)
+ expect(innerCounts[0].status).toMatch(/^(success|error)$/)
+
+ const innerDurations = mockToolDurationObserve.mock.calls.filter((c: any[]) => c[0]?.tool === 'docs-search')
+ expect(innerDurations.length).toBeGreaterThan(0)
+
+ expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)
+ })
+
+ it('classifies inner tool errors under the inner tool name, not exec', async () => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
+ makeProps(),
+ execState()
+ )
+
+ const innerClassifications = callsFor(mockToolErrorsInc, 'docs-search')
+ const execClassifications = callsFor(mockToolErrorsInc, 'exec')
+
+ expect(innerClassifications.length).toBeGreaterThan(0)
+ expect(innerClassifications[0].error_type).toBeTruthy()
+ expect(execClassifications).toHaveLength(0)
+ })
+
+ it('emits exec-level error for framework failures before inner dispatch', async () => {
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'call nonexistent-tool-xyz {}' } },
+ makeProps(),
+ execState()
+ )
+
+ const execErrors = callsFor(mockToolCallsInc, 'exec')
+ expect(execErrors.length).toBeGreaterThan(0)
+ expect(execErrors[0].status).toBe('error')
+
+ expect(callsFor(mockToolErrorsInc, 'exec').length).toBeGreaterThan(0)
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 10af221069ab..070ee0122a30 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -11,13 +11,12 @@ vi.mock('@/resources', () => ({
getPromptsFromManifest: vi.fn().mockResolvedValue([]),
}))
-
import type { RequestProperties } from '@/lib/request-properties'
import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
import { InstructionsBuilder } from '@/hono/instructions'
-import type { } from '@/tools/types'
+import type {} from '@/tools/types'
function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
return {
@@ -104,7 +103,9 @@ describe('ToolExecutor', () => {
it('returns validation error for invalid arguments', async () => {
const knownTool = catalog.getPreBuiltEntries()[0]
- if (!knownTool) {throw new Error('need at least one tool to test validation')}
+ if (!knownTool) {
+ throw new Error('need at least one tool to test validation')
+ }
const result = (await executor.handleToolCall(
{ name: knownTool.name, arguments: { __invalid_field_xyz: 'bad' } },
@@ -118,7 +119,9 @@ describe('ToolExecutor', () => {
it('successfully calls a real tool from the catalog', async () => {
const entries = catalog.getPreBuiltEntries()
const userGet = entries.find((e) => e.name === 'user-get')
- if (!userGet) {throw new Error('user-get tool not found in catalog')}
+ if (!userGet) {
+ throw new Error('user-get tool not found in catalog')
+ }
const result = (await executor.handleToolCall(
{ name: 'user-get', arguments: {} },
@@ -136,10 +139,7 @@ describe('ToolExecutor', () => {
const allEntries = catalog.getPreBuiltEntries()
const subset = allEntries.slice(0, 3)
- const result = await executor.handleToolsList(
- makeState(subset.map((e) => ({ name: e.name }))),
- makeProps()
- )
+ const result = await executor.handleToolsList(makeState(subset.map((e) => ({ name: e.name }))), makeProps())
expect(result.tools).toHaveLength(3)
expect(result.tools.map((t) => t.name)).toEqual(subset.map((e) => e.name))
@@ -152,7 +152,10 @@ describe('ToolExecutor', () => {
it('returns single exec tool entry when useSingleExec is true', async () => {
const state = makeState(
- catalog.getPreBuiltEntries().slice(0, 5).map((e) => ({ name: e.name })),
+ catalog
+ .getPreBuiltEntries()
+ .slice(0, 5)
+ .map((e) => ({ name: e.name })),
{ useSingleExec: true, version: 2 }
)
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index d0c9cbc9f4aa..2afdf2746040 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -48,6 +48,22 @@ function buildStreamableClient(
return { client, transport }
}
+function buildExecModeClient(
+ harness: ProtocolTestHarness
+): { client: Client; transport: StreamableHTTPClientTransport } {
+ const transport = new StreamableHTTPClientTransport(new URL('/mcp', harness.baseUrl), {
+ fetch: harness.fetch,
+ requestInit: {
+ headers: {
+ Authorization: `Bearer ${harness.token}`,
+ 'x-posthog-mcp-mode': 'cli',
+ },
+ },
+ })
+ const client = new Client({ name: 'mcp-exec-test', version: '0.0.0' }, { capabilities: {} })
+ return { client, transport }
+}
+
// SDK exposes `sessionId` as `string | undefined` but the `Transport` interface
// declares it as `string`. The runtime contract is satisfied (the transport
// sets the id after the initialize handshake); the assignability mismatch is a
@@ -1111,17 +1127,12 @@ export function defineToolBehaviorTests(
fetch: harness.fetch,
requestInit: { headers: { Authorization: `Bearer ${harness.token}` } },
})
- const pinnedClient = new Client(
- { name: 'pinned-project-test', version: '0.0.0' },
- { capabilities: {} }
- )
+ const pinnedClient = new Client({ name: 'pinned-project-test', version: '0.0.0' }, { capabilities: {} })
try {
await pinnedClient.connect(transport as ConnectableTransport)
const result = await pinnedClient.callTool({ name: 'feature-flag-get-all', arguments: {} })
if (result.isError) {
- throw new Error(
- `feature-flag-get-all errored with pinned projectId: ${decodeText(result.content)}`
- )
+ throw new Error(`feature-flag-get-all errored with pinned projectId: ${decodeText(result.content)}`)
}
} finally {
await safeClose(pinnedClient)
@@ -1234,10 +1245,7 @@ export function defineCatalogFilterTests(
it('pins the catalog to specific tools when ?tools= is set', async () => {
const harness = await getHarness()
- const { tools } = await listToolsWithQuery(
- harness,
- '?tools=organization-get,projects-get'
- )
+ const { tools } = await listToolsWithQuery(harness, '?tools=organization-get,projects-get')
expect(tools.length).toBeGreaterThan(0)
const names = tools.map((t) => t.name)
// Pinned tools must appear; non-pinned ones must not.
@@ -1453,3 +1461,98 @@ export function defineResourceCatalogTests(
})
})
}
+
+// Single-exec mode: the server exposes one `exec` tool that wraps all inner
+// tools. Clients send `x-posthog-mcp-mode: cli` to enter this mode. The exec
+// tool accepts a `command` string that dispatches to the inner tool catalog
+// via verbs: `tools`, `search <regex>`, `info <tool>`, `call <tool> <json>`.
+//
+// These tests exercise the full exec flow end-to-end through the dispatcher,
+// state resolver, and tool executor — catching regressions in command parsing,
+// inner tool dispatch, and result formatting that unit tests on exec.ts alone
+// would miss.
+export function defineExecModeTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP exec mode (${label})`, () => {
+ let client: Client
+
+ beforeEach(async () => {
+ const harness = await getHarness()
+ const built = buildExecModeClient(harness)
+ client = built.client
+ await client.connect(built.transport as ConnectableTransport)
+ })
+
+ afterEach(async () => {
+ await safeClose(client)
+ })
+
+ it('lists only the exec tool when in cli mode', async () => {
+ const { tools } = await client.listTools()
+ expect(tools).toHaveLength(1)
+ expect(tools[0]!.name).toBe('exec')
+ })
+
+ it('exec "tools" lists available inner tools', async () => {
+ const result = await client.callTool({ name: 'exec', arguments: { command: 'tools' } })
+ expect(result.isError).toBeFalsy()
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text).toContain('execute-sql')
+ expect(text).toContain('organization-get')
+ })
+
+ it('exec "search" finds tools by regex', async () => {
+ const result = await client.callTool({ name: 'exec', arguments: { command: 'search feature-flag' } })
+ expect(result.isError).toBeFalsy()
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text).toContain('feature-flag')
+ })
+
+ it('exec "info" returns tool description and schema', async () => {
+ const result = await client.callTool({ name: 'exec', arguments: { command: 'info organization-get' } })
+ expect(result.isError).toBeFalsy()
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text.length).toBeGreaterThan(50)
+ expect(text.toLowerCase()).toContain('organization')
+ })
+
+ it('exec "call" dispatches to an inner tool and returns a result', async () => {
+ const result = await client.callTool({
+ name: 'exec',
+ arguments: { command: 'call organization-get {}' },
+ })
+ expect(result.isError).toBeFalsy()
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text.length).toBeGreaterThan(0)
+ })
+
+ it('exec "call" with an unknown tool returns an error message', async () => {
+ const result = await client.callTool({
+ name: 'exec',
+ arguments: { command: 'call nonexistent-tool-xyz {}' },
+ })
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text.toLowerCase()).toMatch(/not found|unknown tool/)
+ })
+
+ it('exec with an unknown verb returns a helpful error', async () => {
+ const result = await client.callTool({
+ name: 'exec',
+ arguments: { command: 'badverb something' },
+ })
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text.toLowerCase()).toMatch(/unknown|unrecognized|invalid/)
+ })
+
+ it('exec "call" with invalid JSON returns a parse error', async () => {
+ const result = await client.callTool({
+ name: 'exec',
+ arguments: { command: 'call organization-get {not-json}' },
+ })
+ const text = (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''
+ expect(text.toLowerCase()).toContain('json')
+ })
+ })
+}
diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.ts
index ddc360580490..838caaa6b543 100644
--- a/services/mcp/tests/unit/feature-flag-version.test.ts
+++ b/services/mcp/tests/unit/feature-flag-version.test.ts
@@ -71,7 +71,7 @@ describe('evaluateFeatureFlags', () => {
})
it('should evaluate multiple flags via getAllFlags and forward groups', async () => {
- mockGetAllFlags.mockResolvedValue({ 'flag-on': true, 'flag-off': false, 'unrelated': true })
+ mockGetAllFlags.mockResolvedValue({ 'flag-on': true, 'flag-off': false, unrelated: true })
const result = await evaluateFeatureFlags(['flag-on', 'flag-off'], 'user-123', { organization: 'org-abc' })