实践是最好的学习,看了很多MCP的文章,还是不懂MCP干啥的,不清楚原理,不如自己搭一个,半小时,彻底掌握MCP。
今天教大家来用typescript搭建一个简单的MCP服务,纯粹用于演示功能。
这个案例不解决任何实际问题,只为直观地展示MCP的资源 (Resources)、工具 (Tools) 和 提示 (Prompts) 这三个核心概念。
实现下面几个功能:
一个资源:用于查询服务器的运行状态(获取知识)。
两个工具:一个用于回显消息,另一个用于执行简单的数学计算(执行功能)
一个提示:用于引导LLM生成口号(提示词管理)
一、项目搭建
1、项目设置 package.json
代码块 { "name": "simple-mcp-demo-server", "version": "1.0.0", "type": "module", "scripts": { "build": "tsc", "start": "node --experimental-specifier-resolution=node build/index.js" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", "zod": "^3.25.53" }, "devDependencies": { "@types/node": "^20.17.58", "typescript": "^5.8.3" } }
2、 TypeScript 配置tsconfig.json
代码块 { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
3、核心代码 (src/index.ts)
代码块 import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; // 用于定义工具和提示的输入验证schema // 1. 创建MCP服务器实例 // McpServer 是您与MCP协议的核心接口。 const server = new McpServer({ name: "Demo互动服务器", // 服务器的名称 version: "1.0.0", // 服务器的版本 capabilities: { // 声明服务器支持的能力,使客户端可以发现这些功能 resources: {}, tools: {}, prompts: {}, }, }); // 2. 暴露一个只读的“资源 (Resource)” // 资源用于向大型语言模型(LLM)暴露数据和内容,类似于Web API中的GET请求。 // 它们不应执行显著的计算或产生副作用。 server.resource( "status", // 资源的内部名称 "resource://status/server", // 资源的URI模板,这是一个固定URI,表示服务器状态 async (uri) => { // 当客户端请求此资源时,返回预设的服务器状态信息。 return { contents: [ { uri: uri.href, text: "服务器运行正常,无已知错误。自上次启动以来已处理 100 次请求。", mimeType: "text/plain" }, ],
为了更好的阅读体验,来飞书看吧:
https://kqxyky8cqrw.feishu.cn/wiki/HGM7wi5JsitfqCkCOmkcCJcLnsd
Comments on "2025/6/19 如何搭建一个MCP服务,然后在Cursor中调用,半小时,彻底掌握MCP" :