Skip to content

Commit 4392722

Browse files
olaservoclaude
andauthored
Add structured content to the TypeScript weather server and client and update to v2 (#165)
* Add structured output to the TypeScript weather server and client Both tools declare an outputSchema and return structuredContent alongside the text. get-alerts declares z.array(...), so it answers with a top-level JSON array rather than an array nested in an object, which protocol revision 2026-07-28 is the first to allow. "No alerts" is simply []. get-forecast returns an object, for contrast. This costs older clients nothing. The server declares the array schema once and never branches on protocol version: serveStdio serves both eras from one factory, and the SDK projects the schema down to {"type":"object","properties":{"result":...}} for a 2025-11-25 client, wrapping the structured content to match. Verified against both eras. Error paths throw: a tool declaring an outputSchema MUST return conforming structured content, so a path with no data has to fail. The client passes versionNegotiation {mode:"auto"}; the SDK default is "legacy". The SDK validates every result against the declared schema, so the client-side SHOULD needs no code. Each channel goes to its stated reader: content is forwarded to the model, structuredContent is used as data, reporting how many items came back. Moves to the 2.0 beta packages, where the 2026-07-28 support lives: @modelcontextprotocol/sdk is replaced by @modelcontextprotocol/server and @modelcontextprotocol/client. Model identifier moves to claude-sonnet-5. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Update to @modelcontextprotocol/{server,client} 2.0.0 The 2.0 packages left beta on 2026-07-27, so the dependency ranges move off 2.0.0-beta.5. Also from review: engines.node goes to 20, which is what the 2.0 packages require, and the client README no longer implies every structured result is counted — only array-rooted ones are. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Query the active-alerts endpoint in the TypeScript server get-alerts asked for /alerts?area=XX, which returns every alert NWS has on file for the state including expired ones. The Python, Go and Rust servers all ask for /alerts/active/area/XX. Measured against the live API for TX: 372 alerts before, 8 after, and the tools/call response drops from roughly 270KB to 5KB. The other four servers return the same 8. Pre-existing on main rather than introduced by the structured-output work, but it is the one thing that stopped the examples being comparable. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Match the shared alert and forecast shapes in the TypeScript server get-alerts published status and headline where Python, Go, Rust and Ruby all publish description and instructions, and get-forecast periods used the NWS camelCase spelling with shortForecast instead of detailed_forecast. The divergence predates this round, but declaring an outputSchema turns it from a difference in prose formatting into a difference in the published contract, which defeats the point of a five-language example. All five now advertise: get_alerts -> [{event, area, severity, description, instructions}] get_forecast -> {latitude, longitude, periods[{name, temperature, temperature_unit, wind_speed, wind_direction, detailed_forecast}]} Also limits the forecast to the next 5 periods, which the other four already did, and uses `??` on the alert fields because NWS sends explicit nulls rather than omitting them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Say "structured content", not "structured output" The spec never uses the phrase "structured output". It defines two separate things under Tool Result: "Structured Content" (the `structuredContent` field) and "Output Schema" (the `outputSchema` field). Collapsing them into "structured output" conflates the two. It is also actively confusing here. In LLM tooling "structured output" means constrained decoding — making the *model* emit conforming JSON. These clients call a model API, so a reader could reasonably take the phrase to mean the tool constrains the model's response, which is the opposite of what is going on: the tool describes the shape of its own result. Headings and prose now say "structured content". References to real identifiers are left alone: the Python SDK's own docs page is called Structured Output and lives at docs/servers/structured-output.md, and its decorator parameter is `structured_output`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Address review feedback on the TypeScript weather server - Point the structured-content link at the dated 2026-07-28 spec rather than /draft, since the surrounding text names that revision. - Model a missing temperature as null instead of 0. `ForecastPeriod.temperature` is optional upstream, so the old `?? 0` published an incorrect but valid-looking 0degF rather than admitting the gap. The output schema now declares `z.number().nullable()`, and formatPeriod renders "Temperature: Unknown" for the null case instead of "null degF". - Fall back to "Unknown" for a missing wind direction, matching the neighbouring fields. - Report out-of-band errors via serveStdio's onerror callback. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Require Node 24 in the TypeScript examples The client declared `>=20.0.0` and the server declared no floor at all, while its lockfile root still recorded `>=16.0.0`. Node 20 reached end of life on 2026-04-30, so it should not be what the examples ask people to install. Both packages now require `>=24.0.0`, the Active LTS, matching the Node 24 that ci.yml already provisions and the reasoning its comment already gives. The SDK's own floor is `>=20`, but that is the oldest runtime the library tolerates, not what an example should recommend. Lockfile roots regenerated; no dependency versions move. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 12ef7bc commit 4392722

8 files changed

Lines changed: 277 additions & 2253 deletions

File tree

‎mcp-client-typescript/README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
11
# An LLM-Powered Chatbot MCP Client written in TypeScript
22

33
See the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial for more information.
4+
5+
## Structured content
6+
7+
The SDK validates every result against the tool's declared `outputSchema`, so the spec's client-side SHOULD needs no code here.
8+
9+
The two channels go to different readers: `content` is forwarded to the model, while `structuredContent` is used as data — when a tool returns an array, the client counts its items rather than re-reading the prose. See [Structured Content](https://modelcontextprotocol.io/specification/draft/server/tools#structured-content).
10+
11+
`versionNegotiation: { mode: 'auto' }` probes `server/discover` and falls back to the `2025-11-25` handshake; the SDK's default is `'legacy'`. See the [SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/).

‎mcp-client-typescript/index.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ import {
77
ToolUseBlock,
88
} from "@anthropic-ai/sdk/resources/messages/messages.mjs";
99

10-
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11-
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
10+
import { Client } from "@modelcontextprotocol/client";
11+
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
1212
import readline from "readline/promises";
1313

1414
import dotenv from "dotenv";
1515

1616
dotenv.config(); // load environment variables from .env
1717

18-
const ANTHROPIC_MODEL = "claude-sonnet-4-5";
18+
const ANTHROPIC_MODEL = "claude-sonnet-5";
1919
const MAX_TOOL_TURNS = 10;
2020

2121
class MCPClient {
@@ -25,8 +25,12 @@ class MCPClient {
2525
private tools: Tool[] = [];
2626

2727
constructor() {
28-
// Initialize MCP client
29-
this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
28+
// 'auto' probes server/discover, falling back to the 2025-11-25 handshake.
29+
// The SDK's default is 'legacy'.
30+
this.mcp = new Client(
31+
{ name: "mcp-client-cli", version: "1.0.0" },
32+
{ versionNegotiation: { mode: "auto" } },
33+
);
3034
}
3135

3236
private get anthropic(): Anthropic {
@@ -123,14 +127,25 @@ class MCPClient {
123127
finalText.push(
124128
`[Calling tool ${toolUse.name} with args ${JSON.stringify(toolArgs)}]`,
125129
);
130+
// callTool validates the result against the declared schema.
126131
const result = await this.mcp.callTool({
127132
name: toolUse.name,
128133
arguments: toolArgs,
129134
});
135+
136+
// structuredContent is data the application can use directly.
137+
if (Array.isArray(result.structuredContent)) {
138+
finalText.push(
139+
`[${toolUse.name} returned ${result.structuredContent.length} items]`,
140+
);
141+
}
142+
143+
// content is what the model reads.
130144
toolResults.push({
131145
type: "tool_result",
132146
tool_use_id: toolUse.id,
133147
content: result.content as ToolResultBlockParam["content"],
148+
is_error: result.isError === true,
134149
});
135150
}
136151

0 commit comments

Comments
 (0)