博客内容Blog Content

模型上下文协议 Model Context Protocol (MCP)

BlogType : IT releaseTime : 2025-08-23 23:00:00

MCP是一种开放协议,能让AI模型能够安全地与本地和远程资源进行交互,进而让其有更强大的感知和操作能力 MCP is an open protocol that enables AI models to safely interact with both local and remote resources, thereby granting them enhanced perception and operational capabilities.

MCP概念 Model Context Protocol

https://docs.mcpcn.org/introduction

MCP 是一种开放协议,通过标准化的服务器实现,使 AI 模型能够安全地与本地和远程资源进行交互。

MCP is an open protocol that enables AI models to safely interact with both local and remote resources through a standardized server implementation.


它标准化了应用程序如何向 LLM 提供上下文。能让LLM通过接入更多外部接口有更强大的感知和操作能力

It standardizes how applications provide context to LLMs, allowing them to gain more powerful perception and operational capabilities by accessing a wider range of external interfaces.


想象一下,MCP 类似于 AI 设备的 USB-C 接口,它提供了连接不同外设和配件的标准方法,就像 USB-C 提供了连接不同外设和配件的标准方法一样。

Imagine MCP as the USB-C port for AI devices — it offers a standardized way to connect to various peripherals and accessories, just like USB-C does for hardware.




使用场景 Use Cases

  1. 智能编程体:类似cursor等,帮用户完成代码,操作本地数据

  2. 数据分析:不用手动写代码了,用自然语言让llm查库,画图等

  3. 企业知识库管理:包含文档生成、维护、管理,收发邮件等工具

  4. 自动化工作流:协调多个节点、链路、自动编排、跨系统

  5. 创意设计类工具:完成各种3d、图片等建模、ai机器人

  1. Smart Programming Agents: Similar to tools like Cursor, assisting users in writing code and interacting with local data.

  2. Data Analysis: No need to write code manually — use natural language to query databases, generate plots, and more.

  3. Enterprise Knowledge Management: Includes tools for document generation, maintenance, management, email handling, etc.

  4. Automated Workflows: Coordinate multiple nodes and links, perform automatic orchestration across systems.

  5. Creative Design Tools: Perform various 3D modeling, image editing, and AI robot design tasks.




MCP通信机制 MCP Communication Mechanisms

Stdio 标准输入输出:操作本地文件、服务进行交互,场景简单,只能单线程,对硬件有要求,配置稍微复杂

SSE(Server Sent Event):操作远程,支持多线程并发,场景通用,部署更灵活,配置更简单

Stdio (Standard Input/Output): Interacts with local files and services. Suitable for simpler scenarios, but limited to single-threading, requires specific hardware, and has slightly more complex setup.

SSE (Server-Sent Events): Operates remotely with support for multithreading and concurrency. Suitable for general-purpose scenarios, more flexible deployment, and simpler configuration.


Cursor集成本地MCP工具 Cursor Integrates Local MCP Tool

https://modelscope.cn/mcp/servers/@modelcontextprotocol/filesystem

选一个本地文件的mcp放入cursor

Select a local file MCP and add it to Cursor.


再配置里面重新加载这个本地文件功能的mcp,完成后可以看到支持的文件相关功能了

Then, reconfigure the MCP for reloading this local file feature. After setup, you’ll see the supported file-related capabilities.


测试一下让agent调用本地文件功能-读取

Test: Let the agent call local file functionality - Read


测试一下让agent调用本地文件功能-写入

Test: Let the agent call local file functionality - Write



角色分工 Role Responsibilities

  • LLM Agent:接收你的自然语言指令,决定调用哪个 MCP 工具以及参数。

    • 它是“指挥者”,不直接读写磁盘。

  • MCP 客户端(Cursor):按照 mcp.json 维护与各个 MCP 服务器的连接,并把 Agent 的工具调用转成协议请求发出去。

    • 根据 mcp.json 注册的服务器,暴露工具列表给 Agent。

  • MCP 服务器(Node.js进程):真正的“服务端”是被 npx 启动起来的那个包的可执行程序(server-filesystem)。

    • 它是一个 Node.js 程序,提供文件读写等工具,并受你配置的根目录沙箱限制。

    • npx:不是“服务器端本身”,而是“启动器”。它把你指定的包(@modelcontextprotocol/server-filesystem)下载/定位并以一个本地进程运行起来。

    • npx 只是把这个服务器进程拉起来的执行器/启动器,不负责具体文件操作。

  • LLM Agent:
    Receives your natural language commands and determines which MCP tool and parameters to use.
    It is the “orchestrator”, and does not directly read/write the disk.

  • MCP Client (Cursor):
    Maintains connections with various MCP servers based on mcp.json, and converts tool calls from the Agent into protocol requests.
    It exposes a list of tools to the Agent based on the servers registered in mcp.json.

  • MCP Server (Node.js process):
    The real “server” is the executable of the MCP package (e.g., server-filesystem) launched via npx.
    It is a Node.js program providing file read/write tools, constrained by a sandboxed root directory you configure.

  • npx:
    Not the “server itself”, but the “launcher”. It downloads/locates the specified package (@modelcontextprotocol/server-filesystem) and runs it as a local process.
    npx merely starts the server process — it does not handle actual file operations.



执行流程 Execution Flow

  1. 你在对话里给LLM Agent下达“查看/创建文件”等指令;

  2. LLM Agent 通过 MCP 协议选择 tools.filesystem 下的某个方法(如 list_directory、write_file)

  3. LLM Agent 通过 Cursor(MCP 客户端)发送指令给 Node.js进程(MCP 服务器)执行

  4. Node.js进程(MCP 服务器)执行后把结构化结果返回给 LLM Agent;

  5. Agent 用自然语言把结果呈现给你。


  1. You give a command to the LLM Agent, such as “view/create file”.

  2. The LLM Agent selects a method under tools.filesystem via the MCP protocol (e.g., list_directory, write_file).

  3. The Agent sends the command to the Node.js process (MCP server) via Cursor (MCP client).

  4. The Node.js process (MCP server) executes the request and returns a structured result to the LLM Agent.

  5. The Agent presents the result to you in natural language.


注意 Note:

  • MCP 服务器的具体工作是由你本机上启动的 MCP 服务器进程执行的,不是由 LLM 执行。

  • 当 Cursor 启动并加载 MCP 配置时,会在你的本机上通过 npx 启动一个独立的“MCP 服务器”进程(或子进程)。

  • npx 是 Node.js 生态里的“包执行器”,随 npm 一起提供(npm 5.2+ 自带)。作用是临时或就地运行一个 npm 包里提供的可执行命令,而不必全局安装它。

  • 连接复用与安全:同一会话内工具调用会复用已启动的服务器与连接;

  • The actual work of the MCP server is executed by the MCP server process running locally — not by the LLM.

  • When Cursor launches and loads the MCP configuration, it starts a separate “MCP server” process (or subprocess) on your machine via npx.

  • npx is a package runner from the Node.js ecosystem, included with npm (5.2+). It allows you to run commands from npm packages without global installation.

  • Connection reuse & security: Tool calls within the same session reuse already launched servers and established connections.




Cursor集成远程MCP工具 Cursor Integrates Remote MCP Tool

示例-接入12306接口 https://modelscope.cn/mcp/servers/@Joooook/12306-mcp

Example — Integrate the 12306 ticket service


根据我们的需要查询和规划可用车次

Use it to query and plan train available schedules according to your needs.

image.png

image.png




常用的MCP服务平台 Common MCP Service Platforms

https://github.com/modelcontextprotocol/servers

https://github.com/punkpeye/awesome-mcp-servers

https://mcp.so/

魔搭社区 https://modelscope.cn/mcp

https://smithery.ai/

https://bailian.console.aliyun.com/?tab=mcp#/mcp-market




开发自己的MCP服务 Personal MCP Server Development

有些场景LLM无法直接获取,需要自己开发MCP功能

Some scenarios cannot be directly accessed by the LLM and require developing the MCP functionality manually.


新建项目mcp-server,部署到本地8081端口,开发代码并添加描述,LLM到时会根据prompt进行相关调用

Create a new project called mcp-server, deploy it locally on port 8081, develop the relevant code, and add descriptions. The LLM will later invoke it via prompts.

@Component

@Slf4j

public class DateTool {

   @Tool(description = "Get the local current date and time in the format 'yyyy-MM-dd HH:mm:ss'")

   public String getCurrentTime() {

       log.info("Call MCP DateTool.getCurrentTime");

       String timeFormat = LocalDateTime

               .now()

               .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

       log.info("Call MCP DateTool.getCurrentTime :{}", timeFormat);

       return  timeFormat;

   }

}


配置config进行bean注入

Configure config for bean injection

@Configuration

public class ToolConfig {


   @Bean

   public ToolCallbackProvider registerToolCallbackProvider(DateTool dateTool) {

       return MethodToolCallbackProvider

               .builder()

               .toolObjects(dateTool)

               .build();

   }


}




先启动mcp-server,访问http://localhost:8081/sse

First, start the mcp-server, and access http://localhost:8081/sse


把mcp-server配置加到mcp-client

Then, add the mcp-server configuration to the mcp-client

spring:

 ai:

   mcp:

     client:

       sse:

         connections:

           my_server:

             url: http://localhost:8081

             sse-endpoint: /sse



让LLM调用这个接口

so that the LLM can call this interface.



也能和日志对应得上

This also ensures the logs can be properly matched.

但不知道其他城市时区对应的时间

But we don't know the corresponding time in other cities' time zones.



此外,我们可以开发更多函数让大模型自己推断相关参数,从而使其有更强能力

(例如给定城市,让大模型自动推断时区,然后用支持时区的API查询当前城市的时间)

In addition, we can develop more functions that allow the large model to infer related parameters on its own, thereby enhancing its capabilities.

(For example, given a city name, the model can automatically infer the time zone and then use a time zone–aware API to query the current time in that city.)


@Tool(description = "First guess the zoneId of the city, then " +

       "get the local current date and time by zoneId with format 'yyyy-MM-dd HH:mm:ss'")

public String getCurrentTimeByCity(String city, String zoneId) {

   log.info("Call MCP DateTool.getCurrentTimeByZoneId city:{}", city);

   String timeFormat = LocalDateTime

           .now(ZoneId.of(zoneId))

           .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

   log.info("Call MCP DateTool.getCurrentTimeByZoneId :{} city:{}", timeFormat, city);

   return  timeFormat;

}