Files
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

232 lines
7.1 KiB
Python

"""stdio 传输层实现。
通过子进程 stdin/stdout 通信的标准 MCP 传输协议(本地 MCP 集成)。
JSON-RPC 2.0 请求写入 stdin,从 stdout 读取响应,stderr 记日志。
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import signal
import time
from typing import Any
from app.core.config import settings
from app.integrations.mcp.client import _parse_call_result
from app.integrations.mcp.transports.base import TransportProtocol
from app.integrations.mcp.models import ToolResult
logger = logging.getLogger(__name__)
class StdioTransport(TransportProtocol):
"""通过子进程 stdin/stdout 通信的 MCP 传输层。"""
def __init__(
self,
server_id: str,
server_name: str,
command: str,
args: list[str] | None = None,
env: dict[str, str] | None = None,
cwd: str | None = None,
) -> None:
self.server_id = server_id
self.server_name = server_name
self._command = command
self._args = args or []
self._env = env
self._cwd = cwd
self._process: asyncio.subprocess.Process | None = None
self._request_id = 0
self._started_at: float | None = None
self._lock = asyncio.Lock()
async def start(self) -> None:
if self._process is not None and self._process.returncode is None:
return # already running
resolved_env = os.environ.copy()
if self._env:
resolved_env.update(self._env)
self._process = await asyncio.create_subprocess_exec(
self._command,
*self._args,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=resolved_env,
cwd=self._cwd,
)
self._started_at = time.time()
logger.info(
"stdio MCP 子进程已启动",
extra={
"server_id": self.server_id,
"server_name": self.server_name,
"pid": self._process.pid,
},
)
# 后台读取 stderr,记日志
asyncio.create_task(self._read_stderr())
async def stop(self) -> None:
proc = self._process
if proc is None or proc.returncode is not None:
self._process = None
self._started_at = None
return
logger.info(
"停止 stdio MCP 子进程",
extra={
"server_id": self.server_id,
"pid": proc.pid,
},
)
try:
proc.send_signal(signal.SIGTERM)
try:
await asyncio.wait_for(proc.wait(), timeout=settings.mcp_stdio_stop_timeout_seconds)
except TimeoutError:
proc.send_signal(signal.SIGKILL)
await proc.wait()
except ProcessLookupError:
pass
self._process = None
self._started_at = None
async def list_tools(self) -> list[dict[str, Any]]:
result = await self._send_request("tools/list", {})
if result is None:
return []
return result.get("tools") if isinstance(result.get("tools"), list) else []
async def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult:
result = await self._send_request(
"tools/call",
{"name": name, "arguments": arguments},
)
if result is None:
return ToolResult(
ok=False,
stdout="",
stderr="stdio 子进程无响应",
duration_ms=0,
exit_code=1,
timeout=False,
truncated=False,
trace_id="",
)
return _parse_call_result({"result": result})
async def restart(self) -> None:
await self.stop()
await self.start()
@property
def is_running(self) -> bool:
return (
self._process is not None
and self._process.returncode is None
and self._process.stdin is not None
)
async def get_status(self) -> dict[str, Any]:
running = self.is_running
uptime = None
if running and self._started_at is not None:
uptime = time.time() - self._started_at
return {
"server_id": self.server_id,
"name": self.server_name,
"transport": "stdio",
"status": "running" if running else "stopped",
"pid": self._process.pid if self._process else None,
"uptime_seconds": uptime,
}
async def _send_request(self, method: str, params: dict[str, Any]) -> dict[str, Any] | None:
async with self._lock:
self._request_id += 1
req_id = self._request_id
proc = self._process
if proc is None or proc.stdin is None or proc.stdout is None:
return None
request = {
"jsonrpc": "2.0",
"id": req_id,
"method": method,
"params": params,
}
line = (json.dumps(request) + "\n").encode("utf-8")
try:
proc.stdin.write(line)
await asyncio.wait_for(
proc.stdin.drain(),
timeout=settings.mcp_stdio_call_timeout_seconds,
)
response_line = await asyncio.wait_for(
proc.stdout.readline(),
timeout=settings.mcp_stdio_call_timeout_seconds,
)
if not response_line:
return None
data = json.loads(response_line.decode("utf-8"))
except (TimeoutError, json.JSONDecodeError, OSError) as exc:
logger.warning(
"stdio MCP 请求失败",
extra={
"server_id": self.server_id,
"method": method,
"error": str(exc),
},
)
return None
if isinstance(data, dict) and data.get("error"):
logger.warning(
"stdio MCP 返回 JSON-RPC 错误",
extra={
"server_id": self.server_id,
"method": method,
"error": data["error"],
},
)
return None
return data.get("result") if isinstance(data, dict) else None
async def _read_stderr(self) -> None:
proc = self._process
if proc is None or proc.stderr is None:
return
try:
while True:
line = await proc.stderr.readline()
if not line:
break
text = line.decode("utf-8", errors="replace").rstrip()
if text:
logger.info(
"[stdio %s] %s",
self.server_name,
text,
extra={
"server_id": self.server_id,
"server_name": self.server_name,
},
)
except Exception: # noqa: BLE001
pass