概述
工具列表
內容詳情
替代品
什麼是MCP Learning Project?
這是一個完整的MCP開發學習項目,通過實踐教學幫助開發者從基礎到高級掌握Model Context Protocol的開發。項目包含服務端(後端)和客戶端(前端)開發內容。如何使用MCP Learning Project?
通過交互式學習環境,您可以逐步學習MCP開發的各個階段,從基礎工具調用到高級狀態管理。適用場景
適合想要學習AI工具開發、構建AI輔助應用或創建自定義MCP服務器的開發者。主要功能
如何使用
使用案例
常見問題
相關資源
安裝
🚀 MCP學習項目 - 完整指南
這是一個全面的教程項目,將教授你從入門到進階的模型上下文協議(Model Context Protocol,MCP)開發。你將學習服務器端(後端)和客戶端(前端)的開發。
🚀 快速開始
1. 項目設置
# 創建項目目錄
mkdir mcp-learning-project
cd mcp-learning-project
# 初始化npm項目
npm init -y
# 安裝依賴
npm install @modelcontextprotocol/sdk
# 安裝開發依賴
npm install --save-dev typescript @types/node tsx
2. 創建package.json
{
"name": "mcp-learning-project",
"version": "1.0.0",
"description": "Learn MCP development from beginner to advanced",
"main": "dist/server.js",
"type": "module",
"scripts": {
"build": "tsc",
"start:server": "node dist/server.js",
"start:client": "node dist/client.js dist/server.js",
"dev:server": "tsx src/server.ts",
"dev:client": "tsx src/client.ts dist/server.js",
"demo": "npm run build && npm run start:client"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^0.4.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"tsx": "^4.0.0",
"typescript": "^5.0.0"
}
}
3. 創建TypeScript配置文件
創建 tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
4. 保存代碼文件
- 將 MCP學習服務器 代碼保存為
src/server.ts - 將 MCP學習客戶端 代碼保存為
src/client.ts
5. 構建並運行項目
# 構建項目
npm run build
# 運行交互式客戶端(這也將啟動服務器)
npm run demo
✨ 主要特性
入門級別
- ✅ 基礎MCP服務器結構和概念
- ✅ 簡單工具的創建和註冊
- ✅ 參數處理和驗證
- ✅ 基本的客戶端連接和工具調用
中級水平
- ✅ 工具調用之間的狀態管理
- ✅ 資源管理(為AI提供數據)
- ✅ 數據處理和複雜操作
- ✅ 客戶端 - 服務器通信模式
高級階段
- ✅ 具有持久狀態的CRUD操作
- ✅ 全面的錯誤處理
- ✅ 用於AI交互的提示模板
- ✅ 最佳實踐和生產環境考慮因素
📦 安裝指南
見快速開始部分的步驟,包含項目設置、依賴安裝、配置文件創建等內容。
💻 使用示例
基礎用法
// 服務器設置
const server = new Server({
name: 'my-server',
version: '1.0.0'
}, {
capabilities: {
tools: {}, // Functions AI can call
resources: {}, // Data AI can read
prompts: {} // Templates AI can use
}
});
// 工具註冊
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'my_tool',
description: 'What this tool does',
inputSchema: { /* JSON Schema */ }
}
]
}));
// 工具實現
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
// Process the tool call and return results
return {
content: [{
type: 'text',
text: 'Tool response'
}]
};
});
// 客戶端設置
const client = new Client({
name: 'my-client',
version: '1.0.0'
}, {
capabilities: { /* client capabilities */ }
});
// 連接到服務器
const transport = new StdioClientTransport(/* server process */);
await client.connect(transport);
// 發現服務器功能
const tools = await client.listTools();
const resources = await client.listResources();
// 使用服務器工具
const result = await client.callTool({
name: 'tool_name',
arguments: { /* tool parameters */ }
});
高級用法
// 以下是一些高級場景的代碼示例
// 例如創建自定義工具、資源和提示等
// 創建自定義工具 - 天氣工具
{
name: 'weather',
description: 'Get weather information',
inputSchema: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' }
},
required: ['city']
}
}
// 創建自定義資源 - 配置資源
{
uri: 'config://app-settings',
name: 'Application Settings',
description: 'Current application configuration',
mimeType: 'application/json'
}
// 創建交互式提示 - 代碼審查提示
{
name: 'code-review',
description: 'Start a code review session',
arguments: [
{
name: 'language',
description: 'Programming language',
required: true
},
{
name: 'focus',
description: 'Review focus (security, performance, style)',
required: false
}
]
}
📚 詳細文檔
學習路徑
階段1:理解基礎
-
啟動交互式客戶端:
npm run demo -
嘗試基本命令:
mcp-learning> help mcp-learning> tools mcp-learning> call hello_world {"name": "Alice"} -
瞭解資源:
mcp-learning> resources mcp-learning> read mcp-concepts
階段2:實踐操作
-
運行入門級演示:
mcp-learning> demo beginner -
練習工具調用:
mcp-learning> call calculator {"operation": "add", "a": 5, "b": 3} mcp-learning> call calculator {"operation": "divide", "a": 10, "b": 0} -
理解狀態管理:
mcp-learning> call counter {"action": "get"} mcp-learning> call counter {"action": "increment", "amount": 5} mcp-learning> call counter {"action": "get"}
階段3:高級概念
-
運行中級演示:
mcp-learning> demo intermediate -
處理複雜數據:
mcp-learning> call data_processor {"data": [5, 2, 8, 1, 9], "operation": "sort"} mcp-learning> call data_processor {"data": [5, 2, 8, 1, 9], "operation": "average"} -
CRUD操作:
mcp-learning> call task_manager {"action": "create", "task": {"title": "Learn MCP", "priority": "high"}} mcp-learning> call task_manager {"action": "list"}
階段4:生產就緒
-
運行高級演示:
mcp-learning> demo advanced -
學習錯誤處理:
mcp-learning> call error_demo {"error_type": "none"} mcp-learning> call error_demo {"error_type": "validation"} -
研究最佳實踐:
mcp-learning> read best-practices
關鍵概念解釋
1. MCP服務器(後端)
服務器為AI模型提供功能:
// 服務器設置
const server = new Server({
name: 'my-server',
version: '1.0.0'
}, {
capabilities: {
tools: {}, // Functions AI can call
resources: {}, // Data AI can read
prompts: {} // Templates AI can use
}
});
// 工具註冊
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'my_tool',
description: 'What this tool does',
inputSchema: { /* JSON Schema */ }
}
]
}));
// 工具實現
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
// Process the tool call and return results
return {
content: [{
type: 'text',
text: 'Tool response'
}]
};
});
2. MCP客戶端(前端)
客戶端連接到服務器並使用其功能:
// 客戶端設置
const client = new Client({
name: 'my-client',
version: '1.0.0'
}, {
capabilities: { /* client capabilities */ }
});
// 連接到服務器
const transport = new StdioClientTransport(/* server process */);
await client.connect(transport);
// 發現服務器功能
const tools = await client.listTools();
const resources = await client.listResources();
// 使用服務器工具
const result = await client.callTool({
name: 'tool_name',
arguments: { /* tool parameters */ }
});
3. 通信流程
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ AI Model │ ───▶ │ MCP Client │ ───▶ │ MCP Server │
│ │ │ (Frontend) │ │ (Backend) │
│ │ ◀─── │ │ ◀─── │ │
└─────────────┘ └─────────────┘ └─────────────┘
▲ │ │
│ │ │
└──────────────────────┴──────────────────────┘
Uses server capabilities
實驗思路
創建自己的工具:
-
天氣工具:
{ name: 'weather', description: 'Get weather information', inputSchema: { type: 'object', properties: { city: { type: 'string', description: 'City name' }, units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' } }, required: ['city'] } } -
文件系統工具:
{ name: 'file_operations', description: 'Basic file system operations', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['list', 'read', 'write'] }, path: { type: 'string', description: 'File or directory path' }, content: { type: 'string', description: 'Content to write' } }, required: ['action', 'path'] } } -
數據庫工具:
{ name: 'database', description: 'Simple in-memory database operations', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['create', 'read', 'update', 'delete'] }, table: { type: 'string', description: 'Table name' }, data: { type: 'object', description: 'Data to store/update' }, id: { type: 'string', description: 'Record ID' } }, required: ['action', 'table'] } }
創建自定義資源:
-
配置資源:
{ uri: 'config://app-settings', name: 'Application Settings', description: 'Current application configuration', mimeType: 'application/json' } -
文檔資源:
{ uri: 'docs://api-reference', name: 'API Reference', description: 'Complete API documentation', mimeType: 'text/markdown' }
創建交互式提示:
- 代碼審查提示:
{ name: 'code-review', description: 'Start a code review session', arguments: [ { name: 'language', description: 'Programming language', required: true }, { name: 'focus', description: 'Review focus (security, performance, style)', required: false } ] }
調試和故障排除
常見問題:
-
服務器無法啟動:
# 檢查TypeScript是否正確編譯 npm run build # 查找編譯錯誤 npx tsc --noEmit # 檢查是否缺少依賴 npm install -
客戶端無法連接:
# 確保服務器路徑正確 node dist/client.js dist/server.js # 檢查服務器進程是否啟動 node dist/server.js -
工具調用失敗:
// 在服務器中添加調試信息 console.error(`[DEBUG] Tool called: ${name}`, JSON.stringify(args)); // 仔細驗證輸入參數 if (typeof args.requiredParam === 'undefined') { throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter'); }
調試模式:
在服務器和客戶端啟用詳細日誌記錄:
// 在服務器中
console.error('[SERVER]', 'Detailed log message');
// 在客戶端
console.log('[CLIENT]', 'Connection status:', connected);
下一步:構建生產服務器
1. 添加實際功能
用實際有用的功能替換演示工具:
// 示例:實際的文件系統訪問
private async handleFileOperations(args: any) {
const { action, path, content } = args;
switch (action) {
case 'read':
return {
content: [{
type: 'text',
text: await fs.readFile(path, 'utf-8')
}]
};
case 'write':
await fs.writeFile(path, content);
return {
content: [{
type: 'text',
text: `File written: ${path}`
}]
};
}
}
2. 添加外部集成
// 示例:HTTP API集成
private async handleApiCall(args: any) {
const { url, method, data } = args;
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: data ? JSON.stringify(data) : undefined
});
return {
content: [{
type: 'text',
text: JSON.stringify({
status: response.status,
data: await response.json()
}, null, 2)
}]
};
}
3. 添加持久化功能
import * as fs from 'fs/promises';
class PersistentMCPServer {
private dataFile = './mcp-data.json';
async loadState(): Promise<Map<string, any>> {
try {
const data = await fs.readFile(this.dataFile, 'utf-8');
return new Map(Object.entries(JSON.parse(data)));
} catch {
return new Map();
}
}
async saveState(state: Map<string, any>): Promise<void> {
const data = Object.fromEntries(state);
await fs.writeFile(this.dataFile, JSON.stringify(data, null, 2));
}
}
4. 添加身份驗證
private validateAuth(headers: any): boolean {
const token = headers['authorization'];
return token === 'Bearer your-secret-token';
}
private async handleSecureTool(args: any, headers: any) {
if (!this.validateAuth(headers)) {
throw new McpError(ErrorCode.InvalidParams, 'Authentication required');
}
// 繼續工具邏輯...
}
🔧 技術細節
服務器和客戶端的工作原理
服務器端通過 Server 類初始化,設置名稱、版本和功能(工具、資源、提示)。使用 setRequestHandler 方法註冊工具和處理工具調用請求。客戶端通過 Client 類初始化,連接到服務器後可以發現服務器的功能並調用工具。
通信流程
AI模型通過MCP客戶端與MCP服務器進行交互。客戶端負責連接服務器、發現功能和調用工具,服務器負責提供功能和處理工具調用請求。
錯誤處理
在服務器和客戶端中,通過捕獲異常和驗證輸入參數來處理錯誤。例如,在工具調用時檢查輸入參數是否合法,若不合法則拋出 McpError 異常。
📚 額外資源
官方文檔:
社區示例:
高級主題:
- 用於Web服務的HTTP傳輸
- 用於即時通信的WebSocket傳輸
- 自定義傳輸實現
- 性能優化技術
- 安全最佳實踐
🎯 學習練習
練習1:擴展計算器
添加更多操作:power、sqrt、factorial、sin、cos
練習2:構建筆記系統
創建用於創建、編輯、搜索和組織帶標籤筆記的工具。
練習3:添加外部API集成
與真實的API(天氣、新聞、股票價格)集成並創建相應的工具。
練習4:構建項目管理系統
創建一個全面的項目管理系統,包含任務、截止日期、優先級和進度跟蹤。
練習5:添加即時功能
實現可以向客戶端發送通知或更新的工具。
🏆 掌握清單
入門級別 ✅
- [ ] 理解MCP架構(客戶端、服務器、傳輸)
- [ ] 創建帶有輸入驗證的基本工具
- [ ] 處理簡單的工具調用和響應
- [ ] 閱讀並理解錯誤消息
中級水平 ✅
- [ ] 實現具有持久化功能的有狀態工具
- [ ] 創建併為AI提供資源
- [ ] 處理複雜的數據處理
- [ ] 實現適當的錯誤處理模式
高級階段 ✅
- [ ] 構建具有複雜狀態的CRUD操作
- [ ] 創建交互式提示模板
- [ ] 實現適用於生產環境的錯誤處理
- [ ] 理解安全和身份驗證概念
- [ ] 優化生產環境的性能
專家級別 🚀
- [ ] 構建自定義傳輸層
- [ ] 創建MCP服務器框架
- [ ] 實現高級安全措施
- [ ] 構建分佈式MCP架構
- [ ] 為MCP生態系統做出貢獻
🎉 恭喜!
現在你已經從前端和後端的角度全面瞭解了MCP開發。你可以:
- 構建MCP服務器,提供工具、資源和提示
- 創建MCP客戶端,與服務器進行有效交互
- 優雅地處理錯誤 並實現適當的驗證
- 管理工具調用和會話之間的狀態
- 遵循最佳實踐 進行生產環境的實現
本項目中的交互式學習環境讓你親身體驗所有MCP概念。以此為基礎,為任何領域或用例構建你自己的專業MCP服務器!
編碼愉快!🚀
替代品








