This example demonstrates how to implement Code execution with MCP by leveraging mcputil and deepagents.
As MCP usage scales, there are two common patterns that can increase agent cost and latency:
- Tool definitions overload the context window;
- Intermediate tool results consume additional tokens.
As a solution, Code execution with MCP thus came into being:
- Present MCP servers as code APIs rather than direct tool calls;
- The agent can then write code to interact with MCP servers.
This approach addresses both challenges: agents can load only the tools they need and process data in the execution environment before passing results back to the model.
Install mcputil:
pip install mcputilInstall dependencies:
pip install deepagents
pip install langchain-community
pip install langchain-experimentalRun the MCP servers:
python examples/code-execution/google_drive.py
# In another terminal
python examples/code-execution/salesforce.pyGenerate a file tree of all available tools from MCP servers:
mcputil \
-s='{"name": "google_drive", "url": "http://localhost:8000"}' \
-s='{"name": "salesforce", "url": "http://localhost:8001"}' \
-o examples/code-execution/output/servers
# Or use the `mcp.json` file directly
mcputil \
-c examples/code-execution/mcp.json \
-o examples/code-execution/output/serversFor those who want to preview the final generated code, see the pre-generated servers.
Run the example agent:
export ANTHROPIC_API_KEY="your-api-key"
python examples/code-execution/agent.py