diff --git a/tests/README.md b/tests/README.md index d3916a9e..8fbdc89c 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,14 +10,15 @@ The smoke tests verify: - **Clients**: Each MCP client (Python, TypeScript, Ruby, Go, Rust) can connect to a mock server and list tools - **Tool loop**: Each client (Python, TypeScript, Ruby, Go, Rust) runs a query through a scripted tool-use loop against a fake Anthropic API and forwards tool results correctly -## Structured content +## Output schemas on both protocol revisions + +Each server test first opens a `2025-11-25` session with raw JSON-RPC — `initialize`, then `tools/list` — and checks that the call succeeds and that every `outputSchema` has an `object` root, which that revision requires. It deliberately skips the client SDK, which might quietly drop or rewrite a tool it can't accept and so hide what an older client receives. This is the regression test for [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272), where four servers sent `get_alerts`' array-rooted schema to `2025-11-25` clients. -Listing tools is not enough to catch a broken structured result, so each server test also **calls** every tool that declares an `outputSchema` and checks the answer: +It then connects with the TypeScript SDK in `auto` mode, which negotiates `2026-07-28`, and checks the same object roots there. -- the result must carry `structuredContent`, and it must conform to the declared schema (the SDK validates this and throws on a mismatch); -- a tool with an array-rooted schema must return a **top-level JSON array**, and one with an object-rooted schema must return an object. +## Structured content -The array case is the one worth guarding. A server that advertises `{"type": "array"}` and then answers `{"result": [...]}` passes a tools/list-only test and fails this one. +Listing tools is not enough to catch a broken structured result, so each server test also **calls** every tool that declares an `outputSchema` and checks the answer: the result must carry `structuredContent`, it must conform to the declared schema (the SDK validates this and throws on a mismatch), and it must be an object. Tool calls reach the live NWS API. When it is unreachable the tools return an error result, which the test reports as a skip rather than a failure — someone else's outage should not fail the build. diff --git a/tests/helpers/mcp-test-client.ts b/tests/helpers/mcp-test-client.ts index c7a670fd..62c2ce58 100644 --- a/tests/helpers/mcp-test-client.ts +++ b/tests/helpers/mcp-test-client.ts @@ -2,23 +2,26 @@ /** * Minimal MCP Test Client for testing servers * - * Connects to a server, initializes, lists tools, and then checks the tools - * actually honour what they advertise: + * First lists tools over a raw 2025-11-25 session, without the SDK, and checks + * that the call succeeds and that every `outputSchema` has an `object` root, + * which that revision requires. A client SDK may quietly drop or rewrite a + * tool it can't accept, so only the raw response shows what an older client + * receives. + * + * Then connects with the SDK, which negotiates 2026-07-28 where the server + * supports it, lists tools, and checks the tools honour what they advertise: * * - every tool declares the same annotations (read-only, open-world); + * - every `outputSchema` still has an `object` root; * - every tool that declares an `outputSchema` is called, and the result must * carry `structuredContent` (the SDK validates it against the schema for us - * and throws on a mismatch); - * - a tool whose `outputSchema` is array-rooted must answer with a top-level - * JSON array, not an object wrapping one. - * - * The second check is the point of the exercise. Listing tools alone would not - * notice a server that advertises `{"type": "array"}` and then returns - * `{"result": [...]}`. + * and throws on a mismatch) that is an object, not an array. */ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { spawn } from "node:child_process"; +import { createInterface } from "node:readline"; /** Arguments to call a tool with, chosen by matching its name. */ const TOOL_ARGUMENTS: { match: RegExp; args: Record }[] = [ @@ -49,9 +52,101 @@ function rootType(schema: unknown): string | undefined { return typeof type === "string" ? type : undefined; } +/** Fails unless every tool's `outputSchema`, where it declares one, has an object root. */ +function assertObjectRoots(tools: { name: string; outputSchema?: unknown }[], era: string) { + for (const tool of tools) { + if (tool.outputSchema === undefined) continue; + const type = rootType(tool.outputSchema); + if (type !== "object") { + throw new Error( + `${tool.name} declares an outputSchema with root type ${JSON.stringify(type)} ` + + `on a ${era} session; it must be "object"`, + ); + } + } +} + +const LEGACY_PROTOCOL_VERSION = "2025-11-25"; + +/** + * Sends `initialize` for 2025-11-25, then `tools/list`, as raw JSON-RPC over + * stdio, and checks the reply the way a strict 2025-11-25 client would. + */ +async function testLegacySession(command: string, args: string[]) { + const child = spawn(command, args, { stdio: ["pipe", "pipe", "inherit"] }); + const lines = createInterface({ input: child.stdout }); + const send = (message: object) => child.stdin.write(`${JSON.stringify(message)}\n`); + + const responses = new Map void>(); + lines.on("line", (line) => { + let message: any; + try { + message = JSON.parse(line); + } catch { + return; + } + responses.get(message.id)?.(message); + }); + + const request = (id: number, method: string, params: object = {}) => + new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`no response to ${method} within 60s`)), + 60_000, + ); + child.once("exit", (code) => reject(new Error(`server exited (${code}) before answering ${method}`))); + responses.set(id, (message) => { + clearTimeout(timer); + resolve(message); + }); + send({ jsonrpc: "2.0", id, method, params }); + }); + + try { + const init = await request(1, "initialize", { + protocolVersion: LEGACY_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: "mcp-test-client", version: "1.0.0" }, + }); + if (init.error) { + throw new Error(`initialize failed: ${JSON.stringify(init.error)}`); + } + if (init.result?.protocolVersion !== LEGACY_PROTOCOL_VERSION) { + throw new Error( + `server answered initialize with ${init.result?.protocolVersion}, not ${LEGACY_PROTOCOL_VERSION}`, + ); + } + send({ jsonrpc: "2.0", method: "notifications/initialized" }); + + const list = await request(2, "tools/list"); + if (list.error) { + throw new Error(`tools/list failed: ${JSON.stringify(list.error)}`); + } + const tools = list.result?.tools; + if (!Array.isArray(tools) || tools.length === 0) { + throw new Error(`tools/list returned no tools: ${JSON.stringify(list.result)}`); + } + assertObjectRoots(tools, LEGACY_PROTOCOL_VERSION); + console.error( + `✓ ${LEGACY_PROTOCOL_VERSION} session: listed ${tools.length} tools, every outputSchema has an object root`, + ); + } finally { + lines.close(); + child.stdin.end(); + child.kill(); + } +} + async function testServer(command: string, args: string[]) { console.error(`Testing server: ${command} ${args.join(" ")}`); + try { + await testLegacySession(command, args); + } catch (error) { + console.error(`✗ Server test failed: ${error}`); + process.exit(1); + } + const transport = new StdioClientTransport({ command, args }); // `auto` probes for 2026-07-28 and falls back to the 2025-11-25 handshake, so @@ -63,10 +158,11 @@ async function testServer(command: string, args: string[]) { try { await client.connect(transport); - console.error("✓ Connected to server"); + console.error(`✓ Connected to server, negotiated ${client.getNegotiatedProtocolVersion()}`); const { tools } = await client.listTools(); console.error(`✓ Listed ${tools.length} tools`); + assertObjectRoots(tools, client.getNegotiatedProtocolVersion() ?? "negotiated"); for (const tool of tools) { for (const [hint, value] of Object.entries(EXPECTED_ANNOTATIONS)) { @@ -110,24 +206,11 @@ async function testServer(command: string, args: string[]) { ); } - const expected = rootType(tool.outputSchema); - const isArray = Array.isArray(result.structuredContent); - - if (expected === "array" && !isArray) { - throw new Error( - `${tool.name} declares an array-rooted output schema but returned ` + - `${JSON.stringify(result.structuredContent).slice(0, 80)}`, - ); - } - if (expected === "object" && isArray) { - throw new Error( - `${tool.name} declares an object-rooted output schema but returned an array`, - ); + if (Array.isArray(result.structuredContent)) { + throw new Error(`${tool.name} returned an array as structuredContent; expected an object`); } - console.error( - `✓ ${tool.name}: structuredContent is ${isArray ? "a top-level array" : "an object"}, matching its schema`, - ); + console.error(`✓ ${tool.name}: structuredContent is an object, matching its schema`); checked += 1; } diff --git a/weather-server-go/README.md b/weather-server-go/README.md index 0130e52b..e811d263 100644 --- a/weather-server-go/README.md +++ b/weather-server-go/README.md @@ -31,8 +31,8 @@ Both tools declare the same [annotations](https://modelcontextprotocol.io/specif ## Structured content -Both tools advertise an `outputSchema` and return `StructuredContent`. `get_forecast` returns an object; `get_alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec. +Both tools advertise an `outputSchema` and return `StructuredContent`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. -`get_forecast` sets no `OutputSchema` on the `Tool`: the SDK infers one from the handler's return type, which is the idiomatic Go spelling. `get_alerts` overrides it, because inference widens a slice to `["null", "array"]` — a nil slice marshals to `null` — and the tool never returns nil. +Neither tool sets `OutputSchema` on the `Tool`: the SDK infers one from the handler's return type, which is the idiomatic Go spelling. Inference types a slice field as `["null", "array"]`, because a nil slice marshals to `null`; the handlers always build a non-nil slice, so the tools never send `null`. -Note that an array-rooted schema requires a `2026-07-28` client: the SDK sends it as written on every connection rather than projecting it down, so an older client rejects the tool list. +Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK sends an array schema as written on every connection rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). diff --git a/weather-server-go/go.mod b/weather-server-go/go.mod index 6d9a96f8..e5f20864 100644 --- a/weather-server-go/go.mod +++ b/weather-server-go/go.mod @@ -2,12 +2,10 @@ module github.com/modelcontextprotocol/quickstart-resources/weather-server-go go 1.25.1 -require ( - github.com/google/jsonschema-go v0.4.3 - github.com/modelcontextprotocol/go-sdk v1.8.0 -) +require github.com/modelcontextprotocol/go-sdk v1.8.0 require ( + github.com/google/jsonschema-go v0.4.3 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect diff --git a/weather-server-go/main.go b/weather-server-go/main.go index 39d4b745..a4f7aa51 100644 --- a/weather-server-go/main.go +++ b/weather-server-go/main.go @@ -10,7 +10,6 @@ import ( "net/http" "strings" - "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -65,9 +64,14 @@ type AlertProperties struct { Instruction string `json:"instruction"` } -// Alert is one element of get_alerts' structured content. Returning []Alert -// makes structuredContent a top-level JSON array rather than an object -// wrapping one, which protocol revision 2026-07-28 is the first to allow. +// Alerts is get_alerts' structured content. Revision 2026-07-28 allows a +// top-level array, but 2025-11-25 clients reject one, and the SDK does not yet +// convert it for them, so wrap the list. +type Alerts struct { + Alerts []Alert `json:"alerts" jsonschema:"Active alerts, empty if there are none"` +} + +// Alert is one element of Alerts. type Alert struct { Event string `json:"event" jsonschema:"The kind of weather event"` Area string `json:"area" jsonschema:"The area the alert covers"` @@ -88,7 +92,7 @@ type Period struct { DetailedForecast string `json:"detailed_forecast"` } -// Forecast is get_forecast's structured content: the object case. +// Forecast is get_forecast's structured content. type Forecast struct { Latitude float64 `json:"latitude" jsonschema:"Latitude the forecast is for"` Longitude float64 `json:"longitude" jsonschema:"Longitude the forecast is for"` @@ -204,10 +208,8 @@ func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastIn return result, forecast, nil } -// getAlerts returns []Alert, so the wire carries [{...}, {...}] and "no alerts" -// is simply []. func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) ( - *mcp.CallToolResult, []Alert, error, + *mcp.CallToolResult, Alerts, error, ) { // Build alerts URL stateCode := strings.ToUpper(input.State) @@ -215,10 +217,11 @@ func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL) if err != nil { - return nil, nil, fmt.Errorf("unable to fetch alerts for state %s: %w", stateCode, err) + return nil, Alerts{}, fmt.Errorf("unable to fetch alerts for state %s: %w", stateCode, err) } - // An empty result is an empty array, not an error. + // No alerts is an empty list, not an error. make, not a nil slice, so it + // marshals to [] rather than null. alerts := make([]Alert, 0, len(alertsData.Features)) for _, feature := range alertsData.Features { props := feature.Properties @@ -244,19 +247,7 @@ func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) Content: []mcp.Content{&mcp.TextContent{Text: text}}, } - return result, alerts, nil -} - -// alertsOutputSchema narrows the inferred root from ["null", "array"] to -// "array": a nil slice would marshal to null, but getAlerts always builds one. -func alertsOutputSchema() *jsonschema.Schema { - schema, err := jsonschema.For[[]Alert](nil) - if err != nil { - log.Fatalf("inferring get_alerts output schema: %v", err) - } - schema.Types = nil - schema.Type = "array" - return schema + return result, Alerts{Alerts: alerts}, nil } // weatherToolAnnotations returns hints for hosts: both tools only read data, @@ -295,10 +286,9 @@ func main() { // Add get_alerts tool mcp.AddTool(server, &mcp.Tool{ - Name: "get_alerts", - Description: "Get weather alerts for a US state", - OutputSchema: alertsOutputSchema(), - Annotations: weatherToolAnnotations(), + Name: "get_alerts", + Description: "Get weather alerts for a US state", + Annotations: weatherToolAnnotations(), }, getAlerts) // Run server on stdio transport diff --git a/weather-server-python/README.md b/weather-server-python/README.md index f07dcea6..40337734 100644 --- a/weather-server-python/README.md +++ b/weather-server-python/README.md @@ -33,8 +33,6 @@ Both tools declare the same [annotations](https://modelcontextprotocol.io/specif ## Structured content -Both tools declare an output schema and return `structured_content`. `get_forecast` returns an object; `get_alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec. +Both tools declare an output schema and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. -`Alerts` is a `RootModel[list[Alert]]` rather than a plain `list[Alert]` because the SDK wraps non-object return types as `{"result": ...}`; a `RootModel` is taken as the schema exactly as written. See [Structured Output](https://py.sdk.modelcontextprotocol.io/v2/servers/structured-output/) in the SDK docs. - -Note that an array-rooted schema requires a `2026-07-28` client. This SDK does not project it down for older ones — it raises instead. +Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK does not convert an array schema for an older client: `tools/list` fails with an internal error, so the client gets no tools at all. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). diff --git a/weather-server-python/weather.py b/weather-server-python/weather.py index 65c0780f..536b86d5 100644 --- a/weather-server-python/weather.py +++ b/weather-server-python/weather.py @@ -4,7 +4,7 @@ from mcp.server import MCPServer from mcp.server.mcpserver.exceptions import ToolError from mcp.types import ToolAnnotations -from pydantic import BaseModel, Field, RootModel +from pydantic import BaseModel, Field # Initialize the MCP server mcp = MCPServer("weather") @@ -34,15 +34,15 @@ class Alert(BaseModel): instructions: str = Field(description="What people in the area should do") -class Alerts(RootModel[list[Alert]]): - """The output schema of get_alerts: a top-level array, not an object. +class Alerts(BaseModel): + """The output schema of get_alerts. - A plain `-> list[Alert]` annotation would be wrapped as `{"result": [...]}`. - A RootModel is a BaseModel, so it is taken as the schema as written, and a - RootModel over a list serializes as the bare list. Revision 2026-07-28 is - the first to allow a non-object root. + Revision 2026-07-28 allows a top-level array here, but 2025-11-25 clients + reject one, and the SDK does not yet convert it for them, so wrap the list. """ + alerts: list[Alert] = Field(description="Active alerts, empty if there are none") + class Period(BaseModel): """One period of a forecast.""" @@ -56,7 +56,7 @@ class Period(BaseModel): class Forecast(BaseModel): - """The output schema of get_forecast: the object case, for contrast.""" + """The output schema of get_forecast.""" latitude: float = Field(description="Latitude the forecast is for") longitude: float = Field(description="Longitude the forecast is for") @@ -88,12 +88,12 @@ async def get_alerts(state: str) -> Alerts: if not data or "features" not in data: raise ToolError(f"Unable to fetch alerts for {state.upper()}.") - # An empty result is an empty array, not an error. + # No alerts is an empty list, not an error. # # `or` rather than a `get` default: NWS sends these fields as explicit # nulls rather than omitting them, and a default only covers a missing key. return Alerts( - [ + alerts=[ Alert( event=props.get("event") or "Unknown", area=props.get("areaDesc") or "Unknown", diff --git a/weather-server-ruby/README.md b/weather-server-ruby/README.md index 6464f9a2..55adbf86 100644 --- a/weather-server-ruby/README.md +++ b/weather-server-ruby/README.md @@ -33,13 +33,13 @@ Both tools declare the same [annotations](https://modelcontextprotocol.io/specif ## Structured content -Both tools declare an `output_schema` and return `structured_content`. `get_forecast` returns an object; `get_alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec. +Both tools declare an `output_schema` and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. -Declaring `type:` at the root of an `output_schema` is what makes the array case work. The SDK applies a `type: "object"` default only when the schema declares no root keyword, so `output_schema(type: "array", items: {...})` is taken as written. +Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. The gem sends an array schema as written rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). -Because a tool that declares an `output_schema` MUST return conforming structured content, the failure paths return an error result rather than a bare text one — error results are exempt from that requirement. "No alerts" is an empty array, not an error. +Because a tool that declares an `output_schema` MUST return conforming structured content, the failure paths return an error result rather than a bare text one — error results are exempt from that requirement. "No alerts" is an empty list, not an error. -The tools also return a human-readable `content` block. When you pass your own `content`, the SDK leaves it alone; if you omit it entirely, the SDK serializes non-object structured content into a text block for you. +The tools also return a human-readable `content` block, which the SDK leaves alone. ## Known limitation: strict `2026-07-28` clients reject this server @@ -47,4 +47,4 @@ The `mcp` gem never emits the `resultType` field on results. The 2026-07-28 sche There is no way to set it from user code: `MCP::Server` accepts `ttl_ms:` and `cache_scope:` for the SEP-2549 cache hints, but nothing for `resultType`. The gem's own client does not check the field, so the gap is invisible when a Ruby client talks to a Ruby server, and only appears cross-SDK. -Until the gem emits `resultType`, this example is verified only against the Ruby client. Note also that an array-rooted schema requires a `2026-07-28` client regardless: the gem sends it as written rather than projecting it down, so a `2025-11-25` client rejects the tool list. +Until the gem emits `resultType`, this example is verified only against the Ruby client. diff --git a/weather-server-ruby/weather.rb b/weather-server-ruby/weather.rb index 6127d38a..4bb58727 100644 --- a/weather-server-ruby/weather.rb +++ b/weather-server-ruby/weather.rb @@ -69,22 +69,27 @@ class GetAlerts < MCP::Tool required: ["state"] ) - # A top-level array, not an object wrapping one. Declaring `type` at the root - # suppresses the object default the SDK would otherwise apply, and revision - # 2026-07-28 is the first to allow a non-object root. + # Revision 2026-07-28 allows a top-level array, but 2025-11-25 clients reject + # one, and the SDK does not yet convert it for them, so wrap the list. output_schema( - type: "array", - items: { - type: "object", - properties: { - event: { type: "string", description: "The kind of weather event" }, - area: { type: "string", description: "The area the alert covers" }, - severity: { type: "string", description: "How severe the event is" }, - description: { type: "string", description: "What is happening" }, - instructions: { type: "string", description: "What people in the area should do" } - }, - required: ["event", "area", "severity", "description", "instructions"] - } + properties: { + alerts: { + type: "array", + description: "Active alerts, empty if there are none", + items: { + type: "object", + properties: { + event: { type: "string", description: "The kind of weather event" }, + area: { type: "string", description: "The area the alert covers" }, + severity: { type: "string", description: "How severe the event is" }, + description: { type: "string", description: "What is happening" }, + instructions: { type: "string", description: "What people in the area should do" } + }, + required: ["event", "area", "severity", "description", "instructions"] + } + } + }, + required: ["alerts"] ) def self.call(state:, server_context: nil) @@ -98,7 +103,7 @@ def self.call(state:, server_context: nil) return error_response("Unable to fetch alerts for #{state.upcase}.") end - # An empty result is an empty array, not an error. + # No alerts is an empty list, not an error. alerts = data["features"].map do |feature| properties = feature["properties"] || {} { @@ -118,7 +123,7 @@ def self.call(state:, server_context: nil) MCP::Tool::Response.new( [{ type: "text", text: text }], - structured_content: alerts + structured_content: { alerts: alerts } ) end end @@ -143,7 +148,6 @@ class GetForecast < MCP::Tool required: ["latitude", "longitude"] ) - # The object case, for contrast with get_alerts' array root. output_schema( type: "object", properties: { diff --git a/weather-server-rust/README.md b/weather-server-rust/README.md index afae6fc2..7509c016 100644 --- a/weather-server-rust/README.md +++ b/weather-server-rust/README.md @@ -37,6 +37,6 @@ Both tools declare the same [annotations](https://modelcontextprotocol.io/specif ## Structured content -Both tools declare an `output_schema` and return `structured_content`. `get_forecast` returns an object; `get_alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec. +Both tools declare an `output_schema` and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. -Note that an array-rooted schema requires a `2026-07-28` client: rmcp sends it as written on every connection rather than projecting it down, so an older client rejects the tool list. +Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. rmcp sends an array schema as written on every connection rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). diff --git a/weather-server-rust/src/main.rs b/weather-server-rust/src/main.rs index 9d07487e..dd30a9b5 100644 --- a/weather-server-rust/src/main.rs +++ b/weather-server-rust/src/main.rs @@ -68,9 +68,16 @@ struct ForecastPeriod { detailed_forecast: String, } -/// One element of `get_alerts`' structured content. Declaring `Vec` as -/// the output schema makes `structuredContent` a top-level JSON array rather -/// than an object wrapping one, which revision 2026-07-28 is the first to allow. +/// `get_alerts`' structured content. Revision 2026-07-28 allows a top-level +/// array, but 2025-11-25 clients reject one, and rmcp does not yet convert it +/// for them, so wrap the list. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Alerts { + /// Active alerts, empty if there are none. + alerts: Vec, +} + +/// One element of `Alerts`. #[derive(Debug, Serialize, JsonSchema)] pub struct Alert { /// The kind of weather event. @@ -85,7 +92,7 @@ pub struct Alert { instructions: String, } -/// `get_forecast`' structured content: the object case. +/// `get_forecast`' structured content. #[derive(Debug, Serialize, JsonSchema)] pub struct Forecast { /// Latitude the forecast is for. @@ -188,7 +195,7 @@ impl Weather { idempotent_hint = true, open_world_hint = true ), - output_schema = schema_for_output::>() + output_schema = schema_for_output::() )] async fn get_alerts( &self, @@ -203,7 +210,7 @@ impl Weather { ))])); }; - // An empty result is an empty array, not an error. + // No alerts is an empty list, not an error. let alerts: Vec = data .features .into_iter() @@ -233,7 +240,7 @@ impl Weather { .join("\n---\n") }; - dual_channel_result(text, &alerts) + dual_channel_result(text, Alerts { alerts }) } #[tool( diff --git a/weather-server-typescript/README.md b/weather-server-typescript/README.md index a5f1ae97..873591ec 100644 --- a/weather-server-typescript/README.md +++ b/weather-server-typescript/README.md @@ -34,6 +34,8 @@ Both tools declare the same [annotations](https://modelcontextprotocol.io/specif ## Structured content -Both tools declare an `outputSchema` and return `structuredContent`. `get-forecast` returns an object; `get-alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec. +Both tools declare an `outputSchema` and return `structuredContent`, and both return an object: `get-alerts` returns `{"alerts": [...]}`, with an empty list when there are none. -`serveStdio` serves both protocol eras from one factory, and the SDK projects the array-rooted schema down to the `{"result": [...]}` form for a `2025-11-25` client, so adopting it costs older clients nothing. See the [SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/). +Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK would cope with an array: it wraps one as `{"result": [...]}` for a `2025-11-25` client. The other four SDKs send it as written, which older clients reject, and the five examples should behave the same. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). + +`serveStdio` serves both protocol eras from one factory. See the [SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/). diff --git a/weather-server-typescript/src/index.ts b/weather-server-typescript/src/index.ts index 3a165788..12b3d6fa 100644 --- a/weather-server-typescript/src/index.ts +++ b/weather-server-typescript/src/index.ts @@ -60,21 +60,25 @@ interface ForecastResponse { } /** - * The output schema of `get-alerts`: a top-level array, not an object, which - * revision 2026-07-28 is the first to allow. The SDK projects it down to the - * old `{ result: [...] }` wrapper for 2025-11-25 clients. + * The output schema of `get-alerts`. Revision 2026-07-28 allows a top-level + * array, but the other SDKs still send one to 2025-11-25 clients, which reject + * it, so all five servers wrap the list in an object for now. */ -const alertsOutputSchema = z.array( - z.object({ - event: z.string().describe("The kind of weather event"), - area: z.string().describe("The area the alert covers"), - severity: z.string().describe("How severe the event is"), - description: z.string().describe("What is happening"), - instructions: z.string().describe("What people in the area should do"), - }), -); +const alertsOutputSchema = z.object({ + alerts: z + .array( + z.object({ + event: z.string().describe("The kind of weather event"), + area: z.string().describe("The area the alert covers"), + severity: z.string().describe("How severe the event is"), + description: z.string().describe("What is happening"), + instructions: z.string().describe("What people in the area should do"), + }), + ) + .describe("Active alerts, empty if there are none"), +}); -/** The output schema of `get-forecast`: the object case. */ +/** The output schema of `get-forecast`. */ const forecastOutputSchema = z.object({ latitude: z.number().describe("Latitude the forecast is for"), longitude: z.number().describe("Longitude the forecast is for"), @@ -92,7 +96,7 @@ const forecastOutputSchema = z.object({ .describe("The forecast periods, soonest first"), }); -type Alert = z.infer[number]; +type Alert = z.infer["alerts"][number]; type Forecast = z.infer; // Format alert data for the model to read @@ -158,7 +162,7 @@ function buildServer(): McpServer { throw new Error(`Failed to retrieve alerts data for ${stateCode}`); } - // An empty result is an empty array, not an error. + // No alerts is an empty list, not an error. // `??` catches the nulls NWS sends for these fields; it does not omit // them, so a key-missing default would not fire. const alerts: Alert[] = (alertsData.features ?? []).map((feature) => ({ @@ -175,7 +179,7 @@ function buildServer(): McpServer { ? `No active alerts for ${stateCode}` : `Active alerts for ${stateCode}:\n\n${alerts.map(formatAlert).join("\n")}`; - return { content: [{ type: "text", text }], structuredContent: alerts }; + return { content: [{ type: "text", text }], structuredContent: { alerts } }; }, );