quickstart-resources/mcp-client-typescript/index.ts
Ola Hungerford 43927228cc
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>
2026-08-17 22:20:07 +02:00

252 lines
6.8 KiB
TypeScript

import { Anthropic } from "@anthropic-ai/sdk";
import {
ContentBlockParam,
MessageParam,
Tool,
ToolResultBlockParam,
ToolUseBlock,
} from "@anthropic-ai/sdk/resources/messages/messages.mjs";
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-5";
const MAX_TOOL_TURNS = 10;
class MCPClient {
private mcp: Client;
private _anthropic: Anthropic | null = null;
private transport: StdioClientTransport | null = null;
private tools: Tool[] = [];
constructor() {
// '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 {
// Lazy-initialize Anthropic client when needed
return this._anthropic ??= new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
}
async connectToServer(serverScriptPath: string) {
/**
* Connect to an MCP server
*
* @param serverScriptPath - Path to the server script (.py or .js)
*/
try {
// Determine script type and appropriate command
const isJs = serverScriptPath.endsWith(".js");
const isPy = serverScriptPath.endsWith(".py");
if (!isJs && !isPy) {
throw new Error("Server script must be a .js or .py file");
}
const command = isPy
? process.platform === "win32"
? "python"
: "python3"
: process.execPath;
// Initialize transport and connect to server
this.transport = new StdioClientTransport({
command,
args: [serverScriptPath],
});
await this.mcp.connect(this.transport);
// List available tools
const toolsResult = await this.mcp.listTools();
this.tools = toolsResult.tools.map((tool) => {
return {
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
};
});
console.log(
"Connected to server with tools:",
this.tools.map(({ name }) => name),
);
} catch (e) {
console.log("Failed to connect to MCP server: ", e);
throw e;
}
}
async processQuery(query: string) {
/**
* Process a query using Claude and available tools
*
* @param query - The user's input query
* @returns Processed response as a string
*/
const messages: MessageParam[] = [
{
role: "user",
content: query,
},
];
let response = await this.anthropic.messages.create({
model: ANTHROPIC_MODEL,
max_tokens: 1000,
messages,
tools: this.tools,
});
const finalText: string[] = [];
for (let turn = 0; turn < MAX_TOOL_TURNS; turn++) {
const toolUses: ToolUseBlock[] = [];
for (const block of response.content) {
if (block.type === "text") {
finalText.push(block.text);
} else if (block.type === "tool_use") {
toolUses.push(block);
}
}
if (toolUses.length === 0) {
return finalText.join("\n");
}
const toolResults: ToolResultBlockParam[] = [];
for (const toolUse of toolUses) {
const toolArgs = toolUse.input as { [x: string]: unknown } | undefined;
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,
});
}
messages.push({
role: "assistant",
content: response.content as unknown as ContentBlockParam[],
});
messages.push({ role: "user", content: toolResults });
response = await this.anthropic.messages.create({
model: ANTHROPIC_MODEL,
max_tokens: 1000,
messages,
tools: this.tools,
});
}
finalText.push(`[Stopped after ${MAX_TOOL_TURNS} tool-use turns]`);
return finalText.join("\n");
}
async chatLoop() {
/**
* Run an interactive chat loop
*/
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// rl.question() doesn't reject on stdin EOF on its own; wire its close
// event to an AbortSignal so EOF (Ctrl-D) and SIGINT both unblock it.
const ac = new AbortController();
const onClose = () => ac.abort();
rl.on("close", onClose);
const onSigint = () => rl.close();
process.once("SIGINT", onSigint);
try {
console.log("\nMCP Client Started!");
console.log("Type your queries or 'quit' to exit.");
while (true) {
let message: string;
try {
message = await rl.question("\nQuery: ", { signal: ac.signal });
} catch {
break;
}
if (message.toLowerCase() === "quit") break;
try {
const response = await this.processQuery(message);
console.log("\n" + response);
} catch (e) {
console.log(`\nError: ${e instanceof Error ? e.message : String(e)}`);
}
}
} finally {
process.off("SIGINT", onSigint);
rl.off("close", onClose);
rl.close();
}
}
async cleanup() {
/**
* Clean up resources
*/
await this.mcp.close();
}
}
async function main() {
if (process.argv.length < 3) {
console.log("Usage: node build/index.js <path_to_server_script>");
return;
}
const mcpClient = new MCPClient();
try {
await mcpClient.connectToServer(process.argv[2]);
// Check if we have a valid API key to continue
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
console.log(
"\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:"
);
console.log(" export ANTHROPIC_API_KEY=your-api-key-here");
return;
}
await mcpClient.chatLoop();
} catch (e) {
console.error("Error:", e);
await mcpClient.cleanup();
process.exit(1);
} finally {
await mcpClient.cleanup();
process.exit(0);
}
}
main();