MCP 协议使用核心讲解

MCP 协议使用核心讲解


✅ MCP 协议的核心在于以下几个方面


一、MCP 请求结构(MCPRequest

{
  "messages": [
    {
      "role": "user",
      "content": "帮我查询一下上海的天气"
    }
  ],
  "tools": [
    {
      "name": "weather_query",
      "description": "查询天气",
      "parameters": {
        "type": "object",
        "properties": {
          "location": { "type": "string", "description": "查询地点" }
        },
        "required": ["location"]
      }
    }
  ]
}
  • messages: 聊天上下文
  • tools: 提供可调用的工具(函数),使用 JSON Schema 描述
  • 模型生成 tool_calls 请求调用工具

二、MCP 响应结构(MCPResponse

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "tool_calls": [
          {
            "id": "call_123",
            "type": "function",
            "function": {
              "name": "weather_query",
              "arguments": "{\"location\": \"上海\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}
  • tool_calls: 模型请求工具调用
  • finish_reason = tool_calls: 模型等待外部执行工具

三、工具执行结果续接请求

{
  "messages": [
    {
      "role": "user",
      "content": "帮我查询一下上海的天气"
    },
    {
      "role": "assistant",
      "tool_calls": [...]
    },
    {
      "role": "tool",
      "tool_call_id": "call_123",
      "content": "{\"weather\": \"晴天,28°C\"}"
    }
  ]
}
  • 工具返回结果通过 role: tool 返回,继续对话

四、MCP 模型调用闭环流程

  1. 用户发起请求(自然语言)
  2. 模型识别出调用意图 → 返回 tool_calls
  3. 外部系统执行工具调用 → 得到结构化结果
  4. 将结构化结果回传给模型(tool 消息)
  5. 模型基于工具结果生成最终响应

五、MCP 协议关键字段说明

字段名 说明
messages 对话上下文
tools 工具定义(JSON Schema)
tool_calls 模型生成的调用请求
tool_call_id 工具调用唯一标识
tool 工具返回结果
finish_reason 模型是否结束、是否等待工具调用

✅ 总结:

MCP 协议的核心在于:通过结构化的工具定义(tools)、模型调用请求(tool_calls)以及工具结果反馈(tool),实现大模型的可控、结构化、插件化调用闭环。

你可能感兴趣的:(服务器,前端,MCP协议)