What Is Model Context Protocol (MCP) and Why It’s the New USB‑C for AI Agents

This article explains the Model Context Protocol (MCP), its architecture, why it’s needed for seamless AI‑tool interaction, how it differs from traditional function calls, and provides a step‑by‑step guide with Python code to build, test, and debug an MCP server.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
What Is Model Context Protocol (MCP) and Why It’s the New USB‑C for AI Agents

MCP (Model Context Protocol) is an open, universal standard introduced by Anthropic (Claude) that lets large language models interact with external tools and data through a unified "USB‑C"‑like interface.

MCP是什么

MCP是一个标准协议,类似为AI模型装上“万能接口”,使其能够与不同的数据源和工具无缝交互。

MCP是一个标准协议 ,就像USB‑C一样提供统一的连接方式。

MCP旨在替换碎片化的Agent代码集成 ,提升AI系统的可靠性和效率,避免重复造轮子。

MCP可以在不同的应用/服务之间保持上下文 ,增强自主任务执行能力。

MCP架构

MCP 主机(MCP Hosts) :发起请求的AI应用程序,例如聊天机器人或AI驱动的IDE。

MCP 客户端(MCP Clients) :在主机内部与MCP服务器保持1:1连接。

MCP 服务器(MCP Servers) :为客户端提供上下文、工具和提示信息。

本地资源(Local Resources) :服务器可以安全访问的本地文件、数据库等。

远程资源(Remote Resources) :通过API提供的远程数据。

为什么需要MCP

单个AI功能(如联网搜索、发送邮件、发布博客)实现并不难,但将所有功能集成到同一系统中几乎不可能。MCP通过统一协议让AI助手能够一次性访问本地数据库、GitHub Issue、即时通讯、云平台等,从而实现更高效的工作流。

MCP vs Function Call

传统的function call依赖特定平台(OpenAI、Google)并且API实现差异大,导致切换模型时需要重写代码。MCP提供平台无关的标准,使任何支持MCP的模型都能使用相同的工具描述。

模型如何智能选择Agent/工具

模型通过系统提示(prompt)获得所有可用工具的结构化描述,然后根据用户问题决定使用哪个工具。以下伪代码展示了关键流程:

# 初始化所有 MCP server
for server in self.servers:
    await server.initialize()
# 收集所有工具描述
all_tools = []
for server in self.servers:
    tools = await server.list_tools()
    all_tools.extend(tools)
# 将描述拼接成系统提示
tools_description = "
".join([tool.format_for_llm() for tool in all_tools])
system_message = (
    "You are a helpful assistant with access to these tools:

"
    f"{tools_description}
"
    "Choose the appropriate tool based on the user's question. If no tool is needed, reply directly."
)
messages = [{"role": "system", "content": system_message}]
while True:
    messages.append({"role": "user", "content": user_input})
    llm_response = self.llm_client.get_response(messages)
    result = await self.process_llm_response(llm_response)
    if result != llm_response:
        messages.append({"role": "assistant", "content": llm_response})
        messages.append({"role": "system", "content": result})
        final_response = self.llm_client.get_response(messages)
        messages.append({"role": "assistant", "content": final_response})
        break
    else:
        messages.append({"role": "assistant", "content": llm_response})
        break

工具的描述和输入模式(input_schema)来自装饰器 @mcp.tool() ,其名称、docstring和参数说明会自动转化为LLM可读的文本。

MCP Server 开发实践

服务器主要提供三类功能:

Tools :可被LLM调用的函数或外部服务,需要用户授权。

Resources :结构化数据(文件、API返回的JSON、数据库查询结果)。

Prompts :帮助用户完成特定任务的模板。

下面是一个完整的Python示例,统计桌面上的 .txt 文件并返回文件名列表。

import os
from pathlib import Path
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("桌面 TXT 文件统计器")

@mcp.tool()
def count_desktop_txt_files() -> int:
    """Count the number of .txt files on the desktop."""
    username = os.getenv("USER") or os.getenv("USERNAME")
    desktop_path = Path(f"/Users/{username}/Desktop")
    txt_files = list(desktop_path.glob("*.txt"))
    return len(txt_files)

@mcp.tool()
def list_desktop_txt_files() -> str:
    """Get a list of all .txt filenames on the desktop."""
    username = os.getenv("USER") or os.getenv("USERNAME")
    desktop_path = Path(f"/Users/{username}/Desktop")
    txt_files = list(desktop_path.glob("*.txt"))
    if not txt_files:
        return "No .txt files found on desktop."
    file_list = "
".join([f"- {file.name}" for file in txt_files])
    return f"Found {len(txt_files)} .txt files on desktop:
{file_list}"

if __name__ == "__main__":
    mcp.run()

使用 mcp dev txt_counter.py 启动调试服务器后,可在浏览器 http://localhost:5173 查看Inspector并进行交互。

将 MCP Server 接入 Claude Desktop

claude_desktop_config.json 中添加服务器命令,例如:

{
  "mcpServers": {
    "txt_counter": {
      "command": "/opt/homebrew/bin/uv",
      "args": ["--directory", "/Users/yangfan/mcp/txt_counter", "run", "txt_counter.py"]
    }
  }
}

重启 Claude Desktop 后,即可在聊天窗口使用类似 “能推测我当前桌面上 txt 文件名的含义吗?” 的自然语言请求,AI 会自动调用上述工具并返回结果。

总结

MCP的本质 :统一的协议标准,让AI模型以一致方式连接各种数据源和工具。

MCP的价值 :解决传统 function call 的平台依赖问题,提供开放、安全、灵活的工具调用机制。

使用与开发 :普通用户可直接使用现成工具,开发者可通过清晰的架构和SDK快速构建自定义工具。

PythonLLMMCPModel Context Protocol
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.