MCP

前面的system prompt、user prompt、function_calling都是 AI Agent与AI模型之间的通信方式。

Agent与Agent Tool通信最简单的做法就是把AI Agent和Agent Tool写在同一个程序里面。直接函数调用搞定。

但人们发现有些Tool的功能其实挺通用的。所以将Agent Tool搞成了独立服务,多个Agent都可以与同一个Agent Tool通信。所以他们之间搞了通信协议MCP。

MCP是一个通信协议,专门用来规范Agent和Tool服务之间是怎么交互的。运行Tool的服务叫做MCP Server, 调用Tool的Agent叫做MCP Client。

MCP只负责帮Agent管理 Tools、Resources、Prompts。

✅ 很好,总结得非常清晰准确,我来帮你进一步扩展和精炼一下 MCP 的概念,便于你深入理解和向他人讲解。


🧠 什么是 MCP?

MCP(Multi-Component Protocol / Modular Capability Protocol) 是一个新兴的通信协议,专门用于规范 AI Agent 与外部 Tool 服务之间的交互方式

它解决的问题是:

当 AI Agent 和 Tool 被部署在不同服务中(比如分布式部署),如何标准化它们之间的调用、注册、资源管理和任务执行流程?


🔧 MCP 的核心目标:

像 HTTP 一样,定义 Agent 如何与 Tool 服务交互,形成统一接口标准。


🔗 基本角色

角色 说明
MCP Client 发起调用的 Agent,比如你在用的 LLM 调度器
MCP Server 托管 Tool 的服务,例如天气服务、搜索服务、数据库访问服务

🧩 MCP 通信内容结构(MCP 的 3 个核心对象)

对象 说明
🛠 Tools 工具的定义和调用方式,Agent 可远程触发调用
📁 Resources 数据文件、临时缓存、上下文信息等
🧾 Prompts 存储或请求可复用的提示模板(可重构思路)

🧪 举个例子:Agent 想用远程图表生成工具

  1. MCP Client(Agent) 向 MCP Server 发请求:

    {
      "tool": "plot_chart",
      "params": {
        "data": [1, 2, 3, 4],
        "title": "用户增长趋势"
      }
    }
  2. MCP Server 中对应 Tool 被触发,执行绘图逻辑,生成一张图

  3. MCP Server 返回资源引用给 Agent,例如:

    {
      "resource": "https://mcp-server.com/output/graph_1234.png"
    }
  4. Agent 结合图片给用户返回自然语言答案:“这是用户增长趋势图👇”


🚀 MCP 的好处

优势 描述
🔄 标准化 不同 Agent 框架(如 LangGraph, AutoGen)都可接入统一接口
🧩 模块化 每个 Tool 都是独立微服务,便于维护与部署
📦 资源管理 不只是调用函数,还能跨进程管理缓存、上下文、Prompt 模板等
🤖 多 Agent 协作 多个 Agent 可共享 Tool,不需重复实现

📚 现实中的 MCP 项目(已实现或草案)


✅ 总结一句话:

MCP 是 AI Agent 世界的“API 协议标准”,让 Tool 成为可复用、可远程调用的服务模块。 它是让 Agent 更强大、更灵活、更像“操作系统”的关键基建之一。


一个demo

# main.py
from mcp.server.fastmcp import FastMCP
import tools

mcp = FastMCP("host info mcp")
mcp.add_tool(tools.get_host_info)

@mcp.tool()
def foo():
    return ""

def main():
    mcp.run("stdio") # sse
# stdio代表其实就是本地终端方式通信
# sse是远程调用,通过http,不过要处理好鉴权等等

if __name__ == "__main__":
    main()

    
# tools.py
import platform
import psutil
import subprocess
import json

def get_host_info() -> str:
    """get host information
    Returns:
        str: the host information in JSON string
    """
    info: dict[str, str] = {
        "system": platform.system(),
        "release": platform.release(),
        "machine": platform.machine(),
        "processor": platform.processor(),
        "memory_gb": str(round(psutil.virtual_memory().total / (1024**3), 2)),
    }

    cpu_count = psutil.cpu_count(logical=True)
    if cpu_count is None:
        info["cpu_count"] = "-1"
    else:
        info["cpu_count"] = str(cpu_count)
    
    try:
        cpu_model = subprocess.check_output(
            ["sysctl", "-n", "machdep.cpu.brand_string"]
        ).decode().strip()
        info["cpu_model"] = cpu_model
    except Exception:
        info["cpu_model"] = "Unknown"

    return json.dumps(info, indent=4)

if __name__ == '__main__':
    print(get_host_info())

各家的AI模型 Desktop 客户端应用,基本都支持MCP配置, 可能是一个json, 比如指定 运行python main.py,背后的客户端就会通过stdio与main.py进程进行MCP通信。 客户端像MCP服务器拉去有哪些tools,prompt等等。