Best Practices
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The MCP Server Code Execution Mode is built on a "security-first" architecture that prioritizes rootless container isolation and host-mediated communication. Best practices for this system focus on maintaining this security posture while optimizing for performance and token efficiency. By adhering to these guidelines, developers can ensure that Large Language Model (LLM) agents operate safely and effectively within a sandboxed Python environment.
These practices cover resource management, security constraints, and the "discovery-first" workflow, which significantly reduces context window overhead. For more technical details on the underlying system, refer to the Technical Architecture.
Sources: HISTORY.md:7-13, README.md:164-180
Discovery-First Workflow
To avoid "Token Bankruptcy"—where tool schemas consume excessive context—agents should follow a discovery-first pattern. Instead of preloading all possible tool definitions, the agent utilizes a constant ~200-token system prompt that directs it to discover servers and hydrate schemas only when needed.
Standard Discovery Sequence
The following sequence diagram illustrates the recommended flow for an agent to interact with the bridge and its proxied servers.
This workflow ensures that schemas flow only when requested, keeping the system prompt lean regardless of whether 10 or 1000 tools are managed.
Sources: README.md:54-91, README.md:447-455, mcp_server_code_execution_mode.py:65-74
Key Discovery Helpers
The mcp.runtime module provides several helpers to facilitate this workflow within the sandbox:
| Helper Function | Description |
|---|---|
runtime.discovered_servers() | Lists all configured servers without loading schemas. |
runtime.query_tool_docs(server) | Hydrates specific tool documentation for a server. |
runtime.search_tool_docs("query") | Performs fuzzy lookups across servers for specific functionality. |
runtime.capability_summary() | Returns a technical digest of sandbox capabilities for the agent. |
Sources: GUIDE.md:387-438, mcp_server_code_execution_mode.py:814-830
Resource and Performance Management
Efficient resource management is critical for preventing sandbox failures and ensuring fast response times. The bridge supports persistent sessions, meaning variables and imports are retained across calls, which should be leveraged to avoid redundant setup code.
Execution Constraints
Developers should be aware of the default resource limits and how to override them for demanding tasks.
# RECOMMENDED: Set appropriate timeouts for slow operations
await mcp_slow_operation(timeout=60) # Overrides default 30s
# RECOMMENDED: Process data in memory rather than large disk writes
data = await mcp_api.get_data()
processed = [item.transform() for item in data]
| Parameter | Default | Practice |
|---|---|---|
Timeout | 30s | Increase via MCP_BRIDGE_TIMEOUT for complex analysis. |
Memory | 512m | Increase via MCP_BRIDGE_MEMORY if processing large datasets. |
PID Limit | 128 | Monitor if spawning many sub-processes in the sandbox. |
Sources: GUIDE.md:651-665, GUIDE.md:736-751, mcp_server_code_execution_mode.py:108-115
Batching and Concurrency
To reduce round-trips between the LLM and the bridge, complex logic (loops, retries, and conditionals) should be encapsulated in a single run_python call rather than multiple sequential tool invocations.
# GOOD: Batching requests with asyncio.gather
results = await asyncio.gather(
mcp_api.call1(),
mcp_api.call2()
)
Sources: README.md:120-130, GUIDE.md:763-772
Security and Isolation
The project follows a "Security-First" design, utilizing rootless containers with comprehensive constraints.
The Security Model
The architecture enforces strict boundaries between the sandbox and the host.
Security Checklist
- Network Isolation: The sandbox is launched with
--network none. Do not attempt to use standard library networking calls; all external data must be retrieved via proxied MCP tools. - Read-Only Root: The container uses a read-only root filesystem. Use
/tmpor/workspace(tmpfs) for temporary file storage. - Dropped Capabilities: All Linux capabilities are dropped (
--cap-drop ALL). Avoid operations requiring system-level privileges. - Credential Management: Never hardcode secrets in sandbox code. Retrieve them via secure MCP vault or credential servers.
Sources: README.md:182-195, GUIDE.md:812-823, ARCHITECTURE.md:130-143
State Persistence
The bridge provides two primary mechanisms for persisting state across independent run_python invocations: memory and user tools.
Memory System vs. User Tools
These systems allow agents to maintain continuity without exhausting the LLM's context window.
| Feature | save_memory() | save_tool() |
|---|---|---|
| Storage Format | JSON Data | Python Function Source |
| Primary Use | State, preferences, context | Reusable logic, custom wrappers |
| Persistence | Permanent (Host Disk) | Permanent (Host Disk) |
| Access Helper | load_memory(key) | Standard Python import |
Best Practice: Use update_memory(key, fn) for atomic read-modify-write operations to prevent race conditions during state updates.
Sources: README.md:214-235, GUIDE.md:586-595, mcp_server_code_execution_mode.py:465-485
Error Handling and Troubleshooting
Reliable agent behavior requires robust error handling within the sandboxed code.
Handling Sandbox Errors
Agents should use standard Python try/except blocks to handle RPC failures or timeout exceptions.
try:
result = await mcp_api.risky_operation()
except Exception as e:
# Log and fallback
print(f"Operation failed: {e}")
Common Runtime Issues
- Container Runtime: Ensure
podmanordockeris available. On macOS/Linux,podmanis recommended for superior rootless support. - Pydantic Compatibility: For Python 3.14+, ensure
pydantic >= 2.12.0is installed to avoidTypeErrorduring metadata evaluation. - Server Initialization: If a proxied server fails to initialize (e.g.,
EOFduring handshake), verify host-side credentials and registry access (e.g.,docker login).
Sources: README.md:310-330, GUIDE.md:612-625, mcp_server_code_execution_mode.py:48-75
Conclusion
Best practices for the MCP Server Code Execution Mode center on leveraging the Discovery-First architecture to maximize token efficiency while respecting the Rootless Isolation model for security. By utilizing persistent memory for state management and batching complex logic into single execution calls, developers can build agents that are both powerful and resource-efficient.
Sources: HISTORY.md:120-125, STATUS.md:120-125