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
8 changed files with 277 additions and 2253 deletions

View file

@ -1,3 +1,11 @@
# An LLM-Powered Chatbot MCP Client written in TypeScript
See the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial for more information.
## Structured content
The SDK validates every result against the tool's declared `outputSchema`, so the spec's client-side SHOULD needs no code here.
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).
`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/).

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,
});
}

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,7 @@
"type": "module",
"dependencies": {
"@anthropic-ai/sdk": "^0.36.3",
"@modelcontextprotocol/sdk": "^1.26.0",
"@modelcontextprotocol/client": "^2.0.0",
"dotenv": "^16.4.7"
},
"devDependencies": {
@ -20,6 +20,6 @@
"typescript": "^5.7.3"
},
"engines": {
"node": ">=16.0.0"
"node": ">=24.0.0"
}
}

View file

@ -1,3 +1,9 @@
# A Simple MCP weather Server written in TypeScript
See the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial for more information.
## 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.
`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/).

File diff suppressed because it is too large Load diff

View file

@ -21,6 +21,10 @@
"typescript": "^5.9.3"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.24.3"
"@modelcontextprotocol/server": "^2.0.0",
"zod": "^4.4.3"
},
"engines": {
"node": ">=24.0.0"
}
}

View file

@ -1,6 +1,6 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";
const NWS_API_BASE = "https://api.weather.gov";
const USER_AGENT = "weather-app/1.0";
@ -29,31 +29,18 @@ interface AlertFeature {
event?: string;
areaDesc?: string;
severity?: string;
status?: string;
headline?: string;
description?: string;
instruction?: string;
};
}
// Format alert data
function formatAlert(feature: AlertFeature): string {
const props = feature.properties;
return [
`Event: ${props.event || "Unknown"}`,
`Area: ${props.areaDesc || "Unknown"}`,
`Severity: ${props.severity || "Unknown"}`,
`Status: ${props.status || "Unknown"}`,
`Headline: ${props.headline || "No headline"}`,
"---",
].join("\n");
}
interface ForecastPeriod {
name?: string;
temperature?: number;
temperatureUnit?: string;
windSpeed?: string;
windDirection?: string;
shortForecast?: string;
detailedForecast?: string;
}
interface AlertsResponse {
@ -72,163 +59,190 @@ interface ForecastResponse {
};
}
// Create server instance
const server = new McpServer({
name: "weather",
version: "1.0.0",
/**
* 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.
*/
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"),
}),
);
/** The output schema of `get-forecast`: the object case. */
const forecastOutputSchema = z.object({
latitude: z.number().describe("Latitude the forecast is for"),
longitude: z.number().describe("Longitude the forecast is for"),
periods: z
.array(
z.object({
name: z.string(),
temperature: z.number().nullable(),
temperature_unit: z.string(),
wind_speed: z.string(),
wind_direction: z.string(),
detailed_forecast: z.string(),
}),
)
.describe("The forecast periods, soonest first"),
});
// Register weather tools
server.registerTool(
"get-alerts",
{
title: "Get Weather Alerts",
description: "Get weather alerts for a state",
inputSchema: {
state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"),
},
},
async ({ state }) => {
const stateCode = state.toUpperCase();
const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
type Alert = z.infer<typeof alertsOutputSchema>[number];
type Forecast = z.infer<typeof forecastOutputSchema>;
if (!alertsData) {
return {
content: [
{
type: "text",
text: "Failed to retrieve alerts data",
},
],
};
}
const features = alertsData.features || [];
if (features.length === 0) {
return {
content: [
{
type: "text",
text: `No active alerts for ${stateCode}`,
},
],
};
}
const formattedAlerts = features.map(formatAlert);
const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
return {
content: [
{
type: "text",
text: alertsText,
},
],
};
},
);
server.registerTool(
"get-forecast",
{
title: "Get Weather Forecast",
description: "Get weather forecast for a location",
inputSchema: {
latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
longitude: z
.number()
.min(-180)
.max(180)
.describe("Longitude of the location"),
},
},
async ({ latitude, longitude }) => {
// Get grid point data
const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
if (!pointsData) {
return {
content: [
{
type: "text",
text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
},
],
};
}
const forecastUrl = pointsData.properties?.forecast;
if (!forecastUrl) {
return {
content: [
{
type: "text",
text: "Failed to get forecast URL from grid point data",
},
],
};
}
// Get forecast data
const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
if (!forecastData) {
return {
content: [
{
type: "text",
text: "Failed to retrieve forecast data",
},
],
};
}
const periods = forecastData.properties?.periods || [];
if (periods.length === 0) {
return {
content: [
{
type: "text",
text: "No forecast periods available",
},
],
};
}
// Format forecast periods
const formattedForecast = periods.map((period: ForecastPeriod) =>
[
`${period.name || "Unknown"}:`,
`Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
`Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
`${period.shortForecast || "No forecast available"}`,
"---",
].join("\n"),
);
const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
return {
content: [
{
type: "text",
text: forecastText,
},
],
};
},
);
// Start the server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Weather MCP Server running on stdio");
// Format alert data for the model to read
function formatAlert(alert: Alert): string {
return [
`Event: ${alert.event}`,
`Area: ${alert.area}`,
`Severity: ${alert.severity}`,
`Description: ${alert.description}`,
`Instructions: ${alert.instructions}`,
"---",
].join("\n");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
function formatPeriod(period: Forecast["periods"][number]): string {
return [
`${period.name}:`,
period.temperature === null
? "Temperature: Unknown"
: `Temperature: ${period.temperature}°${period.temperature_unit}`,
`Wind: ${period.wind_speed} ${period.wind_direction}`,
period.detailed_forecast,
"---",
].join("\n");
}
function buildServer(): McpServer {
const server = new McpServer({
name: "weather",
version: "1.0.0",
});
server.registerTool(
"get-alerts",
{
title: "Get Weather Alerts",
description: "Get weather alerts for a state",
inputSchema: z.object({
state: z
.string()
.length(2)
.describe("Two-letter state code (e.g. CA, NY)"),
}),
outputSchema: alertsOutputSchema,
},
async ({ state }) => {
const stateCode = state.toUpperCase();
const alertsUrl = `${NWS_API_BASE}/alerts/active/area/${stateCode}`;
const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
if (!alertsData) {
throw new Error(`Failed to retrieve alerts data for ${stateCode}`);
}
// An empty result is an empty array, 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) => ({
event: feature.properties.event ?? "Unknown",
area: feature.properties.areaDesc ?? "Unknown",
severity: feature.properties.severity ?? "Unknown",
description: feature.properties.description ?? "No description available",
instructions:
feature.properties.instruction ?? "No specific instructions provided",
}));
const text =
alerts.length === 0
? `No active alerts for ${stateCode}`
: `Active alerts for ${stateCode}:\n\n${alerts.map(formatAlert).join("\n")}`;
return { content: [{ type: "text", text }], structuredContent: alerts };
},
);
server.registerTool(
"get-forecast",
{
title: "Get Weather Forecast",
description: "Get weather forecast for a location",
inputSchema: z.object({
latitude: z
.number()
.min(-90)
.max(90)
.describe("Latitude of the location"),
longitude: z
.number()
.min(-180)
.max(180)
.describe("Longitude of the location"),
}),
outputSchema: forecastOutputSchema,
},
async ({ latitude, longitude }) => {
// Get grid point data
const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
if (!pointsData) {
throw new Error(
`Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
);
}
const forecastUrl = pointsData.properties?.forecast;
if (!forecastUrl) {
throw new Error("Failed to get forecast URL from grid point data");
}
// Get forecast data
const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
if (!forecastData) {
throw new Error("Failed to retrieve forecast data");
}
const rawPeriods = forecastData.properties?.periods ?? [];
if (rawPeriods.length === 0) {
throw new Error("No forecast periods available");
}
const forecast: Forecast = {
latitude,
longitude,
// Only show the next 5 periods.
periods: rawPeriods.slice(0, 5).map((period) => ({
name: period.name ?? "Unknown",
temperature: period.temperature ?? null,
temperature_unit: period.temperatureUnit ?? "F",
wind_speed: period.windSpeed ?? "Unknown",
wind_direction: period.windDirection ?? "Unknown",
detailed_forecast: period.detailedForecast ?? "No forecast available",
})),
};
const text = `Forecast for ${latitude}, ${longitude}:\n\n${forecast.periods
.map(formatPeriod)
.join("\n")}`;
return { content: [{ type: "text", text }], structuredContent: forecast };
},
);
return server;
}
// One factory serves both protocol eras.
serveStdio(buildServer, {
onerror: (error) => {
console.error("Weather MCP Server error:", error);
},
});
console.error("Weather MCP Server running on stdio");