: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): keep account data out of advertised mcp prompts (#105547)
Rafael Audibert1feca2f1ffab
diff --git a/services/mcp/src/cli/agent-help.ts b/services/mcp/src/cli/agent-help.tsindex a4280ab0ed93..cb2e5f7dbc29 100644--- a/services/mcp/src/cli/agent-help.ts+++ b/services/mcp/src/cli/agent-help.ts@@ -60,10 +60,6 @@ export function buildAgentHelp(tools: Tool<ZodObjectAny>[]): string {})const ctx: InstructionsContext = { guidelines: '', tools: toolInfos, queryTools }- const sections = [- AGENT_HELP_HEADER,- formatter.buildExecToolDescription(),- formatter.buildExecCommandReference(ctx, { stripEnvContext: false }),- ]+ const sections = [AGENT_HELP_HEADER, formatter.buildExecToolDescription(), formatter.buildExecCommandReference(ctx)]return toCliSyntax(sections.join('\n\n'))}diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex 65f2a11da32f..c24e29415663 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -76,9 +76,6 @@ export class InstructionsBuilder {} as QueryToolInfo}),renderUiEnabled: state.renderUiEnabled,- metadata: state.metadata,- metadataCompact: state.metadataCompact,- groupTypes: state.groupTypes,notebookCellsEnabled: state.allTools.some((tool) => tool.name === NOTEBOOK_ADD_CELL_TOOL),docsSearchEnabled: state.allTools.some((tool) => tool.name === DOCS_SEARCH_TOOL),}@@ -120,13 +117,7 @@ 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. Those chat hosts get their- // own smaller-budget reference. (Codex, which reports- // `supportsInstructions: false`, gets the full env-context via the- // un-stripped path.)+ // Claude web/desktop never show `instructions` to the model, so their reference carries the domain index.const { guidesEnabled, skillsEnabled } = this.getExecLearnCapabilities(state)const ctx = this.buildContext(state)if (state.clientProfile.isClaudeChatHost()) {@@ -135,15 +126,7 @@ export class InstructionsBuilder {skillsEnabled,})}- return this.formatter.buildExecCommandReference(ctx, {- stripEnvContext: supportsInstructions,- // Env-context rides here even for clients that honor `instructions`: that- // payload is capped at MCP_INSTRUCTIONS_CHAR_BUDGET and is spent entirely- // on the tool-domain index, which is the part that can't be recovered by- // any later tool call. This description has no such cap.- keepEnvContext: true,- learnEnabled: skillsEnabled,- })+ return this.formatter.buildExecCommandReference(ctx, { learnEnabled: skillsEnabled })}buildExecLearnCatalog(state: ResolvedState, skills: SkillCatalog | undefined): ExecLearnCatalog | undefined {diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 2678a6f44fca..0194c373660b 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -1,5 +1,3 @@-import type { GroupType } from '@/api/client'-import { hasScope } from '@/lib/api'import { MCPClientProfile } from '@/lib/client-detection'import { isCloudApi, isLocalApi, MCP_GATEWAY_FLAG } from '@/lib/constants'import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'@@ -64,18 +62,6 @@ export interface ResolvedState {gatewayToolsEnabled: booleandistinctId: 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- // Variant of `metadata` without the product/integration context lines, for the- // claude.ai exec command reference: that surface counts against the ~16 KiB- // connector-registry cap on the serialized inputSchema, which already sits- // within tens of characters of the worst-case env context. Every uncapped- // surface renders the full `metadata`.- metadataCompact: string | undefined- groupTypes: GroupType[] | undefined}// ─── Pure helpers ───@@ -154,13 +140,11 @@ export class RequestStateResolver {await this.applyPinnedContext(reqCtx, { organizationId, projectId })// Read the active project back from the token cache (the source every tool- // resolves through) rather than the request pin, so the banner and group- // types reflect an in-session switch instead of the resent pin value.- let cachedProjectId = (await reqCtx.tokenCache.get('projectId')) || projectId+ // resolves through) rather than the request pin, so an in-session switch wins.+ const cachedProjectId = (await reqCtx.tokenCache.get('projectId')) || projectIdif (!cachedProjectId) {const contextForDefault = await contextPromiseawait contextForDefault.stateManager.setDefaultOrganizationAndProject()- cachedProjectId = (await reqCtx.tokenCache.get('projectId')) ?? undefined}const [context, sessionContext] = await Promise.all([@@ -255,14 +239,6 @@ export class RequestStateResolver {// Only exec redirects a call to a gated tool; tools mode just omits it.const flagGatedTools = useSingleExec ? getFlagGatedTools(filterOptions) : []- const [groupTypes, metadata, metadataCompact] = await Promise.all([- cachedProjectId && hasScope(apiKeyScopes, 'group:read')- ? context.stateManager.getOrFetchGroupTypes(cachedProjectId).catch(() => undefined)- : undefined,- context.stateManager.getEnvironmentPrompt(),- context.stateManager.getEnvironmentPrompt({ includeProductContext: false }),- ])-return {reqCtx,context,@@ -284,9 +260,6 @@ export class RequestStateResolver {!mountsGatewayServersDirectly(props.taskOriginProduct),distinctId,renderUiEnabled,- metadata,- metadataCompact,- groupTypes,}}diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.tsindex 0fbdffa7db7c..ced7c85e4e36 100644--- a/services/mcp/src/lib/StateManager.ts+++ b/services/mcp/src/lib/StateManager.ts@@ -9,7 +9,6 @@ import {PostHogApiError,wrapError,} from '@/lib/errors'-import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'import { getPostHogClient } from '@/lib/posthog'import { sanitizeHeaderValue } from '@/lib/utils'import type { ApiUser } from '@/schema/api'@@ -353,8 +352,7 @@ export class StateManager {return undefined}- // Use the non-throwing resolver: callers like `getEnvironmentPrompt` and- // consent checks treat "no org" as "skip", not as a hard error.+ // Non-throwing: consent checks treat "no org" as "skip", not as an error.const orgId = await this._resolveOrganizationId()if (!orgId) {return undefined@@ -443,23 +441,6 @@ export class StateManager {})}- async getEnvironmentPrompt(opts?: { includeProductContext?: boolean }): Promise<string | undefined> {- const includeProductContext = opts?.includeProductContext !== false- const [user, org, project] = await Promise.all([- this.getCachedOrFetchUser().catch(() => undefined),- this.getCachedOrFetchOrg().catch(() => undefined),- this.getCachedOrFetchProject().catch(() => undefined),- ])- const integrationKinds =- includeProductContext && project- ? await this.getOrFetchIntegrationKinds(String(project.id)).catch(() => undefined)- : undefined- return buildActiveEnvironmentContextPrompt(user, org, project, this._api.publicBaseUrl, {- integrationKinds,- includeProductContext,- })- }-/*** Resolve the workspace identifiers used to attach analytics events to the* `organization` and `project` PostHog groups. Reuses the cached user/org/projectdiff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.tsindex 00b4f4e836c2..d501c129bf1a 100644--- a/services/mcp/src/lib/client-detection.ts+++ b/services/mcp/src/lib/client-detection.ts@@ -185,11 +185,8 @@ export const POSTHOG_CODE_CONSUMER = 'posthog-code'// would misclassify Claude Code as a UI host.export const ANTHROPIC_UI_HOST_VENDOR_FRAGMENTS = ['claudeai', 'cowork'] as const-// Claude web/desktop report `supportsInstructions` but never surface the-// `instructions` payload to the model, so their env-context rides on the exec-// command description instead (`keepEnvContext`). Cowork surfaces instructions-// normally and gets env-context through them, so it is not a chat host even-// though it is a UI host.+// Claude web/desktop never show `instructions` to the model. Cowork does, so it+// is not a chat host even though it is a UI host.export const ANTHROPIC_CHAT_HOST_VENDOR_FRAGMENTS = ['claudeai'] as const// Anthropic coding-agent surfaces that render MCP UI apps inline through thediff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 835c4a738a0f..4f1cfae1e1d1 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -1,8 +1,6 @@-import type { GroupType } from '@/api/client'import { MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET, MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'import {buildAvailableToolsBlock,- buildDefinedGroupsBlock,buildQueryToolsBlock,buildToolDomainsBlock,buildToolDomainsCompact,@@ -46,14 +44,12 @@ const WHATS_NEW_WITH_DOCS_SEARCH ="Check what's new via the `docs-search` tool or the changelog (https://posthog.com/changelog.md)."const WHATS_NEW_CHANGELOG_ONLY = "Check what's new in the changelog (https://posthog.com/changelog.md)."+const PROJECT_LOOKUP =+ 'Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range.'+const GROUP_TYPES_LOOKUP = "For the project's group types, run `execute-sql` on `system.group_type_mappings`."+export interface InstructionsContext {guidelines: string- groupTypes?: GroupType[] | undefined- metadata?: string | undefined- /** `metadata` without the product/integration context lines, for the claude.ai- * exec command reference, which counts against the ~16 KiB registry cap on the- * serialized inputSchema. Falls back to `metadata` when unset. */- metadataCompact?: string | undefinedtools?: ToolInfo[] | undefinedqueryTools?: QueryToolInfo[] | undefined/** Whether `render-ui` is actually available to this client (i.e. the client is@@ -77,6 +73,15 @@ function docsSearchAvailable(ctx: InstructionsContext): boolean {return ctx.docsSearchEnabled ?? ctx.tools?.some(({ name }) => name === 'docs-search') ?? false}+function envContextSections(ctx: InstructionsContext): string[] {+ const available = (tool: string): boolean => ctx.tools?.some(({ name }) => name === tool) ?? false+ const lookups = [+ ...(available('project-get') ? [PROJECT_LOOKUP] : []),+ ...(available('execute-sql') ? [GROUP_TYPES_LOOKUP] : []),+ ]+ return lookups.length > 0 ? [formatPrompt(ENV_CONTEXT, { env_lookups: lookups.join(' ') })] : []+}+/*** Composes MCP instruction prompts for the two client modes (tools-mode and* single-exec). Each mode declares an ordered list of subprompts under@@ -128,7 +133,7 @@ export class InstructionsFormatter {SCHEMA_WORKFLOW,CATALOG_TRUST_DISCOVERY,...this.artifactSections(ctx),- ENV_CONTEXT,+ ...envContextSections(ctx),URL_PATTERNS,AGENT_FEEDBACK,EXAMPLES,@@ -139,7 +144,7 @@ export class InstructionsFormatter {}/** Build the compact `instructions` payload for single-exec clients. Everything- * but the tool-domain index — env context included — lives on the exec tool's+ * but the tool-domain index lives on the exec tool's* `command` parameter description (`buildExecCommandReference`), because this* payload is hard-capped at {@link MCP_INSTRUCTIONS_CHAR_BUDGET} by Claude Code* and the command description is not.@@ -260,8 +265,6 @@ export class InstructionsFormatter {const learnSection = learnEnabled ? formatPrompt(EXEC_LEARN, { help_topics: learnGuideList }) : undefinedconst renderCtx: InstructionsContext = {guidelines: ctx.guidelines,- metadata: ctx.metadataCompact ?? ctx.metadata,- groupTypes: ctx.groupTypes,tools: ctx.tools,}@@ -280,7 +283,7 @@ export class InstructionsFormatter {CLI_ERROR_HANDLING,BASIC_FUNCTIONALITY,TOOL_SEARCH,- ENV_CONTEXT,+ ...envContextSections(ctx),// URL patterns live behind `learn urls` to protect the schema budget;// with learn unavailable there is no topic to load, so stay inline....(learnSection ? [] : [URL_PATTERNS]),@@ -295,25 +298,13 @@ export class InstructionsFormatter {)}- /** Build the `command` parameter description for the exec tool. When- * `stripEnvContext` is true (the client already received env via the- * `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).- *- * `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 env-context- * (project metadata, group types) here even though `stripEnvContext` is- * set, so it still reaches the agent.+ /** Build the `command` parameter description for the exec tool. The+ * query-tool catalog lives here: in single-exec mode `instructions` only+ * carries the `query` tool domain.** Claude web/desktop uses `buildClaudeExecCommandReference` instead because* its complete JSON schema has a smaller client-enforced size budget. */- buildExecCommandReference(- ctx: InstructionsContext,- opts: { stripEnvContext: boolean; keepEnvContext?: boolean; learnEnabled?: boolean }- ): string {+ buildExecCommandReference(ctx: InstructionsContext, opts: { learnEnabled?: boolean } = {}): string {const sections = [CLI_SYNTAX,...(opts.learnEnabled ? [CLI_LEARN] : []),@@ -329,20 +320,12 @@ export class InstructionsFormatter {SCHEMA_WORKFLOW,CATALOG_TRUST_DISCOVERY,...this.artifactSections(ctx),- ENV_CONTEXT,+ ...envContextSections(ctx),URL_PATTERNS,AGENT_FEEDBACK,EXAMPLES,]- const docsSearchEnabled = docsSearchAvailable(ctx)- const renderCtx: InstructionsContext = opts.stripEnvContext- ? {- guidelines: ctx.guidelines,- queryTools: ctx.queryTools,- docsSearchEnabled,- ...(opts.keepEnvContext ? { metadata: ctx.metadata, groupTypes: ctx.groupTypes } : {}),- }- : { ...ctx, tools: undefined, docsSearchEnabled }+ const renderCtx: InstructionsContext = { ...ctx, tools: undefined, docsSearchEnabled: docsSearchAvailable(ctx) }// Tool domains are temporarily omitted from the command reference while we// probe claude.ai's per-tool size cap (it silently drops oversized entries);// agents still discover domains at runtime via the `search` command, and@@ -371,8 +354,6 @@ export class InstructionsFormatter {const vars = {guidelines: ctx.guidelines.trim(),available_tools: buildAvailableToolsBlock(ctx.renderUiEnabled),- defined_groups: buildDefinedGroupsBlock(ctx.groupTypes),- metadata: ctx.metadata?.trim() ?? '',tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',entity_schema_discovery: ENTITY_SCHEMA_DISCOVERY.trim(),diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex 06d29d083341..34f095ecd371 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -1,12 +1,4 @@-import type { GroupType } from '@/api/client'-import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'--export function buildDefinedGroupsBlock(groupTypes?: GroupType[]): string {- if (!groupTypes || groupTypes.length === 0) {- return ''- }- return `Defined group types: ${groupTypes.map((gt) => gt.group_type).join(', ')}`-}+import type { CachedOrg, CachedProject } from '@/tools/types'/** Bounds the onboarded-products line for intent-heavy teams; the environment* prompt is repeated context, so the tail is summarized as a count instead. */@@ -72,36 +64,28 @@ function buildIntegrationsLine(integrationKinds?: string[]): string | undefinedexport interface EnvironmentContextOptions {/** Integration kinds connected in the active project; `undefined` means unknown. */integrationKinds?: string[]- /** Set to false for character-budgeted surfaces (the claude.ai exec command- * reference counts against a ~16 KiB registry cap on the serialized- * inputSchema) where the product/integration lines do not fit. */- includeProductContext?: boolean}export function buildActiveEnvironmentContextPrompt(- user?: CachedUser,org?: CachedOrg,project?: CachedProject,regionalBaseUrl?: string,opts?: EnvironmentContextOptions): string | undefined {- if (!user && !org && !project) {+ if (!org && !project) {return undefined}const lines: string[] = []- if (org || project) {- const projectName = project?.name ?? 'Unknown'- const projectId = project?.id ?? 'unknown'-- if (org) {- const orgName = org.name ?? 'Unknown'- const orgId = org.id ?? 'unknown'- lines.push(- `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`- )- } else {- lines.push(`You are currently in project "${projectName}" (id: ${projectId}).`)- }+ const projectName = project?.name ?? 'Unknown'+ const projectId = project?.id ?? 'unknown'+ if (org) {+ const orgName = org.name ?? 'Unknown'+ const orgId = org.id ?? 'unknown'+ lines.push(+ `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`+ )+ } else {+ lines.push(`You are currently in project "${projectName}" (id: ${projectId}).`)}if (regionalBaseUrl) {const origin = regionalBaseUrl.replace(/^https?:\/\//, '')@@ -112,7 +96,7 @@ export function buildActiveEnvironmentContextPrompt()}if (project) {- lines.push(`Project timezone: ${project.timezone ?? 'UTC'}.`)+ lines.push('For project settings such as the timezone, call `project-get` without an ID.')if (project.test_account_filters_default_checked) {lines.push('This project filters out internal and test users by default. `query-*` tools apply this automatically when `filterTestAccounts` is omitted; when composing queries for other tools (e.g. insight-create), set `filterTestAccounts: true` unless the user asks to include internal/test data.'@@ -128,18 +112,12 @@ export function buildActiveEnvironmentContextPrompt("Person properties are query-time in this project. `person.properties.*` on the events table always returns the person's current (latest) value, regardless of when the event occurred.")}- if (opts?.includeProductContext !== false) {- lines.push(...buildProductLines(project))- const integrationsLine = buildIntegrationsLine(opts?.integrationKinds)- if (integrationsLine) {- lines.push(integrationsLine)- }+ lines.push(...buildProductLines(project))+ const integrationsLine = buildIntegrationsLine(opts?.integrationKinds)+ if (integrationsLine) {+ lines.push(integrationsLine)}}- if (user) {- const fullName = [user.first_name, user.last_name].filter(Boolean).join(' ') || 'Unknown'- lines.push(`The user's name is ${fullName} (${user.email}).`)- }// No prose preamble: the heading plus the lines themselves already say the agent// is in this project, and the sentence it replaced ("All tool calls and queries// default to this environment…") cost 111 characters of a budgeted payload todiff --git a/services/mcp/src/templates/sections/env-context.md b/services/mcp/src/templates/sections/env-context.mdindex df4030054cab..35d550bcb21a 100644--- a/services/mcp/src/templates/sections/env-context.md+++ b/services/mcp/src/templates/sections/env-context.md@@ -1,3 +1,3 @@-{defined_groups}+### Active environment-{metadata}+{env_lookups}diff --git a/services/mcp/src/templates/sections/url-patterns.md b/services/mcp/src/templates/sections/url-patterns.mdindex a6ad0bff89a5..186be7b295b4 100644--- a/services/mcp/src/templates/sections/url-patterns.md+++ b/services/mcp/src/templates/sections/url-patterns.md@@ -6,6 +6,6 @@ Choose the link source in this order:1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.-3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.+3. Only for genuinely static pages not in the `generate-app-url` catalog (some settings pages), take the origin from a PostHog URL you already have (any `_posthogUrl`, or a `generate-app-url` result). Then build the link (don't double-prefix):+ - Project-scoped paths → origin + `/project/<active project id>`, never an id copied from another URL: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`).+ - Org-/account-level paths → origin only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.diff --git a/services/mcp/src/tools/organizations/setActive.ts b/services/mcp/src/tools/organizations/setActive.tsindex eb8d4d89fcd5..a37acb405e6f 100644--- a/services/mcp/src/tools/organizations/setActive.ts+++ b/services/mcp/src/tools/organizations/setActive.ts@@ -2,7 +2,7 @@ import type { z } from 'zod'import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'import { OrganizationSetActiveSchema } from '@/schema/tool-inputs'-import type { CachedOrg, CachedProject, CachedUser, Context, ToolBase } from '@/tools/types'+import type { CachedOrg, CachedProject, Context, ToolBase } from '@/tools/types'const schema = OrganizationSetActiveSchema@@ -29,16 +29,14 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asynawait context.cache.set(`cachedOrgFetchedAt:${orgId}` as const, Date.now())}- // Read cached user and project for full metadata block- const distinctId = (await context.cache.get('distinctId')) ?? 'unknown'+ // Read cached project for full metadata blockconst projectId = (await context.cache.get('projectId')) ?? 'unknown'- const user = (await context.cache.get(`cachedUser:${distinctId}` as const)) as CachedUser | undefinedconst project = (await context.cache.get(`cachedProject:${projectId}` as const)) as CachedProject | undefinedconst integrationKinds = project? await context.stateManager.getOrFetchIntegrationKinds(String(project.id)).catch(() => undefined): undefined- const metadata = buildActiveEnvironmentContextPrompt(user, org, project, context.api.publicBaseUrl, {+ const metadata = buildActiveEnvironmentContextPrompt(org, project, context.api.publicBaseUrl, {integrationKinds,})const text = metadatadiff --git a/services/mcp/src/tools/projects/setActive.ts b/services/mcp/src/tools/projects/setActive.tsindex d31576f38fa8..b0753f5b0f0c 100644--- a/services/mcp/src/tools/projects/setActive.ts+++ b/services/mcp/src/tools/projects/setActive.ts@@ -3,7 +3,7 @@ import type { z } from 'zod'import { wrapError } from '@/lib/errors'import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'import { ProjectSetActiveSchema } from '@/schema/tool-inputs'-import type { CachedOrg, CachedProject, CachedUser, Context, ToolBase } from '@/tools/types'+import type { CachedOrg, CachedProject, Context, ToolBase } from '@/tools/types'const schema = ProjectSetActiveSchema@@ -71,16 +71,14 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn// doesn't revert it on the next request.await context.setSessionActiveContext?.({ projectId: projectIdStr, ...(orgId ? { orgId } : {}) })- // Read cached user (and org, when we didn't just fetch it) for the metadata block- const distinctId = (await context.cache.get('distinctId')) ?? 'unknown'- const user = (await context.cache.get(`cachedUser:${distinctId}` as const)) as CachedUser | undefined+ // Read the cached org, when we didn't just fetch it, for the metadata blockif (!org && orgId) {org = (await context.cache.get(`cachedOrg:${orgId}` as const)) as CachedOrg | undefined}const orgNote = switchedOrg ? ` (also switched the active organization to ${orgId} to match)` : ''const integrationKinds = await context.stateManager.getOrFetchIntegrationKinds(projectIdStr).catch(() => undefined)- const metadata = buildActiveEnvironmentContextPrompt(user, org, project, context.api.publicBaseUrl, {+ const metadata = buildActiveEnvironmentContextPrompt(org, project, context.api.publicBaseUrl, {integrationKinds,})const text = metadatadiff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex fe8c5f4ef34d..34b6c14b275a 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -81,9 +81,6 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {gatewayToolsEnabled: false,distinctId: 'distinct-id',renderUiEnabled: false,- metadata: undefined,- metadataCompact: 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 d45eabde147c..9487b9a6ed4f 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -87,8 +87,6 @@ vi.mock('@/hono/request-context', () => {setDefaultOrganizationAndProject: vi.fn(async () => {}),getApiKey: vi.fn(async () => mockApiKey),getAiConsentGiven: vi.fn(async () => undefined),- getOrFetchGroupTypes: vi.fn(async () => undefined),- getEnvironmentPrompt: vi.fn(async () => undefined),getAvailableFeatures: vi.fn(async () => undefined),},})),diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 95dbf085f564..dc49331f8a08 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -451,11 +451,8 @@ describe('ToolExecutor', () => {})})- // Active project metadata reaches the model on the exec `command` for every- // single-exec client, including the ones that honor `instructions`: that payload is- // capped at MCP_INSTRUCTIONS_CHAR_BUDGET and spends all of it on the tool-domain- // index, so env-context would be the first thing a client-side truncation ate. The- // command description has no cap. The domain index is the mirror image — it stays+ // Hosts cache one tool roster and serve it to other accounts, so nothing+ // account-specific may reach the advertised exec entry. The domain index stays// out of the command description except for Claude web/desktop, which ignores// `instructions` and has nowhere else to receive it.it.each([@@ -475,38 +472,42 @@ describe('ToolExecutor', () => {isClaudeChatHost: false,},])(- 'injects project metadata into the exec command for $label',+ 'advertises the same exec entry to every account for $label',async ({ supportsInstructions, isClaudeChatHost }) => {- const tools = catalog- .getPreBuiltEntries()- .slice(0, 5)- .map((e) => ({ name: e.name }))- const metadataMarker = 'CURRENT PROJECT: Acme (timezone America/New_York)'-- const state = makeToolExecutorState(tools, {- useSingleExec: true,- metadata: metadataMarker,- clientProfile: {- capabilities: { supportsInstructions },- isCliModeEnabled: vi.fn(() => true),- isClaudeUiHost: vi.fn(() => false),- isInlineExecUiHost: vi.fn(() => false),- isClaudeChatHost: vi.fn(() => isClaudeChatHost),- } as any,- })+ const tools = [+ ...catalog+ .getPreBuiltEntries()+ .slice(0, 5)+ .map((e) => ({ name: e.name })),+ { name: 'project-get' },+ ]+ const stateFor = (distinctId: string): ReturnType<typeof makeToolExecutorState> =>+ makeToolExecutorState(tools, {+ useSingleExec: true,+ distinctId,+ clientProfile: {+ capabilities: { supportsInstructions },+ isCliModeEnabled: vi.fn(() => true),+ isClaudeUiHost: vi.fn(() => false),+ isInlineExecUiHost: vi.fn(() => false),+ isClaudeChatHost: vi.fn(() => isClaudeChatHost),+ } as any,+ })- const result = await executor.handleToolsList(state)+ const result = await executor.handleToolsList(stateFor('account-a'))+ const other = await executor.handleToolsList(stateFor('account-b'))const commandDesc = (result.tools[0]!.inputSchema.properties as any).command.description as stringconst compactDomains = buildToolDomainsCompact(tools.map(({ name }) => ({ name, category: getToolDefinition(name).category })))+ expect(JSON.stringify(other.tools)).toBe(JSON.stringify(result.tools))expect(commandDesc).toContain('PostHog tools have lowercase kebab-case naming')expect(commandDesc.includes('**LEARN FIRST: HARD REQUIREMENT**')).toBe(isClaudeChatHost)expect(commandDesc.includes('- analytics:')).toBe(isClaudeChatHost)expect(commandDesc.includes('### Retrieving data')).toBe(!isClaudeChatHost)expect(commandDesc.includes(compactDomains)).toBe(isClaudeChatHost)- expect(commandDesc).toContain(metadataMarker)+ expect(commandDesc).toContain('Call `project-get` without an ID to read the active project')})diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex ca99693eaf2b..9232319555b1 100644--- a/services/mcp/tests/shared/test-utils.ts+++ b/services/mcp/tests/shared/test-utils.ts@@ -701,9 +701,6 @@ export function makeToolExecutorState(gatewayToolsEnabled: false,distinctId: 'test-distinct-id',renderUiEnabled: false,- metadata: undefined,- metadataCompact: undefined,- groupTypes: undefined,...overrides,}}diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.tsindex c1956d665a56..85121bc9129c 100644--- a/services/mcp/tests/unit/StateManager.test.ts+++ b/services/mcp/tests/unit/StateManager.test.ts@@ -492,8 +492,7 @@ describe('StateManager', () => {describe('getCachedOrFetchOrg', () => {it('returns undefined when no org can be resolved (does not throw)', async () => {- // Preserves the best-effort contract used by getEnvironmentPrompt and- // consent checks: if no org is in scope, the call is a no-op.+ // Consent checks rely on this best-effort contract.vi.spyOn(stateManager, 'getApiKey').mockResolvedValue({scopes: ['organization:read'],scoped_organizations: [],diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txtindex 6f549e671eea..8ece99581f19 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt@@ -163,12 +163,10 @@ Only fall back to `tools` if you have no idea which domain to search, or if `seaPostHog tools have lowercase kebab-case naming. Tools are organized by category:-business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|query+business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|project|queryTypical action names: list/retrieve/get/create/update/delete/query.Example tool names: execute-sql, experiment-create, feature-flag-get-all.-Defined group types: organization, project+### Active environment-You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).-Project timezone: America/New_York.-The user's name is Jane Doe ([email protected]).\ No newline at end of file+Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range. For the project's group types, run `execute-sql` on `system.group_type_mappings`.\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txtindex 6f98619ce7b8..c99304193c6f 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt@@ -150,12 +150,10 @@ Only fall back to `tools` if you have no idea which domain to search, or if `seaPostHog tools have lowercase kebab-case naming. Tools are organized by category:-business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|query+business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|project|queryTypical action names: list/retrieve/get/create/update/delete/query.Example tool names: execute-sql, experiment-create, feature-flag-get-all.-Defined group types: organization, project+### Active environment-You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).-Project timezone: America/New_York.-The user's name is Jane Doe ([email protected]).\ No newline at end of file+Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range. For the project's group types, run `execute-sql` on `system.group_type_mappings`.\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex 8e223b65dd0a..b5194af0f437 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -266,11 +266,9 @@ When work produces something worth keeping, pick the artifact before you start bDefault to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true" — a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard.-Defined group types: organization, project+### Active environment-You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).-Project timezone: America/New_York.-The user's name is Jane Doe ([email protected]).+Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range. For the project's group types, run `execute-sql` on `system.group_type_mappings`.### URL patterns@@ -280,9 +278,9 @@ Choose the link source in this order:1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.-3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.+3. Only for genuinely static pages not in the `generate-app-url` catalog (some settings pages), take the origin from a PostHog URL you already have (any `_posthogUrl`, or a `generate-app-url` result). Then build the link (don't double-prefix):+ - Project-scoped paths → origin + `/project/<active project id>`, never an id copied from another URL: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`).+ - Org-/account-level paths → origin only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.### Sharing feedback on PostHogdiff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txtindex 4eb66c4ca723..753be71b2df4 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt@@ -1,6 +1,6 @@# PostHog `exec` covers-business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|query+business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|project|query# Toolsdiff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex e4bb428a2d46..dc67e14b6e2b 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -53,6 +53,7 @@ PostHog tools have lowercase kebab-case naming. Tools are organized by category:- docs-search- execute-sql- feature-flag+- project- queryTypical action names: list/retrieve/get/create/update/delete/query.Example tool names: execute-sql, experiment-create, feature-flag-get-all.@@ -167,11 +168,9 @@ When work produces something worth keeping, pick the artifact before you start bDefault to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true" — a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard.-Defined group types: organization, project+### Active environment-You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).-Project timezone: America/New_York.-The user's name is Jane Doe ([email protected]).+Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range. For the project's group types, run `execute-sql` on `system.group_type_mappings`.### URL patterns@@ -181,9 +180,9 @@ Choose the link source in this order:1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.-3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.+3. Only for genuinely static pages not in the `generate-app-url` catalog (some settings pages), take the origin from a PostHog URL you already have (any `_posthogUrl`, or a `generate-app-url` result). Then build the link (don't double-prefix):+ - Project-scoped paths → origin + `/project/<active project id>`, never an id copied from another URL: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`).+ - Org-/account-level paths → origin only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.### Sharing feedback on PostHogdiff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 6fa37f6ea5dd..837f212d04b8 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -6,9 +6,9 @@ import { z } from 'zod'import { STRUCTURED_CONTENT_ONLY_TEXT, type ToolResultPayload, UI_APP_RENDER_NOTE } from '@/lib/build-tool-result'import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'-import { formatResponse } from '@/lib/response'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'+import { formatResponse } from '@/lib/response'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'import {@@ -1880,10 +1880,11 @@ describe('exec tool', () => {}})const formatter = new InstructionsFormatter()- const commandReference = formatter.buildExecCommandReference(- { guidelines, tools: toolInfos, queryTools: queryToolInfos },- { stripEnvContext: false }- )+ const commandReference = formatter.buildExecCommandReference({+ guidelines,+ tools: toolInfos,+ queryTools: queryToolInfos,+ })const execTool = createExecTool(v2Tools,context,@@ -1913,10 +1914,11 @@ describe('exec tool', () => {const queryToolInfos = [{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' }]const formatter = new InstructionsFormatter()- const commandReference = formatter.buildExecCommandReference(- { guidelines, tools: toolInfos, queryTools: queryToolInfos },- { stripEnvContext: false }- )+ const commandReference = formatter.buildExecCommandReference({+ guidelines,+ tools: toolInfos,+ queryTools: queryToolInfos,+ })const execTool = createExecTool([],createExecContext(),diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex 52384dfe0dfb..f6a28bf4d4cb 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -4,24 +4,18 @@ import { describe, expect, it } from 'vitest'import { PostHogMCP } from '@posthog/mcp-analytics'-import type { GroupType } from '@/api/client'import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { MCPClientProfile } from '@/lib/client-detection'import { MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'-import { buildActiveEnvironmentContextPrompt, buildToolDomainsCompact, type QueryToolInfo } from '@/lib/instructions'+import { buildToolDomainsCompact, type QueryToolInfo } from '@/lib/instructions'import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'import { getToolCategory, getToolDefinitions } from '@/tools/toolDefinitions'-import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'// Static, deterministic context shared by all snapshots — mirrors the realistic// values used in `instructions-formatter.test.ts` so the rendered prompts cover-// guidelines, group types, metadata, tool domains, and query tools.-const STATIC_GROUP_TYPES: GroupType[] = [- { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },- { group_type: 'project', group_type_index: 1, name_singular: null, name_plural: null },-]+// guidelines, tool domains, and query tools.// Includes query-* (collapsed into the single `query` domain) so the snapshots// mirror production, where `tools` is the full set and `queryTools` is the// parallel catalog projection.@@ -31,6 +25,7 @@ const STATIC_TOOLS = [{ name: 'create-feature-flag', category: 'Feature flags' },{ name: 'feature-flag-get-all', category: 'Feature flags' },{ name: 'execute-sql', category: 'SQL' },+ { name: 'project-get', category: 'Core' },{ name: 'business-knowledge-documents-search', category: 'Business knowledge' },{ name: 'docs-search', category: 'Docs' },{ name: 'query-funnel', category: 'Query wrappers' },@@ -40,16 +35,8 @@ const STATIC_QUERY_TOOLS: QueryToolInfo[] = [{ name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },]-const STATIC_METADATA = [- 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).',- 'Project timezone: America/New_York.',- "The user's name is Jane Doe ([email protected]).",-].join('\n')-const STATIC_CTX: InstructionsContext = {guidelines: 'some guidelines',- groupTypes: STATIC_GROUP_TYPES,- metadata: STATIC_METADATA,tools: STATIC_TOOLS,queryTools: STATIC_QUERY_TOOLS,renderUiEnabled: true,@@ -101,7 +88,7 @@ describe('InstructionsFormatter prompt snapshots', () => {it('matches the exec command reference (Codex wiring, every placeholder filled)', async () => {const formatter = new InstructionsFormatter()- const rendered = formatter.buildExecCommandReference(STATIC_CTX, { stripEnvContext: false })+ const rendered = formatter.buildExecCommandReference(STATIC_CTX)await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-full.txt'))})@@ -111,8 +98,6 @@ describe('InstructionsFormatter prompt snapshots', () => {clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI' }),toolFeatureFlags,renderUiEnabled: STATIC_CTX.renderUiEnabled,- metadata: STATIC_CTX.metadata,- groupTypes: STATIC_CTX.groupTypes,requestContext: { mcpConsumer: undefined },sessionContext: null,} as unknown as ResolvedState@@ -183,49 +168,7 @@ describe('InstructionsFormatter prompt snapshots', () => {// ------------------------------------------------------------------------------------------------it('keeps the serialized exec inputSchema under the claude.ai registry cap', () => {// Worst case served in production: Claude web/desktop with every optional- // learning topic advertised, the full live tool catalog, and long environment- // context. The metadata goes through the real- // env-context builder with inputs at the backing columns' max lengths- // (Team.name 200, Organization.name 64, email 254, Django names 150) plus- // the longer person-on-events branch, so a long org/project/user cannot- // push the real schema past the cap while this test passes.- const worstCaseUser = {- first_name: 'F'.repeat(150),- last_name: 'L'.repeat(150),- email: `${'e'.repeat(242)}@example.com`,- } as CachedUser- const worstCaseOrg = { name: 'O'.repeat(64), id: '00000000-0000-0000-0000-000000000000' } as CachedOrg- const worstCaseProject = {- name: 'P'.repeat(200),- id: 9_999_999,- api_token: `phc_${'x'.repeat(43)}`,- timezone: 'America/Argentina/ComodRivadavia',- person_on_events_querying_enabled: true,- } as CachedProject- const worstCaseMetadata = buildActiveEnvironmentContextPrompt(- worstCaseUser,- worstCaseOrg,- worstCaseProject,- 'https://us.posthog.com'- )- // The claude.ai reference renders the compact metadata variant: the- // product/integration context lines are excluded from this surface by- // design because they do not fit under the cap (see- // `buildClaudeExecCommandReference` and `ResolvedState.metadataCompact`).- const worstCaseMetadataCompact = buildActiveEnvironmentContextPrompt(- worstCaseUser,- worstCaseOrg,- worstCaseProject,- 'https://us.posthog.com',- { includeProductContext: false }- )- // Five group types (the product cap) with generously long names.- const worstCaseGroupTypes = Array.from({ length: 5 }, (_, i) => ({- group_type: `${'g'.repeat(28)}-${i}`,- group_type_index: i,- name_singular: null,- name_plural: null,- })) as GroupType[]+ // learning topic advertised and the full live tool catalog.const state = {allTools: Object.keys(getToolDefinitions()).map((name) => ({ name })),clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI', userAgent: 'Claude-User' }),@@ -233,9 +176,6 @@ describe('InstructionsFormatter prompt snapshots', () => {// capped command reference.toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },renderUiEnabled: true,- metadata: worstCaseMetadata,- metadataCompact: worstCaseMetadataCompact,- groupTypes: worstCaseGroupTypes,requestContext: { mcpConsumer: undefined },sessionContext: null,} as unknown as ResolvedState@@ -267,12 +207,8 @@ describe('InstructionsFormatter prompt snapshots', () => {// reference, which has no such cap.// ------------------------------------------------------------------------------------------------it('keeps the compact exec instructions under the Claude Code truncation cap', () => {- // The full live tool catalog, plus env context and group types that the payload no- // longer carries — if either is ever spliced back into the compact template, the- // budget has to account for it here rather than fail silently in production.const ctx: InstructionsContext = {...STATIC_CTX,- metadata: STATIC_METADATA,tools: Object.keys(getToolDefinitions()).map((name) => ({name,category: getToolCategory(name) ?? 'Other',diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 932fbb630ee4..1f7cfe6101af 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -1,13 +1,9 @@import { describe, expect, it } from 'vitest'-import type { GroupType } from '@/api/client'import { MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'import { buildToolDomainsCompact, type QueryToolInfo } from '@/lib/instructions'import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'-const realisticGroupTypes: GroupType[] = [- { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },-]// `tools` mirrors production: the full tool set, query-* included (the domain// extractor collapses them into the single `query` domain). `queryTools` below// is the parallel catalog projection with hints.@@ -17,6 +13,7 @@ const realisticTools = [{ name: 'feature-flag-create', category: 'Feature flags' },{ name: 'feature-flag-get-all', category: 'Feature flags' },{ name: 'execute-sql', category: 'SQL' },+ { name: 'project-get', category: 'Core' },{ name: 'business-knowledge-documents-search', category: 'Business knowledge' },{ name: 'docs-search', category: 'Docs' },{ name: 'query-trends', category: 'Query wrappers' },@@ -26,15 +23,11 @@ const realisticQueryTools: QueryToolInfo[] = [{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },{ name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },]-const realisticMetadata =- 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).\n' +- 'Project timezone: America/New_York.\n' +- "The user's name is Jane Doe ([email protected])."+const ENV_POINTER = 'Call `project-get` without an ID to read the active project'+const GROUP_TYPES_POINTER = 'run `execute-sql` on `system.group_type_mappings`'const fullCtx: InstructionsContext = {guidelines: 'some guidelines',- groupTypes: realisticGroupTypes,- metadata: realisticMetadata,tools: realisticTools,queryTools: realisticQueryTools,renderUiEnabled: true,@@ -45,17 +38,13 @@ describe('InstructionsFormatter', () => {it('resolves every placeholder when fully populated', () => {const formatter = new InstructionsFormatter()const result = formatter.buildToolsInstructions(fullCtx)- expect(result).toContain('Defined group types: organization')- expect(result).toContain("The user's name is Jane Doe")- expect(result).toContain('Project timezone: America/New_York.')+ expect(result).toContain(ENV_POINTER)expect(result).toContain('- dashboard')expect(result).toContain('- feature-flag')expect(result).toContain('- execute-sql')expect(result).toContain('- `query-funnel` — conversion rate')expect(result).toContain('- `query-trends` — time series')- expect(result).not.toMatch(- /\{tool_domains\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/- )+ expect(result).not.toMatch(/\{tool_domains\}|\{query_tools\}|\{guidelines\}/)})it('renders the basic functionality, retrieving data, and examples sections', () => {@@ -82,10 +71,8 @@ describe('InstructionsFormatter', () => {const formatter = new InstructionsFormatter()const result = formatter.buildToolsInstructions({ guidelines: 'rules' })expect(result).not.toContain('{guidelines}')- expect(result).not.toContain('{defined_groups}')expect(result).not.toContain('{tool_domains}')expect(result).not.toContain('{query_tools}')- expect(result).not.toContain('{metadata}')})it('omits business knowledge guidance when search is unavailable', () => {@@ -132,17 +119,14 @@ describe('InstructionsFormatter', () => {const result = formatter.buildExecInstructions(fullCtx)// query-* tools surface as the single `query` domain, not a separate catalog lineexpect(result).toContain(- 'business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|query'+ 'business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|project|query')expect(result).not.toContain('### PostHog knowledge sources')expect(result).not.toContain('query-*:')// Env context is not here — it rides the exec command description, which has no// truncation cap, leaving this payload's whole budget to the domain index.- expect(result).not.toContain('Defined group types: organization')- expect(result).not.toContain("The user's name is Jane Doe")- expect(result).not.toMatch(- /\{tool_domains\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/- )+ expect(result).not.toContain(ENV_POINTER)+ expect(result).not.toMatch(/\{tool_domains\}|\{query_tools\}|\{guidelines\}/)})// Synthetic fixture: 60 uniform `domain-N-get` names collapse to short domains and@@ -163,8 +147,6 @@ describe('InstructionsFormatter', () => {const formatter = new InstructionsFormatter()const result = formatter.buildExecInstructions({guidelines: 'guidelines',- groupTypes: realisticGroupTypes,- metadata: realisticMetadata,tools: manyTools,queryTools: manyQueryTools,})@@ -240,81 +222,59 @@ describe('InstructionsFormatter', () => {})describe('buildExecCommandReference', () => {- it('carries the CLI mechanics regardless of stripEnvContext', () => {- const formatter = new InstructionsFormatter()- for (const stripEnvContext of [true, false]) {- const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })- expect(result).toContain('SCHEMA DRILL-DOWN RULE')- expect(result).not.toContain('### PostHog knowledge sources')- expect(result).toContain('### Basic functionality')- expect(result).toContain('### Examples')- }+ it.each([+ { name: 'both lookup tools', tools: ['project-get', 'execute-sql'], project: true, groups: true },+ { name: 'only project-get', tools: ['project-get'], project: true, groups: false },+ { name: 'only execute-sql', tools: ['execute-sql'], project: false, groups: true },+ { name: 'neither lookup tool', tools: [], project: false, groups: false },+ ])('names only the env lookup tools the roster has: $name', ({ tools, project, groups }) => {+ const ctx = { ...fullCtx, tools: tools.map((name) => ({ name, category: 'Core' })) }+ const result = new InstructionsFormatter().buildExecCommandReference(ctx)+ expect(result.includes(ENV_POINTER)).toBe(project)+ expect(result.includes(GROUP_TYPES_POINTER)).toBe(groups)+ expect(result.includes('### Active environment')).toBe(project || groups)+ })++ it('carries the CLI mechanics', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecCommandReference(fullCtx)+ expect(result).toContain('SCHEMA DRILL-DOWN RULE')+ expect(result).not.toContain('### PostHog knowledge sources')+ expect(result).toContain('### Basic functionality')+ expect(result).toContain('### Examples')})it('does not include the exec-tool blurb (that lives on the tool description)', () => {const formatter = new InstructionsFormatter()- const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })+ const result = formatter.buildExecCommandReference(fullCtx)expect(result).not.toContain('Using the `posthog` tool')})- it('embeds env-context and query-tool catalog when stripEnvContext is false', () => {+ it('embeds the env-context pointer and query-tool catalog', () => {const formatter = new InstructionsFormatter()- const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })- expect(result).toContain("The user's name is Jane Doe")- expect(result).toContain('Defined group types: organization')+ const result = formatter.buildExecCommandReference(fullCtx)+ expect(result).toContain(ENV_POINTER)// Tool domains are temporarily omitted from the command reference while// probing claude.ai's per-tool size cap; discovery rides on `search`.expect(result).not.toContain('dashboard|execute-sql')expect(result).toContain('- `query-trends` — time series')})- it('strips env-context and tool-domain list but keeps the query-tool catalog when stripEnvContext is true', () => {- const formatter = new InstructionsFormatter()- const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: true })- expect(result).not.toContain("The user's name is Jane Doe")- expect(result).not.toContain('Defined group types: organization')- // The query catalog stays on the exec command reference even when env is stripped.- expect(result).toContain('- `query-trends` — time series')- expect(result).not.toContain('dashboard|execute-sql')- })-- it('keeps the env-context even when stripEnvContext is set, when keepEnvContext is set', () => {- const formatter = new InstructionsFormatter()- const result = formatter.buildExecCommandReference(fullCtx, {- stripEnvContext: true,- keepEnvContext: true,- })- // Project metadata and group types survive for clients (Claude- // web/desktop) that ignore the `instructions` payload, so they still- // reach the model via the command reference. Tool domains are- // temporarily omitted (size-cap probe).- expect(result).not.toContain('dashboard|execute-sql')- expect(result).toContain("The user's name is Jane Doe")- expect(result).toContain('Defined group types: organization')- })-it('always includes the agent-feedback section', () => {const formatter = new InstructionsFormatter()- for (const stripEnvContext of [true, false]) {- const withFeedback = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })- expect(withFeedback).toContain('### Sharing feedback on PostHog')- }+ const withFeedback = formatter.buildExecCommandReference(fullCtx)+ expect(withFeedback).toContain('### Sharing feedback on PostHog')})it('includes the rendering section only when render-ui is available for the client', () => {const formatter = new InstructionsFormatter()- for (const stripEnvContext of [true, false]) {- const withRendering = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })- expect(withRendering).toContain('### Rendering visualizations')+ const withRendering = formatter.buildExecCommandReference(fullCtx)+ expect(withRendering).toContain('### Rendering visualizations')- // The raw flag being on isn't enough — a non-UI-host client (e.g. Claude Code)- // resolves `renderUiEnabled` to false and must not see the rendering section.- const withoutRendering = formatter.buildExecCommandReference(- { ...fullCtx, renderUiEnabled: false },- { stripEnvContext }- )- expect(withoutRendering).not.toContain('### Rendering visualizations')- }+ // The raw flag being on isn't enough — a non-UI-host client (e.g. Claude Code)+ // resolves `renderUiEnabled` to false and must not see the rendering section.+ const withoutRendering = formatter.buildExecCommandReference({ ...fullCtx, renderUiEnabled: false })+ expect(withoutRendering).not.toContain('### Rendering visualizations')})})@@ -353,15 +313,14 @@ describe('InstructionsFormatter', () => {expect(result).toContain('### Basic functionality')expect(result).toContain('### Tool search')expect(result).toContain(buildToolDomainsCompact(realisticTools))- expect(result).toContain("The user's name is Jane Doe")- expect(result).toContain('Defined group types: organization')+ expect(result).toContain(ENV_POINTER)expect(result).not.toContain('### Retrieving data')expect(result).not.toContain('### Examples')expect(result).not.toContain('### Rendering visualizations')expect(result).not.toContain('### URL patterns')expect(result).not.toContain('### Sharing feedback on PostHog')expect(result).not.toContain('- `query-trends` — time series')- expect(result).not.toMatch(/\{help_topics\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/)+ expect(result).not.toMatch(/\{help_topics\}|\{query_tools\}|\{guidelines\}/)})it('advertises skill syntax inside the schema budget only when skills are enabled', () => {@@ -390,8 +349,8 @@ describe('InstructionsFormatter', () => {it('adds the full skills-first routing to the uncapped reference only when enabled', () => {const formatter = new InstructionsFormatter()- const off = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })- const on = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false, learnEnabled: true })+ const off = formatter.buildExecCommandReference(fullCtx)+ const on = formatter.buildExecCommandReference(fullCtx, { learnEnabled: true })expect(off).not.toContain('SKILLS FIRST')expect(on).toContain('**SKILLS FIRST: HARD REQUIREMENT**')@@ -484,7 +443,7 @@ describe('InstructionsFormatter', () => {},{name: 'buildExecCommandReference',- render: (formatter, ctx) => formatter.buildExecCommandReference(ctx, { stripEnvContext: false }),+ render: (formatter, ctx) => formatter.buildExecCommandReference(ctx),mustPrecede: ['SCHEMA DRILL-DOWN RULE', '### Retrieving data'],},]@@ -527,7 +486,7 @@ describe('InstructionsFormatter', () => {},{name: 'buildExecCommandReference',- render: (formatter, ctx) => formatter.buildExecCommandReference(ctx, { stripEnvContext: false }),+ render: (formatter, ctx) => formatter.buildExecCommandReference(ctx),},]@@ -566,10 +525,7 @@ describe('InstructionsFormatter', () => {])('$name: splits product context between instructions and commandReference', ({ supportsInstructions }) => {const formatter = new InstructionsFormatter()const instructions = supportsInstructions ? formatter.buildExecInstructions(fullCtx) : ''- const commandReference = formatter.buildExecCommandReference(fullCtx, {- stripEnvContext: supportsInstructions,- keepEnvContext: true,- })+ const commandReference = formatter.buildExecCommandReference(fullCtx)expect(commandReference).toContain('SCHEMA DRILL-DOWN RULE')expect(commandReference).toContain('### Basic functionality')@@ -579,20 +535,17 @@ describe('InstructionsFormatter', () => {if (supportsInstructions) {// queries surface in instructions only as the `query` tool domainexpect(instructions).toContain(- 'business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|query'+ 'business-knowledge-documents|dashboard|docs-search|execute-sql|feature-flag|project|query')expect(instructions).not.toContain('- `query-trends` — time series')- expect(instructions).not.toContain("The user's name is Jane Doe")- expect(instructions).not.toContain('Defined group types: organization')- expect(commandReference).toContain("The user's name is Jane Doe")- expect(commandReference).toContain('Defined group types: organization')+ expect(instructions).not.toContain(ENV_POINTER)+ expect(commandReference).toContain(ENV_POINTER)expect(commandReference).not.toContain('dashboard|execute-sql')} else {expect(instructions).toBe('')expect(commandReference).toContain('- `query-trends` — time series')- expect(commandReference).toContain("The user's name is Jane Doe")+ expect(commandReference).toContain(ENV_POINTER)expect(commandReference).not.toContain('dashboard|execute-sql')- expect(commandReference).toContain('Defined group types: organization')}})})diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex f9afebc83054..5323eadab697 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -1,47 +1,14 @@import { describe, expect, it } from 'vitest'-import type { GroupType } from '@/api/client'import {buildActiveEnvironmentContextPrompt,- buildDefinedGroupsBlock,buildQueryToolsBlock,buildToolDomainsBlock,buildToolDomainsCompact,QueryToolCatalog,type QueryToolInfo,} from '@/lib/instructions'-import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'--describe('buildDefinedGroupsBlock', () => {- it('should format group types as a comma-separated list of group_type names', () => {- const groupTypes: GroupType[] = [- {- group_type: 'organization',- group_type_index: 0,- name_singular: 'Organization',- name_plural: 'Organizations',- },- { group_type: 'instance', group_type_index: 1, name_singular: 'Instance', name_plural: 'Instances' },- { group_type: 'business', group_type_index: 2, name_singular: null, name_plural: null },- ]- expect(buildDefinedGroupsBlock(groupTypes)).toBe('Defined group types: organization, instance, business')- })-- it('should ignore singular/plural names and only use group_type', () => {- const groupTypes: GroupType[] = [- { group_type: 'workspace', group_type_index: 0, name_singular: 'Workspace', name_plural: 'Workspaces' },- ]- expect(buildDefinedGroupsBlock(groupTypes)).toBe('Defined group types: workspace')- })-- it('should return empty string for undefined', () => {- expect(buildDefinedGroupsBlock(undefined)).toBe('')- })-- it('should return empty string for empty array', () => {- expect(buildDefinedGroupsBlock([])).toBe('')- })-})+import type { CachedOrg, CachedProject } from '@/tools/types'describe('buildToolDomainsBlock', () => {it('should extract CRUD domains from tool names grouped by category', () => {@@ -312,21 +279,15 @@ describe('buildActiveEnvironmentContextPrompt', () => {api_token: 'token_1',person_on_events_querying_enabled: false,} satisfies Partial<CachedProject> as unknown as CachedProject- const user = {- first_name: 'Jane',- last_name: 'Doe',- email: '[email protected]',- } satisfies Partial<CachedUser> as unknown as CachedUser-it('renders the full project + org line when both are present', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, project)+ const result = buildActiveEnvironmentContextPrompt(org, project)expect(result).toContain('You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).')})it('never leaks the project API token into the environment prompt', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, project)+ const result = buildActiveEnvironmentContextPrompt(org, project)expect(result).not.toContain('token_1')})@@ -334,21 +295,21 @@ describe('buildActiveEnvironmentContextPrompt', () => {// Project-scoped personal API keys lack `organization:read`, so the org// fetch is skipped. The line drops the "within organization …" tail// rather than rendering a fabricated "Unknown" placeholder.- const result = buildActiveEnvironmentContextPrompt(user, undefined, project)+ const result = buildActiveEnvironmentContextPrompt(undefined, project)expect(result).toContain('You are currently in project "My App" (id: 1).')expect(result).not.toContain('within organization')expect(result).not.toContain('Unknown')expect(result).not.toContain('unknown')})- it('keeps the timezone and user lines when org is omitted', () => {- const result = buildActiveEnvironmentContextPrompt(user, undefined, project)- expect(result).toContain('Project timezone: America/New_York.')- expect(result).toContain("The user's name is Jane Doe ([email protected]).")+ it('points to project-get for project settings instead of inlining them', () => {+ const result = buildActiveEnvironmentContextPrompt(org, project)+ expect(result).toContain('call `project-get` without an ID')+ expect(result).not.toContain('America/New_York')})it('renders a single base URL line (scheme stripped, project segment appended) when a base URL is given', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, project, 'https://us.posthog.com')+ const result = buildActiveEnvironmentContextPrompt(org, project, 'https://us.posthog.com')expect(result).toContain('Base URL: us.posthog.com — add /project/1 for project-scoped paths.')// Sits right after the project/org context line.const lines = (result ?? '').split('\n')@@ -358,18 +319,18 @@ describe('buildActiveEnvironmentContextPrompt', () => {})it('renders the base URL without a project segment when no project is active', () => {- const result = buildActiveEnvironmentContextPrompt(user, undefined, undefined, 'https://us.posthog.com')+ const result = buildActiveEnvironmentContextPrompt(org, undefined, 'https://us.posthog.com')expect(result).toContain('Base URL: us.posthog.com.')expect(result).not.toContain('/project/')})it('omits the base URL line when no base URL is given', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, project)+ const result = buildActiveEnvironmentContextPrompt(org, project)expect(result).not.toContain('Base URL:')})it('returns undefined when no context is available at all', () => {- expect(buildActiveEnvironmentContextPrompt(undefined, undefined, undefined)).toBeUndefined()+ expect(buildActiveEnvironmentContextPrompt(undefined, undefined)).toBeUndefined()})it.each([@@ -377,7 +338,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {['unchecked', false, false],['unset', undefined, false],])('surfaces the test account filter default only when %s', (_name, testAccountFiltersDefaultChecked, expected) => {- const result = buildActiveEnvironmentContextPrompt(user, org, {+ const result = buildActiveEnvironmentContextPrompt(org, {...project,test_account_filters_default_checked: testAccountFiltersDefaultChecked,} as CachedProject)@@ -386,14 +347,14 @@ describe('buildActiveEnvironmentContextPrompt', () => {it('still renders an "Unknown" project when org is present but project is missing', () => {// The org branch is unchanged — only the no-org branch was added.- const result = buildActiveEnvironmentContextPrompt(user, org, undefined)+ const result = buildActiveEnvironmentContextPrompt(org, undefined)expect(result).toContain('You are currently in project "Unknown" (id: unknown) within organization "Acme" (id: org_1).')})it('buckets flag-backed products strictly, so only an explicit true counts as enabled', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, {+ const result = buildActiveEnvironmentContextPrompt(org, {...project,session_recording_opt_in: true,autocapture_exceptions_opt_in: false,@@ -405,7 +366,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {})it('lists only onboarding-completed product intents, with underscores humanized', () => {- const result = buildActiveEnvironmentContextPrompt(user, org, {+ const result = buildActiveEnvironmentContextPrompt(org, {...project,product_intents: [{ product_type: 'feature_flags', onboarding_completed_at: '2026-01-01T00:00:00Z' },@@ -421,7 +382,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {product_type: `product_${String(i).padStart(2, '0')}`,onboarding_completed_at: '2026-01-01T00:00:00Z',}))- const result = buildActiveEnvironmentContextPrompt(user, org, {+ const result = buildActiveEnvironmentContextPrompt(org, {...project,product_intents: intents,} as CachedProject)@@ -434,7 +395,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {['an empty list', [], 'Integrations connected: none.'],['a duplicated unsorted list', ['slack', 'github', 'github'], 'Integrations connected: github, slack.'],])('renders the integrations line for %s', (_name, kinds, expectedLine) => {- const result = buildActiveEnvironmentContextPrompt(user, org, project, undefined, {+ const result = buildActiveEnvironmentContextPrompt(org, project, undefined, {integrationKinds: kinds,})if (expectedLine) {@@ -444,22 +405,4 @@ describe('buildActiveEnvironmentContextPrompt', () => {expect(result).not.toContain('Integrations connected')}})-- it('omits all product and integration lines when includeProductContext is false', () => {- // The claude.ai exec command reference sits within tens of characters of the- // registry's inputSchema cap; the compact variant must add nothing to it.- const result = buildActiveEnvironmentContextPrompt(- user,- org,- {- ...project,- session_recording_opt_in: true,- product_intents: [{ product_type: 'feature_flags', onboarding_completed_at: '2026-01-01T00:00:00Z' }],- } as CachedProject,- undefined,- { integrationKinds: ['github'], includeProductContext: false }- )- expect(result).not.toContain('Products')- expect(result).not.toContain('Integrations connected')- })})