构建MCP服务器:第1部分——资源入门
本教程将引导您设置一个基本的MCP(模型上下文协议)服务器,以向像Claude这样的大型语言模型(LLM)公开只读资源。您将了解什么是MCP,为什么资源有用,以及如何使用以下代码初始化Node.js/TypeScript项目 @modelcontextprotocol/sdk.
目录
什么是模型上下文协议?
模型上下文协议(MCP)是一个标准化的接口,允许LLM与外部数据和服务安全交互。使用MCP,您可以以受控的方式向您的AI模型公开文件、数据库、API等。
什么是MCP资源?
资源是通过唯一URI公开内容(文本或二进制)的只读端点。示例包括:
file:///path/to/file.txtdatabase://users/123api://weather/latest
每个资源都有元数据,如显示名称和MIME类型。
为什么要使用资源?
资源使LLM能够:
- 读取文件和数据库
- 执行命令
- 访问API
- 与本地工具交互
所有交互都需要明确的用户权限,以确保安全性和可审计性。
示例服务器
文档服务器
公开您的文档:
docs://api/reference → API documentation
docs://guides/getting-started → User guides日志分析服务器
提供系统日志:
logs://system/today → Today's logs
logs://errors/recent → Recent error messages客户数据服务器
提供客户见解:
customers://profiles/summary → Customer overview
customers://feedback/recent → Latest feedback入门指南
先决条件
- Node.js(>=16)
- npm(>=8)
- TypeScript
安装
mkdir hello-mcp
cd hello-mcp
npm init -y
npm install @modelcontextprotocol/sdk
npm install -D typescript @types/node项目设置
- 更新
package.json:
{
"name": "hello-mcp",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.1.0"
},
"devDependencies": {
"typescript": "^5.7.2",
"@types/node": "^22.10.5"
}
}- 创建
tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}- 创建一个
src/目录并开始对MCP服务器进行编码。
后续步骤
有关配置传输和高级功能的信息,请参阅第2部分。
MCP工具(动态操作)
MCP工具(也称为动态操作)允许您定义LLM在会话期间可以调用的自定义函数,将MCP的功能扩展到静态资源之外。
工具vs提示
| 特性 | MCP工具 | 提示 |
|---|---|---|
| 能力 | 执行代码和操作 | 静态自然语言 |
| 安全 | 受控和可审计 | 无外部影响 |
| 灵活性 | 高(自定义逻辑) | 仅限于推理 |
完成我们的问候服务器
下面是一个展示问候资源的问候服务器的简单示例:
import { ResourceServer } from "@modelcontextprotocol/sdk";
const server = new ResourceServer({ port: 3000 });
server.addResource({
uri: "greeting://hello",
displayName: "Greeting Resource",
fn: async (req) => {
const name = req.query.name || "World";
return `Hello, ${name}!`;
},
});
server.listen(() => console.log("Greeting server running on port 3000"));来源和附加阅读
许可证
麻省理工学院
