当前位置:首页>python>用 Python + MCP 写一个完整 AI Agent(100行代码,真的能跑)

用 Python + MCP 写一个完整 AI Agent(100行代码,真的能跑)

  • 2026-09-02 19:29:53
用 Python + MCP 写一个完整 AI Agent(100行代码,真的能跑)

如果你已经看过上一篇 MCP 的文章,那么现在是时候进入真正的实战了。

今天这篇,我们只做一件事:

用不到 100 行 Python,写一个真正能用的 AI Agent。

它可以做到:

  • 接收用户问题
  • 自动选择工具
  • 执行任务(查天气 / 计算等)
  • 返回结果

重点是:

不是 Demo,而是一个最小可用 Agent。


一、最终效果(你将得到什么)

运行后,你可以这样用:

请输入问题:帮我查一下新加坡天气

AI 会自动:

调用工具 → get_weather返回结果 → Singapore: 🌦 +30°C

再比如:

请输入问题:帮我计算 23 + 19

AI 会:

调用 add 工具 → 返回 42

这就是一个完整的 AI Agent闭环。

二、项目结构(极简)

整个项目只有一个文件:

agent.py

依赖:

pip install mcp openai requests
三、完整代码(核心 100 行)
import jsonimport requestsfrom openai import OpenAIfrom mcp.server.fastmcp import FastMCP# =====================# 1. MCP Server(工具层)# =====================mcp = FastMCP("Agent Tools")@mcp.tool()def add(a: int, b: int) -> int:    """计算两个数字之和"""    return a + b@mcp.tool()def get_weather(city: str) -> str:    """获取城市天气"""    url = f"https://wttr.in/{city}?format=3"    return requests.get(url).text# =====================# 2. AI Agent(核心逻辑)# =====================client = OpenAI(api_key="你的API_KEY")def run_agent(user_input: str):    tools = [        {            "type": "function",            "function": {                "name": "add",                "description": "计算两个数字相加",                "parameters": {                    "type": "object",                    "properties": {                        "a": {"type": "integer"},                        "b": {"type": "integer"},                    },                    "required": ["a", "b"],                },            },        },        {            "type": "function",            "function": {                "name": "get_weather",                "description": "获取城市天气",                "parameters": {                    "type": "object",                    "properties": {                        "city": {"type": "string"},                    },                    "required": ["city"],                },            },        },    ]    response = client.chat.completions.create(        model="gpt-4o-mini",        messages=[{"role": "user", "content": user_input}],        tools=tools,    )    msg = response.choices[0].message    # =====================    # 3. 工具调用    # =====================    if msg.tool_calls:        tool_call = msg.tool_calls[0]        name = tool_call.function.name        args = json.loads(tool_call.function.arguments)        if name == "add":            result = add(**args)        elif name == "get_weather":            result = get_weather(**args)        else:            result = "未知工具"        return f"[工具调用] {name} → {result}"    return msg.content# =====================# 4. CLI 入口# =====================if __name__ == "__main__":    print("AI Agent 已启动(输入 exit 退出)")    while True:        user_input = input("请输入问题:")        if user_input == "exit":            break        result = run_agent(user_input)        print(result)

四、代码拆解(核心理解)

这 100 行代码,其实只做了 3 件事:


1️⃣ 定义工具(MCP思想)

@mcp.tool()def add()@mcp.tool()def get_weather()

本质:

把函数变成 AI 可调用工具


2️⃣ 告诉 AI 有哪些工具

tools = [...]

这里定义:

  • 工具名称
  • 参数结构
  • 功能描述

AI 会根据用户问题自动选择。


3️⃣ 执行工具调用

if msg.tool_calls:

流程:

用户输入↓AI判断是否需要工具↓返回 tool_call↓Python执行函数↓返回结果

这一步,就是 Agent 的核心。


五、关键理解:这就是 Agent 的本质

很多人把 AI Agent 想复杂了。

其实核心只有一句话:

AI + Tools + 自动执行

展开就是:

理解问题↓选择工具↓执行工具↓返回结果

你刚刚写的这 100 行代码:

已经是一个完整 AI Agent。


六、进阶升级(3个方向)

如果你想把这个 Agent 做强,可以往这 3 个方向升级:


1️⃣ 多工具系统

send_email()search_news()read_file()write_file()

AI能力 = 工具数量


2️⃣ 多轮对话

加入 memory:

messages = []

实现:

  • 上下文理解
  • 连续任务

3️⃣ 自动执行任务(真正 Agent)

例如:

每天8点执行自动生成报告自动发送邮件

这一步,就进入:

OpenClaw / AutoGPT 的领域


七、一个非常重要的认知

很多人写到这里会有一个顿悟:

AI Agent 不难,难的是工具生态。

未来真正的竞争不是:

模型谁更强

而是:

谁的工具更多谁的工具更好

八、总结

今天你用 100 行 Python,实现了:

  • AI调用工具
  • 自动执行逻辑
  • 基础Agent能力

这已经是:

AI应用开发的核心能力。

如果你是 Python 开发者,现在正处在一个非常关键的时间点:

过去:写 API现在:写 MCP Tools未来:构建 AI 系统

最后一句话

未来的软件,不再是人调用 API,而是 AI 调用你的代码。

而 MCP,就是这场变革的入口。

最新文章

随机文章