MCP任务服务器
一个生产就绪的模型上下文协议(MCP)服务器,使AI代理能够与任务管理PostgreSQL数据库交互,进行模式检查、批量数据插入和统计检索。
🎯 特性
- 7 MCP工具:架构检查、批量插入、文件导入、任务列表、统计信息、作业状态、帮助
- 3个MCP提示:用于任务创建、状态摘要和报告生成的可重用提示模板(
prompts/list+prompts/get) - 1 MCP资源:实时任务数据可作为MCP资源访问(
resources/list+resources/read) - 双重运输支持:STDIO(本地)和HTTP/SSE(远程)传输
- STDIO传输:JSON-RPC 2.0通过stdin/stdout用于本地AI代理(默认) - HTTP传输:带有JSON-RPC 2.0的REST API,用于远程访问 - SSE通知:服务器发送实时作业进度更新事件
- 灵活部署:以STDIO模式、HTTP模式或两者同时运行
- 高性能:通过优化的批插入,每秒约2000个任务
- 生产就绪:API密钥认证(HTTP)、全面测试、审核日志记录、速率限制
- 可观测性:带审计跟踪的结构化日志记录、MDC上下文传播、SSE事件流
- 分页:基于偏移量的任务列表分页,带过滤功能
📊 生产准备状态:98/100✅
| 类别 | 得分 | 状态 | 亮点 |
|---|---|---|---|
| 建筑 | 98/100 | ✅ 优秀 | 干净的层、MCP SDK、自动模式生成 |
| 安全 | 98/100 | ✅ 生产就绪 | 速率限制、环境变量、STDIO隔离、审计日志 |
| 性能 | 95/100 | ✅ 优化 | 约2000个任务/秒,批插入,连接池 |
| 测试 | 95/100 | ✅ 全面 | 188个测试,80%覆盖率,测试容器,Jacoco |
| 操作 | 98/100 | ✅ 可观察 | CI/CD、Docker、结构化日志、指标 |
🚀 快速开始
先决条件
- Java 21
- Podman(用于PostgreSQL容器)
- Maven 3.8+
1.配置环境变量
选项A:使用.env文件(建议用于开发)
# Copy template
cp .env.example .env
# Edit .env and set secure values
# IMPORTANT: Never commit .env to git!
vi .env选项B:手动导出(备选)
export DB_PASSWORD=$(openssl rand -base64 32) # Secure random password
export DB_HOST=localhost
export DB_PORT=5432
export DB_NAME=taskdb
export DB_USER=taskuser2.启动PostgreSQL
# Automatically uses .env file if present
podman-compose up -d
# Or with explicit env file
podman-compose --env-file .env up -d3.建造
./mvnw clean package -DskipTests4.跑步
选项A:在本地运行(开发)
java -jar target/mcp-task-server-1.0.0-SNAPSHOT.jar选项B:使用Docker Compose运行(生产)
# Build and start both PostgreSQL and application
podman-compose up --build
# Or in detached mode
podman-compose up -d --build
# View logs
podman-compose logs -f app
# Stop services
podman-compose down5.验证
服务器在STDIO模式下运行,并通过stdin/stdout进行通信。使用MCP客户端(如Claude Desktop)与工具进行交互。对于测试,您可以使用 start-mcp-server.sh 以正确模式启动服务器的脚本。
______________________________________________________________________
🌐 HTTP传输模式
MCP服务器还可以使用HTTP/SSE传输进行远程访问。
配置
通过环境变量设置运输模式:
# STDIO only (default)
export MCP_TRANSPORT=stdio
# HTTP only
export MCP_TRANSPORT=http
export MCP_API_KEY=your-secure-api-key-here
# Both transports simultaneously
export MCP_TRANSPORT=both
export MCP_API_KEY=your-secure-api-key-here在HTTP模式下运行
# Set environment variables
export MCP_TRANSPORT=http
export MCP_API_KEY=$(openssl rand -base64 32)
export MCP_HTTP_PORT=8070
export DB_PASSWORD=your-db-password
# Run the server
java -jar target/mcp-task-server-1.0.0-SNAPSHOT.jar服务器将于启动 http://localhost:8070.
HTTP端点
| 端点 | 方法 | 描述 |
|---|---|---|
/mcp | POST | JSON-RPC 2.0消息(工具、资源、提示) |
/mcp | GET | SSE流用于实时服务器通知 |
/mcp | DELETE | 关闭活动会话 |
/mcp/health | GET | 健康检查——无需身份验证;活跃于 http 和 both 模式 |
JSON-RPC 2.0 API
所有工具和资源操作都使用JSON-RPC 2.0协议。
列出工具
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}'调用工具
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "mcp-tasks-summary",
"arguments": {}
}
}'列出资源
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "resources/list"
}'阅读资源
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "resources/read",
"params": {
"uri": "task://123"
}
}'JSON-RPC 2.0合规功能
服务器实现 完整的JSON-RPC 2.0规范 顺从:
批量请求
在单个HTTP调用中发送多个请求:
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '[
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
{"jsonrpc": "2.0", "id": 2, "method": "resources/list"},
{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "mcp-tasks-summary", "arguments": {}}}
]'答复:
[
{"jsonrpc": "2.0", "id": 1, "result": {"tools": [...]}},
{"jsonrpc": "2.0", "id": 2, "result": {"resourceTemplates": [...]}},
{"jsonrpc": "2.0", "id": 3, "result": {"content": [...], "isError": false}}
]通知
无请求 id 字段是通知,没有收到响应:
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"method": "tools/list"
}'
# Returns: 204 No ContentID类型
符合JSON-RPC 2.0规范的有效ID类型:
- 字符串:
"id": "request-123" - 数字:
"id": 42 - 空值:
"id": null
无效(将返回错误-32600):
- 数组:
"id": [1,2,3] - 对象:
"id": {"foo": "bar"} - 布尔值:
"id": true
错误代码
标准JSON-RPC 2.0错误代码:
| 代码 | 消息 | 描述 |
|---|---|---|
| -32700 | 分析错误 | JSON无效 |
| -32600 | 无效请求 | 缺少/无效字段 |
| -32601 | 找不到方法 | 未知方法或保留方法 rpc.* 前缀 |
| -32602 | 参数无效 | 方法参数无效 |
| -32603 | 内部错误 | 服务器端错误 |
| -32000 | 服务器错误 | 特定于应用程序的错误 |
保留方法
方法开始于 rpc. 根据规范保留,将返回错误-32601:
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "rpc.internal"
}'
# Returns: {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found: rpc.internal (reserved prefix)"}}服务器发送事件(SSE)
订阅实时作业进度更新:
curl -N -H "X-API-Key: your-api-key" http://localhost:8070/mcp事件类型:
connected-已建立连接job-progress-异步批处理作业进度更新job-completed-批处理作业已成功完成job-failed-批处理作业失败heartbeat-保持活力(每30秒)
SSE事件示例:
event: job-progress
id: evt_a1b2c3d4
data: {
"jobId": "550e8400-e29b-41d4-a716-446655440000",
"status": "RUNNING",
"totalTasks": 1000,
"processedTasks": 500,
"progressPercent": 50,
"message": "Processing batch 500/1000",
"timestamp": "2026-02-16T10:30:00Z"
}安全
- API密钥验证:除以下端点外,所有端点都需要
/mcp/health - 头球:
X-API-Key: your-api-key - 跨域资源共享:默认启用(可通过配置
mcp.transport.http.cors-allowed-origins) - 速率限制:按工具应用(与STDIO模式相同)
配置选项
增添 application.yml 或使用环境变量:
mcp:
transport:
mode: ${MCP_TRANSPORT:stdio} # stdio, http, or both
http:
port: ${MCP_HTTP_PORT:8070}
cors-enabled: true
cors-allowed-origins: [] # Empty = allow all
sse:
heartbeat-interval-seconds: 30
connection-timeout-minutes: 5
max-connections: 100
security:
api-keys:
- name: "default"
key: ${MCP_API_KEY:}
description: "API key for HTTP transport"______________________________________________________________________
💬 MCP提示
服务器通过以下方式公开了三个可重用的提示模板 prompts/list 和 prompts/get:
| 提示名称 | 描述 | 参数 | |
|---|---|---|---|
create-tasks-from-description | 根据自然语言描述生成结构化任务列表 | description (必填) | |
summarize-tasks-by-status | 返回按状态分组的任务的实时摘要 | status (可选过滤器) | |
task-report-template | 生成格式化的任务报告模板 | format: brief | detailed (可选) |
示例-- prompts/get:
curl -X POST http://localhost:8070/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"jsonrpc": "2.0",
"id": 5,
"method": "prompts/get",
"params": {
"name": "summarize-tasks-by-status",
"arguments": { "status": "TODO" }
}
}'______________________________________________________________________
🛠️ MCP工具
1.mcp模式任务
返回Task对象的JSON模式。
用途:
{}答复:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Task",
"type": "object",
"properties": {
"title": {"type": "string", "maxLength": 255},
"description": {"type": "string", "maxLength": 2000},
"status": {"type": "string", "enum": ["TODO", "IN_PROGRESS", "DONE"]},
"dueDate": {"type": "string", "format": "date"}
},
"required": ["title", "status"]
}2.mcp任务
批量插入任务(每批最多5000个)。
用途:
{
"tasks": [
{
"title": "Complete documentation",
"description": "Write comprehensive README",
"status": "TODO",
"dueDate": "2025-03-15"
}
]
}答复:
{
"success": true,
"insertedCount": 1,
"durationMs": 45,
"tasksPerSecond": 22
}3.mcp任务总结
获取任务统计信息。
用途:
{}答复:
{
"totalCount": 1000,
"countByStatus": {
"TODO": 400,
"IN_PROGRESS": 300,
"DONE": 300
},
"earliestDueDate": "2025-01-15",
"latestDueDate": "2025-12-31",
"generatedAt": "2025-02-12T22:30:00"
}4.mcp任务列表
使用可选筛选检索分页任务列表。
用途:
{
"page": 0,
"pageSize": 100,
"status": "TODO"
}参数:
page(可选):页码,从0开始(默认值:0)pageSize(可选):每页项目数,1-1000(默认值:100)status(可选):按状态筛选-“TODO”、“IN_PROGRESS”或“DONE”
答复:
{
"tasks": [
{
"id": 1,
"title": "Complete documentation",
"description": "Write comprehensive README",
"status": "TODO",
"dueDate": "2025-03-15",
"createdAt": "2025-02-15T10:30:00",
"updatedAt": "2025-02-15T10:30:00"
}
],
"total": 150,
"page": 0,
"pageSize": 100,
"totalPages": 2
}使用案例:
- 使用分页浏览现有任务
- 按状态筛选任务以进行工作流管理
- 检索任务详细信息,包括更新的ID
- 审核任务创建时间戳
分页说明:
- 使用基于偏移量的分页(page/pageSize)
- 默认情况下按ID升序排列的结果
- 对于非常大的数据集(>10万个任务),考虑基于光标的分页(请参阅配置部分)
5.mcp帮助
获取工具文档。
用途:
{}6.文件中的mcp任务
从JSON文件导入任务——绕过大批量(最多5000个任务)的令牌限制。
用途:
{
"filePath": "tasks/tasks_1000.json"
}答复:
{
"success": true,
"jobId": "550e8400-e29b-41d4-a716-446655440000",
"status": "PENDING",
"totalTasks": 1000,
"message": "Batch job started asynchronously"
}使用 mcp-job-status 与返回 jobId 以监控进展。
7.mcp作业状态
检查异步批处理作业的状态(由返回 mcp-tasks 或 mcp-tasks-from-file).
用途:
{
"jobId": "550e8400-e29b-41d4-a716-446655440000"
}答复:
{
"jobId": "550e8400-e29b-41d4-a716-446655440000",
"status": "COMPLETED",
"totalTasks": 1000,
"processedTasks": 1000,
"progressPercent": 100,
"durationMs": 512,
"tasksPerSecond": 1953,
"errorMessage": null,
"createdAt": "2026-02-16T10:30:00",
"completedAt": "2026-02-16T10:30:00.512"
}作业状态: PENDING → RUNNING → COMPLETED / FAILED
🧪 测试
运行所有测试
./mvnw test运行特定测试
./mvnw test -Dtest=PerformanceIntegrationTest测试覆盖率
使用JaCoCo生成覆盖率报告:
./mvnw test # Run tests with coverage
./mvnw jacoco:report # Generate HTML report
./mvnw jacoco:check # Verify 80% threshold
# View report
open target/site/jacoco/index.html测试套件:
- 12个集成测试课程
- 15个单元测试类
- 总共188次测试 --全绿
- PostgreSQL的测试容器
- 性能测试(1000个任务\100000
- 分页过程中频繁并发写入
- 具有无限滚动功能的移动应用程序
游标实现示例:
# Future enhancement - not currently implemented
{
"cursor": "base64EncodedCursor", # Last item's ID + timestamp
"limit": 100,
"status": "TODO"
}目前,基于偏移量的分页对于大多数用例来说已经足够了。监控性能 mcp-tasks-summary 以确定是否需要迁移到基于光标的分页。
📚 建筑
[AI Agent] ↔ [STDIO Transport] ↔ [MCP Server (Spring Boot)] ↔ [PostgreSQL DB]层:
- STDIO传输 -JSON-RPC 2.0通过标准输入/标准输出(MCP兼容)
- MCP工具 -带有审计日志的工具实现
- 服务 -业务逻辑和批量优化
- 仓库 -Spring数据JPA
- 模型 -具有SEQUENCE优化的JPA实体
- 审计 -结构化审计日志记录到单独的文件
🎯 AI代理提示示例
Please inspect the task schema using mcp-schema-tasks.
Then generate and insert 1000 diverse tasks with:
- Random statuses (TODO, IN_PROGRESS, DONE)
- Varied titles and descriptions
- Due dates spread across next 90 days
Submit them via mcp-tasks endpoint.
Verify success using mcp-tasks-summary.📝 许可证
该项目根据MIT许可证获得许可。
📊 代码覆盖率
该项目使用JaCoCo进行代码覆盖率报告,行覆盖率阈值为80%。
生成覆盖率报告:
./mvnw clean test jacoco:report查看报告:
open target/site/jacoco/index.html检查覆盖阈值:
./mvnw jacoco:check覆盖率报告在CI/CD构建过程中自动生成,可以上传到Codecov。
🤝 贡献
欢迎投稿!请确保:
- 所有测试均通过(
./mvnw test) - 代码覆盖率达到80%阈值(
./mvnw jacoco:check) - 代码遵循现有模式
- 已解决的安全问题
📞 支持
对于问题或疑问:
- 在存储库中创建问题
- 检查现有文档
- 查看使用示例的测试用例
______________________________________________________________________
MCP规范版本: 2025-06-18\ Spring Boot版本: 3.3.5\ Java版本: 21
