Add structured content to the Python weather server and client and update to v2 - #164
Add structured content to the Python weather server and client and update to v2#164olaservo wants to merge 5 commits into
Conversation
0eac5ce to
704cea2
Compare
Both tools declare an output schema - the return type annotation - and return
structured_content alongside the text.
get_alerts 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.
The detail worth reading the source for: Alerts is a RootModel[list[Alert]],
not a plain list[Alert]. A list is not a JSON object, so the SDK wraps it as
{"result": [...]} and advertises an object-rooted schema to match, with no
opt-out. A RootModel is a BaseModel, so it is taken as the schema exactly as
written, and a RootModel over a list serializes as the bare list.
Error paths raise: a tool declaring an output schema MUST return conforming
structured content, so a path with no data has to fail.
The client moves to the 2.0 Client API with mode="auto" and prints the
negotiated version on connect. call_tool already revalidates every non-error
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,
structured_content is used as data, reporting how many items came back.
This clears the staleness modelcontextprotocol#3124 flags against this
repository - weather.py imported mcp.server.fastmcp, client.py held the
ClientSession version - and matches that PR's idioms: the short
"from mcp.server import MCPServer" spelling, httpx2 with httpx dropped from
the dependencies since httpx2>=2.5.0 is a hard dependency of mcp,
result.content narrowed to TextContent, and input() on a worker thread.
Requires mcp 2.0.0b2; pyproject.toml sets [tool.uv] prerelease = "allow" so
plain uv run and uv sync work without flags. Model identifier moves to
claude-sonnet-5.
Note that an array-rooted schema only works on a 2026-07-28 connection. This
SDK does not project it down for older clients; it raises server-side instead.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
704cea2 to
c76c52e
Compare
There was a problem hiding this comment.
Pull request overview
Updates the Python weather MCP server and client to MCP SDK v2 (protocol revision 2026-07-28) and adds explicit structured output via declared outputSchema / structuredContent, including an array-rooted schema for get_alerts.
Changes:
- Migrates the Python weather server to
MCPServer, switches HTTP stack usage tohttpx2, and returns Pydantic-typed structured results (array root for alerts, object root for forecast). - Migrates the Python client to the v2
ClientAPI withmode="auto"version negotiation and usesstructured_contentas app data while forwarding only text blocks fromcontentto the model. - Updates Python project config/locks and docs to allow prereleases (
uvprerelease mode) and document structured output behavior.
Reviewed changes
Copilot reviewed 6 out of 8 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| weather-server-python/weather.py | Moves to MCP SDK v2 server API and returns structured Pydantic models (including array-root alerts). |
| weather-server-python/uv.lock | Updates locked deps for MCP 2.0 prerelease and enables prerelease mode. |
| weather-server-python/README.md | Documents structured output behavior and protocol requirements. |
| weather-server-python/pyproject.toml | Pins mcp[cli]>=2.0.0b2 and configures uv prerelease allowance. |
| mcp-client-python/client.py | Migrates to v2 Client with auto negotiation; forwards only text content and uses structured content as data. |
| mcp-client-python/uv.lock | Updates locked deps for MCP 2.0 prerelease and enables prerelease mode. |
| mcp-client-python/README.md | Documents structured output usage and version negotiation behavior. |
| mcp-client-python/pyproject.toml | Pins mcp>=2.0.0b2 and configures uv prerelease allowance. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
The SDK left beta on 2026-07-28, so the pins move off 2.0.0b2 and both projects drop `[tool.uv] prerelease = allow` — plain `uv run` works now. Also from review: declare the imports rather than lean on transitive resolution. weather.py imports httpx2 and client.py imports mcp_types, so both are listed explicitly. 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>
`dict.get(key, default)` returns the default only when the key is absent. The
NWS API sends these fields as explicit nulls instead of omitting them, so
`props.get(instruction, ...)` passed None straight into a `str` field and
Pydantic rejected the whole result.
One alert in eight for TX is a Special Weather Statement with a null
instruction, which was enough to fail the entire call:
Error executing tool get_alerts: 1 validation error for Alert
instructions
Input should be a valid string [type=string_type, input_value=None]
The smoke test missed it twice over: it calls get_alerts with CA, whose
alerts happen to have no nulls today, and it reports an isError result as a
skip rather than a failure.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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>
|
|
||
| response = self.anthropic.messages.create( | ||
| model=ANTHROPIC_MODEL, | ||
| max_tokens=1000, |
There was a problem hiding this comment.
Since we are switching to Sonnet 5 above, which uses adaptive thinking, I suggest that we reconsider this value (see https://platform.claude.com/docs/en/about-claude/models/whats-new-sonnet-5). Let's maybe make it 10,000 here?
Otherwise we can diasble adaptive thinking.
| temperature_unit: str | ||
| wind_speed: str | ||
| wind_direction: str | ||
| detailed_forecast: str |
There was a problem hiding this comment.
Let's add descriptions here as well? For example:
name: str = Field(description="Label for the period, e.g. Tonight or Tuesday")
temperature: int = Field(description="Forecast temperature")
temperature_unit: str = Field(description="Unit of the temperature, F or C")
wind_speed: str = Field(description="Wind speed, e.g. 10 to 15 mph")
wind_direction: str = Field(description="Wind direction as a compass point")
detailed_forecast: str = Field(description="Prose description of the period")
Brings the Python examples onto MCP SDK 2.0.0 and protocol revision
2026-07-28, and gives both tools a declaredoutputSchemawith matchingstructuredContent.This also clears the staleness that modelcontextprotocol/modelcontextprotocol#3124 flags against this repository. That PR modernises the Python in the tutorials and notes that the "complete code" they link to here had fallen behind:
weather.pyimportedmcp.server.fastmcp, which does not exist in v2, andclient.pystill held theClientSessionversion.get_alertsanswers with a top-level JSON array:[ { "event": "Flood Warning", "area": "La Salle County", ... }, { "event": "Heat Advisory", "area": "Wheeler County", ... } ]Through
2025-11-25anoutputSchemahad to be object-rooted, so a tool returning a list had to invent a key to hang it off.get_forecastreturns an object, for contrast.The bare array without dropping to the low-level API
Alertsis aRootModel[list[Alert]]rather than a plainlist[Alert]. Alist[...]annotation is silently wrapped as{"result": ...}, but_try_create_model_and_schematakes anyBaseModelsubclass as the schema verbatim andRootModelis one — so the ordinary@mcp.tool()decorator yields an array-rooted schema and a bare array.This is undocumented:
docs/servers/structured-output.mdstill presents the wrapper as unavoidable for a list return. It is the difference between Python being able to demonstrate this spec feature idiomatically and not, and it is worth a docs PR upstream.Other changes
Error paths raise. Once a tool declares an output schema it MUST return conforming structured content, so a path with no data to return has to fail rather than answer with a bare text result. "No alerts" is an empty array, not an error.
A null-field crash is fixed.
props.get("instruction", "…")supplies its default only when the key is absent, and NWS sends these fields as explicit nulls.Nonereached astrfield and Pydantic rejected the whole result, soget_alertsfailed outright for any state with such an alert — one Texas alert in eight was enough. All five fields now useor.The client negotiates. It moves to the 2.0
ClientAPI and passesmode="auto"— oneserver/discoverprobe, falling back to the2025-11-25handshake — and prints the negotiated version on connect.call_toolrevalidates non-error results against the declared schema, so the spec's client-side SHOULD needs no code here.Dependencies are declared rather than inherited.
weather.pyimportshttpx2andclient.pyimportsmcp_types, so both are listed explicitly instead of relying onmcppulling them in.httpxstays out —mcpdepends onhttpx2, and listinghttpxinstalls a second HTTP stack.Matched to modelcontextprotocol/modelcontextprotocol#3124 so the tutorials and this code agree: the short
from mcp.server import MCPServerspelling;TextContentnarrowing before forwarding content to the model API; andinput()moved onto a worker thread so it does not block the event loop.Verification
Captured off the raw wire — a real
get_alerts("TX")call against live NWS data, with no SDK on the client side, so this is literally what the server sends:structuredContentis a JSON array at the top level, not an object wrapping one. The single content block is the serialised JSON — the backwards-compatibility fallback the tools specification recommends for structured results.Driven through the client with a real API key on
mcp 2.0.0, the model calls the tool and answers from the structured result:The
8 itemsline comes fromstructured_content, not from re-reading the prose — the two channels going to their stated readers. That run also covers the null-field fix above: one of the eight is a Special Weather Statement with a nullinstruction, which is exactly the alert that failed before it.Related
One of a set bringing the examples onto
2026-07-28, one PR per language so the four can be compared: #164 (Python), #165 (TypeScript), #166 (Go), #167 (Rust), with #163 as the shared prerequisite — now merged, so the smoke test negotiates2026-07-28and CI here is green.The Ruby examples are not in the set. The
mcpgem 1.1.0 does now negotiate2026-07-28, but its server never emits theresultTypefield that the revision makes mandatory, so a spec-strict client rejects every response includingtools/list. That is an upstream fix, not something an example can work around.🤖 Generated with Claude Code