Skip to content
Back to search

mcp-server-code-execution-mode

An MCP server that executes Python code in isolated rootless containers with optional MCP server proxying. Implementation of Anthropic's and Cloudflare's ideas for reducing MCP tool definitions context bloat.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/elusznik--mcp-server-code-execution-mode/badge.svg)](/listings/elusznik--mcp-server-code-execution-mode)

HTML

<a href="/listings/elusznik--mcp-server-code-execution-mode"><img src="/api/listings/elusznik--mcp-server-code-execution-mode/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

1. Prerequisites (macOS or Linux)

- Check version: `python3 --version` (Python 3.11+ required) - If needed, install Python via package manager or [python.org](https://python.org) - macOS: `brew install podman` or `brew install --cask docker` - Ubuntu/Debian: `sudo apt-get install -y podman` or `curl -fsSL https://get.docker.com | sh`

curl -LsSf https://astral.sh/uv/install.sh | sh
podman pull python:3.13-slim
# or
docker pull python:3.13-slim

Note on Pydantic compatibility:

- If you use Python 3.14+, ensure you have a modern Pydantic release installed (for example, `pydantic >= 2.12.0`). Some older Pydantic versions or environments that install a separate `typing` package from PyPI may raise errors such as:

TypeError: _eval_type() got an unexpected keyword argument 'prefer_fwd_module'

If you see this error, run:

pip install -U pydantic
pip uninstall typing  # if present; the stdlib's typing should be used

And re-run the project setup (e.g. remove `.venv/` and `uv sync`).

2. Install Dependencies

Use uv to sync the project environment:

uv sync

3. Launch Bridge

uvx --from git+https://github.com/elusznik/mcp-server-code-execution-mode mcp-server-code-execution-mode run

If you prefer to run from a local checkout, the equivalent command is:

uv run python mcp_server_code_execution_mode.py

4. Register with Your Agent

Add the following server configuration to your agent's MCP settings file (e.g., `mcp_config.json`, `claude_desktop_config.json`, etc.):

{
  "mcpServers": {
    "mcp-server-code-execution-mode": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/elusznik/mcp-server-code-execution-mode",
        "mcp-server-code-execution-mode",
        "run"
      ],
      "env": {
        "MCP_BRIDGE_RUNTIME": "podman"
      }
    }
  }
}

5. Execute Code

# Use MCP tools in sandboxed code
result = await mcp_filesystem.read_file(path='/tmp/test.txt')

# Complex workflows
data = await mcp_search.search(query="TODO")
await mcp_github.create_issue(repo='owner/repo', title=data.title)

Load Servers Explicitly

`run_python` only loads the MCP servers you request. Pass them via the `servers` array when you invoke the tool so proxies such as `mcp_serena` or `mcp_filesystem` become available inside the sandbox:

{
  "code": "print(await mcp_serena.search(query='latest AI papers'))",
  "servers": ["serena", "filesystem"]
}

If you omit the list the discovery helpers still enumerate everything, but any RPC call that targets an unloaded server returns `Server '<name>' is not available`.

Note: The `servers` array only controls which proxies are generated for a sandbox invocation. It does not set server configuration fields such as `cwd`. The `cwd` property is part of the host/server config and LLMs should call `runtime.describe_server(name)` or inspect `runtime.list_loaded_server_metadata()` to discover the configured `cwd` before assuming the server's working directory.

Note: server configurations can include an optional `cwd` property. If present the bridge will start the host MCP server process in that working directory; agents should check `runtime.describe_server(name)` to discover a server's configured `cwd` before making assumptions.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 675 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Code Execution Server: Zero-Context Discovery for 100+ MCP Tools
  2. [![MseeP.ai Security Assessment Badge](https://mseep.net/pr/elusznik-mcp-server-code-execution-mode-badge.png)](https://mseep.ai/app/elusznik-mcp-server-code-execution-mode)
  3. **Stop paying 30,000 tokens per query.** This bridge implements Anthropic's discovery pattern with rootless security—reducing MCP context from 30K to 200 tokens while proxying any stdio server.
  4. [![Anthropic Engineering](https://img.shields.io/badge/Anthropic-Engineering-orange)](https://www.anthropic.com/engineering/code-execution-with-mcp)
  5. [![Cloudflare Blog](https://img.shields.io/badge/Cloudflare-Code_Mode-orange)](https://blog.cloudflare.com/code-mode/)
  6. [![Docker MCP Gateway](https://img.shields.io/badge/Docker-MCP_Gateway-blue)](https://www.docker.com/blog/dynamic-mcps-stop-hardcoding-your-agents-world/)
  7. [![Apple Machine Learning](https://img.shields.io/badge/Apple_Machine_Learning-CodeAct?logo=apple&style=flat-square)](https://machinelearning.apple.com/research/codeact)
  8. [![MCP Protocol](https://img.shields.io/badge/MCP-Documentation-green)](https://modelcontextprotocol.io/)
  9. [![Verified on MseeP](https://mseep.ai/badge.svg)](https://mseep.ai/app/4a84c349-1795-41fc-a299-83d4a29feee8)
  10. ## Overview
  11. This bridge implements the **"Code Execution with MCP"** pattern, a convergence of ideas from industry leaders:
  12. - **Apple's [CodeAct](https://machinelearning.apple.com/research/codeact)**: "Your LLM Agent Acts Better when Generating Code."
  13. - **Anthropic's [Code execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp)**: "Building more efficient agents."
  14. - **Cloudflare's [Code Mode](https://blog.cloudflare.com/code-mode/)**: "LLMs are better at writing code to call MCP, than at calling MCP directly."
  15. - **Docker's [Dynamic MCPs](https://www.docker.com/blog/dynamic-mcps-stop-hardcoding-your-agents-world/)**: "Stop Hardcoding Your Agents’ World."
  16. - **[Terminal Bench](https://www.tbench.ai)'s [Terminus](https://www.tbench.ai/terminus)**: "A realistic terminal environment for evaluating LLM agents."
  17. Instead of exposing hundreds of individual tools to the LLM (which consumes massive context and confuses the model), this bridge exposes **one** tool: `run_python`. The LLM writes Python code to discover, call, and compose other tools.
  18. ### Why This vs. JS "Code Mode"?
  19. While there are JavaScript-based alternatives (like [`universal-tool-calling-protocol/code-mode`](https://github.com/universal-tool-calling-protocol/code-mode)), this project is built for **Data Science** and **Security**:
  20. | Feature | This Project (Python) | JS Code Mode (Node.js) |
  21. | :--- | :--- | :--- |
  22. | **Native Language** | **Python** (The language of AI/ML) | TypeScript/JavaScript |
  23. | **Data Science** | **Native** (`pandas`, `numpy`, `scikit-learn`) | Impossible / Hacky |
  24. | **Isolation** | **Hard** (Podman/Docker Containers) | Soft (Node.js VM) |
  25. | **Security** | **Enterprise** (Rootless, No Net, Read-Only) | Process-level |
  26. | **Philosophy** | **Infrastructure** (Standalone Bridge) | Library (Embeddable) |
  27. **Choose this if:** You want your agent to analyze data, generate charts, use scientific libraries, or if you require strict container-based isolation for running untrusted code.
  28. ## What This Solves (That Others Don't)
  29. ### The Pain: MCP Token Bankruptcy
  30. Connect Claude to 11 MCP servers with ~100 tools = **30,000 tokens** of tool schemas loaded into every prompt. That's **$0.09 per query** before you ask a single question. Scale to 50 servers and your context window *breaks*.
  31. ### Why Existing "Solutions" Fail
  32. - **Docker MCP Gateway**: Manages containers beautifully, but still streams **all tool schemas** into Claude's context. No token optimization.
  33. - **Cloudflare Code Mode**: V8 isolates are fast, but you **can't proxy your existing MCP servers** (Serena, Wolfram, custom tools). Platform lock-in.
  34. - **Academic Papers**: Describe Anthropic's discovery pattern, but provide **no hardened implementation**.
  35. - **Proofs of Concept**: Skip security (no rootless), skip persistence (cold starts), skip proxying edge cases.
  36. ### The Fix: Discovery-First Architecture
  37. - **Constant 200-token overhead** regardless of server count
  38. - **Proxy any stdio MCP server** into rootless containers
  39. - **Fuzzy search across servers** without preloading schemas
  40. - **Production-hardened** with capability dropping and security isolation
  41. ### Architecture: How It Differs
  42. ```text
  43. Traditional MCP (Context-Bound)
  44. ┌─────────────────────────────┐
  45. │ LLM Context (30K tokens) │
  46. │ - serverA.tool1: {...} │
  47. │ - serverA.tool2: {...} │
  48. │ - serverB.tool1: {...} │
  49. │ - … (dozens more) │
  50. └─────────────────────────────┘
  51. ↓
  52. LLM picks tool
  53. ↓
  54. Tool executes
  55. This Bridge (Discovery-First)
  56. ┌─────────────────────────────┐
  57. │ LLM Context (≈200 tokens) │
  58. │ “Use discovered_servers(), │
  59. │ query_tool_docs(), │
  60. │ search_tool_docs()” │
  61. └─────────────────────────────┘
  62. ↓
  63. LLM discovers servers
  64. ↓
  65. LLM hydrates schemas
  66. ↓
  67. LLM writes Python
  68. ↓
  69. Bridge proxies execution
  70. ```
  71. Result: constant overhead. Whether you manage 10 or 1000 tools, the system prompt stays right-sized and schemas flow only when requested.
  72. ### Comparison At A Glance
  73. | Capability | Docker MCP Gateway | Cloudflare Code Mode | Research Patterns | This Bridge |
  74. |------------|--------------------|----------------------|-------------------|--------------|
  75. | Solves token bloat | ❌ Manual preload | ❌ Fixed catalog | ❌ Theory only | ✅ Discovery runtime |
  76. | Universal MCP proxying | ✅ Containers | ⚠️ Platform-specific | ❌ Not provided | ✅ Any stdio server |
  77. | Rootless security | ⚠️ Optional | ✅ V8 isolate | ❌ Not addressed | ✅ Cap-dropped sandbox |
  78. | Auto-discovery | ⚠️ Catalog-bound | ❌ N/A | ❌ Not implemented | ✅ 12+ config paths |
  79. | Tool doc search | ❌ | ❌ | ⚠️ Conceptual | ✅ `search_tool_docs()` |
  80. | Production hardening | ⚠️ Depends on you | ✅ Managed service | ❌ Prototype | ✅ Tested bridge |
  81. ### Vs. Dynamic Toolsets (Speakeasy)
  82. Speakeasy's [Dynamic Toolsets](https://www.speakeasy.com/blog/how-we-reduced-token-usage-by-100x-dynamic-toolsets-v2) use a 3-step flow: `search_tools` → `describe_tools` → `execute_tool`. While this saves tokens, it forces the agent into a "chatty" loop:
  83. 1. **Search**: "Find tools for GitHub issues"
  84. 2. **Describe**: "Get schema for `create_issue`"
  85. 3. **Execute**: "Call `create_issue`"
  86. **This Bridge (Code-First) collapses that loop:**
  87. 1. **Code**: "Import `mcp_github`, search for 'issues', and create one if missing."
  88. The agent writes a **single Python script** that performs discovery, logic, and execution in one round-trip. It's faster, cheaper (fewer intermediate LLM calls), and handles complex logic (loops, retries) that a simple "execute" tool cannot.
  89. ### Vs. OneMCP (Gentoro)
  90. [OneMCP](https://github.com/Gentoro-OneMCP/onemcp) provides a "Handbook" chat interface where you ask questions and it plans execution. This is great for simple queries but turns the execution into a **black box**.
  91. **This Bridge** gives the agent **raw, sandboxed control**. The agent isn't asking a black box to "do it"; the agent *is* the programmer, writing the exact code to interact with the API. This allows for precise edge-case handling and complex data processing that a natural language planner might miss.
  92. ### Unique Features
  93. 1. **Two-stage discovery** – `discovered_servers()` reveals what exists; `query_tool_docs(name)` loads only the schemas you need.
  94. 2. **Fuzzy search across servers** – let the model find tools without memorising catalog names:
  95. ```python
  96. from mcp import runtime
  97. matches = await runtime.search_tool_docs("calendar events", limit=5)
  98. for hit in matches:
  99. print(hit["server"], hit["tool"], hit.get("description", ""))
  100. ```
  101. 3. **Zero-copy proxying** – every tool call stays within the sandbox, mirrored over stdio with strict timeouts.
  102. 4. **Rootless by default** – Podman/Docker containers run with `--cap-drop=ALL`, read-only root, no-new-privileges, and explicit memory/PID caps.
  103. 5. **Compact + TOON output** – minimal plain-text responses for most runs, with deterministic TOON blocks available via `MCP_BRIDGE_OUTPUT_MODE=toon`.
  104. ### Who This Helps
  105. - Teams juggling double-digit MCP servers who cannot afford context bloat.
  106. - Agents that orchestrate loops, retries, and conditionals rather than single tool invocations.
  107. - Security-conscious operators who need rootless isolation for LLM-generated code.
  108. - Practitioners who want to reuse existing MCP catalogs without hand-curating manifests.
  109. ### Philosophy: The "No-MCP" Approach
  110. This server aligns with the philosophy that [you might not need MCP at all](https://mariozechner.at/posts/2025-11-02-what-if-you-dont-need-mcp/) for every little tool. Instead of building rigid MCP servers for simple tasks, you can use this server to give your agent **raw, sandboxed access to Bash and Python**.
  111. - **Ad-Hoc Tools**: Need a script to scrape a site or parse a file? Just write it and run it. No need to deploy a new MCP server.
  112. - **Composability**: Pipe outputs between commands, save intermediate results to files, and use standard Unix tools.
  113. - **Safety**: Unlike giving an agent raw shell access to your machine, this server runs everything in a secure, rootless container. You get the power of "Bash/Code" without the risk.
  114. ## Key Features
  115. ### 🛡️ Robustness & Reliability
  116. - **Lazy Runtime Detection**: Starts up instantly even if Podman/Docker isn't ready. Checks for runtime only when code execution is requested.
  117. - **Self-Reference Prevention**: Automatically detects and skips configurations that would launch the bridge recursively.
  118. - **Noise Filtering**: Ignores benign JSON parse errors (like blank lines) from chatty MCP clients.
  119. - **Smart Volume Sharing**: Probes Podman VMs to ensure volume sharing works, even on older versions.
  120. ### 🔒 Security First
  121. - **Rootless containers** - No privileged helpers required
  122. - **Network isolation** - No network access
  123. - **Read-only filesystem** - Immutable root
  124. - **Dropped capabilities** - No system access
  125. - **Unprivileged user** - Runs as UID 65534
  126. - **Resource limits** - Memory, PIDs, CPU, time
  127. - **Auto-cleanup** - Temporary IPC directories
  128. ### ⚡ Performance
  129. - **Persistent sessions** - Variables and state retained across calls
  130. - **Persistent clients** - MCP servers stay warm
  131. - **Context efficiency** - 95%+ reduction vs traditional MCP
  132. - **Async execution** - Proper resource management
  133. - **Single tool** - Only `run_python` in Claude's context
  134. ### 🔧 Developer Experience
  135. - **Multiple access patterns**:
  136. ```python
  137. mcp_servers["server"] # Dynamic lookup
  138. mcp_server_name # Attribute access
  139. from mcp.servers.server import * # Module import
  140. ```
  141. - **Top-level await** - Modern Python patterns
  142. - **Type-safe** - Proper signatures and docs
  143. - **Compact responses** - Plain-text output by default with optional TOON blocks when requested
  144. ### Response Formats
  145. - **Default (compact)** – responses render as plain text plus a minimal `structuredContent` payload containing only non-empty fields. `stdout`/`stderr` lines stay intact, so prompts remain lean without sacrificing content.
  146. - **Optional TOON** – set `MCP_BRIDGE_OUTPUT_MODE=toon` to emit [Token-Oriented Object Notation](https://github.com/toon-format/toon) blocks. We still drop empty fields and mirror the same structure in `structuredContent`; TOON is handy when you want deterministic tokenisation for downstream prompts.
  147. - **Fallback JSON** – if the TOON encoder is unavailable we automatically fall back to pretty JSON blocks while preserving the trimmed payload.
  148. ### 🧠 Persistent Memory System
  149. - **Cross-session persistence** - Memory data survives container restarts and sessions
  150. - **JSON-based storage** - Flexible value types (strings, dicts, lists, etc.)
  151. - **Metadata support** - Add tags and custom metadata to memory entries
  152. - **Atomic updates** - Update memory values with custom functions
  153. - **Discovery-friendly** - List all memories and check existence
  154. ```python
  155. # Save context for future sessions
  156. save_memory("project_context", {
  157. "goal": "Build REST API",
  158. "current_task": "Implement auth",
  159. "decisions": ["Use JWT tokens", "PostgreSQL backend"]
  160. })
  161. # Retrieve in a later session
  162. context = load_memory("project_context")
  163. print(f"Working on: {context['current_task']}")
  164. # Update incrementally
  165. update_memory("project_context", lambda ctx: {
  166. **ctx,
  167. "decisions": ctx["decisions"] + ["Add rate limiting"]
  168. })
  169. # List all saved memories
  170. for mem in list_memories():
  171. print(f"{mem['key']}: created {mem['created_at']}")
  172. # Check existence before loading
  173. if memory_exists("user_preferences"):
  174. prefs = load_memory("user_preferences")
  175. ```
  176. Memory files are stored in `/projects/memory/` inside the container, which maps to `~/MCPs/user_tools/memory/` on the host. This persists across sessions and container restarts.
  177. ### Discovery Workflow
  178. - `SANDBOX_HELPERS_SUMMARY` in the tool schema only advertises the discovery helpers (`discovered_servers()`, `list_servers()`, `query_tool_docs()`, `search_tool_docs()`, etc.). It never includes individual server or tool documentation.
  179. - On first use the LLM typically calls `discovered_servers()` (or `list_servers_sync()` for the cached list) to enumerate MCP servers, then `query_tool_docs(server)` / `query_tool_docs_sync(server)` or `search_tool_docs("keyword")` / `search_tool_docs_sync("keyword")` to fetch the relevant subset of documentation.
  180. - Tool metadata is streamed on demand, keeping the system prompt at roughly 200 tokens regardless of how many servers or tools are installed.
  181. - Once the LLM has the docs it needs, it writes Python that uses the generated `mcp_<alias>` proxies or `mcp.runtime` helpers to invoke tools.
  182. **Need a short description without probing the helpers?** Call `runtime.capability_summary()` to print a one-paragraph overview suitable for replying to questions such as “what can the code-execution MCP do?”
  183. ## Quick Start
  184. ### 1. Prerequisites (macOS or Linux)
  185. - Check version: `python3 --version` (Python 3.11+ required)
  186. - If needed, install Python via package manager or [python.org](https://python.org)
  187. - macOS: `brew install podman` or `brew install --cask docker`
  188. - Ubuntu/Debian: `sudo apt-get install -y podman` or `curl -fsSL https://get.docker.com | sh`
  189. ```bash
  190. curl -LsSf https://astral.sh/uv/install.sh | sh
  191. ```
  192. ```bash
  193. podman pull python:3.13-slim
  194. # or
  195. docker pull python:3.13-slim
  196. ```
  197. Note on Pydantic compatibility:
  198. - If you use Python 3.14+, ensure you have a modern Pydantic release installed (for example, `pydantic >= 2.12.0`). Some older Pydantic versions or environments that install a separate `typing` package from PyPI may raise errors such as:
  199. ```text
  200. TypeError: _eval_type() got an unexpected keyword argument 'prefer_fwd_module'
  201. ```
  202. If you see this error, run:
  203. ```bash
  204. pip install -U pydantic
  205. pip uninstall typing # if present; the stdlib's typing should be used
  206. ```
  207. And re-run the project setup (e.g. remove `.venv/` and `uv sync`).
  208. ### 2. Install Dependencies
  209. Use uv to sync the project environment:
  210. ```bash
  211. uv sync
  212. ```
  213. ### 3. Launch Bridge
  214. ```bash
  215. uvx --from git+https://github.com/elusznik/mcp-server-code-execution-mode mcp-server-code-execution-mode run
  216. ```
  217. If you prefer to run from a local checkout, the equivalent command is:
  218. ```bash
  219. uv run python mcp_server_code_execution_mode.py
  220. ```
  221. ### 4. Register with Your Agent
  222. Add the following server configuration to your agent's MCP settings file (e.g., `mcp_config.json`, `claude_desktop_config.json`, etc.):
  223. ```json
  224. {
  225. "mcpServers": {
  226. "mcp-server-code-execution-mode": {
  227. "command": "uvx",
  228. "args": [
  229. "--from",
  230. "git+https://github.com/elusznik/mcp-server-code-execution-mode",
  231. "mcp-server-code-execution-mode",
  232. "run"
  233. ],
  234. "env": {
  235. "MCP_BRIDGE_RUNTIME": "podman"
  236. }
  237. }
  238. }
  239. }
  240. ```
  241. ### 5. Execute Code
  242. ```python
  243. # Use MCP tools in sandboxed code
  244. result = await mcp_filesystem.read_file(path='/tmp/test.txt')
  245. # Complex workflows
  246. data = await mcp_search.search(query="TODO")
  247. await mcp_github.create_issue(repo='owner/repo', title=data.title)
  248. ```
  249. ### Load Servers Explicitly
  250. `run_python` only loads the MCP servers you request. Pass them via the `servers` array when you invoke the tool so proxies such as `mcp_serena` or `mcp_filesystem` become available inside the sandbox:
  251. ```json
  252. {
  253. "code": "print(await mcp_serena.search(query='latest AI papers'))",
  254. "servers": ["serena", "filesystem"]
  255. }
  256. ```
  257. If you omit the list the discovery helpers still enumerate everything, but any RPC call that targets an unloaded server returns `Server '<name>' is not available`.
  258. Note: The `servers` array only controls which proxies are generated for a sandbox invocation. It does not set server configuration fields such as `cwd`. The `cwd` property is part of the host/server config and LLMs should call `runtime.describe_server(name)` or inspect `runtime.list_loaded_server_metadata()` to discover the configured `cwd` before assuming the server's working directory.
  259. Note: server configurations can include an optional `cwd` property. If present the bridge will start the host MCP server process in that working directory; agents should check `runtime.describe_server(name)` to discover a server's configured `cwd` before making assumptions.
  260. ## Testing
  261. Project environments support CPython 3.11+. Ensure your local environment uses a compatible Python version:
  262. ```bash
  263. uv python pin 3.13
  264. uv sync
  265. ```
  266. Runtime dependencies stay lean; dev dependencies (pytest, etc.) are available via the `dev` extra:
  267. ```bash
  268. # Install with dev dependencies
  269. uv sync --group dev
  270. # Run tests
  271. uv run pytest
  272. # Or run without installing dev dependencies permanently
  273. uv run --with pytest pytest
  274. ```
  275. ## Architecture
  276. ```text
  277. ┌─────────────┐
  278. │ MCP Client │ (Your Agent)
  279. └──────┬──────┘
  280. │ stdio
  281. ▼
  282. ┌──────────────┐
  283. │ MCP Code Exec │ ← Discovers, proxies, manages
  284. │ Bridge │
  285. └──────┬──────┘
  286. │ container
  287. ▼
  288. ┌─────────────┐
  289. │ Container │ ← Executes with strict isolation
  290. │ Sandbox │
  291. └─────────────┘
  292. ```
  293. ### Zero-Context Discovery
  294. Unlike traditional MCP servers that preload every tool definition (sometimes 30k+ tokens), this bridge pins its system prompt to roughly 200 tokens and trains the LLM to discover what it needs on demand:
  295. 1. LLM calls `discovered_servers()` → learns which bridges are available without loading schemas.
  296. 2. LLM calls `query_tool_docs("serena")` → hydrates just that server's tool docs, optionally filtered per tool.
  297. 3. LLM writes orchestration code → invokes helpers like `mcp_serena.search()` or `mcp.runtime.call_tool()`.
  298. **Result:** context usage stays effectively constant no matter how many MCP servers you configure.
  299. **Process:**
  300. 1. Client calls `run_python(code, servers, timeout)`
  301. 2. Bridge loads requested MCP servers
  302. 3. Prepares a sandbox invocation: collects MCP tool metadata, writes an entrypoint into a shared `/ipc` volume, and exports `MCP_AVAILABLE_SERVERS`
  303. 4. Generated entrypoint rewires stdio into JSON-framed messages and proxies MCP calls over the container's stdin/stdout pipe
  304. 5. **Persistent Execution**: The container is started once (if not running) and stays active.
  305. 6. **State Retention**: Variables, imports, and functions defined in one call are available in subsequent calls.
  306. 7. Host stream handler processes JSON frames, forwards MCP traffic, enforces timeouts, and keeps the container alive for the next request.
  307. ## Configuration
  308. ### Environment Variables
  309. | Variable | Default | Description |
  310. |----------|---------|-------------|
  311. | `MCP_BRIDGE_RUNTIME` | auto | Container runtime (podman/docker) |
  312. | `MCP_BRIDGE_IMAGE` | python:3.14-slim | Container image |
  313. | `MCP_BRIDGE_TIMEOUT` | 30s | Default timeout |
  314. | `MCP_BRIDGE_MAX_TIMEOUT` | 120s | Max timeout |
  315. | `MCP_BRIDGE_MEMORY` | 512m | Memory limit |
  316. | `MCP_BRIDGE_PIDS` | 128 | Process limit |
  317. | `MCP_BRIDGE_CPUS` | - | CPU limit |
  318. | `MCP_BRIDGE_CONTAINER_USER` | 65534:65534 | Run as UID:GID |
  319. | `MCP_BRIDGE_RUNTIME_IDLE_TIMEOUT` | 300s | Shutdown delay |
  320. | `MCP_BRIDGE_STATE_DIR` | `~/MCPs` | Host directory for IPC sockets and temp state |
  321. | `MCP_BRIDGE_OUTPUT_MODE` | `compact` | Response text format (`compact` or `toon`) |
  322. | `MCP_BRIDGE_LOG_LEVEL` | `INFO` | Bridge logging verbosity |
  323. ### Server Discovery
  324. The bridge automatically discovers MCP servers from multiple configuration sources:
  325. **Supported Locations:**
  326. | Location | Name | Priority |
  327. |----------|------|----------|
  328. | `~/MCPs/` | User MCPs | Highest |
  329. | `~/.config/mcp/servers/` | Standard MCP | |
  330. | `./mcp-servers/` | Local Project | |
  331. | `./.vscode/mcp.json` | VS Code Workspace | |
  332. | `~/.claude.json` | Claude CLI | |
  333. | `~/.cursor/mcp.json` | Cursor | |
  334. | `~/.opencode.json` | OpenCode CLI | |
  335. | `~/.codeium/windsurf/mcp_config.json` | Windsurf | |
  336. | `~/Library/Application Support/Claude Code/claude_code_config.json` | Claude Code (macOS) | |
  337. | `~/Library/Application Support/Claude/claude_desktop_config.json` | Claude Desktop (macOS) | |
  338. | `~/Library/Application Support/Code/User/settings.json` | VS Code Global (macOS) | |
  339. | `~/.config/Code/User/settings.json` | VS Code Global (Linux) | Lowest |
  340. > **Note:** Earlier sources take precedence. If the same server is defined in multiple locations, the first one wins.
  341. **Example Server** (`~/MCPs/filesystem.json`):
  342. ```json
  343. {
  344. "mcpServers": {
  345. "filesystem": {
  346. "command": "npx",
  347. "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
  348. }
  349. }
  350. }
  351. ```
  352. > **Note:** To prevent recursive launches, the bridge automatically skips any config entry that appears to start `mcp-server-code-execution-mode` again (including `uvx … mcp-server-code-execution-mode run`). Set `MCP_BRIDGE_ALLOW_SELF_SERVER=1` if you intentionally need to expose the bridge as a nested MCP server.
  353. ### Docker MCP Gateway Integration
  354. When you rely on `docker mcp gateway run` to expose third-party MCP servers, the bridge simply executes the gateway binary. The gateway is responsible for pulling tool images and wiring stdio transports, so make sure the host environment is ready:
  355. - Run `docker login` for every registry referenced in the gateway catalog (e.g. Docker Hub `mcp/*` images, `ghcr.io/github/github-mcp-server`). Without cached credentials the pull step fails before any tools come online.
  356. - Provide required secrets for those servers—`github-official` needs `github.personal_access_token`, others may expect API keys or auth tokens. Use `docker mcp secret set <name>` (or whichever mechanism your gateway is configured with) so the container sees the values at start-up.
  357. - Mirror any volume mounts or environment variables that the catalog expects (filesystem paths, storage volumes, etc.). Missing mounts or credentials commonly surface as `failed to connect: calling "initialize": EOF` during the stdio handshake.
  358. - If `list_tools` only returns the internal management helpers (`mcp-add`, `code-mode`, …), the gateway never finished initializing the external servers—check the gateway logs for missing secrets or registry access errors.
  359. ### State Directory & Volume Sharing
  360. - Runtime artifacts (including the generated `/ipc/entrypoint.py` and related handshake metadata) live under `~/MCPs/` by default. Set `MCP_BRIDGE_STATE_DIR` to relocate them.
  361. - When the selected runtime is Podman, the bridge automatically issues `podman machine set --rootful --now --volume <state_dir>:<state_dir>` so the VM can mount the directory. On older `podman machine` builds that do not support `--volume`, the bridge now probes the VM with `podman machine ssh test -d <state_dir>` and proceeds if the share is already available.
  362. - Docker Desktop does not expose a CLI for file sharing; ensure the chosen state directory is marked as shared in Docker Desktop → Settings → Resources → File Sharing before running the bridge.
  363. - To verify a share manually, run `docker run --rm -v ~/MCPs:/ipc alpine ls /ipc` (or the Podman equivalent) and confirm the files are visible.
  364. ## Usage Examples
  365. ### File Processing
  366. ```python
  367. # List and filter files
  368. files = await mcp_filesystem.list_directory(path='/tmp')
  369. for file in files:
  370. content = await mcp_filesystem.read_file(path=file)
  371. if 'TODO' in content:
  372. print(f"TODO in {file}")
  373. ```
  374. ### Data Pipeline
  375. ```python
  376. # Extract data
  377. transcript = await mcp_google_drive.get_document(documentId='abc123')
  378. # Process
  379. summary = transcript[:500] + "..."
  380. # Store
  381. await mcp_salesforce.update_record(
  382. objectType='SalesMeeting',
  383. recordId='00Q5f000001abcXYZ',
  384. data={'Notes': summary}
  385. )
  386. ```
  387. ### Multi-System Workflow
  388. ```python
  389. # Jira → GitHub migration
  390. issues = await mcp_jira.search_issues(project='API', status='Open')
  391. for issue in issues:
  392. details = await mcp_jira.get_issue(id=issue.id)
  393. if 'bug' in details.description.lower():
  394. await mcp_github.create_issue(
  395. repo='owner/repo',
  396. title=f"Bug: {issue.title}",
  397. body=details.description
  398. )
  399. ```
  400. ### Inspect Available Servers
  401. ```python
  402. from mcp import runtime
  403. print("Discovered:", runtime.discovered_servers())
  404. print("Cached servers:", runtime.list_servers_sync())
  405. print("Loaded metadata:", runtime.list_loaded_server_metadata())
  406. print("Selectable via RPC:", await runtime.list_servers())
  407. # Peek at tool docs for a server that's already loaded in this run
  408. loaded = runtime.list_loaded_server_metadata()
  409. if loaded:
  410. first = runtime.describe_server(loaded[0]["name"])
  411. for tool in first["tools"]:
  412. print(tool["alias"], "→", tool.get("description", ""))
  413. # Ask for summaries or full schemas only when needed
  414. if loaded:
  415. summaries = await runtime.query_tool_docs(loaded[0]["name"])
  416. detailed = await runtime.query_tool_docs(
  417. loaded[0]["name"],
  418. tool=summaries[0]["toolAlias"],
  419. detail="full",
  420. )
  421. print("Summaries:", summaries)
  422. print("Cached tools:", runtime.list_tools_sync(loaded[0]["name"]))
  423. print("Detailed doc:", detailed)
  424. # Fuzzy search across loaded servers without rehydrating every schema
  425. results = await runtime.search_tool_docs("calendar events", limit=3)
  426. for result in results:
  427. print(result["server"], result["tool"], result.get("description", ""))
  428. # Synchronous helpers for quick answers without extra awaits
  429. print("Capability summary:", runtime.capability_summary())
  430. print("Docs from cache:", runtime.query_tool_docs_sync(loaded[0]["name"]) if loaded else [])
  431. print("Search from cache:", runtime.search_tool_docs_sync("calendar"))
  432. ```
  433. Example output seen by the LLM when running the snippet above with the stub server:
  434. ```text
  435. Discovered: ('stub',)
  436. Loaded metadata: ({'name': 'stub', 'alias': 'stub', 'tools': [{'name': 'echo', 'alias': 'echo', 'description': 'Echo the provided message', 'input_schema': {...}}]},)
  437. Selectable via RPC: ('stub',)
  438. ```
  439. Clients that prefer `listMcpResources` can skip executing the helper snippet and instead request the
  440. `resource://mcp-server-code-execution-mode/capabilities` resource. The server advertises it via
  441. `resources/list`, and reading it returns the same helper summary plus a short checklist for loading
  442. servers explicitly.
  443. ## Security
  444. ### Container Constraints
  445. | Constraint | Setting | Purpose |
  446. |------------|---------|---------|
  447. | Network | `--network none` | No external access |
  448. | Filesystem | `--read-only` | Immutable base |
  449. | Capabilities | `--cap-drop ALL` | No system access |
  450. | Privileges | `no-new-privileges` | No escalation |
  451. | User | `65534:65534` | Unprivileged |
  452. | Memory | `--memory 512m` | Resource cap |
  453. | PIDs | `--pids-limit 128` | Process cap |
  454. | Workspace | tmpfs, noexec | Safe temp storage |
  455. ### Capabilities Matrix
  456. | Action | Allowed | Details |
  457. |--------|---------|---------|
  458. | Import stdlib | ✅ | Python standard library |
  459. | Access MCP tools | ✅ | Via proxies |
  460. | Memory ops | ✅ | Process data |
  461. | Write to disk | ✅ | Only /tmp, /workspace |
  462. | Network | ❌ | Completely blocked |
  463. | Host access | ❌ | No system calls |
  464. | Privilege escalation | ❌ | Prevented by sandbox |
  465. | Container escape | ❌ | Rootless + isolation |
  466. ## Documentation
  467. - **README.md** - This file, quick start
  468. - **[GUIDE.md](GUIDE.md)** - Comprehensive user guide
  469. - **[ARCHITECTURE.md](ARCHITECTURE.md)** - Technical deep dive
  470. - **[HISTORY.md](HISTORY.md)** - Evolution and lessons
  471. - **[STATUS.md](STATUS.md)** - Current state and roadmap
  472. ## Resources
  473. ### External
  474. - [Code Execution with MCP (Anthropic)](https://www.anthropic.com/engineering/code-execution-with-mcp)
  475. - [Code Mode (Cloudflare)](https://blog.cloudflare.com/code-mode/)
  476. - [Model Context Protocol](https://modelcontextprotocol.io/)
  477. - [Dynamic MCPs with Docker](https://www.docker.com/blog/dynamic-mcps-stop-hardcoding-your-agents-world/)
  478. - [CodeAct: Your LLM Agent Acts Better when Generating Code (Apple)](https://machinelearning.apple.com/research/codeact)
  479. - [Terminal Bench](https://github.com/laude-institute/terminal-bench)
  480. ## Status
  481. ### ✅ Implemented
  482. - Rootless container sandbox
  483. - Single `run_python` tool
  484. - MCP server proxying
  485. - Persistent sessions (state retention)
  486. - Persistent clients (warm MCP servers)
  487. - Comprehensive docs
  488. ### 🔄 In Progress
  489. - Automated testing
  490. - Observability (logging, metrics)
  491. - Policy controls
  492. - Runtime diagnostics
  493. ### 📋 Roadmap
  494. - Connection pooling
  495. - Web UI
  496. - Multi-language support
  497. - Workflow orchestration
  498. - Agent-visible discovery channel (host-proxied `mcp-find`/`mcp-add`)
  499. - Execution telemetry (structured logs, metrics, traces)
  500. - Persistent and shareable code-mode artifacts
  501. ## License
  502. GPLv3 License
  503. ## Support
  504. For issues or questions, see the documentation or file an issue.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.