Skip to content

MCP-可跨进程调用的tool ​

一、什么是MCP ​

1.1 MCP简介 ​

  • MCP = Model Context Protocol(模型上下文协议),是 Anthropic 在 2024 年 11 月推出的开放标准,用来给大模型(LLM)应用接外部数据、工具、业务系统的一套“统一插头”。

最流行的类比:AI 世界的 USB-C。以前每个 AI 应用连每个系统都要单独写代码,现在只要双方都支持 MCP,就能按同一套规则互相发现、传上下文、调工具。

1.2 解决了什么问题 ​

  • 没有 MCP 时,N 个 AI 客户端 × M 个数据源 = N×M 套定制集成(每个数据库、文件系统、SaaS 都要单独接一次)。

1.2.1 命令执行流程 ​

  • stdio是标准输入输出流,也就是键盘输入、控制台输出,也是跑一个子进程的时候的通讯方式

1.2.2 Http链接服务 ​

1.2.3 MCP ​

  • 有了 MCP 后:
    • 客户端(Claude、ChatGPT、Cursor、VS Code 等)实现一次 MCP Client
    • 服务端(数据库 / 文件系统 / GitHub / 日历 / 内部 API)实现一次 MCP Server
    • 总集成量从 N×M 降到 N+M

在tool函数里面,调用了MCP Client,访问远程MCP Server,本质上还是tool,但是却集成了MCP工具

二、实现简易的MCP服务 ​

2.1 @modelcontextprotocol/sdk ​

  • @modelcontextprotocol/sdk 是 MCP 的官方 TypeScript SDK(repo:modelcontextprotocol/typescript-sdk,MCP 官方 Tier 1 SDK),在 npm 上的包名就是 @modelcontextprotocol/sdk。它完整实现了 MCP 规范,让你用 JS/TS 一套代码同时写 MCP Server(暴露工具/资源/提示给 LLM)和 MCP Client(连任意 MCP Server 拿能力),是 Claude Desktop、Cursor、Zed 等客户端在 Node/Bun/Deno 侧最常消费的包。

2.2 安装依赖 ​

bash
pnpm add @modelcontextprotocol/sdk

2.3 实现简单的MCP ​

  • src/my-mcp-server.mjs
mjs
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio"
import z from "zod"

const database = {
  users: {
    "001": {id: '001', name: '张三', email: 'zhangsan@example.com', role: 'admin'},
    "002": {id: '002', name: '李四', email: 'lisi@example.com', role: 'user'},
    "003": {id: '003', name: '王五', email: 'wangwu@example.com', role: 'user'}
  }
}
// 新建一个mcp server实例
const server = new McpServer({
  name: 'my-mcp-server',
  version: '1.0.0'
})

// 注册工具,生命name=query_user,description和schema内容
server.registerTool('query_user', {
  description: '查询数据库中的用户信息,输入用户的ID,返回该用户的详细信息,如姓名、邮箱、角色',
  inputSchema: {
    userId: z.string().describe('用户ID,例如001,002,003')
  }
}, async ({ userId }) => {
  const user = database.users[userId];
  if (!user) {
    return {
      content: [
        { type: 'text', text: `用户ID ${userId} 信息不存在,可用的ID为001,002,003` }
      ]
    }
  }
  return {
    content: [
      {
        type: 'text',
        text: `用户信息:\n- ID: ${user.id}\n- 姓名:${user.name}\n- 邮箱:${user.email}\n- 用户角色:${user.role}`
      }
    ]
  }
})
// 注册静态数据资源
server.registerResource('使用指南', 'docs://guide', {
  description: 'MCP Server使用文档',
  mimeType: 'text/plain'
}, async () => {
  return {
    contents: [
      {
        uri: 'docs://guide',
        mimeType: 'text/plain',
        text: `MCP Server 使用指南
        功能:提供用户查询等工具
        使用:在Cursor等Mcp Client中通过自然语言对话,Cursor会自动调用对应工具。
        `
      }
    ]
  }
})
// stdio的transport传输方式
const transport = new StdioServerTransport();
await server.connect(transport)

2.4 修复sdk导入问题 ​

SDK 的 exports 映射在 ESM 下不会自动补 .js 扩展名

  • src/my-mcp-server.mjs
diff
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp"
-import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio"
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import z from "zod"

const database = {
  users: {
    "001": {id: '001', name: '张三', email: 'zhangsan@example.com', role: 'admin'},
    "002": {id: '002', name: '李四', email: 'lisi@example.com', role: 'user'},
    "003": {id: '003', name: '王五', email: 'wangwu@example.com', role: 'user'}
  }
}
// 新建一个mcp server实例
const server = new McpServer({
  name: 'my-mcp-server',
  version: '1.0.0'
})

// 注册工具,生命name=query_user,description和schema内容
server.registerTool('query_user', {
  description: '查询数据库中的用户信息,输入用户的ID,返回该用户的详细信息,如姓名、邮箱、角色',
  inputSchema: {
    userId: z.string().describe('用户ID,例如001,002,003')
  }
}, async ({ userId }) => {
  const user = database.users[userId];
  if (!user) {
    return {
      content: [
        { type: 'text', text: `用户ID ${userId} 信息不存在,可用的ID为001,002,003` }
      ]
    }
  }
  return {
    content: [
      {
        type: 'text',
        text: `用户信息:\n- ID: ${user.id}\n- 姓名:${user.name}\n- 邮箱:${user.email}\n- 用户角色:${user.role}`
      }
    ]
  }
})
// 注册静态数据资源
server.registerResource('使用指南', 'docs://guide', {
  description: 'MCP Server使用文档',
  mimeType: 'text/plain'
}, async () => {
  return {
    contents: [
      {
        uri: 'docs://guide',
        mimeType: 'text/plain',
        text: `MCP Server 使用指南
        功能:提供用户查询等工具
        使用:在Cursor等Mcp Client中通过自然语言对话,Cursor会自动调用对应工具。
        `
      }
    ]
  }
})
// stdio的transport传输方式
const transport = new StdioServerTransport();
await server.connect(transport)

2.5 在vscode中配置mcp服务 ​

  • .vscode/mcp.json
json
{
  "servers": {
    "my-mcp-server": {
      "type": "stdio",
      "command": "node",
      "args": ["d:/ai/tool-test/src/my-mcp-server.mjs"]
    }
  }
}

2.6 在copilot中调用mcp服务 ​

txt
- 查询用户 002 的信息

我来调用 MCP 工具查询用户 002 的信息:

✅ 已通过 my-mcp-server 的 query_user 工具查询到用户 002 的信息:

用户信息:
- ID: 002
- 姓名:李四
- 邮箱:lisi@example.com
- 用户角色:user

李四是一位普通用户(user 角色),邮箱为 lisi@example.com。

2.7 调用流程 ​

2.8 在langchain调用mcp server ​

2.8.1 @langchain/mcp-adapters ​

  • @langchain/mcp-adapters提供了一个轻量级的封装器,使人因模型上下文协议 (MCP)工具与LangChain.js和LangGraph.js兼容。

2.8.2 调用脚本 ​

  • src/langchain-mcp-test.mjs
mjs
import { HumanMessage, ToolMessage } from '@langchain/core/messages';
import { MultiServerMCPClient } from '@langchain/mcp-adapters';
import { ChatOpenAI } from '@langchain/openai';
import chalk from 'chalk';
import 'dotenv/config'

const model = new ChatOpenAI({
  modelName: process.env.OPENAI_MODEL,
  apiKey: process.env.OPENAI_API_KEY,
  configuration: {
    baseURL: process.env.OPENAI_API_BASE
  },
  temperature: 0
});

const mcpClient = new MultiServerMCPClient({
  mcpServers: {
    'my-mcp-server': {
      command: 'node',
      args: ['d:/ai/tool-test/src/my-mcp-server.mjs']
    }
  }
})

const tools = await mcpClient.getTools();
const modalWithTools = model.bindTools(tools);

async function runAgentWithTools(query, maxIterations = 30) {
  const messages = [new HumanMessage(query)]
  for (let i = 0; i < maxIterations; i++) {
    console.log(chalk.bgGreen(`⌛️正在等待AI思考……`))
    const response = await modalWithTools.invoke(messages);
    messages.push(response);
    // 检查是否有工具调用
    if (!response.tool_calls || response.tool_calls.length === 0) {
      console.log(`\n🌟AI最终回复:\n${response.content}\n`)
      return response.content
    }
    console.log(chalk.bgBlue(`🔍️检测到${response.tool_calls.length}个工具调用`))
    console.log(chalk.bgBlue(`🔍️工具调用:${response.tool_calls.map(t => t.name).join(', ')}`));
    // 执行工具调用
    for (const toolCall of response.tool_calls) {
      const foundTool = tools.find(t => t.name === toolCall.name);
      if (foundTool) {
        const toolResult = await foundTool.invoke(toolCall.args);
        messages.push(new ToolMessage({ content: toolResult, tool_call_id: toolCall.id }))
      }
    }
  }
  return messages[messages.length - 1].content
}

await runAgentWithTools("查一下用户003的信息")

2.8.3 输出结果 ​

txt
⌛️正在等待AI思考……
🔍️检测到1个工具调用
🔍️工具调用:query_user
⌛️正在等待AI思考……

🌟AI最终回复:
用户003的信息如下:

- **ID**:003
- **姓名**:王五
- **邮箱**:wangwu@example.com
- **用户角色**:user

请问还需要查询其他用户吗?

2.9 遍历读取uri内容 ​

2.9.1 src/langchain-mcp-test.mjs ​

mjs
import { HumanMessage, ToolMessage } from '@langchain/core/messages';
import { MultiServerMCPClient } from '@langchain/mcp-adapters';
import { ChatOpenAI } from '@langchain/openai';
import chalk from 'chalk';
import 'dotenv/config'

const model = new ChatOpenAI({
  modelName: process.env.OPENAI_MODEL,
  apiKey: process.env.OPENAI_API_KEY,
  configuration: {
    baseURL: process.env.OPENAI_API_BASE
  },
  temperature: 0
});

const mcpClient = new MultiServerMCPClient({
  mcpServers: {
    'my-mcp-server': {
      command: 'node',
      args: ['d:/ai/tool-test/src/my-mcp-server.mjs']
    }
  }
})

const res = await mcpClient.listResources();
for (const [serverName, resources] of Object.entries(res)) {
  for (const resource of resources) {
    const content = await mcpClient.readResource(serverName, resource.uri);
    console.log(content)
  }
}
await mcpClient.close();

2.9.2 输出 ​

txt
[
  {
    uri: 'docs://guide',
    mimeType: 'text/plain',
    text: 'MCP Server 使用指南\n' +
      '        功能:提供用户查询等工具\n' +
      '        使用:在Cursor等Mcp Client中通过自然语言对话,Cursor会自动调用对应工具。\n' +
      '        ',
    blob: undefined
  }
]

2.10 使用指南 ​

2.10.1 src/langchain-mcp-test.mjs ​

mjs
import { HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
import { MultiServerMCPClient } from '@langchain/mcp-adapters';
import { ChatOpenAI } from '@langchain/openai';
import chalk from 'chalk';
import 'dotenv/config'

const model = new ChatOpenAI({
  modelName: process.env.OPENAI_MODEL,
  apiKey: process.env.OPENAI_API_KEY,
  configuration: {
    baseURL: process.env.OPENAI_API_BASE
  },
  temperature: 0
});

const mcpClient = new MultiServerMCPClient({
  mcpServers: {
    'my-mcp-server': {
      command: 'node',
      args: ['d:/ai/tool-test/src/my-mcp-server.mjs']
    }
  }
})

let resourceContent = ''
const res = await mcpClient.listResources();
for (const [serverName, resources] of Object.entries(res)) {
  for (const resource of resources) {
    const content = await mcpClient.readResource(serverName, resource.uri);
    resourceContent += content[0].text;
  }
}

const tools = await mcpClient.getTools();
const modalWithTools = model.bindTools(tools);

async function runAgentWithTools(query, maxIterations = 30) {
  const messages = [new SystemMessage(resourceContent), new HumanMessage(query)]
  for (let i = 0; i < maxIterations; i++) {
    console.log(chalk.bgGreen(`⌛️正在等待AI思考……`))
    const response = await modalWithTools.invoke(messages);
    messages.push(response);
    // 检查是否有工具调用
    if (!response.tool_calls || response.tool_calls.length === 0) {
      console.log(`\n🌟AI最终回复:\n${response.content}\n`)
      return response.content
    }
    console.log(chalk.bgBlue(`🔍️检测到${response.tool_calls.length}个工具调用`))
    console.log(chalk.bgBlue(`🔍️工具调用:${response.tool_calls.map(t => t.name).join(', ')}`));
    // 执行工具调用
    for (const toolCall of response.tool_calls) {
      const foundTool = tools.find(t => t.name === toolCall.name);
      if (foundTool) {
        const toolResult = await foundTool.invoke(toolCall.args);
        messages.push(new ToolMessage({ content: toolResult, tool_call_id: toolCall.id }))
      }
    }
  }
  return messages[messages.length - 1].content
}

await runAgentWithTools("MCP Server的使用指南是什么")

await mcpClient.close();

2.10.2 输出 ​

markdown
# MCP Server 使用指南

根据当前环境,这里为您整理 MCP Server 的使用说明:

## 📌 功能概览

当前 MCP Server 提供 **用户信息查询** 工具,可以查询数据库中的用户详细信息。

## 🛠️ 可用工具

### `query_user`(查询用户信息)
- **功能**:输入用户的 ID,返回该用户的详细信息,如姓名、邮箱、角色
- **参数**:`userId`(用户ID,例如 001、002、003)

## 💬 使用方式

**在 Cursor 等 MCP Client 中,您无需手动调用工具**,只需通过自然语言对话即可。

### 使用示例

您可以这样提问:

> "帮我查询用户 001 的信息"
> 
> "查一下用户 002 的邮箱是什么"
> 
> "用户 003 的角色是什么?"

Cursor 等客户端会自动识别您的意图,并**自动调用对应的工具**来查询数据,然后将结果返回给您。

## ✅ 总结

| 项目 | 说明 |
|------|------|
| 使用环境 | Cursor 等 MCP Client |
| 交互方式 | 自然语言对话(无需手动调用) |
| 支持工具 | `query_user`(按用户ID查询信息) |
| 数据返回 | 姓名、邮箱、角色等用户详情 |

如果您想实际测试一下,可以直接告诉我一个用户 ID(如 001、002 或 003),我就可以帮您查询该用户的信息!需要我试试吗? 😊