MCP员工API-概念验证
概念验证实施证明 模型上下文协议(MCP) 作为REST API端点和AI代理之间的中间层。该项目展示了人工智能代理如何通过标准化的MCP接口与后端服务进行交互。
架构概述
该POC实现了三层架构:
┌─────────────────┐
│ AI Agent │ (Google Gemini)
│ (Conversational│
│ Interface) │
└────────┬────────┘
│ JSON-RPC
↓
┌─────────────────┐
│ MCP Server │ (Port 8001)
│ (Translation │
│ Layer) │
└────────┬────────┘
│ REST API
↓
┌─────────────────┐
│ REST API │ (Port 8000)
│ (FastAPI + │
│ PostgreSQL) │
└─────────────────┘组件
- REST API层 (
main.py):基于FastAPI的CRUD操作,用于员工管理 - MCP服务器层 (
mcp_server.py):将来自AI代理的JSON-RPC调用转换为REST API调用 - AI代理客户端 (
ai_agent_client.py):使用带有函数调用的Google Gemini的对话界面
特性
- 员工CRUD操作:创建、读取和列出员工记录
- MCP协议实现:JSON-RPC 2.0兼容接口
- 人工智能驱动的交互:通过Google Gemini进行自然语言查询
- 过滤和分页:按姓名、电子邮件或职位搜索员工
- PostgreSQL数据库:强大的数据持久性
先决条件
- Python 3.8+
- PostgreSQL 12+
- 启用Vertex AI API的谷歌云项目
- 已配置Google Cloud凭据
安装
- 克隆存储库 (或提取项目文件)
- 创建虚拟环境
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- 安装依赖项
pip install -r requirements.txt- 设置PostgreSQL数据库
# Create the database
createdb employees_db
# Or using psql
psql -U postgres
CREATE DATABASE employees_db;
\q配置
- 创建一个
.env文件 在项目根目录中使用以下变量:
# Google Configuration
GOOGLE_PROJECT_ID=your-google-project-id
GOOGLE_CLOUD_LOCATION=us-central1
MODEL_NAME=gemini-2.5-flash
# REST API base URL for MCP server to call
REST_API_BASE_URL=http://127.0.0.1:8000
# MCP Server URL
MCP_SERVER_URL=http://127.0.0.1:8001/mcp/
# Database configuration
DB_USER=postgres
DB_PASSWORD=your-password
DB_HOST=localhost
DB_PORT=5432
DB_NAME=employees_db- 配置Google Cloud身份验证
# Set up application default credentials
gcloud auth application-default login
# Or set the service account key
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json用法
步骤1:启动REST API服务器
uvicorn main:app --host 0.0.0.0 --port 8000 --reloadAPI将于 http://localhost:8000
- API文件:
http://localhost:8000/docs - OpenAPI架构:
http://localhost:8000/openapi.json
步骤2:启动MCP服务器
在新终端中:
python mcp_server.pyMCP服务器将在 http://localhost:8001
步骤3:运行AI代理客户端
在新终端中:
python ai_agent_client.py与AI Agent交互
代理运行后,您可以使用自然语言查询:
[USER] > Create an employee named John Doe with email john.doe@company.com as a Software Engineer
[USER] > List all employees
[USER] > Find employees with position Software Engineer
[USER] > Get details for employee with ID 1
[USER] > Show me all employees with "Engineer" in their position类型 exit 或 quit 结束会议。
API文档
REST API端点
创建员工
POST /employees/
Content-Type: application/json
{
"name": "John Doe",
"email": "john.doe@company.com",
"position": "Software Engineer"
}列出员工(带过滤器)
GET /employees/?name=John&position=Engineer&limit=10&skip=0按ID获取员工
GET /employees/{employee_id}MCP协议端点
列出可用工具
{
"jsonrpc": "2.0",
"method": "mcp/tool/list",
"params": {},
"id": 1
}调用MCP工具
请求示例 create_employee_record 工具:
{
"jsonrpc": "2.0",
"method": "create_employee_record",
"params": {
"name": "John Doe",
"email": "john.doe@company.com",
"position": "Software Engineer"
},
"id": 1
}MCP协议
MCP(模型上下文协议)层实现了三个主要工具:
1. create_employee_record
将新员工保存到数据库。
参数:
name(string,必填):员工的全名email(字符串,必填):唯一电子邮件地址position(字符串,必填):职位或角色
2. get_employee_details
按ID检索单个员工。
参数:
employee_id(整数,必填):唯一的员工ID
3. list_employees
使用可选筛选器检索员工列表。
参数:
name(字符串,可选):部分名称筛选器email(字符串,可选):部分电子邮件过滤器position(字符串,可选):位置过滤器limit(整数,可选):最大结果(默认值:100)
运作原理
请求流
- 用户输入:用户键入自然语言查询
- AI处理:Gemini解释意图并决定调用哪个工具
- 函数调用:AI生成结构化函数调用
- MCP翻译:MCP服务器接收JSON-RPC请求并转换为REST API调用
- 数据库操作:REST API对PostgreSQL执行CRUD操作
- 响应链:结果通过MCP服务器流回AI代理
- 自然反应:AI将结果格式化为自然语言供用户使用
示例流程
User: "Add Jane Smith as a Data Scientist with email jane@company.com"
↓
Gemini: Calls create_employee_record(name="Jane Smith", email="jane@company.com", position="Data Scientist")
↓
MCP Server: POST http://localhost:8000/employees/ with JSON body
↓
REST API: Inserts record into PostgreSQL
↓
Returns: {"id": 1, "name": "Jane Smith", "email": "jane@company.com", "position": "Data Scientist"}
↓
Gemini: "I've successfully created a new employee record for Jane Smith as a Data Scientist."测试
手动测试-REST API
# Create an employee
curl -X POST "http://localhost:8000/employees/" \
-H "Content-Type: application/json" \
-d '{"name":"Test User","email":"test@example.com","position":"Tester"}'
# List all employees
curl "http://localhost:8000/employees/"
# Get specific employee
curl "http://localhost:8000/employees/1"手动测试-MCP服务器
# List available tools
curl -X POST "http://localhost:8001/mcp/" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/tool/list","params":{},"id":1}'
# Create employee via MCP
curl -X POST "http://localhost:8001/mcp/" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"create_employee_record","params":{"name":"MCP Test","email":"mcp@test.com","position":"Engineer"},"id":1}'对话测试示例
1. "Create an employee with details Carol (carol@co.com, Designer)"
2. "Show me all employees"
3. "Find all developers"
4. "What's the email of employee ID 2?"
5. "List employees whose names start with 'A'"故障排除
谷歌云身份验证问题
问题: DefaultCredentialsError: Could not automatically determine credentials
解决方案:
gcloud auth application-default login
# or
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.jsonMCP服务器连接问题
问题:AI代理无法访问MCP服务器
解决方案:
- 验证MCP服务器是否在端口8001上运行
- 检查
MCP_SERVER_URL在.env与服务器地址匹配 - 确保防火墙允许本地连接
