掘金 人工智能 07月07日 19:13
MCP极简入门:node+idea运行简单的MCP服务和MCP客户端
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文详细介绍了如何使用 Node.js 和 IntelliJ IDEA 构建一个简单的 MCP(Model Context Protocol)服务端和客户端。通过 TypeScript 和 @modelcontextprotocol/sdk,利用 Stdio 协议实现通信,演示了注册工具、客户端调用等核心流程,适合初学者快速入门 MCP 开发,并提供了详细的步骤和常见问题的解决方案。

💻 **项目环境准备**: 搭建 Node.js 项目,安装必要的依赖,包括 @modelcontextprotocol/sdk、zod 和 tsx,并配置 TypeScript 环境,为后续的 MCP 开发打下基础。

➕ **服务端实现**: 创建 MCP 服务端,注册加法工具,该工具接受两个数字输入并返回它们的和。服务端通过 StdioServerTransport 与客户端进行通信,展示了 MCP 服务端的基本功能。

📱 **客户端开发**: 构建 MCP 客户端,连接服务端,列出可用的工具并调用加法工具。客户端使用 StdioClientTransport 与服务端交互,实现了工具的调用和结果的获取。

⚙️ **运行与调试**: 详细介绍了在 IntelliJ IDEA 中运行服务端和客户端的步骤,包括创建运行配置和常见问题的解决方案,帮助开发者顺利运行代码并进行调试。

本文将指导你使用 Node.js 和 IntelliJ IDEA 创建并运行一个简单的 MCP(Model Context Protocol)服务端和客户端。示例使用 TypeScript 和 @modelcontextprotocol/sdk,通过 Stdio 协议实现通信。服务端提供一个加法工具,客户端列出工具并调用它。适合初学者快速入门 MCP 开发。

前提条件

项目设置

    创建项目

      打开 IntelliJ IDEA,选择 File > New > Project,选择 Node.js 项目模板。项目命名为 mcp-quickstart,选择 Node.js 版本,点击 Create。

    安装依赖

      打开终端(IDEA 底部 Terminal),运行:

       npm init -y npm install @modelcontextprotocol/sdk zod tsx --save-dev

    配置 TypeScript

      在项目根目录创建 tsconfig.json:

       {   "compilerOptions": {     "target": "ESNext",     "module": "CommonJS",     "strict": true,     "esModuleInterop": true,     "skipLibCheck": true,     "forceConsistentCasingInFileNames": true,     "outDir": "./dist"   },   "include": ["*.ts"] }

创建 MCP 服务端

创建一个简单的 MCP 服务端,提供一个加法工具。

    新建文件 McpServer.ts:

      在项目根目录创建 McpServer.ts,添加以下代码:

       import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js' import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' import { z } from 'zod'  // Create an MCP server const server = new McpServer({   name: 'demo-server',   version: '1.0.0' })  // Add an addition tool server.registerTool(   'add',   {     title: 'Addition Tool',     description: 'Add two numbers',     inputSchema: { a: z.number(), b: z.number() }   },   async ({ a, b }) => ({     content: [{ type: 'text', text: String(a + b) }]   }) )  // Add a dynamic greeting resource server.registerResource(   'greeting',   new ResourceTemplate('greeting://{name}', { list: undefined }),   {     title: 'Greeting Resource', // Display name for UI     description: 'Dynamic greeting generator'   },   async (uri, { name }) => ({     contents: [       {         uri: uri.href,         text: `Hello, ${name}!`       }     ]   }) )  // 启动服务器 async function startServer() {   try {     const transport = new StdioServerTransport()     await server.connect(transport)     console.error('MCP 服务器在 Stdio 上运行...')   } catch (error) {     console.error('服务器错误:', error)     process.exit(1)   } }  startServer().catch((error) => {   console.error('主程序错误:', error)   process.exit(1) }) 

    代码说明

      创建一个名为demo-server 的 MCP 服务器。注册一个 add 工具,接受两个数字(a 和 b),返回它们的和。使用 StdioServerTransport 通过标准输入/输出通信。

创建 MCP 客户端

创建一个客户端,连接服务端,列出工具并调用加法工具。

    新建文件 McpClient.ts:

      在项目根目录创建 McpClient.ts,添加以下代码:

       #!/usr/bin/env node import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'  // 客户端设置 const client = new Client({   name: 'example-client',   version: '1.0.0' })  // 客户端逻辑:连接服务器并与之交互 async function startClient() {   try {     // 使用命令和参数方式初始化传输层     const transport = new StdioClientTransport({       command: 'npx.cmd',       args: ['tsx', 'McpServer.ts']     })      await client.connect(transport)     console.log('已连接到 MCP 服务器:', client.serverInfo?.name || '未知')      // 列出可用工具     const toolsList = await client.listTools()     console.log(       '可用工具:',       toolsList.tools.map((t) => t.name)     )      // 调用加法工具     if (toolsList.tools.some((t) => t.name === 'add')) {       const result = await client.callTool({         name: 'add',         arguments: { a: 5, b: 3 }       })       console.log('加法结果:', result.content[0].text)     }      // 断开客户端连接     await client.close()     console.log('客户端已断开连接。')   } catch (error) {     console.error('客户端错误:', error)     process.exit(1)   } }  startClient().catch((error) => {   console.error('主程序错误:', error)   process.exit(1) }) 

    代码说明

      创建一个名为 example-client 的 MCP 客户端。使用 spawn 启动服务器进程(McpServer.ts),通过 tsx 运行。通过 StdioClientTransport 连接服务器,列出工具并调用 add 工具(输入 a=5, b=3)。包含错误处理和进程清理。

在 IntelliJ IDEA 中运行

    右键文件运行

    创建运行配置

      点击 Run > Edit Configurations。

      点击 + 添加新配置,选择 Node.js。

      设置以下字段:

        Name:MCP ClientNode interpreter:选择你的 Node.js 路径(运行 which node 确认)。TypeScript Loader: 选择Boudled(tsx),只有选择这个才能直接运行。Node parameters:留空。File:选择 node_modules/tsx/dist/cli.js(tsx 的入口)。

      保存配置。

    运行客户端

      点击 IDEA 顶部绿色三角形(Run),选择 MCP Client。

      或者在终端运行:

       npx tsx McpClient.ts

预期输出

 MCP 服务器在 Stdio 上运行... 已连接到 MCP 服务器: 未知 可用工具: [ 'add' ] 加法结果: 8 客户端已断开连接。

调试常见问题

    错误: The "path" argument must be of type string:

      确认 mcp-client.ts 中使用 spawn("npx.cmd", ["tsx", "mcp-server.ts"], { shell: true })(Windows 环境)。

      确保 tsx 已安装:

       npm install --save-dev tsx

    错误: McpError: Cannot read properties of null (reading '_def'):

      确保 @modelcontextprotocol/sdk 和 zod 版本最新:

       npm install @modelcontextprotocol/sdk@latest zod@latest

      检查 mcp-server.ts 中的 addToolSchema 是否正确定义。

    服务器名称显示“未知”

      确认 mcp-server.ts 中 McpServer 的 name 字段设置为 "example-server"。

      在客户端添加调试日志:

       console.log("服务器信息:", client.serverInfo);

总结

通过以上步骤,你在 IntelliJ IDEA 中成功搭建并运行了一个简单的 MCP 服务端和客户端。服务端提供了一个加法工具,客户端通过 Stdio 协议调用它。这个示例展示了 MCP 的核心功能,适合快速入门。你可以进一步扩展工具功能或尝试其他协议(如 WebSocket)。

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Node.js MCP IntelliJ IDEA TypeScript
相关文章