一个界面照着豆包抠的 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。
261 lines
9.9 KiB
JavaScript
261 lines
9.9 KiB
JavaScript
/**
|
||
* MCP(Model Context Protocol)客户端管理。
|
||
*
|
||
* tools/mcp.servers.json 描述要连接的服务:
|
||
* stdio: { "transport": "stdio", "command": "npx", "args": [...] }
|
||
* http : { "transport": "http", "url": "https://.../mcp", "headers": {...} }
|
||
* sse : { "transport": "sse", "url": "https://.../sse" }
|
||
*
|
||
* 对外暴露的工具名统一为 mcp__<server>__<tool>,避免和 Python 工具重名。
|
||
*/
|
||
import fs from 'node:fs';
|
||
import { MCP_FILE } from './config.mjs';
|
||
|
||
const clients = new Map(); // serverName -> { client, transport, tools, error, spec }
|
||
|
||
export function readMcpConfig() {
|
||
if (!fs.existsSync(MCP_FILE)) return { servers: [] };
|
||
try {
|
||
const json = JSON.parse(fs.readFileSync(MCP_FILE, 'utf8'));
|
||
const servers = Array.isArray(json) ? json : json.servers || [];
|
||
// 支持 ${VAR} 占位符:打包后路径随机器变,写死绝对路径不合适
|
||
return { servers: servers.map(expandServer) };
|
||
} catch (err) {
|
||
console.error('[mcp] mcp.servers.json 解析失败:', err.message);
|
||
return { servers: [], error: err.message };
|
||
}
|
||
}
|
||
|
||
function expand(value) {
|
||
if (typeof value !== 'string') return value;
|
||
return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name) => process.env[name] ?? match);
|
||
}
|
||
|
||
function expandServer(server) {
|
||
return {
|
||
...server,
|
||
command: expand(server.command),
|
||
args: (server.args || []).map(expand),
|
||
url: expand(server.url),
|
||
env: Object.fromEntries(Object.entries(server.env || {}).map(([k, v]) => [k, expand(v)])),
|
||
headers: Object.fromEntries(Object.entries(server.headers || {}).map(([k, v]) => [k, expand(v)])),
|
||
};
|
||
}
|
||
|
||
export function writeMcpConfig(config) {
|
||
fs.writeFileSync(MCP_FILE, JSON.stringify(config, null, 2), 'utf8');
|
||
}
|
||
|
||
/** 配置文件路径(界面上要显示给用户看) */
|
||
export function mcpConfigPath() {
|
||
return MCP_FILE;
|
||
}
|
||
|
||
/** 配置文件原文(供界面里直接编辑) */
|
||
export function readMcpConfigText() {
|
||
if (!fs.existsSync(MCP_FILE)) return '{\n "servers": []\n}\n';
|
||
return fs.readFileSync(MCP_FILE, 'utf8');
|
||
}
|
||
|
||
/**
|
||
* 保存界面里编辑的 JSON 文本。
|
||
* 先校验再落盘,避免把坏 JSON 写进去导致下次起不来。
|
||
*/
|
||
export function writeMcpConfigText(text) {
|
||
let parsed;
|
||
try {
|
||
parsed = JSON.parse(text);
|
||
} catch (err) {
|
||
throw new Error(`JSON 格式错误:${err.message}`);
|
||
}
|
||
const servers = Array.isArray(parsed) ? parsed : parsed.servers;
|
||
if (!Array.isArray(servers)) throw new Error('顶层必须是 { "servers": [ ... ] } 或一个数组');
|
||
for (const [i, server] of servers.entries()) {
|
||
if (!server || typeof server !== 'object') throw new Error(`第 ${i + 1} 项不是对象`);
|
||
if (!server.name) throw new Error(`第 ${i + 1} 项缺少 name`);
|
||
const transport = server.transport || 'stdio';
|
||
if (!['stdio', 'http', 'sse', 'inproc'].includes(transport)) {
|
||
throw new Error(`${server.name}: transport 只能是 stdio / http / sse / inproc`);
|
||
}
|
||
// inproc:安卓端内核直接 import 这个 py 文件;桌面上等价于用 python 起子进程
|
||
if (transport === 'inproc' && !server.path) throw new Error(`${server.name}: inproc 需要 path(py 文件路径)`);
|
||
if (transport === 'stdio' && !server.command) throw new Error(`${server.name}: stdio 需要 command`);
|
||
if ((transport === 'http' || transport === 'sse') && !server.url) throw new Error(`${server.name}: ${transport} 需要 url`);
|
||
}
|
||
writeMcpConfig(Array.isArray(parsed) ? { servers } : parsed);
|
||
return servers.length;
|
||
}
|
||
|
||
/** 断开全部连接(改完配置要重连) */
|
||
export async function disconnectAll() {
|
||
for (const name of [...clients.keys()]) {
|
||
await disconnect(name);
|
||
}
|
||
}
|
||
|
||
async function loadSdk() {
|
||
const [clientMod, stdioMod, httpMod, sseMod] = await Promise.all([
|
||
import('@modelcontextprotocol/sdk/client/index.js'),
|
||
import('@modelcontextprotocol/sdk/client/stdio.js'),
|
||
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
|
||
import('@modelcontextprotocol/sdk/client/sse.js'),
|
||
]);
|
||
return {
|
||
Client: clientMod.Client,
|
||
StdioClientTransport: stdioMod.StdioClientTransport,
|
||
StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,
|
||
SSEClientTransport: sseMod.SSEClientTransport,
|
||
};
|
||
}
|
||
|
||
export async function connect(serverName, { force = false } = {}) {
|
||
const existing = clients.get(serverName);
|
||
if (existing?.client && !force) return existing;
|
||
if (existing?.client && force) await disconnect(serverName);
|
||
|
||
const spec = readMcpConfig().servers.find((s) => s.name === serverName);
|
||
if (!spec) throw new Error(`mcp.servers.json 里没有服务器 ${serverName}`);
|
||
if (spec.enabled === false) throw new Error(`服务器 ${serverName} 已被禁用`);
|
||
|
||
const record = { spec, client: null, transport: null, tools: [], error: null };
|
||
clients.set(serverName, record);
|
||
|
||
try {
|
||
const sdk = await loadSdk();
|
||
let transport;
|
||
// inproc 在桌面/服务器上退化成"用 python 起这个脚本",行为和 stdio 一样
|
||
const isStdioLike = (spec.transport || 'stdio') === 'stdio' || spec.transport === 'inproc';
|
||
if (isStdioLike) {
|
||
const command = spec.transport === 'inproc' ? (spec.python || process.env.PYTHON || 'python') : spec.command;
|
||
const rawArgs = spec.transport === 'inproc' ? [spec.path, ...(spec.args || [])] : spec.args || [];
|
||
// Windows 下 npx / npm 是 .cmd,必须用 cmd /c 包一层(官方 README 明确要求)
|
||
const isWin = process.platform === 'win32';
|
||
const needsShellWrap = isWin && /^(npx|npm|node|pnpm|yarn)$/i.test(command || '');
|
||
transport = new sdk.StdioClientTransport({
|
||
command: needsShellWrap ? 'cmd' : command,
|
||
args: needsShellWrap ? ['/c', command, ...rawArgs] : rawArgs,
|
||
env: { ...process.env, ...(spec.env || {}) },
|
||
// inherit:子进程日志进内核的 stderr,既能诊断又不会把管道塞满
|
||
stderr: 'inherit',
|
||
});
|
||
} else if (spec.transport === 'sse') {
|
||
transport = new sdk.SSEClientTransport(new URL(spec.url), {
|
||
requestInit: { headers: spec.headers || {} },
|
||
});
|
||
} else {
|
||
transport = new sdk.StreamableHTTPClientTransport(new URL(spec.url), {
|
||
requestInit: { headers: spec.headers || {} },
|
||
});
|
||
}
|
||
const client = new sdk.Client({ name: 'doubao-kernel', version: '0.1.0' }, { capabilities: {} });
|
||
// 首次用 npx 拉起服务器时要下载包,可能远超 SDK 默认的 60s 超时
|
||
await client.connect(transport, { timeout: 180000 });
|
||
const listed = await client.listTools(undefined, { timeout: 60000 });
|
||
record.client = client;
|
||
record.transport = transport;
|
||
record.tools = listed.tools || [];
|
||
record.error = null;
|
||
console.log(`[mcp] ${serverName} 已连接,${record.tools.length} 个工具`);
|
||
} catch (err) {
|
||
record.error = err?.message || String(err);
|
||
console.error(`[mcp] ${serverName} 连接失败:${record.error}`);
|
||
}
|
||
return record;
|
||
}
|
||
|
||
export async function disconnect(serverName) {
|
||
const record = clients.get(serverName);
|
||
if (!record) return;
|
||
try {
|
||
await record.client?.close();
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
clients.delete(serverName);
|
||
}
|
||
|
||
export async function connectAllEnabled() {
|
||
const { servers } = readMcpConfig();
|
||
const results = [];
|
||
for (const spec of servers) {
|
||
if (spec.enabled === false) continue;
|
||
try {
|
||
const record = await connect(spec.name);
|
||
results.push({ name: spec.name, ok: !record.error, error: record.error, toolCount: record.tools.length });
|
||
} catch (err) {
|
||
results.push({ name: spec.name, ok: false, error: err.message });
|
||
}
|
||
}
|
||
return results;
|
||
}
|
||
|
||
export async function getMcpState() {
|
||
const { servers } = readMcpConfig();
|
||
return servers.map((spec) => {
|
||
const record = clients.get(spec.name);
|
||
return {
|
||
name: spec.name,
|
||
enabled: spec.enabled !== false,
|
||
transport: spec.transport || 'stdio',
|
||
target: spec.transport === 'stdio' ? `${spec.command} ${(spec.args || []).join(' ')}`.trim() : spec.url,
|
||
connected: Boolean(record?.client),
|
||
error: record?.error || null,
|
||
tools: (record?.tools || []).map((t) => ({
|
||
name: t.name,
|
||
description: t.description || '',
|
||
})),
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* MCP 的 inputSchema 不能直接当 OpenAI 的 parameters 用:
|
||
* 必须去掉 $schema、保证 type=object、补 properties/required,
|
||
* 并且 outputSchema 绝不能混进来(OpenAI 会直接拒)。
|
||
*/
|
||
export function sanitizeSchema(schema) {
|
||
const src = schema && typeof schema === 'object' ? schema : {};
|
||
const out = { ...src };
|
||
delete out.$schema;
|
||
delete out.outputSchema;
|
||
if (out.type !== 'object') out.type = 'object';
|
||
if (!out.properties || typeof out.properties !== 'object') out.properties = {};
|
||
if (!Array.isArray(out.required)) {
|
||
out.required = Object.keys(out.properties).filter((k) => out.properties[k]?.required === true);
|
||
}
|
||
if (out.additionalProperties === undefined) out.additionalProperties = false;
|
||
return out;
|
||
}
|
||
|
||
/** 全部已连接 MCP 工具 → OpenAI tools 定义 */
|
||
export function mcpToolDefs() {
|
||
const defs = [];
|
||
for (const [serverName, record] of clients.entries()) {
|
||
if (!record.client) continue;
|
||
for (const tool of record.tools) {
|
||
defs.push({
|
||
type: 'function',
|
||
function: {
|
||
name: `mcp__${serverName}__${tool.name}`,
|
||
description: `[MCP:${serverName}] ${tool.description || tool.name}`,
|
||
parameters: sanitizeSchema(tool.inputSchema),
|
||
},
|
||
});
|
||
}
|
||
}
|
||
return defs;
|
||
}
|
||
|
||
export async function callMcpTool(fullName, args) {
|
||
const [, serverName, ...rest] = fullName.split('__');
|
||
const toolName = rest.join('__');
|
||
const record = clients.get(serverName);
|
||
if (!record?.client) throw new Error(`MCP 服务器 ${serverName} 未连接`);
|
||
const res = await record.client.callTool({ name: toolName, arguments: args || {} });
|
||
return res;
|
||
}
|
||
|
||
export function isMcpTool(name) {
|
||
return typeof name === 'string' && name.startsWith('mcp__');
|
||
}
|