LLM对话与工具集成服务

支持OpenAI兼容的LLM对话和MCP工具集成,同时支持SSE和stdio两种MCP传输协议。

  • by randolph555
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 randolph555/chat-mcp

使用说明

MCP Service - 模型上下文协议服务

支持OpenAI兼容的LLM对话和MCP工具集成,同时支持SSE和stdio两种MCP传输协议。

🚀 架构设计

  • manager/ - MCP服务管理 + FastAPI主入口
    • service.py - 主服务(MCP 管理、进程管理、HTTP API)
    • llm_chat.py - LLM 聊天处理
  • servers/ - MCP 工具服务
    • command_tools.py - 命令和文件操作工具(端口8002)
    • macos_tools.py - macOS 系统工具(端口8003)
┌─────────────────┐    ┌─────────────────┐
│   MCP Tools     │    │   LLM Client    │
│  (localhost:    │    │  (Chat with     │
│   8002/8003)    │    │   AI + Tools)   │
└─────────┬───────┘    └─────────┬───────┘
          │                      │
          │ Register/Discover    │ POST /chat/completions
          │                      │
          └──────────────────────┼────────┐
                                 │        │
                    ┌─────────────▼────────▼─┐
                    │    mcp_manager.py      │
                    │  (主服务 - Port 8000)   │
                    │                        │
                    │  • MCP Registry        │
                    │  • Process Manager     │
                    │  • FastAPI Routes      │
                    └───────────┬────────────┘
                                │
                    ┌───────────▼────────────┐
                    │    llm_chat.py         │
                    │  (LLM聊天处理)          │
                    │                        │
                    │  • OpenAI Client       │
                    │  • Tool Integration    │
                    │  • Streaming Support   │
                    └────────────────────────┘

📁 项目结构

mcp-service/
├── 📂 manager/                # 管理服务(协调和 API)
│   ├── service.py            # 主服务入口 (端口8000) ⭐
│   └── llm_chat.py           # LLM 聊天处理 ⭐
├── 📂 servers/                # MCP 工具服务(提供功能)
│   ├── command_tools.py      # 命令和文件工具 (端口8002)
│   └── macos_tools.py        # macOS 工具服务 (端口8003)
├── 📂 config/                 # 配置文件
│   └── servers.json          # MCP 服务配置
├── 📂 log/                    # 日志文件
├── restart.sh                # 一键启动脚本
├── requirements.txt          # Python 依赖
└── README.md                 # 本文档

💡 目录说明:servers/ 是提供工具的 MCP 服务器,manager/ 是管理和协调服务

详细结构说明请查看 PROJECT_STRUCTURE.md

🔧 快速开始

1. 配置环境

# 克隆项目
git clone <your-repo>
cd mcp-service

# 确认.env配置 (已预配置百炼API)
cat .env

2. 一键启动

./restart.sh

启动后:

  • MCP Manager (主服务): http://localhost:8000 - LLM聊天 + MCP管理
  • 文件工具服务: http://localhost:8002 - 文件操作工具
  • macOS工具服务: http://localhost:8003 - 系统工具

3. 测试对话

curl -X POST "http://localhost:8000/chat/completions" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "列出当前目录的文件"}
    ],
    "use_tools": true
  }'

🛠️ 核心功能

mcp_manager.py (主服务)

  • ✅ MCP服务器注册/删除/查询
  • ✅ stdio进程生命周期管理
  • ✅ 支持SSE和stdio两种传输协议
  • ✅ 配置导入/导出(兼容Claude Desktop格式)
  • ✅ FastAPI路由和中间件
  • ✅ 自动清理和优雅关闭

llm_chat.py (聊天处理)

  • ✅ OpenAI兼容的聊天API
  • ✅ 流式和非流式响应
  • ✅ 工具自动发现和映射
  • ✅ 智能工具调用编排
  • ✅ 多服务工具集成

MCP工具服务

  • ✅ 文件操作工具(ls, cat, grep等)
  • ✅ macOS系统工具(截图、消息、热榜等)
  • ✅ 标准MCP协议实现
  • ✅ 安全的命令执行

🔐 安全特性

命令白名单:

SAFE_COMMANDS = {
    'ls', 'pwd', 'date', 'whoami', 'uname', 'echo',
    'cat', 'head', 'tail', 'grep', 'find', 'ps',
    'df', 'du', 'free', 'uptime', 'which', 'wc'
}

📝 API使用

注册MCP服务

方式1: SSE传输(URL方式)

curl -X POST "http://localhost:8000/register" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my_tools",
    "endpoint": "http://localhost:8003/sse",
    "description": "My custom tools"
  }'

方式2: stdio传输(命令方式,兼容Claude Desktop)

curl -X POST "http://localhost:8000/register" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "chrome-devtools",
    "command": "npx",
    "args": ["-y", "chrome-devtools-mcp@latest"],
    "description": "Chrome DevTools MCP"
  }'

导入配置文件

# 使用示例配置
curl -X POST "http://localhost:8000/config/import" \
  -H "Content-Type: application/json" \
  -d @stdio_config_example.json

# 或直接传JSON
curl -X POST "http://localhost:8000/config/import" \
  -H "Content-Type: application/json" \
  -d '{
    "mcpServers": {
      "local-tools": {
        "url": "http://localhost:8002/sse",
        "description": "本地工具"
      },
      "chrome-devtools": {
        "command": "npx",
        "args": ["-y", "chrome-devtools-mcp@latest"],
        "description": "Chrome工具"
      }
    }
  }'

查看已注册服务

curl "http://localhost:8000/servers"

LLM聊天对话

curl -X POST "http://localhost:8000/chat/completions" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-max",
    "messages": [
      {"role": "user", "content": "帮我查看~/Downloads目录"}
    ],
    "use_tools": true
  }'

🔄 扩展更多工具

方式1: 使用npm包(推荐,支持stdio)

# 直接注册npm包(自动下载和运行)
curl -X POST "http://localhost:8000/register" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "filesystem",
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem@latest", "/tmp"],
    "description": "文件系统工具"
  }'

方式2: 自定义MCP服务

# my_custom_tools.py
from fastmcp import FastMCP

mcp = FastMCP("My Custom Tools")

@mcp.tool()
def my_tool(param: str) -> str:
    """我的自定义工具"""
    return f"处理结果: {param}"

if __name__ == "__main__":
    mcp.run(transport="sse")  # SSE方式,监听默认端口

然后注册:

curl -X POST "http://localhost:8000/register" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "custom_tools",
    "endpoint": "http://localhost:8004/sse",
    "description": "自定义工具"
  }'

🐛 故障排除

服务启动失败:

# 检查端口占用
lsof -i :8000

# 停止并重启
./restart.sh

# 查看日志
tail -f log/manager.log
tail -f log/command_tools.log
tail -f log/macos_tools.log

stdio服务连接失败:

# 检查npm是否安装
npm --version

# 手动测试stdio服务
npx -y chrome-devtools-mcp@latest

# 查看进程状态
ps aux | grep node

工具调用失败:

  • 检查服务是否注册成功:curl http://localhost:8000/servers
  • 查看工具列表是否正确
  • 检查日志输出中的错误信息
  • 确认网络连接正常

⚡ 特性亮点

  • 模块化架构:MCP和LLM完全解耦,易于维护
  • 双协议支持:同时支持SSE和stdio传输方式
  • 进程管理:自动管理stdio子进程生命周期
  • 标准兼容:兼容Claude Desktop配置格式
  • 快速启动:3秒内完成服务启动和注册
  • 优雅关闭:自动清理所有子进程

🤝 贡献

欢迎提交Issue和PR来改进项目!

📄 许可证

MIT License - 详见LICENSE文件