Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion .agents/skills/tracking/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`)
Expand Down
5 changes: 5 additions & 0 deletions .changeset/mcp-tool-call-result-size.md
Original file line number Diff line number Diff line change
@@ -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.
48 changes: 47 additions & 1 deletion packages/core/src/mcp/analytics.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import type { TrackingEvent } from "../tracking/types.js";
import {
detectVendorClient,
mcpToolResultSize,
readClientInfoFromRequest,
vendorForRedirectHost,
} from "./analytics.js";
Expand All @@ -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 },
Expand Down Expand Up @@ -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();
Expand Down
62 changes: 53 additions & 9 deletions packages/core/src/mcp/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function readClientInfoFromRequest(
};
}

function analyticsEnabled(): boolean {
export function mcpAnalyticsEnabled(): boolean {
if (listTrackingProviders().length === 0) return false;
return getAppConfig().observability.mcpEvents;
}
Expand Down Expand Up @@ -194,22 +194,60 @@ function emit(
}

export function trackMcpInitialize(ctx: McpAnalyticsContext): void {
if (!analyticsEnabled()) return;
if (!mcpAnalyticsEnabled()) return;
emit(MCP_ANALYTICS_EVENTS.initialize, ctx, {});
}

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,
$mcp_duration_ms: args.durationMs,
});
}

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<McpToolResultSize> {
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: {
Expand All @@ -221,9 +259,9 @@ export function trackMcpToolCall(
isError: boolean;
errorType?: string;
errorMessage?: string;
},
} & Partial<McpToolResultSize>,
): void {
if (!analyticsEnabled()) return;
if (!mcpAnalyticsEnabled()) return;
emit(MCP_ANALYTICS_EVENTS.toolCall, ctx, {
$mcp_tool_name: args.toolName,
...(args.toolDescription
Expand All @@ -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 } : {}),
Expand All @@ -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,
Expand All @@ -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 } : {}),
Expand All @@ -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,
Expand All @@ -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,
});
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/mcp/build-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ import {
import {
type McpAnalyticsContext,
describeMcpError,
mcpAnalyticsEnabled,
mcpToolResultSize,
readClientInfoFromRequest,
trackMcpResourceRead,
trackMcpResourcesList,
Expand Down Expand Up @@ -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 ?? {}),
});
Expand Down
Loading