当前位置: 首页 > news >正文

告别无状态:Bedrock AgentCore 有状态 MCP Server 开发实录

搞 MCP 开发的应该都碰过这个问题——server 不记状态。每次请求都是从零开始,上一轮用户说了什么完全不知道。

这在简单场景没啥,但做复杂 agent 就很烦。比如订机票,用户得一口气把目的地、日期、人数、舱位全说清楚,不能分步来。

上周亚马逊云科技给 Bedrock AgentCore Runtime 加了有状态 MCP 支持。三个新能力:Elicitation(主动追问)、Sampling(反向调 LLM)、Progress Notifications(进度通知)。我试了一天,记录一下。

怎么用

核心是 FastMCP 库,版本要 >= 2.10.0:

pip install "fastmcp>=2.10.0" mcp

Server 端

from fastmcp import FastMCP, Context
from enum import Enum
import asynciomcp = FastMCP("Travel-Booking-Agent")class TripType(str, Enum):BUSINESS = "business"LEISURE = "leisure"FAMILY = "family"DESTINATIONS = {"paris": {"name": "Paris, France", "flight": 450, "hotel": 180,"highlights": ["Eiffel Tower", "Louvre", "Notre-Dame"]},"tokyo": {"name": "Tokyo, Japan", "flight": 900, "hotel": 150,"highlights": ["Shibuya", "Senso-ji Temple"]},
}@mcp.tool()
async def plan_trip(ctx: Context) -> str:# Elicitation: 多轮追问dest_result = await ctx.elicit(message="Where would you like to go? (Paris/Tokyo)",response_type=str)if dest_result.action != "accept":return "Cancelled."dest = DESTINATIONS.get(dest_result.data.lower().strip())type_result = await ctx.elicit(message="Trip type? (business/leisure/family)",response_type=TripType)days_result = await ctx.elicit(message="How many days? (3-14)",response_type=int)days = max(3, min(14, days_result.data))# Progress: 搜索进度for i in range(1, 6):await ctx.report_progress(progress=i, total=5)await asyncio.sleep(0.4)# Sampling: 让客户端的 LLM 生成推荐try:resp = await ctx.sample(messages=f"3 tips for {dest['name']}, {days} days",max_tokens=150)tips = resp.text if hasattr(resp, 'text') and resp.text else ""except Exception:tips = f"Visit {dest['highlights'][0]}!"total = dest["flight"] * 2 + dest["hotel"] * daysreturn f"Booked: {dest['name']}, {days} days, ${total}\nTips: {tips}"# 启动时必须关闭无状态模式
mcp.run(transport="streamable-http",host="0.0.0.0",port=8000,stateless_http=False
)

客户端

from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
from fastmcp.client.elicitation import ElicitResult
from mcp.types import CreateMessageResult, TextContentasync def elicit_handler(message, response_type, params, ctx):print(f"\n>>> {message}")answer = input("回答: ").strip()if response_type == int:answer = int(answer)return ElicitResult(action="accept", content={"value": answer})async def sampling_handler(messages, params, ctx):return CreateMessageResult(role="assistant",content=TextContent(type="text", text="试试当地美食!"),model="local",stopReason="endTurn")transport = StreamableHttpTransport(url="http://localhost:8000/mcp")
client = Client(transport,elicitation_handler=elicit_handler,sampling_handler=sampling_handler)

部署到 AgentCore

pip install bedrock-agentcore-starter-toolkit
agentcore configure -e travel_server.py -p MCP -n travel_agent_demo
agentcore deploy

每个 session 在独立 microVM 里运行,session 之间隔离。

踩坑

  • stateless_http 默认 True,不关就用不了 elicitation
  • Session 有超时,客户端要处理 404 重连
  • sampling_handler 返回空文本会导致 server 端字符串拼接报错

适用场景

有状态 MCP 把多轮对话能力从 agent 框架层下沉到 tool 层面。适合多步骤表单、审批流程、交互式调试、个性化推荐等场景。

目前 14 个区域可用,含亚太区的孟买、首尔、新加坡、悉尼、东京。

http://www.jsqmd.com/news/527354/

相关文章:

  • Mac终端文件操作全攻略:从创建到删除的完整命令手册
  • 2026年聊聊国际化CPVC电力管供应商,CPVC电力管价格怎么算 - 工业品网
  • NumPy数组切片语法
  • scrapy框架下载与创建
  • Unity多线程避坑指南:为什么你的子线程总崩溃?
  • 船舶/无人艇/无人船,线性nomoto响应型操纵运动,回转实验和Z型实验MATLAB仿真程序(...
  • 深圳寄修安全|2026高端奢华腕表寄修全指南(含6城正规门店及全品牌维修明细) - 时光修表匠
  • Photoshop安装教程 2026最新版详细图文安装教程
  • 2026无锡GEO运营|推广|优化公司获客能力深度评测报告 - 资讯焦点
  • WSL2 中部署 Pixel Mind Decoder:Windows 开发者的 Linux 模型测试方案
  • CyberChef:解锁数据处理能力的安全分析瑞士军刀
  • 【含文档+源码】基于SSM框架的宠物领养系统设计与实现
  • 【OpenClaw 全面解析:从零到精通】第 004 篇:OpenClaw 在 Linux/Ubuntu 上的安装与部署实战
  • STM32嵌入式开发笔记的智能整理:BERT文本分割模型应用尝试
  • 树莓派安装与配置
  • 探索C++标准库中的算法:<algorithm> 头文件概览
  • 别再只用RSA了!手把手教你用Java SM2国密算法给接口数据加个密
  • 2026年路面灌缝胶厂家推荐:泰安市元博工程材料有限公司,沥青灌缝胶/聚氨酯灌缝胶/道路灌缝胶厂家精选 - 品牌推荐官
  • 本地商家做小红书3个月0咨询?90%都死在路径全错 - Redbook_CD
  • Z-Image-Turbo-辉夜巫女提示词工程入门:从C语言逻辑到自然语言描述的转换技巧
  • RAKwireless SDI-12库深度解析:嵌入式环境传感器通信实现
  • MC33926电机驱动芯片原理与STM32嵌入式实践
  • eVTOL应急消杀模块功率链路优化:基于高压隔离、高效驱动与精准负载管理的MOSFET选型方案
  • 7.MySQL-InnoDB
  • 大润发购物卡高价回收,立即变现! - 团团收购物卡回收
  • Day1学习笔记 --AIAgent 项目 --文件上传与解析(一)
  • CLIP-GmP-ViT-L-14图文匹配测试工具:在Ubuntu服务器上的生产环境部署详解
  • Qwen3-0.6B-FP8作品集:FP8模型在正则表达式生成任务准确率
  • Adafruit Unified Sensor传感器抽象层原理与工程实践
  • 零门槛上手:五款永久免费内网穿透工具实战指南