Microsoft Agent Framework 整体架构设计
文档版本: v1.0
生成日期: 2026-02-03
来源: 整合所有子任务分析
执行摘要
Microsoft Agent Framework 是一个协议优先、分层解耦的 AI Agent 开发框架。核心设计理念是通过 Protocol 定义契约而非强制继承,实现了零侵入集成和渐进式采用。
架构核心价值
- 协议驱动设计 - 使用 Python Protocol 实现结构化子类型,第三方 Agent 无需继承框架类
- 统一内容模型 - 单一
Content类处理 18+ 种内容类型,避免类型爆炸 - 分层职责 - Protocol → BaseAgent → ChatAgent 三级架构,每层职责单一清晰
- 企业级特性 - 内置 MCP 协议支持、Durable Agent 持久化、OpenTelemetry 可观测性
- 高度可扩展 - Middleware 管道、Context Provider、动态工具注册
分层架构图
核心组件关系
Agent 架构分层
Content 模型体系
数据流图
Agent Run 完整数据流
Streaming 数据流
MCP 工具集成数据流
关键设计决策
1. 协议优先 vs 继承强制
| 设计选择 | Protocol | ABC |
|---|---|---|
| 类型检查 | 运行时 + 静态 | 运行时 + 静态 |
| 继承要求 | 无需显式继承 | 必须显式继承 |
| 灵活性 | 高(鸭子类型) | 低(名义子类型) |
| 框架侵入性 | 零侵入 | 强制依赖 |
决策理由:Protocol 实现零侵入集成,允许第三方完全自定义 Agent 实现。
2. 统一 Content 模型 vs 多类继承
| 设计选择 | 统一 Content | 多类继承 |
|---|---|---|
| API 复杂度 | 单一类,工厂方法 | 18+ 独立类 |
| 类型安全 | ContentType + 工厂方法 | 类继承体系 |
| 序列化 | 统一逻辑 | 每类独立实现 |
| 扩展性 | 添加类型简单 | 需创建新类 |
决策理由:统一模型大幅简化 API,18+ 种内容类型使用同一入口点。
3. Middleware 洋葱模型
Middleware#1 (before)
Middleware#2 (before)
Middleware#3 (before)
Final Handler (实际执行)
Middleware#3 (after)
Middleware#2 (after)
Middleware#1 (after)
决策理由:
- 双向拦截能力(前置/后置处理)
- 链式执行保证顺序
- 支持短路终止(context.terminate)
4. MCP 惰性连接策略
| 策略 | 立即连接 | 惰性连接 |
|---|---|---|
| 启动时间 | 慢(建立所有连接) | 快(按需连接) |
| 资源占用 | 高 | 低 |
| 失败影响 | 启动失败 | 运行时失败 |
| 工具新鲜度 | 启动时固定 | 运行时获取最新 |
决策理由:惰性连接减少启动延迟和资源占用,使用 AsyncExitStack 自动管理生命周期。
5. Durable Agent 双模式设计
决策理由:统一 DurableAgentExecutor 抽象,支持客户端直连和编排上下文两种使用场景。
组件职责矩阵
| 组件 | 核心职责 | 关键方法 | 依赖 |
|---|---|---|---|
| AgentProtocol | 定义 Agent 契约 | run(), run_stream(), get_new_thread() | 无 |
| BaseAgent | 通用能力(Thread、序列化、as_tool) | as_tool(), get_new_thread() | AgentProtocol |
| ChatAgent | LLM 交互实现 | run(), run_stream(), as_mcp_server() | BaseAgent, ChatClientProtocol |
| DurableAIAgent | 持久化 Agent 扩展 | run() → Task | ChatAgent, DurableAgentExecutor |
| Content | 统一内容模型 | from_xxx(), add() | SerializationMixin |
| ChatMessage | 消息容器 | to_dict(), from_dict() | Content, Role |
| FunctionTool | 函数工具包装 | invoke(), parameters() | BaseTool, Pydantic |
| MCPTool | MCP 协议集成 | connect(), load_tools() | BaseTool, mcp.ClientSession |
| Middleware | 请求/响应处理 | process(context, next) | AgentRunContext |
| ContextProvider | 动态上下文注入 | invoking(), invoked() | AgentThread |
| AgentThread | 会话状态管理 | on_new_messages(), serialize() | ChatMessageStore |
| ChatClientProtocol | LLM 客户端抽象 | get_response(), get_streaming_response() | ChatResponse |
扩展点清单
1. 自定义 Agent
# 无需继承框架类,实现 Protocol 即可
class CustomAgent:
def __init__(self):
self.id = "custom-001"
self.name = "Custom Agent"
self.description = "Custom implementation"
async def run(self, messages, *, thread=None, **kwargs):
return AgentResponse(messages=[], response_id="resp-001")
def run_stream(self, messages, *, thread=None, **kwargs):
async def _stream():
yield AgentResponseUpdate()
return _stream()
def get_new_thread(self, **kwargs):
return AgentThread()
# 自动满足协议
assert isinstance(CustomAgent(), AgentProtocol) # True
2. 自定义 Middleware
# 函数方式(简洁)
@agent_middleware
async def logging_middleware(context: AgentRunContext, next):
print(f"Before: {context.agent.name}")
await next(context)
print(f"After: {context.result}")
# 类方式(有状态)
class CacheMiddleware(AgentMiddleware):
def __init__(self, cache):
self.cache = cache
async def process(self, context, next):
cache_key = self._get_key(context)
if cache_key in self.cache:
context.result = self.cache[cache_key]
context.terminate = True
return
await next(context)
self.cache[cache_key] = context.result
3. 自定义 Tool
@tool(name="custom_search", description="Custom search tool")
async def custom_search(
query: Annotated[str, "Search query"],
limit: int = 10
) -> str:
"""Custom search implementation"""
return f"Results for {query}: ..."
4. 自定义 ContextProvider
class CustomContextProvider:
async def invoking(self, messages, **kwargs):
# 动态注入上下文
return Context(
messages=[ChatMessage(role="system", text="Context...")],
tools=[custom_tool],
instructions="Additional instructions..."
)
async def invoked(self, input_messages, response_messages, **kwargs):
# 响应后处理
pass
部署架构建议
标准模式
┌─────────────────────────────────────────────────────┐
│ 应用服务层 │
│ ┌──────────────────────────────────────────────┐ │
│ │ Agent Framework │ │
│ │ ChatAgent + Tools + Middleware │ │
│ └──────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────────────────┴───────────────────────┐ │
│ │ ChatClient │ │
│ │ OpenAIClient / AzureOpenAIClient │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│
LLM Service
Durable 模式(无服务器)
┌─────────────────────────────────────────────────────┐
│ Azure Functions / Durable Task │
│ ┌──────────────────────────────────────────────┐ │
│ │ AgentFunctionApp │ │
│ │ DurableAIAgent + Durable Functions │ │
│ └──────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────────────────┴───────────────────────┐ │
│ │ Durable Task Scheduler │ │
│ │ State Persistence + Orchestration │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│
┌──────────┴──────────┐
▼ ▼
LLM Service State Storage
MCP 扩展模式
┌─────────────────────────────────────────────────────┐
│ Application with MCP │
│ ┌──────────────────────────────────────────────┐ │
│ │ ChatAgent │ │
│ │ tools=[MCPTool, FunctionTool, ...] │ │
│ └──────────────────────────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Local Tools │ │ External MCP │ │
│ │ FunctionTool │ │ Server Tools │ │
│ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────┘
│
MCP Protocol Connection
│
┌──────────┴──────────┐
▼ ▼
File System Tool Weather API Tool
性能考量
1. Middleware 链构建
- 当前设计:每次请求递归构建 Handler Chain
- 优化建议:中间件配置不变时缓存 Handler Chain
- 复杂度:O(n),n 为中间件数量
2. MCP 连接管理
- 连接池:考虑 MCP Server 连接池化
- 预热策略:关键 MCP Server 启动时预热
- 超时配置:设置合理的
request_timeout
3. 状态序列化(Durable)
- 瓶颈点:状态序列化/反序列化、存储I/O
- 优化策略:压缩、增量更新、状态分片
4. Content 加法操作
- 流式累积:
__add__操作支持流式内容拼接 - 复杂度:O(1) 每操作,累计 O(n) 对于 n 个 chunks
安全考量
1. 工具调用安全
- 审批模式:
approval_mode支持always_require/never_require - 调用限制:
max_invocations和max_invocation_exceptions防止无限循环
2. 函数执行隔离
- 参数验证:Pydantic 模型自动验证输入
- 异常处理:FunctionTool 捕获并包装异常
3. 持久化安全
- 状态加密:敏感字段建议加密后存储
- 访问控制:Durable Entity 访问需要身份验证
总结
Microsoft Agent Framework 的核心架构优势在于:
- 协议驱动设计 实现了零侵入集成
- 统一 Content 模型 简化了多模态内容处理
- 分层架构 保证了清晰的职责分离
- 完整的生命周期管理 确保资源正确释放
- 企业级特性 支持持久化、编排、MCP 等高级场景
这套架构既适合快速原型开发,也能支撑企业级生产部署。