MCP示例代理教程
一个模型上下文协议(MCP)服务器,为用户和待办事项提供工具、资源和提示。支持两者 标准 (当地)和 流式HTTP (云就绪)传输。本教程解释了项目结构、如何构建工具、资源和提示,以及如何与Cursor集成。
先决条件
- Node.js 18+
- npm或pnpm
快速开始
npm install
npm run dev # Run the MCP server (Streamable HTTP on port 3000)
npm run inspect # Test in MCP Inspector______________________________________________________________________
项目结构
tc_mcp_III/
├── src/
│ ├── index.ts # Entry point: Express + Streamable HTTP transport
│ ├── server.ts # MCP server factory (createMCPServer)
│ ├── entities/
│ │ ├── user.entity.ts # Zod schemas and types for users
│ │ └── todo.entity.ts # Zod schemas and types for todos
│ ├── users/
│ │ └── userHandler.ts # Business logic: create, fetch users
│ ├── tools/
│ │ └── users/
│ │ ├── createUserTool.ts # MCP tool: create-user
│ │ └── fetchUsersTool.ts # MCP tool: fetch-users
│ ├── resources/
│ │ ├── users/
│ │ │ └── usersResources.ts # MCP resource: users (read-only)
│ │ └── todo/
│ │ ├── todoResources.ts # MCP resources: todos, single-todo (template)
│ │ └── todoHandler.ts # Fetches todos from dummyjson.com
│ └── prompts/
│ └── todos/
│ └── todosPrompts.ts # MCP prompt: fetch-todo-item
├── users.json # JSON "database" for users
├── .cursor/
│ └── mcp.json # Cursor MCP configuration
├── package.json
└── tsconfig.json层职责
| 层 | 目的 |
|---|---|
| index.ts | Bootstraps Express,根据请求创建服务器,连接流式HTTP传输 |
| server.ts | 工厂 createMCPServer() 对于无状态的按请求服务器 |
| 实体/ | 共享模式(Zod)和TypeScript类型 |
| 用户/ | 独立于MCP的域逻辑(CRUD) |
| 工具/ | MCP工具定义:接线模式+处理程序 registerXxx(server) |
| 资源/ | MCP资源定义:通过URI公开的只读数据 |
| 提示/ | 人工智能交互的MCP提示模板 |
______________________________________________________________________
传输:流式HTTP
服务器使用 流式HTTP 传输,使其适合云部署(例如GCP cloud Run)。每个HTTP请求都会得到一个新的MCP服务器实例(无状态模式)。
运作原理
- Express应用程序正在监听
PORT(默认值3000) - 所有MCP流量都流向
/mcp端点 - 对于每个请求:创建服务器→ 注册工具/资源/提示→ 连接运输→ 处理→ close
// src/index.ts (simplified)
function getServer() {
const server = createMCPServer();
registerCreateUserTool(server);
registerFetchUserTool(server);
registerAllUsersResource(server);
registerAllTodoResources(server);
registerSingleTodoResource(server);
registerFetchPrompt(server);
return server;
}
app.all('/mcp', async (req, res) => {
const server = getServer();
const transport = new StreamableHTTPServerTransport();
await server.connect(transport);
await transport.handleRequest(req, res, req.body ?? {});
res.on('close', () => {
server.close();
transport.close();
});
});______________________________________________________________________
服务器工厂(src/server.ts)
服务器是根据请求创建的,以支持无状态HTTP:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function createMCPServer() {
return new McpServer(
{ name: 'emi_mcp_server', version: '1.0.0' },
{
capabilities: {
tools: {},
prompts: {},
resources: {},
tasks: {}
}
}
);
}______________________________________________________________________
注册模式
工具、资源和提示的使用 注册功能 接受服务器实例。这允许根据请求创建新服务器,并在使用前进行配置。
示例:获取用户工具
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
export function registerFetchUserTool(server: McpServer) {
server.registerTool(
'fetch-users',
{ title: '...', description: '...', inputSchema: fetchUserSchema },
async (userSearch) => ({ content: [{ type: 'text', text: JSON.stringify(foundUsers) }] })
);
}______________________________________________________________________
资源
静态资源
| 资源 | URI | 描述 |
|---|---|---|
users | users://all | 来自的所有用户 users.json |
todos | todos://all | dummyjson.com API的所有todo |
资源模板
| 资源 | URI模板 | 描述 |
|---|---|---|
single-todo | todos://{id}/single | 按ID获取单个待办事项 |
资源模板出现在 模板 MCP检查员的一部分。要阅读单个待办事项,请请求例如。 todos://5/single.
返回格式: { contents: [{ uri: string, text: string }] }
______________________________________________________________________
提示
提示是人工智能交互的可重用模板。在光标中,键入 / 在聊天中查看可用提示。
| 提示 | 参数 | 描述 |
|---|---|---|
fetch-todo-item | id (number) | 生成按ID获取待办事项的提示 |
例子: /fetch-todo-item 随着 id: 1 → *“去获取一个基于1的待办事项”*
______________________________________________________________________
将服务器添加到游标
选项A:本地(通过mcp远程进行stdio)
如果在本地运行HTTP服务器,请使用 mcp-remote 代理:
{
"mcpServers": {
"tc_mcp_iii": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/mcp"],
"cwd": "C:\\code\\MCP\\tc_mcp_III"
}
}
}选项B:直接URL(如果Cursor支持)
{
"mcpServers": {
"tc_mcp_iii": {
"url": "http://localhost:3000/mcp"
}
}
}选项C:云部署
对于部署在Cloud Run或类似平台上的服务器:
{
"mcpServers": {
"tc_mcp_iii": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://YOUR-SERVICE.run.app/mcp"]
}
}
}______________________________________________________________________
MCP检验员测试
通过URL连接(流式HTTP)
- 端子1 启动服务器:
npm run dev- 2号航站楼 –启动检查器并连接到URL:
npx @modelcontextprotocol/inspector --connect http://localhost:3000/mcp- 在检查器UI中,选择 可流式传输http 作为运输和进入
http://localhost:3000/mcp如果提示。
通过stdio连接(传统)
这 npm run inspect 脚本将服务器作为子进程生成。对于Streamable HTTP测试,请使用上面的双终端方法。
______________________________________________________________________
可用工具
| 工具 | 说明 | 必填参数 |
|---|---|---|
create-user | 创建新用户 | 姓名、电子邮件、电话(地址可选) |
fetch-users | 搜索用户 | 姓名、电子邮件、电话 |
可用资源
| 资源 | URI | 描述 |
|---|---|---|
users | users://all | 来自的所有用户 users.json |
todos | todos://all | 来自dummyjson.com的所有待办事项 |
single-todo | todos://{id}/single | 按ID列出的单个待办事项(模板) |
可用提示
| 提示 | 参数 | 描述 |
|---|---|---|
fetch-todo-item | id(number) | 生成按id获取待办事项的提示 |
______________________________________________________________________
云部署(GCP云运行)
服务器已准备好进行云部署:
- 构建和部署:
gcloud run deploy tc-mcp-server --source .- 环境: 集
PORT(Cloud Run默认使用8080)。
- 客户端配置: 将光标或检查器指向
https://YOUR-SERVICE.run.app/mcp.
- 认证: 使用
gcloud run services proxy对于本地客户,或OIDC/IAM用于生产。
看 在云端运行主机MCP服务器 了解详情。
______________________________________________________________________
故障排除
| 问题 | 解决方案 |
|---|---|
| 工具未显示 | 确保全部 registerXxx(server) 被召唤 getServer() |
| “已连接到传输” | 使用按请求服务器模式:在处理程序中创建服务器,调用 server.close() 响应关闭 |
| 检查器URL未连接 | 使用启动服务器 npm run dev 首先,然后 --connect http://localhost:3000/mcp |
| 提示不在光标中 | 类型 / 聊天;确保服务器已配置并连接 |
| 单个待办事项不在资源列表中 | 这是一个模板——检查 模板 部分,或阅读 todos://1/single 直接 |
Transport 类型错误 | 使用 transport as Transport 随着 exactOptionalPropertyTypes |
______________________________________________________________________
