luatos-mcp.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. #!/usr/bin/env node
  2. /**
  3. * LuatOS Flasher MCP server (stdio).
  4. *
  5. * This is a thin, AI-friendly wrapper around luatos-cli. It exposes serial,
  6. * flashing, resource-download and project-management operations as MCP tools.
  7. *
  8. * Configure it in an MCP client, for example:
  9. *
  10. * {
  11. * "mcpServers": {
  12. * "luatos": {
  13. * "command": "node",
  14. * "args": ["/Applications/LuatOS Flasher.app/Contents/Resources/mcp/luatos-mcp.mjs"],
  15. * "env": { "LUATOS_CLI": "/Applications/LuatOS Flasher.app/Contents/MacOS/luatos-cli" }
  16. * }
  17. * }
  18. * }
  19. *
  20. * stdout is reserved for JSON-RPC; diagnostics go to stderr.
  21. */
  22. import fs from 'node:fs';
  23. import os from 'node:os';
  24. import path from 'node:path';
  25. import readline from 'node:readline';
  26. import { execFile } from 'node:child_process';
  27. import { fileURLToPath } from 'node:url';
  28. const SERVER_NAME = 'luatos-mcp';
  29. const SERVER_VERSION = '0.1.0';
  30. const PROTOCOL_VERSION = '2024-11-05';
  31. const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
  32. const IS_WINDOWS = process.platform === 'win32';
  33. function log(...args) {
  34. console.error(`[${SERVER_NAME}]`, ...args);
  35. }
  36. function defaultAppDataDir() {
  37. if (process.platform === 'darwin') {
  38. return path.join(os.homedir(), 'Library', 'Application Support', 'com.luatos.flasher');
  39. }
  40. if (IS_WINDOWS) {
  41. return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'com.luatos.flasher');
  42. }
  43. return path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'com.luatos.flasher');
  44. }
  45. function defaultProjectsDir() {
  46. return path.join(defaultAppDataDir(), 'projects');
  47. }
  48. function defaultResourcesDir() {
  49. return path.join(defaultAppDataDir(), 'resources');
  50. }
  51. function isFile(candidate) {
  52. try {
  53. return fs.statSync(candidate).isFile();
  54. } catch {
  55. return false;
  56. }
  57. }
  58. function findCli() {
  59. const envPath = process.env.LUATOS_CLI;
  60. if (envPath && isFile(envPath)) return envPath;
  61. const exe = IS_WINDOWS ? 'luatos-cli.exe' : 'luatos-cli';
  62. const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
  63. const candidates = [
  64. path.join(SCRIPT_DIR, exe),
  65. path.join(SCRIPT_DIR, '..', exe),
  66. path.join(SCRIPT_DIR, '..', '..', 'MacOS', exe),
  67. path.join(SCRIPT_DIR, '..', '..', 'Resources', 'bin', exe),
  68. path.join(SCRIPT_DIR, '..', '..', 'binaries', `luatos-cli-${arch}-apple-darwin`),
  69. path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', IS_WINDOWS ? 'win' : 'bin', exe),
  70. path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', 'bin', exe),
  71. ];
  72. for (const candidate of candidates) {
  73. if (isFile(candidate)) return candidate;
  74. }
  75. return exe; // rely on PATH
  76. }
  77. const CLI = findCli();
  78. function execCli(args, timeoutMs = 300_000) {
  79. return new Promise((resolve) => {
  80. const started = Date.now();
  81. execFile(
  82. CLI,
  83. args,
  84. {
  85. timeout: timeoutMs,
  86. maxBuffer: 64 * 1024 * 1024,
  87. windowsHide: true,
  88. env: { ...process.env, NO_COLOR: '1' },
  89. },
  90. (error, stdout, stderr) => {
  91. const timedOut = Boolean(error && (error.killed || error.signal === 'SIGTERM'));
  92. resolve({
  93. ok: !error,
  94. code: error && typeof error.code === 'number' ? error.code : error ? -1 : 0,
  95. timedOut,
  96. stdout: String(stdout || ''),
  97. stderr: String(stderr || ''),
  98. elapsed_ms: Date.now() - started,
  99. error: error ? String(error.message || error) : null,
  100. });
  101. },
  102. );
  103. });
  104. }
  105. async function runJson(args, timeoutMs) {
  106. const result = await execCli(['--format', 'json', ...args], timeoutMs);
  107. if (result.timedOut) {
  108. throw new Error(`luatos-cli 超时(${Math.round(timeoutMs / 1000)}s):${args.join(' ')}`);
  109. }
  110. if (!result.ok) {
  111. throw new Error((result.stderr || result.stdout || result.error || `退出码 ${result.code}`).trim());
  112. }
  113. try {
  114. return JSON.parse(result.stdout);
  115. } catch (error) {
  116. throw new Error(`无法解析 luatos-cli JSON 输出:${error.message}\n${result.stdout.slice(0, 1200)}`);
  117. }
  118. }
  119. async function runJsonl(args, timeoutMs) {
  120. const result = await execCli(['--format', 'jsonl', ...args], timeoutMs);
  121. const events = [];
  122. const lines = [];
  123. for (const raw of result.stdout.split(/\r?\n/)) {
  124. const line = raw.trim();
  125. if (!line) continue;
  126. lines.push(line);
  127. if (line.startsWith('{')) {
  128. try {
  129. events.push(JSON.parse(line));
  130. continue;
  131. } catch {
  132. // keep as a plain line
  133. }
  134. }
  135. }
  136. for (const raw of result.stderr.split(/\r?\n/)) {
  137. const line = raw.trim();
  138. if (line) lines.push(line);
  139. }
  140. return { ...result, events, lines };
  141. }
  142. function tail(lines, count = 160) {
  143. return lines.slice(Math.max(0, lines.length - count)).join('\n');
  144. }
  145. function summarizeEvents(events) {
  146. const result = [...events].reverse().find((event) => event.type === 'result') || null;
  147. const progress = [...events].reverse().find((event) => event.type === 'progress') || null;
  148. return { result, progress };
  149. }
  150. function formatSize(bytes) {
  151. const value = Number(bytes) || 0;
  152. const units = ['B', 'KB', 'MB', 'GB'];
  153. let index = 0;
  154. let size = value;
  155. while (size >= 1024 && index < units.length - 1) {
  156. size /= 1024;
  157. index += 1;
  158. }
  159. return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
  160. }
  161. function scanProjects(root) {
  162. fs.mkdirSync(root, { recursive: true });
  163. const projects = [];
  164. for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
  165. if (!entry.isDirectory()) continue;
  166. const dir = path.join(root, entry.name);
  167. if (!isFile(path.join(dir, 'luatos-project.toml'))) continue;
  168. let modified = 0;
  169. try {
  170. modified = Math.floor(fs.statSync(dir).mtimeMs / 1000);
  171. } catch {
  172. // ignore
  173. }
  174. projects.push({ name: entry.name, path: dir, modified });
  175. }
  176. projects.sort((left, right) => right.modified - left.modified);
  177. return projects;
  178. }
  179. function flashArgs(args) {
  180. const soc = args.soc || args.soc_path;
  181. if (!soc || !isFile(soc)) throw new Error('soc 固件文件不存在');
  182. if (!args.port) throw new Error('port 不能为空');
  183. const mode = args.mode === 'script' ? 'script' : 'run';
  184. const command = ['flash', mode, '--soc', soc, '--port', args.port];
  185. if (args.script_dir) command.push('--script', args.script_dir);
  186. if (args.baud) command.push('--baud', String(args.baud));
  187. if (mode === 'run' && Number(args.tail_log_secs) > 0) {
  188. command.push('--tail-log-secs', String(Number(args.tail_log_secs)));
  189. }
  190. if (args.rts_reset) command.push('--rts-reset');
  191. return command;
  192. }
  193. const TOOLS = [
  194. {
  195. name: 'serial_list',
  196. description: '列出当前系统可用的串口(含 VID/PID/产品名)。',
  197. inputSchema: { type: 'object', properties: {}, additionalProperties: false },
  198. },
  199. {
  200. name: 'guide_models',
  201. description: '列出 luatos-cli 支持的芯片/型号及推荐命令。',
  202. inputSchema: { type: 'object', properties: {}, additionalProperties: false },
  203. },
  204. {
  205. name: 'firmware_info',
  206. description: '解析 .soc 固件,返回芯片、版本、分区和文件列表。',
  207. inputSchema: {
  208. type: 'object',
  209. properties: { soc: { type: 'string', description: '.soc 文件路径' } },
  210. required: ['soc'],
  211. },
  212. },
  213. {
  214. name: 'flash_firmware',
  215. description:
  216. '烧录 .soc 固件到设备。全量烧录用 mode=full;仅刷脚本区用 mode=script 并传 script_dir。该调用会等待烧录完成。',
  217. inputSchema: {
  218. type: 'object',
  219. properties: {
  220. soc: { type: 'string', description: '.soc 文件路径' },
  221. port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
  222. mode: { type: 'string', enum: ['full', 'script'], default: 'full' },
  223. script_dir: { type: 'string', description: '脚本目录(mode=script 时必填)' },
  224. baud: { type: ['string', 'number'], description: '可选烧录波特率' },
  225. tail_log_secs: { type: 'number', description: '烧录后继续抓日志的秒数' },
  226. rts_reset: { type: 'boolean', description: '烧录前发送 RTS 复位脉冲' },
  227. timeout_secs: { type: 'number', description: '超时秒数,默认 900' },
  228. },
  229. required: ['soc', 'port'],
  230. },
  231. },
  232. {
  233. name: 'serial_log',
  234. description:
  235. '采集一段串口日志(默认 5 秒)并返回文本。Air1601/Air1602/EC718 用 mode=binary,probe 默认开启。',
  236. inputSchema: {
  237. type: 'object',
  238. properties: {
  239. port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
  240. baud: { type: ['string', 'number'], description: '波特率;文本默认 921600,二进制默认 2000000' },
  241. mode: { type: 'string', enum: ['text', 'binary'], default: 'text' },
  242. duration_secs: { type: 'number', description: '采集秒数,默认 5,最大 60' },
  243. probe: { type: 'boolean', description: '二进制模式发送 Probe,默认 true' },
  244. smart: { type: 'boolean', description: '启用智能分析' },
  245. rts_reset: { type: 'boolean', description: '开始前发送 RTS 复位脉冲' },
  246. },
  247. required: ['port'],
  248. },
  249. },
  250. {
  251. name: 'resource_list',
  252. description: '列出 LuatOS CDN 资源分类;传 module 可列出该分类下的子项、版本和文件。',
  253. inputSchema: {
  254. type: 'object',
  255. properties: { module: { type: 'string', description: '分类名,例如 Air8101、Air8000、public' } },
  256. },
  257. },
  258. {
  259. name: 'resource_download',
  260. description:
  261. '下载 LuatOS CDN 资源。例:category=public, sub=soc_script;或 category=Air8000, sub=V2032。会等待下载完成。',
  262. inputSchema: {
  263. type: 'object',
  264. properties: {
  265. category: { type: 'string', description: '资源大类,例如 public、Air8101' },
  266. sub: { type: 'string', description: '子项名(如 soc_script)或版本过滤(如 V2032)' },
  267. item: { type: 'string', description: '版本名或文件名过滤,可选' },
  268. output: { type: 'string', description: '下载目录,默认应用资源目录' },
  269. timeout_secs: { type: 'number', description: '超时秒数,默认 1800' },
  270. },
  271. required: ['category', 'sub'],
  272. },
  273. },
  274. {
  275. name: 'project_list',
  276. description: '扫描项目根目录,列出 LuatOS 项目(含 luatos-project.toml 的目录)。',
  277. inputSchema: {
  278. type: 'object',
  279. properties: { root: { type: 'string', description: '项目根目录,默认应用项目目录' } },
  280. },
  281. },
  282. {
  283. name: 'project_create',
  284. description: '创建新的 LuatOS 项目(非交互式)。',
  285. inputSchema: {
  286. type: 'object',
  287. properties: {
  288. name: { type: 'string', description: '项目名' },
  289. chip: { type: 'string', description: '芯片族,例如 bk72xx、air8101、air8000、air6208、ec7xx' },
  290. dir: { type: 'string', description: '项目目录,默认 <项目根>/<name>' },
  291. },
  292. required: ['name', 'chip'],
  293. },
  294. },
  295. {
  296. name: 'project_import',
  297. description: '导入 LuaTools .ini 工程或 .luatos 归档。',
  298. inputSchema: {
  299. type: 'object',
  300. properties: {
  301. file: { type: 'string', description: '.ini 或 .luatos 文件路径' },
  302. dir: { type: 'string', description: '输出目录,默认 <项目根>/<文件名>' },
  303. },
  304. required: ['file'],
  305. },
  306. },
  307. {
  308. name: 'project_info',
  309. description: '读取项目配置(芯片、版本、脚本目录、输出、flash 配置等)。',
  310. inputSchema: {
  311. type: 'object',
  312. properties: { dir: { type: 'string', description: '项目目录' } },
  313. required: ['dir'],
  314. },
  315. },
  316. {
  317. name: 'project_config',
  318. description:
  319. '读取或修改项目配置。省略 key 显示完整配置;只传 key 读取;key+value 修改。常用 key:build.script_dirs、build.script_files、build.output_dir、build.use_luac、flash.soc_file、flash.port。',
  320. inputSchema: {
  321. type: 'object',
  322. properties: {
  323. dir: { type: 'string', description: '项目目录' },
  324. key: { type: 'string', description: '配置键' },
  325. value: { type: 'string', description: '配置值' },
  326. },
  327. required: ['dir'],
  328. },
  329. },
  330. {
  331. name: 'project_analyze',
  332. description: '完整分析项目:Lua 语法、依赖、空间占用、分区信息。',
  333. inputSchema: {
  334. type: 'object',
  335. properties: {
  336. dir: { type: 'string', description: '项目目录' },
  337. soc: { type: 'string', description: '可选 .soc,覆盖项目配置用于分区信息' },
  338. },
  339. required: ['dir'],
  340. },
  341. },
  342. {
  343. name: 'project_prepare',
  344. description:
  345. '把 public/soc_script 扩展库下载到项目的 resource/ 目录。首次构建前调用一次;等同于界面上的“准备扩展库”。',
  346. inputSchema: {
  347. type: 'object',
  348. properties: { dir: { type: 'string', description: '项目目录' } },
  349. required: ['dir'],
  350. },
  351. },
  352. {
  353. name: 'project_build',
  354. description: '按项目配置构建脚本文件系统镜像(script.bin)。',
  355. inputSchema: {
  356. type: 'object',
  357. properties: { dir: { type: 'string', description: '项目目录' } },
  358. required: ['dir'],
  359. },
  360. },
  361. {
  362. name: 'project_export',
  363. description: '把项目导出为 .luatos 归档。',
  364. inputSchema: {
  365. type: 'object',
  366. properties: {
  367. dir: { type: 'string', description: '项目目录' },
  368. output: { type: 'string', description: '输出 .luatos 路径,默认 <项目名>.luatos' },
  369. },
  370. required: ['dir'],
  371. },
  372. },
  373. {
  374. name: 'project_deps',
  375. description: '分析项目 Lua 脚本依赖。',
  376. inputSchema: {
  377. type: 'object',
  378. properties: { dir: { type: 'string', description: '项目目录' } },
  379. required: ['dir'],
  380. },
  381. },
  382. {
  383. name: 'app_paths',
  384. description: '返回应用的默认项目目录和资源下载目录。',
  385. inputSchema: { type: 'object', properties: {}, additionalProperties: false },
  386. },
  387. ];
  388. async function callTool(name, args = {}) {
  389. switch (name) {
  390. case 'serial_list': {
  391. const response = await runJson(['serial', 'list']);
  392. return response.data ?? response;
  393. }
  394. case 'guide_models': {
  395. const response = await runJson(['guide', 'models']);
  396. return response.data ?? response;
  397. }
  398. case 'firmware_info': {
  399. if (!args.soc || !isFile(args.soc)) throw new Error('soc 文件不存在');
  400. const response = await runJson(['soc', 'info', args.soc]);
  401. return response.data ?? response;
  402. }
  403. case 'flash_firmware': {
  404. const command = flashArgs(args);
  405. const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 900_000;
  406. const result = await runJsonl(command, timeout);
  407. const { result: finalEvent } = summarizeEvents(result.events);
  408. return {
  409. ok: result.ok && result.code === 0,
  410. code: result.code,
  411. timed_out: result.timedOut,
  412. result: finalEvent,
  413. log_tail: tail(result.lines),
  414. };
  415. }
  416. case 'serial_log': {
  417. if (!args.port) throw new Error('port 不能为空');
  418. const mode = args.mode === 'binary' ? 'binary' : 'text';
  419. const duration = Math.min(60, Math.max(1, Number(args.duration_secs) || 5));
  420. const baud = args.baud || (mode === 'binary' ? 2000000 : 921600);
  421. const command = ['log', mode === 'binary' ? 'view-binary' : 'view', '--port', String(args.port), '--baud', String(baud)];
  422. if (mode === 'binary' && args.probe !== false) command.push('--probe');
  423. if (args.smart) command.push('--smart');
  424. if (args.rts_reset) command.push('--rts-reset');
  425. const result = await runJsonl(command, duration * 1000 + 2000);
  426. const logLines = [];
  427. for (const event of result.events) {
  428. if (event.type === 'log_entry') {
  429. const entry = event.entry || {};
  430. const prefix = [entry.device_time || entry.timestamp, entry.level, entry.module].filter(Boolean).join(' ');
  431. logLines.push(prefix ? `${prefix} ${entry.message || entry.line || ''}` : String(entry.message || entry.line || ''));
  432. } else if (event.type === 'message') {
  433. logLines.push(String(event.message || ''));
  434. } else if (event.type === 'diagnostic') {
  435. logLines.push(`[diagnostic] ${JSON.stringify(event.diagnostic || {})}`);
  436. } else if (event.type === 'error') {
  437. logLines.push(`[error] ${event.message || ''}`);
  438. }
  439. }
  440. if (!logLines.length) logLines.push(...result.lines);
  441. const hasEntry = result.events.some((event) => event.type === 'log_entry');
  442. const hadError = logLines.some((line) => line.startsWith('[error]'));
  443. return {
  444. // A bounded capture normally ends by killing `log view`, so a timeout is
  445. // success as long as the session did not report an error.
  446. ok: !hadError && (result.timedOut || result.ok),
  447. mode,
  448. baud,
  449. duration_secs: duration,
  450. timed_out: result.timedOut,
  451. entries: hasEntry,
  452. lines: logLines.slice(-600),
  453. };
  454. }
  455. case 'resource_list': {
  456. const command = ['resource', 'list'];
  457. if (args.module) command.push(args.module);
  458. const response = await runJson(command);
  459. return response.data ?? response;
  460. }
  461. case 'resource_download': {
  462. if (!args.category || !args.sub) throw new Error('category 和 sub 不能为空');
  463. const output = args.output || defaultResourcesDir();
  464. fs.mkdirSync(output, { recursive: true });
  465. const command = ['resource', 'download', args.category, args.sub];
  466. if (args.item) command.push(args.item);
  467. command.push('--output', output);
  468. const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 1_800_000;
  469. const result = await runJsonl(command, timeout);
  470. const { result: finalEvent } = summarizeEvents(result.events);
  471. return {
  472. ok: result.ok && result.code === 0,
  473. code: result.code,
  474. timed_out: result.timedOut,
  475. output,
  476. result: finalEvent,
  477. log_tail: tail(result.lines),
  478. };
  479. }
  480. case 'project_list': {
  481. const root = args.root || defaultProjectsDir();
  482. return { root, projects: scanProjects(root) };
  483. }
  484. case 'project_create': {
  485. if (!args.name || !args.chip) throw new Error('name 和 chip 不能为空');
  486. const root = defaultProjectsDir();
  487. const dir = args.dir || path.join(root, args.name);
  488. fs.mkdirSync(path.dirname(dir), { recursive: true });
  489. const response = await runJson(['project', 'new', args.name, '--chip', args.chip, '--dir', dir]);
  490. return response.data ?? response;
  491. }
  492. case 'project_import': {
  493. if (!args.file || !isFile(args.file)) throw new Error('导入文件不存在');
  494. const root = defaultProjectsDir();
  495. const base = path.basename(args.file, path.extname(args.file));
  496. const dir = args.dir || path.join(root, base);
  497. fs.mkdirSync(path.dirname(dir), { recursive: true });
  498. const response = await runJson(['project', 'import', args.file, '--dir', dir]);
  499. return response.data ?? response;
  500. }
  501. case 'project_info': {
  502. requireDir(args.dir);
  503. const response = await runJson(['project', 'info', '--dir', args.dir]);
  504. return response.data ?? response;
  505. }
  506. case 'project_config': {
  507. requireDir(args.dir);
  508. const command = ['project', 'config', '--dir', args.dir];
  509. if (args.key) command.push(args.key);
  510. if (args.value !== undefined && args.value !== null) command.push(String(args.value));
  511. const response = await runJson(command);
  512. return response.data ?? response;
  513. }
  514. case 'project_analyze': {
  515. requireDir(args.dir);
  516. const command = ['project', 'analyze', '--dir', args.dir];
  517. if (args.soc) command.push('--soc', args.soc);
  518. const response = await runJson(command, 600_000);
  519. return response.data ?? response;
  520. }
  521. case 'project_prepare': {
  522. requireDir(args.dir);
  523. const output = path.join(args.dir, 'resource');
  524. fs.mkdirSync(output, { recursive: true });
  525. const result = await runJsonl(
  526. ['resource', 'download', 'public', 'soc_script', '--output', output],
  527. 300_000,
  528. );
  529. const { result: finalEvent } = summarizeEvents(result.events);
  530. return {
  531. ok: result.ok && result.code === 0,
  532. code: result.code,
  533. output,
  534. result: finalEvent,
  535. log_tail: tail(result.lines, 40),
  536. };
  537. }
  538. case 'project_build': {
  539. requireDir(args.dir);
  540. const result = await runJsonl(['project', 'build', '--dir', args.dir], 600_000);
  541. const { result: finalEvent } = summarizeEvents(result.events);
  542. return {
  543. ok: result.ok && result.code === 0,
  544. code: result.code,
  545. result: finalEvent,
  546. log_tail: tail(result.lines),
  547. };
  548. }
  549. case 'project_export': {
  550. requireDir(args.dir);
  551. const output = args.output || path.join(args.dir, `${path.basename(args.dir)}.luatos`);
  552. const response = await runJson(['project', 'export', '--dir', args.dir, '-o', output], 300_000);
  553. return response.data ?? response;
  554. }
  555. case 'project_deps': {
  556. requireDir(args.dir);
  557. const response = await runJson(['project', 'deps', '--dir', args.dir]);
  558. return response.data ?? response;
  559. }
  560. case 'app_paths': {
  561. return {
  562. app_data: defaultAppDataDir(),
  563. projects: defaultProjectsDir(),
  564. resources: defaultResourcesDir(),
  565. luatos_cli: CLI,
  566. };
  567. }
  568. default:
  569. throw new Error(`未知工具:${name}`);
  570. }
  571. }
  572. function requireDir(dir) {
  573. if (!dir) throw new Error('dir 不能为空');
  574. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
  575. throw new Error(`项目目录不存在:${dir}`);
  576. }
  577. }
  578. function textContent(value) {
  579. if (typeof value === 'string') return value;
  580. return JSON.stringify(value, null, 2);
  581. }
  582. function send(payload) {
  583. process.stdout.write(`${JSON.stringify(payload)}\n`);
  584. }
  585. function sendResult(id, result) {
  586. send({ jsonrpc: '2.0', id, result });
  587. }
  588. function sendError(id, code, message) {
  589. send({ jsonrpc: '2.0', id, error: { code, message } });
  590. }
  591. async function handleRequest(request) {
  592. const { id, method, params } = request;
  593. if (method === 'initialize') {
  594. sendResult(id, {
  595. protocolVersion: PROTOCOL_VERSION,
  596. capabilities: { tools: {} },
  597. serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
  598. });
  599. return;
  600. }
  601. if (method === 'ping') {
  602. sendResult(id, {});
  603. return;
  604. }
  605. if (method === 'tools/list') {
  606. sendResult(id, { tools: TOOLS });
  607. return;
  608. }
  609. if (method === 'tools/call') {
  610. const name = params?.name;
  611. const args = params?.arguments || {};
  612. if (!name) {
  613. sendError(id, -32602, '缺少工具名称');
  614. return;
  615. }
  616. try {
  617. const value = await callTool(name, args);
  618. const failed = value && typeof value === 'object' && value.ok === false;
  619. sendResult(id, {
  620. content: [{ type: 'text', text: textContent(value) }],
  621. isError: failed,
  622. });
  623. } catch (error) {
  624. sendResult(id, {
  625. content: [{ type: 'text', text: String(error.message || error) }],
  626. isError: true,
  627. });
  628. }
  629. return;
  630. }
  631. if (method === 'resources/list') {
  632. sendResult(id, { resources: [] });
  633. return;
  634. }
  635. if (method === 'prompts/list') {
  636. sendResult(id, { prompts: [] });
  637. return;
  638. }
  639. sendError(id, -32601, `未知方法:${method}`);
  640. }
  641. const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
  642. let queue = Promise.resolve();
  643. rl.on('line', (line) => {
  644. const trimmed = line.trim();
  645. if (!trimmed) return;
  646. let request;
  647. try {
  648. request = JSON.parse(trimmed);
  649. } catch (error) {
  650. log('无法解析 JSON-RPC:', error.message);
  651. return;
  652. }
  653. // Notifications have no id and must not receive a response.
  654. if (request.id === undefined || request.id === null) {
  655. if (request.method === 'notifications/initialized') log('client initialized');
  656. return;
  657. }
  658. queue = queue
  659. .then(() => handleRequest(request))
  660. .catch((error) => {
  661. log('处理请求失败:', error);
  662. sendError(request.id, -32603, String(error.message || error));
  663. });
  664. });
  665. rl.on('close', () => {
  666. log('stdin closed, exiting');
  667. });
  668. log(`ready; cli=${CLI}; node=${process.version}`);