aura-basetools 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aura-basetools contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # aura-basetools 0.7.0
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 coding agent 用的文件读写工具。**不依赖 DSH**:纯 Node(>=18),CLI + MCP 两条入口。
4
+
5
+ ## CLI
6
+
7
+ ```bash
8
+ aura read --file src/app.ts --mode map
9
+ aura edit --file src/app.ts --hunks '[{"target":"main","replace":"…"}]'
10
+ aura --help
11
+ ```
12
+
13
+ ## MCP
14
+
15
+ ```json
16
+ { "mcpServers": { "aura": { "command": "aura", "args": ["mcp"] } } }
17
+ ```
18
+
19
+ 或 `npx -y aura-basetools mcp`。
20
+
21
+ ## DSH
22
+
23
+ DSH 用户安装适配器包:`aura-basetools-dsh`。
24
+
25
+ ## 写事务
26
+
27
+ `aura edit ... --transaction` 返回事务 id;`aura undo [--id id]` 回滚;`aura transactions` 列出。
@@ -0,0 +1,9 @@
1
+ # Third-Party Notices
2
+
3
+ 本仓主体按 **MIT** 许可分发(全文见 [`LICENSE`](./LICENSE))。
4
+
5
+ This repository is MIT-licensed (see `LICENSE`).
6
+
7
+ 当前源码中没有内联的第三方代码;`src/`、`dsh/`、`build/` 已排查。若后续引入第三方代码,按各自许可在此登记,MIT 不覆盖对应部分。
8
+
9
+ No third-party code is currently inlined in this repository; `src/`, `dsh/`, and `build/` have been checked. If third-party code is added later, it will be listed here with its own license; MIT does not cover those parts.
@@ -0,0 +1,424 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * aura MCP 服务(stdio,JSON-RPC 2.0,一行一条消息)。
4
+ *
5
+ * 为什么是它:Codex / Claude Code / Cursor / Zed 这些 agent 都吃 MCP —— 一次写壳,到处能用,
6
+ * 且**不要求对方装 DSH**(本文件只依赖 node:fs 与本包的引擎)。
7
+ *
8
+ * 暴露四个工具:
9
+ * aura_read 七种取景(map/digest/full/around/lines/search/changed)+ 版本令牌
10
+ * aura_edit 四层寻址 + expect + dry_run;逐字节写回 + 陈旧区域闸门 + 落盘后回读校验
11
+ * aura_undo 撤销最近一次/指定写事务(默认拒绝覆盖后续编辑)
12
+ * aura_transactions 列出当前工作区写事务
13
+ *
14
+ * 接法(写进各家的 MCP 配置即可):
15
+ * codex: codex mcp add aura -- npx -y aura-basetools mcp
16
+ * claude code: claude mcp add aura -- npx -y aura-basetools mcp
17
+ * cursor/zed: command = "npx", args = ["-y", "aura-basetools", "mcp"]
18
+ */
19
+ import { readFileSync } from 'node:fs'
20
+ import process from 'node:process'
21
+ import { pathToFileURL } from 'node:url'
22
+ import {
23
+ openProvider,
24
+ readEnvelope,
25
+ editEnvelope,
26
+ // 多目标(fs-contract-v2)的引擎绑定:与单目标同一处(`lib/ops.mjs`),bin 里不另找引擎。
27
+ readManyWith,
28
+ editManyEnvelope,
29
+ undoEnvelope,
30
+ transactionsEnvelope,
31
+ assertReadTargets,
32
+ assertEditTargets,
33
+ assertTargetShape,
34
+ } from '../lib/ops.mjs'
35
+
36
+ // 版本从包自己的 package.json 读:写死过一次,结果 0.4.0 的服务对外还报 0.2.1。
37
+ // 取不到(开发树里没有包清单)就报 dev,不谎报版本号。
38
+ const VERSION = (() => {
39
+ try {
40
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
41
+ } catch {
42
+ return 'dev'
43
+ }
44
+ })()
45
+ const DEFAULT_PROTOCOL = '2024-11-05'
46
+
47
+ /**
48
+ * 两个工具共用的 `targets` 声明(fs-contract-v2 §2.1/§2.2)。
49
+ *
50
+ * 一句话说清四件事:一次调用、逐项回执、输出按输入序、一个目标失败不连坐其余
51
+ * (写侧例外:先全部规划,任一规划失败 ⇒ 一个字都不写)。
52
+ * 元素内部**不在 schema 层细化**:读侧元素就是上面那套单目标参数、写侧元素就是 `{file_path, hunks}`,
53
+ * 判据由运行期那两份(`assertReadTargets` / `assertEditTargets`)给,与 DSH 壳一字不差。
54
+ */
55
+ const TARGETS_SCHEMA = {
56
+ type: 'array',
57
+ items: { type: 'object' },
58
+ description:
59
+ '一次调用读/改多个目标(与 `file_path` 互斥,最多 32 项):每个元素就是上面那套单目标参数(读:file_path/mode/lines…;写:file_path/hunks/create)。' +
60
+ '一次调用、逐项回执、输出按输入序;一个目标失败不连坐其余(写侧例外:先全部规划,任一规划失败 ⇒ 一个字都不写)。',
61
+ }
62
+
63
+ const HUNK_SCHEMA = {
64
+ type: 'object',
65
+ properties: {
66
+ target: { type: 'string', description: '符号名,如 `toTodoList` 或 `function:apply`;跳过全部文本匹配' },
67
+ lines: {
68
+ oneOf: [
69
+ { type: 'array' },
70
+ { type: 'string' },
71
+ { type: 'integer' },
72
+ { type: 'object', additionalProperties: true },
73
+ ],
74
+ description: '行号区间 [起, 止](1-based,闭区间);也接受 "4,6"、单个 4 或 {start,end}。推荐改用 start_line + end_line',
75
+ },
76
+ start_line: { type: 'integer', description: '推荐:区间起始行(1-based,闭区间)' },
77
+ end_line: { type: 'integer', description: '推荐:区间结束行(1-based,闭区间);省略则等于 start_line' },
78
+ line_cue: { type: 'string', description: '该行上唯一的词' },
79
+ anchor: { type: 'string', description: '记得的原文,容忍空白漂移与改写' },
80
+ /**
81
+ * fs-contract-v2 §5:读侧发的**区间句柄**(`aura_read` 的回执里就有,也在正文首行行尾)。
82
+ *
83
+ * 为什么要声明:句柄把「被编辑的那段字节」从模型手里拿走,换成工具自己账本里那份逐字节副本的
84
+ * 凭据;而**参数表里没有的键在这一面就等于不存在** —— CLI 读出来的回执带着柄,模型却看不见
85
+ * 这条路。这一面只做「收得下 + 原样递到引擎」两件事,判据(形状、过期、身份标签、相对定位)
86
+ * 全在引擎(`locator-lab/handle-core.mjs` + `write-path.mjs`),与 DSH 壳那三处**同一套事实**。
87
+ */
88
+ handle: {
89
+ type: 'string',
90
+ description:
91
+ '`aura_read` 发的区间句柄(不透明,如 `h9f3ac1b2e4d5:120-160`):工具读过的**逐字节区间**,于是那段文字不必由你转述。配合 `line` 或 `position` 在区间内/边界定位。句柄优先于 `old`/坐标——被让开的一方会在回执里点名。',
92
+ },
93
+ /** 段内**相对**行:整段替换与“只换其中一行”由此分开;越界是**结果**(正常 not_found 回执),不是抛错。 */
94
+ line: {
95
+ type: 'integer',
96
+ description:
97
+ '与 `handle` 同用:区间**内**第 k 行(1-based,从区间首行数起)——只换这一行,不必重述整段。越界走正常的 not_found 回执(`PATCH_HANDLE_LINE_OUT_OF_RANGE`)。单独给(没有 `handle`)不构成地址。',
98
+ },
99
+ /** 区间**边界**插入:不改动区间本身;“在这段里面”由 `line`/`old` 表达。 */
100
+ position: {
101
+ type: 'string',
102
+ enum: ['before', 'after'],
103
+ description:
104
+ '与 `handle` 同用:把替换文本插在区间**边界**(`before` / `after`)而不是替换区间本身——区间一个字节都不动。单独给(没有 `handle`)不构成地址。',
105
+ },
106
+ near: { type: 'integer', description: '歧义时的行号提示' },
107
+ expect: { type: 'string', description: '断言该处应是什么;对不上则整个补丁失败' },
108
+ replace: { type: 'string', description: '替换文本;空串 = 删除该区域' },
109
+ },
110
+ // `required` 只写 `replace`:`handle`/`line`/`position` 是**地址的可选形态**,写进必填会让
111
+ // 「按符号改一行」这类调用在参数层就被拒(与 DSH 壳那三处同一条:它们不是必填)。
112
+ required: ['replace'],
113
+ }
114
+
115
+ const TOOLS = [
116
+ {
117
+ name: 'aura_read',
118
+ description:
119
+ 'Read a file the way you actually need it. Modes: map (symbol directory), digest (interface only), full, around, lines, search, changed. `auto` picks one for you. Prefer this over reading the whole file.',
120
+ inputSchema: {
121
+ type: 'object',
122
+ properties: {
123
+ file_path: { type: 'string', description: '要读的文件路径(绝对或相对 cwd)' },
124
+ mode: {
125
+ type: 'string',
126
+ enum: ['map', 'digest', 'full', 'around', 'lines', 'search', 'changed'],
127
+ description: '省略时按你给的参数自动判断:行区间→lines、around→around、search→search、since→changed',
128
+ },
129
+ around: { type: 'string', description: 'mode=around:以该符号或短语为中心开窗' },
130
+ lines: {
131
+ oneOf: [
132
+ { type: 'array' },
133
+ { type: 'string' },
134
+ { type: 'integer' },
135
+ { type: 'object', additionalProperties: true },
136
+ ],
137
+ description: 'mode=lines:[起, 止];也接受 "412,500"、单个 412 或 {start,end}。推荐改用 start_line + end_line',
138
+ },
139
+ start_line: { type: 'integer', description: 'mode=lines(推荐):起始行,1-based,闭区间' },
140
+ end_line: { type: 'integer', description: 'mode=lines(推荐):结束行,1-based,闭区间;省略则等于 start_line' },
141
+ search: { type: 'string', description: 'mode=search:子串' },
142
+ since: { type: 'string', description: 'mode=changed:上次回执里的 version 令牌' },
143
+ max_chars: { type: 'integer' },
144
+ targets: TARGETS_SCHEMA,
145
+ },
146
+ /**
147
+ * `required` 里**不写** `file_path`:单目标(`file_path`)与多目标(`targets`)必居其一,
148
+ * 而“二选一”在 schema 层表达不了(本框架方言不支持 `anyOf`)—— 硬写必填会让多目标形状
149
+ * 在**到达服务之前**就被客户端拒掉。判据只有一处:运行期 `assertTargetShape`(两者都没给)
150
+ * 与 `assertReadTargets`(形状与互斥),与两个 DSH 壳、CLI 共用同一份。
151
+ * 与下面 `aura_edit` 里 `hunks` 不在 required 是同一条理由。
152
+ */
153
+ },
154
+ },
155
+ {
156
+ name: 'aura_edit',
157
+ description:
158
+ 'Edit or create a UTF-8 text file with hunks in one call. Address each hunk by target (symbol), lines, line_cue, or anchor. Writes back byte-for-byte (BOM and per-line endings preserved), refuses a hunk whose addressed region changed since your last read, and reads the file back to verify. All hunks must locate or nothing is written.',
159
+ inputSchema: {
160
+ type: 'object',
161
+ properties: {
162
+ file_path: { type: 'string' },
163
+ hunks: { type: 'array', items: HUNK_SCHEMA },
164
+ dry_run: { type: 'boolean', description: '只定位不落盘' },
165
+ include_transaction: { type: 'boolean', description: '在回执里返回 transaction id(默认不返回,保持输出稳定)' },
166
+ create: { type: 'string', description: '文件不存在时用它创建(整份内容)' },
167
+ targets: TARGETS_SCHEMA,
168
+ },
169
+ /**
170
+ * `hunks` **不在 required 里**:`create` 就是在建一个新文件,那时没有 hunk 可给。
171
+ *
172
+ * 旧版把它写成必填,于是客户端在**到达下面那句友好提示之前**就被 JSON Schema 拒了——
173
+ * 而 `callTool` 里那句“hunks 必须是数组(即使是空数组也要给)”本来就是为了引导这个情况。
174
+ * 同一个坑 DSH 壳早就修过(`aura-edit/index.js`:不在 schema 层声明 hunks 必选,
175
+ * 因为“schema 层表达不了‘二选一’,硬写必填会让创建功能被自己的 schema 挡住”)。
176
+ * MCP 面只是把同一件事补上:两者真正的约束是“**hunks 或 create 至少一个**”,由运行期判。
177
+ *
178
+ * `required` 里同样**不写** `file_path`:单目标(`file_path`)与多目标(`targets`)必居其一,
179
+ * 判据只有一处(运行期 `assertTargetShape` ↔ `assertEditTargets`,与 DSH 壳共用)。
180
+ */
181
+ },
182
+ },
183
+ {
184
+ name: 'aura_undo',
185
+ description:
186
+ 'Undo the latest committed write transaction, or the transaction with the given id. Refuses if a file changed after the transaction; pass force=true to override. Restores the exact bytes captured before the write.',
187
+ inputSchema: {
188
+ type: 'object',
189
+ properties: {
190
+ id: { type: 'string', description: '事务 id;省略则撤销最近一条 committed 事务' },
191
+ force: { type: 'boolean', description: '即使文件在事务后又被改过也强制恢复' },
192
+ },
193
+ },
194
+ },
195
+ {
196
+ name: 'aura_transactions',
197
+ description: 'List write transactions for the current workspace (id, status, file count, time).',
198
+ inputSchema: { type: 'object', properties: {} },
199
+ },
200
+ ]
201
+
202
+ /**
203
+ * MCP 客户端的 `arguments` 按规范是对象;实测有的客户端会把 JSON 当**字符串**传过来(模型
204
+ * 把参数写坏时尤其常见),也有传数组的。字符串能解析就用,解不了就回一条可读的结构化错误——
205
+ * 绝不能让它变成 provider 内部的 TypeError(那种不给回包,客户端会一直等到自己的超时)。
206
+ */
207
+ function toolArguments(raw) {
208
+ if (raw === undefined || raw === null) return {}
209
+ if (typeof raw === 'object' && !Array.isArray(raw)) return raw
210
+ if (typeof raw === 'string') {
211
+ try {
212
+ const parsed = JSON.parse(raw)
213
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
214
+ } catch {
215
+ /* 落到下面那条统一错误 */
216
+ }
217
+ }
218
+ return undefined
219
+ }
220
+
221
+ /**
222
+ * 多目标读(MCP 面):`targets` 在场 ⇒ 引擎的批入口 `readManyWith`。
223
+ *
224
+ * 形状判据**一条都不在这里**:`assertReadTargets`(与写侧 `assertEditTargets` 是同一个判据,
225
+ * 只是提示语不同)住在 `locator-lab/args.mjs`,两个 DSH 壳与 CLI 共用同一份。
226
+ * 它抛的是**参数面**错(`ARGS_TARGETS_SHAPE` / `ARGS_TARGETS_LIMIT` / `ARGS_SHAPE_EXCLUSIVE`),
227
+ * 这里把它接成回包 —— 这一面从不把抛出交给客户端(等不到回包就是挂死,见 `serve` 里那条兜底)。
228
+ *
229
+ * 返回值就是**引擎那份批回执**(逐项 + 汇总行 `summary`,原样 JSON):一个目标失败不连坐其余,
230
+ * 整批 `ok` = 引擎自己的 `counts.failed === 0`。
231
+ */
232
+ async function readTargetsCall(provider, args) {
233
+ let targets
234
+ try {
235
+ targets = assertReadTargets(args, { toolName: 'aura_read' })
236
+ } catch (error) {
237
+ return { ok: false, error: String(error?.message ?? error), code: typeof error?.code === 'string' ? error.code : 'BAD_ARGS' }
238
+ }
239
+ return await readManyWith(provider, targets)
240
+ }
241
+
242
+ /**
243
+ * 多目标写(MCP 面):`targets` ⇒ `editManyEnvelope`(引擎三阶段提交 + 独立面那个 `ok` 位)。
244
+ *
245
+ * `dry_run` 是这一面的旗标名(单目标那条路就是它)。元素自带 `hunks` / `create`,因此
246
+ * “hunks 或 create 至少一个”那条规则对多目标形状**不适用**。
247
+ */
248
+ async function editTargetsCall(provider, args) {
249
+ let targets
250
+ try {
251
+ targets = assertEditTargets(args, { toolName: 'aura_edit' })
252
+ } catch (error) {
253
+ return { ok: false, error: String(error?.message ?? error), code: typeof error?.code === 'string' ? error.code : 'BAD_ARGS' }
254
+ }
255
+ return await editManyEnvelope(provider, {
256
+ targets,
257
+ dryRun: args.dry_run === true,
258
+ includeTransaction: args.include_transaction === true,
259
+ })
260
+ }
261
+
262
+ /**
263
+ * 两种形状**都没给**(`file_path` 缺席或空串,且没有 `targets`)⇒ 参数面拒绝。
264
+ *
265
+ * 判据本体是引擎的 `assertTargetShape`(“必居其一”只有那一份);这里只把码换成这一面的
266
+ * `BAD_ARGS`(既有行为不变),并把**两种形状**写进错误里 —— 旧版那句只说 `file_path`,
267
+ * 于是“你其实该用 targets”这件事在回执里根本看不到。
268
+ */
269
+ function noShapeRefusal(source, toolName) {
270
+ try {
271
+ assertTargetShape(source, { toolName })
272
+ } catch (error) {
273
+ return {
274
+ ok: false,
275
+ error: `${String(error?.message ?? error)} — MCP 参数面:单目标是 \`file_path\`(非空字符串),一次多个目标是 \`targets\` 数组(每个元素就是那套单目标参数)`,
276
+ code: 'BAD_ARGS',
277
+ }
278
+ }
279
+ return undefined
280
+ }
281
+
282
+ async function callTool(provider, name, args = {}) {
283
+ // 参数名错是最常见的 agent 失误(比如把 file_path 写成 file)。
284
+ // 这里先给一句人话,不让它退化成 provider 内部的 TypeError(那个不给回包,客户端会挂死)。
285
+ // 多目标形状(fs-contract-v2 §2.1/§2.2):`targets` 在场 ⇒ 走引擎的批入口;
286
+ // 此时 `file_path` **可以缺席**(“file_path 与 targets 二者至少一个,都缺才拒”)。
287
+ const multi = args.targets !== undefined && args.targets !== null
288
+ if (name === 'aura_read') {
289
+ if (multi) return await readTargetsCall(provider, args)
290
+ const noShape = noShapeRefusal(args, 'aura_read')
291
+ if (noShape !== undefined) return noShape
292
+ // 原样透传(不再自己挑字段):行区间的宽容解析在 lib/ops.mjs → locator-lab/args.mjs 一处做,
293
+ // 三个调用面共用同一套判据。之前这里只挑了几个字段,start_line/end_line 会被默默丢掉。
294
+ return readEnvelope(provider, { ...args, file: args.file_path, maxChars: args.max_chars })
295
+ }
296
+ if (name === 'aura_edit') {
297
+ if (multi) return await editTargetsCall(provider, args)
298
+ const noShape = noShapeRefusal(args, 'aura_edit')
299
+ if (noShape !== undefined) return noShape
300
+ /**
301
+ * 真正的约束是“**hunks 或 create 至少一个**”(与 schema 的 `required` 一致)。
302
+ *
303
+ * 旧版无条件要求 hunks,于是 `create` 路径被自己的校验挡住,
304
+ * 而那句提示(“即使是空数组也要给”)本意是引导用户去写 `hunks: []`——
305
+ * 但那本来就是 workaround,不该是必需写法。三面(DSH 壳 / CLI / MCP)现在同一条规则。
306
+ * 多目标形状不走这一条:每个 target 自带 hunks/create(契约 §2.2)。
307
+ */
308
+ const creating = typeof args.create === 'string'
309
+ if (!Array.isArray(args.hunks) && !creating) {
310
+ return {
311
+ ok: false,
312
+ error: 'aura_edit 需要 hunks 数组,或 create(整份内容建文件)二选一;只建文件时直接给 create 即可',
313
+ code: 'BAD_ARGS',
314
+ }
315
+ }
316
+ return await editEnvelope(provider, {
317
+ file: args.file_path,
318
+ hunks: Array.isArray(args.hunks) ? args.hunks : [],
319
+ dryRun: args.dry_run === true,
320
+ create: creating ? args.create : undefined,
321
+ includeTransaction: args.include_transaction === true,
322
+ })
323
+ }
324
+ if (name === 'aura_undo') return await undoEnvelope(provider, { id: args.id, force: args.force === true })
325
+ if (name === 'aura_transactions') return transactionsEnvelope(provider)
326
+ return { ok: false, error: `unknown tool ${JSON.stringify(name)}`, code: 'UNKNOWN_TOOL' }
327
+ }
328
+
329
+ export async function serve() {
330
+ const provider = openProvider()
331
+ let buffer = ''
332
+ let chain = Promise.resolve()
333
+
334
+ const send = (message) => {
335
+ process.stdout.write(`${JSON.stringify(message)}\n`)
336
+ }
337
+ const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
338
+ const replyError = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } })
339
+
340
+ const handle = async (line) => {
341
+ let msg
342
+ try {
343
+ msg = JSON.parse(line)
344
+ } catch {
345
+ return replyError(null, -32700, 'Parse error')
346
+ }
347
+ const { id, method, params } = msg
348
+ const isNotification = id === undefined || id === null
349
+ try {
350
+ if (method === 'initialize') {
351
+ const asked = params?.protocolVersion
352
+ return reply(id, {
353
+ protocolVersion: typeof asked === 'string' && asked.length > 0 ? asked : DEFAULT_PROTOCOL,
354
+ capabilities: { tools: { listChanged: false } },
355
+ serverInfo: { name: 'aura-basetools', version: VERSION },
356
+ })
357
+ }
358
+ if (method === 'ping') return reply(id, {})
359
+ if (method === 'tools/list') return reply(id, { tools: TOOLS })
360
+ if (method === 'tools/call') {
361
+ let env
362
+ const callArgs = toolArguments(params?.arguments)
363
+ if (callArgs === undefined) {
364
+ return reply(id, {
365
+ content: [
366
+ {
367
+ type: 'text',
368
+ text: JSON.stringify({
369
+ ok: false,
370
+ code: 'BAD_ARGS',
371
+ error: 'arguments 必须是 JSON 对象(收到字符串或数组,且不是可解析的 JSON 对象)',
372
+ }),
373
+ },
374
+ ],
375
+ isError: true,
376
+ })
377
+ }
378
+ try {
379
+ env = await callTool(provider, params?.name, callArgs)
380
+ } catch (error) {
381
+ // 兜底:漏网的抛出也必须变成回包。不回包 = 客户端永久等待(实测过一轮:
382
+ // 参数名写错 → 只有一行 stderr,客户端挂到自己的超时为止)。
383
+ process.stderr.write(`aura-mcp: tools/call 抛出:${String(error?.stack ?? error)}\n`)
384
+ env = { ok: false, error: String(error?.message ?? error), code: error?.code ?? 'TOOL_THREW' }
385
+ }
386
+ return reply(id, {
387
+ content: [{ type: 'text', text: JSON.stringify(env) }],
388
+ isError: env.ok !== true,
389
+ })
390
+ }
391
+ if (isNotification) return undefined // 通知不回包(notifications/initialized、cancelled…)
392
+ return replyError(id, -32601, `Method not found: ${String(method)}`)
393
+ } catch (error) {
394
+ process.stderr.write(`aura-mcp: 处理抛出:${String(error?.stack ?? error)}\n`)
395
+ if (isNotification) return undefined
396
+ return replyError(id, -32603, `内部错误:${String(error?.message ?? error)}`)
397
+ }
398
+ }
399
+
400
+ process.stdin.setEncoding('utf8')
401
+ process.stdin.on('data', (chunk) => {
402
+ buffer += chunk
403
+ let index
404
+ while ((index = buffer.indexOf('\n')) >= 0) {
405
+ const line = buffer.slice(0, index).trim()
406
+ buffer = buffer.slice(index + 1)
407
+ // 单帧失败不能让服务停摆,但**绝不能吞掉**(这里原本写的是 `.catch(() => undefined)`,
408
+ // 结果 MCP 一声不响、定位花了一轮):错误写 stderr,回包给结构化错误。
409
+ chain = chain
410
+ .then(() => handle(line))
411
+ .catch((error) => {
412
+ process.stderr.write(`aura-mcp: ${String(error?.stack ?? error)}\n`)
413
+ })
414
+ }
415
+ })
416
+ await new Promise((resolve) => process.stdin.on('end', resolve))
417
+ await chain
418
+ }
419
+
420
+ // 直接运行本文件(`aura-mcp`,package.json 里声明的第二个 bin)也要起服务,与 `aura mcp` 等价。
421
+ // 用 pathToFileURL 比手拼 file:// 靠得住(Windows 盘符就是那种手拼会踩的地方)。
422
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
423
+ await serve()
424
+ }