DSPy: The framework for programming—not prompting—language models
Python
Add opt-in structured results for MCP tools (#10235)
Isaac Millerca0a088bde91
diff --git a/docs/docs/diving-deeper/tools.md b/docs/docs/diving-deeper/tools.mdindex 574e8082b..3919fa145 100644--- a/docs/docs/diving-deeper/tools.md+++ b/docs/docs/diving-deeper/tools.md@@ -99,7 +99,7 @@ The bridge:3. Unpacks MCP text content into a string or list and preserves non-text content.4. Raises an execution error when the MCP response has `isError=True`.-The bridge supports both the camelCase result fields in MCP SDK v1 and their snake_case replacements in v2 without changing text or non-text result behavior.+The bridge supports both the camelCase result fields in MCP SDK v1 and their snake_case replacements in v2 without changing text or non-text result behavior. Pass `result_mode="structured"` to return `structuredContent` when available, falling back to the default conversion when it is absent.MCP tools are asynchronous because `mcp.ClientSession` is asynchronous. Use a module's async entry point, such as `acall`, or explicitly enable async-to-sync conversion when appropriate.@@ -116,8 +116,8 @@ Validates, coerces, and executes tool arguments through synchronous or asynchron**`Tool.format_as_litellm_function_call()`** → `dict`Returns the OpenAI/LiteLLM-style function descriptor used by adapters for native calling.-**`Tool.from_mcp_tool(session, tool)`** → `Tool`-Wraps a remote MCP tool as an asynchronous DSPy tool.+**`Tool.from_mcp_tool(session, tool, *, result_mode="text")`** → `Tool`+Wraps a remote MCP tool as an asynchronous DSPy tool. Set `result_mode="structured"` to return structured MCP results when available.**`Tool.from_langchain(tool)`** → `Tool`Wraps a LangChain tool in the same DSPy interface.diff --git a/docs/docs/learn/programming/mcp.md b/docs/docs/learn/programming/mcp.mdindex 6da07ccc2..a75d077b5 100644--- a/docs/docs/learn/programming/mcp.md+++ b/docs/docs/learn/programming/mcp.md@@ -158,6 +158,8 @@ dspy_tool = dspy.Tool.from_mcp_tool(session, mcp_tool)result = await dspy_tool.acall(param1="value", param2=123)```+By default, MCP tools return the `content` field. Pass `result_mode="structured"` to `dspy.Tool.from_mcp_tool` to return `structuredContent` when available; if it is absent, DSPy falls back to the default conversion.+## Learn More- [MCP Official Documentation](https://modelcontextprotocol.io/)diff --git a/dspy/adapters/types/tool.py b/dspy/adapters/types/tool.pyindex 0aac2dd27..8dc81e398 100644--- a/dspy/adapters/types/tool.py+++ b/dspy/adapters/types/tool.py@@ -1,6 +1,6 @@import asyncioimport inspect-from typing import TYPE_CHECKING, Any, Callable, Protocol, get_origin, get_type_hints+from typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, get_origin, get_type_hintsimport json_repairimport pydantic@@ -204,20 +204,29 @@ class Tool(Type):return result@classmethod- def from_mcp_tool(cls, session: _MCPToolClient, tool: "mcp.types.Tool") -> "Tool":+ def from_mcp_tool(+ cls,+ session: _MCPToolClient,+ tool: "mcp.types.Tool",+ *,+ result_mode: Literal["text", "structured"] = "text",+ ) -> "Tool":"""Build a DSPy tool from an MCP tool and a compatible MCP client.Args:session: An MCP client or session with an async ``call_tool`` method.tool: The MCP tool to convert.+ result_mode: ``"text"`` preserves DSPy's existing text/non-text+ conversion. ``"structured"`` returns MCP structured content+ exactly when present, with the existing conversion as fallback.Returns:A Tool object."""from dspy.utils.mcp import convert_mcp_tool- return convert_mcp_tool(session, tool)+ return convert_mcp_tool(session, tool, result_mode=result_mode)@classmethoddef from_langchain(cls, tool: "BaseTool") -> "Tool":diff --git a/dspy/utils/mcp.py b/dspy/utils/mcp.pyindex 82802e206..98827108f 100644--- a/dspy/utils/mcp.py+++ b/dspy/utils/mcp.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literalfrom dspy.adapters.types.tool import Tool, _MCPToolClient, convert_input_schema_to_tool_args@@ -14,7 +14,20 @@ def _get_field(obj: Any, snake_name: str, camel_name: str, default: Any = None)return default-def _convert_mcp_tool_result(call_tool_result: "mcp.types.CallToolResult") -> str | list[Any]:+def _field_is_set(obj: Any, snake_name: str, camel_name: str) -> bool:+ """Check whether an optional field was explicitly set, including to null."""+ fields_set = getattr(obj, "model_fields_set", None)+ if fields_set is None:+ fields_set = getattr(obj, "__fields_set__", None)+ if fields_set is not None:+ return snake_name in fields_set or camel_name in fields_set+ return hasattr(obj, snake_name) or hasattr(obj, camel_name)+++def _convert_mcp_tool_result(+ call_tool_result: "mcp.types.CallToolResult",+ result_mode: Literal["text", "structured"] = "text",+) -> Any:from mcp.types import TextContenttext_contents: list[TextContent] = []@@ -32,10 +45,18 @@ def _convert_mcp_tool_result(call_tool_result: "mcp.types.CallToolResult") -> stif _get_field(call_tool_result, "is_error", "isError", default=False):raise RuntimeError(f"Failed to call a MCP tool: {tool_content}")+ if result_mode == "structured" and _field_is_set(call_tool_result, "structured_content", "structuredContent"):+ return _get_field(call_tool_result, "structured_content", "structuredContent")+return tool_content or non_text_contents-def convert_mcp_tool(session: _MCPToolClient, tool: "mcp.types.Tool") -> Tool:+def convert_mcp_tool(+ session: _MCPToolClient,+ tool: "mcp.types.Tool",+ *,+ result_mode: Literal["text", "structured"] = "text",+) -> Tool:"""Build a DSPy tool from an MCP tool.Both mcp SDK v1's ``ClientSession`` and v2's high-level ``Client`` satisfy@@ -44,16 +65,22 @@ def convert_mcp_tool(session: _MCPToolClient, tool: "mcp.types.Tool") -> Tool:Args:session: An MCP client or session with an async ``call_tool`` method.tool: The MCP tool to convert.+ result_mode: ``"text"`` preserves DSPy's existing text/non-text+ conversion. ``"structured"`` returns MCP structured content+ exactly when present, with the existing conversion as fallback.Returns:A dspy Tool object."""+ if result_mode not in ("text", "structured"):+ raise ValueError(f"Unsupported MCP result mode: {result_mode!r}")+input_schema = _get_field(tool, "input_schema", "inputSchema", default={})args, arg_types, arg_desc = convert_input_schema_to_tool_args(input_schema)# Convert the MCP tool and Session to a single async methodasync def func(*args, **kwargs):result = await session.call_tool(tool.name, arguments=kwargs)- return _convert_mcp_tool_result(result)+ return _convert_mcp_tool_result(result, result_mode=result_mode)return Tool(func=func, name=tool.name, desc=tool.description, args=args, arg_types=arg_types, arg_desc=arg_desc)diff --git a/tests/utils/test_mcp.py b/tests/utils/test_mcp.pyindex 5ccbdb891..1108ae8ca 100644--- a/tests/utils/test_mcp.py+++ b/tests/utils/test_mcp.py@@ -12,30 +12,99 @@ from dspy.utils.mcp import _convert_mcp_tool_result, convert_mcp_toolif importlib.util.find_spec("mcp") is None:pytest.skip(reason="mcp is not installed", allow_module_level=True)+_UNSET = object()-def make_call_tool_result(field_style, texts=(), is_error=False):++def make_call_tool_result(field_style, texts=(), structured=_UNSET, is_error=False):from mcp.types import TextContentfields = {"content": [TextContent(type="text", text=text) for text in texts],- "structured_content" if field_style == "snake" else "structuredContent": {"result": "ignored"},"is_error" if field_style == "snake" else "isError": is_error,}+ if structured is not _UNSET:+ fields["structured_content" if field_style == "snake" else "structuredContent"] = structuredreturn SimpleNamespace(**fields)@pytest.mark.extradef test_convert_mcp_tool_result_supports_both_field_styles_without_changing_results():- assert _convert_mcp_tool_result(make_call_tool_result("camel", texts=["hi"])) == "hi"- assert _convert_mcp_tool_result(make_call_tool_result("snake", texts=["a", "b"])) == ["a", "b"]+ camel_result = make_call_tool_result("camel", texts=["hi"], structured={"result": "ignored"})+ snake_result = make_call_tool_result("snake", texts=["a", "b"], structured={"result": "ignored"})++ assert _convert_mcp_tool_result(camel_result) == "hi"+ assert _convert_mcp_tool_result(snake_result) == ["a", "b"]++[email protected]("field_style", ["camel", "snake"])+ "structured",+ [+ pytest.param({"answer": 42}, id="object"),+ pytest.param([1, 2], id="array"),+ pytest.param("answer", id="string"),+ pytest.param(3.5, id="number"),+ pytest.param(False, id="boolean"),+ pytest.param(None, id="null"),+ pytest.param({}, id="empty-object"),+ pytest.param([], id="empty-array"),+ pytest.param("", id="empty-string"),+ pytest.param(0, id="zero"),+ ],+)+def test_structured_result_mode_returns_every_json_value_exactly(field_style, structured):+ result = make_call_tool_result(field_style, texts=["fallback"], structured=structured)++ converted = _convert_mcp_tool_result(result, result_mode="structured")+ assert converted == structured+ assert type(converted) is type(structured)++[email protected]("field_style", ["camel", "snake"])+def test_structured_result_mode_falls_back_when_field_is_absent(field_style):+ result = make_call_tool_result(field_style, texts=["fallback"])++ assert _convert_mcp_tool_result(result, result_mode="structured") == "fallback"+++def test_structured_result_mode_distinguishes_explicit_null_from_omission():+ from mcp.types import CallToolResult++ model_fields = getattr(CallToolResult, "model_fields", None)+ if model_fields is None:+ model_fields = getattr(CallToolResult, "__fields__", {})+ field_name = next(+ (name for name in ("structured_content", "structuredContent") if name in model_fields),+ None,+ )+ if field_name is None:+ pytest.skip("This MCP version predates structured content")++ omitted = CallToolResult(content=[])+ explicit_null = CallToolResult(content=[], **{field_name: None})++ assert _convert_mcp_tool_result(omitted, result_mode="structured") == []+ assert _convert_mcp_tool_result(explicit_null, result_mode="structured") is None@pytest.mark.extra@pytest.mark.parametrize("field_style", ["camel", "snake"])-def test_error_result_raises(field_style):- result = make_call_tool_result(field_style, texts=["boom"], is_error=True)[email protected]("result_mode", ["text", "structured"])+def test_error_result_raises_before_conversion(field_style, result_mode):+ result = make_call_tool_result(field_style, texts=["boom"], structured={"result": "ignored"}, is_error=True)with pytest.raises(RuntimeError, match="Failed to call a MCP tool: boom"):- _convert_mcp_tool_result(result)+ _convert_mcp_tool_result(result, result_mode=result_mode)+++def test_convert_mcp_tool_rejects_unknown_result_mode():+ tool = SimpleNamespace(name="test", description="test", input_schema={})++ with pytest.raises(ValueError, match="Unsupported MCP result mode: 'invalid'"):+ convert_mcp_tool(SimpleNamespace(), tool, result_mode="invalid")@pytest.mark.asyncio@@ -56,7 +125,10 @@ async def test_convert_mcp_tool_with_v2_client():async with Client(server) as client:response = await client.list_tools()increment_tool = Tool.from_mcp_tool(client, response.tools[0])+ structured_increment_tool = Tool.from_mcp_tool(client, response.tools[0], result_mode="structured")+assert await increment_tool.acall(value=1) == "2"+ assert await structured_increment_tool.acall(value=1) == {"result": 2}@pytest.mark.asyncio