diff --git a/docs/contributing/tool-responses.md b/docs/contributing/tool-responses.md index 477168f47..6b78753b5 100644 --- a/docs/contributing/tool-responses.md +++ b/docs/contributing/tool-responses.md @@ -171,6 +171,13 @@ Policy (encoded in `packages/mcp-core/src/internal/tool-helpers/results.ts`): what the framework already checks. Shared builders should declare their return type (`StructuredToolOutput>`) so `structuredResult` gets its type from there. +- Output schema changes are additive only. Clients validate results against + the `tools/list` they cached when they connected, often across our deploys. + The server lists every output object without `additionalProperties: false` + (`internal/tool-helpers/output-schema.ts`), so a new field is safe. Removing + or renaming a field, making a required field optional or nullable, or + widening a value (a new enum member or union arm, a broader type) still + breaks those clients. - Do not duplicate a large structured payload into a markdown artifact block. - Treat `structuredContent` as a stable product contract, not a raw upstream API passthrough. Map only documented fields that callers should depend on. diff --git a/packages/mcp-core/src/internal/tool-helpers/output-schema.ts b/packages/mcp-core/src/internal/tool-helpers/output-schema.ts new file mode 100644 index 000000000..561cbdc8a --- /dev/null +++ b/packages/mcp-core/src/internal/tool-helpers/output-schema.ts @@ -0,0 +1,47 @@ +import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server"; +import type { z } from "zod"; +import type { ToolOutputSchema } from "../../tools/types"; + +type JsonSchemaOverride = NonNullable; + +const openObjects: JsonSchemaOverride = ({ zodSchema, jsonSchema }) => { + if ( + zodSchema._zod.def.type === "object" && + jsonSchema.additionalProperties === false + ) { + delete jsonSchema.additionalProperties; + } +}; + +/** + * Wraps a tool's output schema so `tools/list` advertises open objects. + * + * Zod lists every `z.object` in an output schema with + * `additionalProperties: false`. SDK clients validate each result against + * the schema they cached when they listed tools, so an output field added in + * a later deploy fails every call from a client that still holds the older + * list (getsentry/toolkit#2293). Without that keyword, adding a field is + * backward compatible, and the listed schema still catches missing or + * mistyped fields. Server-side validation stays with the Zod schema. + */ +export function openOutputSchema( + schema: ToolOutputSchema, +): StandardSchemaWithJSON { + const standard = schema["~standard"]; + return { + "~standard": { + ...standard, + jsonSchema: { + input: standard.jsonSchema.input, + output: (options) => + standard.jsonSchema.output({ + ...options, + libraryOptions: { + ...options.libraryOptions, + override: openObjects, + }, + }), + }, + }, + }; +} diff --git a/packages/mcp-core/src/server.all-tools.test.ts b/packages/mcp-core/src/server.all-tools.test.ts index be504d760..18e20a05a 100644 --- a/packages/mcp-core/src/server.all-tools.test.ts +++ b/packages/mcp-core/src/server.all-tools.test.ts @@ -96,6 +96,25 @@ function findArraysWithoutItemSchema( ]; } +/** Paths of nodes that list `additionalProperties: false`. */ +function findClosedObjects(schema: unknown, path: string[] = []): string[] { + if (!schema || typeof schema !== "object") { + return []; + } + const entries = Object.entries(schema); + const closed = + !Array.isArray(schema) && + (schema as Record)["additionalProperties"] === false + ? [path.join(".") || "(root)"] + : []; + return [ + ...closed, + ...entries.flatMap(([key, value]) => + findClosedObjects(value, [...path, key]), + ), + ]; +} + // server.test.ts covers the gateway surface used when the flag is off. describe.skipIf(!EXPOSE_ALL_TOOLS)("buildServer with EXPOSE_ALL_TOOLS", () => { it("lists every skill-granted tool and drops the catalog gateway", async () => { @@ -156,6 +175,27 @@ describe.skipIf(!EXPOSE_ALL_TOOLS)("buildServer with EXPOSE_ALL_TOOLS", () => { }, ); + // A client validates results against the tools/list it cached, so a closed + // object breaks it as soon as a later deploy adds a field (#2293). + it.each([false, true])( + "lists output schemas with open objects (experimentalMode=%s)", + async (experimentalMode) => { + const listed = await withClient( + getContext(), + async (client) => (await client.listTools()).tools, + experimentalMode, + ); + + expect(listed.some((tool) => tool.outputSchema)).toBe(true); + const violations = listed.flatMap((tool) => + findClosedObjects(tool.outputSchema).map( + (path) => `${tool.name}: ${path}`, + ), + ); + expect(violations).toEqual([]); + }, + ); + it("lists the replacements of deprecated tools instead of the tools", async () => { const toolNames = await listToolNames(getContext()); const deprecatedTools = Object.values(tools).filter( diff --git a/packages/mcp-core/src/server.test.ts b/packages/mcp-core/src/server.test.ts index a5e12dbc5..cff7fe61d 100644 --- a/packages/mcp-core/src/server.test.ts +++ b/packages/mcp-core/src/server.test.ts @@ -886,6 +886,75 @@ describe("buildServer", () => { }); }); + describe("listed output schemas", () => { + const createServer = () => + buildServer({ + context: baseContext, + tools: { + structured_tool: createMockTool("structured_tool", { + outputSchema: z.object({ + status: z.string(), + details: z.object({ count: z.number() }), + totals: z.record(z.string(), z.number()), + }), + // `added` stands in for a field from a later deploy that a client's + // cached tools/list does not have yet. + handler: async () => + structuredResult({ + status: "ok", + details: { count: 2, added: true }, + totals: { a: 1 }, + added: "new", + }), + }), + }, + }); + + it("leave objects open and keep record value schemas", async () => { + const [tool] = await listRegisteredTools(createServer()); + expect(tool?.outputSchema).toEqual({ + $schema: expect.any(String), + type: "object", + properties: { + status: { type: "string" }, + details: { + type: "object", + properties: { count: { type: "number" } }, + required: ["count"], + }, + totals: { + type: "object", + propertyNames: { type: "string" }, + additionalProperties: { type: "number" }, + }, + }, + required: ["status", "details", "totals"], + }); + }); + + it("let a client accept fields its listed schema lacks", async () => { + const server = createServer(); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "cached-list", version: "1.0.0" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + let result: Awaited>; + try { + // the client validates results only against a schema it has listed + await client.listTools(); + result = await client.callTool({ name: "structured_tool" }); + } finally { + await client.close(); + await server.close(); + } + expect(getStructuredContent(result)).toMatchObject({ + added: "new", + details: { count: 2, added: true }, + }); + }); + }); + describe("telemetry context", () => { it("generates compatibility text for structured-only tool output", async () => { const server = buildServer({ diff --git a/packages/mcp-core/src/server.ts b/packages/mcp-core/src/server.ts index 49702c0b8..3d0d07eb6 100644 --- a/packages/mcp-core/src/server.ts +++ b/packages/mcp-core/src/server.ts @@ -36,6 +36,7 @@ import { import { wrapMcpServerWithSentry } from "@sentry/core/server"; import { isApiAuthenticationErrorDeep } from "./api-client"; import { withCallSignal } from "./internal/tool-helpers/call-signal"; +import { openOutputSchema } from "./internal/tool-helpers/output-schema"; import { isUnauthorizedHandled } from "./internal/tool-helpers/credential-routing"; import { MAX_TOOL_INPUT_ELEMENTS } from "@sentry/toolkit-core/mcp-limits"; import { MCP_SERVER_INFO } from "./constants"; @@ -339,7 +340,15 @@ export function buildServer({ logIssue(error, transportLogOptions); }; for (const { name, config, handler } of registrations) { - server.registerTool(name, config, handler); + server.registerTool( + name, + { + ...config, + outputSchema: + config.outputSchema && openOutputSchema(config.outputSchema), + }, + handler, + ); } registerUiResources( server,