🚀 MCP服务器编排器
MCP(模型上下文协议)服务器的完整编排系统,通过现代、可扩展的架构将AI模型与自定义工具集成在一起。
📋 目录
- - -
______________________________________________________________________
🎯 关于项目
MCP服务器编排器 是一个允许您创建能够通过自定义工具执行操作的智能AI代理的系统。该项目包括两项主要服务:
- 🔧 MCP服务器 (端口3000):一个遵循MCP协议公开自定义工具的服务器。
- 🎭 编排器 (端口3001):一种在AI模型(OpenAI)和MCP服务器之间协调请求的服务。
使用案例:
- 创建具有自定义功能的AI助手。
- 将语言模型与数据库和API集成。
- 构建可以在系统内执行操作的智能代理。
- 快速原型化人工智能新工具。
______________________________________________________________________
🏗️ 建筑
graph LR
A[Client/User] -->|POST /api/inquire| B[Orchestrator :3001]
B -->|LLM Request| C[OpenAI API]
B -->|MCP Protocol| D[MCP Server :3000]
D -->|Query| E[(PostgreSQL)]
C -->|Tool Calls| B
B -->|Response| A
style A fill:#e1f5ff
style B fill:#fff4e6
style C fill:#f3e5f5
style D fill:#e8f5e9
style E fill:#fce4ec通信流
- 客户 向发送请求 编排器 带有用户消息。
- 编排器 连接到 MCP服务器 以获取可用的工具。
- 编排器 将消息和工具发送到 开放人工智能.
- 开放人工智能 决定使用哪些工具并返回
tool_calls. - 编排器 执行上的工具 MCP服务器.
- MCP服务器 处理请求(DB查询、API等)。
- 结果将发送回 开放人工智能 以生成最终响应。
- 编排器 将响应返回给 客户.
______________________________________________________________________
⚙️ 运作原理
主要组件
1. MCP服务器 (services/mcp-server)
- 使用以下方式实现MCP协议
@modelcontextprotocol/sdk. - 展示AI模型可以执行的工具。
- 使用Prisma管理与PostgreSQL的连接。
- 端口3000上的HTTP服务器
/mcp终点。
工具示例:
// Simple tool that greets
server.tool(
'hello',
'Say hello to someone',
{
name: z.string().describe('Name of the person to greet'),
},
async ({ name }) => {
return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
},
);2. 编排器 (services/orchestrator)
- 端口3001上的Express服务器。
- 协调OpenAI和MCP服务器之间的通信。
- 实施策略模式以支持多个LLM提供者。
- 使用身份验证中间件验证请求(
KAA头球
请求流:
POST /api/inquire
→ validateAgentMiddleware (checks KAA header)
→ inquireController (validates and processes messages)
→ Orchestrator.processConversation()
├─ Connects to MCP Server
├─ Fetches available tools
├─ Conversation Loop (max 10 iterations):
│ ├─ Sends messages to OpenAI with available tools
│ ├─ If OpenAI requests tool_calls → executes on MCP Server
│ ├─ Adds results to history
│ └─ Repeats until final response is obtained
└─ Returns response to client______________________________________________________________________
📦 先决条件
最低要求
- ✅ Node.js:v20.x或更高版本(下载)
- ✅ npm:v10.x或更高版本(包含在Node.js中)
- ✅ PostgreSQL:v14或更高版本(可以是外部版本)
- ✅ OpenAI API密钥:获取它 platform.openai.com
Docker要求
- ✅ 码头工人:v20.10或更高版本(下载)
- ✅ Docker Compose:v2.0或更高版本
- ✅ 至少 2GB内存 可用的
验证安装
# Verify Node.js
node --version # Should show v20.x.x or higher
# Verify npm
npm --version # Should show v10.x.x or higher
# Verify Docker (if using it)
docker --version
docker-compose --version______________________________________________________________________
🚀 快速开始
初始设置(两种选项)
- 克隆存储库
git clone
cd mcp-server-orchestrator- 配置环境变量
# Copy example file
cp .env.example .env- 编辑
.env使用您的凭据
# Windows
notepad .env
# Linux/Mac
nano .env至少配置:
- DATABASE_URL:PostgreSQL数据库的连接URL。 - OPENAI_API_KEY:您的OpenAI API密钥。 - KEY_ALLOWED_AGENTS:用于身份验证的密钥。
现在选择您首选的部署选项⬇️
______________________________________________________________________
🛠️ 部署选项
选项A:无Docker(本地开发)
适用于: 积极开发、调试、测试新功能。
步骤1:安装依赖项
# Install dependencies in the entire monorepo
npm install
# Build the shared package (required by other services)
npm run build:shared步骤2:配置数据库
# Generate Prisma client
npm run prisma:generate
# Run migrations (optional, if you have pending migrations)
npm run prisma:migrate步骤3:启动服务
选项3A:独立端子 (建议开发)
# Terminal 1: MCP Server
npm run dev:mcp-server
# Terminal 2: Orchestrator
npm run dev:orchestrator选项3B:生产模式
# Build all services
npm run build
# Terminal 1: MCP Server
npm run start:mcp-server
# Terminal 2: Orchestrator
npm run start:orchestrator步骤4:验证安装
# Verify MCP Server
curl http://localhost:3000/health
# Verify Orchestrator
curl http://localhost:3001/health✅ 如果两者都回应 OK 或 {"status":"ok"}你准备好了!
______________________________________________________________________
选项B:使用Docker Compose(推荐)
适用于: 生产、服务器部署、一致的环境。
步骤1:配置变量
# Copy template
cp env.template .env
# Edit with your values
notepad .env # Windows
nano .env # Linux/Mac重要提示: 配置 DATABASE_URL 使用您的外部PostgreSQL数据库。
步骤2:启动服务
# Build and start all services
docker-compose up -d --build
# View real-time logs
docker-compose logs -f
# View logs for a specific service
docker-compose logs -f orchestrator步骤3:运行迁移(第一次)
# Generate Prisma client (if necessary)
docker-compose exec mcp-server npx prisma generate
# Run migrations (if necessary)
docker-compose exec mcp-server npx prisma migrate deploy步骤4:验证安装
# View container status
docker-compose ps
# Verify health checks
curl http://localhost:3000/health
curl http://localhost:3001/health有用的Docker编写命令
# Stop services
docker-compose down
# Restart a service
docker-compose restart mcp-server
# View error logs
docker-compose logs | grep ERROR
# Rebuild from scratch
docker-compose down
docker-compose build --no-cache
docker-compose up -d
# Enter a container
docker-compose exec mcp-server sh______________________________________________________________________
选项C:单个Docker容器
适用于: 高级部署、自定义编排、Kubernetes。
构建图像
# Build MCP Server image
docker build --target mcp-server -t mcp-server:latest -f Dockerfile .
# Build Orchestrator image
docker build --target orchestrator -t orchestrator:latest -f Dockerfile .创建Docker网络
docker network create mcp-network运行MCP服务器
docker run -d \
--name mcp-server \
--network mcp-network \
-p 3000:3000 \
-e DATABASE_URL="postgresql://user:password@host:5432/db" \
-e PORT=3000 \
-e NODE_ENV=production \
--restart unless-stopped \
mcp-server:latest运行编排器
docker run -d \
--name orchestrator \
--network mcp-network \
-p 3001:3001 \
-e MCP_SERVER_URL="http://mcp-server:3000/mcp" \
-e OPENAI_API_KEY="your-api-key" \
-e KEY_ALLOWED_AGENTS="your-secret-key" \
-e PORT=3001 \
-e NODE_ENV=production \
--restart unless-stopped \
orchestrator:latest验证容器
# View active containers
docker ps
# View logs
docker logs -f mcp-server
docker logs -f orchestrator
# Execute commands inside the container
docker exec -it mcp-server sh______________________________________________________________________
🔐 环境变量
变量表
| 变量 | 服务 | 必需 | 描述 | 示例 |
|---|---|---|---|---|
NODE_ENV | 两者 | 否 | 执行环境 | production / development |
DATABASE_URL | MCP服务器 | ✅ 是 | PostgreSQL连接URL | postgresql://user:pass@localhost:5432/dbname |
MCP_SERVER_PORT | MCP服务器 | 否 | MCP服务器端口 | 3000 (默认) |
ORCHESTRATOR_PORT | 编排器 | 否 | 编排器端口 | 3001 (默认) |
MCP_SERVER_URL | 编排器 | ✅ 是 | MCP服务器URL | http://localhost:3000/mcp |
OPENAI_API_KEY | 编排器 | ✅ 是 | OpenAI API密钥 | sk-... |
KEY_ALLOWED_AGENTS | 编排器 | ✅ 是 | 身份验证密钥 | my-secret-key |
OPENAI_MODEL | 编排器 | 否 | 要使用的OpenAI模型 | gpt-4o-mini (默认) |
GEMINI_API_KEY | 编排者 | 指挥。 | Gemini API密钥 | AI... |
GEMINI_MODEL | 编排器 | 否 | 要使用的Gemini模型 | gemini-2.0-flash (默认) |
LLM_PROVIDER | 编排器 | 否 | LLM提供程序 | openai / gemini (默认值: openai) |
示例 .env 文件
# General
NODE_ENV=production
# PostgreSQL Database (External)
DATABASE_URL=postgresql://user:password@db.example.com:5432/mcp_db
# MCP Server
MCP_SERVER_PORT=3000
# Orchestrator
ORCHESTRATOR_PORT=3001
MCP_SERVER_URL=http://localhost:3000/mcp
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxx
KEY_ALLOWED_AGENTS=my-super-secret-key-12345
# LLM Configuration (Optional)
LLM_PROVIDER=openai
OPENAI_MODEL=gpt-4o-mini
# Gemini (use LLM_PROVIDER=gemini)
# GEMINI_API_KEY=AI...
# GEMINI_MODEL=gemini-2.0-flash______________________________________________________________________
� MCP配置:连接到外部MCP服务器
编排器可以连接到 任何兼容MCP的服务器,而不仅仅是内置的。这是通过以下方式配置的 mcp_config.json 文件放置在 services/orchestrator/ 目录。
支持的交通工具
| 运输 | 描述 | 用例 |
|---|---|---|
stdio | 生成一个本地进程,并通过stdin/stdout | npm包、本地脚本、与Claude Desktop兼容的服务器进行通信 |
streamableHttp | 使用当前的MCP Streamable HTTP协议通过HTTP连接 | 远程服务器、您自己的MCP服务器、生产API |
sse | 通过服务器发送事件进行连接(传统MCP协议2024-11-05) | 尚未迁移到流式HTTP的旧MCP服务器 |
配置文件
创建 services/orchestrator/mcp_config.json:
{
"mcpServers": {
"my-mcp-server": {
"transport": "streamableHttp",
"url": "http://localhost:3000/mcp"
},
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"]
},
"github": {
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx"
}
},
"filesystem": {
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
"remote-server": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://your-remote-server.com/mcp"]
},
"legacy-sse-server": {
"transport": "sse",
"url": "http://localhost:8080/sse"
}
}
}运输自动检测
这 transport 字段是 可选的如果省略,则根据配置形状自动检测:
| 配置已检测到传输 | |
|---|---|
command | stdio |
url | streamableHttp |
这使得配置与 克劳德桌面/光标/风帆 格式:
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"]
}
}
}配置文件解析
编排器按以下顺序搜索配置文件:
MCP_CONFIG_PATH环境变量(绝对路径)mcp_config.json在当前工作目录中.mcp_config.json在当前工作目录中mcp.config.json在当前工作目录中
交通参考
标准
生成一个子进程,并通过stdin/stdout进行通信。非常适合基于npm的MCP服务器。
{
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_TOKEN": "..." },
"cwd": "/optional/working/directory"
}| 字段 | 必填 | 描述 |
|---|---|---|
command | ✅ | 可执行文件运行(npx, node, python等等) |
args | 无 | 命令行参数 |
env | 否 | 流程的环境变量 |
cwd | 否 | 工作目录 |
流式Http
通过MCP Streamable HTTP协议连接到远程服务器。
{
"transport": "streamableHttp",
"url": "http://localhost:3000/mcp",
"headers": { "Authorization": "Bearer ..." }
}| 字段 | 必填 | 描述 |
|---|---|---|
url | ✅ | MCP端点的完整URL |
headers | 否 | 其他HTTP标头 |
SSE
通过SSE(传统协议)连接。仅适用于尚未迁移到Streamable HTTP的服务器。
{
"transport": "sse",
"url": "http://localhost:8080/sse",
"headers": { "Authorization": "Bearer ..." }
}| 字段 | 必填 | 描述 |
|---|---|---|
url | ✅ | SSE端点的完整URL |
headers | 否 | 其他HTTP标头 |
运作原理
当编排器开始处理对话时:
- 负载
mcp_config.json并连接到所有配置的服务器。 - 从每个服务器中发现工具并构建统一的工具注册表。
- 来自所有服务器的所有工具都传递给LLM。
- 当LLM调用工具时,Orchestrator会自动将其路由到正确的服务器。
- 无法连接的服务器将被跳过(非阻塞),其余服务器将继续工作。
注: 如果两台服务器公开了一个同名工具,则最后一台加载的服务器获胜。发生这种情况时会记录一条警告。
______________________________________________________________________
�💡 用法和示例
MCP检验员(测试工具)
要直观地测试MCP服务器:
# From the project root
npm run start:inspector-mcp这将打开一个web界面,与MCP工具进行交互。
示例1:Orchestrator API调用
curl -X POST http://localhost:3001/api/inquire \
-H "Content-Type: application/json" \
-H "KAA: your-secret-key" \
-d '{
"messages": [
{"role": "user", "content": "Hello, what tools do you have available?"}
]
}'示例2:使用特定工具
curl -X POST http://localhost:3001/api/inquire \
-H "Content-Type: application/json" \
-H "KAA: your-secret-key" \
-d '{
"messages": [
{"role": "user", "content": "Use the hello tool to greet John"}
]
}'示例3:多回合对话
curl -X POST http://localhost:3001/api/inquire \
-H "Content-Type: application/json" \
-H "KAA: your-secret-key" \
-d '{
"messages": [
{"role": "user", "content": "What is your name?"},
{"role": "assistant", "content": "I am an AI assistant powered by MCP."},
{"role": "user", "content": "Can you help me with data analysis?"}
]
}'示例4:使用邮递员
网址: http://localhost:3001/api/inquire\ 方法: POST\ 标题:
Content-Type: application/jsonKAA: your-secret-key
正文(JSON):
{
"messages": [{ "role": "user", "content": "message here" }]
}预期响应
{
"success": true,
"response": "Response generated by the AI model",
"metadata": {
"iterations": 2,
"toolsUsed": ["hello", "getAccountAnalytics"]
}
}______________________________________________________________________
📁 项目结构
mcp-server-orchestrator/
├── services/
│ ├── mcp-server/ # MCP Server (Port 3000)
│ │ ├── src/
│ │ │ ├── core/ # MCP Server logic
│ │ │ │ └── server.ts # Configuration and tool registration
│ │ │ ├── infraestructure/ # Infrastructure
│ │ │ │ └── tools/ # MCP tool implementation
│ │ │ └── index.ts # Entry point
│ │ ├── prisma/
│ │ │ └── schema.prisma # Database schema
│ │ └── package.json
│ │
│ └── orchestrator/ # Orchestrator (Port 3001)
│ ├── src/
│ │ ├── api/ # Controllers and middleware
│ │ │ ├── inquireController.ts
│ │ │ └── validateAgentMiddleware.ts
│ │ ├── llm/ # LLM Providers (Strategy Pattern)
│ │ │ ├── ILlmProvider.ts
│ │ │ ├── OpenAIProvider.ts
│ │ │ └── LlmProviderFactory.ts
│ │ ├── mcp/ # MCP Client
│ │ │ ├── McpClient.ts
│ │ │ └── Orchestrator.ts
│ │ └── index.ts # Entry point - Express Server
│ ├── ARCHITECTURE.md # Detailed documentation
│ └── package.json
│
├── packages/
│ └── shared/ # Shared utilities
│ ├── src/
│ │ ├── types/ # TypeScript Types
│ │ ├── utils/ # Utility functions
│ │ └── schemas/ # Zod Schemas
│ └── package.json
│
├── Dockerfile # Multi-stage build for both services
├── docker-compose.yml # Service orchestration
├── .env.example # Environment variable example
├── env.template # Template for Docker
├── package.json # Workspace root
├── tsconfig.json # TypeScript configuration
└── README.md # This file______________________________________________________________________
🎯 可用脚本
根脚本(工作区)
# Build
npm run build # Builds all services
npm run build:shared # Builds only the shared package
npm run build:mcp-server # Builds only the MCP Server
npm run build:orchestrator # Builds only the Orchestrator
# Development
npm run dev:mcp-server # Development mode MCP Server (hot reload)
npm run dev:orchestrator # Development mode Orchestrator (hot reload)
npm run dev:shared # Development mode Shared (watch)
# Production
npm run start:mcp-server # Runs compiled MCP Server
npm run start:orchestrator # Runs compiled Orchestrator
npm run start:inspector-mcp # Opens MCP Inspector in the browser
# Database (Prisma)
npm run prisma:generate # Generates Prisma client
npm run prisma:migrate # Runs migrations
npm run prisma:studio # Opens Prisma Studio (GUI)
# Code Quality
npm run lint # Checks code with ESLint
npm run lint:fix # Automatically fixes errors
npm run format # Formats code with Prettier
# Maintenance
npm run clean # Cleans builds and node_modules
npm run install:all # Installs deps and builds shared每个服务的脚本
# In services/mcp-server/
cd services/mcp-server
npm run dev # Development with hot reload
npm run build # Builds the service
npm run start # Runs compiled version
npm run prisma:generate # Generates Prisma client
npm run prisma:studio # Opens Prisma Studio
# In services/orchestrator/
cd services/orchestrator
npm run dev # Development with tsx
npm run build # Builds the service
npm run start # Runs compiled version______________________________________________________________________
🔥 故障排除
常见问题及解决方法
1.错误:“找不到模块'@modelcontextprotocol/sdk'”
原因: 依赖项安装不正确。
解决方案:
# Clean cache and reinstall
npm run clean
npm install
npm run build:shared2.错误:“未生成Prisma客户端”
原因: 未生成Prisma客户端。
解决方案:
npm run prisma:generate3.错误:“端口3000已在使用中”
原因: 端口被另一个进程占用。
解决方案:
# Windows - Find process using the port
netstat -ano | findstr :3000
taskkill /PID
/F
# Linux/Mac
lsof -i :3000
kill -9
# Or change the port in .env
MCP_SERVER_PORT=30024.数据库连接错误
原因: 不正确 DATABASE_URL 或数据库不可访问。
解决方案:
# Verify connection
psql postgresql://user:password@host:5432/dbname
# Verify variable is set
echo $DATABASE_URL # Linux/Mac
echo %DATABASE_URL% # Windows cmd
$env:DATABASE_URL # Windows PowerShell
# Ensure correct format
DATABASE_URL="postgresql://user:password@host:5432/db_name"5.Docker:“服务'mcp-server'未成功完成”
原因: 环境变量或构建中出错。
解决方案:
# View detailed logs
docker-compose logs mcp-server
# Rebuild without cache
docker-compose down
docker-compose build --no-cache
docker-compose up -d
# Verify environment variables
docker-compose config6.错误:Orchestrator中的“无效的API密钥”
原因: OPENAI_API_KEY 未配置或无效。
解决方案:
# Verify key is in .env
cat .env | grep OPENAI_API_KEY
# Ensure it starts with 'sk-'
OPENAI_API_KEY=sk-proj-...7.调用时出现401/403错误 /api/inquire
原因: 缺失或不正确 KAA 头球
解决方案:
# Ensure correct header is included
curl -H "KAA: your-secret-key" ...
# Verify it matches .env
KEY_ALLOWED_AGENTS=your-secret-key8.编排器无法连接到MCP服务器
原因: 不正确 MCP_SERVER_URL.
解决方案:
# Without Docker (localhost)
MCP_SERVER_URL=http://localhost:3000/mcp
# With Docker Compose (service name)
MCP_SERVER_URL=http://mcp-server:3000/mcp
# Verify both services are running
curl http://localhost:3000/health
curl http://localhost:3001/health9.热重载在开发中不起作用
原因: 文件未被查看。
解决方案:
# Stop process and restart
# Ctrl+C to stop
npm run dev:mcp-server
# If using Windows with WSL, there might be file watching issues
# Use polling mode
npm run dev -- --usePolling10.在Docker中执行迁移时出错
原因: 未生成权限或Prisma客户端。
解决方案:
# Generate client first
docker-compose exec mcp-server npx prisma generate
# Then execute migrations
docker-compose exec mcp-server npx prisma migrate deploy
# If it fails, enter container and debug
docker-compose exec mcp-server sh
cd /app/services/mcp-server
npx prisma migrate deploy --schema=prisma/schema.prisma诊断命令
# Verify versions
node --version
npm --version
docker --version
docker-compose --version
# Verify running services
# Without Docker
curl http://localhost:3000/health
curl http://localhost:3001/health
# With Docker
docker-compose ps
docker-compose logs --tail=50
# Verify connectivity between services (Docker)
docker-compose exec orchestrator ping mcp-server
# View environment variables (Docker)
docker-compose exec mcp-server env | grep DATABASE
docker-compose exec orchestrator env | grep OPENAI______________________________________________________________________
🤝 贡献
Git工作流
- 分叉存储库
- 从以下位置创建要素分支
develop
git checkout develop
git pull origin develop
git checkout -b feat/feature-name- 开发和测试
# Develop your feature
npm run dev:mcp-server
# Format code
npm run format
# Verify linting
npm run lint:fix- 用描述性消息提交
git add .
git commit -m "feat: description of change"- 推送并创建拉取请求
git push origin feat/feature-name- PR到
develop,不main
分支命名约定
feat/feature-name-新功能fix/bug-description-Bug修复docs/topic-文件refactor/component-代码重构test/component-添加测试
添加新的MCP工具
- 在中创建文件
services/mcp-server/src/infraestructure/tools/. - 按照现有模式实施该工具。
- 注册于
services/mcp-server/src/core/server.ts. - 编排器将自动发现它们✨
例子:
// services/mcp-server/src/infraestructure/tools/myTool.ts
import { z } from 'zod';
export function registerMyTool(server: Server) {
server.tool(
'myTool',
'Description of what the tool does',
{
param1: z.string().describe('Description of param1'),
param2: z.number().describe('Description of param2'),
},
async ({ param1, param2 }) => {
// Implementation
const result = doSomething(param1, param2);
return {
content: [
{
type: 'text',
text: JSON.stringify(result),
},
],
};
},
);
}添加新的LLM提供程序
- 实施
ILlmProvider在services/orchestrator/src/llm/. - 添加到工厂
LlmProviderFactory.ts. - 在中配置
.env随着LLM_PROVIDER=new-provider.
______________________________________________________________________
📚 附加文档
______________________________________________________________________
📄 许可证
既然什么都没有,你可以从头开始这个项目。
______________________________________________________________________
🙏 致谢
- 模型上下文协议(MCP) 对于SDK。
- 开放人工智能 用于语言模型API。
- 棱镜 对于优秀的ORM。
______________________________________________________________________
Made with ❤️ to simplify AI integration with custom tools
⭐ If this project was useful, consider giving it a star
