API查询服务器

一个基于MCP协议的API查询服务器,提供标准化接口以通过stdio和HTTP传输方式与外部API交互。

  • by Omega-me
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 Omega-me/mcp-hackathon

使用说明

MCP API服务器

一个模型上下文协议(MCP)服务器,公开用于查询外部API端点的工具。

概述

此MCP服务器提供了一个标准化的接口,通过MCP协议与外部API进行交互。它支持stdio(用于本地生成进程)和HTTP传输(用于远程访问)。

特性

  • 符合MCP协议:完全支持MCP工具调用
  • 双重运输:支持stdio和HTTP传输
  • 类型安全:在严格模式下使用TypeScript构建
  • 简单配置:基于环境变量的配置
  • 错误处理:清晰、可操作的错误消息

快速开始

先决条件

  • Node.js v22.x或更高版本
  • pnpm包管理器

安装

# Clone the repository
git clone <repository-url>
cd hackathon

# Install dependencies
pnpm install

# Copy environment configuration
cp .env.example .env

# Build the project
pnpm build

运行服务器

标准运输(用于本地工具)

pnpm start:stdio

HTTP传输(用于远程访问)

pnpm start:http

自动检测运输

pnpm start

项目结构

src/
├── features/
│   └── mcp-api-server/       # MCP API server feature
│       ├── transports/        # Transport implementations
│       ├── tools/             # MCP tools
│       ├── services/          # Business logic
│       ├── constants.ts       # Constants and configuration
│       ├── types.ts           # TypeScript interfaces
│       └── server.ts          # MCP server setup
├── shared/                    # Shared utilities
└── index.ts                   # Main entry point

配置

配置是通过环境变量完成的。复制 .env.example 到 .env 并根据需要调整值:

cp .env.example .env

环境变量

变量 默认值 描述
API_BASE_URL http://10.138.80.113:5000 外部API的基本URL
API_TIMEOUT 5000 API请求超时(以毫秒为单位)
TRANSPORT auto 运输类型: stdio, http,或 auto
HTTP_PORT 3000 HTTP传输端口(仅在以下情况下使用 http)
DEBUG false 启用调试日志记录(true 或 false)

运输自动检测

当 TRANSPORT=auto (默认),服务器会自动检测适当的传输:

  • 检测到TTY:使用HTTP传输(端口3000)
  • 无TTY(管道/衍生):使用stdio传输

可用工具

身份验证工具

signup

注册一个新的用户帐户。

参数:

  • email (字符串,必填):用户电子邮件地址
  • password (string,必填):用户密码

示例:

{
  "method": "tools/call",
  "params": {
    "name": "signup",
    "arguments": {
      "email": "user@example.com",
      "password": "SecurePass123!"
    }
  }
}

login

对现有用户进行身份验证。

参数:

  • email (字符串,必填):用户电子邮件地址
  • password (string,必填):用户密码

示例:

{
  "method": "tools/call",
  "params": {
    "name": "login",
    "arguments": {
      "email": "user@example.com",
      "password": "SecurePass123!"
    }
  }
}

get-token

检索当前存储的身份验证令牌。

参数:无

示例:

{
  "method": "tools/call",
  "params": {
    "name": "get-token",
    "arguments": {}
  }
}

组织CRUD工具

一套完整的工具,用于管理具有完整创建、读取、更新、删除操作的组织。

get-all-organizations

检索经过身份验证的用户有权查看的所有组织的列表。

参数:无(未来支持分页/过滤器)

认证:必填(JWT令牌)

示例:

{
  "method": "tools/call",
  "params": {
    "name": "get-all-organizations",
    "arguments": {}
  }
}

成功响应:

{
  "success": true,
  "data": [
    {
      "id": "org-123",
      "name": "Acme Corp",
      "description": "Leading technology company",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    }
  ]
}

create-organization

使用指定的名称和可选的描述创建新组织。

参数:

  • name (字符串,必填):组织名称(1-255个字符)
  • description (字符串,可选):组织描述(最多1000个字符)

认证:必填(JWT令牌)

示例:

{
  "method": "tools/call",
  "params": {
    "name": "create-organization",
    "arguments": {
      "name": "Tech Innovators Inc",
      "description": "Cutting-edge technology solutions"
    }
  }
}

成功响应:

{
  "success": true,
  "data": {
    "id": "org-456",
    "name": "Tech Innovators Inc",
    "description": "Cutting-edge technology solutions",
    "createdAt": "2024-01-20T14:25:00Z",
    "updatedAt": "2024-01-20T14:25:00Z"
  }
}

get-organization

通过特定组织的唯一标识符检索该组织。

参数:

  • id (字符串,必填):组织ID

认证:必填(JWT令牌)

示例:

{
  "method": "tools/call",
  "params": {
    "name": "get-organization",
    "arguments": {
      "id": "org-123"
    }
  }
}

成功响应:

{
  "success": true,
  "data": {
    "id": "org-123",
    "name": "Acme Corp",
    "description": "Leading technology company",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  }
}

错误响应(未找到):

{
  "success": false,
  "error": "Organization not found"
}

update-organization

使用全身替换(PUT语义)更新现有组织。

参数:

  • id (字符串,必填):组织ID
  • name (字符串,必填):组织名称(1-255个字符)
  • description (字符串,可选):组织描述(最多1000个字符)

认证:必填(JWT令牌)

备注:这是一个完整的替换操作-必须提供所有字段。

示例:

{
  "method": "tools/call",
  "params": {
    "name": "update-organization",
    "arguments": {
      "id": "org-123",
      "name": "Acme Corporation",
      "description": "Global leader in technology solutions"
    }
  }
}

成功响应:

{
  "success": true,
  "data": {
    "id": "org-123",
    "name": "Acme Corporation",
    "description": "Global leader in technology solutions",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-20T16:45:00Z"
  }
}

delete-organization

通过组织的唯一标识符永久删除组织。

参数:

  • id (字符串,必填):组织ID

认证:必填(JWT令牌)

警告:此操作是不可逆的。无法删除具有依赖关系的组织。

示例:

{
  "method": "tools/call",
  "params": {
    "name": "delete-organization",
    "arguments": {
      "id": "org-789"
    }
  }
}

成功响应:

{
  "success": true,
  "message": "Organization with ID 'org-789' has been successfully deleted."
}

错误响应(具有相关性):

{
  "success": false,
  "error": "Cannot delete organization with existing dependencies"
}

演示工具

hello

查询 /api/hello 端点并返回API响应。

参数:无

示例请求 (MCP检查员或客户):

{
  "method": "tools/call",
  "params": {
    "name": "hello",
    "arguments": {}
  }
}

示例响应:

{
  "content": [
    {
      "type": "text",
      "text": "{\n  \"message\": \"Hello from API\"\n}"
    }
  ]
}

测试

MCP检验员测试

安装MCP检查器:

npm install -g @modelcontextprotocol/inspector

使用stdio传输测试服务器:

pnpm build
mcp-inspector node dist/stdio-entry.js

使用HTTP传输进行测试

启动HTTP服务器:

pnpm start:http

卷曲测试:

# Health check
curl http://localhost:3000/health

# Call the hello tool
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "hello",
      "arguments": {}
    }
  }'

错误处理

服务器为常见场景提供清晰的错误消息:

  • TIMEOUT:API请求超出超时限制
  • NETWORK_ERROR:无法连接到API或DNS解析失败
  • API_ERROR:API返回错误状态(4xx/5xx)
  • INTERNAL_ERROR:意外的服务器错误

错误响应示例:

{
  "content": [
    {
      "type": "text",
      "text": "Error: Request timed out after 5000ms. The API did not respond in time."
    }
  ],
  "isError": true
}

故障排除

API连接问题

如果你看到 NETWORK_ERROR:

  1. 验证API是否正在运行并可访问
  2. 检查 API_BASE_URL 在你的 .env 文件
  3. 确保与API服务器的网络连接

超时问题

如果你看到 TIMEOUT 错误:

  1. 检查API是否响应缓慢
  2. 增加 API_TIMEOUT 在 .env (默认值:5000ms)
  3. 验证API终结点是否正确

构建错误

# Clean build
rm -rf dist/
pnpm build

发展

按照项目章程建造:

  • ✅ 雅格尼 -只建造需要的东西
  • ✅ 基于特征的体系结构 -按功能组织
  • ✅ TypeScript+Node.js+pnpm -现代堆栈
  • ✅ 坚实的原则 -干净的建筑
  • ✅ 常量模式 -集中配置
  • ✅ 保持简单 -保持简单

添加新工具

  1. 在中创建工具实现 src/features/mcp-api-server/tools/
  2. 定义工具元数据(名称、描述、模式)
  3. 在中注册工具 src/features/mcp-api-server/server.ts
  4. 重建: pnpm build

部署

生产的先决条件

  • 目标服务器上已安装Node.js v22.x LTS
  • pnpm包管理器
  • 对外部API端点的网络访问
  • 已配置环境变量

部署步骤

  1. 构建项目:

    pnpm install
    pnpm build
    
  2. 配置环境:

    # Create production .env file
    cp .env.example .env
    
    # Edit .env with production values
    nano .env
    
  3. 与流程管理器一起运行 (推荐):

    使用PM2:

    npm install -g pm2
    
    # For stdio transport
    pm2 start dist/stdio-entry.js --name mcp-api-server-stdio
    
    # For HTTP transport
    pm2 start dist/http-entry.js --name mcp-api-server-http --env production
    
    # Save configuration
    pm2 save
    pm2 startup
    
  4. 验证部署:

    # Check logs
    pm2 logs mcp-api-server-http
    
    # Check status
    pm2 status
    
    # Test health endpoint (HTTP transport)
    curl http://localhost:3000/health
    

Docker部署(可选)

创建 Dockerfile:

FROM node:22-alpine

WORKDIR /app

# Install pnpm
RUN npm install -g pnpm

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install dependencies
RUN pnpm install --frozen-lockfile --prod

# Copy source and build
COPY . .
RUN pnpm build

# Expose HTTP port
EXPOSE 3000

# Run HTTP transport by default
CMD ["node", "dist/http-entry.js"]

构建并运行:

docker build -t mcp-api-server .
docker run -d \
  --name mcp-api-server \
  -p 3000:3000 \
  -e API_BASE_URL=http://10.138.80.113:5000 \
  -e TRANSPORT=http \
  mcp-api-server

监控

监控生产中的应用程序:

# With PM2
pm2 monit

# View logs
pm2 logs --lines 100

# Restart if needed
pm2 restart mcp-api-server-http

健康检查

对于HTTP传输,请使用 /health 端点:

curl http://localhost:3000/health

预期响应:

{
  "status": "healthy",
  "transport": "http"
}

安全考虑

  1. 环境变量:从不承诺 .env 文件到版本控制
  2. 网络安全:限制API访问受信任的网络
  3. 速率限制:考虑为HTTP传输添加速率限制
  4. 超文本传输安全协议:在生产环境中使用HTTPS反向代理(nginx、caddy)

nginx配置示例:

server {
    listen 443 ssl;
    server_name mcp-api.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

许可证

ISC