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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
---
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)。