Dead code path in MCPServer._handle_call_tool and incorrect call_tool return type
Summary
MCPServer._handle_call_tool in src/mcp/server/mcpserver/server.py
contains a dead isinstance(result, dict) branch, with an inline TODO
that already documents both the dead-code issue and the related
incorrect return-type annotation on MCPServer.call_tool.
I'd like to clean this up. Posting the diagnosis here first per CONTRIBUTING.md.
Diagnosis
FuncMetadata.convert_result in
src/mcp/server/mcpserver/utilities/func_metadata.py can return exactly
three shapes (lines 105-123):
CallToolResult(when the tool function returned one directly)Sequence[ContentBlock](no output schema — via_convert_to_content)(unstructured_content, structured_content)tuple (with output schema)
Never a raw dict. So:
- The
isinstance(result, dict)branch in_handle_call_tool(lines 325-332 on main) is unreachable. It's marked# pragma: no coverbecause tests cannot reach it. MCPServer.call_tool's return-type annotationSequence[ContentBlock] | dict[str, Any](line 402 on main) is wrong: it advertises a dict return that cannot happen, and is missing theCallToolResultand tuple shapes that can happen.
Proposed fix
- Remove the dead
isinstance(result, dict)branch. - Drop the now-unused
import json. - Change
call_tool's return type toCallToolResult | Sequence[ContentBlock] | tuple[Sequence[ContentBlock], dict[str, Any]]and document all three shapes in the docstring.
The return-type change is a breaking type-signature change for
subclasses, so this targets main (v2) per CONTRIBUTING.md.
I have the patch ready and CI-clean locally (pytest + ruff + pyright). Happy to open the PR once this is acknowledged.
AI assistance disclosure
I used an AI assistant to help trace the call path and draft the diff. I've reviewed every changed line, validated the diagnosis against the source, and run the local checks myself.
I checked this against current main and the shape analysis lines up with the source.
One regression test that would make the cleanup hard to accidentally undo: register a tool with an output schema that returns structured data, call through _handle_call_tool, and assert the handler produces a CallToolResult with both content and structured_content populated. That exercises the reachable tuple path from convert_result=True and makes the removed raw-dict branch unnecessary by construction.
For the public call_tool() annotation, it may also be worth aliasing the return shape in one place, e.g. something like ToolResult = CallToolResult | Sequence[ContentBlock] | tuple[Sequence[ContentBlock], dict[str, Any]]. That keeps _handle_call_tool, call_tool, and any subclass docs from drifting apart again.
Thanks @scosemicolon — both suggestions land for me.
The regression test you describe is the right shape: register a tool with an
output schema, invoke through _handle_call_tool, assert both content and
structured_content populate. That pins the reachable tuple path from
convert_result=True and makes any re-introduction of the raw-dict branch
immediately surface as a failing test.
The ToolResult alias also makes sense — keeping _handle_call_tool,
MCPServer.call_tool, and the eventual subclass docs all referencing one
canonical shape definition is exactly the kind of drift prevention this
refactor needs.
@Ar-maan05 has already opened #2700 covering parts 1–3 of the proposed fix. @Ar-maan05, happy to put together the regression test and the type alias as either commits on your branch (if you'd take a co-author push) or as a follow-up PR after yours lands — whichever you and the reviewers prefer.
Thanks for the suggestions. I've added the ToolResult alias and the regression test covering the structured output path in #2700 ; both are now part of the same PR.
Nice — the ToolResult alias landing in one place looks clean, and the
make_point test pins the tuple path exactly as @scosemicolon described.
One follow-up I'd like to do once #2700 lands: extend the same test file to
also pin the other two reachable shapes from convert_result=True —
- a tool with no output schema (the bare
Sequence[ContentBlock]path), and - a tool that returns a
CallToolResultdirectly.
Same shape as the new test, just three small cases instead of one. Together
the three lock down every path that _handle_call_tool actually traverses,
so any future regression that brings back a raw-dict (or any other) branch
fails loudly. Happy to open that as a small follow-up PR — let me know if
that's wanted.
Thanks for the suggestion. That makes total sense to lock down all the reachable paths. I have updated this PR directly to include those two additional tests: one for a tool returning a CallToolResult directly, and one for a tool with no output schema returning a bare Sequence[ContentBlock]. This ensures all three branches of _handle_call_tool are fully pinned.
confirmed on main at 616476f. the isinstance(result, dict) branch in _handle_call_tool (server.py:325-332) is unreachable — FuncMetadata.convert_result only returns CallToolResult, Sequence[ContentBlock] (via _convert_to_content, signature -> Sequence[ContentBlock]), or an (unstructured, structured) tuple. the call_tool annotation Sequence[ContentBlock] | dict[str, Any] (server.py:402) is wrong on both ends: advertises an impossible dict, omits the CallToolResult and tuple shapes that actually occur.
#2700 is already in flight covering the cleanup, the ToolResult alias, and regression tests pinning all three reachable shapes.
repro
# repro.py
import asyncio, inspect
from typing import Any
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.utilities.func_metadata import _convert_to_content
from mcp.types import CallToolResult, TextContent
server = MCPServer(name="repro-2695")
@server.tool()
def returns_str() -> str: return "hello"
@server.tool()
def returns_int() -> int: return 7
@server.tool(structured_output=True)
def returns_structured() -> dict[str, int]: return {"a": 1, "b": 2}
@server.tool()
def returns_call_tool_result() -> CallToolResult:
return CallToolResult(content=[TextContent(type="text", text="direct")])
async def main() -> None:
for name in ("returns_str", "returns_int", "returns_structured", "returns_call_tool_result"):
r: Any = await server.call_tool(name, {})
print(f" {name:30s} -> {type(r).__name__}")
assert not isinstance(r, dict)
print(f"annotation: {inspect.signature(MCPServer.call_tool).return_annotation}")
out = _convert_to_content({"k": "v"})
print(f"_convert_to_content({{}}) -> {type(out).__name__}")
assert not isinstance(out, dict)
asyncio.run(main())
async def bare() -> None:
s = MCPServer(name="bare")
@s.tool()
def no_annot(): return "x"
r: Any = await s.call_tool("no_annot", {})
print(f"bare: no_annot -> {type(r).__name__}")
asyncio.run(bare())
$ uv run python repro.py
returns_str -> tuple
returns_int -> tuple
returns_structured -> tuple
returns_call_tool_result -> CallToolResult
annotation: Sequence[ContentBlock] | dict[str, Any]
_convert_to_content({}) -> list
bare: no_annot -> list
observed return shapes from call_tool: tuple, CallToolResult, list[ContentBlock]. never dict.
scope: v2 only — v1.x doesn't carry src/mcp/server/mcpserver/, no backport needed.
This looks worth pinning down as a protocol-level regression rather than only an implementation bug.
For dead code path in MCPServer handle_call_tool, the acceptance test I would want is a minimal client/server fixture that records the exact JSON-RPC or HTTP exchange, then asserts both the wire result and the local lifecycle state after the failure path. In MCP deployments, the dangerous failures are often not just wrong return values; they are pending requests, dropped notifications, mismatched session state, or errors that get translated into a generic response and become impossible to diagnose.
A useful fix boundary would preserve three signals: the protocol error sent to the peer, the local exception or cancellation reason available to application code, and a trace/log field that ties the two together. That makes the behavior debuggable for agent hosts without requiring every host to special-case this SDK detail.
Thanks @norika1207-lab. For this specific cleanup the unit-level
coverage in #2700 pins all three reachable shapes from convert_result,
and since the removed branch was unreachable the wire output is
unchanged by construction. The broader protocol-error-surface concern
you describe sounds real but feels like a separate scope — worth its
own issue if you want to open one.
One thing worth nailing down so this survives the v2 receive-path swap in #2710: that PR deletes the old _handle_* path, so the unit tests in #2700 that exercise _handle_call_tool directly may not carry over as-is.
The durable, implementation-agnostic acceptance criterion (independent of whether _handle_call_tool or the new ServerRunner produces it):
Invoking a tool through the public MCPServer surface must, on the wire:
- pass a directly-returned
CallToolResultthrough unchanged, - wrap a bare
Sequence[ContentBlock]as unstructured content, and - emit both
contentandstructuredContentfor the(unstructured, structured)tuple shape,
and call_tool's public return annotation must enumerate exactly those three, never a raw dict. Pinned that way, the fix holds regardless of which runtime path lands.
I can pick this up from current main now that #2700 is closed and unmerged. I'll keep the scope to the ready-for-work issue: remove the unreachable raw-dict path, align the public return type, add focused coverage for the reachable result shapes, and run the targeted uv/pytest checks before opening a small PR.
Quick note as the issue author: since #2700 was closed unmerged and there are now several competing PRs in flight (#2816, #2830, #2833, #2855, #2863), I have a CI-clean patch ready that covers the full scope outlined in the issue — dead branch removal, json import drop, ToolResult alias, corrected return-type annotation, and regression tests pinning all three reachable shapes from convert_result.
Happy to open it as a consolidated PR if the maintainers would prefer a single clean submission, or to defer to whichever of the existing PRs the reviewers pick. Just want to flag the option so the work isn't duplicated further.
I've banned most of the users that created PRs from this PR.