Files
hunjing/backend/app/integrations/mcp/client.py
T
chenxin 684261f4b4 M5:百工与司命——能力注册表、授契行契请命、禁域裁决与观察标证
- 百工域 domains/baigong:capabilities(统一能力契约:执行类型 builtin/qiankun/mcp/http + 四维风险标注 + 来源版本)、mandates(授契 grant / 行契 charter 预算时间窗,撤销立即生效)、tool_calls(净化摘要 + 观察标证);请命复用 pending_confirmations 加 expires_at/brief_json(超时=拒绝执行 HJ-1302,六要素说明)
- 司命裁决器 siming.py:四维取最高档(能力/数据/后果/情境);禁域为代码常量不可配置(递归删根/格式化/写裸设备/fork 炸弹、file:// 协议、密钥材料外发)——专项测试断言恶意标注与篡改对象仍拒 HJ-1301
- 执行链:禁域→裁决(HJ-1303 未授契拒且双留痕)→请命→执行(乾坤经 SandboxClient HMAC;MCP 经 call_tool;内置无副作用)→净化标证(观察非事实,敏感遮蔽+体量截断)→行动账
- MCP 登记/启停/刷新自动派生与撤下 capabilities(博闻登记接入点);内置能力种子(echo/datetime/qiankun.shell/web.fetch)
- 端点:/capabilities /mandates /petitions /tool-calls + /tools 兼容投影;前端百工页四区(能力目录四维标注/授契行契/请命批准拒绝/行动账观察标证)
- 退役:modules/safety|skills|tool_runtime|agent、application/tool_runtime、services/skills|safety、tool_policies/skills/model_endpoint_overrides 表(迁移 006)、前端 SkillManager/ToolsConsole/旧 tools 页
- 验收(test_baigong_siming 四用例):未授契被拒留痕、请命超时不执行、禁域不可关闭、结果为观察不入忆;后端 454、前端 220、BFF 4、神识 5 包全绿(2 个预存环境失败不变)
2026-08-27 19:17:21 +08:00

107 lines
3.0 KiB
Python

"""MCP 客户端 — Streamable HTTP 与 stdio 均用的 JSON-RPC 解析工具。
两种传输层的具体实现在 ``transports/`` 子包中。
"""
from __future__ import annotations
from typing import Any
import httpx
from app.core.config import settings
from app.integrations.mcp.models import ToolResult
def _auth_headers(auth_token: str | None) -> dict[str, str]:
return {"Authorization": f"Bearer {auth_token}"} if auth_token else {}
def _parse_call_result(data: dict) -> ToolResult:
"""解析 JSON-RPC tools/call 响应为 ToolResult。
供 StreamableHttpTransport 和 StdioTransport 共用。
"""
if data.get("error"):
return ToolResult(
ok=False,
stdout="",
stderr=data["error"].get("message", "MCP 错误"),
duration_ms=0,
exit_code=1,
timeout=False,
truncated=False,
trace_id="",
)
result = data.get("result") if isinstance(data, dict) else None
if not isinstance(result, dict):
return ToolResult(
ok=False,
stdout=str(result) if result else "",
stderr="无效响应格式",
duration_ms=0,
exit_code=1,
timeout=False,
truncated=False,
trace_id="",
)
content = result.get("content", [])
stdout_parts = []
for item in content:
if item.get("type") in ("text", "json"):
stdout_parts.append(item.get("text", ""))
truncated = bool((result.get("meta") or {}).get("truncated", False))
return ToolResult(
ok=not result.get("isError", False),
stdout="".join(stdout_parts),
stderr="",
duration_ms=0,
exit_code=0 if not result.get("isError", False) else 1,
timeout=False,
truncated=truncated,
trace_id="",
)
async def call_tool(
http_client: httpx.AsyncClient,
endpoint_url: str,
tool_name: str,
arguments: dict,
auth_token: str | None = None,
meta: dict | None = None,
) -> ToolResult:
"""通过 Streamable HTTP 调用 MCP 工具(供 _make_mcp_executor 使用)。"""
body: dict[str, Any] = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments,
},
}
if meta:
body["meta"] = meta
try:
resp = await http_client.post(
endpoint_url,
json=body,
headers=_auth_headers(auth_token),
timeout=settings.mcp_call_timeout_seconds,
)
resp.raise_for_status()
data = resp.json()
except (httpx.HTTPError, ValueError, TypeError) as exc:
return ToolResult(
ok=False,
stdout="",
stderr=str(exc),
duration_ms=0,
exit_code=None,
timeout=False,
truncated=False,
trace_id="",
)
return _parse_call_result(data)