Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Add `dspy.Tool.from_mcp_tool` (#8130)

TomuHiratab58f0759135c
diff --git a/dspy/primitives/tool.py b/dspy/primitives/tool.py
index 0716ded7c..1ad2a40d2 100644
--- a/dspy/primitives/tool.py
+++ b/dspy/primitives/tool.py
@@ -1,12 +1,14 @@
import asyncio
import inspect
-from typing import Any, Callable, Optional, get_origin, get_type_hints
+from typing import Any, Callable, Optional, get_origin, get_type_hints, TYPE_CHECKING
from jsonschema import ValidationError, validate
from pydantic import BaseModel, TypeAdapter, create_model
from dspy.utils.callback import with_callbacks
+if TYPE_CHECKING:
+ import mcp
class Tool:
"""Tool class.
@@ -176,3 +178,18 @@ class Tool:
if not asyncio.iscoroutine(result):
raise ValueError("You are calling `acall` on a non-async tool, please use `__call__` instead.")
return await result
+
+ @classmethod
+ def from_mcp_tool(cls, session: "mcp.client.session.ClientSession", tool: "mcp.types.Tool") -> "Tool":
+ """
+ Build a DSPy tool from an MCP tool and a ClientSession.
+
+ Args:
+ session: The MCP session to use.
+ tool: The MCP tool to convert.
+
+ Returns:
+ A Tool object.
+ """
+ from dspy.utils.mcp import convert_mcp_tool
+ return convert_mcp_tool(session, tool)
diff --git a/dspy/utils/mcp.py b/dspy/utils/mcp.py
new file mode 100644
index 000000000..1eeb54e79
--- /dev/null
+++ b/dspy/utils/mcp.py
@@ -0,0 +1,79 @@
+from typing import Any, Tuple, Type, Union, TYPE_CHECKING
+from dspy.primitives.tool import Tool
+
+if TYPE_CHECKING:
+ import mcp
+
+TYPE_MAPPING = {"string": str, "integer": int, "number": float, "boolean": bool, "array": list, "object": dict}
+
+
+def _convert_input_schema_to_tool_args(
+ schema: dict[str, Any],
+) -> Tuple[dict[str, Any], dict[str, Type], dict[str, str]]:
+ """Convert an input schema to tool arguments compatible with DSPy Tool.
+
+ Args:
+ schema: An input schema describing the tool's input parameters
+
+ Returns:
+ A tuple of (args, arg_types, arg_desc) for DSPy Tool definition.
+ """
+ args, arg_types, arg_desc = {}, {}, {}
+ properties = schema.get("properties", None)
+ if properties is None:
+ return args, arg_types, arg_desc
+
+ required = schema.get("required", [])
+
+ for name, prop in properties.items():
+ args[name] = prop
+ # MCP tools are validated through jsonschema using args, so arg_types are not strictly required.
+ arg_types[name] = TYPE_MAPPING.get(prop.get("type"), Any)
+ arg_desc[name] = prop.get("description", "No description provided.")
+ if name in required:
+ arg_desc[name] += " (Required)"
+
+ return args, arg_types, arg_desc
+
+
+def _convert_mcp_tool_result(call_tool_result: "mcp.types.CallToolResult") -> Union[str, list[Any]]:
+ from mcp.types import (
+ TextContent,
+ )
+
+ text_contents: list[TextContent] = []
+ non_text_contents = []
+ for content in call_tool_result.content:
+ if isinstance(content, TextContent):
+ text_contents.append(content)
+ else:
+ non_text_contents.append(content)
+
+ tool_content = [content.text for content in text_contents]
+ if len(text_contents) == 1:
+ tool_content = tool_content[0]
+
+ if call_tool_result.isError:
+ raise RuntimeError(f"Failed to call a MCP tool: {tool_content}")
+
+ return tool_content or non_text_contents
+
+
+def convert_mcp_tool(session: "mcp.client.session.ClientSession", tool: "mcp.types.Tool") -> Tool:
+ """Build a DSPy tool from an MCP tool.
+
+ Args:
+ session: The MCP session to use.
+ tool: The MCP tool to convert.
+
+ Returns:
+ A dspy Tool object.
+ """
+ args, arg_types, arg_desc = _convert_input_schema_to_tool_args(tool.inputSchema)
+
+ # Convert the MCP tool and Session to a single async method
+ async def func(*args, **kwargs):
+ result = await session.call_tool(tool.name, arguments=kwargs)
+ return _convert_mcp_tool_result(result)
+
+ return Tool(func=func, name=tool.name, desc=tool.description, args=args, arg_types=arg_types, arg_desc=arg_desc)
diff --git a/pyproject.toml b/pyproject.toml
index 27d37a706..ac93529b0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -62,7 +62,9 @@ dev = [
"build>=1.0.3",
"litellm>=1.60.3; sys_platform == 'win32'",
"litellm[proxy]>=1.60.3; sys_platform != 'win32'",
+ "mcp>=1.5.0; python_version >= '3.10'",
]
+mcp = ["mcp; python_version >= '3.10'"]
[tool.setuptools.packages.find]
where = ["."]
diff --git a/tests/utils/resources/mcp_server.py b/tests/utils/resources/mcp_server.py
new file mode 100644
index 000000000..3eeea15ef
--- /dev/null
+++ b/tests/utils/resources/mcp_server.py
@@ -0,0 +1,23 @@
+from mcp.server.fastmcp import FastMCP
+
+mcp = FastMCP("test")
+
+
+def add(a: int, b: int) -> int:
+ """Add two numbers"""
+ return a + b
+
+
+def hello(names: list[str]) -> str:
+ """Greet people"""
+ return [f"Hello, {name}!" for name in names]
+
+def wrong_tool():
+ """This tool raises an error"""
+ raise ValueError("error!")
+
+if __name__ == "__main__":
+ mcp.run()
diff --git a/tests/utils/test_mcp.py b/tests/utils/test_mcp.py
new file mode 100644
index 000000000..ce3e3916c
--- /dev/null
+++ b/tests/utils/test_mcp.py
@@ -0,0 +1,50 @@
+import pytest
+import asyncio
+
+from mcp import ClientSession, StdioServerParameters
+from mcp.client.stdio import stdio_client
+
+from dspy.utils.mcp import convert_mcp_tool
+
+
+async def test_convert_mcp_tool():
+ server_params = StdioServerParameters(
+ command="python",
+ args=["tests/utils/resources/mcp_server.py"],
+ env=None,
+ )
+ async with stdio_client(server_params) as (read, write):
+ async with ClientSession(read, write) as session:
+ await asyncio.wait_for(session.initialize(), timeout=5)
+ response = await session.list_tools()
+
+ # Check add
+ add_tool = convert_mcp_tool(session, response.tools[0])
+ assert add_tool.name == "add"
+ assert add_tool.desc == "Add two numbers"
+ assert add_tool.args == {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "integer"}}
+ assert add_tool.arg_types == {"a": int, "b": int}
+ assert add_tool.arg_desc == {
+ "a": "No description provided. (Required)",
+ "b": "No description provided. (Required)",
+ }
+ assert await add_tool.acall(a=1, b=2) == "3"
+
+ # Check hello
+ hello_tool = convert_mcp_tool(session, response.tools[1])
+ assert hello_tool.name == "hello"
+ assert hello_tool.desc == "Greet people"
+ assert hello_tool.args == {"names": {"title": "Names", "type": "array", "items": {"type": "string"}}}
+ assert hello_tool.arg_types == {"names": list}
+ assert hello_tool.arg_desc == {"names": "No description provided. (Required)"}
+ assert await hello_tool.acall(names=["Bob", "Tom"]) == ["Hello, Bob!", "Hello, Tom!"]
+
+ # Check error handling
+ error_tool = convert_mcp_tool(session, response.tools[2])
+ assert error_tool.name == "wrong_tool"
+ assert error_tool.desc == "This tool raises an error"
+ with pytest.raises(
+ RuntimeError, match="Failed to call a MCP tool: Error executing tool wrong_tool: error!"
+ ):
+ await error_tool.acall()
diff --git a/uv.lock b/uv.lock
index ee8da45b2..fd41b9611 100644
--- a/uv.lock
+++ b/uv.lock
@@ -705,6 +705,7 @@ dev = [
{ name = "datamodel-code-generator" },
{ name = "litellm" },
{ name = "litellm", extra = ["proxy"], marker = "sys_platform != 'win32'" },
+ { name = "mcp", marker = "python_full_version >= '3.10'" },
{ name = "pillow" },
{ name = "pre-commit" },
{ name = "pytest" },
@@ -712,6 +713,9 @@ dev = [
{ name = "pytest-mock" },
{ name = "ruff" },
]
+mcp = [
+ { name = "mcp", marker = "python_full_version >= '3.10'" },
+]
weaviate = [
{ name = "weaviate-client" },
]
@@ -735,9 +739,11 @@ requires-dist = [
{ name = "litellm", marker = "sys_platform == 'win32' and extra == 'dev'", specifier = ">=1.60.3" },
{ name = "litellm", extras = ["proxy"], marker = "sys_platform != 'win32' and extra == 'dev'", specifier = ">=1.60.3" },
{ name = "magicattr", specifier = ">=0.1.6" },
+ { name = "mcp", marker = "python_full_version >= '3.10' and extra == 'dev'", specifier = ">=1.5.0" },
+ { name = "mcp", marker = "python_full_version >= '3.10' and extra == 'mcp'" },
{ name = "numpy", marker = "python_full_version == '3.9.*'", specifier = ">=1.26.0,<2.2" },
{ name = "numpy", marker = "python_full_version >= '3.10'", specifier = ">=1.26.0" },
- { name = "openai", specifier = ">=0.28.1,<=1.61.0" },
+ { name = "openai", specifier = ">=0.28.1" },
{ name = "optuna", specifier = ">=3.4.0" },
{ name = "pandas", specifier = ">=2.1.1" },
{ name = "pillow", marker = "extra == 'dev'", specifier = ">=10.1.0" },
@@ -755,7 +761,7 @@ requires-dist = [
{ name = "ujson", specifier = ">=5.8.0" },
{ name = "weaviate-client", marker = "extra == 'weaviate'", specifier = "~=4.5.4" },
]
-provides-extras = ["anthropic", "weaviate", "aws", "dev"]
+provides-extras = ["anthropic", "weaviate", "aws", "dev", "mcp"]
[[package]]
name = "email-validator"
@@ -1127,6 +1133,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/7b/ddacf6dcebb42466abd03f368782142baa82e08fc0c1f8eaa05b4bae87d5/httpx-0.27.0-py3-none-any.whl", hash = "sha256:71d5465162c13681bff01ad59b2cc68dd838ea1f10e51574bac27103f00c91a5", size = 75590 },
]
+[[package]]
+name = "httpx-sse"
+version = "0.4.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4c/60/8f4281fa9bbf3c8034fd54c0e7412e66edbab6bc74c4996bd616f8d0406e/httpx-sse-0.4.0.tar.gz", hash = "sha256:1e81a3a3070ce322add1d3529ed42eb5f70817f45ed6ec915ab753f961139721", size = 12624 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/9b/a181f281f65d776426002f330c31849b86b31fc9d848db62e16f03ff739f/httpx_sse-0.4.0-py3-none-any.whl", hash = "sha256:f329af6eae57eaa2bdfd962b42524764af68075ea87370a2de920af5341e318f", size = 7819 },
+]
+
[[package]]
name = "huggingface-hub"
version = "0.30.2"
@@ -1448,6 +1463,25 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/73/085399401383ce949f727afec55ec3abd76648d04b9f22e1c0e99cb4bec3/MarkupSafe-3.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:6e296a513ca3d94054c2c881cc913116e90fd030ad1c656b3869762b754f5f8a", size = 15506 },
]
+[[package]]
+name = "mcp"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio", marker = "python_full_version >= '3.10'" },
+ { name = "httpx", marker = "python_full_version >= '3.10'" },
+ { name = "httpx-sse", marker = "python_full_version >= '3.10'" },
+ { name = "pydantic", marker = "python_full_version >= '3.10'" },
+ { name = "pydantic-settings", marker = "python_full_version >= '3.10'" },
+ { name = "sse-starlette", marker = "python_full_version >= '3.10'" },
+ { name = "starlette", marker = "python_full_version >= '3.10'" },
+ { name = "uvicorn", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/95/d2/f587cb965a56e992634bebc8611c5b579af912b74e04eb9164bd49527d21/mcp-1.6.0.tar.gz", hash = "sha256:d9324876de2c5637369f43161cd71eebfd803df5a95e46225cab8d280e366723", size = 200031 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/30/20a7f33b0b884a9d14dd3aa94ff1ac9da1479fe2ad66dd9e2736075d2506/mcp-1.6.0-py3-none-any.whl", hash = "sha256:7bd24c6ea042dbec44c754f100984d186620d8b841ec30f1b19eda9b93a634d0", size = 76077 },
+]
+
[[package]]
name = "mdurl"
version = "0.1.2"
@@ -2197,6 +2231,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/25/f2/1647933efaaad61846109a27619f3704929e758a09e6431b8f932a053d40/pydantic_core-2.33.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:de9e06abe3cc5ec6a2d5f75bc99b0bdca4f5c719a5b34026f8c57efbdecd2ee3", size = 2081073 },
]
+[[package]]
+name = "pydantic-settings"
+version = "2.9.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pydantic", marker = "python_full_version >= '3.10'" },
+ { name = "python-dotenv", marker = "python_full_version >= '3.10'" },
+ { name = "typing-inspection", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/1d/42628a2c33e93f8e9acbde0d5d735fa0850f3e6a2f8cb1eb6c40b9a732ac/pydantic_settings-2.9.1.tar.gz", hash = "sha256:c509bf79d27563add44e8446233359004ed85066cd096d8b510f715e6ef5d268", size = 163234 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b6/5f/d6d641b490fd3ec2c4c13b4244d68deea3a1b970a97be64f34fb5504ff72/pydantic_settings-2.9.1-py3-none-any.whl", hash = "sha256:59b4f431b1defb26fe620c71a7d3968a710d719f5f4cdbbdb7926edeb770f6ef", size = 44356 },
+]
+
[[package]]
name = "pygments"
version = "2.19.1"
@@ -2710,12 +2758,25 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/7c/5fc8e802e7506fe8b55a03a2e1dab156eae205c91bee46305755e086d2e2/sqlalchemy-2.0.40-py3-none-any.whl", hash = "sha256:32587e2e1e359276957e6fe5dad089758bc042a971a8a09ae8ecf7a8fe23d07a", size = 1903894 },
]
+[[package]]
+name = "sse-starlette"
+version = "2.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio", marker = "python_full_version >= '3.10'" },
+ { name = "starlette", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/86/35/7d8d94eb0474352d55f60f80ebc30f7e59441a29e18886a6425f0bccd0d3/sse_starlette-2.3.3.tar.gz", hash = "sha256:fdd47c254aad42907cfd5c5b83e2282be15be6c51197bf1a9b70b8e990522072", size = 17499 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5d/20/52fdb5ebb158294b0adb5662235dd396fc7e47aa31c293978d8d8942095a/sse_starlette-2.3.3-py3-none-any.whl", hash = "sha256:8b0a0ced04a329ff7341b01007580dd8cf71331cc21c0ccea677d500618da1e0", size = 10235 },
+]
+
[[package]]
name = "starlette"
version = "0.46.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "anyio", marker = "sys_platform != 'win32'" },
+ { name = "anyio", marker = "python_full_version >= '3.10' or sys_platform != 'win32'" },
{ name = "typing-extensions", marker = "python_full_version < '3.10' and sys_platform != 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ce/20/08dfcd9c983f6a6f4a1000d934b9e6d626cff8d2eeb77a89a68eef20a2b7/starlette-0.46.2.tar.gz", hash = "sha256:7f7361f34eed179294600af672f565727419830b54b7b084efe44bb82d2fccd5", size = 2580846 }
@@ -2981,9 +3042,9 @@ name = "uvicorn"
version = "0.29.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "click", marker = "sys_platform != 'win32'" },
- { name = "h11", marker = "sys_platform != 'win32'" },
- { name = "typing-extensions", marker = "python_full_version < '3.11' and sys_platform != 'win32'" },
+ { name = "click", marker = "python_full_version >= '3.10' or sys_platform != 'win32'" },
+ { name = "h11", marker = "python_full_version >= '3.10' or sys_platform != 'win32'" },
+ { name = "typing-extensions", marker = "(python_full_version < '3.11' and sys_platform != 'win32') or (python_full_version == '3.10.*' and sys_platform == 'win32')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/49/8d/5005d39cd79c9ae87baf7d7aafdcdfe0b13aa69d9a1e3b7f1c984a2ac6d2/uvicorn-0.29.0.tar.gz", hash = "sha256:6a69214c0b6a087462412670b3ef21224fa48cae0e452b5883e8e8bdfdd11dd0", size = 40894 }
wheels = [