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
7 changes: 7 additions & 0 deletions docs/contributing/tool-responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<z.output<typeof schema>>`) 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.
Expand Down
47 changes: 47 additions & 0 deletions packages/mcp-core/src/internal/tool-helpers/output-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server";
import type { z } from "zod";
import type { ToolOutputSchema } from "../../tools/types";

type JsonSchemaOverride = NonNullable<z.core.ToJSONSchemaParams["override"]>;

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,
},
}),
},
},
};
}
40 changes: 40 additions & 0 deletions packages/mcp-core/src/server.all-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>)["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 () => {
Expand Down Expand Up @@ -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(
Expand Down
69 changes: 69 additions & 0 deletions packages/mcp-core/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof client.callTool>>;
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({
Expand Down
11 changes: 10 additions & 1 deletion packages/mcp-core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down
Loading