diff --git a/.agents/skills/tracking/SKILL.md b/.agents/skills/tracking/SKILL.md index 06ec047462e..ba95990b92e 100644 --- a/.agents/skills/tracking/SKILL.md +++ b/.agents/skills/tracking/SKILL.md @@ -350,7 +350,8 @@ Shared properties: `$mcp_source` (`http` / `stdio`), `$mcp_server_name`, `$mcp_client_user_agent`, `$mcp_vendor_client`, `$mcp_protocol_version`. Per event: `$mcp_tool_name`, `$mcp_tool_description`, `$mcp_tool_category` (`read` / `write`), `$mcp_listed_tool_names`, `$mcp_duration_ms`, -`$mcp_is_error`, `$mcp_error_type`, `$mcp_error_message`, `$mcp_resource_name`, +`$mcp_response_text_chars`, `$mcp_response_structured_chars`, `$mcp_is_error`, +`$mcp_error_type`, `$mcp_error_message`, `$mcp_resource_name`, `$mcp_resource_uri`. - **A client's own name is only on the wire at `initialize`.** The mount is @@ -364,6 +365,15 @@ event: `$mcp_tool_name`, `$mcp_tool_description`, `$mcp_tool_category` where it returns rather than having it guessed back out of the response text. - **Payloads stay out.** `$mcp_response` is never emitted. `$mcp_parameters` is off by default and redacted when on — tool arguments carry user content. +- **A result's size goes in, counted per part.** `$mcp_response_text_chars` + counts the characters in the result's text blocks, and + `$mcp_response_structured_chars` the structured content as JSON (absent when + the result has none). Hosts cut or move a result past about 40,000 + characters, and they read different parts: Claude Code and OpenCode show the + model only the structured content when there is one, Codex shows both. The + handler measures the result only when MCP analytics are on + (`mcpAnalyticsEnabled()`), and passes only the two numbers, so no part of + the payload reaches `trackMcpToolCall`. Off switches: `MCP_ANALYTICS=false` (`observability.mcpEvents`) disables the events; `MCP_ANALYTICS_PARAMETERS=true` (`observability.mcpCaptureParameters`) diff --git a/.changeset/mcp-tool-call-result-size.md b/.changeset/mcp-tool-call-result-size.md new file mode 100644 index 00000000000..7ba6d077ac5 --- /dev/null +++ b/.changeset/mcp-tool-call-result-size.md @@ -0,0 +1,5 @@ +--- +"@agent-native/core": patch +--- + +`$mcp_tool_call` now records how big each result is: `$mcp_response_text_chars` counts the characters in its text blocks, and `$mcp_response_structured_chars` its structured content as JSON, when it has any. MCP hosts cut or move a result past about 40,000 characters, and Claude Code and OpenCode show the model only the structured content while Codex shows both, so the two are counted apart. Only the numbers are sent; the result's text stays out of analytics. diff --git a/packages/core/src/mcp/analytics.spec.ts b/packages/core/src/mcp/analytics.spec.ts index 95f58004d27..6b4eec0387b 100644 --- a/packages/core/src/mcp/analytics.spec.ts +++ b/packages/core/src/mcp/analytics.spec.ts @@ -10,6 +10,7 @@ import { import type { TrackingEvent } from "../tracking/types.js"; import { detectVendorClient, + mcpToolResultSize, readClientInfoFromRequest, vendorForRedirectHost, } from "./analytics.js"; @@ -29,7 +30,7 @@ function config(): MCPConfig { "list-messages": { tool: { description: "List messages", parameters: undefined }, readOnly: true, - run: async () => [{ id: "m1" }], + run: async () => [{ id: "m1", subject: "Quarterly plan draft" }], } as any, "send-message": { tool: { description: "Send a message", parameters: undefined }, @@ -119,6 +120,51 @@ describe("MCP analytics events", () => { expect(props.$mcp_error_type).toBeUndefined(); }); + it("reports how big the result the client got is, never its text", async () => { + const client = await connectedClient(); + const result = await client.callTool({ + name: "list-messages", + arguments: {}, + }); + + const props = eventNamed("$mcp_tool_call")?.properties; + expect(props).toBeDefined(); + const text = (result.content as Array<{ type: string; text?: string }>) + .filter((block) => block.type === "text") + .map((block) => block.text ?? "") + .join(""); + expect(text).toContain("Quarterly plan draft"); + expect(props?.$mcp_response_text_chars).toBe(text.length); + expect(result.structuredContent).toBeDefined(); + expect(props?.$mcp_response_structured_chars).toBe( + JSON.stringify(result.structuredContent).length, + ); + expect(JSON.stringify(props)).not.toContain("Quarterly plan draft"); + }); + + it("counts a result's text blocks and leaves out structured content it lacks", () => { + expect( + mcpToolResultSize({ + content: [ + { type: "text", text: "Two parts" }, + { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + { type: "text", text: ", one size." }, + ], + }), + ).toEqual({ resultTextChars: 20 }); + expect( + mcpToolResultSize({ + content: [{ type: "text", text: "{}" }], + structuredContent: { items: ["a"] }, + }), + ).toEqual({ resultTextChars: 2, resultStructuredChars: 15 }); + expect(mcpToolResultSize({ structuredContent: null })).toEqual({ + resultTextChars: 0, + resultStructuredChars: 4, + }); + expect(mcpToolResultSize(undefined)).toEqual({}); + }); + it("includes redacted $mcp_parameters only when opted in", async () => { process.env.MCP_ANALYTICS_PARAMETERS = "true"; resetAppConfigForTests(); diff --git a/packages/core/src/mcp/analytics.ts b/packages/core/src/mcp/analytics.ts index 0b7e1e0289e..72f9c987b82 100644 --- a/packages/core/src/mcp/analytics.ts +++ b/packages/core/src/mcp/analytics.ts @@ -119,7 +119,7 @@ export function readClientInfoFromRequest( }; } -function analyticsEnabled(): boolean { +export function mcpAnalyticsEnabled(): boolean { if (listTrackingProviders().length === 0) return false; return getAppConfig().observability.mcpEvents; } @@ -194,7 +194,7 @@ function emit( } export function trackMcpInitialize(ctx: McpAnalyticsContext): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.initialize, ctx, {}); } @@ -202,7 +202,7 @@ export function trackMcpToolsList( ctx: McpAnalyticsContext, args: { toolNames: string[]; durationMs: number }, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.toolsList, ctx, { $mcp_listed_tool_names: args.toolNames, $mcp_listed_tool_count: args.toolNames.length, @@ -210,6 +210,44 @@ export function trackMcpToolsList( }); } +export interface McpToolResultSize { + resultTextChars: number; + resultStructuredChars?: number; +} + +/** + * How big an MCP tool result is, never what it says: the characters in its + * text blocks, and in its structured content as JSON when it has any. Hosts + * read different parts of a result, so each part is counted on its own. + */ +export function mcpToolResultSize(result: unknown): Partial { + if (typeof result !== "object" || result === null) return {}; + const blocks: unknown[] = + "content" in result && Array.isArray(result.content) ? result.content : []; + let resultTextChars = 0; + for (const block of blocks) { + if ( + typeof block === "object" && + block !== null && + "type" in block && + block.type === "text" && + "text" in block && + typeof block.text === "string" + ) { + resultTextChars += block.text.length; + } + } + return { + resultTextChars, + ...("structuredContent" in result && result.structuredContent !== undefined + ? { + resultStructuredChars: JSON.stringify(result.structuredContent) + .length, + } + : {}), + }; +} + export function trackMcpToolCall( ctx: McpAnalyticsContext, args: { @@ -221,9 +259,9 @@ export function trackMcpToolCall( isError: boolean; errorType?: string; errorMessage?: string; - }, + } & Partial, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.toolCall, ctx, { $mcp_tool_name: args.toolName, ...(args.toolDescription @@ -234,6 +272,12 @@ export function trackMcpToolCall( ? { $mcp_parameters: safeValue(args.parameters) } : {}), $mcp_duration_ms: args.durationMs, + ...(args.resultTextChars !== undefined + ? { $mcp_response_text_chars: args.resultTextChars } + : {}), + ...(args.resultStructuredChars !== undefined + ? { $mcp_response_structured_chars: args.resultStructuredChars } + : {}), $mcp_is_error: args.isError, ...(args.errorType ? { $mcp_error_type: args.errorType } : {}), ...(args.errorMessage ? { $mcp_error_message: args.errorMessage } : {}), @@ -244,7 +288,7 @@ export function trackMcpResourcesList( ctx: McpAnalyticsContext, args: { resourceCount: number; durationMs: number }, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.resourcesList, ctx, { $mcp_listed_resource_count: args.resourceCount, $mcp_duration_ms: args.durationMs, @@ -262,7 +306,7 @@ export function trackMcpResourceRead( errorMessage?: string; }, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.resourceRead, ctx, { ...(args.resourceName ? { $mcp_resource_name: args.resourceName } : {}), ...(args.resourceUri ? { $mcp_resource_uri: args.resourceUri } : {}), @@ -285,7 +329,7 @@ export function trackMcpOAuthAuthorizeOpened( ctx: McpAnalyticsContext, args: { route: McpOAuthRoute; signedIn: boolean }, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.oauthAuthorizeOpened, ctx, { $mcp_oauth_route: args.route, $mcp_oauth_signed_in: args.signedIn, @@ -296,7 +340,7 @@ export function trackMcpOAuthLoginWallShown( ctx: McpAnalyticsContext, args: { route: McpOAuthRoute }, ): void { - if (!analyticsEnabled()) return; + if (!mcpAnalyticsEnabled()) return; emit(MCP_ANALYTICS_EVENTS.oauthLoginWallShown, ctx, { $mcp_oauth_route: args.route, }); diff --git a/packages/core/src/mcp/build-server.ts b/packages/core/src/mcp/build-server.ts index 1a79971b5e8..48d34639225 100644 --- a/packages/core/src/mcp/build-server.ts +++ b/packages/core/src/mcp/build-server.ts @@ -99,6 +99,8 @@ import { import { type McpAnalyticsContext, describeMcpError, + mcpAnalyticsEnabled, + mcpToolResultSize, readClientInfoFromRequest, trackMcpResourceRead, trackMcpResourcesList, @@ -4987,6 +4989,7 @@ export async function createMCPServerForRequest( : {}), parameters: analyticsParameters(toolName, calledArgs), durationMs: Date.now() - startedAt, + ...(mcpAnalyticsEnabled() ? mcpToolResultSize(result) : {}), isError: (result as { isError?: boolean }).isError === true, ...(failure ?? {}), });