mirror of
https://github.com/samanhappy/mcphub.git
synced 2025-12-24 02:39:19 -05:00
718 lines
12 KiB
Plaintext
718 lines
12 KiB
Plaintext
---
|
||
title: 'API 参考'
|
||
description: 'MCPHub REST API 完整参考文档'
|
||
---
|
||
|
||
## 概述
|
||
|
||
MCPHub 提供全面的 REST API,用于管理 MCP 服务器、用户、组和监控。所有 API 端点都需要身份验证,并支持 JSON 格式的请求和响应。
|
||
|
||
## 基础信息
|
||
|
||
### 基础 URL
|
||
|
||
```
|
||
https://your-mcphub-instance.com/api
|
||
```
|
||
|
||
### 身份验证
|
||
|
||
所有 API 请求都需要身份验证。支持以下方法:
|
||
|
||
#### JWT 令牌认证
|
||
|
||
```bash
|
||
curl -X GET https://api.mcphub.com/servers \
|
||
-H "Authorization: Bearer YOUR_JWT_TOKEN"
|
||
```
|
||
|
||
#### API 密钥认证
|
||
|
||
```bash
|
||
curl -X GET https://api.mcphub.com/servers \
|
||
-H "X-API-Key: YOUR_API_KEY"
|
||
```
|
||
|
||
### 请求格式
|
||
|
||
- **Content-Type**: `application/json`
|
||
- **Accept**: `application/json`
|
||
- **User-Agent**: 建议包含您的应用程序名称和版本
|
||
|
||
### 响应格式
|
||
|
||
所有响应都采用 JSON 格式:
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"data": {
|
||
// 响应数据
|
||
},
|
||
"message": "操作成功",
|
||
"timestamp": "2024-01-01T12:00:00Z"
|
||
}
|
||
```
|
||
|
||
错误响应格式:
|
||
|
||
```json
|
||
{
|
||
"success": false,
|
||
"error": {
|
||
"code": "VALIDATION_ERROR",
|
||
"message": "请求数据无效",
|
||
"details": {
|
||
"field": "name",
|
||
"reason": "名称不能为空"
|
||
}
|
||
},
|
||
"timestamp": "2024-01-01T12:00:00Z"
|
||
}
|
||
```
|
||
|
||
## 状态码
|
||
|
||
| 状态码 | 说明 |
|
||
| ------ | -------------------- |
|
||
| 200 | 请求成功 |
|
||
| 201 | 资源创建成功 |
|
||
| 204 | 请求成功,无返回内容 |
|
||
| 400 | 请求参数错误 |
|
||
| 401 | 未授权访问 |
|
||
| 403 | 权限不足 |
|
||
| 404 | 资源不存在 |
|
||
| 409 | 资源冲突 |
|
||
| 422 | 请求数据验证失败 |
|
||
| 429 | 请求频率超限 |
|
||
| 500 | 服务器内部错误 |
|
||
|
||
## 分页
|
||
|
||
支持分页的端点使用以下参数:
|
||
|
||
- `page`: 页码(从 1 开始)
|
||
- `limit`: 每页记录数(默认 20,最大 100)
|
||
- `sort`: 排序字段
|
||
- `order`: 排序顺序(`asc` 或 `desc`)
|
||
|
||
```bash
|
||
curl -X GET "https://api.mcphub.com/servers?page=2&limit=50&sort=name&order=asc" \
|
||
-H "Authorization: Bearer $TOKEN"
|
||
```
|
||
|
||
分页响应格式:
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"data": {
|
||
"items": [...],
|
||
"pagination": {
|
||
"page": 2,
|
||
"limit": 50,
|
||
"total": 234,
|
||
"pages": 5,
|
||
"hasNext": true,
|
||
"hasPrev": true
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
## 过滤和搜索
|
||
|
||
支持过滤的端点可以使用以下参数:
|
||
|
||
- `search`: 全文搜索
|
||
- `filter[field]`: 字段过滤
|
||
- `status`: 状态过滤
|
||
- `created_after`: 创建时间筛选
|
||
- `created_before`: 创建时间筛选
|
||
|
||
```bash
|
||
curl -X GET "https://api.mcphub.com/servers?search=python&filter[status]=running&created_after=2024-01-01" \
|
||
-H "Authorization: Bearer $TOKEN"
|
||
```
|
||
|
||
## API 端点
|
||
|
||
### 服务器管理
|
||
|
||
#### 获取服务器列表
|
||
|
||
```http
|
||
GET /api/servers
|
||
```
|
||
|
||
参数:
|
||
|
||
- `status` (可选): 过滤服务器状态 (`running`, `stopped`, `error`)
|
||
- `group` (可选): 过滤所属组
|
||
- `search` (可选): 搜索服务器名称或描述
|
||
|
||
示例响应:
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"data": {
|
||
"items": [
|
||
{
|
||
"id": "server-1",
|
||
"name": "文件系统服务器",
|
||
"status": "running",
|
||
"command": "npx",
|
||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"],
|
||
"env": {
|
||
"NODE_ENV": "production"
|
||
},
|
||
"cwd": "/app",
|
||
"pid": 12345,
|
||
"uptime": 3600000,
|
||
"lastRestart": "2024-01-01T12:00:00Z",
|
||
"createdAt": "2024-01-01T10:00:00Z",
|
||
"updatedAt": "2024-01-01T12:00:00Z"
|
||
}
|
||
]
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 创建服务器
|
||
|
||
```http
|
||
POST /api/servers
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"name": "新服务器",
|
||
"command": "python",
|
||
"args": ["-m", "mcp_server"],
|
||
"env": {
|
||
"API_KEY": "your-api-key",
|
||
"LOG_LEVEL": "INFO"
|
||
},
|
||
"cwd": "/app/python-server",
|
||
"enabled": true,
|
||
"description": "Python MCP 服务器",
|
||
"tags": ["python", "production"]
|
||
}
|
||
```
|
||
|
||
#### 获取服务器详情
|
||
|
||
```http
|
||
GET /api/servers/{serverId}
|
||
```
|
||
|
||
#### 更新服务器
|
||
|
||
```http
|
||
PUT /api/servers/{serverId}
|
||
```
|
||
|
||
#### 删除服务器
|
||
|
||
```http
|
||
DELETE /api/servers/{serverId}
|
||
```
|
||
|
||
#### 启动服务器
|
||
|
||
```http
|
||
POST /api/servers/{serverId}/start
|
||
```
|
||
|
||
#### 停止服务器
|
||
|
||
```http
|
||
POST /api/servers/{serverId}/stop
|
||
```
|
||
|
||
请求体(可选):
|
||
|
||
```json
|
||
{
|
||
"graceful": true,
|
||
"timeout": 30000
|
||
}
|
||
```
|
||
|
||
#### 重启服务器
|
||
|
||
```http
|
||
POST /api/servers/{serverId}/restart
|
||
```
|
||
|
||
#### 获取服务器日志
|
||
|
||
```http
|
||
GET /api/servers/{serverId}/logs
|
||
```
|
||
|
||
参数:
|
||
|
||
- `level` (可选): 日志级别过滤
|
||
- `limit` (可选): 返回日志条数
|
||
- `since` (可选): 开始时间
|
||
- `follow` (可选): 实时跟踪日志
|
||
|
||
### 用户管理
|
||
|
||
#### 获取用户列表
|
||
|
||
```http
|
||
GET /api/users
|
||
```
|
||
|
||
#### 创建用户
|
||
|
||
```http
|
||
POST /api/users
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"username": "newuser",
|
||
"email": "user@example.com",
|
||
"password": "securepassword",
|
||
"role": "user",
|
||
"groups": ["dev-team"],
|
||
"profile": {
|
||
"firstName": "张",
|
||
"lastName": "三",
|
||
"department": "开发部"
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 获取用户详情
|
||
|
||
```http
|
||
GET /api/users/{userId}
|
||
```
|
||
|
||
#### 更新用户
|
||
|
||
```http
|
||
PUT /api/users/{userId}
|
||
```
|
||
|
||
#### 删除用户
|
||
|
||
```http
|
||
DELETE /api/users/{userId}
|
||
```
|
||
|
||
### 组管理
|
||
|
||
#### 获取组列表
|
||
|
||
```http
|
||
GET /api/groups
|
||
```
|
||
|
||
#### 创建组
|
||
|
||
```http
|
||
POST /api/groups
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"name": "dev-team",
|
||
"displayName": "开发团队",
|
||
"description": "前端和后端开发人员",
|
||
"parentGroup": null,
|
||
"permissions": {
|
||
"servers": ["read", "write", "execute"],
|
||
"tools": ["read", "execute"]
|
||
},
|
||
"settings": {
|
||
"autoAssign": false,
|
||
"maxMembers": 50,
|
||
"requireApproval": true
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 添加用户到组
|
||
|
||
```http
|
||
POST /api/groups/{groupId}/members
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"userId": "user123",
|
||
"role": "member"
|
||
}
|
||
```
|
||
|
||
#### 从组中移除用户
|
||
|
||
```http
|
||
DELETE /api/groups/{groupId}/members/{userId}
|
||
```
|
||
|
||
#### 分配服务器到组
|
||
|
||
```http
|
||
POST /api/groups/{groupId}/servers
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"serverId": "server-1",
|
||
"permissions": ["read", "write", "execute"]
|
||
}
|
||
```
|
||
|
||
### 身份验证
|
||
|
||
#### 登录
|
||
|
||
```http
|
||
POST /api/auth/login
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"username": "admin",
|
||
"password": "password",
|
||
"mfaCode": "123456"
|
||
}
|
||
```
|
||
|
||
响应:
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"data": {
|
||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||
"refreshToken": "refresh_token_here",
|
||
"expiresIn": 86400,
|
||
"user": {
|
||
"id": "user123",
|
||
"username": "admin",
|
||
"role": "admin",
|
||
"permissions": ["*"]
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 刷新令牌
|
||
|
||
```http
|
||
POST /api/auth/refresh
|
||
```
|
||
|
||
#### 注销
|
||
|
||
```http
|
||
POST /api/auth/logout
|
||
```
|
||
|
||
#### 验证令牌
|
||
|
||
```http
|
||
GET /api/auth/verify
|
||
```
|
||
|
||
### 监控
|
||
|
||
#### 获取系统状态
|
||
|
||
```http
|
||
GET /api/monitoring/status
|
||
```
|
||
|
||
响应:
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"data": {
|
||
"system": {
|
||
"uptime": 86400,
|
||
"version": "2.1.0",
|
||
"nodeVersion": "18.17.0"
|
||
},
|
||
"servers": {
|
||
"total": 12,
|
||
"running": 10,
|
||
"stopped": 1,
|
||
"error": 1
|
||
},
|
||
"performance": {
|
||
"requestsPerMinute": 85,
|
||
"avgResponseTime": "245ms",
|
||
"errorRate": "0.3%"
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 获取性能指标
|
||
|
||
```http
|
||
GET /api/monitoring/metrics
|
||
```
|
||
|
||
参数:
|
||
|
||
- `timeRange`: 时间范围 (`1h`, `24h`, `7d`, `30d`)
|
||
- `granularity`: 数据粒度 (`1m`, `5m`, `1h`, `1d`)
|
||
- `metrics`: 指定指标名称(逗号分隔)
|
||
|
||
#### 获取日志
|
||
|
||
```http
|
||
GET /api/monitoring/logs
|
||
```
|
||
|
||
参数:
|
||
|
||
- `level`: 日志级别
|
||
- `source`: 日志源
|
||
- `limit`: 返回条数
|
||
- `since`: 开始时间
|
||
- `until`: 结束时间
|
||
|
||
### 配置管理
|
||
|
||
#### 获取系统配置
|
||
|
||
```http
|
||
GET /api/config
|
||
```
|
||
|
||
#### 更新系统配置
|
||
|
||
```http
|
||
PUT /api/config
|
||
```
|
||
|
||
请求体:
|
||
|
||
```json
|
||
{
|
||
"smtp": {
|
||
"host": "smtp.example.com",
|
||
"port": 587,
|
||
"secure": false,
|
||
"auth": {
|
||
"user": "noreply@example.com",
|
||
"pass": "password"
|
||
}
|
||
},
|
||
"notifications": {
|
||
"email": true,
|
||
"slack": true,
|
||
"webhook": "https://hooks.example.com/notifications"
|
||
}
|
||
}
|
||
```
|
||
|
||
## WebSocket API
|
||
|
||
MCPHub 支持 WebSocket 连接以获取实时更新。
|
||
|
||
### 连接
|
||
|
||
```javascript
|
||
const ws = new WebSocket('wss://api.mcphub.com/ws');
|
||
ws.onopen = function () {
|
||
// 发送认证消息
|
||
ws.send(
|
||
JSON.stringify({
|
||
type: 'auth',
|
||
token: 'YOUR_JWT_TOKEN',
|
||
}),
|
||
);
|
||
};
|
||
```
|
||
|
||
### 订阅事件
|
||
|
||
```javascript
|
||
// 订阅服务器状态更新
|
||
ws.send(
|
||
JSON.stringify({
|
||
type: 'subscribe',
|
||
channel: 'server-status',
|
||
filters: {
|
||
serverId: 'server-1',
|
||
},
|
||
}),
|
||
);
|
||
|
||
// 订阅系统监控
|
||
ws.send(
|
||
JSON.stringify({
|
||
type: 'subscribe',
|
||
channel: 'monitoring',
|
||
metrics: ['cpu', 'memory', 'requests'],
|
||
}),
|
||
);
|
||
```
|
||
|
||
### 事件类型
|
||
|
||
- `server-status`: 服务器状态变化
|
||
- `server-logs`: 实时日志流
|
||
- `monitoring`: 系统监控指标
|
||
- `alerts`: 系统警报
|
||
- `user-activity`: 用户活动事件
|
||
|
||
## 错误处理
|
||
|
||
### 错误代码
|
||
|
||
| 错误代码 | 描述 |
|
||
| ----------------------- | -------------- |
|
||
| `INVALID_REQUEST` | 请求格式无效 |
|
||
| `AUTHENTICATION_FAILED` | 身份验证失败 |
|
||
| `AUTHORIZATION_FAILED` | 权限不足 |
|
||
| `RESOURCE_NOT_FOUND` | 资源不存在 |
|
||
| `RESOURCE_CONFLICT` | 资源冲突 |
|
||
| `VALIDATION_ERROR` | 数据验证失败 |
|
||
| `RATE_LIMIT_EXCEEDED` | 请求频率超限 |
|
||
| `SERVER_ERROR` | 服务器内部错误 |
|
||
|
||
### 错误处理示例
|
||
|
||
```javascript
|
||
async function handleApiRequest() {
|
||
try {
|
||
const response = await fetch('/api/servers', {
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
|
||
const data = await response.json();
|
||
|
||
if (!data.success) {
|
||
switch (data.error.code) {
|
||
case 'AUTHENTICATION_FAILED':
|
||
// 重新登录
|
||
redirectToLogin();
|
||
break;
|
||
case 'RATE_LIMIT_EXCEEDED':
|
||
// 延迟重试
|
||
setTimeout(() => handleApiRequest(), 5000);
|
||
break;
|
||
default:
|
||
// 显示错误消息
|
||
showError(data.error.message);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 处理成功响应
|
||
handleSuccessResponse(data.data);
|
||
} catch (error) {
|
||
// 处理网络错误
|
||
console.error('网络请求失败:', error);
|
||
}
|
||
}
|
||
```
|
||
|
||
## 速率限制
|
||
|
||
API 实施速率限制以防止滥用:
|
||
|
||
- **默认限制**: 每分钟 100 请求
|
||
- **认证用户**: 每分钟 1000 请求
|
||
- **管理员**: 每分钟 5000 请求
|
||
|
||
响应头包含速率限制信息:
|
||
|
||
```
|
||
X-RateLimit-Limit: 1000
|
||
X-RateLimit-Remaining: 999
|
||
X-RateLimit-Reset: 1609459200
|
||
```
|
||
|
||
## SDK 和客户端库
|
||
|
||
### JavaScript/Node.js
|
||
|
||
```bash
|
||
npm install @mcphub/sdk
|
||
```
|
||
|
||
```javascript
|
||
import { MCPHubClient } from '@mcphub/sdk';
|
||
|
||
const client = new MCPHubClient({
|
||
baseURL: 'https://api.mcphub.com',
|
||
token: 'YOUR_JWT_TOKEN',
|
||
});
|
||
|
||
// 获取服务器列表
|
||
const servers = await client.servers.list();
|
||
|
||
// 创建服务器
|
||
const newServer = await client.servers.create({
|
||
name: '新服务器',
|
||
command: 'python',
|
||
args: ['-m', 'mcp_server'],
|
||
});
|
||
```
|
||
|
||
### Python
|
||
|
||
```bash
|
||
pip install mcphub-sdk
|
||
```
|
||
|
||
```python
|
||
from mcphub_sdk import MCPHubClient
|
||
|
||
client = MCPHubClient(
|
||
base_url='https://api.mcphub.com',
|
||
token='YOUR_JWT_TOKEN'
|
||
)
|
||
|
||
# 获取服务器列表
|
||
servers = client.servers.list()
|
||
|
||
# 创建服务器
|
||
new_server = client.servers.create(
|
||
name='新服务器',
|
||
command='python',
|
||
args=['-m', 'mcp_server']
|
||
)
|
||
```
|
||
|
||
## 最佳实践
|
||
|
||
1. **使用 HTTPS**: 始终通过 HTTPS 访问 API
|
||
2. **安全存储令牌**: 不要在客户端代码中硬编码令牌
|
||
3. **处理错误**: 实施适当的错误处理和重试逻辑
|
||
4. **遵守速率限制**: 监控速率限制并实施退避策略
|
||
5. **使用分页**: 对于大数据集使用分页参数
|
||
6. **缓存响应**: 适当缓存 API 响应以减少请求
|
||
7. **版本控制**: 使用 API 版本号以确保兼容性
|
||
|
||
有关更多信息,请参阅我们的 [SDK 文档](https://docs.mcphub.com/sdk) 和 [示例代码](https://github.com/mcphub/examples)。
|