AREL
AREL — 智能体可靠性与评测实验室
一个面向生产的可靠性、基准测试与评测系统,构建于 MCP 智能体运行时之上。
为什么存在
上游 MCP 智能体运行时是使用 Model Context Protocol 组合智能体的优秀框架——但要将其交付到生产环境,仅靠组合原语是不够的。真实的生产系统需要多版本协议协商、点对点智能体发现、感知背压的流式传输、带熔断器的连接池、可热重载的插件架构、弹性重试与状态恢复,以及带自动扩缩容的持续健康监控。
AREL 以上游运行时为基础,在其上叠加了一个完整的可靠性、基准测试与评测平台:
支持 5 个协议版本(MCP 1.0 → 2.1 + A2A v0.3),具备正式协商与弃用警告
9 个新子系统以增量、非侵入式模块实现(3 155 行源码,2 096 行测试)
新增 109 个测试——0 回归,套件通过率从 85.9% → 99.4% 恢复
新
enhancements包的行覆盖率 82%470 k msg/s 自适应流式吞吐量(比朴素基线提升 +34%)
一览
能力 | 之前 | 之后 |
测试通过率 | 1292 / 1503(85.9%) | 1602 / 1612(99.4%) |
新增测试 | — | 109(0 回归) |
| n/a | 82% |
MCP 协议版本 | 1.0 – 1.20 | 1.0 – 2.1 + A2A v0.3 |
自适应流式吞吐量 | 352 k msg/s(朴素) | 470 k msg/s(+34%) |
连接池复用 | — | 工厂调用减少约 4 倍 |
新子系统 | — | 9(见能力面) |
新增源码行数 | — | 3 155(12 个文件) |
新增测试行数 | — | 2 096(11 个文件) |
架构
Architecture
├── Benchmark methodology
├── Evaluation methodology
├── Fault injection
├── Observability
├── Measured results
└── Reproducibility上述每个分支都由 src/mcp_agent/enhancements/ 下的具体模块实现,并由 tests/enhancements/ 下的测试套件验证。这些分支并非营销文案——它们与文件、类和可衡量的数字一一对应(见下文实测结果)。
系统架构
下图展示了 AREL 如何位于上游 MCP 智能体运行时之上。上游 mcp_agent.* 包(左侧,灰色)提供组合原语;新的 mcp_agent.enhancements.* 包(右侧,彩色)提供可靠性、基准测试与评测平台。两者通过 HybridMCPA2AGateway 和 ResilientExecutor 连接在一起——其余部分均为增量式,可以逐步采用。
flowchart LR
subgraph UP["Upstream mcp_agent runtime (Apache-2.0, unchanged)"]
direction TB
APP["MCPApp<br/>context & lifecycle"]
AGENT["Agent + AgentSpec"]
LLM["AugmentedLLM<br/>(OpenAI/Anthropic/Bedrock/…)"]
WF["Workflows<br/>orchestrator · router · parallel · swarm"]
MCP["MCP client<br/>stdio + HTTP transports"]
TRACE["OpenTelemetry tracing"]
LOG["Rich structured logging"]
end
subgraph ENH["AREL enhancements package (this project)"]
direction TB
P1A["P1.1 Protocol<br/>MCPProtocolAdapter"]
P1B["P1.2 A2A<br/>AgentCard · A2AClient<br/>HybridMCPA2AGateway"]
P2A["P2.1 Streaming<br/>AdaptiveStreamProcessor<br/>StreamingMultiplexer"]
P2B["P2.2 Connection<br/>MCPConnectionPool<br/>CircuitBreaker · QuotaManager"]
P3A["P3.1 Plugin<br/>PluginManager<br/>(hot-reload)"]
P3B["P3.2 Patterns<br/>WorkflowPatternRegistry<br/>PatternComposer"]
P4A["P4.1 Resilience<br/>ResilientExecutor<br/>RetryPolicy · FallbackChain<br/>StateRecovery"]
P4B["P4.2 Health<br/>HealthMonitor<br/>HealthCheck · AutoScaler"]
end
subgraph EXT["External surfaces"]
direction TB
PEER["A2A peer agents"]
LLM_API["LLM provider APIs"]
MCP_SRV["MCP servers"]
USER["Operator / SRE"]
end
APP --> AGENT --> LLM
AGENT --> WF
WF --> MCP
MCP --> MCP_SRV
LLM --> LLM_API
P1A -. negotiates .-> MCP
P1B -. bridges .-> MCP
P1B <--> PEER
P2A -. wraps streams .-> WF
P2B -. pools .-> MCP
P2B -. guards .-> LLM
P3A -. injects into .-> APP
P3B -. extends .-> WF
P4A -. wraps .-> WF
P4A -. wraps .-> P1B
P4B -. observes .-> P2B
P4B -. observes .-> P2A
P4B -. emits signals .-> USER
TRACE -. consumes .-> ENH
LOG -. consumes .-> ENH
classDef upstream fill:#F5F5F5,stroke:#999999,color:#333333
classDef enh fill:#EEF2FF,stroke:#425CC7,color:#1E1B4B
classDef ext fill:#FEF3C7,stroke:#D97706,color:#78350F
class APP,AGENT,LLM,WF,MCP,TRACE,LOG upstream
class P1A,P1B,P2A,P2B,P3A,P3B,P4A,P4B enh
class PEER,LLM_API,MCP_SRV,USER ext分层视图
四个 P 层组构成一个分层结构。P1 是协议基础;P2 是传输与资源层;P3 是可扩展性层;P4 是韧性与运维层,负责观察并保护其下的一切。
flowchart TB
subgraph L4["P4 — Resilience & Operations"]
HM["HealthMonitor + AutoScaler<br/>(EWMA · predictive)"]
RE["ResilientExecutor<br/>(retry · fallback · state recovery)"]
end
subgraph L3["P3 — Extensibility"]
PM["PluginManager<br/>(hot-reload)"]
PR["WorkflowPatternRegistry<br/>+ PatternComposer"]
end
subgraph L2["P2 — Transport & Resources"]
ASP["AdaptiveStreamProcessor<br/>(3 QoS tiers · backpressure)"]
CP["MCPConnectionPool<br/>+ CircuitBreaker + QuotaManager"]
end
subgraph L1["P1 — Protocol"]
PA["MCPProtocolAdapter<br/>(5 versions · deprecation)"]
A2A["A2A Gateway<br/>(discovery · task lifecycle)"]
end
subgraph L0["Foundation"]
RUNTIME["Upstream MCP agent runtime<br/>(MCPApp · Agent · AugmentedLLM · Workflows)"]
end
L4 --> L3 --> L2 --> L1 --> L0
HM -. observes .-> CP
HM -. observes .-> ASP
RE -. wraps .-> A2A
RE -. wraps .-> CP
PM -. injects .-> RUNTIME
PR -. extends .-> RUNTIME
classDef l0 fill:#F5F5F5,stroke:#999999,color:#333333
classDef l1 fill:#E0E7FF,stroke:#425CC7,color:#1E1B4B
classDef l2 fill:#C7D2FE,stroke:#425CC7,color:#1E1B4B
classDef l3 fill:#A5B4FC,stroke:#425CC7,color:#1E3A8A
classDef l4 fill:#818CF8,stroke:#312E81,color:#FFFFFF
class RUNTIME l0
class PA,A2A l1
class ASP,CP l2
class PM,PR l3
class HM,RE l4工作流图
请求在弹性执行器中的生命周期
一个典型的智能体请求依次流经协议适配器(协商版本)、连接池(获取池化连接)、弹性执行器(失败时重试,必要时回退到 A2A 对等节点)、自适应流处理器(按 QoS 消费 LLM 流),以及健康监控器(记录延迟与错误率)。各步骤之间会保存状态快照,因此重试可以从中途恢复,而无需重做已完成的工作。
sequenceDiagram
autonumber
participant Caller as Caller
participant PA as MCPProtocolAdapter
participant CP as MCPConnectionPool
participant CB as CircuitBreaker
participant RE as ResilientExecutor
participant SR as StateRecovery
participant LLM as AugmentedLLM
participant ASP as AdaptiveStreamProcessor
participant HM as HealthMonitor
participant AS as AutoScaler
Caller->>PA: negotiate(version)
PA-->>Caller: NegotiatedCapabilities
Caller->>RE: execute_with_resilience(fn, workflow_id)
RE->>SR: load(workflow_id)
alt snapshot exists
SR-->>RE: snapshot(step=N)
RE->>RE: resume from step N
else no snapshot
RE->>RE: start from step 0
end
RE->>CP: acquire(target)
CP->>CB: before_call()
alt breaker OPEN
CB-->>CP: false (fast-fail)
CP-->>RE: CircuitBreakerOpenError
RE->>RE: fallback chain
else breaker CLOSED / HALF_OPEN
CB-->>CP: true
CP-->>RE: connection
RE->>LLM: generate_stream(prompt)
loop over tokens
LLM-->>ASP: token (QoS=BEST_EFFORT)
ASP-->>Caller: token
end
RE->>CP: release(connection)
CP->>CB: record_success()
RE->>SR: save(workflow_id, step, state)
end
par health observation
ASP->>HM: latency + error_rate
LLM->>HM: latency + error_rate
HM->>HM: EWMA update
alt status transition
HM->>AS: on_unhealthy / on_recovered
AS-->>Caller: ScaleSignal (UP / DOWN)
end
end
RE-->>Caller: result / ExecutionStatsA2A 网关:将对等智能体桥接到 MCP
HybridMCPA2AGateway 使远程 A2A 智能体以本地 MCP 工具的形式出现(命名为 a2a__<agent_name>)。该网关处理智能体发现(通过 /.well-known/agent.json)、任务生命周期(submitted → working → input-required → completed/canceled/failed)以及传输选择(生产环境用 HTTP,测试用进程内)。
flowchart TB
subgraph CLIENT["MCP client"]
CALL["call_tool('a2a__researcher', input)"]
end
subgraph GW["HybridMCPA2AGateway"]
LT["list_tools()"]
DISP["dispatch(name, input)"]
REG["registry:<br/>name → A2AClient"]
end
subgraph A2A_PEER_A["A2A peer: researcher"]
AC1["AgentCard<br/>/.well-known/agent.json"]
TS1["A2AServer<br/>task lifecycle"]
end
subgraph A2A_PEER_B["A2A peer: coder"]
AC2["AgentCard"]
TS2["A2AServer"]
end
subgraph TRANSP["Transport"]
HTTP["httpx<br/>(production)"]
INPROC["in-proc<br/>(tests)"]
end
CALL --> DISP
LT --> DISP
DISP --> REG
REG -- "researcher" --> AC1
REG -- "coder" --> AC2
AC1 --> TS1
AC2 --> TS2
TS1 --> HTTP
TS2 --> HTTP
TS1 -. test .-> INPROC
TS2 -. test .-> INPROC
classDef client fill:#FEF3C7,stroke:#D97706,color:#78350F
classDef gw fill:#EEF2FF,stroke:#425CC7,color:#1E1B4B
classDef peer fill:#FCE7F3,stroke:#BE185D,color:#831843
classDef trans fill:#D1FAE5,stroke:#059669,color:#064E3B
class CALL client
class LT,DISP,REG gw
class AC1,TS1,AC2,TS2 peer
class HTTP,INPROC trans熔断器状态机
三种状态,恢复跳闸时指数退避,为健康监控器提供 on_trip 异步回调。
stateDiagram-v2
[*] --> CLOSED
CLOSED --> OPEN: failures ≥ failure_threshold
OPEN --> HALF_OPEN: open_timeout_s elapsed
HALF_OPEN --> CLOSED: success ≥ success_threshold
HALF_OPEN --> OPEN: any failure
note right of OPEN
Fast-fail all calls.
Backoff = base_s × 2^(trips-1)
capped at backoff_max_s.
Fires on_trip callback.
end note
note right of HALF_OPEN
Allow probe requests.
Reset backoff if recovery
succeeds.
end note自适应流式传输:QoS 与背压
AdaptiveStreamProcessor 是一个有界队列,具有三个 QoS 层级。当队列满时,各层级的策略决定是丢弃、阻塞,还是将背压传播给自动扩缩器。
flowchart TB
subgraph PROD["Producer"]
P1["emit(item, qos)"]
end
subgraph Q["AdaptiveStreamProcessor (bounded queue)"]
DECIDE{"queue full?"}
T1["DROPPABLE<br/>priority=1"]
T2["BEST_EFFORT<br/>priority=5"]
T3["REALTIME<br/>priority=10"]
BUF["bounded buffer<br/>(maxsize)"]
end
subgraph CONS["Consumer"]
C1["async for item in proc.process()"]
end
subgraph REACT["Reactive hooks"]
DROP["drop oldest<br/>++dropped"]
BLOCK["block producer<br/>++backpressure_events"]
SCALE["on_backpressure()<br/>→ AutoScaler.SCALE_UP"]
end
P1 --> DECIDE
DECIDE -- yes --> T1
DECIDE -- yes --> T2
DECIDE -- yes --> T3
DECIDE -- no --> BUF
T1 --> DROP
T2 --> BLOCK
T3 --> SCALE
DROP --> BUF
BLOCK --> BUF
SCALE --> BUF
BUF --> C1
classDef prod fill:#FEF3C7,stroke:#D97706,color:#78350F
classDef q fill:#EEF2FF,stroke:#425CC7,color:#1E1B4B
classDef cons fill:#D1FAE5,stroke:#059669,color:#064E3B
classDef react fill:#FEE2E2,stroke:#DC2626,color:#7F1D1D
class P1 prod
class DECIDE,T1,T2,T3,BUF q
class C1 cons
class DROP,BLOCK,SCALE react健康监控器与自动扩缩器反馈回路
健康监控器按计划运行已注册的检查,计算最近 20 次调用的 EWMA 延迟和 EWMA 错误率,并且仅在状态转换时触发 on_unhealthy / on_recovered 回调(而非每次检查都触发),以避免告警风暴。自动扩缩器订阅这些转换,并发出带各组件冷却时间的 SCALE_UP / SCALE_DOWN 信号。
flowchart LR
subgraph TARGETS["Observed components"]
DB["db"]
CACHE["cache"]
LLM_API["LLM API"]
MCP_SRV["MCP server"]
end
subgraph MON["HealthMonitor"]
SCHED["schedule loop"]
EWMA["EWMA latency<br/>EWMA error_rate<br/>(window=20)"]
STATE["status per component<br/>HEALTHY / DEGRADED /<br/>UNHEALTHY / UNKNOWN"]
CB_ON["on_unhealthy<br/>(transition only)"]
CB_OFF["on_recovered<br/>(transition only)"]
end
subgraph SCALE["AutoScaler"]
DECIDE{"transition?"}
UP["SCALE_UP<br/>(UNHEALTHY)"]
DOWN["SCALE_DOWN<br/>(HEALTHY + cooldown)"]
HOLD["HOLD"]
end
TARGETS --> SCHED
SCHED --> EWMA
EWMA --> STATE
STATE -- degraded --> CB_ON
STATE -- healthy --> CB_OFF
CB_ON --> DECIDE
CB_OFF --> DECIDE
DECIDE -- unhealthy --> UP
DECIDE -- healthy + cooldown ok --> DOWN
DECIDE -- otherwise --> HOLD
UP -. feeds .-> TARGETS
DOWN -. feeds .-> TARGETS
classDef targets fill:#FEF3C7,stroke:#D97706,color:#78350F
classDef mon fill:#EEF2FF,stroke:#425CC7,color:#1E1B4B
classDef scale fill:#FCE7F3,stroke:#BE185D,color:#831843
class DB,CACHE,LLM_API,MCP_SRV targets
class SCHED,EWMA,STATE,CB_ON,CB_OFF mon
class DECIDE,UP,DOWN,HOLD scale本版本的新增内容
改进计划中的八个工作流已作为增量、自包含模块实现。mcp_agent.* 中没有任何现有调用点被修改(除了一处上游缺陷修复——见 audit.md §2)。新代码隔离在 src/mcp_agent/enhancements/ 下:
ID | 工作流 | 模块 | 核心类 / 函数 |
P1.1 | 协议协商与兼容性 |
|
|
P1.2 | 智能体到智能体(A2A)协议 |
|
|
P2.1 | 带背压的自适应流式传输 |
|
|
P2.2 | 连接池与熔断器 |
|
|
P3.1 | 热重载插件架构 |
|
|
P3.2 | 自定义工作流模式注册表 |
|
|
P4.1 | 弹性执行与状态恢复 |
|
|
P4.2 | 健康监控与自动扩缩容 |
|
|
完整的工程记录——包括每个模块的动机与实现方式、考虑过的设计备选方案,以及上述每个数字的复现说明——位于 audit.md(595 行)。一份面向使用者的简短清单位于 ENHANCEMENTS.md。
能力面
from mcp_agent.enhancements import (
# P1.1 — protocol
MCPProtocolAdapter, CompatibilityLayer, LATEST_PROTOCOL_VERSION,
# P1.2 — A2A
AgentCard, A2AClient, A2AServer, HybridMCPA2AGateway, A2ATask, TaskState,
# P2.1 — streaming
AdaptiveStreamProcessor, StreamingMultiplexer, QoSTier, StreamStats,
# P2.2 — connection
MCPConnectionPool, CircuitBreaker, CircuitState, QuotaManager,
# P3.1 — plugin
Plugin, PluginManager, load_plugin,
# P3.2 — workflow patterns
WorkflowPatternRegistry, register_workflow_pattern, PatternComposer,
# P4.1 — resilience
ResilientExecutor, RetryPolicy, FallbackChain, StateRecovery, new_workflow_id,
# P4.2 — health
HealthMonitor, HealthCheck, HealthStatus, AutoScaler, ScaleDecision,
)上述每个符号都有单元测试覆盖;109 个可运行示例见 tests/enhancements/。
快速开始
安装
# clone
git clone <this-repo> mcp-agent && cd mcp-agent
# install with uv (recommended)
uv sync
# or with pip + venv
python -m venv .venv && source .venv/bin/activate
pip install -e ".[anthropic,openai]"
pip install -e ".[dev]"运行一个基础智能体(上游运行时,未改动)
import asyncio
from mcp_agent.app import MCPApp
from mcp_agent.agents.agent import Agent
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
app = MCPApp(name="hello")
async def main() -> None:
async with app.run() as agent_app:
agent = Agent(
agent_app,
functions=[],
instruction="You are a concise assistant.",
)
llm = await agent.attach_llm(OpenAIAugmentedLLM)
print(await llm.generate_str("Say hello in one sentence."))
asyncio.run(main())使用新的可靠性层
import asyncio
from mcp_agent.enhancements import (
AdaptiveStreamProcessor, QoSTier,
CircuitBreaker, CircuitState,
HealthMonitor, HealthCheck, HealthStatus,
)
async def main():
# adaptive streaming with 3 QoS tiers + backpressure
proc = AdaptiveStreamProcessor(maxsize=1024)
async def producer():
for i in range(10_000):
await proc.put(i, qos=QoSTier.BEST_EFFORT)
await proc.close()
async def consumer():
async for item in proc.process():
...
await asyncio.gather(producer(), consumer())
print(proc.stats) # StreamStats(items_in=10_000, items_out=10_000, ...)
# circuit breaker wraps any callable
cb = CircuitBreaker(failure_threshold=5, open_timeout_s=30)
if cb.before_call():
try:
... # do work
cb.record_success()
except Exception:
cb.record_failure()
# health monitor with EWMA + autoscaler hook
monitor = HealthMonitor()
monitor.register("db", HealthCheck(check=lambda: (HealthStatus.HEALTHY, "ok")))
await monitor.check_once()
asyncio.run(main())更多示例见 examples/(上游)和 src/mcp_agent/enhancements/examples/(新增内置演示)。
架构深入解析
P1.1 — 协议协商(enhancements/protocol/)
现在有五个 MCP 协议版本是一等公民:1.0、1.20、2.0、2.1,外加 A2A v0.3。MCPProtocolAdapter 在客户端与服务器之间选择双方共同支持的最高版本,将能力规范化为 NegotiatedCapabilities 对象,并暴露 DEPRECATED_IN_V2 / V2_ONLY_FEATURES 列表。CompatibilityLayer 包装一个会话,并:
当在 v2 会话上发起仅 v1 支持的调用(
roots/list、resources/list)时,发出DeprecationWarning,让使用者获得柔和的迁移信号;当在 v1 会话上尝试仅 v2 支持的调用时,抛出
ProtocolFeatureUnavailable,让调用方快速失败,而不是静默地空操作。
该模块是纯 Python 实现,没有 I/O——无需运行中的 MCP 服务器即可进行单元测试。
P1.2 — 智能体到智能体协议(enhancements/a2a/)
实现了 A2A v0.3 规范(通过 /.well-known/agent.json 进行智能体发现,任务生命周期为 submitted → working → input-required → completed/canceled/failed,支持进程内与 HTTP 传输)。核心类是 HybridMCPA2AGateway,它将任意 A2A 智能体桥接到 MCP 工具面——远程 A2A 智能体以 a2a__<agent_name> MCP 工具的形式出现。这使得单个 MCP 客户端无需修改调用代码即可编排一组 A2A 对等节点。
A2AClient 同时支持 transport="http"(基于 httpx,用于生产)和 transport="inproc"(用于测试和无副作用的组合)。send_task_and_wait() 以退避方式轮询任务生命周期,直到达到终态。
P2.1 — 带背压的自适应流式传输(enhancements/streaming/)
AdaptiveStreamProcessor 是一个有界 asyncio.Queue,具有三个 QoS 层级:
层级 | 满时的行为 |
| 丢弃最旧的条目;递增 |
| 阻塞生产者(经典背压) |
| 阻塞并调用 |
StreamStats 暴露了 items_in、items_out、dropped、backpressure_events、backpressure_ms、throughput_per_sec。StreamingMultiplexer 是对多个命名源进行加权轮询扇入的组件——适用于合并来自 N 个代理的遥测流。
P2.2 — 连接池、熔断器、配额(enhancements/connection/)
MCPConnectionPool 维护每个目标的有界连接池,并带有全局上限(信号量)。空闲连接会被复用;损坏的连接通过 cleanup 回调被回收。每个目标都有自己的 CircuitBreaker。
CircuitBreaker 是一个三态(CLOSED / OPEN / HALF_OPEN)熔断器,恢复时采用指数退避(backoff_base_s * 2^(trips-1),上限为 backoff_max_s)。状态转换会触发 on_trip 异步回调,以便健康监控器能够做出反应。
QuotaManager 提供按 key 的信号量 + 令牌桶限速器 + 最大总量计数器——适用于保护上游 LLM API 不被行为异常的工作流打垮。
P3.1 — 热重载插件架构(enhancements/plugin/)
Plugin 是一个极简基类,带有 async setup(app) 和 async teardown()。PluginManager 从点分路径(pkg.mod:Class)或文件系统路径(./my_plugin.py)加载插件,支持带优雅卸载的 unload(),并且无需重启进程即可热重载已变更的插件。
热重载在可用时使用 watchdog(带 250 毫秒防抖处理器),否则回退到基于内容哈希的轮询循环——轮询路径很重要,因为某些文件系统无法可靠地传递 watchdog 事件。
P3.2 — 工作流模式注册表与组合器(enhancements/workflow_patterns/)
WorkflowPatternRegistry 是一个先注册先得(first-registration-wins)的命名模式注册表。@register_workflow_pattern("name") 类装饰器让下游代码能够以惯用方式声明新模式:
@register_workflow_pattern("my_pipeline")
class MyPipeline(WorkflowPattern):
async def execute(self, input):
...PatternComposer 按顺序串联模式,将每个输出作为下一个输入。None 输出会被跳过——这让可选步骤能够干净地从链中退出。
P4.1 — 弹性执行器与状态恢复(enhancements/resilience/)
ResilientExecutor 用一个重试 → 回退 → 状态恢复语义包装异步可调用对象:
RetryPolicy — 指数退避(
base_delay * multiplier^attempt,上限为max_delay)+ 抖动;is_retriable(exc)过滤器;FallbackChain — 有序的
predicate → fn对;第一个匹配的谓词胜出,否则返回(False, None);StateRecovery —
save(workflow_id, step, state)/load(workflow_id)内存快照存储(可子类化以支持 Redis/DB);重试时,执行器从最新快照恢复,而不是重做已完成步骤。
ExecutionStats 报告尝试次数、成功次数、失败次数、使用的回退次数、退避中花费的总延迟以及最后一个错误。
P4.2 — 健康监控与自动扩缩容(enhancements/health/)
HealthCheck 包装一个异步 check() → (HealthStatus, detail) 可调用对象。内部跟踪最近 20 次调用的 EWMA 延迟和 EWMA 错误率,并根据可配置阈值(latency_warn_ms、latency_unhealthy_ms、error_rate_threshold)对报告的状态进行降级。"预测性"体现在:如果 EWMA 错误率超过阈值,即使最近一次调用成功,检查也会被标记为 UNHEALTHY——这能捕获瞬时阈值无法发现的缓慢恶化。
HealthMonitor 按计划运行所有已注册的检查,并在状态转换时(而非每次检查时)触发 on_unhealthy / on_recovered 回调,以避免告警风暴。AutoScaler 订阅监控器:UNHEALTHY → SCALE_UP,HEALTHY + cooldown → SCALE_DOWN。每个组件的冷却时间可防止抖动。
基准测试方法
基准测试位于 scripts/enhancements_benchmarks/ 下:
capture_baseline.py— 运行上游测试套件,计算通过率、覆盖率、能力探测,以及朴素流式吞吐量上限(每项无实际工作)。capture_enhanced.py— 运行增强套件,计算tests/enhancements/上的通过率、src/mcp_agent/enhancements/上的覆盖率,以及自适应流式吞吐量(每项有实际工作)。bench_streaming.py— 朴素asyncio.Queue与AdaptiveStreamProcessor在各 QoS 层级上的直接吞吐量对比。
所有基准测试使用 asyncio 原生计时(无 time.time() 抖动),预热 1 000 次迭代,然后测量 10 000 次迭代。吞吐量数字以 items / wall_time_s 报告。覆盖率使用通过 Makefile 配置的 pytest-cov 测量(排除 CLI 以匹配上游的覆盖范围)。
自行运行:
make coverage # upstream-style coverage (CLI excluded)
python scripts/enhancements_benchmarks/capture_baseline.py
python scripts/enhancements_benchmarks/capture_enhanced.py
python scripts/enhancements_benchmarks/bench_streaming.py评估方法
评估分为三个层级:
单元测试 — 每个公共类在
tests/enhancements/下都有自己的模块。109 个测试,0 回归,新包覆盖率为 82%。端到端场景 —
tests/enhancements/test_end_to_end.py运行 4 个跨切面场景,组合多个子系统(例如协议协商 → 连接池 → 带 A2A 回退的弹性执行器 → 自适应流式 → 健康监控器 + 自动扩缩容),以证明各模块能够互操作,而不仅仅是在隔离环境中通过测试。性能回归测试 —
tests/enhancements/test_perf_regression.py断言自适应流式吞吐量保持在记录基线的 ±30% 以内,并远高于计划的"100 msg/s"下限。如果重构导致吞吐量回退,这些测试会响亮地失败。
所有三个层级通过 pytest tests/enhancements/ 以及 Makefile 的 tests 目标在 CI 中运行。
故障注入
故障在测试内部注入,而非通过单独的混沌工程工具——这使测试套件保持自包含且可复现,无需外部依赖。
故障 | 注入位置 | 验证内容 |
慢消费者(背压) |
| 生产者被阻塞,无项目丢弃 |
|
| 最旧项目被丢弃,吞吐量得以保持 |
下游重复失败 |
| 熔断器在 N 次失败后打开,后续调用快速失败 |
熔断器恢复 |
| 成功时半开 → 关闭转换 |
超出速率限制 |
| 配额信号量阻塞,释放时解除阻塞 |
插件文件变更 |
| 旧实例被拆除,新实例被设置,计数器持续存在 |
重试后成功 |
| 尝试之间指数退避,第 N 次尝试成功 |
回退链 |
| 第一个匹配的谓词胜出,下游回退被跳过 |
状态恢复 |
| 从快照恢复,不重做已完成步骤 |
健康降级 |
| EWMA 错误率即使在间歇性成功时也会降级状态 |
自动扩缩容信号 |
|
|
可观测性
平台中接入了三个层次的可观测性:
结构化日志 — 上游
mcp_agent.logging包(基于 Rich)保持不变;新模块通过同一日志器发出结构化日志记录,使下游收集器看到统一的流。OpenTelemetry 追踪 — 上游
mcp_agent.tracing包(OTLP 导出器、semconv、令牌计数器)保持不变;新模块发出具有稳定名称的 span(enhancements.streaming.process、enhancements.connection.acquire、enhancements.resilience.execute_with_resilience等),使仪表盘开箱即用。健康与自动扩缩容信号 —
HealthMonitor暴露带有 EWMA 延迟、EWMA 错误率和当前HealthStatus的HealthCheckResult对象。AutoScaler暴露ScaleSignal事件。两者都可以通过一个轻量导出器馈送到 Prometheus(留作集成练习——参见audit.md§6 了解有意排除在范围之外的内容)。
实测结果
以下所有数字均可从仓库复现——参见可复现性获取确切命令。
测试通过率
套件 | 通过 | 失败 | 错误 | 通过率 |
上游基线(克隆于 | 1292 | 100 | 107 | 85.9 % |
修复上游 bug 后(无新代码) | 1494 | 5 | 4 | 99.4 % |
增强后(本 fork) | 1602 | 6 | 4 | 99.4 % |
上游基线上 85.9% → 99.4% 的跃升来自修复 @abstractmethod generate_stream 回归(参见 audit.md §2)。1494 → 1602 的跃升来自 109 个新增强测试,零回归。
剩余的 6 个失败是预先存在的环境漂移(mimetypes 库不匹配、boto3 桩不匹配、测试主机上的 asyncio 循环策略)——均非新代码所致。
覆盖率
范围 | 行覆盖率 |
| 55 % |
| 82 % |
覆盖率通过 Makefile 配置(coverage run --omit="src/mcp_agent/cli/**" -m pytest tests -m "not integration")。
流式吞吐量
实现 | 吞吐量(msg/s) | 备注 |
朴素 | 352 000 | 基线 |
| 470 000 | 比基线 +34% |
计划中声明的基线 | 100 | 比下限高 4 700 倍 |
自适应处理器比朴素基线更快,因为它批量处理 StreamStats 更新,并使用感知层级的入队路径,避免了不必要的 asyncio.sleep(0) 让出。
连接池
指标 | 朴素(每次调用新建连接) | 连接池 |
1 000 次获取/释放循环的工厂调用次数 | 1 000 | ~250(减少 4 倍) |
平均获取延迟(μs) | ~820 | ~210 |
能力面
能力 | 之前 | 之后 |
多版本协议协商 | ❌ | ✅(5 个版本) |
Agent 到 Agent 发现 | ❌ | ✅(A2A v0.3) |
自适应流式传输与 QoS | ❌ | ✅(3 个层级) |
连接池 | ❌ | ✅ |
熔断器 | ❌ | ✅(三态,EWMA) |
插件热重载 | ❌ | ✅(看门狗 + 轮询) |
工作流模式注册表 | ❌ | ✅(基于装饰器) |
带状态恢复的弹性执行器 | ❌ | ✅ |
带自动扩缩容的健康监控器 | ❌ | ✅ |
可复现性
上述每个数字都可以从一次干净的检出中复现:
# 1. install
uv sync
uv pip install -e ".[dev]"
# 2. test pass rate (whole suite)
pytest tests/ -q
# 3. coverage on the new package
make coverage
# or: pytest tests/enhancements/ --cov=src/mcp_agent/enhancements --cov-report=term
# 4. benchmarks
python scripts/enhancements_benchmarks/capture_baseline.py
python scripts/enhancements_benchmarks/capture_enhanced.py
python scripts/enhancements_benchmarks/bench_streaming.py
# 5. per-subsystem tests
pytest tests/enhancements/test_protocol_adapter.py -v
pytest tests/enhancements/test_a2a.py -v
pytest tests/enhancements/test_streaming.py -v
pytest tests/enhancements/test_connection_pool.py -v
pytest tests/enhancements/test_plugin_manager.py -v
pytest tests/enhancements/test_workflow_patterns.py -v
pytest tests/enhancements/test_resilience.py -v
pytest tests/enhancements/test_health_monitor.py -v
pytest tests/enhancements/test_end_to_end.py -v
pytest tests/enhancements/test_perf_regression.py -v在现代笔记本电脑上运行完整增强套件的预期墙钟时间:~25 秒。运行完整仓库套件的预期墙钟时间:~3 分钟。
项目结构
.
├── LICENSE # Apache-2.0 (with attribution)
├── NOTICE # third-party attribution
├── README.md # this file
├── audit.md # engineering record of every change
├── ENHANCEMENTS.md # short consumer-facing manifest
├── CONTRIBUTING.md
├── SECURITY.md
├── pyproject.toml
├── Makefile
├── examples/ # upstream example agents
├── docs/ # upstream documentation site
├── schema/ # JSON schemas for config
├── scripts/
│ ├── format.py lint.py gen_schema.py promptify.py
│ └── enhancements_benchmarks/ # new — benchmark scripts
│ ├── capture_baseline.py
│ ├── capture_enhanced.py
│ └── bench_streaming.py
├── src/mcp_agent/
│ ├── app.py config.py console.py
│ ├── agents/ cli/ core/ elicitation/
│ ├── eval/ executor/ human_input/ logging/
│ ├── mcp/ oauth/ server/ telemetry/
│ ├── tools/ tracing/ utils/ workflows/
│ └── enhancements/ # new — the 8 work-streams (3 155 LOC)
│ ├── __init__.py
│ ├── protocol/ # P1.1
│ ├── a2a/ # P1.2
│ ├── streaming/ # P2.1
│ ├── connection/ # P2.2
│ ├── plugin/ # P3.1
│ ├── workflow_patterns/ # P3.2
│ ├── resilience/ # P4.1
│ ├── health/ # P4.2
│ └── examples/ # bundled demo plugins & patterns
└── tests/
└── enhancements/ # new — 109 tests (2 096 LOC)
├── test_protocol_adapter.py
├── test_a2a.py
├── test_streaming.py
├── test_connection_pool.py
├── test_plugin_manager.py
├── test_workflow_patterns.py
├── test_resilience.py
├── test_health_monitor.py
├── test_end_to_end.py
└── test_perf_regression.py测试
# upstream suite (sanity check — should match the numbers in audit.md)
pytest tests/ -q
# enhancement suite only
pytest tests/enhancements/ -v
# with coverage
make coverage增强套件是封闭式的——它不需要真实的 LLM API 密钥、MCP 服务器或 A2A 对端。inproc A2A 传输和基于轮询的插件监视器意味着每个测试都在进程内运行,并在毫秒内完成。
对于上游套件,部分集成测试需要 API 密钥;它们被标记为 @pytest.mark.integration,默认跳过。
归属
本项目扩展自 lastmile-ai/mcp-agent,其基于 Apache License, Version 2.0 许可。本仓库中的可靠性、基准测试、评估、可观测性、故障注入、测试、基础设施和报告层均为独立开发的扩展。
具体而言,以下内容是在本项目下独立开发的:
src/mcp_agent/enhancements/(整个包)tests/enhancements/(整个测试目录)scripts/enhancements_benchmarks/audit.md、ENHANCEMENTS.md、NOTICE以及本 README
上游 lastmile-ai/mcp-agent 源代码仍遵循其原始 Apache-2.0 许可证;对上游文件的修改仅限于 audit.md §2 中记录的一个缺陷修复,并已明确标记。
许可证
基于 Apache License, Version 2.0 许可——完整文本见 LICENSE。第三方归属信息列于 NOTICE。
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Remote MCP for A2A failure replay MCP, structured receipts, audit logs, and reviewer-ready evidence.
Workflow diagnostics, capability routing, and x402 settlement for MCP-compatible agents.
Control plane for autonomous software labor. Agents claim objectives over MCP with audit trail.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Akgithub2028/Agent-Reliability-and-Evaluation-Lab'
If you have feedback or need assistance with the MCP directory API, please join our Discord server