: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): fit the CLI-mode instructions payload in its 2048-char cap (#79414)
Georgiy Tarasov38a3c0ecde8b
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex dbe173f8bb46..53e31cc94a58 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -108,18 +108,21 @@ export class InstructionsBuilder {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 chat hosts only — Cowork surfaces instructions- // normally and gets env-context through them. (Codex, which reports- // `supportsInstructions: false`, already gets the full env-context via the+ // 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.)- const keepEnvContext = state.clientProfile.isClaudeChatHost()const ctx = this.buildContext(state)- if (keepEnvContext) {+ if (state.clientProfile.isClaudeChatHost()) {return this.formatter.buildClaudeExecCommandReference(ctx)}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,})}diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.tsindex 7af242779599..fb7181365ee4 100644--- a/services/mcp/src/lib/constants.ts+++ b/services/mcp/src/lib/constants.ts@@ -23,6 +23,11 @@ export const MCP_SERVER_NAME = 'PostHog'export const MCP_SERVER_VERSION = '1.0.0'export const MCP_ANALYTICS_SOURCE = 'posthog_mcp_analytics'+// Claude Code truncates a server's `instructions` payload at this many characters — silently,+// mid-token, with nothing the model can act on. The compact single-exec payload is sized to+// fit, and the tool-domain index absorbs whatever budget the fixed sections leave.+export const MCP_INSTRUCTIONS_CHAR_BUDGET = 2048+// Gates the semantic layer (governed-metrics catalog) — no tool declares it, so it must be// joined into the evaluated flag set explicitly; instructions content branches on it.export const PRODUCT_DATA_CATALOG_FLAG = 'product-data-catalog'diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex da173f766971..d9b28ea05274 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -1,5 +1,7 @@import type { GroupType } from '@/api/client'+import { MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'import {+ buildAvailableToolsBlock,buildDefinedGroupsBlock,buildQueryToolsBlock,buildToolDomainsBlock,@@ -75,11 +77,30 @@ export class InstructionsFormatter {)}- /** Build the compact `instructions` payload for single-exec clients (~2KB budget).- * The bulk of the system prompt lives on the exec tool's `command` parameter- * description (`buildExecCommandReference`) — this is just env + tool index. */+ /** Build the compact `instructions` payload for single-exec clients. Everything+ * but the tool-domain index — env context included — 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.+ *+ * Rendered optimistically, then re-rendered against the measured overflow if it+ * doesn't fit — the index is the only part that can shrink. Measuring the overflow+ * rather than the surround keeps the arithmetic exact: both renders carry a+ * non-empty index, so they share a byte-identical surround, and shrinking the index+ * by N shrinks the payload by exactly N. (Sizing an index-less render instead+ * overshoots, because `formatPrompt` trims the trailing separator the real payload+ * keeps.) Enforced by the budget test in `instructions-formatter-snapshot.test.ts`. */buildExecInstructions(ctx: InstructionsContext): string {- return this.compose([COMPACT_INSTRUCTIONS], ctx, { compact: true })+ const rendered = this.compose([COMPACT_INSTRUCTIONS], ctx, { compact: true })+ const overflow = rendered.length - MCP_INSTRUCTIONS_CHAR_BUDGET+ if (overflow <= 0) {+ return rendered+ }+ const domains = buildToolDomainsCompact(ctx.tools ?? [])+ return this.compose([COMPACT_INSTRUCTIONS], ctx, {+ compact: true,+ toolDomainsMaxChars: domains.length - overflow,+ })}/** Build the top-level description of the `posthog:exec` tool. */@@ -231,15 +252,24 @@ export class InstructionsFormatter {private compose(sections: string[],ctx: InstructionsContext,- opts: { compact: boolean; compactToolDomains?: boolean; extraCommands?: string }+ opts: {+ compact: boolean+ compactToolDomains?: boolean+ extraCommands?: string+ /** Character budget for the domain index; it collapses sub-families to fit. */+ toolDomainsMaxChars?: number+ }): string {const renderToolDomains =- opts.compact || opts.compactToolDomains ? buildToolDomainsCompact : buildToolDomainsBlock+ opts.compact || opts.compactToolDomains+ ? (tools: ToolInfo[]) => buildToolDomainsCompact(tools, opts.toolDomainsMaxChars)+ : buildToolDomainsBlock// `{query_tools}` only appears in non-compact sections (the exec command// reference and tools-mode instructions); compact mode surfaces queries// via the single `query` tool domain instead.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) : '',diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex 1c746442ae38..3eb5520d9656 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -63,7 +63,25 @@ export function buildActiveEnvironmentContextPrompt(const fullName = [user.first_name, user.last_name].filter(Boolean).join(' ') || 'Unknown'lines.push(`The user's name is ${fullName} (${user.email}).`)}- return `### Active environment\n\nAll tool calls and queries default to this environment; you can switch projects or organizations at any time.\n\n${lines.join('\n')}`+ // 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 to+ // restate that.+ return `### Active environment\n\n${lines.join('\n')}`+}++/**+ * The tools the MCP actually advertises in single-exec mode. Without this the domain+ * index is the only list in the payload, and it names PostHog resources rather than+ * callable tools — so a model that reads `scout|survey|…` as the tool list has no+ * callable name to reach for. `render-ui` is listed only where it is mounted.+ */+export function buildAvailableToolsBlock(renderUiEnabled?: boolean): string {+ const lines = ['exec – run any PostHog command; its `command` description has the syntax.']+ if (renderUiEnabled) {+ lines.push('render-ui – show a tool result as an interactive app.')+ }+ return lines.join('\n')}export interface ToolInfo {@@ -99,7 +117,11 @@ interface ToolItem {export class ToolDomainExtractor {/** A family at or below this many tools stays one domain; above it, split* into sub-family roots. ~25 keeps flat CRUD families (e.g. experiment) whole- * while breaking up large multi-family areas (e.g. AI observability). */+ * while breaking up large multi-family areas (e.g. AI observability).+ *+ * This is the preferred split, not a hard one: {@link toCompact} raises the+ * threshold when the rendered index has to fit a character budget, trading+ * sub-family precision for keeping every family represented. */private static readonly MAX_FAMILY_SIZE = 25/** Cap on rendered segments so a singleton/leaf family becomes a short* domain (`activity-log`) rather than its full tool name. */@@ -147,7 +169,7 @@ export class ToolDomainExtractor {})}- getDomains(): string[] {+ getDomains(maxFamilySize: number = ToolDomainExtractor.MAX_FAMILY_SIZE): string[] {const byRoot = new Map<string, ToolItem[]>()for (const item of this.items) {const root = item.key[0]@@ -163,7 +185,7 @@ export class ToolDomainExtractor {}const domains = new Set<string>()for (const bucket of byRoot.values()) {- this.cut(bucket, 1, domains)+ this.cut(bucket, 1, domains, maxFamilySize)}if (this.hasQueryTools) {domains.add('query')@@ -177,23 +199,47 @@ export class ToolDomainExtractor {.join('\n')}- toCompact(): string {- return this.getDomains().join('|')+ /**+ * Render the index as a single pipe-delimited line, collapsing sub-families+ * until it fits `maxChars`.+ *+ * The index is a routing hint — every domain is a literal tool-name prefix+ * that `search` expands — so `scout` costs 120 fewer characters than its ten+ * `scout-*` roots and still reaches the same tools. Dropping precision is+ * therefore much cheaper than dropping domains, which is what a client-side+ * truncation does: the list is alphabetical, so an overrun silently deletes+ * the tail (every `scout`, `survey`, `workflows`, `web-analytics` domain)+ * while the model has no way to know they exist.+ *+ * Raising the family-size threshold only ever merges families, so the+ * rendered length decreases monotonically and doubling converges quickly.+ * The floor is one domain per root; if even that overruns, the caller gets+ * the too-long string rather than a silently trimmed one.+ */+ toCompact(maxChars?: number): string {+ let maxFamilySize = ToolDomainExtractor.MAX_FAMILY_SIZE+ for (;;) {+ const rendered = this.getDomains(maxFamilySize).join('|')+ if (maxChars === undefined || rendered.length <= maxChars || maxFamilySize >= this.items.length) {+ return rendered+ }+ maxFamilySize *= 2+ }}/** Reduce a group sharing a `depth`-segment prefix to one or more domains,* splitting only when the group is too large to scan in one search. */- private cut(group: ToolItem[], depth: number, out: Set<string>): void {+ private cut(group: ToolItem[], depth: number, out: Set<string>, maxFamilySize: number): void {depth = this.compressUnary(group, depth)- if (group.length <= ToolDomainExtractor.MAX_FAMILY_SIZE) {+ if (group.length <= maxFamilySize) {out.add(this.render(group, depth))return}for (const [childKey, childGroup] of this.childrenBySegment(group, depth)) {- if (childKey === null || childGroup.length <= ToolDomainExtractor.MAX_FAMILY_SIZE) {+ if (childKey === null || childGroup.length <= maxFamilySize) {out.add(this.render(childGroup, depth + 1))} else {- this.cut(childGroup, depth + 1, out)+ this.cut(childGroup, depth + 1, out, maxFamilySize)}}}@@ -268,8 +314,8 @@ export function buildToolDomainsBlock(tools: ToolInfo[]): string {return new ToolDomainExtractor(tools).toMarkdown()}-export function buildToolDomainsCompact(tools: ToolInfo[]): string {- return new ToolDomainExtractor(tools).toCompact()+export function buildToolDomainsCompact(tools: ToolInfo[], maxChars?: number): string {+ return new ToolDomainExtractor(tools).toCompact(maxChars)}export interface QueryToolInfo {diff --git a/services/mcp/src/templates/sections/compact-instructions.md b/services/mcp/src/templates/sections/compact-instructions.mdindex 7a32a20c75f3..80f3196503d4 100644--- a/services/mcp/src/templates/sections/compact-instructions.md+++ b/services/mcp/src/templates/sections/compact-instructions.md@@ -1,7 +1,9 @@-Below are tools available in the MCP. Prioritize skills over tools.-{metadata}-{defined_groups}--# Tool domains+# PostHog `exec` covers{tool_domains}++# Tools++{available_tools}++Prioritize skills over tools.diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 4e7e347c9ac1..247ae4c607f0 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -187,33 +187,32 @@ 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 and Cowork strip- // it here because it arrives via `instructions` instead.+ // 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+ // out of the command description except for Claude web/desktop, which ignores+ // `instructions` and has nowhere else to receive it.it.each([{label: 'Claude web/desktop (ignores instructions)',supportsInstructions: true,isClaudeChatHost: true,- expectEnv: true,},{label: 'Codex (supportsInstructions: false)',supportsInstructions: false,isClaudeChatHost: false,- expectEnv: true,},{label: 'Claude Code / Cowork (consume instructions)',supportsInstructions: true,isClaudeChatHost: false,- expectEnv: false,},])(- 'injects project metadata into the exec command for $label → $expectEnv',- async ({ supportsInstructions, isClaudeChatHost, expectEnv }) => {+ 'injects project metadata into the exec command for $label',+ async ({ supportsInstructions, isClaudeChatHost }) => {const tools = catalog.getPreBuiltEntries().slice(0, 5)@@ -243,11 +242,7 @@ describe('ToolExecutor', () => {expect(commandDesc.includes('- analytics:')).toBe(isClaudeChatHost)expect(commandDesc.includes('### Retrieving data')).toBe(!isClaudeChatHost)expect(commandDesc.includes(compactDomains)).toBe(isClaudeChatHost)- if (expectEnv) {- expect(commandDesc).toContain(metadataMarker)- } else {- expect(commandDesc).not.toContain(metadataMarker)- }+ expect(commandDesc).toContain(metadataMarker)})diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txtindex 6ed995a7a334..65ce7cca456a 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt@@ -1,9 +1,10 @@-Below are tools available in the MCP. Prioritize skills over tools.-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]).-Defined group types: organization, project+# PostHog `exec` covers-# Tool domains+dashboard|execute-sql|feature-flag|query-dashboard|execute-sql|feature-flag|query\ No newline at end of file+# Tools++exec – run any PostHog command; its `command` description has the syntax.+render-ui – show a tool result as an interactive app.++Prioritize skills over tools.\ No newline at end of filediff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex 92f98578f0d3..e067c3492e3e 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -8,10 +8,10 @@ import type { GroupType } from '@/api/client'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { MCPClientProfile } from '@/lib/client-detection'-import { PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'-import { buildActiveEnvironmentContextPrompt, type QueryToolInfo } from '@/lib/instructions'+import { MCP_INSTRUCTIONS_CHAR_BUDGET, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'+import { buildActiveEnvironmentContextPrompt, buildToolDomainsCompact, type QueryToolInfo } from '@/lib/instructions'import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'-import { getToolDefinitions } from '@/tools/toolDefinitions'+import { getToolCategory, getToolDefinitions } from '@/tools/toolDefinitions'import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'// Static, deterministic context shared by all snapshots — mirrors the realistic@@ -52,6 +52,13 @@ const STATIC_CTX: InstructionsContext = {renderUiEnabled: true,}+/** The domain index is the only pipe-delimited line in the compact payload. */+const domainsIn = (payload: string): string[] =>+ payload+ .split('\n')+ .find((line) => line.includes('|'))+ ?.split('|') ?? []+const __dirname = path.dirname(fileURLToPath(import.meta.url))const SNAPSHOT_DIR = path.resolve(__dirname, '__snapshots__', 'instructions')@@ -201,4 +208,60 @@ describe('InstructionsFormatter prompt snapshots', () => {expect(properties).toHaveProperty('context')expect(inputSchemaSize).toBeLessThan(16_384)})++ // ------------------------------------------------------------------------------------------------+ // DO NOT weaken or delete this test. Claude Code truncates a server's `instructions`+ // payload at MCP_INSTRUCTIONS_CHAR_BUDGET chars, silently and mid-token. The payload+ // is a single alphabetical tool-domain index, so an overrun does not degrade evenly —+ // it deletes the tail. Measured 2026-08-07 before this budget existed: 2,923 chars+ // rendered, 148 domains, of which the 67 from `marketing-analytics` down never+ // reached the model, including every `scout-*`, `survey`, `session-recording`,+ // `web-analytics`, `workflows-*` and `vision-*` domain. Agents concluded those+ // products had no tools and reached for their own built-ins instead.+ //+ // If this fails, do NOT trim the domain index by hand — `toCompact` already collapses+ // sub-families to fit. It means a fixed section grew; move it to the exec command+ // 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',+ })),+ }+ const rendered = new InstructionsFormatter().buildExecInstructions(ctx)+ const domains = domainsIn(rendered)++ expect(rendered.length).toBeLessThanOrEqual(MCP_INSTRUCTIONS_CHAR_BUDGET)+ // Domains past the old cutoff point, i.e. the ones a truncated payload lost.+ // (`workflow` singular: the extractor renders a family's shortest spelling.)+ for (const domain of ['query', 'scout', 'session-recording', 'survey', 'web-analytics', 'workflow']) {+ expect(domains).toContain(domain)+ }+ })++ // Exercises the re-render branch, which the live catalog no longer reaches now that it+ // fits on the first pass. 40 families of 30 tools each split into long sub-family roots+ // that blow the cap unbudgeted, and collapse to 40 short roots that clear it.+ it('collapses an over-budget domain index until the payload fits', () => {+ const tools = Array.from({ length: 40 }, (_, family) =>+ Array.from({ length: 30 }, (_, i) => ({+ name: `family${family}-subfamily${i % 5}-verylongtoolname${i}`,+ category: 'Other',+ }))+ ).flat()+ const formatter = new InstructionsFormatter()++ expect(buildToolDomainsCompact(tools).length).toBeGreaterThan(MCP_INSTRUCTIONS_CHAR_BUDGET)++ const rendered = formatter.buildExecInstructions({ guidelines: '', tools })+ expect(rendered.length).toBeLessThanOrEqual(MCP_INSTRUCTIONS_CHAR_BUDGET)+ expect(domainsIn(rendered)).toHaveLength(40)+ })})diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 48cf24c061e1..d6edeabbe4b0 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -1,6 +1,7 @@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'@@ -97,17 +98,21 @@ describe('InstructionsFormatter', () => {// query-* tools surface as the single `query` domain, not a separate catalog lineexpect(result).toContain('dashboard|execute-sql|feature-flag|query')expect(result).not.toContain('query-*:')- expect(result).toContain('Defined group types: organization')- expect(result).toContain("The user's name is Jane Doe")+ // 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\}/)})- // Claude Code caps MCP `instructions` at 2048 chars — stay under the budget with- // a realistic-ish tool count so this asserts something meaningful. 60 domains +- // 12 query tools ≈ today's v2 deployment.- it('stays under the 2048-character budget at realistic tool counts', () => {+ // Synthetic fixture: 60 uniform `domain-N-get` names collapse to short domains and+ // cost ~1/3 of what the live catalog does, which is how a 2,923-char payload shipped+ // past a passing 2048 assertion. Kept for the placeholder wiring it exercises; the+ // assertion that actually guards the cap runs the real catalog, in+ // `instructions-formatter-snapshot.test.ts`.+ it('stays under the character budget at synthetic tool counts', () => {const manyTools = Array.from({ length: 60 }, (_, i) => ({name: `domain-${i}-get`,category: `Category ${i % 6}`,@@ -125,7 +130,21 @@ describe('InstructionsFormatter', () => {tools: manyTools,queryTools: manyQueryTools,})- expect(result.length).toBeLessThanOrEqual(2048)+ expect(result.length).toBeLessThanOrEqual(MCP_INSTRUCTIONS_CHAR_BUDGET)+ })++ // The domain index names PostHog resources, not callable tools, so without this+ // line the payload never states what can actually be called. `render-ui` is only+ // mounted on MCP Apps hosts — naming it elsewhere advertises a tool that isn't there.+ it('names the callable tools, gating render-ui on the host mounting it', () => {+ const formatter = new InstructionsFormatter()+ const withUi = formatter.buildExecInstructions({ ...fullCtx, renderUiEnabled: true })+ const withoutUi = formatter.buildExecInstructions({ ...fullCtx, renderUiEnabled: false })++ expect(withUi).toContain('exec – run any PostHog command')+ expect(withUi).toContain('render-ui – show a tool result as an interactive app.')+ expect(withoutUi).toContain('exec – run any PostHog command')+ expect(withoutUi).not.toContain('render-ui')})it('does not bleed the full command reference into the compact instructions', () => {@@ -360,11 +379,11 @@ describe('InstructionsFormatter', () => {})// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP- // `instructions` field, env-context moves out of the `command` description and into- // `instructions`: tool domains (including the `query` domain), user preferences- // (timezone/name via `{metadata}`), and defined group types. The query-tool catalog- // stays on the `command` description. Codex (no `instructions` support) keeps today's- // behavior: empty `instructions`, everything inlined in the `command` description.+ // `instructions` field, that payload carries exactly one thing — the tool-domain index+ // (including the `query` domain) — because clients hard-truncate it. Everything else,+ // env-context and the query-tool catalog included, stays on the `command` description,+ // which has no cap. Codex (no `instructions` support) keeps today's behavior: empty+ // `instructions`, everything inlined in the `command` description.describe('exec mode wiring', () => {it.each([{ name: 'supportsInstructions=true (Claude Code etc.)', supportsInstructions: true },@@ -374,6 +393,7 @@ describe('InstructionsFormatter', () => {const instructions = supportsInstructions ? formatter.buildExecInstructions(fullCtx) : ''const commandReference = formatter.buildExecCommandReference(fullCtx, {stripEnvContext: supportsInstructions,+ keepEnvContext: true,})expect(commandReference).toContain('SCHEMA DRILL-DOWN RULE')@@ -385,10 +405,10 @@ describe('InstructionsFormatter', () => {// queries surface in instructions only as the `query` tool domainexpect(instructions).toContain('dashboard|execute-sql|feature-flag|query')expect(instructions).not.toContain('- `query-trends` — time series')- expect(instructions).toContain("The user's name is Jane Doe")- expect(instructions).toContain('Defined group types: organization')- expect(commandReference).not.toContain("The user's name is Jane Doe")- expect(commandReference).not.toContain('Defined group types: organization')+ 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(commandReference).not.toContain('dashboard|execute-sql')} else {expect(instructions).toBe('')diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex 1f94bfa2d980..78904bebd21d 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -171,6 +171,36 @@ describe('buildToolDomainsCompact', () => {it('returns an empty string for an empty array', () => {expect(buildToolDomainsCompact([])).toBe('')})++ // A tight budget must cost sub-family precision, never whole families: the caller+ // renders this into a payload a client will hard-truncate, and a family that isn't+ // named at all is a product the agent believes has no tools.+ it('collapses sub-families to fit a character budget instead of dropping domains', () => {+ // 30 scout-* tools across 3 sub-families exceeds MAX_FAMILY_SIZE (25), so the+ // unbudgeted render splits them; `survey` is the family that a truncation would+ // take off the end.+ const tools = [+ ...Array.from({ length: 10 }, (_, i) => ({ name: `scout-config-${i}`, category: 'Signals' })),+ ...Array.from({ length: 10 }, (_, i) => ({ name: `scout-notes-${i}`, category: 'Signals' })),+ ...Array.from({ length: 10 }, (_, i) => ({ name: `scout-record-${i}`, category: 'Signals' })),+ { name: 'survey-create', category: 'Surveys' },+ ]+ expect(buildToolDomainsCompact(tools)).toBe('scout-config|scout-notes|scout-record|survey')++ const budgeted = buildToolDomainsCompact(tools, 20)+ expect(budgeted).toBe('scout|survey')+ expect(budgeted.length).toBeLessThanOrEqual(20)+ })++ // The floor is one domain per root. Returning an over-budget string is deliberate:+ // the budget test that calls this must fail loudly rather than see a silent trim.+ it('returns the fully collapsed index when even that exceeds the budget', () => {+ const tools = [+ { name: 'experiment-create', category: 'Experiments' },+ { name: 'survey-create', category: 'Surveys' },+ ]+ expect(buildToolDomainsCompact(tools, 5)).toBe('experiment|survey')+ })})describe('QueryToolCatalog', () => {