跳转至

MCP 运行时

MCP 在聊天运行时里的关键问题不是“能不能调用”,而是“什么时候调用、允许调用什么、调用结果怎样进入最终回答”。

运行阶段

  1. 从 Agent 挂载解析可用 server 和 tool 清单
  2. 应用 runtime config、quick-match、intent gate 和预算限制
  3. 生成调用参数并执行工具
  4. 把成功、跳过、阻断或失败结果都写入可观测上下文
  5. 决定是直返响应,还是把结果送入最终生成阶段

每个阶段在做什么

1. 挂载解析

运行时首先会从 Agent 挂载里解析:

  • server 列表
  • tool 列表
  • mount priority
  • tool_capability
  • allowlist

这一步不是简单地把所有 server 暴露给模型,而是先形成一个“当前 turn 可见能力面”。

2. 运行时配置折叠

MCP 的有效运行策略来自两层:

  • 全局 config.mcp
  • Agent 级 mcp_runtime_config

当前 AgentMCPRuntimeConfig 已支持:

  • history_user_message_window
  • tool_selection_prompt_guidance
  • tool_argument_prompt_guidance

所以同一套全局 MCP 配置下,不同 Agent 的调用表现也可以完全不同。

3. 前门禁

在真正挑工具之前,运行时会先应用:

  • quick match
  • intent gate
  • mount capability gate
  • per-turn budget

这一步的结果不只有 allow / deny,还会产生具体的 gate_reason,并写入 MCP context。

4. 参数生成与调用

通过前门禁后,运行时会构造 tool arguments,并按 transport 执行:

  • stdio
  • http_sse

如果某个工具被配置为需要审批,调用不会立刻继续,而会转成 checkpoint。

5. 结果进入响应链路

调用结束后,结果有几种去向:

  • 作为上下文送回模型总结
  • direct response
  • passthrough
  • quick-match 直接返回

因此 MCP runtime 的最后一步不是“拿到 JSON 就结束”,而是决定谁拥有最终响应权。

当前关键对象

对象 位置 作用
AgentMCPRuntimeConfig ai_service/orchestrator/mcp_runtime_config.py Agent 级运行时策略
AgentMCPResponseConfig ai_service/orchestrator/mcp_response_config.py quick match / direct response / intent gate
MCPPassthroughDecision ai_service/orchestrator/mcp_passthrough.py 是否跳过模型总结直接返回
MCPPolicyService ai_service/services/mcp_policy.py allowlist、budget、timeout
MCP context records orchestrator runtime payload 记录 success / skipped / blocked / failed outcome

关键点

  • 非成功 outcome 也是上下文的一部分,不只是日志
  • direct response 和 quick match 会改变主链路的返回方式
  • MCP 运行时配置是 Agent 级运行时输入的一部分

常见症状与动作

工具明明挂载了,但模型完全不选

先看:

  1. history_user_message_window 是否太小
  2. quick match / intent gate 是否根本没放行
  3. capability gate 是否把它当 generic mount 跳过

工具被选中了,但很快被拒绝

优先看:

  1. allowlist
  2. call budget
  3. timeout
  4. approval-required 规则

工具执行成功,但用户看不到结果

先看:

  1. 是否进入 passthrough / direct response
  2. 若没有,模型总结是否忽略了 MCP context
  3. direct response preview 是否渲染失败并 fallback

每轮都重复调用同一个工具

先看:

  1. quick match 规则是否过宽
  2. history window 是否过大导致重复触发
  3. tool guidance 是否鼓励了不必要调用

代码入口

想改 Agent 级 MCP 运行策略

ai_service/orchestrator/mcp_runtime_config.py

想改前门禁与 direct response

ai_service/orchestrator/mcp_response_config.py

想改 allowlist / budget / timeout

ai_service/services/mcp_policy.py

想改实际工具执行 transport

ai_service/services/mcp_client.py