如何為 Claude Desktop 構建自定義 MCP 服務器:完整實戰指南
掌握使用 @zhama/mcp-server 框架為 Claude Desktop 構建自定義模型上下文協議服務器的技能。這份深度指南涵蓋了從安裝設置到生產部署的全部內容,包含實用示例和生產級最佳實踐。
本文發佈於 2024年11月14日。產品當前能力參見產品能力。
隨著 Claude 等 AI 助手的普及,開發者面臨著一個新的挑戰:如何使用自定義工具和集成來擴展 AI 的能力?
答案就在**模型上下文協議(MCP)**中。藉助現代 TypeScript 框架,構建 MCP 服務器從未如此簡單。無論你是想為 AI 添加數據庫查詢能力、集成第三方 API,還是創建專屬的業務工具,MCP 都能讓這一切變得輕而易舉。
在深入實現之前,讓我們先了解 MCP 是什麼。
模型上下文協議是一種標準化的方式,使 AI 應用程序能夠與外部工具、資源和數據源進行交互。可以把它想像成 AI 模型和你的自定義功能之間的橋梁。
通過 MCP,AI 助手能夠:
TypeScript 為 MCP 服務器開發帶來了多個優勢:
現在讓我們動手實踐!我們將構建一個簡單但實用的計算器工具,讓 Claude 能夠執行數學運算。
首先,使用 npm 安裝所需的包:
npm install @zhama/mcp-server
以下是如何使用裝飾器創建一個簡單的計算器工具。代碼非常直觀,即使是初學者也能輕鬆理解:
import { createMCPServer, BaseTool, Tool } from '@zhama/mcp-server';
@Tool({
name: 'calculator',
description: '执行基本算术运算',
parameters: [
{
name: 'operation',
type: 'string',
description: '运算类型:add(加)、subtract(减)、multiply(乘)或 divide(除)',
required: true
},
{
name: 'a',
type: 'number',
description: '第一个数字',
required: true
},
{
name: 'b',
type: 'number',
description: '第二个数字',
required: true
}
]
})
class CalculatorTool extends BaseTool {
protected toolDefinition = {
name: 'calculator',
description: '执行基本算术运算',
parameters: []
};
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { operation, a, b } = params as {
operation: string;
a: number;
b: number
};
const operations = {
add: () => a + b,
subtract: () => a - b,
multiply: () => a * b,
divide: () => b !== 0 ? a / b : '错误:除数不能为零'
};
return { result: operations[operation]() };
}
}
最後一步,創建服務器實例並啟動它:
async function main() {
const server = createMCPServer('calculator-server', '1.0.0')
.description('为 AI 助手提供的强大计算器')
.enableTools()
.addTool(new CalculatorTool());
await server.runStdio();
}
main().catch(console.error);
資源允許你的 AI 訪問動態內容。以下是一個獲取用戶數據的資源示例:
class UserDataResource extends BaseResource {
protected resourceDefinition = {
type: 'application/json' as const,
description: '访问用户资料信息'
};
protected async executeInternal(userId: string): Promise<Resource> {
const userData = await fetchUserFromDatabase(userId);
return {
id: `user-${userId}`,
uri: `resource://users/${userId}`,
name: `用户资料:${userData.name}`,
type: 'application/json',
content: JSON.stringify(userData)
};
}
}
創建上下文提示,幫助 AI 理解你的業務領域:
class DocumentAnalysisPrompt extends BasePrompt {
protected promptDefinition = {
type: 'text' as const,
description: '生成文档分析指令'
};
protected async executeInternal(documentType: string): Promise<Prompt> {
const instructions = generateAnalysisInstructions(documentType);
return {
id: `analysis-${documentType}`,
name: `分析${documentType}`,
type: 'text',
content: instructions
};
}
}
對於生產部署,配置日誌記錄、錯誤處理和多種功能:
const server = createMCPServer('production-server', '2.0.0')
.description('生产级 MCP 服务器')
.author('您的公司')
.license('MIT')
.enableTools({ listChanged: true })
.enableResources({ subscribe: true, listChanged: true })
.enablePrompts({ listChanged: true })
.enableLogging('info')
.addTool(new CalculatorTool())
.addResource(new UserDataResource())
.addPromptGenerator('analysis', async (type) => {
return await generatePrompt(type);
});
// 用于 Claude Desktop - 使用 STDIO
await server.runStdio();
// 用于 Web 应用 - 使用 SSE
await server.runSSE(3000);
要在 Claude Desktop 中使用你的 MCP 服務器,需要將其添加到配置文件:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"calculator": {
"command": "node",
"args": ["/path/to/your/built/server.js", "--stdio"]
}
}
}
重啟 Claude Desktop 後,你的工具就可以被 AI 助手使用了!
始終為參數和返回值定義適當的 TypeScript 類型:
interface CalculationParams {
operation: 'add' | 'subtract' | 'multiply' | 'divide';
a: number;
b: number;
}
interface CalculationResult {
result: number;
operation: string;
}
實現全面的錯誤處理:
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
try {
// 验证输入
if (!isValidOperation(params.operation)) {
throw new Error('无效的运算类型');
}
// 执行逻辑
return await performCalculation(params);
} catch (error) {
this.logger.error('计算失败', error);
throw new Error(`计算失败:${error.message}`);
}
}
清晰地記錄你的工具,讓 AI 理解何時以及如何使用它們:
@Tool({
name: 'send_email',
description: '向收件人发送电子邮件。当用户要求发送邮件或给某人发消息时使用此工具。',
parameters: [
{
name: 'to',
type: 'string',
description: '收件人的电子邮件地址',
required: true
},
{
name: 'subject',
type: 'string',
description: '邮件主题',
required: true
},
{
name: 'body',
type: 'string',
description: '邮件正文内容',
required: true
}
]
})
創建允許 AI 安全查詢數據庫的工具:
@Tool({
name: 'query_customer_data',
description: '通过邮箱或 ID 搜索客户记录',
parameters: [/* ... */]
})
class CustomerQueryTool extends BaseTool {
// 实现时要注意 SQL 注入防护
}
將 AI 連接到外部服務:
@Tool({
name: 'check_weather',
description: '获取指定位置的当前天气',
parameters: [/* ... */]
})
class WeatherTool extends BaseTool {
// 调用天气 API 的实现
}
使 AI 能夠處理文件:
@Tool({
name: 'analyze_document',
description: '从文档中提取和分析内容',
parameters: [/* ... */]
})
class DocumentAnalyzerTool extends BaseTool {
// 文档处理的实现
}
利用 TypeScript 的 async/await 實現最佳性能:
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
// 并行执行
const [userData, preferences, history] = await Promise.all([
fetchUserData(params.userId),
fetchUserPreferences(params.userId),
fetchUserHistory(params.userId)
]);
return { userData, preferences, history };
}
為頻繁訪問的資源實現緩存:
private cache = new Map<string, CachedData>();
protected async executeInternal(key: string): Promise<unknown> {
if (this.cache.has(key)) {
return this.cache.get(key);
}
const data = await fetchExpensiveData(key);
this.cache.set(key, data);
return data;
}
始終全面測試你的工具:
import { CalculatorTool } from './calculator';
describe('CalculatorTool', () => {
it('应该正确地将两个数字相加', async () => {
const tool = new CalculatorTool();
const result = await tool.execute({
operation: 'add',
a: 5,
b: 3
});
expect(result.result).toBe(8);
});
});
使用環境變量進行配置:
const server = createMCPServer('my-server', '1.0.0')
.enableLogging(process.env.LOG_LEVEL || 'info');
容器化你的 MCP 服務器:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD ["node", "dist/server.js", "--stdio"]
使用 TypeScript 構建 MCP 服務器為擴展 AI 能力開啟了無限可能。無論你是集成數據庫、外部 API,還是自定義業務邏輯,基於裝飾器的方法都使開發變得直觀且易於維護。
關鍵要點:
準備好構建自己的 MCP 服務器了嗎?可能性是無限的。從客戶服務自動化到數據分析工具,MCP 服務器是連接 AI 智能與你獨特業務需求的橋梁。
有問題或想分享你的 MCP 服務器實現?加入我們的社區討論!
掌握使用 @zhama/mcp-server 框架為 Claude Desktop 構建自定義模型上下文協議服務器的技能。這份深度指南涵蓋了從安裝設置到生產部署的全部內容,包含實用示例和生產級最佳實踐。
Muse 讓雲端 Agent 走到臺前。Tego OS 把數字分身帶進中國企業的真實工作:接任務、用工具、交結果,也讓關鍵操作回到人的判斷中。
Tego OS v3.0.0 在桌面端做了三件事:常駐置頂的 Mini Chat 浮窗、統一的下載中心、Windows NSIS 安裝器全面重寫。本文聚焦體驗細節,解釋這套組合是怎麼把數字分身真正「裝進每天的工作流」的。