深入解析MCP:从Function Calling到工具调用的标准化革命

理论基础

RAG 是为了让大模型(LLM)获取足够的上下文,Function Calling 是为了让模型使用工具。

Agent是为了解决LLM作为工具的辅助场景,能够通过拆分任务等直接解决问题,而不是辅助。

AI应用是一个很宽泛的概念,指的是任何集成了人工智能技术来解决特定问题的软件或程序。Agent是AI 应用的子集。Cursor是AI应用,但核心驱动是用户,可以说是"弱Agent"(不过也有Agent模型支持Cursor自主动编程)。--来自Deepseek

RAG

RAG(Retrieval Augmented Generation ,**检索增强生成**),可以不需要训练和微调大模型,**只需要提供和用户提问相关的额外的信息到提示词中,从而可以获得更高质量的回答**。

图片来源:www.dailydoseofds.com/16-techniqu...

通常,需要将资料通过嵌入模型生成服务转化为向量 ,然后存储到向量数据库中。

用户提问时,将用户的问题向量化从向量数据库中进行相似度匹配出 TOP N 个片段拼接成新的提示词 发送给大模型,大模型就可以结合你的资料更好地回答问题

RAG 还有很多变种,如 Agentic RAG 、Modular RAG、Graph RAG 等多种高级形式。


Function Calling

Function Calling (函数调用) 是一种允许大型语言模型(LLM)根据用户输入识别它需要的工具并决定何时调用该工具的机制。

图片来源:ailydoseofds

基本工作原理如下:LLM 接收用户的提示词,LLM 决定它需要的工具,响应Function call,AI应用(如cursor)执行方法调用,后端服务执行实际的请求给出处理结果,大语言模型根据处理结果生成最终给用户的回答

从AI应用(如cursor)出发,不同的 API 需要封装成不同的方法提供给不同LLM调用,通常需要编写代码,很难在不同的LLM平台灵活复用。

传统架构的荒谬之处(来自deepseek):

在传统Function Calling中,AI应用要同时适配上游的LLM下游的工具服务,如下代码

java 复制代码
# AI应用代码 - 承担了所有适配工作
class AIClient:
    def __init__(self):
        # 适配不同LLM
        self.llm_adapters = {
            'openai': OpenAIToolAdapter(),
            'anthropic': AnthropicToolAdapter(), 
            'google': GoogleToolAdapter()
        }
        
        # 适配不同天气服务
        self.weather_adapters = {
            'accuweather': AccuWeatherAdapter(),
            'weather_com': WeatherComAdapter(),
            'openweather': OpenWeatherAdapter()
        }
    
    async def process_query(self, user_input: str, llm_provider: str):
        # 1. 向上游适配:将工具转换成LLM能理解的格式
        llm_adapter = self.llm_adapters[llm_provider]
        tools_config = llm_adapter.convert_tools(self.available_tools)
        
        # 2. 调用LLM
        llm_response = await llm_adapter.call_llm(user_input, tools_config)
        
        # 3. 解析LLM的决策
        tool_calls = llm_adapter.parse_response(llm_response)
        
        # 4. 向下游适配:调用具体的工具服务
        for tool_call in tool_calls:
            if tool_call.name == 'get_weather':
                weather_adapter = self.weather_adapters['accuweather']
                result = await weather_adapter.get_weather(tool_call.arguments['city'])
        
        return result

MCP解决了AI应用(如Cursor)适配下游工具的工作,之前有N个工具需要适配N次,现在无需适配。

参见百炼函数调用文档:help.aliyun.com/zh/model-st...


为什么不是LLM去适配不同的天气应用之类的,而是AI应用:(****来自deepseek)

1、LLM的商业价值:LLM厂商说:"我们的价值是智能决策 ,不是服务集成"

2、LLM的局限性:本身无法直接调用API,LLM只能输出:"我应该调用天气API,参数是{city: '北京'}",但无法实际执行这个HTTP请求。这也是为什么需要Agent的出现。

MCP

模型上下文协议Model Context Protocol ,简称MCP)是一个由 Anthropic 在 2024.11.25 开源的新标准 。MCP 是一个开放标准旨在连接AI助手(Agent)与数据所在的系统,如内容存储库、业务工具和开发环境。

MCP 可以看作是 AI 应用程序的 "USB-C端口" 。就像 USB-C 为连接设备与各种外设提供了标准化方式,MCP为 AI 模型连接不同数据源和工具提供了标准化方法

图片来源:ailydoseofds

MCP的核心

从技术角度看,MCP 遵循客户端-服务器架构,其中主机应用可以连接到多个服务器。

MCP 有三个关键组件:

  • 主机(Host):代表任何提供 AI 交互环境的应用程序(如 Claude 桌面版、Cursor),它能访问工具和数据,并运行 MCP 客户端。
  • 客户端(Client):在主机内运行,使其能与 MCP 服务器通信。
  • 服务器(Server):暴露特定功能并提供数据访问,例如: Tools/Resource/Promote
    • 工具:使 LLM 能通过服务器执行操作
    • 资源:向 LLM 公开服务器中的数据和内容
    • 提示:创建可重用的提示模板和工作流
MCP 相比传统 API 的优势

传统 API :

图片来源:ailydoseofds

  • 如果 API 最初需要两个参数(例如天气服务的位置和日期),用户集成应用程序会发送带有这些确切参数的请求
  • 如果后来添加第三个必需参数(例如温度单位,如摄氏度或华氏度),API的合约就会改变。
  • 这意味着所有 API 用户必须更新代码以包含新参数。如果不更新,请求可能失败、返回错误或提供不完整结果。

MCP 的设计解决了这个问题:

  • MCP 引入了与传统 API 截然不同的动态灵活方法

  • 当客户端(如 Claude 桌面版)连接到 MCP 服务器(如您的天气服务)时,它发送初始请求以了解服务器的能力

  • 服务器响应其可用工具、资源、提示和参数的详细信息。例如,如果您的天气 API 最初支持位置和日期,服务器会将这些作为其功能的一部分进行通信。

  • 如果您稍后添加单位参数,MCP 服务器可以在下一次交换期间动态更新其功能描述。客户端不需要硬编码或预定义参数---只需查询服务器的当前功能并相应地适应
  • 这样,客户端可以及时调整其行为,使用更新的功能(例如在请求中包含单位),无需重写或重新部署代码。

图源:www.latent.space/p/why-mcp-w...

其实,MCP 也是用了 "中间层"的思想,让大模型使用工具标准化,让大模型调用工具更方便,焕发出新的生机。

MCP 简易过程

图片来源:ailydoseofds

首先需要在主机上自动或手动配置 MCP 服务

java 复制代码
{
  "mcpServers": {
    "weather-server": {
      "url": "https://api.example.com/weather-mcp",
      "transport": "sse" // 或 "streamable-http"
    }
  }
}

MCP Client初始话,会通过这个文件 与所有MCP Server建立连接。在真正服务前,会进行"工具发现"(通过tools/list获取MCP Server所有工具列表)

当用户输入问题时, MCP 客户端 会 让 大语言模型选择 MCP 工具,大模型选择好 MCP 工具以后,,MCP 客户端会请求 MCP 服务器(JSON-RPC请求), MCP 服务调用(通过SSE或Streamable HTTP协议)工具并将工具的结果返回给 MCP 客户端, MCP 客户端将模型调用结果和用户的查询发送给大语言模型,大语言模型组织答案给用户。

其实 RAG 、Function Call 和 MCP 本质上都是一样,都是为了借助外部工具帮助大模型完成更复杂的事情。

mcp 请求详细信息

Cherry Studio 开启 开发者模式

输入想要问的问题,开启需要的 MCP 服务。

为了看见 MCP 的执行过程,还需要通过 Ctrl+Shift+I(Mac端:Command+Option+I)打开开发者模式。

第一次请求,发送系统提示词,包括大模型可以选择的工具和要求等,然后给出用户的问题。

内部必然通过MCP请求了MCP Server,不过这里没有显示

可以看到第二次调用,获取内容返回给用户,即 模型选择使用 infoq 工具获得资讯后组织语言展示给用户

第三次调用主要是为了给话题起标题。
针对第二次调用**模型选择使用 infoq 工具后的请求内容后组织语言展示给用户:**

  1. index =0 的系统提示词的内容(工具内容等发送给LLM):
java 复制代码
{
  "role": "system",
  "content": "In this environment you have access to a set of tools you can use to answer the user's question. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.\n\n## Tool Use Formatting\n\nTool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:\n\n<tool_use>\n  <name>{tool_name}</name>\n  <arguments>{json_arguments}</arguments>\n</tool_use>\n\nThe tool name should be the exact name of the tool you are using, and the arguments should be a JSON object containing the parameters required by that tool. For example:\n<tool_use>\n  <name>python_interpreter</name>\n  <arguments>{\"code\": \"5 + 3 + 1294.678\"}</arguments>\n</tool_use>\n\nThe user will respond with the result of the tool use, which should be formatted as follows:\n\n<tool_use_result>\n  <name>{tool_name}</name>\n  <result>{result}</result>\n</tool_use_result>\n\nThe result should be a string, which can represent a file or any other output type. You can use this result as input for the next action.\nFor example, if the result of the tool use is an image file, you can use it in the next action like this:\n\n<tool_use>\n  <name>image_transformer</name>\n  <arguments>{\"image\": \"image_1.jpg\"}</arguments>\n</tool_use>\n\nAlways adhere to this format for the tool use to ensure proper parsing and execution.\n\n## Tool Use Examples\n\nHere are a few examples using notional tools:\n---\nUser: Generate an image of the oldest person in this document.\n\nAssistant: I can use the document_qa tool to find out who the oldest person is in the document.\n<tool_use>\n  <name>document_qa</name>\n  <arguments>{\"document\": \"document.pdf\", \"question\": \"Who is the oldest person mentioned?\"}</arguments>\n</tool_use>\n\nUser: <tool_use_result>\n  <name>document_qa</name>\n  <result>John Doe, a 55 year old lumberjack living in Newfoundland.</result>\n</tool_use_result>\n\nAssistant: I can use the image_generator tool to create a portrait of John Doe.\n<tool_use>\n  <name>image_generator</name>\n  <arguments>{\"prompt\": \"A portrait of John Doe, a 55-year-old man living in Canada.\"}</arguments>\n</tool_use>\n\nUser: <tool_use_result>\n  <name>image_generator</name>\n  <result>image.png</result>\n</tool_use_result>\n\nAssistant: the image is generated as image.png\n\n---\nUser: \"What is the result of the following operation: 5 + 3 + 1294.678?\"\n\nAssistant: I can use the python_interpreter tool to calculate the result of the operation.\n<tool_use>\n  <name>python_interpreter</name>\n  <arguments>{\"code\": \"5 + 3 + 1294.678\"}</arguments>\n</tool_use>\n\nUser: <tool_use_result>\n  <name>python_interpreter</name>\n  <result>1302.678</result>\n</tool_use_result>\n\nAssistant: The result of the operation is 1302.678.\n\n---\nUser: \"Which city has the highest population , Guangzhou or Shanghai?\"\n\nAssistant: I can use the search tool to find the population of Guangzhou.\n<tool_use>\n  <name>search</name>\n  <arguments>{\"query\": \"Population Guangzhou\"}</arguments>\n</tool_use>\n\nUser: <tool_use_result>\n  <name>search</name>\n  <result>Guangzhou has a population of 15 million inhabitants as of 2021.</result>\n</tool_use_result>\n\nAssistant: I can use the search tool to find the population of Shanghai.\n<tool_use>\n  <name>search</name>\n  <arguments>{\"query\": \"Population Shanghai\"}</arguments>\n</tool_use>\n\nUser: <tool_use_result>\n  <name>search</name>\n  <result>26 million (2019)</result>\n</tool_use_result>\nAssistant: The population of Shanghai is 26 million, while Guangzhou has a population of 15 million. Therefore, Shanghai has the highest population.\n\n\n## Tool Use Available Tools\nAbove example were using notional tools that might not exist for you. You only have access to these tools:\n<tools>\n\n<tool>\n  <name>f_u-LsDUyQWsNFAUjL-_Vi</name>\n  <description>获取 36 氪热榜,提供创业、商业、科技领域的热门资讯,包含投融资动态、新兴产业分析和商业模式创新信息</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"type\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"hot\",\"description\":\"人气榜\"},{\"type\":\"string\",\"const\":\"video\",\"description\":\"视频榜\"},{\"type\":\"string\",\"const\":\"comment\",\"description\":\"热议榜\"},{\"type\":\"string\",\"const\":\"collect\",\"description\":\"收藏榜\"}],\"default\":\"hot\",\"description\":\"分类\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fyQ3DOUpLJDGPLCjslT6P1</name>\n  <description>获取 9to5Mac 苹果相关新闻,包含苹果产品发布、iOS 更新、Mac 硬件、应用推荐及苹果公司动态的英文资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fBOukVLVbqIh69earzcYca</name>\n  <description>获取 BBC 新闻,提供全球新闻、英国新闻、商业、政治、健康、教育、科技、娱乐等资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"category\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"\",\"description\":\"热门新闻\"},{\"type\":\"string\",\"const\":\"world\",\"description\":\"国际\"},{\"type\":\"string\",\"const\":\"uk\",\"description\":\"英国\"},{\"type\":\"string\",\"const\":\"business\",\"description\":\"商业\"},{\"type\":\"string\",\"const\":\"politics\",\"description\":\"政治\"},{\"type\":\"string\",\"const\":\"health\",\"description\":\"健康\"},{\"type\":\"string\",\"const\":\"education\",\"description\":\"教育\"},{\"type\":\"string\",\"const\":\"science_and_environment\",\"description\":\"科学与环境\"},{\"type\":\"string\",\"const\":\"technology\",\"description\":\"科技\"},{\"type\":\"string\",\"const\":\"entertainment_and_arts\",\"description\":\"娱乐与艺术\"}],\"default\":\"\"},\"edition\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"\"},{\"type\":\"string\",\"const\":\"uk\",\"description\":\"UK\"},{\"type\":\"string\",\"const\":\"us\",\"description\":\"US & Canada\"},{\"type\":\"string\",\"const\":\"int\",\"description\":\"Rest of the world\"}],\"default\":\"\",\"description\":\"版本,仅对 `category` 为空有效\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fTU2iCLtmsEWljy_HbEhCa</name>\n  <description>获取哔哩哔哩视频排行榜,包含全站、动画、音乐、游戏等多个分区的热门视频,反映当下年轻人的内容消费趋势</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"type\":{\"anyOf\":[{\"type\":\"number\",\"const\":0,\"description\":\"全站\"},{\"type\":\"number\",\"const\":1,\"description\":\"动画\"},{\"type\":\"number\",\"const\":3,\"description\":\"音乐\"},{\"type\":\"number\",\"const\":4,\"description\":\"游戏\"},{\"type\":\"number\",\"const\":5,\"description\":\"娱乐\"},{\"type\":\"number\",\"const\":188,\"description\":\"科技\"},{\"type\":\"number\",\"const\":119,\"description\":\"鬼畜\"},{\"type\":\"number\",\"const\":129,\"description\":\"舞蹈\"},{\"type\":\"number\",\"const\":155,\"description\":\"时尚\"},{\"type\":\"number\",\"const\":160,\"description\":\"生活\"},{\"type\":\"number\",\"const\":168,\"description\":\"国创相关\"},{\"type\":\"number\",\"const\":181,\"description\":\"影视\"}],\"default\":0,\"description\":\"排行榜分区\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>f_OULD1Qnu5wPblKHFTzYw</name>\n  <description>获取豆瓣实时热门榜单,提供当前热门的图书、电影、电视剧、综艺等作品信息,包含评分和热度数据</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"type\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"subject\",\"description\":\"图书、电影、电视剧、综艺等\"},{\"type\":\"string\",\"const\":\"movie\",\"description\":\"电影\"},{\"type\":\"string\",\"const\":\"tv\",\"description\":\"电视剧\"}],\"default\":\"subject\"},\"start\":{\"type\":\"integer\",\"default\":0},\"count\":{\"type\":\"integer\",\"default\":10}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fL5c-CwZ3bUckaatY_MC8Z</name>\n  <description>获取抖音热搜榜单,展示当下最热门的社会话题、娱乐事件、网络热点和流行趋势</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>flPxhdB8Wyw8DDuban0pMa</name>\n  <description>获取机核网游戏相关资讯,包含电子游戏评测、玩家文化、游戏开发和游戏周边产品的深度内容</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fdj1bDLATGns6ZdclA68UF</name>\n  <description>获取爱范儿科技快讯,包含最新的科技产品、数码设备、互联网动态等前沿科技资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\",\"default\":20},\"offset\":{\"type\":\"integer\",\"default\":0}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>f0Uk75Pbfsx0rfdD725CYI</name>\n  <description>获取 InfoQ 技术资讯,包含软件开发、架构设计、云计算、AI等企业级技术内容和前沿开发者动态</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"region\":{\"type\":\"string\",\"enum\":[\"cn\",\"global\"],\"default\":\"cn\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fu70DSpIpWTVlq11tEKJZd</name>\n  <description>获取掘金文章榜,包含前端开发、后端技术、人工智能、移动开发及技术架构等领域的高质量中文技术文章和教程</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"category_id\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"6809637769959178254\",\"description\":\"后端\"},{\"type\":\"string\",\"const\":\"6809637767543259144\",\"description\":\"前端\"},{\"type\":\"string\",\"const\":\"6809635626879549454\",\"description\":\"Android\"},{\"type\":\"string\",\"const\":\"6809635626661445640\",\"description\":\"iOS\"},{\"type\":\"string\",\"const\":\"6809637773935378440\",\"description\":\"人工智能\"},{\"type\":\"string\",\"const\":\"6809637771511070734\",\"description\":\"开发工具\"},{\"type\":\"string\",\"const\":\"6809637776263217160\",\"description\":\"代码人生\"},{\"type\":\"string\",\"const\":\"6809637772874219534\",\"description\":\"阅读\"}],\"default\":\"6809637769959178254\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fZMjSXkog94GRA7VoZpJtw</name>\n  <description>获取网易新闻热点榜,包含时政要闻、社会事件、财经资讯、科技动态及娱乐体育的全方位中文新闻资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>f5s3U6zXATp3L6wpAwNcn4</name>\n  <description>获取纽约时报新闻,包含国际政治、经济金融、社会文化、科学技术及艺术评论的高质量英文或中文国际新闻资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"region\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"cn\",\"description\":\"中文\"},{\"type\":\"string\",\"const\":\"global\",\"description\":\"全球\"}],\"default\":\"cn\"},\"section\":{\"type\":\"string\",\"default\":\"HomePage\",\"description\":\"分类,当 `region` 为 `cn` 时无效。可选值: Africa, Americas, ArtandDesign, Arts, AsiaPacific, Automobiles, Baseball, Books/Review, Business, Climate, CollegeBasketball, CollegeFootball, Dance, Dealbook, DiningandWine, Economy, Education, EnergyEnvironment, Europe, FashionandStyle, Golf, Health, Hockey, HomePage, Jobs, Lens, MediaandAdvertising, MiddleEast, MostEmailed, MostShared, MostViewed, Movies, Music, NYRegion, Obituaries, PersonalTech, Politics, ProBasketball, ProFootball, RealEstate, Science, SmallBusiness, Soccer, Space, Sports, SundayBookReview, Sunday-Review, Technology, Television, Tennis, Theater, TMagazine, Travel, Upshot, US, Weddings, Well, World, YourMoney\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fSodMRu-GB5-mpBxBvxc2D</name>\n  <description>获取什么值得买热门,包含商品推荐、优惠信息、购物攻略、产品评测及消费经验分享的实用中文消费类资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"unit\":{\"anyOf\":[{\"type\":\"number\",\"const\":1,\"description\":\"今日热门\"},{\"type\":\"number\",\"const\":7,\"description\":\"周热门\"},{\"type\":\"number\",\"const\":30,\"description\":\"月热门\"}],\"default\":1}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fnY78eScFYQ-6xtUUQg8fB</name>\n  <description>获取少数派热榜,包含数码产品评测、软件应用推荐、生活方式指南及效率工作技巧的优质中文科技生活类内容</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"tag\":{\"type\":\"string\",\"enum\":[\"热门文章\",\"应用推荐\",\"生活方式\",\"效率技巧\",\"少数派播客\"],\"default\":\"热门文章\",\"description\":\"分类\"},\"limit\":{\"type\":\"integer\",\"default\":40}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fFlnyuBJfPLifqYRkW94Lh</name>\n  <description>获取腾讯新闻热点榜,包含国内外时事、社会热点、财经资讯、娱乐动态及体育赛事的综合性中文新闻资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"page_size\":{\"type\":\"integer\",\"default\":20}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>f0YfISsRrFbNGGwO3XVCFY</name>\n  <description>获取澎湃新闻热榜,包含时政要闻、财经动态、社会事件、文化教育及深度报道的高质量中文新闻资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fIKw7RiYt2oAptPSBtelf-</name>\n  <description>获取 The Verge 新闻,包含科技创新、数码产品评测、互联网趋势及科技公司动态的英文科技资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fH1Xj1bmY_qWxS6b8BoSCK</name>\n  <description>获取今日头条热榜,包含时政要闻、社会事件、国际新闻、科技发展及娱乐八卦等多领域的热门中文资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fIoNHXnzDif1o8sJSRpVBu</name>\n  <description>获取微博热搜榜,包含时事热点、社会现象、娱乐新闻、明星动态及网络热议话题的实时热门中文资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fX_nTem-9mBD-9Th_ZVRdA</name>\n  <description>获取微信读书排行榜,包含热门小说、畅销书籍、新书推荐及各类文学作品的阅读数据和排名信息</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"category\":{\"anyOf\":[{\"type\":\"string\",\"const\":\"rising\",\"description\":\"飙升榜\"},{\"type\":\"string\",\"const\":\"hot_search\",\"description\":\"热搜榜\"},{\"type\":\"string\",\"const\":\"newbook\",\"description\":\"新书榜\"},{\"type\":\"string\",\"const\":\"general_novel_rising\",\"description\":\"小说榜\"},{\"type\":\"string\",\"const\":\"all\",\"description\":\"总榜\"}],\"default\":\"rising\",\"description\":\"排行榜分区\"}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n\n<tool>\n  <name>fzIq8ORLIZHJLRU6pJt3O5</name>\n  <description>获取知乎热榜,包含时事热点、社会话题、科技动态、娱乐八卦等多领域的热门问答和讨论的中文资讯</description>\n  <arguments>\n    {\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"number\",\"default\":50}},\"additionalProperties\":false,\"$schema\":\"http://json-schema.org/draft-07/schema#\"}\n  </arguments>\n</tool>\n\n</tools>\n\n## Tool Use Rules\nHere are the rules you should always follow to solve your task:\n1. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.\n2. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself.\n3. If no tool call is needed, just answer the question directly.\n4. Never re-do a tool call that you previously did with the exact same parameters.\n5. For tool use, MARK SURE use XML tag format as shown in the examples above. Do not use any other format.\n\n# User Instructions\n\n\nNow Begin! If you solve the task correctly, you will receive a reward of $1,000,000.\n"
}

主要包括:

  • 工具使用格式 - 使用XML风格的标签来调用工具,包括工具名称和JSON格式的参数;
  • 工具使用示例 - 展示了如何使用各种假设工具的例子,如文档问答、图像生成、Python解释器等;
  • 可用工具列表 - 提供了多个实际可用的信息获取工具,主要是各种中英文新闻和内容平台的热门榜单;
  • 工具使用规则 - 强调了正确使用参数、仅在需要时调用工具、不重复调用等规则;
  • 最后,提示词以一个有趣的激励结束,表示如果任务正确完成,将获得一百万美元奖励。
  1. index =1 的用户的内容
java 复制代码
{
  "role": "user",
  "content": "帮我搜索 模型上下文协议 MCP 相关的最新技术文章"
}
  1. index =2 的助手的内容(指明使用的工具)
java 复制代码
{
  "role": "assistant",
  "content": "为了找到关于模型上下文协议(MCP)的最新技术文章,我将使用一些可用的工具来搜索相关资讯。首先,我可以从InfoQ开始,因为它经常发布企业级技术内容和前沿开发者动态。\n\n<tool_use>\n  <name>f0Uk75Pbfsx0rfdD725CYI</name>\n  <arguments>{\"region\":\"global\"}</arguments>\n</tool_use>"
}
  1. index =3 的 用户的内容(回复用户内容)
java 复制代码
{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "Here is the result of tool call f0Uk75Pbfsx0rfdD725CYI:"
    },
    {
      "type": "text",
      "text": "[{\"type\":\"text\",\"text\":\"<title>Docker Desktop 4.40 Introduces Model Runner to Run LLMs Locally Expanding its AI Capabilities</title>\\n<description> 省略其他}]"
    }
  ]
}

深入MCP

剖析MCP核心架构:从CS误解到CHS本质

Model Context Protocol(MCP)不是传统的CS架构

参考1《MCP架构》

MCP引入了Host,组成了(Client-Host-Server, CHS)。

责任:

  • Host:AI智能的唯一承载者
    • Host是整个系统中唯一与大型语言模型(LLM)直接交互的组件 。其核心任务包括:管理完整的对话上下文、动态构建和拼接Prompt、解析LLM的响应、根据AI决策生成与MCP Server交互的指令。简而言之,一个MCP应用的"智能水平"完全由其Host的实现质量决定。
  • Server:确定性能力的执行器
    • Server是一个标准的网络服务,它向外界声明并提供一组具有确定性的、可供远程调用的能力(Capabilities)。这些能力可以是工具调用、文件操作等(全量枚举源码里有)。Server接收标准化的请求,执行相应的能力,并返回确定的结果。它不包含任何AI逻辑,其行为是可预测且可靠的。值得注意的是,工具调用只是其众多规划能力中的一种,尽管是目前最常用的一种。
  • Client:无状态的协议中间件
    • Client的角色最为纯粹,它是一个位于Host和Server之间的协议客户端和状态管理器 。它严格实现了MCP的通信协议,负责处理协议握手、会话管理、心跳维持 以及将Host的意图 (如"调用某个工具")转换为符合MCP规范的JSON-RPC请求并发送给Server 。它不关心业务逻辑,也不理解AI意图,仅作为连接Host与Server的标准化通信管道

注意:Client并不会调用大模型。

如下图,都隐藏了Host的存在,容易让人觉得Client会调用LLM

图中容易引发Client发起了大模型调用的误会

图中容易引发Client发起了大模型调用的误会

Server与Client的模型无关性证明

  • MCP Server 是一个实现了MCP协议的、模型无关的RPC服务端。它的核心职责是:在启动时声明能力、通过initialize握手交换元数据、并将符合规范的JSON-RPC请求分发给预定义的确定性函数执行
  • MCP Client(基于协议对称性)扮演着完全对等的角色:一个RPC客户端。它的职责是将Host的指令封装成标准化的JSON-RPC请求,发送给Server,并接收响应。

Host实战解剖:在CherryStudio中定位LLM交互

CherryStudio,一个基于Electron构建的AI桌面应用。由于Electron特殊的双进程架构(主进程+渲染进程),CherryStudio对MCP Host的实现进行了一次职责拆分:

  • 主进程:运行在Node.js环境中,负责系统级操作和网络通信。其中MCPService.ts封装了Client能力和一部分Host调用职责主要作为与外部MCP Server通信的代理
  • **渲染进程:**运行在内置浏览器环境中,负责UI渲染和用户交互。其中ApiService.ts承担了Host的核心AI职责,包括Prompt构建和LLM调用。

主进程:

  • 连接管理:通过 initClient 方法,负责创建和管理与外部MCP Server的 Client 连接实例。
  • 请求转发:它暴露了如 listTools 和 callTool 等方法,但其内部实现仅仅是将来自渲染进程的IPC请求,转换为对 中 MCP Client 实例的方法调用。

渲染进程:

  1. 工具发现:通过IPC调用主进程的MCPService.ts,获取当前可用MCP Server提供的工具列表(window.api.mcp.listTools())。
  2. 系统提示词构建 :调用buildSystemPromptWithTools函数,将获取到的工具定义(包括名称、描述、参数Schema)格式化后,注入到一个庞大的System Prompt中。这个Prompt指导LLM如何理解和使用这些工具
  3. 大模型调用:这是决定性的证据。代码最终调用了AI.completionsForTrace,这是一个封装了对底层AI Provider(如OpenAI、Anthropic)API请求的函数。

概念辨析:MCP与Function Calling的层级与关系

MCP与Function Calling协作而非替代:Host中融合MCP与Function Calling的策略。

  • Function Calling: 是一种内嵌于LLM中的模型决策能力 。它解决了"决定做什么 "的问题。当模型具备Function Calling能力时,它能根据对话上下文,自行决定是否需要调用外部工具,并以结构化的格式(如JSON)返回调用意图(函数名和参数)。这是LLM自身推理能力的延伸。
  • MCP****: 是一套定义"如何调用 "的基础设施协议。它解决了工具的标准化、发现、安全和互操作性问题。MCP将外部工具抽象为标准化的、可通过网络访问的服务。它就像软件工程中的REST API或gRPC,为AI应用提供了一个统一、解耦的工具调用框架。

因此,**Function Calling是AI的"大脑",而MCP是连接大脑与外部世界的"神经系统"。**它们并非替代关系,而是协作关系,共同构成一个完整的"感知-决策-行动"循环。

以AI应用(CherryStudio)以例,其Host实现,会根据模型的具体能力,智能地选择使用Function Calling或基于Prompt的指令来与MCP Server交互:

在其Host实现中,存在一个双重意图识别机制

1.能力检测:首先通过isFunctionCallingModel函数判断当前配置的LLM是否原生支持Function Calling。(Function Calling是需要LLM模型训练的,不是所有都支持)。

java 复制代码
// src/config/models.ts  第356-359行
// 确认模型是不是支持Function Calling
export function isFunctionCallingModel(model?: Model): boolean {
  // Logic to check provider, model name, and user settings...
  if (['openai', 'anthropic', 'deepseek'].includes(model.provider)) {
    returntrue;
  }
  return FUNCTION_CALLING_REGEX.test(model.id);
}

2.策略切换:

  • 如果模型支持Function Calling**:**Host会将从MCP Server获取的工具列表,通过mcpToolsToOpenAIChatTools函数转换成符合OpenAI规范的tools参数,直接利用模型原生的Function Calling能力进行决策。
  • 如果模型不支持:Host会回退到"Prompt Engineering"模式,将工具定义拼接成XML格式的文本,注入System Prompt (下面代码的"role":"system")中,并依赖parseToolUse函数从LLM返回的纯文本中用正则表达式提取<tool_use>标签,来解析工具调用意图。(如Cursor)过程伪代码可以参考如下:
java 复制代码
## Step0.初始化MCP客户端
client = Client()
await client.connect("...")
tools = await client.list_tools()

## Step1.调用大模型意图识别 注意 role:system 注入 system prompt
messages = [
    {"role": "system", "content": build_mcp_tool_prompt(tools)},#注意:这里是文本拼接了Prompt
    {"role": "user", "content": "帮我查一下杭州4C8G的ECS规格?"}
]
assistant_response = await call_llm(messages)

## Step2.解析意图识别结果,并且远程调用工具
tool_call = parse_tool_use(assistant_response)
result = await client.call_tool(name=tool_call["name"],arguments=tool_call["arguments"])

## Step3.结果输出
messages.append({"result": result})
final_response = await call_llm(messages)

## 工具定义 TOOLS 不再需要,client.list_tools()获得
## 工具实现 def describe_regions()不再需要,client.call_tool()调用

## 新增:通用意图识别提示词构建
def build_mcp_tool_prompt(tools)
    tool_descriptions = ""
    for tool in tools:
        tool_descriptions = tool_descriptions + f"<tool>{tool['name']}</tool>\n"
    return f"""
你是一个智能助手,可以使用以下工具来帮助用户解决问题。可用MCP工具列表:
{tool_descriptions}
请使用以下XML格式调用工具:
<tool_use><name>{{工具名称}}</name><arguments>{{JSON格式参数}}</arguments></tool_use>
示例:
<tool_use><name>DescribeInstanceTypes</name>
<arguments>{{"param_1": "cn-hangzhou", "param_2": "4C8G"}}</arguments></tool_use>"""

## 新增:解析大模型输出获得工具和入参
def parse_tool_use(response):
    tool_use_regex = re.compile(r"<tool_use>\s*<name>(.*?)</name>\s*<arguments>(.*?)</arguments>\s*</tool_use>",re.DOTALL)
    match = tool_use_regex.search(response)
    tool_name, arguments_str = match.groups()
    return {"name": tool_name, "arguments": arguments_str}

这个设计证明:Function Calling和基于Prompt的指令生成,都是Host用来驱动MCP协议的"上层决策方法"。MCP作为底层基础设施,对上层决策方式保持中立。因此,MCP不仅不是Function Calling的替代品,反而可以与Function Calling(或其他意图识别技术)无缝协作,各司其职。

总结下链路,这个链路是从AI应用(如Cursor或**CherryStudio****)角度出发:**

  • LLM 支持 Function Call:Host -> 从MCP Server获取的工具列表,转换符合OpenAI规范的tools参数传入LLM -> LLM利用Function Calling能力进行决策返回(每个模型格式不同) -> Host适配不同模型格式并转换为tool -> 利用MCPClient调用tool。
  • LLM 不支持 Function Call:Host -> 从MCP Server获取的工具列表,将工具定义拼接成XML格式的文本,注入System Prompt中 -> LLM意图识别返回结果 -> Host解析提取<tool_use>标签获取对应tool -> 利用MCPClient调用tool。

MCP的意义:如果LLM支持Function Call,LLM仍然返回不同格式的Function Call,但AI应用只需要适配一次不同LLM的Function Call来提取tool,然后根据MCP协议调用下游即可。**减少了调用下有的适配工作量。**当然LLM如果不支持Function Call,根据LLM返回的tool同理利用根据MCP协议调用下游。

角色 传统模式 MCP模式
AI应用开发者 需要适配N个LLM + M个工具 只需适配N个LLM
LLM厂商 定义自己的标准 继续定义自己的标准

另外一个角色,工具开发者,可以自行适配MCP协议,但也可以使用第三方提供的MCP Server来暴露他们的工具,如MCP市场。(但MCP市场不止这个功能)

参考文档

mp.weixin.qq.com/s/UfzmzJ3zT...

mp.weixin.qq.com/s/EcDCKN4-m...

相关推荐
Emrys_2 小时前
装饰者模式详解与计费功能实现
后端
猎豹奕叔2 小时前
注解规则编排组件
后端
程序员小假2 小时前
线程池执行过程中遇到异常该怎么办?
java·后端
karry_k2 小时前
常用的同步辅助类
后端
Mr.Entropy3 小时前
Hibernate批量查询方法全面解析
java·后端·hibernate
绝顶少年3 小时前
Spring 框架中 RestTemplate 的使用方法
java·后端·spring
信安成长日记3 小时前
golang 写路由的时候要注意
开发语言·后端·golang
Lojarro3 小时前
GO学习2:基本数据类型 与 转换
后端·学习·golang
闲人编程4 小时前
2025年,如何选择Python Web框架:Django, Flask还是FastAPI?
前端·后端·python·django·flask·fastapi·web