diff --git a/.changeset/register-tool-output-typing.md b/.changeset/register-tool-output-typing.md index 5b4c90381b..a4dcfe3480 100644 --- a/.changeset/register-tool-output-typing.md +++ b/.changeset/register-tool-output-typing.md @@ -2,13 +2,13 @@ '@modelcontextprotocol/server': minor --- -`McpServer.registerTool` now type-checks a callback's successful result against the tool's `outputSchema`, for Standard Schema and deprecated raw-shape schemas. A successful result must include `structuredContent` that matches the schema and is not `undefined`; `isError: true` results, input-required results and tools without an `outputSchema` are unchanged. Runtime output validation is unchanged. +`McpServer.registerTool` now type-checks a callback's successful result against the tool's `outputSchema`, for Standard Schema and deprecated raw-shape schemas. A successful result must include `structuredContent` that matches the schema and is not `undefined`; `isError: true` results, input-required results, tools without an `outputSchema`, and tools whose schema has an `unknown` output type (such as an untyped `fromJsonSchema(...)`) are unchanged. Runtime output validation is unchanged. New exported types: `ToolResultFor`, `ToolStructuredContent`, `ToolResultWithStructuredContent`, `ToolErrorResult`. `ToolCallback` takes an optional second type parameter for the output schema. -Code that compiled before can now fail to compile, for a tool with an `outputSchema`, when the callback: +Code that compiled before can now fail to compile, for a tool with a typed `outputSchema`, when the callback: - returns `structuredContent` that does not match the schema, or a successful result without it; - builds the value from a wider type than the schema (e.g. `string` for an enum); - has its result typed as plain `CallToolResult` (a `Promise` annotation, a helper returning `CallToolResult`, or `ToolCallback`); use `ToolCallback` or drop the annotation; -- is registered with an `outputSchema` typed `S | undefined`, which is checked as if present. +- is registered with a typed `outputSchema` that may be `undefined`, which is checked as if present. diff --git a/.changeset/tool-structured-content-text.md b/.changeset/tool-structured-content-text.md new file mode 100644 index 0000000000..162c4aa34b --- /dev/null +++ b/.changeset/tool-structured-content-text.md @@ -0,0 +1,5 @@ +--- +'@modelcontextprotocol/server': minor +--- + +A `McpServer` tool result with `structuredContent` and no `content` now gets a text block holding the serialized JSON of `structuredContent`, as the tools spec recommends, instead of `content: []`. This applies to every tool result, with or without an `outputSchema` or `isError`. A result that supplies `content`, even an empty array, is handled as before. To match, successful results of a tool with a typed `outputSchema` may omit `content` in TypeScript, both in `registerTool` and in `RegisteredTool.update({ callback })`. diff --git a/docs/servers/tools.md b/docs/servers/tools.md index 26a666920c..14add90f8d 100644 --- a/docs/servers/tools.md +++ b/docs/servers/tools.md @@ -116,12 +116,14 @@ server.registerTool( ); ``` -TypeScript checks the callback against `outputSchema`: in this example, returning a string, leaving out `price`, or returning `price: '24'` is a compile error, and so is a successful result with no `structuredContent`. Results with `isError: true` and [input-required results](input-required.md) are exempt. `structuredContent: undefined` counts as missing; `null` is fine when the schema allows it. +TypeScript checks the callback against `outputSchema`: in this example, returning a string, leaving out `price`, or returning `price: '24'` is a compile error, and so is a successful result with no `structuredContent`. Results with `isError: true` and [input-required results](input-required.md) are exempt. `structuredContent: undefined` counts as missing; `null` is fine when the schema allows it. A schema with no static output type, such as an untyped `fromJsonSchema(...)`, is not checked at compile time. The SDK validates the value you return and sends it as is, without the parsed result. So the type TypeScript asks for is one that satisfies both the input and the output side of the schema: fields with a `.default()` must be supplied, coerced fields must already have the output type, and a `.transform()` whose output is not a valid input cannot be satisfied at all. Values built from wider types, such as a `string` that should be one of an enum's members, need narrowing or a `satisfies` annotation before you return them. The SDK also validates `structuredContent` against `outputSchema` at runtime before the result leaves your server, and advertises the derived JSON Schema in `tools/list` so clients can validate it too. The runtime check is still the one that counts: it covers JavaScript callers, values cast with `as`, and constraints TypeScript cannot express, such as `.min()`, `.email()` or `.refine()`. +With a typed `outputSchema` you may leave out `content`; the server then sends the JSON of `structuredContent` as a single text block, so clients that ignore `structuredContent` still see the result. Supply your own `content` to control that text. + Calling `product-details` with `{ name: 'Travel mug' }` returns both renderings: ``` diff --git a/packages/server/src/server/mcp.ts b/packages/server/src/server/mcp.ts index 3da77fc62f..3e4279e5e2 100644 --- a/packages/server/src/server/mcp.ts +++ b/packages/server/src/server/mcp.ts @@ -42,6 +42,7 @@ import { ResourceNotFoundError, scanXMcpHeaderDeclarations, standardSchemaToJsonSchema, + TOOL_RESULT_FOREIGN_FAMILY_KEYS, UriTemplate, validateAndWarnToolName, validateStandardSchema @@ -342,12 +343,13 @@ export class McpServer { const result = await this.executeToolHandler(tool, args, ctx); await this.validateToolOutput(tool, result, request.params.name); if (isInputRequiredResult(result)) return result; + const completed = withStructuredContentText(result); // SEP-2106 result-side projection (the era-agnostic TextContent auto-append; the // `{result:…}` wrap on the 2025 era) lives behind the wire codec's // `projectCallToolResult`. The codec receives the SAME advertised JSON Schema // `tools/list` emits (and that the codec's `encodeResult('tools/list', …)` may have // wrapped) so the listing and the call cannot diverge. - return this.server.projectCallToolResult(result, tool.outputSchemaJson); + return this.server.projectCallToolResult(completed, tool.outputSchemaJson); } catch (error) { if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) { throw error; // Return the error to the caller without wrapping in CallToolResult @@ -1035,8 +1037,8 @@ export class McpServer { needsExecutorRegen = true; } if (updates.callback !== undefined) { - registeredTool.handler = updates.callback; currentHandler = updates.callback as AnyToolHandler; + registeredTool.handler = currentHandler; needsExecutorRegen = true; } if (needsExecutorRegen) { @@ -1374,6 +1376,18 @@ export class ResourceTemplate { } } +// Mirrors `structuredContent` as JSON text when a tool result omits `content`; other result families are left to fail validation. +function withStructuredContentText(result: CallToolResult): CallToolResult { + if ( + (result as { content?: unknown }).content !== undefined || + result.structuredContent === undefined || + TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key => key in result) + ) { + return result; + } + return { ...result, content: [{ type: 'text', text: JSON.stringify(result.structuredContent) }] }; +} + /** * A plain record of Zod field schemas, e.g. `{ name: z.string() }`. Accepted by * `registerTool`/`registerPrompt` as a shorthand; auto-wrapped with `z.object()`. @@ -1394,9 +1408,9 @@ export type InferRawShape = z.infer>; * the intersection of input and output otherwise — so a transforming schema whose output is not * a valid input cannot be satisfied by accident. `undefined` is excluded because the runtime * treats `structuredContent: undefined` as absent; `null` is kept when the schema allows it. - * When the schema's output type is `unknown` (an untyped `fromJsonSchema(...)`, `z.unknown()`), - * any value is accepted, so forwarded `unknown` values type-check; the key is still required. * A branded output (Zod `.brand()`) requires a branded value, as brands are meant to. + * For a schema whose output type is `unknown` this is `unknown`, and `registerTool` does not + * check the result at compile time (see {@linkcode ToolResultFor}). * * @typeParam Output - the tool's `outputSchema`: a Standard Schema or a {@linkcode ZodRawShape}. */ @@ -1414,14 +1428,18 @@ export type ToolStructuredContent = { // `Omit` would collapse CallToolResult's known keys into its index signature; key remapping keeps them. [K in keyof CallToolResult as K extends 'content' | 'structuredContent' | 'isError' ? never : K]: CallToolResult[K]; } & { - content: CallToolResult['content']; + content?: CallToolResult['content']; structuredContent: T; isError?: false; }; @@ -1432,11 +1450,12 @@ export type ToolErrorResult = CallToolResult & { isError: true }; /** * Maps a tool's declared `outputSchema` to the {@link CallToolResult} its handler may return. * - * With an `outputSchema`, a successful result must carry matching `structuredContent` + * With a typed `outputSchema`, a successful result must carry matching `structuredContent` * ({@linkcode ToolResultWithStructuredContent}); `isError: true` results are unconstrained. - * Without one, any {@link CallToolResult} is allowed. A schema typed `S | undefined` also allows - * any result here, but `registerTool`'s optional `outputSchema` property drops the `undefined` - * when inferring, so a forwarded optional schema is checked as if present. + * Without one, or with one whose output type is `unknown` (such as an untyped + * `fromJsonSchema(...)`), any {@link CallToolResult} is allowed. A schema typed `S | undefined` + * also allows any result here, but `registerTool`'s optional `outputSchema` property drops the + * `undefined` when inferring, so a forwarded optional typed schema is checked as if present. * Input-required results are added by {@linkcode ToolCallback} and are never constrained. * * @typeParam Output - the tool's `outputSchema`: a Standard Schema, a {@linkcode ZodRawShape}, or `undefined`. @@ -1444,7 +1463,9 @@ export type ToolErrorResult = CallToolResult & { isError: true }; export type ToolResultFor = [Output] extends [ StandardSchemaWithJSON | ZodRawShape ] - ? ToolResultWithStructuredContent> | ToolErrorResult + ? unknown extends ToolStructuredContent + ? CallToolResult + : ToolResultWithStructuredContent> | ToolErrorResult : CallToolResult; /** {@linkcode ToolCallback} variant used when `inputSchema` is a {@linkcode ZodRawShape}. */ @@ -1486,8 +1507,8 @@ export type BaseToolCallback< /** * Callback for a tool handler registered with {@linkcode McpServer.registerTool}. * - * `registerTool` passes the tool's `outputSchema` as `Output`, so a successful result's - * `structuredContent` is checked against the schema at compile time (see {@linkcode ToolResultFor}). + * `registerTool` passes the tool's `outputSchema` as `Output`, so for a typed schema a successful + * result's `structuredContent` is checked at compile time (see {@linkcode ToolResultFor}). * Runtime validation still runs and remains authoritative. */ export type ToolCallback< @@ -1546,7 +1567,11 @@ export type RegisteredTool = { icons?: Icon[]; scopeChallenge?: ScopeChallengeHandler | null; _meta?: Record; - callback?: ToolCallback; + callback?: BaseToolCallback< + CallToolResult | ToolResultWithStructuredContent | InputRequiredResult, + ServerContext, + StandardSchemaWithJSON + >; enabled?: boolean; }): void; remove(): void; diff --git a/packages/server/test/server/registerToolOutputTyping.test.ts b/packages/server/test/server/registerToolOutputTyping.test.ts index 24e4ac5bac..d1b3b83b63 100644 --- a/packages/server/test/server/registerToolOutputTyping.test.ts +++ b/packages/server/test/server/registerToolOutputTyping.test.ts @@ -1,19 +1,20 @@ /** * Compile-time contract for `McpServer.registerTool` handler results (SEP-2106 / #2754). * - * These are type-level tests: every `@ts-expect-error` line must fail to compile and every - * other registration must compile. `pnpm typecheck` enforces both. The runtime assertions only - * pin the authoring affordances the types rely on (content auto-fill). + * Mostly type-level tests: every `@ts-expect-error` line must fail to compile and every other + * registration must compile; `pnpm typecheck` enforces both. The last describe block covers the + * runtime text block for results that omit `content`. */ import type { StandardSchemaWithJSON } from '@modelcontextprotocol/core-internal'; import { toStandardJsonSchema } from '@valibot/to-json-schema'; import { type } from 'arktype'; import * as v from 'valibot'; -import { describe, expect, expectTypeOf, it } from 'vitest'; +import { describe, expectTypeOf, it } from 'vitest'; import * as z from 'zod/v4'; import type { CallToolResult, ServerContext, ToolCallback, ToolResultFor, ToolStructuredContent } from '../../src/index'; import { fromJsonSchema, inputRequired, McpServer } from '../../src/index'; +import { invoke } from '../../src/server/invoke'; const server = new McpServer({ name: 's', version: '1' }); @@ -80,9 +81,6 @@ describe('registerTool: structuredContent is typed from outputSchema', () => { server.registerTool('str-bad', { outputSchema: z.string() }, () => ({ content: [], structuredContent: 1 })); server.registerTool('nul', { outputSchema: z.null() }, () => ({ content: [], structuredContent: null })); server.registerTool('unk', { outputSchema: z.unknown() }, () => ({ content: [], structuredContent: null })); - // An unknown output accepts any value, so forwarded `unknown` values type-check. The cost: a - // literal `undefined` here is left to the runtime "no structured content" check. - expectTypeOf>().toEqualTypeOf(); // @ts-expect-error an optional root still requires a defined value at runtime server.registerTool('opt-undef', { outputSchema: z.string().optional() }, () => ({ content: [], structuredContent: undefined })); server.registerTool('opt-val', { outputSchema: z.string().optional() }, () => ({ content: [], structuredContent: 'x' })); @@ -125,18 +123,26 @@ describe('registerTool: structuredContent is typed from outputSchema', () => { server.registerTool('mixed-bad', { inputSchema, outputSchema }, ({ ok }) => (ok ? { content: [], structuredContent: { data: 1 } } : { content: [], isError: true })); }); - it('requires content on every result, typed or not', () => { + it('lets typed successes omit content (the server sends structuredContent as JSON text)', () => { const outputSchema = z.object({ data: z.string() }); - // @ts-expect-error content is required on typed successes too server.registerTool('no-content', { outputSchema }, () => ({ structuredContent: { data: 'x' } })); // The rest of CallToolResult keeps its types on the typed branch. - server.registerTool('meta', { outputSchema }, () => ({ content: [], _meta: { trace: 'abc' }, structuredContent: { data: 'x' } })); - // @ts-expect-error content blocks are still checked + server.registerTool('meta', { outputSchema }, () => ({ _meta: { trace: 'abc' }, structuredContent: { data: 'x' } })); + // @ts-expect-error content blocks are still checked when supplied server.registerTool('bad-block', { outputSchema }, () => ({ content: [{ type: 'bogus' }], structuredContent: { data: 'x' } })); + // Schema-less and error results keep the CallToolResult contract (content required). // @ts-expect-error content is required without an outputSchema server.registerTool('schemaless-no-content', {}, () => ({ structuredContent: 'x' })); // @ts-expect-error content is required on error results server.registerTool('err-no-content', { outputSchema }, () => ({ isError: true })); + + // update({ callback }) accepts the same content-less typed result. + const tool = server.registerTool('updatable', { outputSchema }, () => ({ structuredContent: { data: 'x' } })); + tool.update({ callback: () => ({ structuredContent: { data: 'y' } }) }); + const typed = (): ToolResultFor => ({ structuredContent: { data: 'z' } }); + tool.update({ callback: typed }); + // @ts-expect-error update still requires content when there is no structuredContent + tool.update({ callback: () => ({}) }); }); it('leaves schema-less tools unchanged', () => { @@ -160,11 +166,6 @@ describe('registerTool: structuredContent is typed from outputSchema', () => { server.registerTool('std', { outputSchema: objectOut }, () => ({ content: [], structuredContent: { answer: 'ok' } })); // @ts-expect-error provider-agnostic: wrong field type server.registerTool('std-bad', { outputSchema: objectOut }, () => ({ content: [], structuredContent: { answer: 1 } })); - - const unknownOut = {} as StandardSchemaWithJSON; - server.registerTool('std-unknown', { outputSchema: unknownOut }, () => ({ content: [], structuredContent: { any: 'thing' } })); - // @ts-expect-error unknown output still needs a defined structuredContent - server.registerTool('std-unknown-missing', { outputSchema: unknownOut }, () => ({ content: [] })); }); it('works with ArkType and Valibot output schemas', () => { @@ -232,14 +233,21 @@ describe('registerTool: structuredContent is typed from outputSchema', () => { }); }); - it('accepts an unknown-typed value for an untyped fromJsonSchema output', () => { - const forwarded: unknown = JSON.parse('{"a":1}'); - server.registerTool('json-out', { outputSchema: fromJsonSchema({ type: 'object' }) }, () => ({ - content: [], - structuredContent: forwarded - })); - // @ts-expect-error structuredContent is still required on success - server.registerTool('json-out-missing', { outputSchema: fromJsonSchema({ type: 'object' }) }, () => ({ content: [] })); + it('leaves the result untyped when the schema output is unknown (runtime validation only)', () => { + expectTypeOf>>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + + // A proxy mirroring an upstream tool: untyped, possibly absent schema. + const upstream = {} as { outputSchema?: Record; result: CallToolResult }; + server.registerTool( + 'proxy', + { outputSchema: upstream.outputSchema ? fromJsonSchema(upstream.outputSchema) : undefined }, + async () => upstream.result + ); + // A typed fromJsonSchema is checked like any other schema. + const typed = fromJsonSchema<{ a: number }>({ type: 'object' }); + // @ts-expect-error typed JSON Schema output: wrong field type + server.registerTool('json-typed-bad', { outputSchema: typed }, () => ({ content: [], structuredContent: { a: 'x' } })); }); it('types standalone callbacks via ToolCallback', () => { @@ -266,3 +274,66 @@ describe('registerTool: structuredContent is typed from outputSchema', () => { void broad; }); }); + +describe('registerTool: runtime content for typed successes', () => { + const call = async (s: McpServer, name: string): Promise => { + const response = await invoke( + s, + { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: {} } }, + { classification: { era: 'legacy' } } + ); + return ((await response.json()) as { result: CallToolResult }).result; + }; + + it('sends structuredContent as a JSON text block when content is omitted', async () => { + const s = new McpServer({ name: 's', version: '1' }); + s.registerTool('obj', { outputSchema: z.object({ data: z.string() }) }, () => ({ structuredContent: { data: 'x' } })); + s.registerTool('arr', { outputSchema: z.array(z.number()) }, () => ({ structuredContent: [1, 2] })); + s.registerTool('empty', { outputSchema: z.object({ data: z.string() }) }, () => ({ + content: [], + structuredContent: { data: 'x' } + })); + + const obj = await call(s, 'obj'); + expect(obj.isError).toBeUndefined(); + expect(obj.content).toEqual([{ type: 'text', text: '{"data":"x"}' }]); + expect(obj.structuredContent).toEqual({ data: 'x' }); + + const arr = await call(s, 'arr'); + expect(arr.content).toEqual([{ type: 'text', text: '[1,2]' }]); + + // Explicit content, even empty, is left alone. + expect((await call(s, 'empty')).content).toEqual([]); + }); + + it('applies to schema-less tools, error results and callbacks swapped in with update()', async () => { + const s = new McpServer({ name: 's', version: '1' }); + s.registerTool('schemaless', {}, (() => ({ structuredContent: { a: 1 } })) as never); + s.registerTool('error', {}, (() => ({ isError: true, structuredContent: { why: 'x' } })) as never); + const tool = s.registerTool('updated', { outputSchema: z.object({ n: z.number() }) }, () => ({ structuredContent: { n: 1 } })); + tool.update({ callback: () => ({ structuredContent: { n: 2 } }) }); + + expect((await call(s, 'schemaless')).content).toEqual([{ type: 'text', text: '{"a":1}' }]); + const error = await call(s, 'error'); + expect(error.isError).toBe(true); + expect(error.content).toEqual([{ type: 'text', text: '{"why":"x"}' }]); + expect((await call(s, 'updated')).content).toEqual([{ type: 'text', text: '{"n":2}' }]); + }); + + it('does not turn a content-less result carrying another result family into a success', async () => { + const s = new McpServer({ name: 's', version: '1' }); + for (const key of ['task', 'inputRequests', 'requestState']) { + s.registerTool(key, {}, (() => ({ structuredContent: { a: 1 }, [key]: {} })) as never); + } + for (const key of ['task', 'inputRequests', 'requestState']) { + const response = await invoke( + s, + { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: key, arguments: {} } }, + { classification: { era: 'legacy' } } + ); + const body = (await response.json()) as { result?: CallToolResult; error?: { code: number } }; + expect(body.result?.content, key).toBeUndefined(); + expect(body.error?.code, key).toBe(-32602); + } + }); +}); diff --git a/skills/mcp-typescript-sdk-upgrade-to-v2/references/behavioral-changes.md b/skills/mcp-typescript-sdk-upgrade-to-v2/references/behavioral-changes.md index e12d54a800..dfbb0b90e2 100644 --- a/skills/mcp-typescript-sdk-upgrade-to-v2/references/behavioral-changes.md +++ b/skills/mcp-typescript-sdk-upgrade-to-v2/references/behavioral-changes.md @@ -197,13 +197,16 @@ requests, the per-request `_meta.logLevel` envelope key is the filter — see - **`CallToolResult.content` keeps the v1 parse tolerance on the legacy era.** An inbound result without `content` defaults to `[]` (deployed servers omit it alongside `structuredContent`); 2026-07-28 connections stay strict. Authoring is - unchanged and era-independent: the TypeScript surface requires `content` on handler - results, and a content-less handler result is normalized to `content: []` before it - reaches the wire. One sharpening remains: a content-less body carrying another - result family's vocabulary (a task handle or an `input_required` round) is still - rejected loudly — tolerance never turns a different result kind into a silent empty - success. A body whose only foreign key was `resultType` strips to an empty object - and defaults, exactly as v1 parsed a payload-free body. + era-independent: the TypeScript surface requires `content` on handler results, except + successful results of a `registerTool` tool with a typed `outputSchema`, which may omit it. + `McpServer` gives any content-less tool result that carries `structuredContent` a JSON + text block of that value; a content-less result without `structuredContent` is + normalized to `content: []` before it reaches the wire. One sharpening remains: a + content-less body carrying another result family's vocabulary (a task handle or an + `input_required` round) is still rejected loudly — tolerance never turns a different + result kind into a silent empty success. A body whose only foreign key was + `resultType` strips to an empty object and defaults, exactly as v1 parsed a + payload-free body. - **`ElicitResult.content` values are typed and validated as `string | number | boolean | string[]`.** v1's TypeScript surface accepted `Record` content values; an elicitation handler returning arbitrary diff --git a/skills/mcp-typescript-sdk-upgrade-to-v2/references/server-registration.md b/skills/mcp-typescript-sdk-upgrade-to-v2/references/server-registration.md index c00fc4dbd6..0d13a07da4 100644 --- a/skills/mcp-typescript-sdk-upgrade-to-v2/references/server-registration.md +++ b/skills/mcp-typescript-sdk-upgrade-to-v2/references/server-registration.md @@ -31,7 +31,7 @@ parameter here is the context object, not an args object. #### `outputSchema` types the callback's `structuredContent` -When a tool declares `outputSchema`, `registerTool` now checks the callback's successful +When a tool declares a typed `outputSchema`, `registerTool` now checks the callback's successful result against it. Earlier v2 releases typed `structuredContent` as `unknown`, and v1 as `{ [k: string]: unknown }`; neither connected it to `outputSchema`. Code that compiled before can now fail to compile when it: @@ -40,11 +40,15 @@ before can now fail to compile when it: - returns a successful result with no `structuredContent` (the server already rejected this at runtime); - builds the value from a wider type, e.g. a `string` where the schema has an enum. Narrow it, or annotate it with `satisfies`; - types the callback's result as plain `CallToolResult`, e.g. a `Promise` return annotation, a helper returning `CallToolResult`, or a callback annotated `ToolCallback`. Drop the annotation, or use `ToolCallback` / `ToolResultFor`; -- passes an `outputSchema` typed as possibly `undefined` (a registry forwarding an optional schema). TypeScript drops the `undefined` at the call site, so the callback is checked as if the schema were present. +- passes a typed `outputSchema` that may be `undefined`. TypeScript drops the `undefined` at the call site, so the callback is checked as if the schema were present. `isError: true` results, input-required results, and tools without an `outputSchema` -are unchanged. Runtime validation is unchanged and still authoritative. A test fixture -that deliberately returns invalid output can cast the result: `() => ({ ... }) as never`. +are unchanged. So are tools whose schema has an `unknown` output type, such as an +untyped `fromJsonSchema(...)`: a proxy that mirrors another server's tools compiles as +before. Successful results of a typed tool may leave out `content`; the server then +sends the JSON of `structuredContent` as a text block. Runtime validation is unchanged +and still authoritative. A test fixture that deliberately returns invalid output can +cast the result: `() => ({ ... }) as never`. #### Standard Schema objects (raw shapes deprecated) diff --git a/test/conformance/src/everythingServer.ts b/test/conformance/src/everythingServer.ts index 2aa3d31601..e546b37074 100644 --- a/test/conformance/src/everythingServer.ts +++ b/test/conformance/src/everythingServer.ts @@ -745,6 +745,30 @@ function createMcpServer() { } ); + // Structured content fixtures; the handlers omit `content` so McpServer supplies the JSON text block. + mcpServer.registerTool( + 'test_structured_content', + { + description: 'Tests structured content against an object outputSchema', + outputSchema: z.object({ temperature: z.number(), conditions: z.string() }) + }, + async () => ({ structuredContent: { temperature: 22.5, conditions: 'Partly cloudy' } }) + ); + // SEP-2106: array outputSchema and structuredContent. + mcpServer.registerTool( + 'test_structured_content_array', + { + description: 'Tests array structured content (SEP-2106)', + outputSchema: z.array(z.object({ hour: z.string(), temp: z.number() })) + }, + async () => ({ + structuredContent: [ + { hour: '09:00', temp: 68 }, + { hour: '10:00', temp: 72 } + ] + }) + ); + // SEP-1613 / SEP-2106: JSON Schema 2020-12 conformance test tool. // The scenario verifies that $schema/$defs/additionalProperties (SEP-1613) // and the broader 2020-12 vocabulary — $anchor, allOf/anyOf, if/then/else — diff --git a/test/e2e/requirements.ts b/test/e2e/requirements.ts index 20a8fb3561..5270df49b4 100644 --- a/test/e2e/requirements.ts +++ b/test/e2e/requirements.ts @@ -452,6 +452,11 @@ export const REQUIREMENTS: Record = { source: 'https://modelcontextprotocol.io/specification/2025-11-25/server/tools#structured-content', behavior: 'A tool returning structured content also returns the serialized JSON as a text content block.' }, + 'server:tools:structured-content:text-when-content-omitted': { + source: 'https://modelcontextprotocol.io/specification/draft/server/tools#structured-content', + behavior: + 'A McpServer tool whose handler returns structuredContent but omits content gets a single {type:"text", text: JSON.stringify(structuredContent)} block, so the result carries the serialized JSON the spec asks for. A handler that returns object structuredContent with content, even an empty array, keeps the content it supplied.' + }, 'tools:call:unknown-name': { source: 'https://modelcontextprotocol.io/specification/2025-11-25/server/tools#error-handling', behavior: 'tools/call for a name the server does not recognise returns a JSON-RPC error.' diff --git a/test/e2e/scenarios/tools.test.ts b/test/e2e/scenarios/tools.test.ts index 517f5daa5f..590ca01f36 100644 --- a/test/e2e/scenarios/tools.test.ts +++ b/test/e2e/scenarios/tools.test.ts @@ -670,6 +670,27 @@ verifies('tools:call:structured-content:text-mirror', async ({ transport }: Test expect(r.content).toContainEqual({ type: 'text', text: JSON.stringify({ doubled: 42 }) }); }); +verifies('server:tools:structured-content:text-when-content-omitted', async ({ transport }: TestArgs) => { + const makeServer = (): McpServer => { + const s = new McpServer({ name: 's', version: '0' }); + const outputSchema = z.object({ data: z.string() }); + s.registerTool('omitted', { inputSchema: z.object({}), outputSchema }, () => ({ structuredContent: { data: 'x' } })); + s.registerTool('empty', { inputSchema: z.object({}), outputSchema }, () => ({ content: [], structuredContent: { data: 'x' } })); + return s; + }; + const client = newClient(); + await using _ = await wire(transport, makeServer, client); + + const omitted = await client.callTool({ name: 'omitted', arguments: {} }); + expect(omitted.isError).toBeFalsy(); + expect(omitted.structuredContent).toEqual({ data: 'x' }); + expect(omitted.content).toEqual([{ type: 'text', text: JSON.stringify({ data: 'x' }) }]); + + const empty = await client.callTool({ name: 'empty', arguments: {} }); + expect(empty.structuredContent).toEqual({ data: 'x' }); + expect(empty.content).toEqual([]); +}); + verifies(['client:output-schema:validate', 'client:output-schema:missing-structured'], async ({ transport }: TestArgs) => { // Client-side validation is only observable when the server does NOT // pre-validate (raw Server) — McpServer would intercept first.