huoyan-enterprise/mcp-server-demo/README.md

71 lines
1.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# MCP Excel 分析服务
基于 **FastMCP** 的 Excel/CSV 表格分析 MCP 服务:在 **Docker 容器内**用 pandas 沙箱执行 LLM 生成的分析代码,与 backend 主进程隔离。
## 提供的 MCP 工具
| 工具 | 说明 |
|------|------|
| `excel_get_schema` | 下载表格,返回 sheet、列名、类型、前 5 行预览JSON |
| `excel_run_pandas` | 在沙箱中执行 pandas 代码(仅 `pd`/`df`,结果赋给 `result` |
## 本地运行
```bash
cd mcp-server-demo
python -m venv .venv && source .venv/bin/activate
pip install -e .
cp .env.example .env
# 编辑 MCP_API_KEY可选与 backend 一致)
python server.py
# 默认 http://0.0.0.0:8010/mcp
```
## Docker 部署
```bash
cd mcp-server-demo
cp .env.example .env
docker compose up -d --build
```
服务监听 `8010`。确保容器能访问 Excel 的 **下载 URL**OSS 公网或内网签名 URL
## 环境变量
| 变量 | 说明 |
|------|------|
| `MCP_HOST` | 绑定地址,默认 `0.0.0.0` |
| `MCP_PORT` | 端口,默认 `8010` |
| `MCP_API_KEY` | 可选;配置后请求需 `Authorization: Bearer <key>` |
| `MCP_ALLOWED_HOSTS` | 反向代理 Host 白名单 |
## Backend 接入
`backend/.env` 中配置:
```env
MCP_URL=http://127.0.0.1:8010/mcp
MCP_TRANSPORT=streamable_http
MCP_API_KEY=与 mcp-server-demo/.env 相同
```
若 backend 与 MCP 同 docker compose 网络:
```env
MCP_URL=http://mcp-excel:8010/mcp
```
重启 backend 后,聊天 Agent 会自动加载 MCP 工具。当会话或绑定知识库中存在 `.xlsx/.xls/.csv` 且文件已处理完成时,系统提示中会注入 **file_url**,模型应:
1. `excel_get_schema(file_url)`
2. `excel_run_pandas(file_url, pandas_code, sheet_name)`
## 安全说明
- pandas 代码经 AST 校验,禁止 `import`、文件与网络操作
- 单次下载上限 20MB执行超时 15sDataFrame 结果最多 200 行
- 生产环境务必使用 Docker 隔离 + `MCP_API_KEY`