| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709 |
- #!/usr/bin/env node
- /**
- * LuatOS Flasher MCP server (stdio).
- *
- * This is a thin, AI-friendly wrapper around luatos-cli. It exposes serial,
- * flashing, resource-download and project-management operations as MCP tools.
- *
- * Configure it in an MCP client, for example:
- *
- * {
- * "mcpServers": {
- * "luatos": {
- * "command": "node",
- * "args": ["/Applications/LuatOS Flasher.app/Contents/Resources/mcp/luatos-mcp.mjs"],
- * "env": { "LUATOS_CLI": "/Applications/LuatOS Flasher.app/Contents/MacOS/luatos-cli" }
- * }
- * }
- * }
- *
- * stdout is reserved for JSON-RPC; diagnostics go to stderr.
- */
- import fs from 'node:fs';
- import os from 'node:os';
- import path from 'node:path';
- import readline from 'node:readline';
- import { execFile } from 'node:child_process';
- import { fileURLToPath } from 'node:url';
- const SERVER_NAME = 'luatos-mcp';
- const SERVER_VERSION = '0.1.0';
- const PROTOCOL_VERSION = '2024-11-05';
- const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
- const IS_WINDOWS = process.platform === 'win32';
- function log(...args) {
- console.error(`[${SERVER_NAME}]`, ...args);
- }
- function defaultAppDataDir() {
- if (process.platform === 'darwin') {
- return path.join(os.homedir(), 'Library', 'Application Support', 'com.luatos.flasher');
- }
- if (IS_WINDOWS) {
- return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'com.luatos.flasher');
- }
- return path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'com.luatos.flasher');
- }
- function defaultProjectsDir() {
- return path.join(defaultAppDataDir(), 'projects');
- }
- function defaultResourcesDir() {
- return path.join(defaultAppDataDir(), 'resources');
- }
- function isFile(candidate) {
- try {
- return fs.statSync(candidate).isFile();
- } catch {
- return false;
- }
- }
- function findCli() {
- const envPath = process.env.LUATOS_CLI;
- if (envPath && isFile(envPath)) return envPath;
- const exe = IS_WINDOWS ? 'luatos-cli.exe' : 'luatos-cli';
- const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
- const candidates = [
- path.join(SCRIPT_DIR, exe),
- path.join(SCRIPT_DIR, '..', exe),
- path.join(SCRIPT_DIR, '..', '..', 'MacOS', exe),
- path.join(SCRIPT_DIR, '..', '..', 'Resources', 'bin', exe),
- path.join(SCRIPT_DIR, '..', '..', 'binaries', `luatos-cli-${arch}-apple-darwin`),
- path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', IS_WINDOWS ? 'win' : 'bin', exe),
- path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', 'bin', exe),
- ];
- for (const candidate of candidates) {
- if (isFile(candidate)) return candidate;
- }
- return exe; // rely on PATH
- }
- const CLI = findCli();
- function execCli(args, timeoutMs = 300_000) {
- return new Promise((resolve) => {
- const started = Date.now();
- execFile(
- CLI,
- args,
- {
- timeout: timeoutMs,
- maxBuffer: 64 * 1024 * 1024,
- windowsHide: true,
- env: { ...process.env, NO_COLOR: '1' },
- },
- (error, stdout, stderr) => {
- const timedOut = Boolean(error && (error.killed || error.signal === 'SIGTERM'));
- resolve({
- ok: !error,
- code: error && typeof error.code === 'number' ? error.code : error ? -1 : 0,
- timedOut,
- stdout: String(stdout || ''),
- stderr: String(stderr || ''),
- elapsed_ms: Date.now() - started,
- error: error ? String(error.message || error) : null,
- });
- },
- );
- });
- }
- async function runJson(args, timeoutMs) {
- const result = await execCli(['--format', 'json', ...args], timeoutMs);
- if (result.timedOut) {
- throw new Error(`luatos-cli 超时(${Math.round(timeoutMs / 1000)}s):${args.join(' ')}`);
- }
- if (!result.ok) {
- throw new Error((result.stderr || result.stdout || result.error || `退出码 ${result.code}`).trim());
- }
- try {
- return JSON.parse(result.stdout);
- } catch (error) {
- throw new Error(`无法解析 luatos-cli JSON 输出:${error.message}\n${result.stdout.slice(0, 1200)}`);
- }
- }
- async function runJsonl(args, timeoutMs) {
- const result = await execCli(['--format', 'jsonl', ...args], timeoutMs);
- const events = [];
- const lines = [];
- for (const raw of result.stdout.split(/\r?\n/)) {
- const line = raw.trim();
- if (!line) continue;
- lines.push(line);
- if (line.startsWith('{')) {
- try {
- events.push(JSON.parse(line));
- continue;
- } catch {
- // keep as a plain line
- }
- }
- }
- for (const raw of result.stderr.split(/\r?\n/)) {
- const line = raw.trim();
- if (line) lines.push(line);
- }
- return { ...result, events, lines };
- }
- function tail(lines, count = 160) {
- return lines.slice(Math.max(0, lines.length - count)).join('\n');
- }
- function summarizeEvents(events) {
- const result = [...events].reverse().find((event) => event.type === 'result') || null;
- const progress = [...events].reverse().find((event) => event.type === 'progress') || null;
- return { result, progress };
- }
- function formatSize(bytes) {
- const value = Number(bytes) || 0;
- const units = ['B', 'KB', 'MB', 'GB'];
- let index = 0;
- let size = value;
- while (size >= 1024 && index < units.length - 1) {
- size /= 1024;
- index += 1;
- }
- return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
- }
- function scanProjects(root) {
- fs.mkdirSync(root, { recursive: true });
- const projects = [];
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
- if (!entry.isDirectory()) continue;
- const dir = path.join(root, entry.name);
- if (!isFile(path.join(dir, 'luatos-project.toml'))) continue;
- let modified = 0;
- try {
- modified = Math.floor(fs.statSync(dir).mtimeMs / 1000);
- } catch {
- // ignore
- }
- projects.push({ name: entry.name, path: dir, modified });
- }
- projects.sort((left, right) => right.modified - left.modified);
- return projects;
- }
- function flashArgs(args) {
- const soc = args.soc || args.soc_path;
- if (!soc || !isFile(soc)) throw new Error('soc 固件文件不存在');
- if (!args.port) throw new Error('port 不能为空');
- const mode = args.mode === 'script' ? 'script' : 'run';
- const command = ['flash', mode, '--soc', soc, '--port', args.port];
- if (args.script_dir) command.push('--script', args.script_dir);
- if (args.baud) command.push('--baud', String(args.baud));
- if (mode === 'run' && Number(args.tail_log_secs) > 0) {
- command.push('--tail-log-secs', String(Number(args.tail_log_secs)));
- }
- if (args.rts_reset) command.push('--rts-reset');
- return command;
- }
- const TOOLS = [
- {
- name: 'serial_list',
- description: '列出当前系统可用的串口(含 VID/PID/产品名)。',
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
- },
- {
- name: 'guide_models',
- description: '列出 luatos-cli 支持的芯片/型号及推荐命令。',
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
- },
- {
- name: 'firmware_info',
- description: '解析 .soc 固件,返回芯片、版本、分区和文件列表。',
- inputSchema: {
- type: 'object',
- properties: { soc: { type: 'string', description: '.soc 文件路径' } },
- required: ['soc'],
- },
- },
- {
- name: 'flash_firmware',
- description:
- '烧录 .soc 固件到设备。全量烧录用 mode=full;仅刷脚本区用 mode=script 并传 script_dir。该调用会等待烧录完成。',
- inputSchema: {
- type: 'object',
- properties: {
- soc: { type: 'string', description: '.soc 文件路径' },
- port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
- mode: { type: 'string', enum: ['full', 'script'], default: 'full' },
- script_dir: { type: 'string', description: '脚本目录(mode=script 时必填)' },
- baud: { type: ['string', 'number'], description: '可选烧录波特率' },
- tail_log_secs: { type: 'number', description: '烧录后继续抓日志的秒数' },
- rts_reset: { type: 'boolean', description: '烧录前发送 RTS 复位脉冲' },
- timeout_secs: { type: 'number', description: '超时秒数,默认 900' },
- },
- required: ['soc', 'port'],
- },
- },
- {
- name: 'serial_log',
- description:
- '采集一段串口日志(默认 5 秒)并返回文本。Air1601/Air1602/EC718 用 mode=binary,probe 默认开启。',
- inputSchema: {
- type: 'object',
- properties: {
- port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
- baud: { type: ['string', 'number'], description: '波特率;文本默认 921600,二进制默认 2000000' },
- mode: { type: 'string', enum: ['text', 'binary'], default: 'text' },
- duration_secs: { type: 'number', description: '采集秒数,默认 5,最大 60' },
- probe: { type: 'boolean', description: '二进制模式发送 Probe,默认 true' },
- smart: { type: 'boolean', description: '启用智能分析' },
- rts_reset: { type: 'boolean', description: '开始前发送 RTS 复位脉冲' },
- },
- required: ['port'],
- },
- },
- {
- name: 'resource_list',
- description: '列出 LuatOS CDN 资源分类;传 module 可列出该分类下的子项、版本和文件。',
- inputSchema: {
- type: 'object',
- properties: { module: { type: 'string', description: '分类名,例如 Air8101、Air8000、public' } },
- },
- },
- {
- name: 'resource_download',
- description:
- '下载 LuatOS CDN 资源。例:category=public, sub=soc_script;或 category=Air8000, sub=V2032。会等待下载完成。',
- inputSchema: {
- type: 'object',
- properties: {
- category: { type: 'string', description: '资源大类,例如 public、Air8101' },
- sub: { type: 'string', description: '子项名(如 soc_script)或版本过滤(如 V2032)' },
- item: { type: 'string', description: '版本名或文件名过滤,可选' },
- output: { type: 'string', description: '下载目录,默认应用资源目录' },
- timeout_secs: { type: 'number', description: '超时秒数,默认 1800' },
- },
- required: ['category', 'sub'],
- },
- },
- {
- name: 'project_list',
- description: '扫描项目根目录,列出 LuatOS 项目(含 luatos-project.toml 的目录)。',
- inputSchema: {
- type: 'object',
- properties: { root: { type: 'string', description: '项目根目录,默认应用项目目录' } },
- },
- },
- {
- name: 'project_create',
- description: '创建新的 LuatOS 项目(非交互式)。',
- inputSchema: {
- type: 'object',
- properties: {
- name: { type: 'string', description: '项目名' },
- chip: { type: 'string', description: '芯片族,例如 bk72xx、air8101、air8000、air6208、ec7xx' },
- dir: { type: 'string', description: '项目目录,默认 <项目根>/<name>' },
- },
- required: ['name', 'chip'],
- },
- },
- {
- name: 'project_import',
- description: '导入 LuaTools .ini 工程或 .luatos 归档。',
- inputSchema: {
- type: 'object',
- properties: {
- file: { type: 'string', description: '.ini 或 .luatos 文件路径' },
- dir: { type: 'string', description: '输出目录,默认 <项目根>/<文件名>' },
- },
- required: ['file'],
- },
- },
- {
- name: 'project_info',
- description: '读取项目配置(芯片、版本、脚本目录、输出、flash 配置等)。',
- inputSchema: {
- type: 'object',
- properties: { dir: { type: 'string', description: '项目目录' } },
- required: ['dir'],
- },
- },
- {
- name: 'project_config',
- description:
- '读取或修改项目配置。省略 key 显示完整配置;只传 key 读取;key+value 修改。常用 key:build.script_dirs、build.script_files、build.output_dir、build.use_luac、flash.soc_file、flash.port。',
- inputSchema: {
- type: 'object',
- properties: {
- dir: { type: 'string', description: '项目目录' },
- key: { type: 'string', description: '配置键' },
- value: { type: 'string', description: '配置值' },
- },
- required: ['dir'],
- },
- },
- {
- name: 'project_analyze',
- description: '完整分析项目:Lua 语法、依赖、空间占用、分区信息。',
- inputSchema: {
- type: 'object',
- properties: {
- dir: { type: 'string', description: '项目目录' },
- soc: { type: 'string', description: '可选 .soc,覆盖项目配置用于分区信息' },
- },
- required: ['dir'],
- },
- },
- {
- name: 'project_prepare',
- description:
- '把 public/soc_script 扩展库下载到项目的 resource/ 目录。首次构建前调用一次;等同于界面上的“准备扩展库”。',
- inputSchema: {
- type: 'object',
- properties: { dir: { type: 'string', description: '项目目录' } },
- required: ['dir'],
- },
- },
- {
- name: 'project_build',
- description: '按项目配置构建脚本文件系统镜像(script.bin)。',
- inputSchema: {
- type: 'object',
- properties: { dir: { type: 'string', description: '项目目录' } },
- required: ['dir'],
- },
- },
- {
- name: 'project_export',
- description: '把项目导出为 .luatos 归档。',
- inputSchema: {
- type: 'object',
- properties: {
- dir: { type: 'string', description: '项目目录' },
- output: { type: 'string', description: '输出 .luatos 路径,默认 <项目名>.luatos' },
- },
- required: ['dir'],
- },
- },
- {
- name: 'project_deps',
- description: '分析项目 Lua 脚本依赖。',
- inputSchema: {
- type: 'object',
- properties: { dir: { type: 'string', description: '项目目录' } },
- required: ['dir'],
- },
- },
- {
- name: 'app_paths',
- description: '返回应用的默认项目目录和资源下载目录。',
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
- },
- ];
- async function callTool(name, args = {}) {
- switch (name) {
- case 'serial_list': {
- const response = await runJson(['serial', 'list']);
- return response.data ?? response;
- }
- case 'guide_models': {
- const response = await runJson(['guide', 'models']);
- return response.data ?? response;
- }
- case 'firmware_info': {
- if (!args.soc || !isFile(args.soc)) throw new Error('soc 文件不存在');
- const response = await runJson(['soc', 'info', args.soc]);
- return response.data ?? response;
- }
- case 'flash_firmware': {
- const command = flashArgs(args);
- const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 900_000;
- const result = await runJsonl(command, timeout);
- const { result: finalEvent } = summarizeEvents(result.events);
- return {
- ok: result.ok && result.code === 0,
- code: result.code,
- timed_out: result.timedOut,
- result: finalEvent,
- log_tail: tail(result.lines),
- };
- }
- case 'serial_log': {
- if (!args.port) throw new Error('port 不能为空');
- const mode = args.mode === 'binary' ? 'binary' : 'text';
- const duration = Math.min(60, Math.max(1, Number(args.duration_secs) || 5));
- const baud = args.baud || (mode === 'binary' ? 2000000 : 921600);
- const command = ['log', mode === 'binary' ? 'view-binary' : 'view', '--port', String(args.port), '--baud', String(baud)];
- if (mode === 'binary' && args.probe !== false) command.push('--probe');
- if (args.smart) command.push('--smart');
- if (args.rts_reset) command.push('--rts-reset');
- const result = await runJsonl(command, duration * 1000 + 2000);
- const logLines = [];
- for (const event of result.events) {
- if (event.type === 'log_entry') {
- const entry = event.entry || {};
- const prefix = [entry.device_time || entry.timestamp, entry.level, entry.module].filter(Boolean).join(' ');
- logLines.push(prefix ? `${prefix} ${entry.message || entry.line || ''}` : String(entry.message || entry.line || ''));
- } else if (event.type === 'message') {
- logLines.push(String(event.message || ''));
- } else if (event.type === 'diagnostic') {
- logLines.push(`[diagnostic] ${JSON.stringify(event.diagnostic || {})}`);
- } else if (event.type === 'error') {
- logLines.push(`[error] ${event.message || ''}`);
- }
- }
- if (!logLines.length) logLines.push(...result.lines);
- const hasEntry = result.events.some((event) => event.type === 'log_entry');
- const hadError = logLines.some((line) => line.startsWith('[error]'));
- return {
- // A bounded capture normally ends by killing `log view`, so a timeout is
- // success as long as the session did not report an error.
- ok: !hadError && (result.timedOut || result.ok),
- mode,
- baud,
- duration_secs: duration,
- timed_out: result.timedOut,
- entries: hasEntry,
- lines: logLines.slice(-600),
- };
- }
- case 'resource_list': {
- const command = ['resource', 'list'];
- if (args.module) command.push(args.module);
- const response = await runJson(command);
- return response.data ?? response;
- }
- case 'resource_download': {
- if (!args.category || !args.sub) throw new Error('category 和 sub 不能为空');
- const output = args.output || defaultResourcesDir();
- fs.mkdirSync(output, { recursive: true });
- const command = ['resource', 'download', args.category, args.sub];
- if (args.item) command.push(args.item);
- command.push('--output', output);
- const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 1_800_000;
- const result = await runJsonl(command, timeout);
- const { result: finalEvent } = summarizeEvents(result.events);
- return {
- ok: result.ok && result.code === 0,
- code: result.code,
- timed_out: result.timedOut,
- output,
- result: finalEvent,
- log_tail: tail(result.lines),
- };
- }
- case 'project_list': {
- const root = args.root || defaultProjectsDir();
- return { root, projects: scanProjects(root) };
- }
- case 'project_create': {
- if (!args.name || !args.chip) throw new Error('name 和 chip 不能为空');
- const root = defaultProjectsDir();
- const dir = args.dir || path.join(root, args.name);
- fs.mkdirSync(path.dirname(dir), { recursive: true });
- const response = await runJson(['project', 'new', args.name, '--chip', args.chip, '--dir', dir]);
- return response.data ?? response;
- }
- case 'project_import': {
- if (!args.file || !isFile(args.file)) throw new Error('导入文件不存在');
- const root = defaultProjectsDir();
- const base = path.basename(args.file, path.extname(args.file));
- const dir = args.dir || path.join(root, base);
- fs.mkdirSync(path.dirname(dir), { recursive: true });
- const response = await runJson(['project', 'import', args.file, '--dir', dir]);
- return response.data ?? response;
- }
- case 'project_info': {
- requireDir(args.dir);
- const response = await runJson(['project', 'info', '--dir', args.dir]);
- return response.data ?? response;
- }
- case 'project_config': {
- requireDir(args.dir);
- const command = ['project', 'config', '--dir', args.dir];
- if (args.key) command.push(args.key);
- if (args.value !== undefined && args.value !== null) command.push(String(args.value));
- const response = await runJson(command);
- return response.data ?? response;
- }
- case 'project_analyze': {
- requireDir(args.dir);
- const command = ['project', 'analyze', '--dir', args.dir];
- if (args.soc) command.push('--soc', args.soc);
- const response = await runJson(command, 600_000);
- return response.data ?? response;
- }
- case 'project_prepare': {
- requireDir(args.dir);
- const output = path.join(args.dir, 'resource');
- fs.mkdirSync(output, { recursive: true });
- const result = await runJsonl(
- ['resource', 'download', 'public', 'soc_script', '--output', output],
- 300_000,
- );
- const { result: finalEvent } = summarizeEvents(result.events);
- return {
- ok: result.ok && result.code === 0,
- code: result.code,
- output,
- result: finalEvent,
- log_tail: tail(result.lines, 40),
- };
- }
- case 'project_build': {
- requireDir(args.dir);
- const result = await runJsonl(['project', 'build', '--dir', args.dir], 600_000);
- const { result: finalEvent } = summarizeEvents(result.events);
- return {
- ok: result.ok && result.code === 0,
- code: result.code,
- result: finalEvent,
- log_tail: tail(result.lines),
- };
- }
- case 'project_export': {
- requireDir(args.dir);
- const output = args.output || path.join(args.dir, `${path.basename(args.dir)}.luatos`);
- const response = await runJson(['project', 'export', '--dir', args.dir, '-o', output], 300_000);
- return response.data ?? response;
- }
- case 'project_deps': {
- requireDir(args.dir);
- const response = await runJson(['project', 'deps', '--dir', args.dir]);
- return response.data ?? response;
- }
- case 'app_paths': {
- return {
- app_data: defaultAppDataDir(),
- projects: defaultProjectsDir(),
- resources: defaultResourcesDir(),
- luatos_cli: CLI,
- };
- }
- default:
- throw new Error(`未知工具:${name}`);
- }
- }
- function requireDir(dir) {
- if (!dir) throw new Error('dir 不能为空');
- if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
- throw new Error(`项目目录不存在:${dir}`);
- }
- }
- function textContent(value) {
- if (typeof value === 'string') return value;
- return JSON.stringify(value, null, 2);
- }
- function send(payload) {
- process.stdout.write(`${JSON.stringify(payload)}\n`);
- }
- function sendResult(id, result) {
- send({ jsonrpc: '2.0', id, result });
- }
- function sendError(id, code, message) {
- send({ jsonrpc: '2.0', id, error: { code, message } });
- }
- async function handleRequest(request) {
- const { id, method, params } = request;
- if (method === 'initialize') {
- sendResult(id, {
- protocolVersion: PROTOCOL_VERSION,
- capabilities: { tools: {} },
- serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
- });
- return;
- }
- if (method === 'ping') {
- sendResult(id, {});
- return;
- }
- if (method === 'tools/list') {
- sendResult(id, { tools: TOOLS });
- return;
- }
- if (method === 'tools/call') {
- const name = params?.name;
- const args = params?.arguments || {};
- if (!name) {
- sendError(id, -32602, '缺少工具名称');
- return;
- }
- try {
- const value = await callTool(name, args);
- const failed = value && typeof value === 'object' && value.ok === false;
- sendResult(id, {
- content: [{ type: 'text', text: textContent(value) }],
- isError: failed,
- });
- } catch (error) {
- sendResult(id, {
- content: [{ type: 'text', text: String(error.message || error) }],
- isError: true,
- });
- }
- return;
- }
- if (method === 'resources/list') {
- sendResult(id, { resources: [] });
- return;
- }
- if (method === 'prompts/list') {
- sendResult(id, { prompts: [] });
- return;
- }
- sendError(id, -32601, `未知方法:${method}`);
- }
- const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
- let queue = Promise.resolve();
- rl.on('line', (line) => {
- const trimmed = line.trim();
- if (!trimmed) return;
- let request;
- try {
- request = JSON.parse(trimmed);
- } catch (error) {
- log('无法解析 JSON-RPC:', error.message);
- return;
- }
- // Notifications have no id and must not receive a response.
- if (request.id === undefined || request.id === null) {
- if (request.method === 'notifications/initialized') log('client initialized');
- return;
- }
- queue = queue
- .then(() => handleRequest(request))
- .catch((error) => {
- log('处理请求失败:', error);
- sendError(request.id, -32603, String(error.message || error));
- });
- });
- rl.on('close', () => {
- log('stdin closed, exiting');
- });
- log(`ready; cli=${CLI}; node=${process.version}`);
|