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>
This commit is contained in:
Ola Hungerford 2026-08-17 13:20:07 -07:00 • committed by GitHub
commit 43927228cc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -7,15 +7,15 @@ import {
ToolUseBlock,
} from "@anthropic-ai/sdk/resources/messages/messages.mjs";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import readline from "readline/promises";
import dotenv from "dotenv";
dotenv.config(); // load environment variables from .env
const ANTHROPIC_MODEL = "claude-sonnet-4-5";
const ANTHROPIC_MODEL = "claude-sonnet-5";
const MAX_TOOL_TURNS = 10;
class MCPClient {
@ -25,8 +25,12 @@ class MCPClient {
private tools: Tool[] = [];
constructor() {
// Initialize MCP client
this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
// 'auto' probes server/discover, falling back to the 2025-11-25 handshake.
// The SDK's default is 'legacy'.
this.mcp = new Client(
{ name: "mcp-client-cli", version: "1.0.0" },
{ versionNegotiation: { mode: "auto" } },
);
}
private get anthropic(): Anthropic {
@ -123,14 +127,25 @@ class MCPClient {
finalText.push(
`[Calling tool ${toolUse.name} with args ${JSON.stringify(toolArgs)}]`,
);
// callTool validates the result against the declared schema.
const result = await this.mcp.callTool({
name: toolUse.name,
arguments: toolArgs,
});
// structuredContent is data the application can use directly.
if (Array.isArray(result.structuredContent)) {
finalText.push(
`[${toolUse.name} returned ${result.structuredContent.length} items]`,
);
}
// content is what the model reads.
toolResults.push({
type: "tool_result",
tool_use_id: toolUse.id,
content: result.content as ToolResultBlockParam["content"],
is_error: result.isError === true,
});
}