Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MCP Integration

MCP (Model Context Protocol) is a standard for AI assistants to communicate with tool servers. Eryx can discover and connect to MCP servers, exposing their tools as async callbacks inside the sandbox.

This means sandboxed Python code can call tools from any MCP server — filesystem access, GitHub, databases, web search, and more — all while maintaining the security of the sandbox.

How It Works

MCP tools are bridged into the sandbox as async callbacks. The entire call path is handled in Rust, bypassing the Python GIL:

Sandbox Python code
    → await mcp["server"].tool(args)
    → WASM callback invoke
    → Rust DynamicCallback
    → rmcp client
    → MCP server (stdio)

From Python’s perspective, MCP tools appear as async functions under the mcp namespace:

# Inside the sandbox
result = await mcp["github"].search_repos(query="eryx sandbox")
print(result["items"])

result = await mcp["filesystem"].read_file(path="/tmp/data.txt")
print(result["text"])

Config Discovery

When --mcp is passed (or connect_servers() is called), Eryx searches the user-wide MCP server configurations of multiple IDEs and tools. Project configs in the current directory are read only with --mcp-project (or include_project=True), since they name commands that run on your machine. Only stdio-type servers are supported.

Supported Config Files

Global (user-wide):

ToolPathKey
Claude Code~/.claude.jsonmcpServers
Cursor~/.cursor/mcp.jsonmcpServers
Windsurf~/.codeium/windsurf/mcp_config.jsonmcpServers
Zed~/.config/zed/settings.jsoncontext_servers
Gemini CLI~/.gemini/settings.jsonmcpServers
Codex~/.codex/config.tomlmcp_servers

Project (cwd-relative, only with --mcp-project):

ToolPathKey
Claude Code.mcp.jsonmcpServers
Cursor.cursor/mcp.jsonmcpServers
VS Code.vscode/mcp.jsonservers
Zed.zed/settings.jsoncontext_servers
Gemini CLI.gemini/settings.jsonmcpServers
Codex.codex/config.tomlmcp_servers

Later sources override earlier ones, except that a project config never replaces a global server of the same name.

Config Format

Most tools use the same JSON format. Here’s a .mcp.json example:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-filesystem", "/tmp"]
    }
  }
}

Environment variables are expanded in env values using $VAR, ${VAR}, or ${VAR:-default} syntax.

Servers with "disabled": true, "enabled": false, or a non-stdio "type" are skipped.

CLI Usage

Enable MCP with the --mcp flag:

# Auto-discover servers from all supported config files
python -m eryx --mcp -c 'tools = list_callbacks(); print([t["name"] for t in tools])'

# Use a specific config file
python -m eryx --mcp-config .mcp.json -c 'r = await mcp["github"].search_repos(query="eryx"); print(r)'

# Multiple config files (later overrides earlier)
python -m eryx --mcp-config global.json --mcp-config project.json -c '...'
FlagDescription
--mcpEnable MCP server integration (auto-discovers from user-wide configs)
--mcp-projectAlso read project configs in the current directory (implies --mcp)
--mcp-config PATHPath to MCP config file (implies --mcp, can be repeated)

Python API

Using connect_servers (High-Level)

The eryx.mcp module provides a high-level helper that discovers and connects to servers:

import eryx
from eryx.mcp import connect_servers

# Auto-discover and connect to all configured MCP servers
manager = connect_servers()

if manager is not None:
    # List discovered tools
    for tool in manager.list_tools():
        print(f"{tool['name']}: {tool['description']}")

    # Use with a sandbox
    sandbox = eryx.Sandbox(mcp=manager)
    result = sandbox.execute("""
r = await mcp["github"].search_repos(query="python sandbox")
print(f"Found {len(r['items'])} repos")
""")
    print(result.stdout_text)

    # Clean up
    manager.close()

Using MCPManager (Low-Level)

For more control, create and configure the MCPManager directly:

import eryx

manager = eryx.MCPManager()

# Connect to specific servers
manager.connect(
    "my-server",           # server name
    "npx",                 # command
    ["-y", "my-mcp-pkg"],  # args
    {"API_KEY": "sk-..."},  # env
    30.0,                   # timeout (seconds)
)

print(f"Servers: {manager.server_names}")
print(f"Tools: {[t['name'] for t in manager.list_tools()]}")

# Use with Sandbox or Session
sandbox = eryx.Sandbox(mcp=manager)
session = eryx.Session(mcp=manager)

# Always close when done
manager.close()

Combining MCP with Python Callbacks

MCP tools and Python callbacks can be used together:

import eryx
from eryx.mcp import connect_servers

def my_transform(text: str):
    return {"result": text.upper()}

manager = connect_servers()

sandbox = eryx.Sandbox(
    mcp=manager,
    callbacks=[
        {"name": "transform", "fn": my_transform, "description": "Uppercases text"}
    ],
)

result = sandbox.execute("""
# MCP tool
data = await mcp["filesystem"].read_file(path="/tmp/input.txt")

# Python callback
upper = await transform(text=data["text"])
print(upper["result"])
""")

Tool Naming

MCP tools are exposed in the sandbox under the mcp namespace using bracket syntax for server names:

# Inside the sandbox
result = await mcp["github"].search_repos(query="test")
#              ^^^  ^^^^^^^^  ^^^^^^^^^^^^
#              |    |         tool name
#              |    server name
#              mcp namespace

The bracket syntax is unambiguous and works for all server names, including those with hyphens or other special characters:

result = await mcp["my-server"].echo(message="hello")
result = await mcp["my-server"]["some-tool"](arg=1)

Dotted Syntax

When server and tool names are valid Python identifiers, you can also use dotted attribute access:

# Equivalent — only works when names are valid identifiers
await mcp.github.search_repos(query="test")

All styles are equivalent and can be mixed:

# These all call the same tool:
await mcp["github"].search_repos(query="test")         # bracket (recommended)
await mcp["github"]["search_repos"](query="test")     # full bracket
await mcp.github.search_repos(query="test")           # dotted
await invoke("mcp.github.search_repos", query="test")  # invoke()

The invoke() function works with any callback name string, regardless of special characters.

Introspection

Discover available MCP tools at runtime:

# Inside the sandbox
callbacks = list_callbacks()
mcp_tools = [c for c in callbacks if c["name"].startswith("mcp.")]
for tool in mcp_tools:
    print(f"{tool['name']}: {tool['description']}")
    print(f"  Parameters: {tool['schema']}")

Best Practices

  1. Use auto-discovery for convenience — --mcp finds servers from your user-wide IDE configs automatically; add --mcp-project only in directories you trust
  2. Use explicit configs for reproducibility — --mcp-config ensures consistent behavior across machines
  3. Close the manager — Always call manager.close() when done to terminate MCP server processes
  4. Handle missing tools gracefully — Not all servers may be available in every environment
  5. Set appropriate timeouts — The default 30s connection timeout can be adjusted via connect_timeout

Next Steps

  • MCP Server — Expose the sandbox as an MCP tool
  • Callbacks — Define custom host-side callbacks
  • CLI — Full CLI reference
  • Sessions — Persistent state across executions