Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/advanced/low-level-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Call it and the result carries both representations:

The `_meta` block is the server's identity stamp: the SDK adds it to every 2026-era result, with the `version` from the constructor (a server that sets none reports an empty string). A server that must not identify itself can strip the key with a middleware, which owns the results it returns.

The server never compares the two fields. This SDK's `Client` does: return `structured_content` that doesn't satisfy the `output_schema` you declared and `call_tool` raises a `RuntimeError` that starts with `Invalid structured content returned by tool search_books` and goes on to quote the `jsonschema` failure. Promising a schema is cheap; keeping it is on you. The whole ladder of return types and schemas is in **[Structured Output](../servers/structured-output.md)**.
The server never compares the two fields, and neither does this SDK's `Client`: `call_tool` hands back `structured_content` exactly as the server sent it. Promising a schema is cheap; keeping it is on you. The whole ladder of return types and schemas is in **[Structured Output](../servers/structured-output.md)**.

## The dialect is JSON Schema 2020-12

Expand All @@ -126,7 +126,7 @@ The server never compares the two fields. This SDK's `Client` does: return `stru
```

* The root of `input_schema` must be `"type": "object"`. Beside it, `oneOf`, `additionalProperties`, `anyOf`, `if`/`then`/`else`, `prefixItems`, `$defs` with local `$ref`s and the rest of the 2020-12 keywords reach the client exactly as written.
* No `$schema` key is needed. Add one only to opt into an older draft: this SDK's `Client`, which validates `structured_content` against a tool's `output_schema`, picks its validator from `$schema` and uses 2020-12 when there is none.
* No `$schema` key is needed. Add one only to opt into an older draft.

## `_meta`: for the application, not the model

Expand Down
17 changes: 16 additions & 1 deletion docs/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,22 @@ That is why `main` narrows with `isinstance(block, TextContent)` before touching

### `structured_content`: what your application reads

`structured_content` is the tool's return value as JSON, matching the tool's declared `output_schema`. No string parsing, no guessing.
`structured_content` is the tool's return value as JSON, shaped by the tool's declared `output_schema`. No string parsing, no guessing.

The client hands it to you exactly as the server sent it; it does not check it against the `output_schema`. The server writes both, so only a model you own says what your code can rely on:

```python
from pydantic import BaseModel


class Book(BaseModel):
title: str
author: str
year: int


book = Book.model_validate(result.structured_content)
```

When both are present they say the same thing twice on purpose: `content` is for a model, `structured_content` is for code. Where the structured half comes from, and how to control it, is the **[Structured Output](../servers/structured-output.md)** page.

Expand Down
1 change: 1 addition & 0 deletions docs/deprecated.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ These are not spec changes, only SDK usage with a better replacement. They warn

| Deprecated | What you do instead |
|---|---|
| `ClientSession.validate_tool_result()` | Nothing: it no longer does anything. Validate `result.structured_content` against a model you own, such as `Book.model_validate(result.structured_content)` (see **[Clients](client/index.md#structured_content-what-your-application-reads)**). |
| `FuncMetadata.call_fn_with_arg_validation()` | `FuncMetadata.validate_arguments()` and then `FuncMetadata.call_fn()`. Only code that drives `FuncMetadata` directly (a custom `Tool` subclass, say) ever called it. |
| `AuthSettings(resource_server_url=...)` without `validate_token_resource=` | Set it: `True` has the server refuse bearer tokens your verifier does not report as issued for `resource_server_url`, `False` says your verifier checks the token's audience itself (see **[Authorization](run/authorization.md#a-token-verifier)**). Unset behaves as `False`; 3.0 makes `True` the default whenever `resource_server_url` is set. |
| `ClientCredentialsOAuthProvider(...)` or `PrivateKeyJWTOAuthProvider(...)` without `issuer=` | Pass `issuer=` naming the authorization server that issued the credentials (see **[Writing OAuth clients](client/oauth-clients.md#machine-to-machine)**). Without it the MCP server decides which authorization server receives them; 3.0 makes the keyword required. |
Expand Down
1 change: 0 additions & 1 deletion docs/get-started/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ You don't need to know any of this to use the SDK, but if you're wondering what
* [`pydantic`](https://docs.pydantic.dev/): what every `mcp.types` model is built on, plus all schema generation and validation.
* [`httpx2`](https://pypi.org/project/httpx2/): the HTTP client behind the Streamable HTTP and SSE *client* transports, with server-sent events support built in.
* [`starlette`](https://www.starlette.io/), [`uvicorn`](https://www.uvicorn.org/), [`sse-starlette`](https://pypi.org/project/sse-starlette/), and [`python-multipart`](https://pypi.org/project/python-multipart/): the HTTP *server* transports.
* [`jsonschema`](https://pypi.org/project/jsonschema/): validates a tool's structured output against its declared output schema.
* [`pyjwt[crypto]`](https://pyjwt.readthedocs.io/): OAuth token handling for authorization.
* [`opentelemetry-api`](https://opentelemetry-python.readthedocs.io/): just the lightweight API, so the SDK's tracing middleware costs nothing unless you install an OpenTelemetry SDK and exporter yourself.
* [`typing-extensions`](https://typing-extensions.readthedocs.io/) and [`typing-inspection`](https://pypi.org/project/typing-inspection/): modern typing features on Python 3.11.
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ dependencies = [
"python-multipart>=0.0.9",
"sse-starlette>=3.0.0",
"uvicorn>=0.31.1; sys_platform != 'emscripten'",
"jsonschema>=4.20.0",
"pywin32>=312; sys_platform == 'win32' and python_version >= '3.15'",
"pywin32>=311; sys_platform == 'win32' and python_version < '3.15'",
"pyjwt[crypto]>=2.10.1",
Expand Down
6 changes: 1 addition & 5 deletions src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,14 +857,10 @@ async def retry(r: InputResponses | None, s: str | None) -> CallToolResult | Inp
return result
# Only claimed shapes reach this point, so the lookup is total.
claim = self._folded_extensions.by_model[type(result)]
final = await claim.resolve(
return await claim.resolve(
result,
ClaimContext(session=self.session, tool_name=name, read_timeout_seconds=read_timeout_seconds),
)
if not final.is_error:
# Match the direct path: revalidate the output schema, but never for isError results.
await self.session.validate_tool_result(name, final)
return final

async def list_prompts(
self,
Expand Down
106 changes: 9 additions & 97 deletions src/mcp/client/session.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from __future__ import annotations

import json
import logging
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from functools import cache, reduce
from operator import or_
from types import TracebackType, UnionType
from typing import TYPE_CHECKING, Annotated, Any, Final, Literal, Protocol, Self, TypeAlias, cast, get_args, overload
from typing import Annotated, Any, Final, Literal, Protocol, Self, TypeAlias, cast, get_args, overload

import anyio
import anyio.abc
Expand Down Expand Up @@ -59,11 +58,6 @@
from mcp.shared.subscriptions import SUBSCRIPTION_ID_META_KEY, event_from_wire
from mcp.shared.transport_context import TransportContext

if TYPE_CHECKING:
# `jsonschema` is imported lazily inside `validate_tool_result`: pulling it (and its
# `attrs`/`referencing` tree) in at module scope costs every client that never validates.
from jsonschema.protocols import Validator

DEFAULT_CLIENT_INFO = types.Implementation(name="mcp", version="0.1.0")
DISCOVER_TIMEOUT_SECONDS = 10.0
_NOTIFICATION_QUEUE_SIZE: Final = 256
Expand Down Expand Up @@ -110,17 +104,6 @@ def _later_revision_fields(method: str, version: str) -> frozenset[str]:
return frozenset(later) - _wire_fields(current)


def _same_schema(a: dict[str, Any] | None, b: dict[str, Any] | None) -> bool:
"""JSON equality for two output schemas.

Python `==` is not JSON equality: it conflates `True`/`1` and `False`/`0`, which JSON
Schema keeps distinct (`const: true` vs `const: 1`). Canonical serialization compares as
JSON does; where it is stricter (`1` vs `1.0`), erring toward "changed" only costs a
recompile, never a stale validator.
"""
return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)


def _preconnect_stamp(data: dict[str, Any], opts: CallOptions) -> None:
# initialize/discover forbid cancellation; other pre-handshake requests (lowlevel
# ClientSession callers may skip the handshake entirely) keep the courtesy cancel.
Expand Down Expand Up @@ -437,10 +420,8 @@ def __init__(
self._logging_callback = logging_callback or _default_logging_callback
self._log_level: types.LoggingLevel | None = log_level
self._message_handler = message_handler or _default_message_handler
# Unused here; downstream clients such as FastMCP read it to build typed tool results.
self._tool_output_schemas: dict[str, dict[str, Any] | None] = {}
# Compiled output-schema validators, derived from `_tool_output_schemas` and owned by
# `_absorb_tool_listing`, which evicts a tool's entry whenever its schema changes.
self._tool_output_validators: dict[str, Validator] = {}
self._x_mcp_header_maps: dict[str, dict[tuple[str, ...], str]] = {}
self._initialize_result: types.InitializeResult | None = None
self._discover_result: types.DiscoverResult | None = None
Expand Down Expand Up @@ -1098,9 +1079,6 @@ async def call_tool(
progress_callback=progress_callback,
)

if isinstance(result, types.CallToolResult) and not result.is_error:
await self.validate_tool_result(name, result)

# The input_required arm stays first; a claimed shape is terminal for the multi-round-trip driver.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Direct ClientSession.call_tool callers on 2026-07-28 HTTP can now get HEADER_MISMATCH for tools with x-mcp-header arguments that worked before. The implicit tools/list removed here was also what filled _x_mcp_header_maps after a first successful call. Without it _resolve_param_headers (session.py:1089) sends no Mcp-Param-* headers until the caller lists tools. Fix: make Mcp-Param-* headers available for a called tool without an explicit listing, e.g. give ClientSession.call_tool the re-list-and-resend recovery at client.py:843, or document that list_tools() must come first. [also at: src/mcp/client/session.py:1080 - Code that calls ClientSession.call_tool directly on a 2026-07-28 HTTP connection can now get HEADER_MISMATCH for x-mcp-header tools where the base recovered by itself.; src/mcp/client/client.py:853 - Client users on a 2026-07-28 HTTP connection now hit a rejected call, a re-list and a resend for some calls that succeeded in one round trip on the base.; +1 more]

Why this was flagged

A caller holds a ClientSession on a 2026-07-28 Streamable HTTP connection, never calls list_tools(), calls tool A, then calls tool B whose input schema marks an argument x-mcp-header. On the base, A's non-error result ran validate_tool_result, whose await self.list_tools() went through _absorb_tool_listing and set self._x_mcp_header_maps[tool.name] (src/mcp/client/session.py:1227) for every listed tool, so B's call carried its header. After the change nothing lists tools, _resolve_param_headers returns {} (src/mcp/client/session.py:1092-1093), and the server rejects B with HEADER_MISMATCH "header is missing but the request body's ... argument is present" (src/mcp/shared/inbound.py:579-583). ClientSession.call_tool has no retry, so the caller gets an MCPError where the base returned the result. Client.call_tool recovers via _relist_tool (src/mcp/client/client.py:843-853) but pays one rejected tools/call the base did not.

Verification: _x_mcp_header_maps is written in only one place, _absorb_tool_listing (src/mcp/client/session.py:1227). _resolve_param_headers (lines 1089-1094) returns {} when the tool has no cached map. ClientSession.call_tool has no recovery. So on the base, call A then call B (annotated argument) succeeded; on head, B is rejected with HEADER_MISMATCH.

Finding ID: f-748c4898

if isinstance(result, types.InputRequiredResult) and not allow_input_required:
raise _input_required_unexpected("call_tool")
Expand All @@ -1115,72 +1093,13 @@ def _resolve_param_headers(self, name: str, arguments: Mapping[str, Any]) -> dic
return {}
return mcp_param_headers(header_map, arguments)

@deprecated(
"The client no longer validates tool results against the server's output schema; "
"validate `structured_content` against your own model instead.",
category=MCPDeprecationWarning,
)
async def validate_tool_result(self, name: str, result: types.CallToolResult) -> None:
"""Revalidate a `CallToolResult` against the tool's declared output schema.

Raises:
RuntimeError: Structured content is missing or does not conform to the schema, or the
schema is invalid or has a `$ref` that does not resolve within the schema document.
"""
if name not in self._tool_output_schemas:
# refresh output schema cache
await self.list_tools()

output_schema = None
if name in self._tool_output_schemas:
output_schema = self._tool_output_schemas.get(name)
else:
logger.warning(f"Tool {name} not listed by server, cannot validate any structured content")

if output_schema is not None:
from jsonschema import exceptions as jsonschema_exceptions
from referencing.exceptions import Unresolvable

if result.structured_content is None and "structured_content" not in result.model_fields_set:
raise RuntimeError(f"Tool {name} has an output schema but did not return structured content")
validator = self._output_schema_validator(name, output_schema)
# `best_match` picks the same error the previous `jsonschema.validate()` call raised,
# so the message a caller sees is unchanged. It is untyped upstream.
errors = validator.iter_errors(result.structured_content)
try:
error = cast(
"Exception | None",
jsonschema_exceptions.best_match(errors), # pyright: ignore[reportUnknownMemberType]
)
except Unresolvable as e:
# A `$ref` did not resolve within the schema document.
raise RuntimeError(f"Invalid schema for tool {name}: {e}") from e
if error is not None:
raise RuntimeError(f"Invalid structured content returned by tool {name}: {error}") from error

def _output_schema_validator(self, name: str, output_schema: dict[str, Any]) -> Validator:
"""Compiled validator for the tool's cached output schema, built once per schema value.

Compiling is ~60x the cost of validating, so a one-shot `jsonschema.validate()` per
result dominates `call_tool`; the compiled validator is cached instead. It stays valid
because `_absorb_tool_listing` evicts a tool's validator whenever it absorbs a different
schema for that tool, so a cached entry always matches `output_schema`.

Raises:
RuntimeError: The schema is not a valid JSON Schema. Raised on every call, since a
failed compile is never cached.
"""
from jsonschema import SchemaError
from jsonschema.validators import validator_for
from referencing import Registry

if (validator := self._tool_output_validators.get(name)) is not None:
return validator

validator_cls = validator_for(output_schema)
try:
validator_cls.check_schema(output_schema)
except SchemaError as e:
raise RuntimeError(f"Invalid schema for tool {name}: {e}")
# An explicit empty registry: `$ref`s resolve within the schema document and the bundled metaschemas.
validator = validator_cls(output_schema, registry=Registry())
self._tool_output_validators[name] = validator
return validator
"""Does nothing. The client no longer validates tool results against the server's output schema."""
Comment on lines +1096 to +1102

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Callers upgrading within 2.x silently lose a check: schema-violating structured_content is now returned instead of raising RuntimeError. AGENTS.md says a change to a released API's observable behaviour, even behind a @ deprecated shim, is an explicit maintainer decision and should generally be avoided. validate_tool_result at session.py:1101 keeps its name but accepts everything, so code using it as a gate fails open. Fix: keep validate_tool_result validating (jsonschema as an optional import with a clear error when absent), or record the maintainer decision for both it and call_tool. [also at: src/mcp/client/session.py:1096 - nit: AGENTS.md (Branching Model) says a change to an existing 2.x API's observable behaviour, even one softened by a @ deprecated shim, is a design decision a maintainer makes explicitly and should generally be avoided.]

Why this was flagged

Trigger: a 2.x application calls ClientSession.call_tool / Client.call_tool on a tool whose listed output_schema the result violates or whose result has no structuredContent, or calls the public ClientSession.validate_tool_result(name, result) directly as a gate. On the base, session.py raised RuntimeError("Invalid structured content returned by tool ...") or "Tool ... has an output schema but did not return structured content", and the claim path in client.py revalidated the resolver product. After the change session.py:1080-1087 returns the result unchecked, client.py:860 returns claim.resolve(...) directly, and session.py:1101-1102 is an empty body that only emits MCPDeprecationWarning. The caller's except RuntimeError branch never runs and malformed data flows on as if validated. The @ deprecated shim does not prevent this: it warns but still returns None, the same value a passing validation returned.

Verification: src/mcp/client/session.py:1096-1102 is a @ deprecated(..., category=MCPDeprecationWarning) method whose body is only the docstring "Does nothing." A tool lists {"x": integer, required} and returns {"x": "no"}. On the base, call_tool raises RuntimeError; on the head, the result is returned and the bad value reaches application code. Callers of call_tool get no signal at all.

Finding ID: f-f4472c1d


async def list_prompts(self, *, params: types.PaginatedRequestParams | None = None) -> types.ListPromptsResult:
"""Send a prompts/list request.
Expand Down Expand Up @@ -1309,14 +1228,8 @@ def _absorb_tool_listing(self, result: types.ListToolsResult, *, complete: bool)
kept.append(tool)
result.tools = kept

# Cache tool output schemas for future validation; cursor pages only ever add. A
# changed schema evicts its compiled validator; an unchanged one (a re-listing, or the
# response cache re-absorbing a served hit) keeps it. Only validated tools pay the check.
# Cursor pages only ever add.
for tool in result.tools:
if tool.name in self._tool_output_validators and not _same_schema(
self._tool_output_schemas.get(tool.name), tool.output_schema
):
del self._tool_output_validators[tool.name]
self._tool_output_schemas[tool.name] = tool.output_schema

if complete:
Expand All @@ -1325,7 +1238,6 @@ def _absorb_tool_listing(self, result: types.ListToolsResult, *, complete: bool)
names = {tool.name for tool in result.tools}
self._x_mcp_header_maps = {k: v for k, v in self._x_mcp_header_maps.items() if k in names}
self._tool_output_schemas = {k: v for k, v in self._tool_output_schemas.items() if k in names}
self._tool_output_validators = {k: v for k, v in self._tool_output_validators.items() if k in names}

return result

Expand Down
4 changes: 0 additions & 4 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,16 +673,12 @@ async def test_a_complete_listing_prunes_per_tool_state_for_tools_it_no_longer_c
with anyio.fail_after(5):
async with Client(server) as client:
await client.session.list_tools()
# Compile the retired tool's output-schema validator so its eviction is observable.
await client.session.validate_tool_result("retired", CallToolResult(content=[], structured_content={}))
assert set(client.session._x_mcp_header_maps) == {"retired", "survivor"}
assert set(client.session._tool_output_schemas) == {"retired", "survivor"}
assert set(client.session._tool_output_validators) == {"retired"}

await client.session.list_tools()
assert set(client.session._x_mcp_header_maps) == {"survivor"}
assert set(client.session._tool_output_schemas) == {"survivor"}
assert client.session._tool_output_validators == {}


async def test_a_complete_listing_prunes_output_schemas_on_a_legacy_session_too() -> None:
Expand Down
Loading
Loading