: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): surface tool domains on exec command for Claude web/desktop (#66565)
Georgiy Tarasov119b3cd8d705
diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex d1bf5af20655..ab7891064bcd 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -205,7 +205,7 @@ class McpDispatcher {: LATEST_PROTOCOL_VERSIONawait this.resourceCatalog.revalidateContextMillResources('initialize')- const instructions = await this.instructionsBuilder.build(props, state)+ const instructions = this.instructionsBuilder.build(state)initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)initTotal.inc({ status: 'success' })diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex 5cb83d2d3e8f..aed0dcfe01e3 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -1,7 +1,6 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'-import { hasScope } from '@/lib/api'import type { QueryToolInfo } from '@/lib/instructions'import {type InstructionsContext,@@ -9,7 +8,6 @@ import {schemaDiscoveryViaSqlEnabled,} from '@/lib/instructions-formatter'import type { EvaluatedFlags } from '@/lib/posthog/flags'-import type { RequestProperties } from '@/lib/request-properties'import { formatPrompt } from '@/lib/utils'import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'@@ -36,27 +34,13 @@ export class InstructionsBuilder {this.formatter = formatter ?? new InstructionsFormatter()}- async build(props: RequestProperties, state: ResolvedState): Promise<string> {+ build(state: ResolvedState): string {const supportsInstructions = state.clientProfile.capabilities.supportsInstructionsif (!supportsInstructions) {return ''}- const { projectId } = props- const resolvedProjectId = projectId || (await state.reqCtx.cache.get('projectId'))- const [groupTypes, metadata] = await Promise.all([- resolvedProjectId && hasScope(state.apiKeyScopes, 'group:read')- ? state.context.stateManager.getOrFetchGroupTypes(resolvedProjectId)- : undefined,- state.context.stateManager.getEnvironmentPrompt(),- ])-- const ctx: InstructionsContext = {- ...this.buildContext(state),- groupTypes,- metadata,- }-+ const ctx = this.buildContext(state)if (state.useSingleExec) {return this.formatter.buildExecInstructions(ctx)}@@ -82,15 +66,13 @@ export class InstructionsBuilder {}),featureFlags: state.toolFeatureFlags,renderUiEnabled: state.renderUiEnabled,+ metadata: state.metadata,+ groupTypes: state.groupTypes,}}buildExecToolEntry(state: ResolvedState): McpTool {- const supportsInstructions = state.clientProfile.capabilities.supportsInstructions- const ctx = this.buildContext(state)- const commandReference = this.formatter.buildExecCommandReference(ctx, {- stripEnvContext: supportsInstructions,- })+ const commandReference = this.buildExecCommandReference(state)const ExecSchema = { command: { type: 'string', description: commandReference } }return {@@ -125,9 +107,16 @@ export class InstructionsBuilder {buildExecCommandReference(state: ResolvedState): string {const supportsInstructions = state.clientProfile.capabilities.supportsInstructions+ // Claude web/desktop report `supportsInstructions` but never surface the+ // `instructions` payload to the model, so its env-context (tool domains,+ // project metadata, group types) would be lost. Keep it on the exec command+ // description for those hosts. (Codex, which reports `supportsInstructions:+ // false`, already gets the full env-context via the un-stripped path.)+ const keepEnvContext = state.clientProfile.isClaudeUiHost()const ctx = this.buildContext(state)return this.formatter.buildExecCommandReference(ctx, {stripEnvContext: supportsInstructions,+ keepEnvContext,})}diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex ca9b61dcb1fc..89d74f4e3718 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -1,3 +1,5 @@+import type { GroupType } from '@/api/client'+import { hasScope } from '@/lib/api'import { MCPClientProfile } from '@/lib/client-detection'import { isLocalApi } from '@/lib/constants'import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'@@ -39,6 +41,12 @@ export interface ResolvedState {scopeGatedTools: ScopeGatedTool[]distinctId: stringrenderUiEnabled: boolean+ // Active project/user environment prompt and group types. Rendered into the+ // `instructions` payload, and (for clients that don't surface instructions to+ // the model like Codex, or ignore it like Claude web/desktop) the exec command+ // reference. Resolved once here so every render path reads the same source.+ metadata: string | undefined+ groupTypes: GroupType[] | undefined}// ─── Pure helpers ───@@ -193,6 +201,13 @@ export class RequestStateResolver {// only exists in single-exec mode — skip the extra scan otherwise.const scopeGatedTools = useSingleExec ? getScopeGatedTools(apiKeyScopes, filterOptions) : []+ const [groupTypes, metadata] = await Promise.all([+ cachedProjectId && hasScope(apiKeyScopes, 'group:read')+ ? context.stateManager.getOrFetchGroupTypes(cachedProjectId).catch(() => undefined)+ : undefined,+ context.stateManager.getEnvironmentPrompt(),+ ])+return {reqCtx,context,@@ -206,6 +221,8 @@ export class RequestStateResolver {scopeGatedTools,distinctId,renderUiEnabled,+ metadata,+ groupTypes,}}diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 5a0e4e721864..d7af02225edf 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -94,8 +94,17 @@ export class InstructionsFormatter {* `instructions` field), the env-related placeholders (metadata, group* types, tool domains) resolve to empty strings to avoid duplication. The* query-tool catalog is kept: in single-exec mode it lives here on the exec- * tool, not in `instructions` (which only carries the `query` tool domain). */- buildExecCommandReference(ctx: InstructionsContext, opts: { stripEnvContext: boolean }): string {+ * tool, not in `instructions` (which only carries the `query` tool domain).+ *+ * `keepEnvContext` is the escape hatch for clients that report+ * `supportsInstructions` but don't actually surface the `instructions`+ * payload to the model (Claude web/desktop): it retains the full env-context+ * (tool-domain index, project metadata, group types) here even though+ * `stripEnvContext` is set, so it still reaches the agent. */+ buildExecCommandReference(+ ctx: InstructionsContext,+ opts: { stripEnvContext: boolean; keepEnvContext?: boolean }+ ): string {const sections = [CLI_SYNTAX,CLI_SCHEMA_DRILLDOWN,@@ -113,7 +122,14 @@ export class InstructionsFormatter {EXAMPLES,]const renderCtx: InstructionsContext = opts.stripEnvContext- ? { guidelines: ctx.guidelines, queryTools: ctx.queryTools, featureFlags: ctx.featureFlags }+ ? {+ guidelines: ctx.guidelines,+ queryTools: ctx.queryTools,+ featureFlags: ctx.featureFlags,+ ...(opts.keepEnvContext+ ? { tools: ctx.tools, metadata: ctx.metadata, groupTypes: ctx.groupTypes }+ : {}),+ }: ctxreturn this.compose(sections, renderCtx, { compact: false })}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex fde500e83b43..4b2f67e34149 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -62,6 +62,8 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {scopeGatedTools: [],distinctId: 'distinct-id',renderUiEnabled: false,+ metadata: undefined,+ groupTypes: undefined,...overrides,}}diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex bee93f3a68aa..469107606ea2 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -55,6 +55,8 @@ vi.mock('@/hono/request-context', () => {setDefaultOrganizationAndProject: vi.fn(async () => {}),getApiKey: vi.fn(async () => ({ scopes: ['*'], scoped_teams: [] })),getAiConsentGiven: vi.fn(async () => undefined),+ getOrFetchGroupTypes: vi.fn(async () => undefined),+ getEnvironmentPrompt: vi.fn(async () => undefined),},})),safelyGetAnalyticsContext: vi.fn(async () => undefined),diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex bccbb001b748..dbd27bc7326d 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -51,6 +51,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => false),+ isClaudeUiHost: vi.fn(() => false),} as any,requestContext: {sessionId: 'sess-1',@@ -64,6 +65,8 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>scopeGatedTools: [],distinctId: 'test-distinct-id',renderUiEnabled: false,+ metadata: undefined,+ groupTypes: undefined,...overrides,}}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 4562de03ae2c..379e03c9029f 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -77,6 +77,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => false),+ isClaudeUiHost: vi.fn(() => false),} as any,requestContext: {sessionId: 'sess-1',@@ -90,6 +91,8 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>scopeGatedTools: [],distinctId: 'test-distinct-id',renderUiEnabled: false,+ metadata: undefined,+ groupTypes: undefined,...overrides,}}diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.tsindex 2975f971d841..680b2ea19e34 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -54,6 +54,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => false),+ isClaudeUiHost: vi.fn(() => false),} as any,requestContext: {sessionId: 'sess-1',@@ -67,6 +68,8 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>scopeGatedTools: [],distinctId: 'test-distinct-id',renderUiEnabled: false,+ metadata: undefined,+ groupTypes: undefined,...overrides,}}diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex d513ca1ab7ed..056d443e08a5 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -48,6 +48,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>clientProfile: {capabilities: { supportsInstructions: true },isCliModeEnabled: vi.fn(() => false),+ isClaudeUiHost: vi.fn(() => false),} as any,requestContext: {sessionId: 'sess-1',@@ -61,6 +62,8 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>scopeGatedTools: [],distinctId: 'test-distinct-id',renderUiEnabled: false,+ metadata: undefined,+ groupTypes: undefined,...overrides,}}@@ -179,6 +182,61 @@ describe('ToolExecutor', () => {expect(result.tools[0]!.name).toBe('exec')})+ // Env-context (active project metadata + tool-domain index) must reach the model+ // on the exec `command` for clients that don't otherwise receive the `instructions`+ // payload: Codex reports `supportsInstructions: false` so never gets it, and Claude+ // web/desktop report `true` but silently ignore it. Claude Code strips it here+ // because it arrives via `instructions` instead.+ it.each([+ {+ label: 'Claude web/desktop (ignores instructions)',+ supportsInstructions: true,+ isClaudeUiHost: true,+ expectEnv: true,+ },+ {+ label: 'Codex (supportsInstructions: false)',+ supportsInstructions: false,+ isClaudeUiHost: false,+ expectEnv: true,+ },+ {+ label: 'Claude Code (consumes instructions)',+ supportsInstructions: true,+ isClaudeUiHost: false,+ expectEnv: false,+ },+ ])(+ 'injects project metadata into the exec command for $label → $expectEnv',+ async ({ supportsInstructions, isClaudeUiHost, expectEnv }) => {+ const tools = catalog+ .getPreBuiltEntries()+ .slice(0, 5)+ .map((e) => ({ name: e.name }))+ const metadataMarker = 'CURRENT PROJECT: Acme (timezone America/New_York)'++ const state = makeState(tools, {+ useSingleExec: true,+ metadata: metadataMarker,+ clientProfile: {+ capabilities: { supportsInstructions },+ isCliModeEnabled: vi.fn(() => true),+ isClaudeUiHost: vi.fn(() => isClaudeUiHost),+ } as any,+ })++ const result = await executor.handleToolsList(state)+ const commandDesc = (result.tools[0]!.inputSchema.properties as any).command.description as string++ expect(commandDesc).toContain('PostHog tools have lowercase kebab-case naming')+ if (expectEnv) {+ expect(commandDesc).toContain(metadataMarker)+ } else {+ expect(commandDesc).not.toContain(metadataMarker)+ }+ }+ )+it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 127f3b979cab..5fec34deaf27 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -190,6 +190,20 @@ describe('InstructionsFormatter', () => {expect(result).not.toContain('\n- dashboard\n')})+ it('keeps the full env-context even when stripEnvContext is set, when keepEnvContext is set', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecCommandReference(fullCtx, {+ stripEnvContext: true,+ keepEnvContext: true,+ })+ // The whole env-context (tool domains, project metadata, group types)+ // survives for clients (Claude web/desktop) that ignore the `instructions`+ // payload, so it still reaches the model via the command reference.+ expect(result).toContain('- dashboard')+ expect(result).toContain("The user's name is Jane Doe")+ expect(result).toContain('Defined group types: organization')+ })+it('includes the agent-feedback section only when the mcp-feedback-tool flag is on', () => {const formatter = new InstructionsFormatter()for (const stripEnvContext of [true, false]) {