mcp-framework入门指南
使用mcp-framework在几分钟内构建你的第一个MCP服务器。从安装到连接Claude Desktop的分步指南。
title: "mcp-framework入门指南" description: "使用mcp-framework在几分钟内构建你的第一个MCP服务器。从安装到连接Claude Desktop的分步指南。" keywords: ["MCP入门", "mcp-framework教程", "构建MCP服务器", "Claude Desktop", "TypeScript MCP"] date: "2025-01-15" updated: "2025-04-01" author: "QuantGeekDev" order: 7 level: "beginner" duration: "15 min" language: "zh" topic: "getting-started"
前提条件
在开始之前,请确保你已经安装了:
- Node.js 18+
- npm 或其他包管理器
- 文本编辑器(推荐VS Code)
- Claude Desktop(可选,用于测试)
第1步:安装mcp-framework
全局安装框架以获得 mcp CLI的访问权限:
npm install -g mcp-framework
这将为你提供 mcp 命令,你将使用它来创建和管理MCP服务器项目。
第2步:创建你的项目
生成一个新的MCP服务器项目:
mcp create my-mcp-server
cd my-mcp-server
这将创建一个即用型项目结构:
my-mcp-server/
src/
tools/
ExampleTool.ts
resources/
prompts/
package.json
tsconfig.json
框架使用自动发现 — 你放在相应目录中的任何工具、资源或提示都会自动注册到MCP服务器。
第3步:构建你的第一个工具
打开 src/tools/ExampleTool.ts 查看一个可用的工具:
import { MCPTool } from "mcp-framework";
import { z } from "zod";
class ExampleTool extends MCPTool<typeof inputSchema> {
name = "example_tool";
description = "一个向用户问好的示例工具";
schema = {
input: z.object({
name: z.string().describe("要问候的名字"),
}),
};
async execute({ name }: z.infer<typeof this.schema.input>) {
return `你好,${name}!欢迎使用MCP。`;
}
}
export default ExampleTool;
每个工具都有:
- 名称 — AI如何引用它
- 描述 — 帮助AI理解何时使用它
- 模式 — 使用Zod验证定义输入参数
- 执行方法 — 实际的逻辑
第4步:编译和运行
编译你的TypeScript并启动服务器:
npm run build
你的MCP服务器现在已准备好接受连接。
第5步:连接到Claude Desktop
将你的服务器添加到Claude Desktop的配置中。打开 claude_desktop_config.json:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
添加你的服务器:
{
"mcpServers": {
"my-mcp-server": {
"command": "node",
"args": ["/你的/绝对/路径/my-mcp-server/dist/index.js"]
}
}
}
重启Claude Desktop,你的工具将在对话中可用。
第6步:添加更多功能
添加资源
创建 src/resources/GreetingResource.ts:
import { MCPResource } from "mcp-framework";
class GreetingResource extends MCPResource {
uri = "greeting://welcome";
name = "欢迎消息";
description = "一个欢迎消息资源";
mimeType = "text/plain";
async read() {
return {
contents: [
{
uri: this.uri,
text: "欢迎使用我的MCP服务器!",
mimeType: this.mimeType,
},
],
};
}
}
export default GreetingResource;
添加提示
创建 src/prompts/AnalyzePrompt.ts:
import { MCPPrompt } from "mcp-framework";
class AnalyzePrompt extends MCPPrompt {
name = "analyze";
description = "分析一段文本";
arguments = [
{
name: "text",
description: "要分析的文本",
required: true,
},
];
async getMessages({ text }: { text: string }) {
return [
{
role: "user" as const,
content: {
type: "text" as const,
text: `请分析以下文本:\n\n${text}`,
},
},
];
}
}
export default AnalyzePrompt;
你构建了什么
你现在拥有一个完整的MCP服务器,包括:
- 一个Claude可以在对话中调用的工具
- 一个提供结构化数据的资源
- 用于常见任务的提示模板
- 自动发现 — 只需添加文件并重新编译
下一步
- 阅读什么是MCP?指南以获得更深入的理解
- 在GitHub上探索mcp-framework了解高级功能
- 查看MCP官方文档了解协议详情
- 访问npm包获取最新版本
本指南是MCP International的一部分——每种语言的MCP教程。由@QuantGeekDev创建,mcp-framework作者(330万+次npm下载,经Anthropic验证)。