Connects DSPy agents to external MCP tool servers for runtime tool discovery and integration with ReAct or CodeAct agents.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through connecting DSPy agents to MCP (Model Context Protocol) servers, discovering tools at runtime, and wiring them into ReAct or CodeAct agents.
DSPy can consume tools from any MCP-compatible server using dspy.Tool.from_mcp_tool(). This lets your agents use tools hosted externally -- databases, file systems, web APIs, or custom services -- without writing Python wrappers for each one. The MCP server handles execution; DSPy handles reasoning.
| Use MCP when... | Use plain dspy.Tool when... |
|---|---|
| Tools are hosted on a separate process or server | You have a simple Python function |
| You want to reuse tools across multiple AI systems | The tool is specific to this DSPy program |
| Tools need isolation (file system access, DB connections) | No isolation needed |
| An MCP server already exists for your use case | You are building tools from scratch |
| You need runtime tool discovery (tools change dynamically) | Tool set is fixed at development time |
pip install dspy mcp
MCP servers communicate via stdio. Use StdioServerParameters to configure the server command and stdio_client to establish the connection:
import dspy
from mcp import StdioServerParameters, ClientSession
from mcp.client.stdio import stdio_client
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# Configure the MCP server to connect to
server_params = StdioServerParameters(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"],
)
Inside an async context, connect to the server, list available tools, and convert them to DSPy tools:
import asyncio
async def build_agent():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the MCP connection
await session.initialize()
# Discover available tools
mcp_tools = await session.list_tools()
print(f"Found {len(mcp_tools.tools)} tools")
# Convert MCP tools to DSPy tools
dspy_tools = [
dspy.Tool.from_mcp_tool(session, tool)
for tool in mcp_tools.tools
]
# Build a ReAct agent with the discovered tools
agent = dspy.ReAct(
"question -> answer",
tools=dspy_tools,
)
# Use acall() for async tool execution
result = await agent.acall(question="List all Python files in the project")
print(result.answer)
asyncio.run(build_agent())
The converted tools work exactly like native DSPy tools:
async def run_agent_with_mcp():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
mcp_tools = await session.list_tools()
dspy_tools = [
dspy.Tool.from_mcp_tool(session, tool)
for tool in mcp_tools.tools
]
# ReAct agent
agent = dspy.ReAct(
"task -> result",
tools=dspy_tools,
max_iters=10,
)
# Must use acall() because MCP tools are async
result = await agent.acall(task="Find the largest file and summarize it")
return result
Important: Use await agent.acall() (not agent()) because MCP tool calls are async operations.
Mix MCP-discovered tools with locally-defined Python tools:
def calculate(expression: str) -> str:
"""Evaluate a math expression."""
return str(eval(expression)) # use a safe evaluator in production
async def build_hybrid_agent():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
mcp_tools = await session.list_tools()
dspy_tools = [
dspy.Tool.from_mcp_tool(session, tool)
for tool in mcp_tools.tools
]
# Combine MCP tools with local tools
all_tools = dspy_tools + [calculate]
agent = dspy.ReAct("question -> answer", tools=all_tools)
result = await agent.acall(question="How many lines in main.py divided by 3?")
return result
MCP connections can fail. Wrap the connection in proper error handling:
from mcp import McpError
async def safe_agent_call(question: str):
try:
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
mcp_tools = await session.list_tools()
dspy_tools = [
dspy.Tool.from_mcp_tool(session, tool)
for tool in mcp_tools.tools
]
agent = dspy.ReAct("question -> answer", tools=dspy_tools)
return await agent.acall(question=question)
except McpError as e:
print(f"MCP server error: {e}")
return None
except ConnectionError:
print("Could not connect to MCP server")
return None
acall() and uses synchronous agent(). MCP tools are async -- you must use await agent.acall() or you get runtime errors. DSPy cannot call async MCP tools from a sync context.async with block. The MCP session is only valid inside the context manager. If you build the tools inside and call the agent outside, the session is closed and tool calls fail.session.list_tools() to get the current tool set -- MCP servers can add/remove tools dynamically.StdioServerParameters launches the server process. If the command fails (e.g., npx not installed, package not found), you get a cryptic connection error. Test the server command manually first.stdio_client context and one ClientSession context. Do not add extra wrappers.Tool descriptions matter for agent performance. The GEPA paper (arxiv 2507.19457) includes an MCP adapter that can automatically optimize tool descriptions -- not just task instructions -- through the same reflective evolution process. If your agent struggles to pick the right tool or misuses tool parameters, consider optimizing tool descriptions with /dspy-gepa.
Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-tools/dspy-react/dspy-codeact/ai-taking-actions/dspy-async/ai-do if you do not have it -- it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
dspy, mcp, agent-tools, model-context-protocol, tool-integration, dspy-mcp
/dspy-api-skills:dspy-mcpfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time.Other plugins' skills for the same job