Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 37 additions & 2 deletions .github/actions/conformance/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,43 @@ async def run_http_invalid_tool_headers(server_url: str) -> None:
logger.exception(f"call_tool({tool.name!r}) failed")


def _stub_args_for_custom_headers(input_schema: dict[str, Any]) -> dict[str, Any]:
"""Arguments exercising every `x-mcp-header`-annotated property in a tool schema.

Each annotated property gets a type-appropriate value so the SDK mirrors it into an
`Mcp-Param-*` header; required properties without an annotation get a placeholder so
the call is well-formed.
"""
by_type: dict[str, Any] = {"string": "us-west1", "integer": 42, "boolean": False, "number": 3.14}
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
properties: dict[str, Any] = input_schema.get("properties", {})
arguments: dict[str, Any] = {}
for name, schema in properties.items():
if "x-mcp-header" in schema:
arguments[name] = by_type.get(schema.get("type"), "x")
for name in input_schema.get("required", []):
arguments.setdefault(name, by_type.get(properties.get(name, {}).get("type"), "x"))
return arguments


@register("http-custom-headers")
async def run_http_custom_headers(server_url: str) -> None:
"""List tools, then call each surfaced tool so its `x-mcp-header` args mirror into headers (SEP-2243).

A conforming client drops tools with invalid annotations during `list_tools` (e.g. the
harness's `number`-typed properties, which the spec forbids), so the loop only calls tools
whose annotations are valid; for those, the SDK emits the `Mcp-Param-*` headers the scenario
checks. Per-call failures are logged and skipped rather than aborting the run.
"""
async with Client(server_url, mode=client_mode()) as client:
listed = await client.list_tools()
logger.debug(f"Surfaced tools: {[t.name for t in listed.tools]}")
for tool in listed.tools:
try:
await client.call_tool(tool.name, _stub_args_for_custom_headers(tool.input_schema))
except Exception:
logger.exception(f"call_tool({tool.name!r}) failed")


@register("elicitation-sep1034-client-defaults")
async def run_elicitation_defaults(server_url: str) -> None:
"""Connect with elicitation callback that applies schema defaults."""
Expand Down Expand Up @@ -526,8 +563,6 @@ def main() -> None:
elif scenario.startswith("auth/"):
asyncio.run(run_auth_code_client(server_url))
else:
# Unhandled scenarios:
# - http-custom-headers (SEP-2243 / S8: Mcp-Param-* emission)
print(f"Unknown scenario: {scenario}", file=sys.stderr)
sys.exit(1)
else:
Expand Down
8 changes: 6 additions & 2 deletions .github/actions/conformance/expected-failures.2026-07-28.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@
# milestone.

client:
# SEP-2243 (HTTP standardization): no client Mcp-Param-* support yet — needs the
# tool-schema-cache vs per-call tool_definition design (S8).
# SEP-2243 (HTTP standardization): the client now mirrors x-mcp-header args into
# Mcp-Param-* headers (S8), but the harness fixture annotates `number`-typed
# properties, which the spec forbids ("Parameters with type number are not
# permitted"). The SDK drops those tools per spec, so the scenario's
# ClientSupportsCustomHeaders check (which requires the tool to be called)
# cannot pass until the harness fixture is corrected.
- http-custom-headers
# auth/enterprise-managed-authorization (SEP-990) is in the 2025 baseline but
# NOT here: the harness skips it as inapplicable at --spec-version 2026-07-28
Expand Down
8 changes: 6 additions & 2 deletions .github/actions/conformance/expected-failures.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@

client:
# --- Draft-spec scenarios (in `--suite draft`, also part of `--suite all`) ---
# SEP-2243 (HTTP standardization): no client Mcp-Param-* support yet — needs the
# tool-schema-cache vs per-call tool_definition design (S8).
# SEP-2243 (HTTP standardization): the client now mirrors x-mcp-header args into
# Mcp-Param-* headers (S8), but the harness fixture annotates `number`-typed
# properties, which the spec forbids ("Parameters with type number are not
# permitted"). The SDK drops those tools per spec, so the scenario's
# ClientSupportsCustomHeaders check (which requires the tool to be called)
# cannot pass until the harness fixture is corrected.
- http-custom-headers

# --- Pre-existing scenarios that fail on checks added after conformance 0.1.15 ---
Expand Down
4 changes: 4 additions & 0 deletions docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ For an in-process `Client(server)` (where `server` is a `Server` or `MCPServer`

For protocol 2026-07-28, a `tools/call` request may return an `InputRequiredResult` asking the client to supply additional input and retry. By default `call_tool` (on `ClientSession`, `Client`, and `ClientSessionGroup`) still returns `CallToolResult` and raises `RuntimeError` if the server requests input. Pass `allow_input_required=True` to receive the `InputRequiredResult` instead, then retry with `input_responses=` / `request_state=`.

### `call_tool` mirrors `x-mcp-header` arguments into `Mcp-Param-*` headers (SEP-2243)

For protocol 2026-07-28 over Streamable HTTP, a tool's input-schema property may carry an `x-mcp-header` annotation. When a tool the client has listed is called, each annotated argument is mirrored into an `Mcp-Param-<name>` request header (string verbatim, integer as decimal, boolean as `true`/`false`, base64-sentinel-wrapped when not header-safe; `null`/absent arguments are omitted). The argument is also left in the request body. `list_tools` caches a tool's annotations; if the client has not listed the tool, pass its definition via `call_tool(..., tool=...)` to enable mirroring without a prior `list_tools`. Other transports ignore the annotation.

### `McpError` renamed to `MCPError`

The `McpError` exception class has been renamed to `MCPError` for consistent naming with the MCP acronym style used throughout the SDK.
Expand Down
9 changes: 9 additions & 0 deletions src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
RequestParamsMeta,
ResourceTemplateReference,
ServerCapabilities,
Tool,
)
from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS, MODERN_PROTOCOL_VERSIONS
from typing_extensions import deprecated
Expand Down Expand Up @@ -387,6 +388,7 @@ async def call_tool(
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: Tool | None = None,
allow_input_required: Literal[False] = False,
) -> CallToolResult: ...

Expand All @@ -401,6 +403,7 @@ async def call_tool(
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: Tool | None = None,
allow_input_required: bool,
) -> CallToolResult | InputRequiredResult: ...

Expand All @@ -414,6 +417,7 @@ async def call_tool(
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: Tool | None = None,
allow_input_required: bool = False,
) -> CallToolResult | InputRequiredResult:
"""Call a tool on the server.
Expand All @@ -426,6 +430,10 @@ async def call_tool(
input_responses: Responses to a prior `InputRequiredResult.input_requests`
request_state: Opaque state echoed from a prior `InputRequiredResult`
meta: Additional metadata for the request
tool: The tool's definition, e.g. from an earlier `list_tools`. On a
modern (2026-07-28) connection its `x-mcp-header` annotations are
mirrored into `Mcp-Param-*` request headers; pass it when the
client has not listed the tool itself.
allow_input_required: When ``False`` (default), an `InputRequiredResult`
from the server raises `RuntimeError`; when ``True``, it is returned
so the caller can resolve the requests and retry.
Expand All @@ -448,6 +456,7 @@ async def call_tool(
input_responses=input_responses,
request_state=request_state,
meta=meta,
tool=tool,
allow_input_required=allow_input_required,
)

Expand Down
42 changes: 40 additions & 2 deletions src/mcp/client/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
NAME_BEARING_METHODS,
encode_header_value,
find_invalid_x_mcp_header,
mcp_param_headers,
x_mcp_header_map,
)
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
from mcp.shared.message import ClientMessageMetadata, SessionMessage
Expand Down Expand Up @@ -68,7 +70,10 @@ def stamp(data: dict[str, Any], opts: CallOptions) -> None:


def _make_modern_stamp(
protocol_version: str, client_info: dict[str, Any], capabilities: dict[str, Any]
protocol_version: str,
client_info: dict[str, Any],
capabilities: dict[str, Any],
resolve_param_headers: Callable[[str, Mapping[str, Any]], dict[str, str]],
) -> Callable[[dict[str, Any], CallOptions], None]:
def stamp(data: dict[str, Any], opts: CallOptions) -> None:
params = data.setdefault("params", {})
Expand All @@ -83,6 +88,8 @@ def stamp(data: dict[str, Any], opts: CallOptions) -> None:
name_key = NAME_BEARING_METHODS.get(data["method"])
if name_key is not None and isinstance(name := params.get(name_key), str):
headers[MCP_NAME_HEADER] = encode_header_value(name)
if data["method"] == "tools/call" and isinstance(name := params.get("name"), str):
headers.update(resolve_param_headers(name, params.get("arguments") or {}))

return stamp

Expand Down Expand Up @@ -215,6 +222,7 @@ def __init__(
self._logging_callback = logging_callback or _default_logging_callback
self._message_handler = message_handler or _default_message_handler
self._tool_output_schemas: dict[str, dict[str, Any] | None] = {}
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
self._negotiated_version: str | None = None
Expand Down Expand Up @@ -393,7 +401,7 @@ def adopt(self, result: types.InitializeResult | types.DiscoverResult) -> None:
)
client_info = self._client_info.model_dump(by_alias=True, mode="json", exclude_none=True)
capabilities = self._build_capabilities().model_dump(by_alias=True, mode="json", exclude_none=True)
self._stamp = _make_modern_stamp(mutual[-1], client_info, capabilities)
self._stamp = _make_modern_stamp(mutual[-1], client_info, capabilities, self._resolve_param_headers)
self._discover_result = result
self._initialize_result = None
self._negotiated_version = mutual[-1]
Expand Down Expand Up @@ -615,6 +623,7 @@ async def call_tool(
input_responses: types.InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: types.Tool | None = None,
allow_input_required: Literal[False] = False,
) -> types.CallToolResult: ...

Expand All @@ -629,6 +638,7 @@ async def call_tool(
input_responses: types.InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: types.Tool | None = None,
allow_input_required: bool,
) -> types.CallToolResult | types.InputRequiredResult: ...

Expand All @@ -642,13 +652,20 @@ async def call_tool(
input_responses: types.InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
tool: types.Tool | None = None,
allow_input_required: bool = False,
) -> types.CallToolResult | types.InputRequiredResult:
"""Send a tools/call request with optional progress callback support.

Args:
input_responses: Responses to a prior `InputRequiredResult.input_requests`.
request_state: Opaque state echoed from a prior `InputRequiredResult`.
tool: The tool's definition, e.g. from an earlier `list_tools`. On a
modern (2026-07-28) connection its `x-mcp-header` annotations are
mirrored into `Mcp-Param-*` request headers; pass it when the
session has not listed the tool itself. Annotations seen by
`list_tools` are cached, so this is only needed to supply or
override them.
allow_input_required: When ``False`` (default), an `InputRequiredResult`
from the server raises `RuntimeError`; when ``True``, it is returned
so the caller can resolve the requests and retry.
Expand All @@ -657,6 +674,11 @@ async def call_tool(
RuntimeError: If the server returns an `InputRequiredResult` and
``allow_input_required`` is ``False``.
"""
if tool is not None:
if (reason := find_invalid_x_mcp_header(tool.input_schema)) is None:
self._register_x_mcp_headers(tool)
else:
logger.warning("not mirroring headers for tool %r: invalid x-mcp-header (%s)", tool.name, reason)

result = await self.send_request(
types.CallToolRequest(
Expand All @@ -683,6 +705,21 @@ async def call_tool(
)
return result

def _register_x_mcp_headers(self, tool: types.Tool) -> None:
"""Cache `tool`'s argument→`x-mcp-header` map so `tools/call` can mirror them into headers.

A tool with no annotations records an empty map, which still pins the
tool as known so a later call emits no `Mcp-Param-*` headers for it.
"""
self._x_mcp_header_maps[tool.name] = x_mcp_header_map(tool.input_schema)

def _resolve_param_headers(self, name: str, arguments: Mapping[str, Any]) -> dict[str, str]:
"""`Mcp-Param-*` headers for a `tools/call`, or empty when the tool was never listed."""
header_map = self._x_mcp_header_maps.get(name)
if header_map is None:
return {}
return mcp_param_headers(header_map, arguments)

async def _validate_tool_result(self, name: str, result: types.CallToolResult) -> None:
"""Validate the structured content of a tool result against its output schema."""
if name not in self._tool_output_schemas:
Expand Down Expand Up @@ -768,6 +805,7 @@ async def list_tools(self, *, params: types.PaginatedRequestParams | None = None
if (reason := find_invalid_x_mcp_header(tool.input_schema)) is not None:
logger.warning("dropping tool %r: invalid x-mcp-header (%s)", tool.name, reason)
continue
self._register_x_mcp_headers(tool)
kept.append(tool)
result.tools = kept

Expand Down
48 changes: 48 additions & 0 deletions src/mcp/shared/inbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,16 @@
"InboundModernRoute",
"MCP_METHOD_HEADER",
"MCP_NAME_HEADER",
"MCP_PARAM_HEADER_PREFIX",
"MCP_PROTOCOL_VERSION_HEADER",
"NAME_BEARING_METHODS",
"X_MCP_HEADER_KEY",
"classify_inbound_request",
"decode_header_value",
"encode_header_value",
"find_invalid_x_mcp_header",
"mcp_param_headers",
"x_mcp_header_map",
]

MCP_PROTOCOL_VERSION_HEADER: Final = "mcp-protocol-version"
Expand Down Expand Up @@ -206,6 +209,51 @@ def find_invalid_x_mcp_header(input_schema: Any) -> str | None:
return None


MCP_PARAM_HEADER_PREFIX: Final = "Mcp-Param-"
"""Prefix the `x-mcp-header` token is joined to, forming the per-parameter HTTP header name."""


def x_mcp_header_map(input_schema: Any) -> dict[tuple[str, ...], str]:
"""Map each property carrying a valid `x-mcp-header` to its annotation token, keyed by property path.

The key is the chain of `properties` keys from the schema root to the
annotated property; a top-level property has a one-element path, a nested
one a longer path. Call only on a schema that
:func:`find_invalid_x_mcp_header` accepts; an invalid schema yields an
undefined subset.
"""
mapping: dict[tuple[str, ...], str] = {}
for path, schema in _walk_schema_positions(input_schema):
if path and isinstance(header := schema.get(X_MCP_HEADER_KEY), str):
mapping[path] = header
return mapping


def mcp_param_headers(header_map: Mapping[tuple[str, ...], str], arguments: Mapping[str, Any]) -> dict[str, str]:
"""Build the `Mcp-Param-*` headers a `tools/call` mirrors from its arguments.

For each `(path, token)` in `header_map`, read the value at that property
path in `arguments` and, when it is present and not `None`, emit
`Mcp-Param-<token>` carrying it: `bool` as `true`/`false`, other scalars via
`str`, each passed through :func:`encode_header_value` so a non-token value
is base64-wrapped. A path that hits a missing key or a non-mapping node is
skipped, matching the spec's "omit the header when no value is present".
"""
headers: dict[str, str] = {}
for path, token in header_map.items():
node: Any = arguments

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It shouldn't be Any here!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Moved the JSON traversal into a small _value_at_path helper so mcp_param_headers no longer carries inline Any. The Any that remains is confined to that helper, which walks arbitrary decoded-JSON arguments - same reason _walk_schema_positions uses it in this file.

for key in path:
if not isinstance(node, Mapping):
node = None
break
node = cast("Mapping[str, Any]", node).get(key)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

cast is not necessary

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed the inline cast from mcp_param_headers. One cast stays inside _value_at_path because strict pyright needs it to narrow isinstance(node, Mapping) (bare Mapping → Unknown keys/values) - it's the same idiom _walk_schema_positions already uses here. Open to a cleaner spelling if you have one.

if node is None:
continue
rendered = ("true" if node else "false") if isinstance(node, bool) else str(node)
headers[f"{MCP_PARAM_HEADER_PREFIX}{token}"] = encode_header_value(rendered)
return headers


# INTERNAL_ERROR is deliberately unmapped (→ HTTP 200): the spec assigns no status to
# -32603, and whether handler-origin errors get 5xx is an open S4 question — see TODO(L66).
ERROR_CODE_HTTP_STATUS: Final[Mapping[int, int]] = MappingProxyType(
Expand Down
35 changes: 35 additions & 0 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,41 @@ async def on_list_tools(
assert [t.name for t in result.tools] == ["ok", "dropme"]


async def test_call_tool_with_invalid_tool_override_logs_warning_and_mirrors_nothing(
caplog: pytest.LogCaptureFixture,
) -> None:
"""A `tool=` override whose schema has a malformed `x-mcp-header` is not mirrored; the client warns instead.

The over-the-wire mirroring is only observable on streamable HTTP (see
`tests/interaction/transports/test_hosting_http_modern.py`); here the in-memory transport proves the
validation gate: an invalid override never registers a header map, and a warning names the tool and reason."""
calls: list[str] = []
bad_tool = types.Tool(
name="run",
input_schema={"type": "object", "properties": {"a": {"type": "string", "x-mcp-header": "bad name"}}},
)

async def on_list_tools(
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
return types.ListToolsResult(tools=[bad_tool])

async def on_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
calls.append(params.name)
return types.CallToolResult(content=[])

server = Server("test", on_list_tools=on_list_tools, on_call_tool=on_call_tool)

with anyio.fail_after(5), caplog.at_level("WARNING", logger="client"):
async with Client(server) as client:
result = await client.call_tool("run", {"a": "x"}, tool=bad_tool)

assert result.content == []
assert calls == ["run"]
assert "not mirroring headers for tool 'run'" in caplog.text
assert "bad name" in caplog.text


def test_client_rejects_handshake_era_mode_at_construction() -> None:
"""A handshake-era protocol-version string passed as `mode=` is rejected by
`__post_init__` with a hint to use `mode='legacy'` — the version-pin path is
Expand Down
Loading
Loading