File size: 16,430 Bytes
eb846d0 |
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 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 |
---
title: '代码块'
description: 'MCPHub 文档中代码块的编写和展示指南'
---
## 内联代码
在 MCPHub 文档中使用内联代码来标记命令、配置键、文件名或短代码片段:
```md
使用 `mcphub start` 命令启动服务器,配置 `MCPHUB_PORT` 环境变量。
```
使用 `mcphub start` 命令启动服务器,配置 `MCPHUB_PORT` 环境变量。
## 代码块语法
### 基本代码块
MCPHub 支持多种编程语言的语法高亮:
````md
```javascript
// JavaScript 示例
const mcpClient = new MCPClient({
endpoint: process.env.MCPHUB_ENDPOINT,
apiKey: process.env.MCPHUB_API_KEY,
});
```
````
```javascript
// JavaScript 示例
const mcpClient = new MCPClient({
endpoint: process.env.MCPHUB_ENDPOINT,
apiKey: process.env.MCPHUB_API_KEY,
});
```
### TypeScript 代码
````md
```typescript
interface MCPServerConfig {
id: string;
name: string;
endpoint: string;
capabilities: string[];
metadata?: Record<string, any>;
}
class MCPServer implements MCPServerConfig {
constructor(
public id: string,
public name: string,
public endpoint: string,
public capabilities: string[],
) {}
}
```
````
```typescript
interface MCPServerConfig {
id: string;
name: string;
endpoint: string;
capabilities: string[];
metadata?: Record<string, any>;
}
class MCPServer implements MCPServerConfig {
constructor(
public id: string,
public name: string,
public endpoint: string,
public capabilities: string[],
) {}
}
```
### Python 代码
````md
```python
import requests
from typing import Dict, List, Optional
class MCPHubClient:
def __init__(self, endpoint: str, api_key: str):
self.endpoint = endpoint
self.api_key = api_key
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def create_server(self, config: Dict) -> Dict:
response = requests.post(
f'{self.endpoint}/api/servers',
json=config,
headers=self.headers
)
return response.json()
```
````
```python
import requests
from typing import Dict, List, Optional
class MCPHubClient:
def __init__(self, endpoint: str, api_key: str):
self.endpoint = endpoint
self.api_key = api_key
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def create_server(self, config: Dict) -> Dict:
response = requests.post(
f'{self.endpoint}/api/servers',
json=config,
headers=self.headers
)
return response.json()
```
## 配置文件
### YAML 配置
````md
```yaml title="mcphub.yml"
server:
port: 3000
host: 0.0.0.0
database:
type: postgresql
host: localhost
port: 5432
database: mcphub
username: mcphub_user
password: secure_password
mcp:
servers:
- id: ai-assistant
name: AI Assistant Server
endpoint: https://ai.example.com
capabilities:
- chat
- completion
- id: data-processor
name: Data Processing Server
endpoint: https://data.example.com
capabilities:
- analysis
- transformation
routing:
strategy: round_robin
health_check:
enabled: true
interval: 30s
timeout: 5s
logging:
level: info
format: json
file: /var/log/mcphub/app.log
```
````
```yaml title="mcphub.yml"
server:
port: 3000
host: 0.0.0.0
database:
type: postgresql
host: localhost
port: 5432
database: mcphub
username: mcphub_user
password: secure_password
mcp:
servers:
- id: ai-assistant
name: AI Assistant Server
endpoint: https://ai.example.com
capabilities:
- chat
- completion
- id: data-processor
name: Data Processing Server
endpoint: https://data.example.com
capabilities:
- analysis
- transformation
routing:
strategy: round_robin
health_check:
enabled: true
interval: 30s
timeout: 5s
logging:
level: info
format: json
file: /var/log/mcphub/app.log
```
### JSON 配置
````md
```json title="package.json"
{
"name": "@mcphub/server",
"version": "2.1.0",
"description": "Model Context Protocol Hub Server",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src/**/*.ts",
"migrate": "prisma migrate deploy"
},
"dependencies": {
"@prisma/client": "^5.7.0",
"express": "^4.18.2",
"helmet": "^7.1.0",
"cors": "^2.8.5",
"jsonwebtoken": "^9.0.2",
"bcryptjs": "^2.4.3",
"winston": "^3.11.0"
},
"devDependencies": {
"@types/node": "^20.10.0",
"@types/express": "^4.17.21",
"typescript": "^5.3.0",
"tsx": "^4.6.0",
"jest": "^29.7.0",
"eslint": "^8.55.0"
}
}
```
````
```json title="package.json"
{
"name": "@mcphub/server",
"version": "2.1.0",
"description": "Model Context Protocol Hub Server",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src/**/*.ts",
"migrate": "prisma migrate deploy"
},
"dependencies": {
"@prisma/client": "^5.7.0",
"express": "^4.18.2",
"helmet": "^7.1.0",
"cors": "^2.8.5",
"jsonwebtoken": "^9.0.2",
"bcryptjs": "^2.4.3",
"winston": "^3.11.0"
},
"devDependencies": {
"@types/node": "^20.10.0",
"@types/express": "^4.17.21",
"typescript": "^5.3.0",
"tsx": "^4.6.0",
"jest": "^29.7.0",
"eslint": "^8.55.0"
}
}
```
### Docker 配置
````md
```dockerfile title="Dockerfile"
FROM node:18-alpine AS builder
WORKDIR /app
# 复制依赖文件
COPY package*.json ./
COPY tsconfig.json ./
# 安装依赖
RUN npm ci --only=production
# 复制源码
COPY src/ ./src/
# 构建应用
RUN npm run build
# 生产环境镜像
FROM node:18-alpine AS production
WORKDIR /app
# 创建非 root 用户
RUN addgroup -g 1001 -S nodejs
RUN adduser -S mcphub -u 1001
# 复制构建产物
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
# 设置权限
USER mcphub
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node dist/health-check.js
EXPOSE 3000
CMD ["node", "dist/index.js"]
```
````
```dockerfile title="Dockerfile"
FROM node:18-alpine AS builder
WORKDIR /app
# 复制依赖文件
COPY package*.json ./
COPY tsconfig.json ./
# 安装依赖
RUN npm ci --only=production
# 复制源码
COPY src/ ./src/
# 构建应用
RUN npm run build
# 生产环境镜像
FROM node:18-alpine AS production
WORKDIR /app
# 创建非 root 用户
RUN addgroup -g 1001 -S nodejs
RUN adduser -S mcphub -u 1001
# 复制构建产物
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
# 设置权限
USER mcphub
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node dist/health-check.js
EXPOSE 3000
CMD ["node", "dist/index.js"]
```
## 终端命令
### Bash/Shell 命令
````md
```bash
# 克隆 MCPHub 仓库
git clone https://github.com/mcphub/mcphub.git
cd mcphub
# 安装依赖
npm install
# 复制环境变量文件
cp .env.example .env
# 设置数据库
npm run db:setup
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 启动生产服务器
npm start
```
````
```bash
# 克隆 MCPHub 仓库
git clone https://github.com/mcphub/mcphub.git
cd mcphub
# 安装依赖
npm install
# 复制环境变量文件
cp .env.example .env
# 设置数据库
npm run db:setup
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 启动生产服务器
npm start
```
### PowerShell 命令
````md
```powershell
# Windows PowerShell 安装步骤
# 克隆仓库
git clone https://github.com/mcphub/mcphub.git
Set-Location mcphub
# 安装 Node.js 依赖
npm install
# 复制环境变量文件
Copy-Item .env.example .env
# 启动开发服务器
npm run dev
```
````
```powershell
# Windows PowerShell 安装步骤
# 克隆仓库
git clone https://github.com/mcphub/mcphub.git
Set-Location mcphub
# 安装 Node.js 依赖
npm install
# 复制环境变量文件
Copy-Item .env.example .env
# 启动开发服务器
npm run dev
```
### Docker 命令
````md
```bash
# 使用 Docker 运行 MCPHub
docker run -d \
--name mcphub \
-p 3000:3000 \
-e NODE_ENV=production \
-e DATABASE_URL=postgresql://user:pass@host:5432/mcphub \
-e JWT_SECRET=your-secret-key \
mcphub/server:latest
# 查看日志
docker logs mcphub
# 进入容器
docker exec -it mcphub sh
# 停止容器
docker stop mcphub
# 使用 Docker Compose
docker-compose up -d
```
````
```bash
# 使用 Docker 运行 MCPHub
docker run -d \
--name mcphub \
-p 3000:3000 \
-e NODE_ENV=production \
-e DATABASE_URL=postgresql://user:pass@host:5432/mcphub \
-e JWT_SECRET=your-secret-key \
mcphub/server:latest
# 查看日志
docker logs mcphub
# 进入容器
docker exec -it mcphub sh
# 停止容器
docker stop mcphub
# 使用 Docker Compose
docker-compose up -d
```
## API 请求示例
### cURL 命令
````md
```bash
# 创建新的 MCP 服务器
curl -X POST https://api.mcphub.io/api/servers \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "AI Assistant Server",
"endpoint": "https://ai.example.com",
"capabilities": ["chat", "completion"],
"groupId": "production"
}'
# 获取服务器列表
curl -X GET "https://api.mcphub.io/api/servers?limit=10&active=true" \
-H "Authorization: Bearer YOUR_API_TOKEN"
# 更新服务器配置
curl -X PUT https://api.mcphub.io/api/servers/server-123 \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Updated AI Assistant",
"active": true
}'
# 删除服务器
curl -X DELETE https://api.mcphub.io/api/servers/server-123 \
-H "Authorization: Bearer YOUR_API_TOKEN"
```
````
```bash
# 创建新的 MCP 服务器
curl -X POST https://api.mcphub.io/api/servers \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "AI Assistant Server",
"endpoint": "https://ai.example.com",
"capabilities": ["chat", "completion"],
"groupId": "production"
}'
# 获取服务器列表
curl -X GET "https://api.mcphub.io/api/servers?limit=10&active=true" \
-H "Authorization: Bearer YOUR_API_TOKEN"
# 更新服务器配置
curl -X PUT https://api.mcphub.io/api/servers/server-123 \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Updated AI Assistant",
"active": true
}'
# 删除服务器
curl -X DELETE https://api.mcphub.io/api/servers/server-123 \
-H "Authorization: Bearer YOUR_API_TOKEN"
```
### HTTP 请求示例
````md
```http
POST /api/servers HTTP/1.1
Host: api.mcphub.io
Authorization: Bearer YOUR_API_TOKEN
Content-Type: application/json
{
"name": "AI Assistant Server",
"endpoint": "https://ai.example.com",
"capabilities": ["chat", "completion"],
"groupId": "production"
}
```
````
```http
POST /api/servers HTTP/1.1
Host: api.mcphub.io
Authorization: Bearer YOUR_API_TOKEN
Content-Type: application/json
{
"name": "AI Assistant Server",
"endpoint": "https://ai.example.com",
"capabilities": ["chat", "completion"],
"groupId": "production"
}
```
## 数据库查询
### SQL 查询
````md
```sql
-- 查询活跃的 MCP 服务器
SELECT
id,
name,
endpoint,
status,
created_at
FROM mcp_servers
WHERE status = 'active'
ORDER BY created_at DESC;
-- 统计每个组的服务器数量
SELECT
g.name as group_name,
COUNT(s.id) as server_count
FROM server_groups g
LEFT JOIN mcp_servers s ON g.id = s.group_id
GROUP BY g.id, g.name
ORDER BY server_count DESC;
-- 查询最近的错误日志
SELECT
timestamp,
level,
message,
metadata
FROM logs
WHERE level = 'error'
AND timestamp >= NOW() - INTERVAL '1 hour'
ORDER BY timestamp DESC
LIMIT 50;
```
````
```sql
-- 查询活跃的 MCP 服务器
SELECT
id,
name,
endpoint,
status,
created_at
FROM mcp_servers
WHERE status = 'active'
ORDER BY created_at DESC;
-- 统计每个组的服务器数量
SELECT
g.name as group_name,
COUNT(s.id) as server_count
FROM server_groups g
LEFT JOIN mcp_servers s ON g.id = s.group_id
GROUP BY g.id, g.name
ORDER BY server_count DESC;
-- 查询最近的错误日志
SELECT
timestamp,
level,
message,
metadata
FROM logs
WHERE level = 'error'
AND timestamp >= NOW() - INTERVAL '1 hour'
ORDER BY timestamp DESC
LIMIT 50;
```
## 代码块最佳实践
### 1. 语言标识
始终为代码块指定正确的语言:
````md
````javascript // ✅ 正确
```js // ✅ 也可以
```; // ❌ 避免无语言标识
````
````
### 2. 文件名标题
为配置文件和示例添加文件名:
````md
```yaml title="docker-compose.yml"
version: '3.8'
services:
mcphub:
image: mcphub/server:latest
```
````
### 3. 突出显示重要行
使用行号高亮重要代码:
````md
```javascript {3,7-9}
const express = require('express');
const app = express();
const port = process.env.PORT || 3000; // 重要:端口配置
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(port, () => {
// 重要:服务器启动
console.log(`Server running on port ${port}`);
}); // 重要:结束
```
````
### 4. 代码注释
添加有意义的中文注释:
```javascript
// 初始化 MCPHub 客户端
const client = new MCPHubClient({
endpoint: 'https://api.mcphub.io',
apiKey: process.env.API_KEY,
timeout: 30000, // 30 秒超时
retries: 3, // 重试 3 次
});
// 配置路由策略
client.setRoutingStrategy({
type: 'weighted', // 加权轮询
healthCheck: true, // 启用健康检查
fallback: 'round_robin', // 降级策略
});
```
### 5. 错误处理示例
展示完整的错误处理:
```javascript
try {
const server = await mcpClient.createServer({
name: 'AI Assistant',
endpoint: 'https://ai.example.com',
});
console.log('服务器创建成功:', server.id);
} catch (error) {
if (error.code === 'DUPLICATE_SERVER') {
console.log('服务器已存在,跳过创建');
} else if (error.code === 'INVALID_ENDPOINT') {
console.error('无效的端点地址:', error.message);
} else {
console.error('创建失败:', error.message);
throw error; // 重新抛出未知错误
}
}
```
## 支持的语言
MCPHub 文档支持以下编程语言的语法高亮:
- **JavaScript/TypeScript**: `javascript`, `js`, `typescript`, `ts`
- **Python**: `python`, `py`
- **Shell/Bash**: `bash`, `shell`, `sh`
- **PowerShell**: `powershell`, `ps1`
- **SQL**: `sql`, `postgresql`, `mysql`
- **YAML**: `yaml`, `yml`
- **JSON**: `json`
- **XML**: `xml`
- **HTML**: `html`
- **CSS**: `css`
- **Dockerfile**: `dockerfile`
- **Go**: `go`
- **Rust**: `rust`
- **Java**: `java`
- **C#**: `csharp`, `cs`
- **PHP**: `php`
- **Ruby**: `ruby`
- **HTTP**: `http`
- **Markdown**: `markdown`, `md`
`````
### 使用三个反引号
````md
```javascript
console.log('Hello World');
`````
`````
### 语法高亮
我们使用 [Prism](https://prismjs.com/) 来语法高亮显示。Prism 支持 [各种编程语言](https://prismjs.com/#supported-languages)。
要添加语法高亮显示,请在代码块的第一行指定语言。
````md
```python
def hello():
print("Hello World")
```
`````
```python
def hello():
print("Hello World")
```
## 代码组
<CodeGroup>
```bash npm
npm i mintlify
```
```bash yarn
yarn add mintlify
```
```bash pnpm
pnpm add mintlify
```
</CodeGroup>
`CodeGroup` 允许您将多个代码块组合在一起,并为它们提供选项卡。
````md
<CodeGroup>
```bash npm
npm i mintlify
```
```bash yarn
yarn add mintlify
```
```bash pnpm
pnpm add mintlify
```
</CodeGroup>
````
### 代码标题
您也可以为代码块设置标题:
```javascript hello.js
const hello = 'world';
console.log(hello);
```
````md
```javascript hello.js
const hello = 'world';
console.log(hello);
```
````
|