← 返回
AI技术

从零做一个自己的 Agent(二):自己写一个 MCP server,再用 Strands Agents 调用它的工具

✍️ zhirenhun 📅 2026/11/17 👁 107 阅读 ⏱ 39 分钟
从零做一个自己的 Agent(二):自己写一个 MCP server,再用 Strands Agents 调用它的工具

系列文章:Once Upon Agentic AI。

尽管拥有了新的能力和无畏的心,我们的英雄仍未击败所有敌人。一个更强大的怪物正在等着他们,比他们此前遭遇的任何对手都更可怕。这一次,光靠自身的力量已经不够了。

本系列分三部分展开这段冒险:

你需要 Python、uv、一个终端,以及可访问 Amazon Bedrock 的 AWS 凭证。

代码位于 aws-samples/sample-once-upon-agentic-ai。main 分支包含带 # TODO 标记的骨架代码。让我们一起学习,保持好奇!

沿用(一)的设置:

git clone https://github.com/aws-samples/sample-once-upon-agentic-ai.git ~/sample-once-upon-agentic-ai
cd ~/sample-once-upon-agentic-ai
uv sync
export AWS_PROFILE=YOUR_AWS_PROFILE AWS_REGION=YOUR_AWS_REGION

还没有配置 AWS profile?Strands Agents 的 Amazon Bedrock 模型提供方指南介绍了如何设置 AWS 凭证(用 aws configure、环境变量、boto3 session 或 aws login),并列出 Agent 调用模型所需的 IAM 权限。Strands 会自动读取这些凭证。

什么是 MCP?

在(一)里,整个 Agent 循环都在同一个 Python 进程中运行:模型读取工具说明,决定调用 roll_dice,Strands 执行该函数,模型再读取结果。MCP(Model Context Protocol,模型上下文协议)是一项开放标准,让 Agent 能使用另一个程序提供的能力。工具就是其中一种,服务器还可以共享数据和可复用的提示词,如下表所示。本文把掷骰子工具移入服务器,Agent 循环保持不变:仍由模型决定调用哪个工具,改变的只是函数运行的位置。

谁和谁通信?MCP 采用客户端/服务器架构:可以类比 HTTP,只不过面向 AI Agent。浏览器向 Web 服务器发送请求并读取响应;MCP 客户端对 MCP 服务器做同样的事,服务器返回自己的工具及执行结果。宿主是 AI 应用,这里就是 Strands Agent。宿主每使用一个服务器,就创建一个客户端,与该服务器保持专用连接。这个客户端就是 TheWitcherish 的绿色光球。服务器是提供能力的程序:客户端用 tools/list 请求时,它列出自己的工具;客户端发送 tools/call 时,它执行其中一个工具。在这两次请求之间,Agent 循环的运行方式与(一)完全相同。

服务器能提供什么?服务器有三类原语,按使用方的控制权划分:

原语 控制方 示例
提示词(Prompts) 用户 系统提示词、少样本示例
资源(Resources) 应用 文件内容、数据库 schema、API 响应
工具(Tools) 模型 一次 API 调用、一次数据库写入

消息如何书写?每条 MCP 消息都是 JSON-RPC 2.0 格式,这是一种用 JSON 调用另一个程序的小型标准。请求包含 id、method 和 params,响应会带回同一个 id,并附带 result 或 error。通知没有 id,因为它不需要回复。下面是一次工具调用:

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search","arguments":{"q":"otters"}}}

消息如何传输?MCP 定义了两种传输方式。使用 stdio 时,客户端把服务器作为子进程启动,通过其标准输入输出交换消息。这是最简单的方案,不需要网络端口,也不需要身份验证,但只有该客户端能使用这个服务器。使用 Streamable HTTP 时,服务器作为独立进程运行,在一个端点接收 HTTP POST 请求。多个客户端可以共享它,无论在本机还是跨网络,但它会开放一个端口,若要让服务器在本机之外共享,就需要 MCP 规范中所述的授权机制。

如果想深入了解,可以查阅MCP 规范原文。

第 1 步:MCP 服务器只是另一个程序里的工具吗?

差不多。服务器可以提供我们前面看到的三种 MCP 原语中的任意一种:工具、资源和提示词。在英雄们的冒险中,我们聚焦于工具。绿色宝珠需要有个对象来对话,于是 TheWitcherish、Amagash 和 Tagazok 构建了它要连接的服务器。他们把幸运女神的骰子从 Agent 中移出,放进自己的文件 4_mcp_integration/dice_roll_mcp_server.py。

他们用 FastMCP(port=8002) 创建服务器,把 @mcp.tool() 放在(一)中同一个 roll_dice 函数上方,并在文件末尾加上启动服务器的那行代码:

import random
import logging
from mcp.server import FastMCP

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

mcp = FastMCP(port=8002)

@mcp.tool()
def roll_dice(faces: int = 6) -> int:
    """Roll one die with a given number of faces and return the result.
    ...
    """
    if faces < 1:
        raise ValueError("Dice must have at least 1 face")

    result = random.randint(1, faces)

    logging.info(f"... DICE ROLL: d{faces} = {result}")

    return result

if __name__ == "__main__":
    mcp.run(transport="streamable-http")

FastMCP 来自官方 MCP Python SDK。和(一)里的 @tool 一样,@mcp.tool() 会把 docstring 和类型提示转成工具描述和输入 schema。函数本身还是老样子,只是换了个地方住。现在每次掷骰结果都会写进服务器自己的日志,让我们在 Agent 之外也能拿到证据。

接下来的问题是,宝珠要怎么连到他们的服务器:

“用 stdio 通信?”

“SSE?”

“我知道了,Streamable HTTP!”

他们选了 Streamable HTTP,服务器通过 transport="streamable-http" 启动。

在一个终端里启动服务器,让它一直运行:

cd ~/sample-once-upon-agentic-ai/4_mcp_integration
uv run python dice_roll_mcp_server.py
INFO - StreamableHTTP session manager started
INFO:     Uvicorn running on http://127.0.0.1:8002 (Press CTRL+C to quit)

它监听 127.0.0.1,这是 FastMCP 的默认主机地址,因此只有本机才能访问。这里不运行任何模型,服务器只等待客户端连接。

第 2 步:在 Agent 调用之前,服务器能正常响应吗?

这一步用 Node.js 运行 MCP Inspector。如果终端里执行 node --version 没有输出版本号,请先从 Node.js 下载页面安装 Node.js。

先单独测试服务器。万一 Agent 表现异常,你需要判断问题出在服务器还是模型上,所以在接入任何模型之前,先单独检查服务器。MCP Inspector 是测试和调试 MCP 服务器的参考工具。它本身是一个不带模型的 MCP 客户端,因此能准确展示 Agent 会收到什么。MCP 骰子服务器启动后,再打开一个终端。

npx @modelcontextprotocol/inspector@2.15.0 会打开 Web 界面,在其中添加服务器 URL http://127.0.0.1:8002/mcp,传输方式选 Streamable HTTP。这个工具还有命令行模式,会把每个响应以文本形式打印出来,下面的跟踪记录就来自该模式。首先,与服务器握手:

npx @modelcontextprotocol/inspector@2.15.0 --cli http://127.0.0.1:8002/mcp --transport http --method initialize
{
  "serverInfo": {
    "name": "FastMCP",
    "version": "1.30.0"
  },
  "protocolVersion": "2025-11-25",
  "capabilities": {
    ...
    "tools": {
      "listChanged": false
    }
  }
}

服务器会自报身份、所支持的协议版本以及提供的能力。"protocolVersion": "2025-11-25" 就是这版 MCP Python SDK 使用的协议版本。接下来,问一个 Agent 在启动时会问的问题:tools/list:

npx @modelcontextprotocol/inspector@2.15.0 --cli http://127.0.0.1:8002/mcp --transport http --method tools/list
{
  "tools": [
    {
      "name": "roll_dice",
      "description": "Roll one die with a given number of faces and return the result.\n\n...faces: Number of faces on the die, 1 or more. ...",
      "inputSchema": {
        "type": "object",
        "properties": {
          "faces": {
            "default": 6,
            "title": "Faces",
            "type": "integer"
          }
        },
        "title": "roll_diceArguments"
      },
      "outputSchema": {
        ...
        "properties": {
          "result": {
            "title": "Result",
            "type": "integer"
          }
        },
        ...
      }
    }
  ]
}

这与(一)的 tool_spec 里的对比相同,只是现在通过网络传输读取。docstring 变成了 description,类型提示变成了 "type": "integer",默认值变成了 "default": 6。服务器还会发送一个 outputSchema,而(一)里的本地工具没有这个字段。不过要注意边界条件:“1 or more”只出现在描述文本里。schema 本身没有 minimum,所以模型只能通过阅读描述来了解这个边界,再由函数来强制执行。先用合法值调用一次工具,再用非法值调用一次:

npx @modelcontextprotocol/inspector@2.15.0 --cli http://127.0.0.1:8002/mcp --transport http --method tools/call --tool-name roll_dice --tool-arg faces=20
npx @modelcontextprotocol/inspector@2.15.0 --cli http://127.0.0.1:8002/mcp --transport http --method tools/call --tool-name roll_dice --tool-arg faces=0
{
  "content": [
    {
      "type": "text",
      "text": "19"
    }
  ],
  "structuredContent": {
    "result": 19
  },
  "isError": false
}
{
  "content": [
    {
      "type": "text",
      "text": "Error executing tool roll_dice: Dice must have at least 1 face"
    }
  ],
  "isError": true
}

骰子服务器的终端记录下了两次访问,而且那次好点数也对得上:

2026-11-11 15:44:58,566 - INFO - Processing request of type ListToolsRequest
2026-11-11 15:44:58,570 - INFO - Processing request of type CallToolRequest
2026-11-11 15:44:58,570 - INFO - ... DICE ROLL: d20 = 19
...
2026-11-11 15:44:59,836 - INFO - Processing request of type ListToolsRequest
2026-11-11 15:44:59,839 - INFO - Processing request of type CallToolRequest

Inspector 在每次调用前都会读取工具列表,和 Agent 的做法一样。faces=0 通过了 schema 校验,却在 if faces < 1 这个检查处被拦下,于是服务器返回一个带 "isError": true 的错误结果,而不是直接崩溃,Inspector 则以退出码 5 结束。

这个边界也可以写进 schema,这样模型看到的就是一条规则,而不用从文字描述里去读。仓库代码里还没有这个改动:你可以在自己的 dice_roll_mcp_server.py 里试一下,用 Annotated 和 Pydantic 的 Field 来声明 faces:

from typing import Annotated
from pydantic import Field

@mcp.tool()
def roll_dice(faces: Annotated[int, Field(ge=1)] = 6) -> int:

重启服务器,再次运行 tools/list。此时 faces 已带上绑定信息:

"faces": {
  "default": 6,
  "minimum": 1,
  "title": "Faces",
  "type": "integer"
}

再次调用时传入 faces=0。这一次,Pydantic 会在 roll_dice 执行之前就拒绝该值:

"text": "Error executing tool roll_dice: 1 validation error for roll_diceArguments\nfaces\n  Input should be greater than or equal to 1 [type=greater_than_equal, input_value=0, input_type=int]..."

服务器日志里出现了 CallToolRequest,却没有 DICE ROLL 这一行:函数根本没执行。服务器有响应。接下来该让 Agent 来调用它了。

第 3 步:Agent 需要工具的代码吗?

不需要。有服务器地址就够了。gamemaster_mcp_client.py 定义了一个名为 gamemaster 的 Agent,以幸运女神的口吻说话,其中没有任何掷骰子的实现:

from strands import Agent
from strands.tools.mcp import MCPClient

mcp_dice_client = MCPClient(url="http://localhost:8002/mcp")

gamemaster = Agent(
    system_prompt="""You are Lady Luck, the mystical keeper of dice and fortune in fantasy role-playing adventures.
    ...""",
    tools=[mcp_dice_client]
)

gamemaster("Help me create a new fantasy character! Roll the strength, wisdom, charisma and intelligence abilities scores using 4d6 drop lowest method.")

把服务器的 url 传给 MCPClient,再把它加入 tools。对 Strands 来说,MCP 工具就是普通工具。MCPClient 充当工具提供方:Agent 启动时,客户端会发出与你刚才用 Inspector 执行的相同的 tools/list 请求,收到的每个工具都会带着名称、描述和输入 schema 加入 Agent 的工具列表,和(一)里的 @tool 函数完全一样。模型选中 roll_dice 后,Strands 会把调用转发给服务器。

三种原语中,只有工具会到达模型。服务器的提示词和资源仍可通过同一个客户端供你自己的代码使用,对应方法是 list_prompts_sync()、get_prompt_sync()、list_resources_sync() 和 read_resource_sync(),何时使用由你决定。

是时候掷出幸运女神的骰子了!

确认 MCP 骰子服务器仍在它的终端里运行。然后另开一个终端,从那里发起调用。这次 Agent 会调用 Amazon Bedrock 上的模型,因此该终端需要有效的 AWS 凭证:导出与初始设置相同的 AWS_PROFILE 和 AWS_REGION,并在运行客户端前用 aws sts get-caller-identity 检查一下:

cd ~/sample-once-upon-agentic-ai/4_mcp_integration
export AWS_PROFILE=YOUR_AWS_PROFILE AWS_REGION=YOUR_AWS_REGION
aws sts get-caller-identity
uv run python gamemaster_mcp_client.py

如果 aws sts get-caller-identity 返回的是错误信息,而不是你的账号和角色,请先刷新凭证;否则客户端会在第一次调用模型时就因 NoCredentialsError 或 token 过期错误而中止。

想了解 SDK 具体做了什么,可以复用 dice 服务器在 gamemaster_mcp_client.py 顶部的日志配置行,把 INFO 改成 DEBUG:

import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

根 logger 上的 DEBUG 还会打印 AWS SDK 自身的请求和响应,因此输出很长:在其中搜索 mcp 和 stop_reason 即可。跟踪日志会逐步记录 SDK 的每一步:

2026-11-12 13:41:13,578 - DEBUG - [...] transport connection established
2026-11-12 13:41:13,584 - DEBUG - [...] session initialized successfully
2026-11-12 13:41:13,591 - DEBUG - [...] received 1 tools from MCP server
2026-11-12 13:41:13,591 - DEBUG - tool_name=<roll_dice> | creating mcp agent tool
...
2026-11-12 13:41:16,639 - DEBUG - stop_reason=<tool_use> | model call succeeded, resetting retry state
...
Tool #1: roll_dice
Tool #2: roll_dice
...
Tool #16: roll_dice

客户端建立连接,收到一个工具,并将其封装为 Agent 工具。模型以 stop_reason=<tool_use> 停止,并在同一轮中请求掷十六次骰子:四项能力各掷四颗骰子。幸运女神报出第一项能力值,已去掉最低骰:

力量
掷骰:3, 6, 4, 2 → 3 + 6 + 4 = 13

服务器日志也遵循同样的路径:

INFO - Created new transport with session ID: 6b20ac77014340f8b57cbd4fa3443214
INFO - Processing request of type ListToolsRequest
INFO - Processing request of type CallToolRequest
INFO - ... DICE ROLL: d6 = 3
INFO - Processing request of type CallToolRequest
INFO - ... DICE ROLL: d6 = 6
INFO - Processing request of type CallToolRequest
INFO - ... DICE ROLL: d6 = 4
INFO - Processing request of type CallToolRequest
INFO - ... DICE ROLL: d6 = 2
...

ListToolsRequest 对应 tools/list;每个 CallToolRequest 对应一次 tools/call。在 roll_dice 执行之前,FastMCP 会用 Pydantic 按工具的输入 schema 校验参数。这就是塔上的“Request Validated”。

现在把两边并排对照。服务器日志记录了十六次掷骰。模型的下一次请求携带了十六个工具结果:

第 1 至 16 次掷骰
服务器日志 3 6 4 2 · 2 1 2 4 · 5 4 1 3 · 5 4 5 6
模型收到 3 6 4 2 · 2 1 4 2 · 5 4 1 3 · 5 4 5 6

两边出现的十六个值完全相同。第 7 次和第 8 次掷骰互换了位置,因为 Strands 会并发执行同一轮中的工具调用。因此,相邻的结果返回顺序可能与服务器记录的顺序不同。

所以,每个数字在模型看到之前,都已经存在于带时间戳的服务器日志中。模型只是复述结果,从未真正掷骰。当它的回复与服务器日志不一致时,以日志为准。

现在你来试试:让 Lady Luck 也掷一下敏捷和体质。然后数一数服务器日志中新增的 DICE ROLL 行。你应该会找到八行。

跟随冒险者

在第 3 部分中,编排器 Agent 会查阅我们角色扮演游戏的规则,因为 Tagazok 可能不被允许使用某种非常特定的能力,而 Amagash 将学会用结构化输出为她的工具赋予形态。

在此之前,请保持两个习惯:

本博文中的漫画插图由 Holy Bird 基于 AWS 研讨会创作并制作。

版权所有。

——

广告 广告
🧑‍💻

zhirenhun

一个热爱技术的程序员,喜欢分享前沿AI知识和开发经验。

ai mcp opensource aws