本文介绍了MCP大模型上下文协议的的概念,并对比了MCP协议和function call的区别,同时用python sdk为例介绍了mcp的使用方式。

1. 什么是MCP?

官网: https://modelcontextprotocol.io/introduction

2025年,Anthropic提出了MCP协议。MCP全称为Model Context Protocol,翻译过来是大模型上下文协议。这个协议的主要为AI大模型和外部工具(比如让AI去查询信息,或者让AI操作本地文件)之间的交互提供了一个统一的处理协议。我们常用的USB TypeC接口(USB-C)统一了USB接口的样式,MCP协议就好比AI大模型中的USB-C,统一了大模型与工具的对接方式。

MCP协议采用了C/S架构,也就是服务端、客户端架构,能支持在客户端设备上调用远程Server提供的服务,同时也支持stdio流式传输模式,也就是在客户端本地启动mcp服务端。只需要在配置文件中新增MCP服务端,就能用上这个MCP服务器提供的各种工具,大大提高了大模型使用外部工具的便捷性。

【MCP】详细了解MCP协议:和function call的区别何在?如何使用MCP?_AI

MCP是开源协议,能让所有AI厂商、AI工具都将MCP集成到自己的客户端中,从而扩大MCP的可用面。毕竟只有用的人越多,协议才能不断发展,不断变得更好。

2. 了解function call

在MCP没有出来之前,我们的AI Agent开发如果想调用外部工具需要针对不同的AI大模型SDK编写不同的代码,其中最为常用的是openai提供的function call的处理逻辑。

本小节参考博客:

  • 深入探讨Function Calling:实现外部函数调用的工作原理;
  • 来自OpenAI官网的Function calling介绍与最佳实践
2.1. function call demo
2.1.1. 配置工具,AI提供参数

当我们调用 OpenAI Chat Completions 接口时,可以通过tools参数传入可供使用的外部工具。这个工具的调用中就包含了工具的作用,工具需要传入的参数,以及参数的释义。其中tool_choice字段设置为auto代表让大模型自动选择tools,设置为none时不会调用外部工具。

{
  "tool_choice": "auto",
  "messages": [
    {
      "role": "system",
      "content": "你是一个天气查询助手"
    },
    {
      "role": "user",
      "content": "帮我查询上海的天气"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "城市名"
            }
          },
          "required": ["city"],
        }
      }
    }
  ]
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

对应的python openai代码如下,我们将tools部分放入一个包含dict的list,作为create函数的tools参数即可。同时tool_choice传入auto代表自动选择工具。这里我用了硅基流动提供的Qwen2.5模型作为演示,运行下面这个代码需要修改api_key为正确值。

import openai # 1.75.0
import json # 后续会用到json

def main():
    client = openai.OpenAI(
        api_key="xxxxx",
        base_url="https://api.siliconflow.cn/v1")
    tools = [{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "城市名"
                    }
                },
                "required": ["city"],
            }
        }
    }]
    res = client.chat.completions.create(model="Qwen/Qwen2.5-32B-Instruct",
                                         messages=[{
                                             "role": "system",
                                             "content": "你是一个天气查询助手"
                                         }, {
                                             "role": "user",
                                             "content": "帮我查询上海的天气"
                                         }],
                                         tools=tools,
                                         tool_choice="auto")
    print("content:",res.choices[0].message.content)
    print("tools:",res.choices[0].message.tool_calls)
    print("message:", res.choices[0].message.to_dict())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.

运行程序,发出请求后,大模型就会根据用户提出的问题和提供的tools,来为这个tools编写需要提供的参数。此时content会是空,不会输出内容,tool_calls中会包含调用的工具和参数。

❯ uv run main.py
content: 
tools: [ChatCompletionMessageToolCall(id='01964be6e485603d6a2a0acbbc7eba91', function=Function(arguments='{"city": "上海"}', name='get_weather'), type='function')]
message: {'content': '', 'role': 'assistant', 'tool_calls': [{'id': '01964be6e485603d6a2a0acbbc7eba91', 'function': {'arguments': '{"city": "上海"}', 'name': 'get_weather'}, 'type': 'function'}]}
  • 1.
  • 2.
  • 3.
  • 4.

对应如下json格式响应,包含了我们的参数

"message": {
        "role": "assistant",
        "content": "",
        "tool_calls": [
          {
            "id": "01964be6e485603d6a2a0acbbc7eba91",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\n  \"city\": \"上海\"\n}"
            }
          }
        ]
      }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
2.1.2. 调用工具并让AI二次处理

随后,我们就可以根据这个大模型返回的参数来调用我们的函数,并得到函数的返回结果,再次与大模型进行对话。此时需要按下面的方式维护对话上下文,首先需要将第一次请求AI返回的结果插入到上下文中("role": "assistant"的json字符串),然后再插入工具调用的数据,格式如下:

{
	"role": "tool",
	"content": "工具调用结果",
	"tool_call_id": "ai调用工具时返回的id"
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

其中content代表工具调用的结果(字符串形式,内容可以是json),并且需要用tool_call_id来标识这是哪一个工具调用的请求,必须要和"role": "assistant"响应中的id对应。

二次AI交互对应python代码如下,在上文提供的python代码之后追加

# 插入结果,再次对话
    messages.append(res.choices[0].message.to_dict()) # ai第一次返回的数据
    # 工具调用的参数
    to