luatos-mcp.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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: 'resource_list',
  234. description: '列出 LuatOS CDN 资源分类;传 module 可列出该分类下的子项、版本和文件。',
  235. inputSchema: {
  236. type: 'object',
  237. properties: { module: { type: 'string', description: '分类名,例如 Air8101、Air8000、public' } },
  238. },
  239. },
  240. {
  241. name: 'resource_download',
  242. description:
  243. '下载 LuatOS CDN 资源。例:category=public, sub=soc_script;或 category=Air8000, sub=V2032。会等待下载完成。',
  244. inputSchema: {
  245. type: 'object',
  246. properties: {
  247. category: { type: 'string', description: '资源大类,例如 public、Air8101' },
  248. sub: { type: 'string', description: '子项名(如 soc_script)或版本过滤(如 V2032)' },
  249. item: { type: 'string', description: '版本名或文件名过滤,可选' },
  250. output: { type: 'string', description: '下载目录,默认应用资源目录' },
  251. timeout_secs: { type: 'number', description: '超时秒数,默认 1800' },
  252. },
  253. required: ['category', 'sub'],
  254. },
  255. },
  256. {
  257. name: 'project_list',
  258. description: '扫描项目根目录,列出 LuatOS 项目(含 luatos-project.toml 的目录)。',
  259. inputSchema: {
  260. type: 'object',
  261. properties: { root: { type: 'string', description: '项目根目录,默认应用项目目录' } },
  262. },
  263. },
  264. {
  265. name: 'project_create',
  266. description: '创建新的 LuatOS 项目(非交互式)。',
  267. inputSchema: {
  268. type: 'object',
  269. properties: {
  270. name: { type: 'string', description: '项目名' },
  271. chip: { type: 'string', description: '芯片族,例如 bk72xx、air8101、air8000、air6208、ec7xx' },
  272. dir: { type: 'string', description: '项目目录,默认 <项目根>/<name>' },
  273. },
  274. required: ['name', 'chip'],
  275. },
  276. },
  277. {
  278. name: 'project_import',
  279. description: '导入 LuaTools .ini 工程或 .luatos 归档。',
  280. inputSchema: {
  281. type: 'object',
  282. properties: {
  283. file: { type: 'string', description: '.ini 或 .luatos 文件路径' },
  284. dir: { type: 'string', description: '输出目录,默认 <项目根>/<文件名>' },
  285. },
  286. required: ['file'],
  287. },
  288. },
  289. {
  290. name: 'project_info',
  291. description: '读取项目配置(芯片、版本、脚本目录、输出、flash 配置等)。',
  292. inputSchema: {
  293. type: 'object',
  294. properties: { dir: { type: 'string', description: '项目目录' } },
  295. required: ['dir'],
  296. },
  297. },
  298. {
  299. name: 'project_config',
  300. description:
  301. '读取或修改项目配置。省略 key 显示完整配置;只传 key 读取;key+value 修改。常用 key:build.script_dirs、build.script_files、build.output_dir、build.use_luac、flash.soc_file、flash.port。',
  302. inputSchema: {
  303. type: 'object',
  304. properties: {
  305. dir: { type: 'string', description: '项目目录' },
  306. key: { type: 'string', description: '配置键' },
  307. value: { type: 'string', description: '配置值' },
  308. },
  309. required: ['dir'],
  310. },
  311. },
  312. {
  313. name: 'project_analyze',
  314. description: '完整分析项目:Lua 语法、依赖、空间占用、分区信息。',
  315. inputSchema: {
  316. type: 'object',
  317. properties: {
  318. dir: { type: 'string', description: '项目目录' },
  319. soc: { type: 'string', description: '可选 .soc,覆盖项目配置用于分区信息' },
  320. },
  321. required: ['dir'],
  322. },
  323. },
  324. {
  325. name: 'project_prepare',
  326. description:
  327. '把 public/soc_script 扩展库下载到项目的 resource/ 目录。首次构建前调用一次;等同于界面上的“准备扩展库”。',
  328. inputSchema: {
  329. type: 'object',
  330. properties: { dir: { type: 'string', description: '项目目录' } },
  331. required: ['dir'],
  332. },
  333. },
  334. {
  335. name: 'project_build',
  336. description: '按项目配置构建脚本文件系统镜像(script.bin)。',
  337. inputSchema: {
  338. type: 'object',
  339. properties: { dir: { type: 'string', description: '项目目录' } },
  340. required: ['dir'],
  341. },
  342. },
  343. {
  344. name: 'project_export',
  345. description: '把项目导出为 .luatos 归档。',
  346. inputSchema: {
  347. type: 'object',
  348. properties: {
  349. dir: { type: 'string', description: '项目目录' },
  350. output: { type: 'string', description: '输出 .luatos 路径,默认 <项目名>.luatos' },
  351. },
  352. required: ['dir'],
  353. },
  354. },
  355. {
  356. name: 'project_deps',
  357. description: '分析项目 Lua 脚本依赖。',
  358. inputSchema: {
  359. type: 'object',
  360. properties: { dir: { type: 'string', description: '项目目录' } },
  361. required: ['dir'],
  362. },
  363. },
  364. {
  365. name: 'app_paths',
  366. description: '返回应用的默认项目目录和资源下载目录。',
  367. inputSchema: { type: 'object', properties: {}, additionalProperties: false },
  368. },
  369. ];
  370. async function callTool(name, args = {}) {
  371. switch (name) {
  372. case 'serial_list': {
  373. const response = await runJson(['serial', 'list']);
  374. return response.data ?? response;
  375. }
  376. case 'guide_models': {
  377. const response = await runJson(['guide', 'models']);
  378. return response.data ?? response;
  379. }
  380. case 'firmware_info': {
  381. if (!args.soc || !isFile(args.soc)) throw new Error('soc 文件不存在');
  382. const response = await runJson(['soc', 'info', args.soc]);
  383. return response.data ?? response;
  384. }
  385. case 'flash_firmware': {
  386. const command = flashArgs(args);
  387. const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 900_000;
  388. const result = await runJsonl(command, timeout);
  389. const { result: finalEvent } = summarizeEvents(result.events);
  390. return {
  391. ok: result.ok && result.code === 0,
  392. code: result.code,
  393. timed_out: result.timedOut,
  394. result: finalEvent,
  395. log_tail: tail(result.lines),
  396. };
  397. }
  398. case 'resource_list': {
  399. const command = ['resource', 'list'];
  400. if (args.module) command.push(args.module);
  401. const response = await runJson(command);
  402. return response.data ?? response;
  403. }
  404. case 'resource_download': {
  405. if (!args.category || !args.sub) throw new Error('category 和 sub 不能为空');
  406. const output = args.output || defaultResourcesDir();
  407. fs.mkdirSync(output, { recursive: true });
  408. const command = ['resource', 'download', args.category, args.sub];
  409. if (args.item) command.push(args.item);
  410. command.push('--output', output);
  411. const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 1_800_000;
  412. const result = await runJsonl(command, timeout);
  413. const { result: finalEvent } = summarizeEvents(result.events);
  414. return {
  415. ok: result.ok && result.code === 0,
  416. code: result.code,
  417. timed_out: result.timedOut,
  418. output,
  419. result: finalEvent,
  420. log_tail: tail(result.lines),
  421. };
  422. }
  423. case 'project_list': {
  424. const root = args.root || defaultProjectsDir();
  425. return { root, projects: scanProjects(root) };
  426. }
  427. case 'project_create': {
  428. if (!args.name || !args.chip) throw new Error('name 和 chip 不能为空');
  429. const root = defaultProjectsDir();
  430. const dir = args.dir || path.join(root, args.name);
  431. fs.mkdirSync(path.dirname(dir), { recursive: true });
  432. const response = await runJson(['project', 'new', args.name, '--chip', args.chip, '--dir', dir]);
  433. return response.data ?? response;
  434. }
  435. case 'project_import': {
  436. if (!args.file || !isFile(args.file)) throw new Error('导入文件不存在');
  437. const root = defaultProjectsDir();
  438. const base = path.basename(args.file, path.extname(args.file));
  439. const dir = args.dir || path.join(root, base);
  440. fs.mkdirSync(path.dirname(dir), { recursive: true });
  441. const response = await runJson(['project', 'import', args.file, '--dir', dir]);
  442. return response.data ?? response;
  443. }
  444. case 'project_info': {
  445. requireDir(args.dir);
  446. const response = await runJson(['project', 'info', '--dir', args.dir]);
  447. return response.data ?? response;
  448. }
  449. case 'project_config': {
  450. requireDir(args.dir);
  451. const command = ['project', 'config', '--dir', args.dir];
  452. if (args.key) command.push(args.key);
  453. if (args.value !== undefined && args.value !== null) command.push(String(args.value));
  454. const response = await runJson(command);
  455. return response.data ?? response;
  456. }
  457. case 'project_analyze': {
  458. requireDir(args.dir);
  459. const command = ['project', 'analyze', '--dir', args.dir];
  460. if (args.soc) command.push('--soc', args.soc);
  461. const response = await runJson(command, 600_000);
  462. return response.data ?? response;
  463. }
  464. case 'project_prepare': {
  465. requireDir(args.dir);
  466. const output = path.join(args.dir, 'resource');
  467. fs.mkdirSync(output, { recursive: true });
  468. const result = await runJsonl(
  469. ['resource', 'download', 'public', 'soc_script', '--output', output],
  470. 300_000,
  471. );
  472. const { result: finalEvent } = summarizeEvents(result.events);
  473. return {
  474. ok: result.ok && result.code === 0,
  475. code: result.code,
  476. output,
  477. result: finalEvent,
  478. log_tail: tail(result.lines, 40),
  479. };
  480. }
  481. case 'project_build': {
  482. requireDir(args.dir);
  483. const result = await runJsonl(['project', 'build', '--dir', args.dir], 600_000);
  484. const { result: finalEvent } = summarizeEvents(result.events);
  485. return {
  486. ok: result.ok && result.code === 0,
  487. code: result.code,
  488. result: finalEvent,
  489. log_tail: tail(result.lines),
  490. };
  491. }
  492. case 'project_export': {
  493. requireDir(args.dir);
  494. const output = args.output || path.join(args.dir, `${path.basename(args.dir)}.luatos`);
  495. const response = await runJson(['project', 'export', '--dir', args.dir, '-o', output], 300_000);
  496. return response.data ?? response;
  497. }
  498. case 'project_deps': {
  499. requireDir(args.dir);
  500. const response = await runJson(['project', 'deps', '--dir', args.dir]);
  501. return response.data ?? response;
  502. }
  503. case 'app_paths': {
  504. return {
  505. app_data: defaultAppDataDir(),
  506. projects: defaultProjectsDir(),
  507. resources: defaultResourcesDir(),
  508. luatos_cli: CLI,
  509. };
  510. }
  511. default:
  512. throw new Error(`未知工具:${name}`);
  513. }
  514. }
  515. function requireDir(dir) {
  516. if (!dir) throw new Error('dir 不能为空');
  517. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
  518. throw new Error(`项目目录不存在:${dir}`);
  519. }
  520. }
  521. function textContent(value) {
  522. if (typeof value === 'string') return value;
  523. return JSON.stringify(value, null, 2);
  524. }
  525. function send(payload) {
  526. process.stdout.write(`${JSON.stringify(payload)}\n`);
  527. }
  528. function sendResult(id, result) {
  529. send({ jsonrpc: '2.0', id, result });
  530. }
  531. function sendError(id, code, message) {
  532. send({ jsonrpc: '2.0', id, error: { code, message } });
  533. }
  534. async function handleRequest(request) {
  535. const { id, method, params } = request;
  536. if (method === 'initialize') {
  537. sendResult(id, {
  538. protocolVersion: PROTOCOL_VERSION,
  539. capabilities: { tools: {} },
  540. serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
  541. });
  542. return;
  543. }
  544. if (method === 'ping') {
  545. sendResult(id, {});
  546. return;
  547. }
  548. if (method === 'tools/list') {
  549. sendResult(id, { tools: TOOLS });
  550. return;
  551. }
  552. if (method === 'tools/call') {
  553. const name = params?.name;
  554. const args = params?.arguments || {};
  555. if (!name) {
  556. sendError(id, -32602, '缺少工具名称');
  557. return;
  558. }
  559. try {
  560. const value = await callTool(name, args);
  561. const failed = value && typeof value === 'object' && value.ok === false;
  562. sendResult(id, {
  563. content: [{ type: 'text', text: textContent(value) }],
  564. isError: failed,
  565. });
  566. } catch (error) {
  567. sendResult(id, {
  568. content: [{ type: 'text', text: String(error.message || error) }],
  569. isError: true,
  570. });
  571. }
  572. return;
  573. }
  574. if (method === 'resources/list') {
  575. sendResult(id, { resources: [] });
  576. return;
  577. }
  578. if (method === 'prompts/list') {
  579. sendResult(id, { prompts: [] });
  580. return;
  581. }
  582. sendError(id, -32601, `未知方法:${method}`);
  583. }
  584. const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
  585. let queue = Promise.resolve();
  586. rl.on('line', (line) => {
  587. const trimmed = line.trim();
  588. if (!trimmed) return;
  589. let request;
  590. try {
  591. request = JSON.parse(trimmed);
  592. } catch (error) {
  593. log('无法解析 JSON-RPC:', error.message);
  594. return;
  595. }
  596. // Notifications have no id and must not receive a response.
  597. if (request.id === undefined || request.id === null) {
  598. if (request.method === 'notifications/initialized') log('client initialized');
  599. return;
  600. }
  601. queue = queue
  602. .then(() => handleRequest(request))
  603. .catch((error) => {
  604. log('处理请求失败:', error);
  605. sendError(request.id, -32603, String(error.message || error));
  606. });
  607. });
  608. rl.on('close', () => {
  609. log('stdin closed, exiting');
  610. });
  611. log(`ready; cli=${CLI}; node=${process.version}`);