Metadata-Version: 2.4
Name: fc-code-interpreter-mcp-server
Version: 0.1.6
Summary: Code Interpreter MCP Server - Secure code execution via E2B on Function Compute
Project-URL: Homepage, https://github.com/alibaba/fc-code-interpreter-mcp-server
Project-URL: Repository, https://github.com/alibaba/fc-code-interpreter-mcp-server
Project-URL: Documentation, https://github.com/alibaba/fc-code-interpreter-mcp-server#readme
Project-URL: Issues, https://github.com/alibaba/fc-code-interpreter-mcp-server/issues
Author-email: Function Compute Team <fc-team@alibaba-inc.com>
License: MIT
License-File: LICENSE
Keywords: code-interpreter,e2b,function-compute,mcp,sandbox
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Requires-Python: >=3.10
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: alibabacloud-credentials-api>=1.0.0
Requires-Dist: alibabacloud-credentials>=1.0.2
Requires-Dist: alibabacloud-endpoint-util>=0.0.4
Requires-Dist: alibabacloud-fc20230330>=4.2.7
Requires-Dist: alibabacloud-gateway-spi>=0.0.3
Requires-Dist: alibabacloud-openapi-util>=0.2.2
Requires-Dist: alibabacloud-tea-openapi>=0.3.16
Requires-Dist: alibabacloud-tea-util>=0.3.13
Requires-Dist: alibabacloud-tea>=0.4.3
Requires-Dist: attrs>=25.3.0
Requires-Dist: certifi>=2025.7.14
Requires-Dist: charset-normalizer>=3.4.2
Requires-Dist: e2b-code-interpreter>=0.8.0
Requires-Dist: e2b>=0.8.0
Requires-Dist: fastmcp>=2.12.5
Requires-Dist: httpcore>=1.0.9
Requires-Dist: httpx>=0.28.1
Requires-Dist: httpx[socks]>=0.24.0
Requires-Dist: idna>=3.10
Requires-Dist: mcp>=1.0.0
Requires-Dist: packaging>=23.0
Requires-Dist: protobuf>=5.29.5
Requires-Dist: pydantic>=2.10.2
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: requests>=2.31.0
Requires-Dist: six>=1.16.0
Requires-Dist: starlette>=0.36.0
Requires-Dist: typing-extensions>=4.14.1
Requires-Dist: urllib3>=2.5.0
Requires-Dist: uvicorn>=0.27.0
Description-Content-Type: text/markdown

# FC Code Interpreter MCP Server

基于 FastMCP 框架的 MCP 服务器，支持通过 Sandbox 服务进行安全的代码执行，提供多种传输协议（stdio、SSE、HTTP Streamable）。

## 🚀 快速开始

### 方式 1: 使用 Docker Compose（推荐）

一键启动 Sandbox 和 MCP Server 服务：

```bash
# 启动所有服务
make up

# 验证服务运行
curl http://localhost:5001/health  # Sandbox 健康检查
curl http://localhost:3000/sse     # MCP Server SSE 端点

# 停止服务
make down
```

**服务端点**：
- **Sandbox API**: `http://localhost:5001`
- **MCP Server (SSE)**: `http://localhost:3000/sse`

### 方式 2: 手动启动

#### 1. 启动 Sandbox Docker 服务

```bash
# 启动本地 sandbox
docker-compose up -d sandbox-code-interpreter

# 等待服务就绪（需要约 40 秒）
sleep 45

# 验证服务运行
curl http://localhost:5001/health
```

**预期输出**: `{"status":"healthy"}`

#### 2. 安装依赖

```bash
# 使用 UV (推荐)
uv install

# 或使用 pip
pip install -e .
```

#### 3. 启动 MCP Server

```bash
# SSE 协议 (推荐)
make run-sse

# HTTP Streamable 协议
make run-http-streamable

# stdio 协议（用于 Claude Desktop）
make run-stdio
```

## ⚙️ 配置说明

### 环境变量

MCP Server 支持以下环境变量配置（**命令行参数优先级更高**）：

| 环境变量 | 默认值 | 说明 | 命令行参数 |
|---------|--------|------|-----------|
| `MCP_TRANSPORT` | `stdio` | 传输协议 (stdio/sse/http) | `--transport` |
| `MCP_HOST` | `0.0.0.0` | 监听地址 | `--host` |
| `MCP_PORT` | `3000` | 服务端口 | `--port` |
| `MCP_PATH` | `/mcp` | HTTP 端点路径 | `--path` |
| `SANDBOX_URL` | `http://localhost:5001` | Sandbox 服务地址（对于 Docker 环境使用 `http://sandbox-code-interpreter:5000`） | `--sandbox-url` |
| `LOG_LEVEL` | `INFO` | 日志级别 | - |

### 配置方式

#### 方式 1: 环境变量

```bash
# 直接设置环境变量
export MCP_TRANSPORT=sse
export MCP_HOST=0.0.0.0
export MCP_PORT=3000
export SANDBOX_URL=http://localhost:5001

# 运行服务器
uv run python mcp_server/main.py
```

#### 方式 2: 命令行参数（优先级更高）

```bash
# 使用命令行参数
uv run python mcp_server/main.py \
  --transport sse \
  --host 0.0.0.0 \
  --port 3000 \
  --sandbox-url http://localhost:5001
```

#### 方式 3: Docker Compose

`docker-compose.yml` 已预配置 SSE 协议的环境变量：

```yaml
environment:
  - MCP_TRANSPORT=sse
  - MCP_HOST=0.0.0.0
  - MCP_PORT=3000
  - MCP_PATH=/sse
  - SANDBOX_URL=http://sandbox-code-interpreter:5000
```

## 📋 可用工具

### 1. **health_check** - 健康检查
检查 Sandbox 服务状态。

**参数**：无

**示例**：
```json
{}
```

**响应**：
```json
{
  "status": "healthy",
  "sandbox_url": "http://localhost:5001/health",
  "response_code": 200,
  "response_body": "{\"status\":\"healthy\"}",
  "timestamp": "2025-10-25T03:00:00"
}
```

### 2. **create_context** - 创建代码执行上下文
创建新的执行上下文（Session）。

**参数**：
- `language` (string, 可选): 编程语言，默认为 "python"
- `description` (string, 可选): 上下文描述

**示例**：
```json
{
  "language": "python"
}
```

**响应**：
```json
{
  "context_id": "context-uuid",
  "language": "python",
  "description": "",
  "created_at": "2025-10-25T03:00:00"
}
```

### 3. **run_code** - 执行代码
在指定上下文中执行代码。

**参数**：
- `code` (string, 必需): 要执行的代码
- `context_id` (string, 可选): 上下文 ID（如果未提供，需要提供 language）
- `language` (string, 可选): 编程语言（如果未提供 context_id，则必需）

**示例**：
```json
{
  "code": "print('Hello World')",
  "language": "python"
}
```

**示例**（使用 context）：
```json
{
  "code": "print('Hello from context')",
  "context_id": "context-uuid"
}
```

### 4. **list_contexts** - 列出所有上下文
获取当前所有活跃的上下文列表。

**参数**：无

**示例**：
```json
{}
```

**响应**：
```json
[
  {
    "id": "context-uuid-1",
    "language": "python",
    "created_at": "2025-10-25T03:00:00",
    "last_used": "2025-10-25T03:01:00",
    "cwd": "/workspace",
    "status": "active",
    "sandbox_exists": true
  }
]
```

### 5. **stop_context** - 停止上下文
终止指定的执行上下文。

**参数**：
- `context_id` (string, 必需): 要停止的上下文 ID

**示例**：
```json
{
  "context_id": "context-uuid"
}
```

**响应**：
```json
{
  "success": true,
  "message": "Context context-uuid stopped successfully"
}
```

## 🔍 测试服务器

### 使用 MCP Inspector（SSE 协议）

```bash
# 确保 MCP Server 以 SSE 模式运行
make run-sse

# 启动 Inspector 连接到 SSE 端点
npx @modelcontextprotocol/inspector http://localhost:3000/sse
```

### 使用 curl 测试

```bash
# 测试健康检查
curl http://localhost:3000/health_check

# 测试 SSE 端点
curl -N http://localhost:3000/sse

# 测试 HTTP Streamable 端点
curl -N http://localhost:3000/mcp
```

## 🔧 与 Claude Desktop 集成

在 Claude Desktop 配置文件中添加：

```json
{
  "mcpServers": {
    "fc-code-interpreter": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/sandbox-code-interpreter-mcp-server",
        "run",
        "python",
        "-m",
        "mcp_server"
      ],
      "env": {
        "SANDBOX_URL": "http://localhost:5001"
      }
    }
  }
}
```

**提示**：
- 配置文件位置通常为 `~/.config/claude-desktop/claude_desktop_config.json`
- 确保 Sandbox 服务已启动（`curl http://localhost:5001/health`）
- 使用 `make run-stdio` 可以测试 stdio 模式

## 🐳 Docker 相关

### 构建镜像

```bash
# 构建镜像（自动使用 git tag 作为版本号）
make docker-build

# 推送到阿里云镜像仓库
make docker-push
```

### Docker 运行参数

Docker 镜像默认配置：
- `MCP_TRANSPORT=http`
- `MCP_HOST=0.0.0.0`
- `MCP_PORT=3000`
- `MCP_PATH=/mcp`
- `SANDBOX_URL=http://host.docker.internal:5001`

可以通过环境变量或命令行参数覆盖：

```bash
# 使用环境变量
docker run -e SANDBOX_URL=http://custom-sandbox:5000 \
           -e MCP_TRANSPORT=sse \
           -p 3000:3000 \
           sandbox-mcp-server:latest

# 使用命令行参数
docker run -p 3000:3000 sandbox-mcp-server:latest \
  --transport sse \
  --sandbox-url http://custom-sandbox:5000
```

## 🐛 故障排查

### 问题 1: 模块导入错误

```bash
# 确保依赖已安装
uv sync

# 或手动安装依赖
pip install mcp python-dotenv requests pydantic starlette uvicorn
```

### 问题 2: 端口被占用

```bash
# 检查端口占用
lsof -i :3000

# 使用其他端口
MCP_PORT=3001 make run-sse
```

### 问题 3: 无法连接到 Sandbox

```bash
# 检查 Docker 容器状态
docker ps | grep sandbox-code-interpreter

# 查看容器日志
docker logs sandbox-code-interpreter

# 重启容器
docker-compose restart sandbox-code-interpreter
```

### 问题 4: Context 初始化失败

```bash
# 检查 Sandbox 连接
curl http://localhost:5001/health

# 查看 MCP Server 日志
# 确认 SANDBOX_URL 配置正确
```

## 📊 日志输出

服务器启动后会显示：

```
============================================
启动 FastMCP Sandbox Server (SSE)
============================================

配置:
  Transport: SSE
  Host: 0.0.0.0
  Port: 3000
  Sandbox URL: http://localhost:5001

SSE 端点: http://0.0.0.0:3000/sse

INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:3000 (Press CTRL+C to quit)
```

## 🆚 传输协议对比

| 特性 | stdio | SSE | HTTP Streamable |
|------|-------|-----|----------------|
| **传输方式** | 标准输入输出 | HTTP SSE | HTTP |
| **调试难度** | 困难 | 简单 | 简单 |
| **网络访问** | 仅本地 | 支持远程 | 支持远程 |
| **浏览器测试** | 不支持 | 支持 | 支持 |
| **日志查看** | 混在一起 | 独立 | 独立 |
| **连接方式** | 进程管道 | Server-Sent Events | HTTP Request |
| **适用场景** | Claude Desktop | 浏览器、远程调试 | API 集成 |
| **MCP Inspector** | 不支持 | ✅ 支持 | ⚠️ 限制性支持 |

## 🔧 技术栈

- **框架**: FastMCP 2.12.5+
- **语言**: Python 3.10+
- **依赖管理**: UV (推荐) / pip
- **容器化**: Docker
- **云平台**: 阿里云 Function Compute
- **包管理**: Hatchling

## 📚 相关文档

- [FastMCP 迁移总结](docs/FASTMCP_MIGRATION_SUMMARY.md)
- [HTTP Streamable 实现](docs/HTTP_STREAMABLE_IMPLEMENTATION.md)
- [Docker 部署指南](docs/DOCKER_DEPLOY.md)
- [本地快速开始](docs/QUICK_START_LOCAL.md)
- [上下文管理指南](docs/CONTEXT_MANAGEMENT_GUIDE.md)
- [Makefile 使用指南](docs/MAKEFILE_GUIDE.md)

## 📦 安装方式

### 从 PyPI 安装

```bash
pip install fc-code-interpreter-mcp-server
```

### 从源码安装

```bash
# 克隆仓库
git clone https://github.com/alibaba/sandbox-code-interpreter-mcp-server.git
cd sandbox-code-interpreter-mcp-server

# 使用 uv 安装（推荐）
uv sync

# 或使用 pip
pip install -e .
```

## ✅ 验证清单

- [ ] Docker 容器运行正常
- [ ] Sandbox 健康检查通过 (`curl http://localhost:5001/health`)
- [ ] Python 依赖已安装 (`uv install`)
- [ ] MCP Server 启动成功
- [ ] 可以通过 MCP Inspector 连接（SSE 模式）
- [ ] 可以创建 context (`create_context`)
- [ ] 可以执行代码 (`run_code`)
- [ ] 可以列出 contexts (`list_contexts`)
- [ ] 可以停止 context (`stop_context`)
- [ ] 健康检查工具可用 (`health_check`)

## 📝 使用示例

### 执行简单代码

```python
# 创建上下文
create_context(language="python")

# 执行代码
run_code(
    code="print('Hello from FC Code Interpreter!')",
    language="python"
)
```

### 使用上下文执行代码

```python
# 创建上下文
result = create_context(language="python")
context_id = result["context_id"]

# 在上下文中执行代码
run_code(
    code="x = 1 + 1\nprint(x)",
    context_id=context_id
)

# 继续使用同一上下文
run_code(
    code="print(x * 2)",
    context_id=context_id
)

# 清理上下文
stop_context(context_id=context_id)
```

### 列出所有上下文

```python
# 列出所有上下文
contexts = list_contexts()
print(contexts)
```

## 🛠️ Makefile 命令

```bash
# 运行 MCP Server
make run-sse              # SSE 协议（推荐）
make run-http-streamable  # HTTP Streamable 协议
make run-stdio            # stdio 协议

# Docker Compose
make up                   # 启动所有服务
make down                 # 停止所有服务

# Docker 镜像
make docker-build         # 构建镜像
make docker-push          # 推送镜像

# 版本发布
make release              # 发布新版本 (git tag + uv build + uv publish)
```

## 🎯 核心特性

- ✅ **多协议支持**: stdio、SSE、HTTP Streamable
- ✅ **上下文管理**: 支持创建、列出、停止上下文
- ✅ **代码执行**: 安全的沙盒环境执行代码
- ✅ **健康检查**: 完整的服务健康检查机制
- ✅ **环境变量配置**: 灵活的配置管理
- ✅ **Docker 支持**: 完整的容器化部署方案
- ✅ **远程调试**: 支持 MCP Inspector 调试
- ✅ **阿里云 FC 集成**: 支持在阿里云 Function Compute 上运行

## 📦 版本发布

### 一键发布流程

```bash
# 执行发布命令
make release
```

**发布脚本会交互式完成以下步骤**：

#### 第 1 步：版本升级
```
版本升级选项:
  1) Patch (0.0.10 → 0.0.11)  - 修复 bug
  2) Minor (0.0.10 → 0.1.0)   - 新功能（向后兼容）
  3) Major (0.0.10 → 1.0.0)   - 重大更新（可能不兼容）
  4) Custom - 手动输入版本号
  5) Skip - 使用当前版本（不升级）
```

#### 第 2 步：自动构建和发布
- ✅ 更新 `pyproject.toml` 版本号
- ✅ 提交版本更新到 Git
- ✅ 创建 Git tag (v x.x.x)
- ✅ 构建 Python 包 (uv build)
- ✅ 发布到 PyPI (uv publish)
- ✅ 构建 Docker 镜像 (包含版本 tag 和 latest tag)
- ✅ 推送 Docker 镜像到阿里云
- ✅ 记录发布历史到 `.release/` 目录
- ✅ 推送 Git tag 到远程

### 发布内容

发布脚本会自动执行以下操作：
- 更新 `pyproject.toml` 版本号
- 创建 Git tag
- 构建 Python 包（wheel 和 sdist）
- 发布到 PyPI 或 TestPyPI
- 构建 Docker 镜像并推送到阿里云
- 记录发布历史

### 发布版本对比

**当前版本**: `0.0.12`（从 `pyproject.toml` 读取）

```bash
# 查看当前版本
grep "^version = " pyproject.toml

# 查看最近的 tags
git tag -l | tail -5
```

### 发布历史

每次发布会在 `.release/` 目录创建一个记录文件：

```
.release/
├── 0.0.10.release     # 版本发布记录
├── 0.0.11.release
└── ...
```

---

**Happy coding with FastMCP! 🎉**
