【入門】使用Node.js開發一個MCP服務器
介紹
一個小小后端碼農,研究了一下午,終于搞明白怎么開發一個nodeJs的MCP服務器,特寫成一篇粗略的博客,供大家參考。
MCP 是什么?
MCP(Model Control Protocol)是一個標準化接口協議,用于定義AI工具的功能和參數格式。它允許AI以標準方式調用各種工具,例如通過定義參數格式(如城市名稱)來獲取城市天氣信息。當用戶請求查詢北京天氣時,AI會按照MCP標準參數格式組裝參數,調用MCP服務器執行相應功能,并處理返回結果。
開發MCP服務器(Node.js方式)
提示:首先需要下載安裝nodeJs
下邊我將帶你開發一個簡單的MCP服務器:
文件結構

package.json 文件:
{
"name": "mcp-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.20.2",
"zod": "^3.23.8"
},
"type": "module"
}
demo-server.js:
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "demo_service",
version: "1.0.0"
});
server.tool(
"say_hello",
{
needShowMeText: z.string().describe("想要展示的話")
},
async ({ needShowMeText }) => {
try {
// 返回成功響應
return {
content: [{ type: "text", text: 'Hello =>' + needShowMeText }]
};
} catch (error) {
// 錯誤處理
return {
content: [{ type: "text", text: `失敗: ${error.message}` }],
isError: true
};
}
}
);
async function main() {
try {
console.log("MCP服務器啟動中...");
const transport = new StdioServerTransport();
await server.connect(transport);
console.log("MCP服務器已啟動并等待連接");
} catch (error) {
console.error("啟動服務器時出錯:", error);
process.exit(1);
}
}
main();
在根目錄下,cmd 命令框輸入 npm install 進行安裝相關依賴:

使用node ./dist/demo-service.js 測試是否可以啟動成功

使用官方工具測試
使用 mcp-inspector 進行測試,打開新終端輸入以下命令:
npx @modelcontextprotocol/inspector

按圖中步驟輸入各項參數:


看到Tool Result: Success便成功了
Qoder、IDEA等代碼編輯器集成MCP服務器
打開 文件 -> 首選項 -> Qoder 設置 -> MCP服務 -> +添加
{
"mcpServers": {
"mcp本地測試3": {
"name": "mcp本地測試3",
"command": "node",
"args": [
"G:\\Dev\\Code\\TestSource\\mcp-test\\dist\\demo-server.js"
]
}
}
}

這樣MCP安裝便成功了!
使用
新建會話窗口,輸入 使用 say_hello 工具告訴我world

總結
MCP 有什么作用呢?我個人理解的是它可以更加精準控制程序的中間執行過程,準確地獲取數據,然后使用AI能力進行分析。比如,我們需要獲取北京今天的天氣,如果沒有MCP服務器,服務器可能會從海量的網頁中尋找數據/接口,我們無法控制最終獲取的結果。如果我們不能控制數據源的準確性,那么后續的分析過程也沒有任何意義。
MCP服務就是封裝了一個個接口的服務器,我們可以從接口獲取我們想要的準確數據,然后通過AI的理解能力,幻化出各種各樣的效果,MCP服務器開發過程,就是按MCP標準封裝一個個接口。
本文來自博客園,作者:帥氣的濤啊,轉載請注明原文鏈接:http://www.rzrgm.cn/handsometaoa/p/19188458

浙公網安備 33010602011771號