mcp-server-code-execution-mode

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP Server Code Execution Mode

MCP Server代码执行模式

Skill by ara.so — MCP Skills collection.
This MCP server implements Anthropic's "Code Execution with MCP" pattern, exposing a single
run_python
tool instead of hundreds of individual tools. The agent writes Python code to discover, call, and compose MCP tools dynamically, reducing context overhead from ~30,000 tokens to ~200 tokens.
Key capabilities:
  • Execute Python in rootless Podman/Docker containers
  • Proxy any stdio MCP server into the sandbox
  • Discover tools at runtime (no context preloading)
  • Fuzzy search across all connected servers
  • Persistent sessions (variables/state retained)
  • Security: no network, read-only filesystem, dropped capabilities
ara.so提供的Skill — MCP Skills合集。
该MCP服务器实现了Anthropic的「基于MCP的代码执行」模式,仅暴露一个
run_python
工具而非数百个独立工具。Agent可编写Python代码来动态发现、调用和组合MCP工具,将上下文开销从约30,000 tokens降低至约200 tokens。
核心功能:
  • 在无根Podman/Docker容器中执行Python代码
  • 将任何标准输入输出的MCP服务器代理到沙箱环境
  • 运行时发现工具(无需预加载上下文)
  • 在所有已连接服务器中进行模糊搜索
  • 持久化会话(保留变量/状态)
  • 安全性:无网络访问、只读文件系统、移除权限

Installation

安装

Prerequisites

前置要求

Install a container runtime (rootless mode):
bash
undefined
安装容器运行时(无根模式):
bash
undefined

macOS (Podman Desktop recommended)

macOS(推荐使用Podman Desktop)

brew install podman podman machine init podman machine start
brew install podman podman machine init podman machine start

Linux

Linux

sudo apt install podman # or dnf/yum/pacman podman system migrate # enable rootless
sudo apt install podman # 或使用dnf/yum/pacman podman system migrate # 启用无根模式

Windows (WSL2 + Podman Desktop)

Windows(WSL2 + Podman Desktop)

undefined
undefined

Install the Bridge

安装桥接工具

bash
undefined
bash
undefined

Via pip

通过pip安装

pip install mcp-code-execution
pip install mcp-code-execution

Via uv (recommended)

通过uv安装(推荐)

uv pip install mcp-code-execution
uv pip install mcp-code-execution

From source

从源码安装

git clone https://github.com/elusznik/mcp-server-code-execution-mode.git cd mcp-server-code-execution-mode uv pip install -e .
undefined
git clone https://github.com/elusznik/mcp-server-code-execution-mode.git cd mcp-server-code-execution-mode uv pip install -e .
undefined

Pull the Container Image

拉取容器镜像

bash
undefined
bash
undefined

Pre-built image (recommended)

预构建镜像(推荐)

podman pull ghcr.io/elusznik/mcp-code-execution:latest
podman pull ghcr.io/elusznik/mcp-code-execution:latest

Or build custom image

或构建自定义镜像

podman build -t mcp-code-execution:custom -f Dockerfile .
undefined
podman build -t mcp-code-execution:custom -f Dockerfile .
undefined

Configuration

配置

Claude Desktop

Claude桌面端

Add to
~/Library/Application Support/Claude/claude_desktop_config.json
(macOS) or
%APPDATA%\Claude\claude_desktop_config.json
(Windows):
json
{
  "mcpServers": {
    "code-execution": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/mcp-server-code-execution-mode",
        "run",
        "mcp-code-execution"
      ],
      "env": {
        "MCP_BRIDGE_RUNTIME": "podman",
        "MCP_BRIDGE_IMAGE": "ghcr.io/elusznik/mcp-code-execution:latest",
        "MCP_BRIDGE_OUTPUT_MODE": "compact"
      }
    }
  }
}
添加至
~/Library/Application Support/Claude/claude_desktop_config.json
(macOS)或
%APPDATA%\Claude\claude_desktop_config.json
(Windows):
json
{
  "mcpServers": {
    "code-execution": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/mcp-server-code-execution-mode",
        "run",
        "mcp-code-execution"
      ],
      "env": {
        "MCP_BRIDGE_RUNTIME": "podman",
        "MCP_BRIDGE_IMAGE": "ghcr.io/elusznik/mcp-code-execution:latest",
        "MCP_BRIDGE_OUTPUT_MODE": "compact"
      }
    }
  }
}

Environment Variables

环境变量

VariableDefaultDescription
MCP_BRIDGE_RUNTIME
podman
Container runtime (
podman
or
docker
)
MCP_BRIDGE_IMAGE
ghcr.io/elusznik/mcp-code-execution:latest
Container image to use
MCP_BRIDGE_TIMEOUT
300
Execution timeout (seconds)
MCP_BRIDGE_OUTPUT_MODE
compact
Output format (
compact
,
toon
, or
json
)
MCP_BRIDGE_MEMORY_LIMIT
512m
Container memory limit
MCP_BRIDGE_PIDS_LIMIT
128
Max processes in container
MCP_BRIDGE_STARTUP_TIMEOUT
60
Server startup timeout (seconds)
变量默认值描述
MCP_BRIDGE_RUNTIME
podman
容器运行时(
podman
docker
MCP_BRIDGE_IMAGE
ghcr.io/elusznik/mcp-code-execution:latest
使用的容器镜像
MCP_BRIDGE_TIMEOUT
300
执行超时时间(秒)
MCP_BRIDGE_OUTPUT_MODE
compact
输出格式(
compact
toon
json
MCP_BRIDGE_MEMORY_LIMIT
512m
容器内存限制
MCP_BRIDGE_PIDS_LIMIT
128
容器内最大进程数
MCP_BRIDGE_STARTUP_TIMEOUT
60
服务器启动超时时间(秒)

Proxying Other MCP Servers

代理其他MCP服务器

Create a
mcp_bridge_config.json
in your working directory:
json
{
  "servers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      "env": {}
    },
    "github": {
      "command": "uvx",
      "args": ["mcp-server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "postgres": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-e", "POSTGRES_CONNECTION_STRING",
        "mcp/postgres"
      ],
      "env": {
        "POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
      }
    }
  }
}
The bridge auto-discovers configs from:
  • ./mcp_bridge_config.json
  • ~/.config/mcp-bridge/config.json
  • MCP_BRIDGE_CONFIG
    env var (JSON string)
  • Claude Desktop config (proxies sibling servers)
在工作目录创建
mcp_bridge_config.json
json
{
  "servers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      "env": {}
    },
    "github": {
      "command": "uvx",
      "args": ["mcp-server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "postgres": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-e", "POSTGRES_CONNECTION_STRING",
        "mcp/postgres"
      ],
      "env": {
        "POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
      }
    }
  }
}
桥接工具会自动从以下位置发现配置:
  • ./mcp_bridge_config.json
  • ~/.config/mcp-bridge/config.json
  • MCP_BRIDGE_CONFIG
    环境变量(JSON字符串)
  • Claude桌面端配置(代理同级服务器)

Usage Patterns

使用模式

Basic Code Execution

基础代码执行

python
undefined
python
undefined

Simple calculation

简单计算

result = 42 * 1.5 print(f"Answer: {result}")

```python
result = 42 * 1.5 print(f"Answer: {result}")

```python

Data analysis

数据分析

import pandas as pd import numpy as np
data = pd.DataFrame({ 'x': np.random.randn(100), 'y': np.random.randn(100) })
correlation = data['x'].corr(data['y']) print(f"Correlation: {correlation:.3f}")
undefined
import pandas as pd import numpy as np
data = pd.DataFrame({ 'x': np.random.randn(100), 'y': np.random.randn(100) })
correlation = data['x'].corr(data['y']) print(f"Correlation: {correlation:.3f}")
undefined

Discovering MCP Servers

发现MCP服务器

python
from mcp import runtime
python
from mcp import runtime

List all available servers

列出所有可用服务器

servers = await runtime.discovered_servers() for server in servers: print(f"- {server}")
undefined
servers = await runtime.discovered_servers() for server in servers: print(f"- {server}")
undefined

Querying Tool Schemas

查询工具Schema

python
from mcp import runtime
python
from mcp import runtime

Get all tools from a specific server

获取特定服务器的所有工具

github_tools = await runtime.query_tool_docs("github")
for tool_name, schema in github_tools.items(): print(f"{tool_name}: {schema.get('description', 'No description')}")
undefined
github_tools = await runtime.query_tool_docs("github")
for tool_name, schema in github_tools.items(): print(f"{tool_name}: {schema.get('description', 'No description')}")
undefined

Fuzzy Tool Search

模糊工具搜索

python
from mcp import runtime
python
from mcp import runtime

Search across all servers

在所有服务器中搜索

matches = await runtime.search_tool_docs("create issue", limit=5)
for hit in matches: print(f"{hit['server']}.{hit['tool']}: {hit.get('description', '')}") print(f" Score: {hit.get('score', 0):.2f}")
undefined
matches = await runtime.search_tool_docs("create issue", limit=5)
for hit in matches: print(f"{hit['server']}.{hit['tool']}: {hit.get('description', '')}") print(f" Score: {hit.get('score', 0):.2f}")
undefined

Calling MCP Tools Directly

直接调用MCP工具

python
undefined
python
undefined

Dynamic lookup

动态查找

result = await mcp_servers["github"].call_tool( "create_issue", { "owner": "elusznik", "repo": "mcp-server-code-execution-mode", "title": "Add feature X", "body": "Description here" } ) print(result)

```python
result = await mcp_servers["github"].call_tool( "create_issue", { "owner": "elusznik", "repo": "mcp-server-code-execution-mode", "title": "Add feature X", "body": "Description here" } ) print(result)

```python

Attribute access

属性访问

result = await mcp_github.create_issue( owner="elusznik", repo="mcp-server-code-execution-mode", title="Bug report", body="Steps to reproduce..." )

```python
result = await mcp_github.create_issue( owner="elusznik", repo="mcp-server-code-execution-mode", title="Bug report", body="Steps to reproduce..." )

```python

Module import pattern

模块导入模式

from mcp.servers.github import create_issue
issue = await create_issue( owner="myorg", repo="myrepo", title="Task", body="Details" )
undefined
from mcp.servers.github import create_issue
issue = await create_issue( owner="myorg", repo="myrepo", title="Task", body="Details" )
undefined

Composing Multiple Tools

组合多个工具

python
from mcp import runtime
python
from mcp import runtime

1. Search for calendar tools

1. 搜索日历工具

cal_tools = await runtime.search_tool_docs("calendar events", limit=3) calendar_server = cal_tools[0]["server"] if cal_tools else None
if calendar_server: # 2. Get today's events events = await mcp_servers[calendar_server].call_tool( "list_events", {"date": "2025-01-15"} )
# 3. Create GitHub issues for each event
for event in events:
    await mcp_github.create_issue(
        owner="myorg",
        repo="tasks",
        title=f"Follow-up: {event['title']}",
        body=f"From calendar: {event['description']}"
    )

print(f"Created {len(events)} issues")
undefined
cal_tools = await runtime.search_tool_docs("calendar events", limit=3) calendar_server = cal_tools[0]["server"] if cal_tools else None
if calendar_server: # 2. 获取今日事件 events = await mcp_servers[calendar_server].call_tool( "list_events", {"date": "2025-01-15"} )
# 3. 为每个事件创建GitHub Issue
for event in events:
    await mcp_github.create_issue(
        owner="myorg",
        repo="tasks",
        title=f"Follow-up: {event['title']}",
        body=f"From calendar: {event['description']}"
    )

print(f"Created {len(events)} issues")
undefined

Error Handling

错误处理

python
from mcp import runtime

try:
    result = await mcp_servers["github"].call_tool(
        "get_issue",
        {"owner": "invalid", "repo": "repo", "issue_number": 999}
    )
except Exception as e:
    print(f"Tool call failed: {e}")
    
    # Fallback: search for alternative tools
    alternatives = await runtime.search_tool_docs("get issue")
    print(f"Found {len(alternatives)} alternative tools")
python
from mcp import runtime

try:
    result = await mcp_servers["github"].call_tool(
        "get_issue",
        {"owner": "invalid", "repo": "repo", "issue_number": 999}
    )
except Exception as e:
    print(f"Tool call failed: {e}")
    
    # 备选方案:搜索替代工具
    alternatives = await runtime.search_tool_docs("get issue")
    print(f"Found {len(alternatives)} alternative tools")

Persistent State

持久化状态

Variables and imports persist across calls in the same session:
python
undefined
同一会话中,变量和导入内容会在多次调用间保留:
python
undefined

First call

第一次调用

import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

```python
import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

```python

Second call (same session)

第二次调用(同一会话)

df and pandas are still available

df和pandas仍可用

print(df.describe())
undefined
print(df.describe())
undefined

Advanced Patterns

进阶模式

Building a Tool Catalog

构建工具目录

python
from mcp import runtime
import json

catalog = {}
python
from mcp import runtime
import json

catalog = {}

Discover all servers

发现所有服务器

servers = await runtime.discovered_servers()
for server_name in servers: # Get all tools for this server tools = await runtime.query_tool_docs(server_name) catalog[server_name] = { tool_name: { "description": schema.get("description", ""), "parameters": schema.get("inputSchema", {}).get("properties", {}) } for tool_name, schema in tools.items() }
servers = await runtime.discovered_servers()
for server_name in servers: # 获取该服务器的所有工具 tools = await runtime.query_tool_docs(server_name) catalog[server_name] = { tool_name: { "description": schema.get("description", ""), "parameters": schema.get("inputSchema", {}).get("properties", {}) } for tool_name, schema in tools.items() }

Save catalog

保存目录

with open("/tmp/tool_catalog.json", "w") as f: json.dump(catalog, f, indent=2)
print(f"Cataloged {len(catalog)} servers")
undefined
with open("/tmp/tool_catalog.json", "w") as f: json.dump(catalog, f, indent=2)
print(f"Cataloged {len(catalog)} servers")
undefined

Conditional Tool Execution

条件工具执行

python
from mcp import runtime
python
from mcp import runtime

Search for weather tools

搜索天气工具

weather_tools = await runtime.search_tool_docs("weather forecast", limit=1)
if weather_tools: server = weather_tools[0]["server"] tool = weather_tools[0]["tool"]
forecast = await mcp_servers[server].call_tool(
    tool,
    {"location": "San Francisco"}
)

# If rain predicted, create calendar reminder
if "rain" in forecast.lower():
    cal_tools = await runtime.search_tool_docs("create event")
    if cal_tools:
        await mcp_servers[cal_tools[0]["server"]].call_tool(
            cal_tools[0]["tool"],
            {
                "title": "Bring umbrella",
                "date": "2025-01-16",
                "time": "08:00"
            }
        )
undefined
weather_tools = await runtime.search_tool_docs("weather forecast", limit=1)
if weather_tools: server = weather_tools[0]["server"] tool = weather_tools[0]["tool"]
forecast = await mcp_servers[server].call_tool(
    tool,
    {"location": "San Francisco"}
)

# 如果预测有雨,创建日历提醒
if "rain" in forecast.lower():
    cal_tools = await runtime.search_tool_docs("create event")
    if cal_tools:
        await mcp_servers[cal_tools[0]["server"]].call_tool(
            cal_tools[0]["tool"],
            {
                "title": "Bring umbrella",
                "date": "2025-01-16",
                "time": "08:00"
            }
        )
undefined

Batch Processing

批量处理

python
import asyncio

repos = ["repo1", "repo2", "repo3"]
results = []

for repo in repos:
    try:
        issues = await mcp_github.list_issues(
            owner="myorg",
            repo=repo,
            state="open"
        )
        results.append({"repo": repo, "count": len(issues)})
    except Exception as e:
        results.append({"repo": repo, "error": str(e)})

for r in results:
    if "error" in r:
        print(f"{r['repo']}: ERROR - {r['error']}")
    else:
        print(f"{r['repo']}: {r['count']} open issues")
python
import asyncio

repos = ["repo1", "repo2", "repo3"]
results = []

for repo in repos:
    try:
        issues = await mcp_github.list_issues(
            owner="myorg",
            repo=repo,
            state="open"
        )
        results.append({"repo": repo, "count": len(issues)})
    except Exception as e:
        results.append({"repo": repo, "error": str(e)})

for r in results:
    if "error" in r:
        print(f"{r['repo']}: ERROR - {r['error']}")
    else:
        print(f"{r['repo']}: {r['count']} open issues")

Data Science Workflow

数据科学工作流

python
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
python
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO

Fetch data from MCP tool

从MCP工具获取数据

csv_data = await mcp_filesystem.read_file(path="/tmp/sales.csv")
csv_data = await mcp_filesystem.read_file(path="/tmp/sales.csv")

Process

处理数据

df = pd.read_csv(StringIO(csv_data)) summary = df.groupby("region")["sales"].sum().sort_values(ascending=False)
df = pd.read_csv(StringIO(csv_data)) summary = df.groupby("region")["sales"].sum().sort_values(ascending=False)

Generate chart

生成图表

fig, ax = plt.subplots() summary.plot(kind="bar", ax=ax) plt.title("Sales by Region") plt.tight_layout() plt.savefig("/tmp/sales_chart.png")
fig, ax = plt.subplots() summary.plot(kind="bar", ax=ax) plt.title("Sales by Region") plt.tight_layout() plt.savefig("/tmp/sales_chart.png")

Save results

保存结果

report = f""" Sales Analysis

Total Sales: ${df['sales'].sum():,.2f} Top Region: {summary.index[0]} (${summary.iloc[0]:,.2f})
Chart saved to /tmp/sales_chart.png """
await mcp_filesystem.write_file( path="/tmp/sales_report.txt", content=report )
print(report)
undefined

report = f""" Sales Analysis

Total Sales: ${df['sales'].sum():,.2f} Top Region: {summary.index[0]} (${summary.iloc[0]:,.2f})
Chart saved to /tmp/sales_chart.png """
await mcp_filesystem.write_file( path="/tmp/sales_report.txt", content=report )
print(report)
undefined

Troubleshooting

故障排除

Container Runtime Not Found

未找到容器运行时

Error:
RuntimeNotFoundError: Neither podman nor docker found
Solution:
bash
undefined
错误:
RuntimeNotFoundError: Neither podman nor docker found
解决方案:
bash
undefined

Install Podman

安装Podman

brew install podman # macOS sudo apt install podman # Linux
brew install podman # macOS sudo apt install podman # Linux

Or install Docker

或安装Docker

brew install docker # macOS (with Docker Desktop)
undefined
brew install docker # macOS(需搭配Docker Desktop)
undefined

Permission Denied (Rootless)

权限拒绝(无根模式)

Error:
Error: creating container: mkdir /run/user/1000: permission denied
Solution:
bash
undefined
错误:
Error: creating container: mkdir /run/user/1000: permission denied
解决方案:
bash
undefined

Enable rootless mode

启用无根模式

podman system migrate
podman system migrate

Or use Docker rootless

或使用Docker无根模式

dockerd-rootless-setuptool.sh install
undefined
dockerd-rootless-setuptool.sh install
undefined

Image Pull Timeout

镜像拉取超时

Error:
TimeoutError: Container image pull exceeded 60s
Solution:
bash
undefined
错误:
TimeoutError: Container image pull exceeded 60s
解决方案:
bash
undefined

Pre-pull image manually

手动预拉取镜像

podman pull ghcr.io/elusznik/mcp-code-execution:latest
podman pull ghcr.io/elusznik/mcp-code-execution:latest

Or increase timeout

或增加超时时间

export MCP_BRIDGE_STARTUP_TIMEOUT=180
undefined
export MCP_BRIDGE_STARTUP_TIMEOUT=180
undefined

Server Discovery Fails

服务器发现失败

Error: No servers found via
discovered_servers()
Solution:
  1. Check config file exists:
    bash
    cat ~/.config/mcp-bridge/config.json
  2. Validate JSON syntax:
    python
    import json
    with open("mcp_bridge_config.json") as f:
        json.load(f)  # Should not raise
  3. Test server manually:
    bash
    npx -y @modelcontextprotocol/server-filesystem /tmp
    # Should output JSON-RPC messages
错误:
discovered_servers()
未找到任何服务器
解决方案:
  1. 检查配置文件是否存在:
    bash
    cat ~/.config/mcp-bridge/config.json
  2. 验证JSON语法:
    python
    import json
    with open("mcp_bridge_config.json") as f:
        json.load(f)  # 不应抛出异常
  3. 手动测试服务器:
    bash
    npx -y @modelcontextprotocol/server-filesystem /tmp
    # 应输出JSON-RPC消息

Tool Call Hangs

工具调用挂起

Error: Tool execution never completes
Solution:
  1. Check timeout settings:
    bash
    export MCP_BRIDGE_TIMEOUT=600  # Increase to 10 minutes
  2. Debug in container:
    bash
    podman run -it --rm ghcr.io/elusznik/mcp-code-execution:latest /bin/bash
    # Test commands manually
错误: 工具执行从未完成
解决方案:
  1. 检查超时设置:
    bash
    export MCP_BRIDGE_TIMEOUT=600  # 增加至10分钟
  2. 在容器中调试:
    bash
    podman run -it --rm ghcr.io/elusznik/mcp-code-execution:latest /bin/bash
    # 手动测试命令

Memory Limit Exceeded

内存限制超出

Error:
OOMKilled
or memory allocation errors
Solution:
bash
export MCP_BRIDGE_MEMORY_LIMIT=2g  # Increase to 2GB
错误:
OOMKilled
或内存分配错误
解决方案:
bash
export MCP_BRIDGE_MEMORY_LIMIT=2g  # 增加至2GB

Volume Mount Issues (macOS)

卷挂载问题(macOS)

Error: Files not accessible in container
Solution:
bash
undefined
错误: 容器内无法访问文件
解决方案:
bash
undefined

Ensure Podman machine has volume sharing enabled

确保Podman机器已启用卷共享

podman machine stop podman machine set --rootful=false --volume /Users:/Users podman machine start
undefined
podman machine stop podman machine set --rootful=false --volume /Users:/Users podman machine start
undefined

Output Format Issues

输出格式问题

Problem: Responses too verbose or unstructured
Solution:
bash
undefined
问题: 响应过于冗长或非结构化
解决方案:
bash
undefined

Use compact mode (default)

使用紧凑模式(默认)

export MCP_BRIDGE_OUTPUT_MODE=compact
export MCP_BRIDGE_OUTPUT_MODE=compact

Or TOON for deterministic tokens

或使用TOON模式获取确定性tokens

export MCP_BRIDGE_OUTPUT_MODE=toon
undefined
export MCP_BRIDGE_OUTPUT_MODE=toon
undefined

Security Best Practices

安全最佳实践

  1. Never expose the bridge directly to untrusted users — the agent can execute arbitrary Python.
  2. Use environment variables for secrets:
    json
    {
      "servers": {
        "github": {
          "env": {
            "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
          }
        }
      }
    }
  3. Restrict filesystem access for proxied servers:
    json
    {
      "servers": {
        "filesystem": {
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "/safe/path"]
        }
      }
    }
  4. Monitor resource usage:
    bash
    podman stats $(podman ps -q --filter ancestor=ghcr.io/elusznik/mcp-code-execution)
  5. Audit logs: Check container logs for suspicious activity:
    bash
    podman logs <container-id>
  1. 切勿将桥接工具直接暴露给不可信用户 — Agent可执行任意Python代码。
  2. 使用环境变量存储密钥:
    json
    {
      "servers": {
        "github": {
          "env": {
            "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
          }
        }
      }
    }
  3. 限制代理服务器的文件系统访问:
    json
    {
      "servers": {
        "filesystem": {
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "/safe/path"]
        }
      }
    }
  4. 监控资源使用:
    bash
    podman stats $(podman ps -q --filter ancestor=ghcr.io/elusznik/mcp-code-execution)
  5. 审计日志: 检查容器日志是否存在可疑活动:
    bash
    podman logs <container-id>

Performance Tips

性能优化建议

  1. Warm up servers by calling
    discovered_servers()
    early in the session.
  2. Cache tool schemas instead of querying repeatedly:
    python
    from mcp import runtime
    
    # Cache at session start
    all_tools = {}
    for server in await runtime.discovered_servers():
        all_tools[server] = await runtime.query_tool_docs(server)
  3. Use attribute access (slightly faster than dynamic lookup):
    python
    # Preferred
    await mcp_github.create_issue(...)
    
    # Slower
    await mcp_servers["github"].call_tool("create_issue", ...)
  4. Pre-pull images to avoid startup delays:
    bash
    podman pull ghcr.io/elusznik/mcp-code-execution:latest
  1. 提前预热服务器:在会话初期调用
    discovered_servers()
  2. 缓存工具Schema:避免重复查询:
    python
    from mcp import runtime
    
    # 在会话开始时缓存
    all_tools = {}
    for server in await runtime.discovered_servers():
        all_tools[server] = await runtime.query_tool_docs(server)
  3. 使用属性访问(比动态查找略快):
    python
    # 推荐方式
    await mcp_github.create_issue(...)
    
    # 较慢方式
    await mcp_servers["github"].call_tool("create_issue", ...)
  4. 预拉取镜像:避免启动延迟:
    bash
    podman pull ghcr.io/elusznik/mcp-code-execution:latest

References

参考资料