Skip to content
Merged
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
11 changes: 6 additions & 5 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
135 changes: 109 additions & 26 deletions tests/helpers/mcp-test-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> }[] = [
Expand Down Expand Up @@ -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<number, (message: any) => 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<any>((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
Expand All @@ -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)) {
Expand Down Expand Up @@ -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;
}

Expand Down
6 changes: 3 additions & 3 deletions weather-server-go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
6 changes: 2 additions & 4 deletions weather-server-go/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 17 additions & 27 deletions weather-server-go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"net/http"
"strings"

"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/mcp"
)

Expand Down Expand Up @@ -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"`
Expand All @@ -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"`
Expand Down Expand Up @@ -204,21 +208,20 @@ 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)
alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode)

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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions weather-server-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
20 changes: 10 additions & 10 deletions weather-server-python/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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."""
Expand All @@ -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")
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading