MCP协议

embedded/2025/2/26 6:36:23/

原理讲解

基础概念

Introduction - Model Context Protocol

  • MCP Host:想要通过 MCP 访问数据的程序,例如 Claude Desktop、IDE 或 AI 工具
  • MCP Clients:与服务器保持 1:1 连接的协议客户端
  • MCP Servers:轻量级程序,每个程序通过标准化模型上下文协议公开特定功能
  • Local Data Sources: MCP 服务器可以安全访问的计算机文件、数据库和服务
  • Remote Services: MCP 服务器可以通过互联网(例如,通过 API)连接的外部系统

核心组件

协议层

协议层处理消息框架,请求/响应链接和高级通信模式。

class Protocol<Request, Notification, Result> {// Handle incoming requests, 处理请求setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void// Handle incoming notifications, 处理通知, 不需要对方响应的请求setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void// Send requests and await responses, 请求request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>// Send one-way notifications, 通知notification(notification: Notification): Promise<void>
}

传输层

运输层处理客户与服务器之间的实际通信。 MCP支持多种运输机制:

  1. Stdio transport
    • 使用标准输入/输出进行通信
    • 适用于本地流程的处理
  1. HTTP with SSE transport
    • 使用服务器范围的事件进行服务器到客户消息
    • 使用 http POST方式发送消息,用于客户到服务器消息

所有运输都使用JSON-RPC 2.0交换消息。有关模型上下文协议消息格式的详细信息,请参见规格。

消息类型

MCP具有这些主要消息类型:

  1. 请求期望对方有回应:
interface Request {method: string;params?: { ... };
}
  1. 结果是对请求的成功响应:
interface Result {[key: string]: unknown;
}
  1. 错误表明请求失败:
interface Error {code: number;message: string;data?: unknown;
}
  1. 通知是单向消息,不会期望回复:
interface Notification {method: string;params?: { ... };
}

生命周期

初始化

  1. 客户以协议版本和功能发送initialize请求
  2. 服务器响应其协议版本和功能
  3. 客户将initialized通知发送为确认
  4. 正常消息交换开始

  1. init client, connect server
  2. init model, get tools, query, tool call
  3. tool result -> model
  4. model summary

尝试使用

通过mcp工具读取本地文件内容

  1. clone 官方提供的mcp服务项目:
git clone git@github.com:modelcontextprotocol/servers.git
  1. 构建本地服务:
docker build -t mcp/filesystem -f src/filesystem/Dockerfile .

  1. 镜像构建完成后, 采用LangChain4j进行测试用例构建:
package dev.langchain4j.example.mcp;import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;import java.io.File;
import java.util.List;public class McpToolsExampleOverStdio {// We will let the AI read the contents of this file/*** This example uses the `server-filesystem` MCP server to showcase how* to allow an LLM to interact with the local filesystem.* <p>* Running this example requires npm to be installed on your machine,* because it spawns the `server-filesystem` as a subprocess via npm:* `npm exec @modelcontextprotocol/server-filesystem@0.6.2`.* <p>* Of course, feel free to swap out the server with any other MCP server.* <p>* The communication with the server is done directly via stdin/stdout.* <p>* IMPORTANT: when executing this, make sure that the working directory is* equal to the root directory of the project* (`langchain4j-examples/mcp-example`), otherwise the program won't be able to find* the proper file to read. If you're working from another directory,* adjust the path inside the StdioMcpTransport.Builder() usage in the main method.*/public static void main(String[] args) throws Exception {ChatLanguageModel model = OpenAiChatModel.builder().apiKey(System.getenv("OPENAI_API_KEY")).baseUrl(System.getenv("OPENAI_API_URL")).modelName("gpt-4o-mini").logRequests(true).logResponses(true).build();McpTransport transport = new StdioMcpTransport.Builder().command(List.of("docker", "run", "-i", "--rm","--mount", "type=bind,src=/Users/louye/fun-project/langchain4j-examples/mcp-example/src/main/resources,dst=/projects","mcp/filesystem","/projects")).logEvents(true).build();McpClient mcpClient = new DefaultMcpClient.Builder().transport(transport).build();ToolProvider toolProvider = McpToolProvider.builder().mcpClients(List.of(mcpClient)).build();Bot bot = AiServices.builder(Bot.class).chatLanguageModel(model).toolProvider(toolProvider).build();try {String response = bot.chat("修改文件 /projects/file.txt 的内容, 将内容修改为: Hello, world!");System.out.println("RESPONSE: " + response);} finally {mcpClient.close();}}
}

参考文档: https://github.com/modelcontextprotocol/servers/blob/main/src/filesystem/README.md

实际上McpTransport 就是帮用户通过特定的命令进行启动MCP的server服务器


http://www.ppmy.cn/embedded/167217.html

相关文章

基于Python+django+mysql旅游数据爬虫采集可视化分析推荐系统

2024旅游推荐系统爬虫可视化&#xff08;协同过滤算法&#xff09; 基于Pythondjangomysql旅游数据爬虫采集可视化分析推荐系统 有文档说明 部署文档 视频讲解 ✅️基于用户的协同过滤推荐算法 卖价就是标价~ 项目技术栈 Python语言、Django框架、MySQL数据库、requests网络爬虫…

开源测试_POmronFINSTCP

常用功能 EtherNetPLC PlcLink new EtherNetPLC(); //连接PLC&#xff0c;成功为0&#xff0c;不成功为非0 short linkSuccess PlcLink.Link(Para.IP, (short)Para.Port, Para.TimeOut); string address "D3000"; //读取PLC寄存器&#xff0c;成功为0&#xff0c…

05-1基于vs2022的c语言笔记——运算符

目录 前言 5.运算符和表达式 5-1-1 加减乘除运算符 1.把变量进行加减乘除运算 2.把常量进行加减乘除运算 3.对于比较大的数&#xff08;往数轴正方向或者负方向&#xff09;&#xff0c;要注意占位符的选取 4.浮点数的加减乘除 5-1-2取余/取模运算符 1.基本规则 2.c语…

uni-app 登录成功后自动跳转至登录前页面(H5\微信小程序)

uni-app 登录成功后自动跳转至登录前页面 一、新建配置文件&#xff0c;位于根目录下&#xff0c;config.js // 应用全局配置 module.exports {// 应用信息appInfo: {loginPage: "/pages/login",cacheRouteKey: "unLoginTargetRoute"// 更多配置项...}/…

嵌入式人工智能应用-第四章 支持向量机 9

文章目录 1 支持向量机(Support Vector Machine, SVM)1.1 背景介绍1.1.1 线性可分1.1.3 最大间隔超平面1.1.4 支持向量1.2 支持向量机问题描述1.3 线性SVM的算法的数学建模1.3.1 决策面方程1.3.2 分类“间隔计算模型”1.3.3 常见核函数1.4 支持向量机的优缺点1.4.1 优点1.4.2…

python-leetcode-字符串解码

394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; class Solution:def decodeString(self, s: str) -> str:stack []num 0curr_str ""for char in s:if char.isdigit():num num * 10 int(char)elif char [:stack.append((curr_str, num))curr_str, …

DeepSeek赋能机器人革命:从推理引擎到行业落地的全栈技术实践

——解析大模型如何重塑机器人产业的智能化未来 引言:机器人产业的技术范式转移 在2025年全球机器人市场规模突破2000亿美元的关键节点,DeepSeek凭借其创新的"推理优先"技术架构,正在重构机器人产业的智能化路径。通过将大模型的认知推理能力与机器人执行系统深…

神经网络 - 神经元

人工神经元(Artificial Neuron)&#xff0c;简称神经元(Neuron)&#xff0c;是构成神经网络的基本单元&#xff0c;其主要是模拟生物神经元的结构和特性&#xff0c;接收一组输入信号并产生输出。 生物学家在 20 世纪初就发现了生物神经元的结构。一个生物神经元通常具有多个树…