一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
984 lines
37 KiB
Python
984 lines
37 KiB
Python
"""
|
||
MCP(Model Context Protocol)客户端。
|
||
|
||
对应 Node 版 server/src/mcp.mjs,但**不依赖官方 `mcp` 包** —— 手写 JSON-RPC 2.0。
|
||
原因:安卓上 pip/Node 包都装不进 APK;而 MCP 的线协议就是 JSON-RPC 2.0,
|
||
initialize / tools/list / tools/call 三步自己发就够了。
|
||
|
||
支持三种传输:
|
||
http Streamable HTTP:POST JSON-RPC,Accept 同时带 application/json 和 text/event-stream
|
||
stdio 起子进程按行收发(安卓上不可用,会给出明确报错而不是莫名卡死)
|
||
inproc 安卓专用:import 一个 .py,用队列 + 线程在内存里跑 JSON-RPC。
|
||
约定该文件暴露 `handle(request: dict) -> dict`(同步函数)。
|
||
|
||
对外工具名统一 `mcp__<server>__<tool>`,避免和 Python 工具重名。
|
||
"""
|
||
|
||
import importlib.util
|
||
import inspect
|
||
import json
|
||
import os
|
||
import queue
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
|
||
import paths
|
||
|
||
PROTOCOL_VERSION = '2024-11-05'
|
||
CLIENT_INFO = {'name': 'doubao-kernel-py', 'version': '0.1.0'}
|
||
|
||
_clients: dict = {} # serverName -> {'spec','client','tools','error'}
|
||
_lock = threading.RLock()
|
||
|
||
_PENDING = object()
|
||
|
||
|
||
class McpError(RuntimeError):
|
||
"""MCP 层的任何错误(连接、协议、超时)都用它,便于统一转成 record.error。"""
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 配置文件
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def mcp_config_path() -> str:
|
||
return paths.get().mcp_file
|
||
|
||
|
||
def mcp_config_dir() -> str:
|
||
return os.path.dirname(mcp_config_path())
|
||
|
||
|
||
def ensure_mcp_config() -> None:
|
||
"""
|
||
首次运行时把内置的 tools/mcp.servers.json 复制到数据目录。
|
||
和 Node 版一样:用户改的是自己可写的那份,升级程序不会覆盖。
|
||
"""
|
||
target = mcp_config_path()
|
||
bundled = os.path.join(paths.get().tools_dir, 'mcp.servers.json')
|
||
if os.path.isfile(target) or not os.path.isfile(bundled):
|
||
return
|
||
try:
|
||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||
shutil.copyfile(bundled, target)
|
||
except OSError as exc:
|
||
print(f'[mcp] 初始化 mcp.servers.json 失败:{exc}', file=sys.stderr)
|
||
|
||
|
||
_VAR_RE = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}')
|
||
|
||
|
||
def _expand(value):
|
||
"""展开 ${VAR} 占位符:打包/安卓上路径随机器变,写死绝对路径不合适。"""
|
||
if not isinstance(value, str):
|
||
return value
|
||
extra = {'DOUBAO_DATA': paths.get().data_dir}
|
||
|
||
def repl(match):
|
||
name = match.group(1)
|
||
return os.environ.get(name) or extra.get(name) or match.group(0)
|
||
|
||
return _VAR_RE.sub(repl, value)
|
||
|
||
|
||
def _expand_server(server: dict) -> dict:
|
||
return {
|
||
**server,
|
||
'command': _expand(server.get('command')),
|
||
'args': [_expand(a) for a in (server.get('args') or [])],
|
||
'url': _expand(server.get('url')),
|
||
'file': _expand(server.get('file')),
|
||
'env': {k: _expand(v) for k, v in (server.get('env') or {}).items()},
|
||
'headers': {k: _expand(v) for k, v in (server.get('headers') or {}).items()},
|
||
}
|
||
|
||
|
||
def read_mcp_config() -> dict:
|
||
file_path = mcp_config_path()
|
||
if not os.path.isfile(file_path):
|
||
return {'servers': []}
|
||
try:
|
||
with open(file_path, 'r', encoding='utf-8') as fh:
|
||
payload = json.load(fh)
|
||
except (OSError, ValueError) as exc:
|
||
print(f'[mcp] mcp.servers.json 解析失败:{exc}', file=sys.stderr)
|
||
return {'servers': [], 'error': str(exc)}
|
||
servers = payload if isinstance(payload, list) else payload.get('servers') or []
|
||
return {'servers': [_expand_server(s) for s in servers]}
|
||
|
||
|
||
def write_mcp_config(config: dict) -> None:
|
||
tmp = f'{mcp_config_path()}.tmp'
|
||
with open(tmp, 'w', encoding='utf-8') as fh:
|
||
json.dump(config, fh, ensure_ascii=False, indent=2)
|
||
os.replace(tmp, mcp_config_path())
|
||
|
||
|
||
def read_mcp_config_text() -> str:
|
||
file_path = mcp_config_path()
|
||
if not os.path.isfile(file_path):
|
||
return '{\n "servers": []\n}\n'
|
||
with open(file_path, 'r', encoding='utf-8') as fh:
|
||
return fh.read()
|
||
|
||
|
||
def write_mcp_config_text(text: str) -> int:
|
||
"""
|
||
保存界面里编辑的 JSON 文本:先校验再落盘,坏 JSON 不许写进去。
|
||
transport 白名单比 Node 版多一个 inproc(安卓专用)。
|
||
"""
|
||
try:
|
||
parsed = json.loads(text)
|
||
except ValueError as exc:
|
||
raise McpError(f'JSON 格式错误:{exc}') from exc
|
||
servers = parsed if isinstance(parsed, list) else (parsed or {}).get('servers')
|
||
if not isinstance(servers, list):
|
||
raise McpError('顶层必须是 { "servers": [ ... ] } 或一个数组')
|
||
for index, server in enumerate(servers):
|
||
if not isinstance(server, dict):
|
||
raise McpError(f'第 {index + 1} 项不是对象')
|
||
name = server.get('name')
|
||
if not name:
|
||
raise McpError(f'第 {index + 1} 项缺少 name')
|
||
transport = server.get('transport') or 'stdio'
|
||
if transport not in ('stdio', 'http', 'sse', 'inproc'):
|
||
raise McpError(f'{name}: transport 只能是 stdio / http / sse / inproc')
|
||
if transport == 'stdio' and not server.get('command'):
|
||
raise McpError(f'{name}: stdio 需要 command')
|
||
if transport in ('http', 'sse') and not server.get('url'):
|
||
raise McpError(f'{name}: {transport} 需要 url')
|
||
if transport == 'inproc' and not (server.get('file') or server.get('path')):
|
||
raise McpError(f'{name}: inproc 需要 file(指向 .py 路径)')
|
||
if isinstance(parsed, list):
|
||
write_mcp_config({'servers': servers})
|
||
else:
|
||
# 保留顶层自定义字段(比如 note/注释),只覆盖 servers
|
||
merged = dict(parsed or {})
|
||
merged['servers'] = servers
|
||
write_mcp_config(merged)
|
||
return len(servers)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 传输层:http
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
class _HttpTransport:
|
||
"""Streamable HTTP:一个 POST 一次往返;也可能用 SSE 回包。"""
|
||
|
||
def __init__(self, spec: dict):
|
||
self.url = spec.get('url') or ''
|
||
self.headers = {str(k): str(v) for k, v in (spec.get('headers') or {}).items()}
|
||
self.session_id = None
|
||
|
||
def _post(self, message: dict, timeout: float):
|
||
data = json.dumps(message, ensure_ascii=False).encode('utf-8')
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
# 两个都带:服务器可以回普通 JSON,也可以回 SSE 流
|
||
'Accept': 'application/json, text/event-stream',
|
||
**self.headers,
|
||
}
|
||
if self.session_id:
|
||
headers['Mcp-Session-Id'] = self.session_id
|
||
req = urllib.request.Request(self.url, data=data, headers=headers, method='POST')
|
||
try:
|
||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', errors='replace')[:400]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise McpError(f'MCP HTTP {exc.code}:{detail}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise McpError(f'无法连接 MCP 服务器 {self.url}:{exc.reason}') from exc
|
||
sid = resp.headers.get('Mcp-Session-Id')
|
||
if sid:
|
||
self.session_id = sid
|
||
return resp
|
||
|
||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||
resp = self._post(message, timeout)
|
||
try:
|
||
status = getattr(resp, 'status', 200)
|
||
if status == 202: # Accepted:通知类请求的正常响应
|
||
raise McpError('MCP 服务器没有返回响应(202 Accepted)')
|
||
content_type = (resp.headers.get('Content-Type') or '').lower()
|
||
if 'text/event-stream' in content_type:
|
||
return self._read_sse(resp, message.get('id'))
|
||
body = resp.read().decode('utf-8', errors='replace')
|
||
finally:
|
||
resp.close()
|
||
if not body.strip():
|
||
raise McpError('MCP 服务器返回空响应')
|
||
try:
|
||
payload = json.loads(body)
|
||
except ValueError as exc:
|
||
raise McpError(f'MCP 返回非 JSON:{body[:300]}') from exc
|
||
if isinstance(payload, list):
|
||
payload = next((p for p in payload if p.get('id') == message.get('id')), payload[0] if payload else {})
|
||
return payload
|
||
|
||
def _read_sse(self, resp, want_id) -> dict:
|
||
"""从 SSE 流里挑出属于本次请求的那条响应(其它消息忽略/回绝)。"""
|
||
while True:
|
||
raw = resp.readline()
|
||
if not raw:
|
||
break
|
||
line = raw.decode('utf-8', errors='replace').strip()
|
||
if not line or line.startswith(':') or not line.startswith('data:'):
|
||
continue
|
||
payload = line[5:].strip()
|
||
if not payload:
|
||
continue
|
||
try:
|
||
message = json.loads(payload)
|
||
except ValueError:
|
||
continue
|
||
if isinstance(message, dict) and message.get('id') == want_id:
|
||
return message
|
||
# 服务器反向发起的请求(采样/roots):一律回"方法不支持",别把连接吊死
|
||
if isinstance(message, dict) and message.get('method') and message.get('id') is not None:
|
||
try:
|
||
self._post({'jsonrpc': '2.0', 'id': message['id'],
|
||
'error': {'code': -32601, 'message': 'method not found'}}, 30)
|
||
except McpError:
|
||
pass
|
||
raise McpError('MCP 的 SSE 流结束了但没有返回本次请求的响应')
|
||
|
||
def notify(self, message: dict) -> None:
|
||
try:
|
||
resp = self._post(message, 30)
|
||
resp.read()
|
||
resp.close()
|
||
except McpError as exc:
|
||
# 通知失败不影响主流程(有些服务器对 notifications/initialized 直接 202/204)
|
||
print(f'[mcp] 通知发送失败(可忽略):{exc}', file=sys.stderr)
|
||
|
||
def close(self) -> None:
|
||
return None
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 传输层:stdio
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
_PYTHON_CMD_RE = re.compile(r'^python[0-9.]*(\.exe)?$', re.IGNORECASE)
|
||
|
||
|
||
def _python_script_of(command: str, args) -> str:
|
||
"""
|
||
判断"这条 stdio 命令是不是在拿 python 跑某个 .py",是就返回那个脚本路径。
|
||
|
||
为什么要判断:安卓(Chaquopy)把 CPython 嵌在 App 主进程里,**没有 python 可执行文件**,
|
||
`python xxx.py` 这种标准写法起不了子进程。但 MCP 的线协议就是"一行一条 JSON",
|
||
所以我们可以给它一对假的 stdin/stdout,把脚本跑在**进程内**,效果完全一样。
|
||
这样同一份 mcp.servers.json 在电脑上走真子进程、在手机上走进程内仿真,用户不用改配置。
|
||
"""
|
||
base = os.path.basename(command or '').lower()
|
||
looks_like_python = bool(_PYTHON_CMD_RE.match(base)) or base in ('py', 'py.exe')
|
||
if not looks_like_python and os.path.basename(sys.executable or '').lower() == base:
|
||
looks_like_python = True
|
||
if not looks_like_python:
|
||
return ''
|
||
for arg in args:
|
||
text = str(arg)
|
||
if text.lower().endswith('.py') and os.path.isfile(text):
|
||
return text
|
||
return ''
|
||
|
||
|
||
def _inproc_stdio_enabled() -> bool:
|
||
"""安卓上自动启用;电脑上可以用 DOUBAO_MCP_INPROC_STDIO=1 强制打开(便于对照测试)"""
|
||
if paths.IS_ANDROID:
|
||
return True
|
||
return os.environ.get('DOUBAO_MCP_INPROC_STDIO') == '1'
|
||
|
||
|
||
class _FakeStdin:
|
||
"""
|
||
喂给 MCP 脚本的假 stdin。
|
||
|
||
关键点:它**按线程区分**——只有跑 MCP 脚本的那个线程读到的是管道数据,
|
||
内核自己的线程读到的还是真正的 stdin。否则整个进程的标准输入就被这一个服务独占了。
|
||
"""
|
||
|
||
def __init__(self, queue_in, real_stream, owner):
|
||
self._q = queue_in
|
||
self._real = real_stream
|
||
self._owner = owner
|
||
|
||
def _mine(self) -> bool:
|
||
return threading.current_thread() is self._owner
|
||
|
||
def readline(self, *_args, **_kwargs) -> str:
|
||
if not self._mine():
|
||
return self._real.readline() if self._real else ''
|
||
item = self._q.get()
|
||
return '' if item is None else item
|
||
|
||
def read(self, *_args, **_kwargs) -> str:
|
||
return self.readline()
|
||
|
||
def __iter__(self):
|
||
while True:
|
||
line = self.readline()
|
||
if not line:
|
||
return
|
||
yield line
|
||
|
||
def close(self):
|
||
pass
|
||
|
||
def fileno(self): # 有些库会调,给个明确失败而不是乱返回值
|
||
raise OSError('inproc stdin 没有文件描述符')
|
||
|
||
|
||
class _FakeStdout:
|
||
"""MCP 脚本的假 stdout:写进来的内容按行进队列,交给 reader 线程解析"""
|
||
|
||
def __init__(self, queue_out, real_stream, owner, mirror: bool):
|
||
self._q = queue_out
|
||
self._real = real_stream
|
||
self._owner = owner
|
||
self._mirror = mirror
|
||
|
||
def _mine(self) -> bool:
|
||
return threading.current_thread() is self._owner
|
||
|
||
def write(self, text) -> int:
|
||
text = str(text)
|
||
if not self._mine():
|
||
if self._real:
|
||
self._real.write(text)
|
||
return len(text)
|
||
if self._mirror and self._real:
|
||
# 进程内没法像子进程那样"日志去 stderr",这里镜像一份方便诊断
|
||
self._real.write(f'[mcp:inproc] {text}')
|
||
for line in text.splitlines(keepends=True):
|
||
self._q.put(line)
|
||
return len(text)
|
||
|
||
def flush(self):
|
||
if self._real and not self._mine():
|
||
self._real.flush()
|
||
|
||
def close(self):
|
||
pass
|
||
|
||
def fileno(self):
|
||
raise OSError('inproc stdout 没有文件描述符')
|
||
|
||
|
||
class _QueueWriter:
|
||
"""
|
||
给 _StdioTransport 用的"假 stdin":内核往这里写,就相当于写进了子进程的标准输入。
|
||
注意方向——transport 的 proc.stdin 是**写入端**,脚本那边的 sys.stdin 才是读取端。
|
||
"""
|
||
|
||
def __init__(self, queue_in):
|
||
self._q = queue_in
|
||
|
||
def write(self, text) -> int:
|
||
text = str(text)
|
||
for line in text.splitlines(keepends=True):
|
||
self._q.put(line)
|
||
return len(text)
|
||
|
||
def flush(self):
|
||
pass
|
||
|
||
def close(self):
|
||
self._q.put(None)
|
||
|
||
|
||
class _LineQueueReader:
|
||
"""给 _read_loop 用的可迭代流:一行一行从队列取,None 表示 EOF"""
|
||
|
||
def __init__(self, queue_out):
|
||
self._q = queue_out
|
||
|
||
def __iter__(self):
|
||
while True:
|
||
item = self._q.get()
|
||
if item is None:
|
||
return
|
||
yield item
|
||
|
||
def readline(self, *_args, **_kwargs) -> str:
|
||
item = self._q.get()
|
||
return '' if item is None else item
|
||
|
||
def close(self):
|
||
self._q.put(None)
|
||
|
||
|
||
class _InProcProcess:
|
||
"""
|
||
假装自己是 subprocess.Popen:只实现 _StdioTransport 用到的那几个接口
|
||
(stdin / stdout / poll / terminate / wait / kill),把 MCP 脚本跑在进程内。
|
||
"""
|
||
|
||
def __init__(self, script: str, argv: list, env: dict):
|
||
self._to_script = queue.Queue()
|
||
self._from_script = queue.Queue()
|
||
self._alive = True
|
||
self._returncode = None
|
||
# transport 视角:stdin 写进去 → 脚本读到;stdout 读出来 ← 脚本写的
|
||
self.stdin = _QueueWriter(self._to_script)
|
||
self.stdout = _LineQueueReader(self._from_script)
|
||
self._thread = threading.Thread(
|
||
target=self._run, args=(script, argv, env), name='mcp-inproc', daemon=True,
|
||
)
|
||
self._thread.start()
|
||
|
||
def _run(self, script: str, argv: list, env: dict) -> None:
|
||
import runpy
|
||
|
||
me = threading.current_thread()
|
||
real_in, real_out, real_err = sys.stdin, sys.stdout, sys.stderr
|
||
real_argv = sys.argv
|
||
real_path = list(sys.path)
|
||
real_env = dict(os.environ)
|
||
|
||
sys.stdin = _FakeStdin(self._to_script, real_in, me)
|
||
# stdout 走进协议管道(镜像到真 stderr 方便排查);
|
||
# stderr 也镜像过去:MCP 服务经常把日志打到 stderr
|
||
sys.stdout = _FakeStdout(self._from_script, real_err, me, mirror=True)
|
||
sys.stderr = _FakeStdout(self._from_script, real_err, me, mirror=False)
|
||
sys.argv = argv
|
||
if os.path.dirname(script) not in sys.path:
|
||
sys.path.insert(0, os.path.dirname(script))
|
||
try:
|
||
os.environ.update({str(k): str(v) for k, v in (env or {}).items()})
|
||
runpy.run_path(script, run_name='__main__')
|
||
except SystemExit:
|
||
pass
|
||
except BaseException as exc: # noqa: BLE001 - 服务崩了要给出可读信息
|
||
print(f'[mcp] 进程内 stdio 服务异常退出:{exc!r}', file=real_err)
|
||
finally:
|
||
sys.stdin, sys.stdout, sys.stderr = real_in, real_out, real_err
|
||
sys.argv = real_argv
|
||
sys.path[:] = real_path
|
||
os.environ.clear()
|
||
os.environ.update(real_env)
|
||
self._alive = False
|
||
self._returncode = 0
|
||
self._from_script.put(None) # 告诉读取方 EOF
|
||
|
||
# --- Popen 的子集 ---
|
||
def poll(self):
|
||
return None if self._alive else self._returncode
|
||
|
||
def terminate(self):
|
||
self._to_script.put(None) # 让阻塞在 stdin 的脚本醒过来并结束
|
||
self._alive = False
|
||
self._returncode = -15
|
||
|
||
def kill(self):
|
||
self.terminate()
|
||
|
||
def wait(self, timeout=None):
|
||
self._thread.join(timeout)
|
||
return self._returncode
|
||
|
||
|
||
class _StdioTransport:
|
||
"""
|
||
按行收发 JSON-RPC。
|
||
|
||
三种情况:
|
||
- 安卓 + 命令是 python 跑 .py → 进程内仿真(没有 python 可执行文件,起不了子进程)
|
||
- 安卓 + 命令是原生可执行文件 → 照常起子进程(/system/bin/sh、toybox 这些是可以起的)
|
||
- 电脑 → 照常起子进程
|
||
"""
|
||
|
||
def __init__(self, spec: dict):
|
||
command = spec.get('command') or ''
|
||
args = [str(a) for a in (spec.get('args') or [])]
|
||
if not command:
|
||
raise McpError('stdio 传输缺少 command')
|
||
|
||
env = {**os.environ, **{str(k): str(v) for k, v in (spec.get('env') or {}).items()}}
|
||
script = _python_script_of(command, args) if _inproc_stdio_enabled() else ''
|
||
|
||
if script:
|
||
# 用 python 跑的 .py 服务:进程内仿真,不需要可执行文件
|
||
forwarded = [a for a in args if a != script and not str(a).startswith('-')]
|
||
self.proc = _InProcProcess(script, [script, *forwarded], env)
|
||
self._inproc = True
|
||
print(f'[mcp] {spec.get("name")}:安卓/无解释器环境,改用进程内 stdio 仿真({script})', file=sys.stderr)
|
||
else:
|
||
# Windows 下 npx/npm/node 是 .cmd,必须用 cmd /c 包一层(官方 README 明确要求)
|
||
if paths.IS_WINDOWS and re.match(r'^(npx|npm|node|pnpm|yarn)$', command, re.IGNORECASE):
|
||
argv = ['cmd', '/c', command, *args]
|
||
else:
|
||
argv = [command, *args]
|
||
if not shutil.which(command) and not os.path.isabs(command):
|
||
raise McpError(
|
||
f'找不到命令 {command}(请确认已安装并在 PATH 里)。'
|
||
'安卓上推荐把 MCP 服务写成 .py,用 transport="stdio" + command="python" 即可(内核会自动改用进程内执行)'
|
||
)
|
||
kwargs = {}
|
||
if paths.IS_WINDOWS:
|
||
kwargs['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
||
try:
|
||
self.proc = subprocess.Popen(
|
||
argv,
|
||
stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE,
|
||
# 子进程日志直接继承内核的 stderr:既能诊断又不会把管道塞满
|
||
stderr=None,
|
||
text=True,
|
||
encoding='utf-8',
|
||
errors='replace',
|
||
bufsize=1,
|
||
env=env,
|
||
**kwargs,
|
||
)
|
||
except OSError as exc:
|
||
raise McpError(f'无法启动 MCP 服务进程 {command}:{exc}') from exc
|
||
self._inproc = False
|
||
self._cv = threading.Condition()
|
||
self._responses: dict = {}
|
||
self._closed = False
|
||
self._reader = threading.Thread(target=self._read_loop, name='mcp-stdio-reader', daemon=True)
|
||
self._reader.start()
|
||
|
||
def _read_loop(self) -> None:
|
||
stream = self.proc.stdout
|
||
try:
|
||
for raw in stream:
|
||
line = raw.strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
message = json.loads(line)
|
||
except ValueError:
|
||
# 有些服务会往 stdout 打日志,忽略掉,不要打断协议
|
||
print(f'[mcp] 忽略非 JSON 输出:{line[:200]}', file=sys.stderr)
|
||
continue
|
||
if isinstance(message, dict) and message.get('id') is not None:
|
||
with self._cv:
|
||
self._responses[message['id']] = message
|
||
self._cv.notify_all()
|
||
except (OSError, ValueError):
|
||
pass
|
||
with self._cv:
|
||
self._closed = True
|
||
self._cv.notify_all()
|
||
|
||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||
with self._cv:
|
||
if self._closed:
|
||
raise McpError('MCP 服务进程已退出')
|
||
try:
|
||
self.proc.stdin.write(json.dumps(message, ensure_ascii=False) + '\n')
|
||
self.proc.stdin.flush()
|
||
except (OSError, ValueError) as exc:
|
||
raise McpError(f'写入 MCP 服务失败:{exc}') from exc
|
||
# 用单调时钟算总超时:被别的响应唤醒时不能把等待时间重新计一遍
|
||
deadline = time.monotonic() + timeout
|
||
with self._cv:
|
||
while message.get('id') not in self._responses:
|
||
remain = deadline - time.monotonic()
|
||
if remain <= 0:
|
||
raise McpError(f'MCP 请求超时({timeout}s):{message.get("method")}')
|
||
if self._closed:
|
||
raise McpError('MCP 服务进程已关闭连接')
|
||
self._cv.wait(remain)
|
||
return self._responses.pop(message['id'])
|
||
|
||
def notify(self, message: dict) -> None:
|
||
try:
|
||
self.proc.stdin.write(json.dumps(message, ensure_ascii=False) + '\n')
|
||
self.proc.stdin.flush()
|
||
except (OSError, ValueError) as exc:
|
||
print(f'[mcp] 通知发送失败:{exc}', file=sys.stderr)
|
||
|
||
def close(self) -> None:
|
||
try:
|
||
if self.proc.poll() is None:
|
||
self.proc.terminate()
|
||
try:
|
||
self.proc.wait(timeout=3)
|
||
except subprocess.TimeoutExpired:
|
||
self.proc.kill()
|
||
except OSError:
|
||
pass
|
||
for stream in (self.proc.stdin, self.proc.stdout):
|
||
try:
|
||
if stream:
|
||
stream.close()
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 传输层:inproc(安卓专用)
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
class _InprocTransport:
|
||
"""
|
||
进程内 MCP:import 用户给的 .py,暴露 handle(request: dict) -> dict。
|
||
|
||
为什么要用"队列 + 工作线程"而不是直接调用 handle:
|
||
* 语义上和 http/stdio 完全一致(请求-响应配对、超时、异常 → JSON-RPC error),
|
||
这样内核上层的 initialize / tools/list / tools/call 编排只有一份代码;
|
||
* handle 里如果阻塞/抛异常,也不会把 HTTP 请求线程搞乱,超时能正常返回。
|
||
|
||
约定(写进 README 和对话提示里):
|
||
* 只把**带 id 的请求**交给 handle;通知(notifications/initialized 等)直接跳过,
|
||
这样最小实现只要处理 initialize / tools/list / tools/call 三个方法。
|
||
* 返回值可以是完整 JSON-RPC 响应,也可以只给 {"result": ...},甚至直接给结果对象。
|
||
"""
|
||
|
||
def __init__(self, spec: dict):
|
||
file_path = spec.get('file') or spec.get('path') or spec.get('script') or ''
|
||
if not file_path:
|
||
raise McpError('inproc 需要 file 字段指向 .py 文件')
|
||
if not os.path.isfile(file_path):
|
||
raise McpError(f'找不到 inproc 服务文件:{file_path}')
|
||
self.path = os.path.abspath(file_path)
|
||
module = _import_module(self.path)
|
||
handler = getattr(module, 'handle', None)
|
||
if not callable(handler):
|
||
raise McpError(f'{os.path.basename(self.path)} 必须暴露 handle(request) -> dict')
|
||
self._handler = handler
|
||
self._queue: queue.Queue = queue.Queue()
|
||
self._inflight: dict = {}
|
||
self._cv = threading.Condition()
|
||
self._closed = False
|
||
self._thread = threading.Thread(
|
||
target=self._worker, name=f'mcp-inproc-{os.path.basename(self.path)}', daemon=True
|
||
)
|
||
self._thread.start()
|
||
|
||
def _call_handler(self, message: dict):
|
||
result = self._handler(message)
|
||
# 顺手支持 async def handle:安卓上有些库只有异步接口
|
||
if inspect.iscoroutine(result):
|
||
import asyncio
|
||
|
||
result = asyncio.run(result)
|
||
return result
|
||
|
||
@staticmethod
|
||
def _normalize(raw, req_id):
|
||
"""把 handle 的返回值规整成 JSON-RPC 响应(宽容一点,方便手写服务)。"""
|
||
if isinstance(raw, dict) and ('result' in raw or 'error' in raw):
|
||
out = {'jsonrpc': '2.0', 'id': raw.get('id', req_id)}
|
||
if 'error' in raw:
|
||
out['error'] = raw['error']
|
||
else:
|
||
out['result'] = raw.get('result')
|
||
return out
|
||
return {'jsonrpc': '2.0', 'id': req_id, 'result': raw}
|
||
|
||
def _worker(self) -> None:
|
||
while True:
|
||
item = self._queue.get()
|
||
if item is None: # 关闭信号
|
||
break
|
||
message = item
|
||
req_id = message.get('id')
|
||
try:
|
||
response = self._normalize(self._call_handler(message), req_id)
|
||
except BaseException as exc: # noqa: BLE001 - 服务里的异常要变成 JSON-RPC error
|
||
response = {
|
||
'jsonrpc': '2.0',
|
||
'id': req_id,
|
||
'error': {'code': -32603, 'message': f'{type(exc).__name__}: {exc}'},
|
||
}
|
||
with self._cv:
|
||
self._inflight[req_id] = response
|
||
self._cv.notify_all()
|
||
with self._cv:
|
||
self._closed = True
|
||
self._cv.notify_all()
|
||
|
||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||
req_id = message.get('id')
|
||
with self._cv:
|
||
if self._closed:
|
||
raise McpError('inproc MCP 服务已关闭')
|
||
self._inflight[req_id] = _PENDING
|
||
self._queue.put(message)
|
||
deadline = time.monotonic() + timeout
|
||
with self._cv:
|
||
while self._inflight.get(req_id) is _PENDING:
|
||
remain = deadline - time.monotonic()
|
||
if remain <= 0:
|
||
self._inflight.pop(req_id, None)
|
||
raise McpError(f'inproc MCP 请求超时({timeout}s):{message.get("method")}')
|
||
self._cv.wait(remain)
|
||
return self._inflight.pop(req_id)
|
||
|
||
def notify(self, message: dict) -> None:
|
||
# 通知不要求响应,也不交给 handle(见类注释:让最小实现只处理三个方法)
|
||
return None
|
||
|
||
def close(self) -> None:
|
||
with self._cv:
|
||
if self._closed:
|
||
return
|
||
self._queue.put(None)
|
||
self._thread.join(timeout=2)
|
||
|
||
|
||
def _import_module(file_path: str):
|
||
"""按路径 import 用户的 MCP 服务文件(和工具运行时同一套手法)。"""
|
||
stem = re.sub(r'\W', '_', os.path.splitext(os.path.basename(file_path))[0])
|
||
mod_name = f'_doubao_mcp_{stem}_{abs(hash(os.path.abspath(file_path))) % 100000}'
|
||
sys.modules.pop(mod_name, None)
|
||
folder = os.path.dirname(os.path.abspath(file_path))
|
||
if folder not in sys.path:
|
||
sys.path.insert(0, folder)
|
||
spec = importlib.util.spec_from_file_location(mod_name, file_path)
|
||
if spec is None or spec.loader is None:
|
||
raise McpError(f'无法为 {file_path} 建立模块 spec')
|
||
module = importlib.util.module_from_spec(spec)
|
||
sys.modules[mod_name] = module
|
||
try:
|
||
spec.loader.exec_module(module)
|
||
except BaseException as exc: # noqa: BLE001
|
||
sys.modules.pop(mod_name, None)
|
||
raise McpError(f'导入 {os.path.basename(file_path)} 失败:{type(exc).__name__}: {exc}') from exc
|
||
return module
|
||
|
||
|
||
def _make_transport(spec: dict):
|
||
transport = (spec.get('transport') or 'stdio').lower()
|
||
if transport == 'http':
|
||
return _HttpTransport(spec)
|
||
if transport == 'stdio':
|
||
return _StdioTransport(spec)
|
||
if transport == 'inproc':
|
||
return _InprocTransport(spec)
|
||
if transport == 'sse':
|
||
raise McpError('sse(旧版 HTTP+SSE)传输在 Python 内核里未实现,请改用 transport="http" 或 "inproc"')
|
||
raise McpError(f'不认识的 transport:{transport}')
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 客户端:initialize / tools/list / tools/call 编排
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
class McpClient:
|
||
def __init__(self, spec: dict):
|
||
self.spec = spec
|
||
self.transport = _make_transport(spec)
|
||
self.tools: list = []
|
||
self._id = 0
|
||
self._lock = threading.RLock()
|
||
|
||
def _next_id(self) -> int:
|
||
with self._lock:
|
||
self._id += 1
|
||
return self._id
|
||
|
||
def _request(self, method: str, params: dict | None, timeout: float, tolerate_error: bool = False):
|
||
message = {'jsonrpc': '2.0', 'id': self._next_id(), 'method': method}
|
||
if params is not None:
|
||
message['params'] = params
|
||
try:
|
||
response = self.transport.request(message, timeout)
|
||
except McpError:
|
||
if tolerate_error:
|
||
return None
|
||
raise
|
||
if not isinstance(response, dict):
|
||
raise McpError(f'{method} 返回了非对象响应')
|
||
if response.get('error'):
|
||
err = response['error'] or {}
|
||
detail = err.get('message') if isinstance(err, dict) else str(err)
|
||
if tolerate_error:
|
||
print(f'[mcp] {method} 失败(已忽略):{detail}', file=sys.stderr)
|
||
return None
|
||
raise McpError(f'{method} 失败:{detail}')
|
||
return response.get('result')
|
||
|
||
def connect(self, timeout: float = 180) -> 'McpClient':
|
||
# initialize 允许失败:inproc 的最小实现可能只认 tools/list、tools/call
|
||
self._request(
|
||
'initialize',
|
||
{
|
||
'protocolVersion': PROTOCOL_VERSION,
|
||
'capabilities': {},
|
||
'clientInfo': CLIENT_INFO,
|
||
},
|
||
timeout,
|
||
tolerate_error=True,
|
||
)
|
||
self.transport.notify({'jsonrpc': '2.0', 'method': 'notifications/initialized', 'params': {}})
|
||
listed = self._request('tools/list', {}, 60) or {}
|
||
self.tools = listed.get('tools') or []
|
||
return self
|
||
|
||
def call_tool(self, name: str, arguments: dict, timeout: float = 120) -> dict:
|
||
result = self._request('tools/call', {'name': name, 'arguments': arguments or {}}, timeout)
|
||
return result or {}
|
||
|
||
def close(self) -> None:
|
||
try:
|
||
self.transport.close()
|
||
except Exception as exc: # noqa: BLE001 - 关闭失败不该影响别的服务器
|
||
print(f'[mcp] 关闭连接失败:{exc}', file=sys.stderr)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 连接池 / 对外接口
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def connect(server_name: str, force: bool = False) -> dict:
|
||
"""连接(或复用)一个 MCP 服务器;错误记在 record['error'] 里,不抛给调用方。"""
|
||
with _lock:
|
||
existing = _clients.get(server_name)
|
||
if existing and existing.get('client') and not force:
|
||
return existing
|
||
if existing and existing.get('client') and force:
|
||
disconnect(server_name)
|
||
|
||
spec = next((s for s in read_mcp_config()['servers'] if s.get('name') == server_name), None)
|
||
if not spec:
|
||
raise McpError(f'mcp.servers.json 里没有服务器 {server_name}')
|
||
if spec.get('enabled') is False:
|
||
raise McpError(f'服务器 {server_name} 已被禁用')
|
||
|
||
record = {'spec': spec, 'client': None, 'tools': [], 'error': None}
|
||
with _lock:
|
||
_clients[server_name] = record
|
||
try:
|
||
client = McpClient(spec).connect()
|
||
record['client'] = client
|
||
record['tools'] = client.tools
|
||
record['error'] = None
|
||
print(f'[mcp] {server_name} 已连接,{len(client.tools)} 个工具')
|
||
except BaseException as exc: # noqa: BLE001 - 单个服务器失败不能影响内核启动
|
||
record['error'] = str(exc)
|
||
print(f'[mcp] {server_name} 连接失败:{record["error"]}', file=sys.stderr)
|
||
return record
|
||
|
||
|
||
def disconnect(server_name: str) -> None:
|
||
with _lock:
|
||
record = _clients.pop(server_name, None)
|
||
if not record:
|
||
return
|
||
client = record.get('client')
|
||
if client:
|
||
client.close()
|
||
|
||
|
||
def disconnect_all() -> None:
|
||
for name in list(_clients.keys()):
|
||
disconnect(name)
|
||
|
||
|
||
def connect_all_enabled() -> list:
|
||
results = []
|
||
for spec in read_mcp_config()['servers']:
|
||
if spec.get('enabled') is False:
|
||
continue
|
||
try:
|
||
record = connect(spec.get('name'))
|
||
results.append({
|
||
'name': spec.get('name'),
|
||
'ok': not record.get('error'),
|
||
'error': record.get('error'),
|
||
'toolCount': len(record.get('tools') or []),
|
||
})
|
||
except BaseException as exc: # noqa: BLE001
|
||
results.append({'name': spec.get('name'), 'ok': False, 'error': str(exc)})
|
||
return results
|
||
|
||
|
||
def get_mcp_state() -> list:
|
||
out = []
|
||
for spec in read_mcp_config()['servers']:
|
||
record = _clients.get(spec.get('name')) or {}
|
||
transport = spec.get('transport') or 'stdio'
|
||
if transport == 'stdio':
|
||
target = f"{spec.get('command') or ''} {' '.join(str(a) for a in (spec.get('args') or []))}".strip()
|
||
elif transport == 'inproc':
|
||
target = spec.get('file') or spec.get('path') or ''
|
||
else:
|
||
target = spec.get('url') or ''
|
||
out.append({
|
||
'name': spec.get('name'),
|
||
'enabled': spec.get('enabled') is not False,
|
||
'transport': transport,
|
||
'target': target,
|
||
'connected': bool(record.get('client')),
|
||
'error': record.get('error') or None,
|
||
'tools': [
|
||
{'name': t.get('name'), 'description': t.get('description') or ''}
|
||
for t in (record.get('tools') or [])
|
||
],
|
||
})
|
||
return out
|
||
|
||
|
||
def sanitize_schema(schema) -> dict:
|
||
"""
|
||
MCP 的 inputSchema 不能直接当 OpenAI 的 parameters:
|
||
必须去 $schema、保证 type=object、补 properties/required,
|
||
并且 outputSchema 绝不能混进来(OpenAI 会直接拒)。
|
||
"""
|
||
src = schema if isinstance(schema, dict) else {}
|
||
out = dict(src)
|
||
out.pop('$schema', None)
|
||
out.pop('outputSchema', None)
|
||
if out.get('type') != 'object':
|
||
out['type'] = 'object'
|
||
if not isinstance(out.get('properties'), dict):
|
||
out['properties'] = {}
|
||
if not isinstance(out.get('required'), list):
|
||
out['required'] = [
|
||
key for key, value in out['properties'].items()
|
||
if isinstance(value, dict) and value.get('required') is True
|
||
]
|
||
if out.get('additionalProperties') is None:
|
||
out['additionalProperties'] = False
|
||
return out
|
||
|
||
|
||
def mcp_tool_defs() -> list:
|
||
defs = []
|
||
with _lock:
|
||
items = list(_clients.items())
|
||
for server_name, record in items:
|
||
if not record.get('client'):
|
||
continue
|
||
for tool in record.get('tools') or []:
|
||
defs.append({
|
||
'type': 'function',
|
||
'function': {
|
||
'name': f"mcp__{server_name}__{tool.get('name')}",
|
||
'description': f"[MCP:{server_name}] {tool.get('description') or tool.get('name')}",
|
||
'parameters': sanitize_schema(tool.get('inputSchema')),
|
||
},
|
||
})
|
||
return defs
|
||
|
||
|
||
def call_mcp_tool(full_name: str, args: dict) -> dict:
|
||
parts = full_name.split('__')
|
||
server_name = parts[1] if len(parts) > 1 else ''
|
||
tool_name = '__'.join(parts[2:])
|
||
record = _clients.get(server_name)
|
||
if not record or not record.get('client'):
|
||
raise McpError(f'MCP 服务器 {server_name} 未连接')
|
||
return record['client'].call_tool(tool_name, args or {})
|
||
|
||
|
||
def is_mcp_tool(name) -> bool:
|
||
return isinstance(name, str) and name.startswith('mcp__')
|