### MCP Server Configuration Example Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Example JSON configuration for an MCP server, specifying the command and arguments to launch it. Ensure the command does not recursively start the MCP server code execution mode unless explicitly allowed. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"] } } } ``` -------------------------------- ### Test MCP Server Installation Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Runs the MCP server using uv to test the installation. Successful execution without errors indicates a correct setup. ```bash uv run python mcp_server_code_execution_mode.py ``` -------------------------------- ### Install Podman on Ubuntu/Debian Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs Podman on Ubuntu or Debian systems using apt-get. Verify the installation by checking the version. ```bash # Ubuntu/Debian sudo apt-get install podman ``` -------------------------------- ### Install uv Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Installs the uv package manager. Ensure Python 3.11+ is installed. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Docker on Ubuntu/Debian Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs Docker on Ubuntu or Debian systems using apt-get. ```bash # Ubuntu/Debian sudo apt-get install docker.io ``` -------------------------------- ### Running Tests with `uv` Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Manage development dependencies and run tests using `uv` and `pytest`. Examples show installing dev dependencies, running tests directly, and pinning a Python version. ```bash # Install dev dependencies and run the full test suite uv sync --group dev uv run pytest # Run without installing dev deps permanently uv run --with pytest pytest # Pin Python version (CPython 3.11+ required) uv python pin 3.13 uv sync uv run pytest -v ``` -------------------------------- ### Stub Test Server Output Example Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Example output demonstrating server discovery and metadata retrieval for the stub test server. ```text Discovered: ('stub',) Loaded metadata: ({'name': 'stub', 'alias': 'stub', 'tools': [{'name': 'echo', 'alias': 'echo', 'description': 'Echo the provided message', 'input_schema': {...}}]},) Selectable via RPC: ('stub',) ``` -------------------------------- ### Install MCP Server Code Execution Mode Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Install the bridge using `uv` or `uvx`. Ensure the container image (Podman or Docker) is pulled before running. ```bash # Install via uv (recommended) uv sync # Or install via uvx directly from GitHub (no local checkout required) uvx --from git+https://github.com/elusznik/mcp-server-code-execution-mode \ mcp-server-code-execution-mode run # Pull the container image first podman pull python:3.13-slim # or docker pull python:3.13-slim ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs project dependencies listed in the requirements.txt file using pip. ```bash # Using pip pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs project dependencies using uv, a fast Python package installer. This is the recommended method. ```bash # Or using uv (recommended) uv sync ``` -------------------------------- ### Install Docker on macOS Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs Docker on macOS using Homebrew. ```bash # macOS brew install docker ``` -------------------------------- ### Install Podman on macOS Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs Podman on macOS using Homebrew. Verify the installation by checking the version. ```bash # macOS brew install podman ``` -------------------------------- ### Install Dev Dependencies and Run Tests Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Installs development dependencies including pytest and runs tests using uv. ```bash uv sync --group dev ``` ```bash uv run pytest ``` ```bash uv run --with pytest pytest ``` -------------------------------- ### Process and Store Data with MCP Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Shows a data pipeline example using MCP to extract data from a Google Drive document, summarize it, and update a Salesforce record. ```python # Extract data transcript = await mcp_google_drive.get_document(documentId='abc123') # Process summary = transcript[:500] + "..." # Store await mcp_salesforce.update_record( objectType='SalesMeeting', recordId='00Q5f000001abcXYZ', data={'Notes': summary} ) ``` -------------------------------- ### Verify Podman Installation Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Checks if Podman is installed and accessible by displaying its version. ```bash podman --version ``` -------------------------------- ### Install and Run MCP Server Code Execution Mode Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/STATUS.md Commands to install dependencies and run the MCP server code execution mode bridge. Configuration for registration with Claude is detailed in the README. ```bash # Install uv sync # Run uv run python mcp_server_code_execution_mode.py # Register with Claude # See README.md for configuration details ``` -------------------------------- ### Get Sandbox Capability Summary Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Use `runtime.capability_summary()` to get a string detailing the sandbox's capabilities, discovery helpers, and memory API. This is useful for understanding what the MCP can do without running exploratory code. ```python from mcp import runtime # Print the full sandbox manual to stdout print(runtime.capability_summary()) ``` -------------------------------- ### Fuzzy Search for Tool Documentation Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Use `search_tool_docs` to find tools across servers without knowing exact names. This example demonstrates how to search for 'calendar events' and print matching tool information. ```python from mcp import runtime matches = await runtime.search_tool_docs("calendar events", limit=5) for hit in matches: print(hit["server"], hit["tool"], hit.get("description", "")) ``` -------------------------------- ### Direct Tool Use with MCP Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Example of calling a single MCP tool directly. This pattern is suitable for simple, isolated operations. ```python # Call a single tool result = await mcp_filesystem.read_file(path='/tmp/data.txt') print(result) ``` -------------------------------- ### Discover Available MCP Servers Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Use `runtime.discovered_servers()` to list all servers found by the bridge during auto-discovery. Pass `detailed=True` to get names and descriptions. Use `runtime.list_servers_sync()` and `runtime.list_loaded_server_metadata()` for synchronous retrieval of loaded servers and their metadata. ```python # Inside run_python sandbox code from mcp import runtime # Basic list (tuple of names) servers = runtime.discovered_servers() print("Available:", servers) # Available: ('filesystem', 'postgres', 'git', 'serena') # With descriptions for srv in runtime.discovered_servers(detailed=True): print(f"{srv['name']}: {srv['description']}") # filesystem: # postgres: PostgreSQL MCP server # Cached list of servers loaded in *this* run (synchronous, no RPC) loaded = runtime.list_servers_sync() print("Loaded this run:", loaded) # Loaded this run: ('filesystem', 'postgres') # Full metadata for loaded servers (alias, tools list, cwd) meta = runtime.list_loaded_server_metadata() for server in meta: print(server["name"], "alias:", server["alias"], "cwd:", server.get("cwd")) for tool in server["tools"]: print(" -", tool["alias"], "→", tool.get("description", "")) ``` -------------------------------- ### Install Pydantic and Uninstall Typing Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Installs the latest Pydantic version and uninstalls the separate 'typing' package if present, to resolve potential Pydantic compatibility issues with Python 3.14+. ```bash pip install -U pydantic pip uninstall typing # if present; the stdlib's typing should be used ``` -------------------------------- ### Pin Python Version and Sync Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Pins the Python version to 3.13 and synchronizes dependencies using uv. This is part of the testing setup. ```bash uv python pin 3.13 ``` ```bash uv sync ``` -------------------------------- ### Successful `run_python` Response (TOON Mode) Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Example of the `run_python` tool's response when `MCP_BRIDGE_OUTPUT_MODE` is set to `toon`. This format provides structured TOON blocks for stdout. ```python # TOON mode: set MCP_BRIDGE_OUTPUT_MODE=toon to get TOON blocks instead # ```toon # status: success # stdout: # - /tmp/notes.txt contents here # ``` ``` -------------------------------- ### Get Server Metadata with runtime.describe_server() Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Retrieve cached metadata for a named server, including its alias, tools, and working directory. Useful for checking the host process's working directory before making filesystem-dependent calls. ```python from mcp import runtime desc = runtime.describe_server("git") print("Alias:", desc["alias"]) print("CWD:", desc.get("cwd")) for tool in desc["tools"]: print(" ", tool["alias"], tool.get("description", "")) cwd = desc.get("cwd") or "bridge-default" print(f"Git server runs in: {cwd}") ``` -------------------------------- ### Data Science Pipeline with Native Libraries Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Integrate native Python libraries (like `csv`, `io`, `statistics`) with MCP tools within the sandbox. This example extracts CSV data from Google Drive, processes it, saves an intermediate summary to memory, and loads results into Salesforce. ```python # run_python invocation: servers=["google_drive", "salesforce"] import json # Extract raw CSV from Google Drive raw_csv = await mcp_google_drive.get_file_content(fileId="abc123xyz") # Transform with stdlib (pandas available if image includes it) import csv, io, statistics reader = csv.DictReader(io.StringIO(raw_csv)) rows = list(reader) revenues = [float(r["revenue"]) for r in rows if r["revenue"]] summary = { "count": len(revenues), "total": sum(revenues), "mean": statistics.mean(revenues), "median": statistics.median(revenues), "stdev": statistics.stdev(revenues) if len(revenues) > 1 else 0, } # Persist intermediate result across sessions save_memory("revenue_summary_2024", summary) # Load into Salesforce await mcp_salesforce.create_record( object_type="RevenueReport__c", fields={ "Period__c": "2024-Q4", "TotalRevenue__c": summary["total"], "MeanRevenue__c": summary["mean"], "RecordCount__c": summary["count"], } ) print(json.dumps(summary, indent=2)) # { # "count": 1250, # "total": 4823910.50, # "mean": 3859.13, # "median": 3200.00, # "stdev": 1742.88 # } ``` -------------------------------- ### Troubleshoot Container Runtime Not Found Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md If the 'No container runtime found' error occurs, ensure Podman or Docker is installed and verify its version. You can also set the `MCP_BRIDGE_RUNTIME` environment variable to explicitly specify the runtime. ```bash # Install podman or docker # Verify: podman --version # Set explicit runtime: export MCP_BRIDGE_RUNTIME=podman ``` -------------------------------- ### Migrate Jira Issues to GitHub Issues Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md An example of a multi-system workflow migrating open bugs from Jira to GitHub. It searches Jira for issues and creates corresponding issues in GitHub. ```python # Jira → GitHub migration issues = await mcp_jira.search_issues(project='API', status='Open') for issue in issues: details = await mcp_jira.get_issue(id=issue.id) if 'bug' in details.description.lower(): await mcp_github.create_issue( repo='owner/repo', title=f"Bug: {issue.title}", body=details.description ) ``` -------------------------------- ### Multi-Server Workflow Orchestration Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Orchestrate data processing across multiple MCP servers (e.g., Jira, GitHub, Slack) within a single `run_python` call. This example pulls issues from Jira, mirrors critical bugs to GitHub in parallel, and notifies on Slack. ```python # run_python invocation: servers=["jira", "github", "slack"] import asyncio # 1. Pull open bugs from Jira issues = await mcp_jira.search_issues( project="API", status="Open", type="Bug", max_results=50 ) # 2. For each critical bug, create a GitHub issue in parallel async def mirror_issue(jira_issue): details = await mcp_jira.get_issue(id=jira_issue["id"]) if "critical" in details.get("labels", []): return await mcp_github.create_issue( repo="owner/api-repo", title=f"[Jira {jira_issue['key']}] {jira_issue['summary']}", body=details["description"], labels=["bug", "from-jira"], ) return None results = await asyncio.gather(*[mirror_issue(i) for i in issues]) created = [r for r in results if r is not None] # 3. Notify on Slack await mcp_slack.post_message( channel="#engineering", text=f"Mirrored {len(created)} critical Jira bugs to GitHub." ) print(f"Done: {len(created)} issues created") # Done: 7 issues created ``` -------------------------------- ### Discover and List Servers Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Explore available servers and their metadata using `mcp.runtime` functions. Includes synchronous and asynchronous methods. ```python from mcp import runtime # See everything the bridge knows about without loading schemas print("Discovered:", runtime.discovered_servers()) print("Cached servers:", runtime.list_servers_sync()) # Metadata for servers already loaded in this run print("Loaded metadata:", runtime.list_loaded_server_metadata()) # Ask the host to enumerate every available server (RPC call) available = await runtime.list_servers() print("Selectable via RPC:", available) # Peek at tool docs before deciding to use them loaded = runtime.list_loaded_server_metadata() if loaded: description = runtime.describe_server(loaded[0]["name"]) for tool in description["tools"]: print(tool["alias"], "→", tool.get("description", "")) # Summaries or full schemas only when needed if loaded: summaries = await runtime.query_tool_docs(loaded[0]["name"]) detailed = await runtime.query_tool_docs( loaded[0]["name"], tool=summaries[0]["toolAlias"], detail="full", ) print("Summaries:", summaries) print("Detailed doc:", detailed) print("Cached tools:", runtime.list_tools_sync(loaded[0]["name"])) # Keyword search across the servers already loaded in this run results = await runtime.search_tool_docs("calendar events", limit=3) for result in results: print(result["server"], result["tool"], result.get("description", "")) # Quick answers without awaiting RPC print("Capability summary:", runtime.capability_summary()) print("Cached docs:", runtime.query_tool_docs_sync(loaded[0]["name"]) if loaded else []) print("Cached search:", runtime.search_tool_docs_sync("calendar")) ``` -------------------------------- ### Inspect Available MCP Servers and Tool Docs Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Demonstrates how to inspect available MCP servers, list cached and discovered servers, and query tool documentation. Useful for understanding the MCP environment and available functionalities. ```python from mcp import runtime print("Discovered:", runtime.discovered_servers()) print("Cached servers:", runtime.list_servers_sync()) print("Loaded metadata:", runtime.list_loaded_server_metadata()) print("Selectable via RPC:", await runtime.list_servers()) # Peek at tool docs for a server that's already loaded in this run loaded = runtime.list_loaded_server_metadata() if loaded: first = runtime.describe_server(loaded[0]["name"]) for tool in first["tools"]: print(tool["alias"], "→", tool.get("description", "")) # Ask for summaries or full schemas only when needed if loaded: summaries = await runtime.query_tool_docs(loaded[0]["name"]) detailed = await runtime.query_tool_docs( loaded[0]["name"], tool=summaries[0]["toolAlias"], detail="full", ) print("Summaries:", summaries) print("Cached tools:", runtime.list_tools_sync(loaded[0]["name"])) print("Detailed doc:", detailed) # Fuzzy search across loaded servers without rehydrating every schema results = await runtime.search_tool_docs("calendar events", limit=3) for result in results: print(result["server"], result["tool"], result.get("description", "")) ``` -------------------------------- ### List and Filter Files with MCP Filesystem Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Demonstrates how to list files in a directory and read their content using the MCP filesystem API. Useful for pre-processing or analysis. ```python # List and filter files files = await mcp_filesystem.list_directory(path='/tmp') for file in files: content = await mcp_filesystem.read_file(path=file) if 'TODO' in content: print(f"TODO in {file}") ``` -------------------------------- ### Launch MCP Server from Git Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Launches the MCP server code execution mode from a Git repository using uvx. ```bash uvx --from git+https://github.com/elusznik/mcp-server-code-execution-mode mcp-server-code-execution-mode run ``` -------------------------------- ### MCP Server Access Patterns in Python Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Demonstrates various ways to access MCP servers within a Python environment. Ensure the MCP library is correctly imported or configured. ```python mcp_servers["server"] # Dynamic lookup mcp_server_name # Attribute access from mcp.servers.server import * # Module import ``` -------------------------------- ### Troubleshoot Permission Denied Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md To resolve 'permission denied' errors, add your user to the `docker` group or use Podman with user namespaces enabled. Verify user namespace status with `podman info`. ```bash # Add user to docker group sudo usermod -aG docker $USER newgrp docker # Or use podman (user namespaces) podman info # Verify user namespace ``` -------------------------------- ### Fetch Tool Documentation Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Retrieve tool documentation using `runtime.query_tool_docs()` for a specific server. Use `detail="full"` to include input JSON schemas. The synchronous variant `runtime.query_tool_docs_sync()` reads from an in-process cache. ```python from mcp import runtime # Summary-level docs for all tools on a server (async, triggers RPC if not cached) summaries = await runtime.query_tool_docs("filesystem") for doc in summaries: print(doc["toolAlias"], "→", doc.get("description", "")) # read_file → Read the complete contents of a file from the file system. # write_file → Create a new file or completely overwrite an existing file. # list_directory → Get a listing of all files and directories in a path. # Full schema for a single tool (includes inputSchema) detailed = await runtime.query_tool_docs( "filesystem", tool="read_file", detail="full", ) print(detailed["inputSchema"]) # {'type': 'object', 'properties': {'path': {'type': 'string'}}, 'required': ['path']} # Synchronous version reads from in-process cache (no RPC, no await) cached_docs = runtime.query_tool_docs_sync("filesystem") print(f"Cached {len(cached_docs)} tools") ``` -------------------------------- ### Idempotent Operation Example Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Design operations to be idempotent, meaning they can be called multiple times with the same result. Prefer upsert operations over create operations for unique identifiers. ```python # GOOD: Idempotent operations await mcp_api.upsert_record(id='123', data=updated_data) ``` ```python # BAD: Non-idempotent await mcp_api.create_record(id='123', ...) await mcp_api.create_record(id='123', ...) # Duplicate ``` -------------------------------- ### Sync Project Dependencies Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Synchronizes project environment dependencies using uv. ```bash uv sync ``` -------------------------------- ### runtime.query_tool_docs() — On-Demand Schema Hydration Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Fetches tool documentation for a specific server. Use `detail="summary"` (default) for descriptions only; `detail="full"` to include input JSON schemas. A synchronous cached variant `query_tool_docs_sync()` avoids an RPC round-trip. ```APIDOC ## `runtime.query_tool_docs()` — On-Demand Schema Hydration Fetches tool documentation for a specific server. Use `detail="summary"` (default) for descriptions only; `detail="full"` to include input JSON schemas. A synchronous cached variant `query_tool_docs_sync()` avoids an RPC round-trip. ```python from mcp import runtime # Summary-level docs for all tools on a server (async, triggers RPC if not cached) summaries = await runtime.query_tool_docs("filesystem") for doc in summaries: print(doc["toolAlias"], "→", doc.get("description", "")) # read_file → Read the complete contents of a file from the file system. # write_file → Create a new file or completely overwrite an existing file. # list_directory → Get a listing of all files and directories in a path. # Full schema for a single tool (includes inputSchema) detailed = await runtime.query_tool_docs( "filesystem", tool="read_file", detail="full", ) print(detailed["inputSchema"]) # {'type': 'object', 'properties': {'path': {'type': 'string'}}, 'required': ['path']} # Synchronous version reads from in-process cache (no RPC, no await) cached_docs = runtime.query_tool_docs_sync("filesystem") print(f"Cached {len(cached_docs)} tools") ``` ``` -------------------------------- ### High-Level Flow Diagram Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/ARCHITECTURE.md Illustrates the request flow from the MCP Client through the Python entry point, into the rootless container runtime, and finally to the Python image executing the code. ```text ┌───────────────────────────┐ │ MCP Client (e.g. Claude) │ └──────────────┬────────────┘ │ JSON-RPC over stdio ▼ ┌───────────────────────────┐ │ main.py / mcp_server_code_execution_mode │ │ - Exposes run_python tool │ │ - Validates input │ │ - Loads MCP servers │ └──────────────┬────────────┘ │ Async subprocess + JSON stdio bridge ▼ ┌───────────────────────────┐ │ Rootless container runtime│ │ (podman or docker rootless)│ │ - Read-only rootfs │ │ - Tmpfs work dir │ │ - No network │ │ - No Linux capabilities │ └──────────────┬────────────┘ │ ▼ ┌───────────────────────────┐ │ python:3.14-slim image │ │ - Runs async entrypoint │ │ - Executes provided code │ │ - Calls mcp_ tools │ └───────────────────────────┘ ``` -------------------------------- ### Configure Filesystem MCP Server Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Create a JSON configuration file for the filesystem MCP server. This server is typically used for file-related operations. ```bash mkdir -p ~/.config/mcp/servers cat > ~/.config/mcp/servers/filesystem.json << 'EOF' { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], "env": {} } } } EOF ``` -------------------------------- ### Synchronous Runtime Helpers Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Use these synchronous helpers for quick answers from the MCP runtime without needing extra awaits. They provide direct access to capability summaries, tool documentation, and search functionalities from the cache. ```python print("Capability summary:", runtime.capability_summary()) print("Docs from cache:", runtime.query_tool_docs_sync(loaded[0]["name"]) if loaded else []) print("Search from cache:", runtime.search_tool_docs_sync("calendar")) ``` -------------------------------- ### runtime.search_tool_docs() — Fuzzy Tool Discovery Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Performs keyword search across all loaded servers' tool descriptions without loading every schema upfront. All tokens in the query must appear in the tool's combined keyword index (name, alias, description). A synchronous cached variant `search_tool_docs_sync()` is available. ```APIDOC ## `runtime.search_tool_docs()` — Fuzzy Tool Discovery Performs keyword search across all loaded servers' tool descriptions without loading every schema upfront. All tokens in the query must appear in the tool's combined keyword index (name, alias, description). A synchronous cached variant `search_tool_docs_sync()` is available. ```python from mcp import runtime # Async fuzzy search (uses loaded server cache + RPC refresh if needed) results = await runtime.search_tool_docs("calendar events", limit=5) for hit in results: print(hit["server"], "/", hit["toolAlias"], "→", hit.get("description", "")) # google_calendar / list_events → List calendar events in a date range # google_calendar / create_event → Create a new calendar event # Search with full schema returned results = await runtime.search_tool_docs("read file", limit=3, detail="full") for hit in results: print(hit["toolAlias"], hit.get("inputSchema", {}).get("required", [])) # Synchronous search from in-process cache (no RPC) hits = runtime.search_tool_docs_sync("database query", limit=5) print(f"Found {len(hits)} matching tools in cache") ``` ``` -------------------------------- ### Register MCP Server with Claude Code / OpenCode Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Create a server configuration file to register the MCP server with clients like Claude Code or OpenCode. Specify the command and arguments to run the bridge. ```json // ~/.config/mcp/servers/mcp-server-code-execution-mode.json { "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" } } } } ``` -------------------------------- ### Execute MCP Tools in Sandboxed Code Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Demonstrates using MCP tools within sandboxed Python code. Includes reading files and performing complex workflows like searching and creating issues. ```python # 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) ``` -------------------------------- ### Configure Git MCP Server Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Create a JSON configuration file for the Git MCP server. This server is used for Git repository operations. It includes a working directory specification. ```bash cat > ~/.config/mcp/servers/git.json << 'EOF' { "mcpServers": { "git": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-git", "/path/to/repo"], "cwd": "/home/user/projects/repo", "env": {} } } } EOF ``` -------------------------------- ### Low-Level RPC with runtime.call_tool() Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Call tools by server and tool name using string identifiers. Useful when server or tool names are determined at runtime. Supports dynamic dispatch and error handling via `MCPError`. ```python from mcp import runtime from mcp.runtime import MCPError # Call by string names result = await runtime.call_tool( "filesystem", "read_file", {"path": "/tmp/data.json"} ) print(result) # Dynamic tool dispatch based on user input server_name = "postgres" tool_name = "query" args = {"sql": "SELECT count(*) FROM orders"} result = await runtime.call_tool(server_name, tool_name, args) print(result) # Error handling try: result = await runtime.call_tool("filesystem", "read_file", {"path": "/nonexistent"}) except MCPError as e: print(f"Tool call failed: {e}") ``` -------------------------------- ### Configure PostgreSQL MCP Server Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Create a JSON configuration file for the PostgreSQL MCP server. This server is used for interacting with PostgreSQL databases. ```bash cat > ~/.config/mcp/servers/postgres.json << 'EOF' { "mcpServers": { "postgres": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/mydb"], "env": {} } } } EOF ``` -------------------------------- ### Register MCP Server with Other Clients Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Adds the MCP server configuration to a generic MCP client's configuration file. Specifies the command to run the server. ```json { "mcpServers": { "mcp-server-code-execution-mode": { "command": "python3", "args": ["/path/to/mcp_server_code_execution_mode.py"] } } } ``` -------------------------------- ### runtime.describe_server() Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Retrieves the full cached metadata for a specified server, including its alias, tool list with input schemas, and current working directory. This is useful for understanding the server's environment before executing filesystem-dependent operations. ```APIDOC ## `runtime.describe_server()` — Single Server Metadata Returns the full cached metadata dict for a named server: its alias, tool list with input schemas, and optional `cwd` field. Useful for checking what working directory the host process uses before making filesystem-dependent calls. ```python from mcp import runtime desc = runtime.describe_server("git") print("Alias:", desc["alias"]) print("CWD:", desc.get("cwd")) for tool in desc["tools"]: print(" ", tool["alias"], tool.get("description", "")) cwd = desc.get("cwd") or "bridge-default" print(f"Git server runs in: {cwd}") ``` ``` -------------------------------- ### Fuzzy Tool Discovery Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Perform keyword searches across tool descriptions using `runtime.search_tool_docs()`. This API avoids loading every schema upfront. A synchronous cached variant `runtime.search_tool_docs_sync()` is also available. ```python from mcp import runtime # Async fuzzy search (uses loaded server cache + RPC refresh if needed) results = await runtime.search_tool_docs("calendar events", limit=5) for hit in results: print(hit["server"], "/", hit["toolAlias"], "→", hit.get("description", "")) # google_calendar / list_events → List calendar events in a date range # google_calendar / create_event → Create a new calendar event # Search with full schema returned results = await runtime.search_tool_docs("read file", limit=3, detail="full") for hit in results: print(hit["toolAlias"], hit.get("inputSchema", {}).get("required", [])) # Synchronous search from in-process cache (no RPC) hits = runtime.search_tool_docs_sync("database query", limit=5) print(f"Found {len(hits)} matching tools in cache") ``` -------------------------------- ### Automated Tests Entrypoint Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/STATUS.md This file serves as the entrypoint for extending automated tests for the MCP server code execution mode. It is a Python file. ```python pass # Placeholder for test implementation ``` -------------------------------- ### runtime.discovered_servers() — Server Enumeration Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Lists all servers the bridge found during auto-discovery, without loading their schemas. Pass `detailed=True` for name + description tuples. Call this first to orient the LLM before fetching tool docs. ```APIDOC ## `runtime.discovered_servers()` — Server Enumeration Lists all servers the bridge found during auto-discovery, without loading their schemas. Pass `detailed=True` for name + description tuples. Call this first to orient the LLM before fetching tool docs. ```python # Inside run_python sandbox code from mcp import runtime # Basic list (tuple of names) servers = runtime.discovered_servers() print("Available:", servers) # Available: ('filesystem', 'postgres', 'git', 'serena') # With descriptions for srv in runtime.discovered_servers(detailed=True): print(f"{srv['name']}: {srv['description']}") # filesystem: # postgres: PostgreSQL MCP server # Cached list of servers loaded in *this* run (synchronous, no RPC) loaded = runtime.list_servers_sync() print("Loaded this run:", loaded) # Loaded this run: ('filesystem', 'postgres') # Full metadata for loaded servers (alias, tools list, cwd) meta = runtime.list_loaded_server_metadata() for server in meta: print(server["name"], "alias:", server["alias"], "cwd:", server.get("cwd")) for tool in server["tools"]: print(" -", tool["alias"], "→", tool.get("description", "")) ``` ``` -------------------------------- ### Troubleshoot Server Not Found Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md If an MCP server is not found, verify its configuration in `~/.config/mcp/servers/*.json`, check bridge logs for discovery messages, restart the bridge, or explicitly request the server using the `servers` parameter. ```bash # Verify server in config: ~/.config/mcp/servers/*.json # Check bridge logs for discovery messages # Restart bridge after adding server # Explicitly request server: servers=['xyz'] ``` -------------------------------- ### Successful `run_python` Response (Compact Mode) Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt The expected response format when the `run_python` tool execution is successful in compact mode (default). The `stdout` field contains the plain text output. ```json # Expected response (compact mode, default) # content[0].text → plain text of stdout/stderr # structuredContent → trimmed JSON payload { "status": "success", "stdout": ["/tmp/notes.txt contents here"] } ``` -------------------------------- ### Container Cleanup Considerations Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md While containers auto-clean up, use temporary paths for files, leverage context managers for resource cleanup, and avoid relying on persistent state as each execution is stateless. ```python # Container auto-cleans up, but: # - Use temporary paths for files # - Let context managers handle cleanup # - Don't rely on persistent state # Each execution is stateless ``` -------------------------------- ### Execute Insecurely (Prototype) Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/HISTORY.md This represents an early, insecure prototype approach to code execution. It is not recommended for use due to significant security flaws. ```python # Prototype approach result = execute_insecurely(code) ``` -------------------------------- ### Register MCP Server with Claude Code/OpenCode Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Configures the MCP server for Claude Code or OpenCode by creating a JSON configuration file. Specifies the command to run the server and environment variables. ```json { "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" } } } } ``` -------------------------------- ### Verify Container Image Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Verifies that the specified container image has been successfully pulled and is available locally. ```bash podman images python:3.13-slim ``` -------------------------------- ### mcp_ Proxies — Direct Tool Invocation Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Allows direct invocation of tools provided by servers. Each server is exposed as an `mcp_` object, where `` is a sanitized version of the server name. Tools can be called as asynchronous methods using keyword arguments. ```APIDOC ## `mcp_` Proxies — Direct Tool Invocation Each server requested via the `servers` array is available inside sandbox code as `mcp_`. The alias is the server name sanitised to a valid Python identifier. All tools are callable with keyword arguments using `await`. ```python # servers=["filesystem", "postgres", "serena"] must be in the run_python call # Read a file content = await mcp_filesystem.read_file(path="/tmp/report.csv") # Write a file await mcp_filesystem.write_file( path="/tmp/output.txt", content="Analysis complete" ) # Query a database rows = await mcp_postgres.query( sql="SELECT id, name, created_at FROM users WHERE active = true LIMIT 10" ) for row in rows: print(row["name"], row["created_at"]) # Alternative: dict-style server lookup server = mcp_servers["serena"] results = await server.search(query="authentication module") # Alternative: module import style from mcp.servers.filesystem import read_file, list_directory files = await list_directory(path="/tmp") # Parallel calls with asyncio.gather import asyncio file1, file2 = await asyncio.gather( mcp_filesystem.read_file(path="/tmp/a.txt"), mcp_filesystem.read_file(path="/tmp/b.txt"), ) ``` ``` -------------------------------- ### Direct Tool Invocation via mcp_ Proxies Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Access server tools directly using generated proxy objects (e.g., `mcp_filesystem`). Requires the server to be listed in the `servers` array during `run_python`. Supports keyword arguments and parallel calls with `asyncio.gather`. ```python # servers=["filesystem", "postgres", "serena"] must be in the run_python call # Read a file content = await mcp_filesystem.read_file(path="/tmp/report.csv") # Write a file await mcp_filesystem.write_file( path="/tmp/output.txt", content="Analysis complete" ) # Query a database rows = await mcp_postgres.query( sql="SELECT id, name, created_at FROM users WHERE active = true LIMIT 10" ) for row in rows: print(row["name"], row["created_at"]) # Alternative: dict-style server lookup server = mcp_servers["serena"] results = await server.search(query="authentication module") # Alternative: module import style from mcp.servers.filesystem import read_file, list_directory files = await list_directory(path="/tmp") # Parallel calls with asyncio.gather import asyncio file1, file2 = await asyncio.gather( mcp_filesystem.read_file(path="/tmp/a.txt"), mcp_filesystem.read_file(path="/tmp/b.txt") ) ``` -------------------------------- ### Configure External MCP Servers Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Define external MCP servers by specifying their command, arguments, environment variables, and optional working directory. This configuration is used for discovering and proxying servers into the sandbox. ```json // ~/.config/mcp/servers/my-tools.json // Supports: command, args, env, cwd (optional working directory for host process) { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], "env": {} }, "postgres": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/mydb"], "env": {} }, "git": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-git", "/path/to/repo"], "cwd": "/home/user/projects/repo", "env": {} } } } ``` -------------------------------- ### Load Specific Servers for Execution Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md When invoking `run_python`, specify the necessary servers using the `servers` parameter to limit the loaded proxies within the sandbox. Access these servers via their proxy objects. ```python # Only load necessary servers # When invoking run_python from your MCP client, specify the servers you need: # servers=['filesystem'] # Inside the sandboxed code you simply call the proxy: result = await mcp_filesystem.read_file(path='/tmp/test.txt') ``` -------------------------------- ### runtime.call_tool() Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Provides a low-level mechanism to call a tool on a specific server using string names for both the server and the tool. This method is useful when the server or tool name is determined dynamically at runtime. ```APIDOC ## `runtime.call_tool()` — Low-Level RPC Calls a tool by server name and tool name directly without going through the proxy object. Useful when the server or tool name is determined at runtime. ```python from mcp import runtime # Call by string names result = await runtime.call_tool( "filesystem", # server name "read_file", # tool name (original, not alias) {"path": "/tmp/data.json"} ) print(result) # Dynamic tool dispatch based on user input server_name = "postgres" tool_name = "query" args = {"sql": "SELECT count(*) FROM orders"} result = await runtime.call_tool(server_name, tool_name, args) print(result) # Error handling from mcp.runtime import MCPError try: result = await runtime.call_tool("filesystem", "read_file", {"path": "/nonexistent"}) except MCPError as e: print(f"Tool call failed: {e}") ``` ``` -------------------------------- ### Configure MCP Bridge Runtime Parameters Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Configure the MCP bridge's runtime behavior using environment variables. These variables control aspects like the container runtime, image, timeouts, resource limits, and output format. ```bash # Container runtime (auto-detected: podman first, then docker) export MCP_BRIDGE_RUNTIME=podman # Container image (default: python:3.14-slim) export MCP_BRIDGE_IMAGE=python:3.13-slim # Default execution timeout in seconds (default: 30) export MCP_BRIDGE_TIMEOUT=60 # Hard ceiling for timeout argument (default: 120) export MCP_BRIDGE_MAX_TIMEOUT=180 # Memory limit passed to --memory (default: 512m) export MCP_BRIDGE_MEMORY=1g # PID limit --pids-limit (default: 128) export MCP_BRIDGE_PIDS=256 # CPU quota --cpus (unset by default) export MCP_BRIDGE_CPUS=2.0 # Container user UID:GID (default: 65534:65534) export MCP_BRIDGE_CONTAINER_USER=65534:65534 # Seconds before idle Podman machine is auto-stopped (default: 300) export MCP_BRIDGE_RUNTIME_IDLE_TIMEOUT=600 # Host directory for IPC sockets and persistent state (default: ~/MCPs) export MCP_BRIDGE_STATE_DIR=/data/mcp-state # Response format: 'compact' (default) or 'toon' export MCP_BRIDGE_OUTPUT_MODE=toon # Bridge logging verbosity (default: INFO) export MCP_BRIDGE_LOG_LEVEL=WARNING # Allow bridge to load itself as a nested server (dangerous; default: 0) export MCP_BRIDGE_ALLOW_SELF_SERVER=0 # Point at an additional server config file (supplements discovered files) export MCP_SERVERS_CONFIG=/home/user/extra-servers.json ``` -------------------------------- ### Data Pipeline: Extract, Transform, Load, Report Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Implement a standard data pipeline pattern involving fetching, cleaning, saving, and reporting. ```python # Extract source_data = await mcp_source.fetch() # Transform cleaned = clean_data(source_data) # Load await mcp_destination.save(data=cleaned) # Report print(f"Processed {len(cleaned)} items") ``` -------------------------------- ### Run Python with Specific Servers Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Invoke `run_python` with a JSON payload specifying the servers to load for the execution context. ```json { "code": "print(await mcp_serena.search(query='latest AI papers'))", "servers": ["serena", "filesystem"] } ``` -------------------------------- ### Persistent Memory Operations in Python Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/README.md Illustrates how to use the persistent memory system to save, load, update, and list data across sessions. Memory files are stored in `/projects/memory/` within the container. ```python # Save context for future sessions save_memory("project_context", { "goal": "Build REST API", "current_task": "Implement auth", "decisions": ["Use JWT tokens", "PostgreSQL backend"] }) # Retrieve in a later session context = load_memory("project_context") print(f"Working on: {context['current_task']}") # Update incrementally update_memory("project_context", lambda ctx: { **ctx, "decisions": ctx["decisions"] + ["Add rate limiting"] }) # List all saved memories for mem in list_memories(): print(f"{mem['key']}: created {mem['created_at']}") # Check existence before loading if memory_exists("user_preferences"): prefs = load_memory("user_preferences") ``` -------------------------------- ### save_memory() / load_memory() / update_memory() / list_memories() / get_memory_info() / delete_memory() / memory_exists() Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt Functions for persisting and retrieving JSON-serializable data across sessions. Data is stored in `~/MCPs/user_tools/memory/` and can be tagged with metadata. Supports atomic updates and checking for memory existence. ```APIDOC ## `save_memory()` / `load_memory()` — Cross-Session Data Persistence Persists JSON-serializable data to `~/MCPs/user_tools/memory/.json` on the host, surviving container restarts and new sessions. Supports optional metadata tagging. All memory functions are available both as globals in sandbox code and as `runtime.*` attributes. ```python # Save project context at the end of a session save_memory("project_context", { "goal": "Build REST API", "current_task": "Implement JWT auth", "decisions": ["PostgreSQL backend", "FastAPI framework"], "completed": ["schema design", "user model"] }, metadata={"tags": ["active", "backend"]}) # Retrieve in a later session (returns None if not found, or default) ctx = load_memory("project_context", default={}) print(f"Continuing: {ctx.get('current_task')}") # Check before loading if memory_exists("user_preferences"): prefs = load_memory("user_preferences") print("Theme:", prefs.get("theme", "default")) # Atomic update: append to decision list update_memory("project_context", lambda c: { **(c or {}), "decisions": (c or {}).get("decisions", []) + ["Add Redis caching"] }) # Increment a run counter atomically update_memory("run_count", lambda x: (x or 0) + 1) # List all persisted memories with timestamps for mem in list_memories(): print(f"{mem['key']} — created {mem['created_at']}, tags: {mem['metadata']}") # Get full record including stored value info = get_memory_info("project_context") print(info["value"]["current_task"]) # Delete a stale memory delete_memory("old_cache") ``` ``` -------------------------------- ### Invoke `run_python` MCP Tool Source: https://context7.com/elusznik/mcp-server-code-execution-mode/llms.txt This is the payload sent by the LLM or MCP client to invoke the `run_python` tool. It includes the Python code to execute, a list of MCP server names to mount as proxies, and an optional timeout. ```json // MCP tool invocation payload (sent by the LLM / MCP client) { "code": "result = await mcp_filesystem.read_file(path='/tmp/notes.txt')\nprint(result)", "servers": ["filesystem"], "timeout": 30 } ``` -------------------------------- ### Discover Server Working Directory (cwd) Source: https://github.com/elusznik/mcp-server-code-execution-mode/blob/main/GUIDE.md Programmatically discover the working directory of an MCP server using the Python runtime. If 'cwd' is not configured, it defaults to the bridge's working directory. ```python from mcp import runtime desc = runtime.describe_server('serena') cdir = desc.get('cwd') or 'bridge-default' print('Server cwd:', cdir) ```