MCP 协议入门:给你的 AI 装上"手脚",从此告别嘴炮

你家 AI 是不是也这样:让它干活,它说"好的",然后给你一段"如何干活"的作文?

开篇:一个悲伤的故事

上周我让 AI 帮我查一下服务器的磁盘空间。

AI 说:

“好的!你可以使用 df -h 命令来查看磁盘空间。首先,打开终端……”

然后它给我写了 500 字的操作教程。

我说的是"帮我查",不是"教我查"啊喂! 😭

这就是现在 AI Agent 的通病——脑子好使,但没有手。它知道怎么做,但它做不了。

直到 MCP 协议出现,这个问题才被解决。


MCP 是个啥?

MCP,全称 Model Context Protocol,Anthropic(Claude 的亲爹)搞出来的一个开源协议。

用大白话说:

MCP 就是给 AI 装了一双手。

以前的 AI:🧠(只有脑子,只会说)
有了 MCP:🧠 + 🤲(脑子 + 手,能干活了)

再打个比方:

没有 MCP 的 AI 有了 MCP 的 AI
像一个只会纸上谈兵的军师 像一个能亲自上阵的将军
像一个只会看菜谱的吃货 像一个能颠勺的大厨
像一个只会写代码的程序员 像一个能写还能跑的全栈

三分钟搭一个 MCP Server

别被"协议"这个词吓到,搭 MCP Server 比泡方便面还简单。

第一步:装包

pip install mcp

就一行,比 npm install 快多了(前端同学别打我)。

第二步:写代码

# weather_mcp.py
from mcp.server.fastmcp import FastMCP

# 创建一个 MCP Server,名字随便起
mcp = FastMCP("天气查询服务")

@mcp.tool()
def get_weather(city: str) -> str:
    """查询城市天气
    
    Args:
        city: 城市名,比如"北京"、"上海"
    """
    # 这里应该调真实 API,但我懒,模拟一下
    fake_data = {
        "北京": "☀️ 晴天 25°C — 适合出门浪",
        "上海": "🌧️ 小雨 20°C — 记得带伞",
        "深圳": "🔥 高温 32°C — 热到融化",
        "成都": "☁️ 阴天 18°C — 适合吃火锅",
    }
    return fake_data.get(city, f"🤷 抱歉,{city}的天气我也不知道")

@mcp.tool()
def add_numbers(a: float, b: float) -> str:
    """两个数相加
    
    Args:
        a: 第一个数
        b: 第二个数
    """
    return f"{a} + {b} = {a + b},小学生都会算"

第三步:运行

python weather_mcp.py

搞定!你的 AI 现在有手了。


让 AI 真的去干活

光有 Server 不行,还得让 AI 知道它有这双手。来看怎么接 Claude:

import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import anthropic

async def let_ai_work():
    # 连接 MCP Server
    server = StdioServerParameters(
        command="python", 
        args=["weather_mcp.py"]
    )
    
    async with stdio_client(server) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            # 拿到工具列表
            tools = await session.list_tools()
            
            # 转成 Claude 认识的格式
            claude_tools = [{
                "name": t.name,
                "description": t.description,
                "input_schema": t.inputSchema
            } for t in tools.tools]
            
            # 问 Claude 一个问题
            client = anthropic.Anthropic()
            response = client.messages.create(
                model="claude-sonnet-4-20250514",
                max_tokens=1000,
                tools=claude_tools,
                messages=[{
                    "role": "user", 
                    "content": "成都今天天气咋样?适合出门不?"
                }]
            )
            
            # Claude 会说:"我要调用 get_weather 工具"
            for block in response.content:
                if block.type == "tool_use":
                    # 真的去调用了!
                    result = await session.call_tool(
                        block.name, 
                        arguments=block.input
                    )
                    print(f"🔧 调用了 {block.name},结果:{result.content[0].text}")

asyncio.run(let_ai_work())

输出:

🔧 调用了 get_weather,结果:☁️ 阴天 18°C — 适合吃火锅

看到没?AI 不再给你写教程了,它真的去查了天气,然后告诉你:适合吃火锅! 🍲


MCP vs Function Calling:到底有啥区别?

“OpenAI 不是有 Function Calling 吗?何必搞 MCP?”

好问题,区别大了:

Function Calling MCP
是什么 OpenAI 的私有方案 行业开放标准
打个比方 苹果的 Lightning 接口 USB-C(Type-C)
工具管理 每次请求都得带上 Server 统一管理
能不能复用 得复制粘贴代码 启动一个服务就行
其他厂商能用吗 只有 OpenAI 谁都能用

Function Calling 是山寨充电器,MCP 是国标充电头。

一个只能给特定手机用,一个所有设备通用。


实战:几个超实用的 MCP Server

1. 文件操作 Server

from mcp.server.fastmcp import FastMCP
import os

mcp = FastMCP("文件管理器")

@mcp.tool()
def list_files(directory: str = ".") -> str:
    """列出目录下的文件"""
    try:
        files = os.listdir(directory)
        return "\n".join(files)
    except Exception as e:
        return f"出错了:{e}"

@mcp.tool()
def read_file(path: str) -> str:
    """读取文件内容"""
    try:
        with open(path, "r", encoding="utf-8") as f:
            content = f.read()
        return content[:2000]  # 限制长度,别把 AI 喂撑了
    except Exception as e:
        return f"读不了:{e}"

现在你可以对 AI 说:“帮我看看 /var/log 下面有什么文件”,它就真的会去看了。

2. 数据库查询 Server

from mcp.server.fastmcp import FastMCP
import sqlite3

mcp = FastMCP("数据库查询")

@mcp.tool()
def query_db(sql: str) -> str:
    """执行 SQL 查询(只读,别想删库)"""
    # 安全检查:只允许 SELECT
    if not sql.strip().upper().startswith("SELECT"):
        return "❌ 只能查,不能改!想删库?没门!"
    
    try:
        conn = sqlite3.connect("mydb.sqlite")
        cursor = conn.execute(sql)
        rows = cursor.fetchall()
        conn.close()
        return f"查到 {len(rows)} 条记录:\n{rows[:10]}"  # 最多显示10条
    except Exception as e:
        return f"SQL 写错了吧:{e}"

现在你可以对 AI 说:“帮我查一下用户表里有多少人”,它就真的去查了。

3. 网页抓取 Server

from mcp.server.fastmcp import FastMCP
import httpx

mcp = FastMCP("网页抓取")

@mcp.tool()
def fetch_webpage(url: str) -> str:
    """抓取网页内容"""
    try:
        resp = httpx.get(url, timeout=10, follow_redirects=True)
        # 只取前 3000 字符,不然 AI 会消化不良
        return resp.text[:3000]
    except Exception as e:
        return f"抓不了:{e}"

安全提醒:别让你的 AI 成为黑客

给 AI 装手是好事,但别让它乱摸:

# ❌ 危险操作:AI 可以执行任意代码
@mcp.tool()
def run_code(code: str) -> str:
    """执行 Python 代码"""
    return exec(code)  # 🚨 AI 一激动给你 rm -rf /

# ✅ 安全操作:限制范围
@mcp.tool()
def safe_calc(expression: str) -> str:
    """安全的计算器"""
    allowed = set("0123456789+-*/.() ")
    if not all(c in allowed for c in expression):
        return "❌ 只能算加减乘除,别想搞事"
    return str(eval(expression))

记住:给 AI 权限就像给小孩零花钱——给够就行,别给太多。


总结

  • MCP = 给 AI 装手的标准协议
  • 比 Function Calling 更通用、更好用
  • Python 三行代码就能搭一个 Server
  • 安全第一,权限要管好

有了 MCP,你的 AI 就从"嘴炮型选手"变成了"实干型选手"。

以前:AI 说"我可以帮你做"→ 然后给你写教程
现在:AI 说"我来帮你做"→ 然后真的做完了

这才是 AI Agent 应该有的样子。


觉得有用就点个赞呗 👍 有问题评论区见,我争取做到每条都回(除了杠精)。
条都回(除了杠精)。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐