@hop-top/kit 0.5.0-alpha.7 → 0.5.0-alpha.9

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/alias-D9_qFlyP.d.ts +174 -0
  3. package/dist/alias.d.ts +1 -1
  4. package/dist/alias.js +8 -2
  5. package/dist/{chunk-263IZ6Z6.js → chunk-B4ULGCCN.js} +43 -154
  6. package/dist/{chunk-DIDN4X5C.js → chunk-BLS2OBIQ.js} +99 -20
  7. package/dist/{chunk-JTMPNXVQ.js → chunk-P6GRX4RV.js} +486 -83
  8. package/dist/chunk-UZ65A27P.js +147 -0
  9. package/dist/{completion-sDKVXPUL.d.ts → completion-csVun6SP.d.ts} +4 -1
  10. package/dist/completion.d.ts +1 -1
  11. package/dist/{index-B-pqGHhU.d.ts → index-CaOXdl38.d.ts} +337 -24
  12. package/dist/index.d.ts +4 -4
  13. package/dist/index.js +5 -4
  14. package/dist/mcp/index.d.ts +2 -1
  15. package/dist/mcp/index.js +31 -2
  16. package/dist/{toolspec-UrWnoJ3Y.d.ts → toolspec-96rkLfsh.d.ts} +7 -2
  17. package/dist/toolspec.d.ts +1 -1
  18. package/dist/toolspec.js +3 -2
  19. package/package.json +1 -1
  20. package/src/alias.conformance.test.ts +250 -0
  21. package/src/alias.test.ts +96 -1
  22. package/src/alias.ts +179 -19
  23. package/src/completion.ts +4 -1
  24. package/src/mcp/README.md +6 -0
  25. package/src/mcp/args-separator.test.ts +164 -0
  26. package/src/mcp/args.test.ts +223 -0
  27. package/src/mcp/args.ts +160 -0
  28. package/src/mcp/audit.test.ts +520 -0
  29. package/src/mcp/audit.ts +70 -0
  30. package/src/mcp/bridge.test.ts +72 -0
  31. package/src/mcp/bridge.ts +50 -5
  32. package/src/mcp/conformance.test.ts +1 -1
  33. package/src/mcp/dispatch.ts +48 -2
  34. package/src/mcp/index.ts +33 -1
  35. package/src/mcp/legacy-notify.test.ts +59 -0
  36. package/src/mcp/legacy.ts +55 -15
  37. package/src/mcp/modern-confirm.ts +42 -10
  38. package/src/mcp/modern.ts +99 -35
  39. package/src/mcp/stdio.test.ts +313 -0
  40. package/src/mcp/stdio.ts +254 -0
  41. package/src/mcp/toolname.test.ts +147 -0
  42. package/src/mcp/types.ts +125 -18
  43. package/src/toolspec-internal.ts +24 -0
  44. package/src/toolspec-manifest.test.ts +25 -0
  45. package/src/toolspec-manifest.ts +5 -1
  46. package/src/toolspec.from-command.test.ts +51 -0
  47. package/src/toolspec.ts +29 -15
  48. package/dist/alias-BsJ2jGqQ.d.ts +0 -96
package/src/alias.ts CHANGED
@@ -186,18 +186,117 @@ export class Expander {
186
186
  return [result, true];
187
187
  }
188
188
 
189
- /** Reject names that shadow builtins or contain whitespace. */
189
+ /**
190
+ * Reject names that shadow builtins or contain whitespace; see
191
+ * {@link validateAliasName}, which needs no config files.
192
+ */
190
193
  validateName(name: string): void {
191
- if (name === '') {
192
- throw new Error('alias name must not be empty');
193
- }
194
- if (/\s/.test(name)) {
195
- throw new Error('alias name must not contain whitespace');
194
+ validateAliasName(name, { builtins: this.cfg.builtins });
195
+ }
196
+ }
197
+
198
+ // ── Standalone validation and cycle detection ───────────────
199
+
200
+ /** The rule an alias name failed; see {@link validateAliasName}. */
201
+ export type AliasNameErrorKind = 'empty' | 'whitespace' | 'builtin' | 'duplicate';
202
+
203
+ /** An alias name {@link validateAliasName} refused. */
204
+ export class AliasNameError extends Error {
205
+ readonly kind: AliasNameErrorKind;
206
+ readonly alias: string;
207
+ /** The existing alias's target, for `duplicate`. */
208
+ readonly target?: string;
209
+
210
+ constructor(kind: AliasNameErrorKind, alias: string, target?: string) {
211
+ super(aliasNameMessage(kind, alias, target));
212
+ this.name = 'AliasNameError';
213
+ this.kind = kind;
214
+ this.alias = alias;
215
+ this.target = target;
216
+ }
217
+ }
218
+
219
+ function aliasNameMessage(
220
+ kind: AliasNameErrorKind, alias: string, target?: string,
221
+ ): string {
222
+ switch (kind) {
223
+ case 'empty': return 'alias name must not be empty';
224
+ case 'whitespace': return 'alias name must not contain whitespace';
225
+ case 'builtin': return `alias "${alias}" conflicts with a built-in command`;
226
+ case 'duplicate':
227
+ return `alias "${alias}" is already registered for "${target ?? ''}"`;
228
+ }
229
+ }
230
+
231
+ /** What {@link validateAliasName} checks a name against. */
232
+ export interface AliasNameRules {
233
+ /** Names an alias must not take: the tool's commands and reserved words. */
234
+ builtins?: Iterable<string>;
235
+ /** The alias map the name would join. */
236
+ existing?: AliasMap;
237
+ }
238
+
239
+ const WHITE_SPACE = /\p{White_Space}/u;
240
+
241
+ /**
242
+ * Check an alias name without a store, config file or command tree.
243
+ * Rules run in order and the first failure throws an
244
+ * {@link AliasNameError}: empty, whitespace (any Unicode White_Space
245
+ * character), builtin, duplicate.
246
+ */
247
+ export function validateAliasName(name: string, rules: AliasNameRules = {}): void {
248
+ if (name === '') throw new AliasNameError('empty', name);
249
+ if (WHITE_SPACE.test(name)) throw new AliasNameError('whitespace', name);
250
+ if (rules.builtins) {
251
+ for (const b of rules.builtins) {
252
+ if (b === name) throw new AliasNameError('builtin', name);
196
253
  }
197
- if (this.cfg.builtins?.has(name)) {
198
- throw new Error(`alias "${name}" conflicts with a built-in command`);
254
+ }
255
+ const existing = rules.existing;
256
+ if (existing && Object.prototype.hasOwnProperty.call(existing, name)) {
257
+ throw new AliasNameError('duplicate', name, existing[name]);
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Report alias cycles in `aliases` (name -> target). An alias points at
263
+ * another when the first word of its target is a key of the map. Each
264
+ * cycle is a path starting at its smallest name and ending with it
265
+ * again (`['a', 'b', 'a']`); cycles are sorted by first name. An alias
266
+ * that only leads into a cycle is not part of one.
267
+ */
268
+ export function detectCycles(aliases: AliasMap): string[][] {
269
+ const has = (n: string) => Object.prototype.hasOwnProperty.call(aliases, n);
270
+ const next = (n: string): string | undefined => {
271
+ const first = aliases[n].trim().split(/\s+/)[0];
272
+ return first !== '' && has(first) ? first : undefined;
273
+ };
274
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
275
+
276
+ const done = new Set<string>();
277
+ const cycles: string[][] = [];
278
+ for (const start of Object.keys(aliases).sort(cmp)) {
279
+ if (done.has(start)) continue;
280
+ const pos = new Map<string, number>();
281
+ const walk: string[] = [];
282
+ let cur: string | undefined = start;
283
+ while (cur !== undefined && !done.has(cur)) {
284
+ const at = pos.get(cur);
285
+ if (at !== undefined) {
286
+ const members = walk.slice(at);
287
+ let min = 0;
288
+ members.forEach((m, i) => { if (m < members[min]) min = i; });
289
+ const path = [...members.slice(min), ...members.slice(0, min)];
290
+ cycles.push([...path, path[0]]);
291
+ break;
292
+ }
293
+ pos.set(cur, walk.length);
294
+ walk.push(cur);
295
+ cur = next(cur);
199
296
  }
297
+ for (const n of walk) done.add(n);
200
298
  }
299
+ return cycles.sort((a, b) => cmp(a[0], b[0]));
201
300
  }
202
301
 
203
302
  // ── Commander bridge ────────────────────────────────────────
@@ -221,13 +320,57 @@ type Dispatcher = {
221
320
  _parseCommand(operands: string[], unknown: string[]): void | Promise<void>;
222
321
  };
223
322
 
323
+ /** Runs an alias proxy in place of its target; `cmd.args` holds every argument after the alias, unparsed. */
324
+ export type AliasDispatch = (
325
+ name: string, target: string, cmd: Command,
326
+ ) => void | Promise<void>;
327
+
328
+ /**
329
+ * Options for {@link bridgeAliases}. Setting any of them registers every
330
+ * alias as a proxy, a root command named after the alias, even for a
331
+ * single-word target that would otherwise take a Commander alias.
332
+ */
333
+ export interface BridgeOptions {
334
+ /** Hide proxies from help. Default true. */
335
+ hidden?: boolean;
336
+ /** A proxy's description, in place of `Alias for <target>`. */
337
+ describe?: (name: string, target: string) => string;
338
+ /**
339
+ * true: the proxy owns -h/--help and shows its own help. false (the
340
+ * default): --help reaches the target, or the dispatch handler.
341
+ */
342
+ helpOption?: boolean;
343
+ /**
344
+ * A handler run instead of the target, or false to register proxies
345
+ * that run nothing (register-only). Default: dispatch the target
346
+ * through the program, like a native subcommand.
347
+ */
348
+ dispatch?: AliasDispatch | false;
349
+ }
350
+
351
+ function hasBridgeOptions(opts?: BridgeOptions): opts is BridgeOptions {
352
+ return opts !== undefined &&
353
+ Object.values(opts).some(v => v !== undefined);
354
+ }
355
+
224
356
  /**
225
357
  * Register loaded aliases with Commander's native .alias() API.
226
358
  *
227
359
  * Simple single-command aliases use Commander's built-in .alias(),
228
360
  * giving free completion and help display. Multi-word or unresolved
229
361
  * targets get a hidden proxy command that dispatches the expanded
230
- * args from the program, like a native subcommand.
362
+ * args from the program, like a native subcommand. With any
363
+ * {@link BridgeOptions} set, every alias gets a proxy shaped by them.
364
+ *
365
+ * Completion offers each alias at most once. A native alias, or a hidden
366
+ * proxy that dispatches its target or runs nothing, is a stand-in:
367
+ * completion lists it as `alias for <target>` and offers a proxy only
368
+ * its help flag. A visible proxy, or one with a dispatch handler, is a
369
+ * real command and completes like any subcommand, with its own flags,
370
+ * including any added after bridging; a hidden one is not listed.
371
+ *
372
+ * `source` is an {@link AliasStore} or a plain alias map, so aliases
373
+ * can come from any storage.
231
374
  *
232
375
  * Dispatch reuses Commander's own subcommand dispatch rather than
233
376
  * calling parse()/parseAsync() again: re-parsing resets program
@@ -238,14 +381,24 @@ type Dispatcher = {
238
381
  */
239
382
  export function bridgeAliases(
240
383
  program: Command,
241
- store: AliasStore,
384
+ source: AliasStore | AliasMap,
385
+ opts?: BridgeOptions,
242
386
  ): void {
243
- const all = store.all();
387
+ const all = typeof (source as AliasStore).all === 'function'
388
+ ? (source as AliasStore).all()
389
+ : { ...(source as AliasMap) };
390
+ const proxyAll = hasBridgeOptions(opts);
391
+ // A visible or custom-dispatch proxy is a real command: completion
392
+ // offers it among the subcommands and walks it for its own flags. A
393
+ // root-alias entry would list it twice and complete it as a flagless
394
+ // stand-in.
395
+ const realProxy = proxyAll &&
396
+ (opts.hidden === false || typeof opts.dispatch === 'function');
244
397
  for (const [name, target] of Object.entries(all)) {
245
- registerRootAlias(program, name, target);
398
+ if (!realProxy) registerRootAlias(program, name, target);
246
399
  const parts = target.split(/\s+/);
247
400
  // simple alias: single word target that exists as a direct subcommand
248
- if (parts.length === 1) {
401
+ if (!proxyAll && parts.length === 1) {
249
402
  const targetCmd = findCommand(program, target);
250
403
  if (targetCmd) {
251
404
  targetCmd.alias(name);
@@ -253,19 +406,26 @@ export function bridgeAliases(
253
406
  }
254
407
  }
255
408
 
256
- // multi-word target or unknown command: hidden proxy
257
- const proxy = new Command(name)
258
- .description(`Alias for ${target}`)
409
+ // multi-word target, unknown command or options: proxy
410
+ const dispatch = opts?.dispatch;
411
+ const proxy = new Command(name);
412
+ // An options proxy behaves like a subcommand made with
413
+ // program.command(): it inherits exitOverride, output and help
414
+ // settings, which matter once it renders its own help.
415
+ if (proxyAll) proxy.copyInheritedSettings(program);
416
+ proxy
417
+ .description(opts?.describe?.(name, target) ?? `Alias for ${target}`)
259
418
  .allowUnknownOption(true)
260
419
  .allowExcessArguments(true)
261
420
  .action(function (this: Command) {
421
+ if (dispatch === false) return undefined;
422
+ if (dispatch) return dispatch(name, target, this);
262
423
  const expanded = target.split(/\s+/);
263
424
  return (program as unknown as Dispatcher)._parseCommand(
264
425
  [], [...expanded, ...this.args],
265
426
  );
266
427
  });
267
- proxy.helpOption(false);
268
- (proxy as any)._hidden = true;
269
- program.addCommand(proxy);
428
+ if (opts?.helpOption !== true) proxy.helpOption(false);
429
+ program.addCommand(proxy, { hidden: opts?.hidden ?? true });
270
430
  }
271
431
  }
package/src/completion.ts CHANGED
@@ -254,7 +254,10 @@ export function bindArgs(cmd: Command, completer: Completer): void {
254
254
  /**
255
255
  * Records `name` as a root-level alias of the command at `target` (a
256
256
  * space-separated path), so root argument completion offers it as
257
- * `name<TAB>alias for <target>`. `bridgeAliases` calls this.
257
+ * `name<TAB>alias for <target>`, and a root subcommand named `name`
258
+ * completes as a flagless stand-in. `bridgeAliases` calls this for
259
+ * every alias but a visible or custom-dispatch proxy, which completes
260
+ * as an ordinary subcommand.
258
261
  */
259
262
  export function registerRootAlias(root: Command, name: string, target: string): void {
260
263
  const t = root as Tagged;
package/src/mcp/README.md CHANGED
@@ -8,8 +8,11 @@ How a Commander command tree is served over the Model Context Protocol from one
8
8
 
9
9
  - expose leaves as MCP tools: `commanderBridge(root, { run })` then `createMcpHandler(bridge, opts)`
10
10
  - bind to your own HTTP stack: the handler is `(McpHttpRequest) => Promise<McpHttpResponse>`; node:http, hono, express, fastify or a Worker is your call
11
+ - serve a host that spawns the tool: `serveStdio(bridge)` (or `serveStdio(handler)`), newline-delimited JSON-RPC on stdin/stdout, `done` resolves when stdin ends
11
12
  - gate destructive tools: `policy` option, `defaultPolicy()` blocks remote destructive calls
12
13
  - require confirmation on the modern era: `headerConfirmationGate` or `ElicitationConfirmGate`
14
+ - name tools for a host that refuses dots (`widget_add`, not `widget.add`): `toolNameSeparator: '_'`
15
+ - record every refusal the mount makes (auth, confirmation, destructive ceiling): `audit: (record: McpAuditRecord) => void`
13
16
 
14
17
  ## Quick start
15
18
 
@@ -38,9 +41,12 @@ console.log(res.status, res.body);
38
41
  - Wire bytes are pinned by [`sdk/tests/cross-lang/fixtures/mcp-wire.json`](../../../tests/cross-lang/fixtures/mcp-wire.json), compared as raw bytes; [`conformance.test.ts`](conformance.test.ts) replays both `cases` and `sequences`.
39
42
  - Protocol layer is `@modelcontextprotocol/core` + `@modelcontextprotocol/server` (v2). The v1 `@modelcontextprotocol/sdk` cannot serve `2026-07-28` and is not a dependency.
40
43
  - Era detection follows the marker set and precedence chain in [`dispatch.ts`](dispatch.ts), not the SDK's own classifier.
44
+ - stdio ([`stdio.ts`](stdio.ts)) drives the same era dispatch with no header layer: the `2026-07-28` header checks are skipped, notifications are never answered, batches are refused.
41
45
  - `tools/list` re-reads the bridge's leaves per request; caching the leaf set fails the sequence fixture.
42
46
  - `commanderBridge` requires `run`: kit does not capture a command's output for you.
47
+ - Tool names join the leaf path with `toolNameSeparator` (default `.`) and split back on it. The mount throws on an empty separator and, for any other than `.`, on a command name containing it (`data_sync` under `_`). Names are not otherwise rewritten or length-checked.
43
48
  - Tasks extension: `TASKS_SUPPORTED` is `false`; `discoverCapabilities` reports it.
49
+ - `audit` ([`audit.ts`](audit.ts)) is the port of Go's bridge sinks for this surface: called after a refusal is decided and before the response is written, never changing the wire bytes; a throw is swallowed. `error` is Go's sentinel string (`MCP_AUDIT_*`).
44
50
  - Parity: [`contracts/parity/README.md`](../../../../contracts/parity/README.md), section "MCP wire contract".
45
51
 
46
52
  ## Neighbours
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Positional arguments under a non-default toolNameSeparator, on both
3
+ * eras over HTTP and over serveStdio: the separator only renames the
4
+ * tool, the "args" array still reaches Invocation.args in order.
5
+ */
6
+
7
+ import { PassThrough } from 'node:stream';
8
+ import { Command } from 'commander';
9
+ import { describe, expect, it } from 'vitest';
10
+
11
+ import { commanderBridge } from './bridge.js';
12
+ import { createMcpHandler } from './dispatch.js';
13
+ import { serveStdio } from './stdio.js';
14
+ import type { Invocation, InvokeResult, McpBridge } from './types.js';
15
+
16
+ const MODERN_META = {
17
+ 'io.modelcontextprotocol/clientCapabilities': {},
18
+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
19
+ };
20
+
21
+ /** root -> item -> add <name> [note] --count <n> */
22
+ function bridge(): McpBridge {
23
+ const root = new Command('root');
24
+ root
25
+ .command('item')
26
+ .command('add')
27
+ .description('Add an item')
28
+ .argument('<name>')
29
+ .argument('[note]')
30
+ .option('--count <n>', 'how many');
31
+ const run = (inv: Invocation): InvokeResult => ({
32
+ stdout: `${inv.path.join(' ')} ${JSON.stringify(inv.args ?? [])} ${JSON.stringify(inv.flags ?? {})}\n`,
33
+ exitCode: 0,
34
+ });
35
+ return commanderBridge(root, { run });
36
+ }
37
+
38
+ function text(result: Record<string, unknown>): string {
39
+ return (result.content as Array<{ text: string }>).map((c) => c.text).join('');
40
+ }
41
+
42
+ describe('positional args with toolNameSeparator', () => {
43
+ const handler = createMcpHandler(bridge(), { toolNameSeparator: '_' });
44
+ const post = (body: unknown, headers: Record<string, string> = {}) =>
45
+ handler({ method: 'POST', headers, body: JSON.stringify(body) });
46
+
47
+ it('publishes the args property under the separated name', async () => {
48
+ const res = await post({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
49
+ const tools = JSON.parse(res.body).result.tools as Array<{
50
+ name: string;
51
+ inputSchema: { properties: Record<string, unknown>; required?: string[] };
52
+ }>;
53
+ const add = tools.find((t) => t.name === 'item_add');
54
+ expect(add).toBeDefined();
55
+ expect(add?.inputSchema.properties.args).toMatchObject({ type: 'array', minItems: 1 });
56
+ expect(add?.inputSchema.required).toContain('args');
57
+ });
58
+
59
+ it('splits args out on a legacy call', async () => {
60
+ const res = await post({
61
+ jsonrpc: '2.0',
62
+ id: 2,
63
+ method: 'tools/call',
64
+ params: { name: 'item_add', arguments: { args: ['bolt', '-x'], count: '2' } },
65
+ });
66
+ const body = JSON.parse(res.body);
67
+ expect(body.result.isError).toBe(false);
68
+ expect(text(body.result)).toBe('item add ["bolt","-x"] {"count":"2"}\n');
69
+ });
70
+
71
+ it('splits args out on a modern call', async () => {
72
+ const res = await post(
73
+ {
74
+ jsonrpc: '2.0',
75
+ id: 3,
76
+ method: 'tools/call',
77
+ params: { name: 'item_add', arguments: { args: ['bolt'] }, _meta: MODERN_META },
78
+ },
79
+ {
80
+ 'MCP-Protocol-Version': '2026-07-28',
81
+ 'Mcp-Method': 'tools/call',
82
+ 'Mcp-Name': 'item_add',
83
+ },
84
+ );
85
+ const body = JSON.parse(res.body);
86
+ expect(body.error).toBeUndefined();
87
+ expect(body.result.isError).toBe(false);
88
+ expect(text(body.result)).toBe('item add ["bolt"] {}\n');
89
+ });
90
+
91
+ it('refuses a missing required argument on both eras', async () => {
92
+ const legacy = JSON.parse(
93
+ (
94
+ await post({
95
+ jsonrpc: '2.0',
96
+ id: 4,
97
+ method: 'tools/call',
98
+ params: { name: 'item_add', arguments: {} },
99
+ })
100
+ ).body,
101
+ );
102
+ expect(legacy.result.isError).toBe(true);
103
+ expect(text(legacy.result)).toContain('missing required argument: name');
104
+
105
+ const modern = JSON.parse(
106
+ (
107
+ await post(
108
+ {
109
+ jsonrpc: '2.0',
110
+ id: 5,
111
+ method: 'tools/call',
112
+ params: { name: 'item_add', arguments: {}, _meta: MODERN_META },
113
+ },
114
+ {
115
+ 'MCP-Protocol-Version': '2026-07-28',
116
+ 'Mcp-Method': 'tools/call',
117
+ 'Mcp-Name': 'item_add',
118
+ },
119
+ )
120
+ ).body,
121
+ );
122
+ expect(modern.result.isError).toBe(true);
123
+ expect(text(modern.result)).toContain('missing required argument: name');
124
+ });
125
+
126
+ it('carries args over serveStdio on both eras', async () => {
127
+ const input = new PassThrough();
128
+ const output = new PassThrough();
129
+ let out = '';
130
+ output.on('data', (c: Buffer) => (out += c.toString('utf8')));
131
+ const server = serveStdio(bridge(), {
132
+ input,
133
+ output,
134
+ log: new PassThrough(),
135
+ mount: { toolNameSeparator: '_' },
136
+ });
137
+ input.write(
138
+ `${JSON.stringify({
139
+ jsonrpc: '2.0',
140
+ id: 1,
141
+ method: 'tools/call',
142
+ params: { name: 'item_add', arguments: { args: ['bolt', 'spare'] } },
143
+ })}\n`,
144
+ );
145
+ input.write(
146
+ `${JSON.stringify({
147
+ jsonrpc: '2.0',
148
+ id: 2,
149
+ method: 'tools/call',
150
+ params: { name: 'item_add', arguments: { args: ['nut'] }, _meta: MODERN_META },
151
+ })}\n`,
152
+ );
153
+ input.end();
154
+ await server.done;
155
+ const got = new Map<number, Record<string, unknown>>();
156
+ for (const line of out.split('\n').filter((l) => l !== '')) {
157
+ const m = JSON.parse(line) as { id: number; result: Record<string, unknown> };
158
+ got.set(m.id, m.result);
159
+ }
160
+ expect(text(got.get(1) ?? {})).toBe('item add ["bolt","spare"] {}\n');
161
+ expect(got.get(2)).toMatchObject({ resultType: 'complete', isError: false });
162
+ expect(text(got.get(2) ?? {})).toBe('item add ["nut"] {}\n');
163
+ });
164
+ });
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Positional arguments over MCP (mcp/args), on both protocol eras:
3
+ * the "args" property tools/list publishes for a commander leaf's
4
+ * declared arguments, and the mapping of a tools/call "args" array
5
+ * back onto Invocation.args. Mirrors the Go reference's
6
+ * surface_mcp_args_test.go case for case, wording included.
7
+ */
8
+
9
+ import { Command } from 'commander';
10
+ import { describe, expect, it } from 'vitest';
11
+
12
+ import { commanderBridge, type AnnotatedCommand } from './bridge.js';
13
+ import { createMcpHandler } from './dispatch.js';
14
+ import type { Invocation, InvokeResult } from './types.js';
15
+
16
+ /**
17
+ * root
18
+ * └── item
19
+ * ├── add <name> [note]; --count
20
+ * ├── pin <id>; an --args flag holds the name
21
+ * ├── approve <name>; kit/requires-confirmation
22
+ * └── tag <files...> variadic, required
23
+ */
24
+ function argsTree(): Command {
25
+ const root = new Command('root');
26
+ const item = root.command('item');
27
+ const ann = (cmd: Command, a: Record<string, string>) => {
28
+ (cmd as AnnotatedCommand).annotations = a;
29
+ return cmd;
30
+ };
31
+ ann(
32
+ item.command('add').description('Add an item').argument('<name>').argument('[note]')
33
+ .option('--count <n>', 'how many'),
34
+ { 'kit/side-effect': 'write' },
35
+ );
36
+ ann(
37
+ item.command('pin').description('Pin an item').argument('<id>')
38
+ .option('--args <v>', 'extra arguments'),
39
+ { 'kit/side-effect': 'write' },
40
+ );
41
+ ann(item.command('approve').description('Approve an item').argument('<name>'), {
42
+ 'kit/side-effect': 'write',
43
+ 'kit/requires-confirmation': 'true',
44
+ });
45
+ item.command('tag').description('Tag files').argument('<files...>');
46
+ return root;
47
+ }
48
+
49
+ function echo(inv: Invocation): InvokeResult {
50
+ const verb = inv.path[inv.path.length - 1];
51
+ let extra = '';
52
+ if (inv.flags?.count !== undefined) extra = ` x${String(inv.flags.count)}`;
53
+ if (inv.flags?.args !== undefined) extra = ` --args=${String(inv.flags.args)}`;
54
+ return { stdout: `${verb} ${JSON.stringify(inv.args ?? [])}${extra}\n`, exitCode: 0 };
55
+ }
56
+
57
+ const MODERN_META = {
58
+ 'io.modelcontextprotocol/clientCapabilities': {},
59
+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
60
+ };
61
+
62
+ interface Tool {
63
+ name: string;
64
+ description: string;
65
+ inputSchema: { properties: Record<string, Record<string, unknown>>; required?: string[] };
66
+ }
67
+
68
+ interface Era {
69
+ name: string;
70
+ list(): Promise<Record<string, Tool>>;
71
+ call(
72
+ tool: string,
73
+ args: Record<string, unknown>,
74
+ ): Promise<{ status: number; text: string; isError: boolean }>;
75
+ }
76
+
77
+ function eras(): Era[] {
78
+ const handler = createMcpHandler(commanderBridge(argsTree(), { run: echo }));
79
+ const send = async (body: unknown, headers: Record<string, string> = {}) => {
80
+ const res = await handler({ method: 'POST', headers, body: JSON.stringify(body) });
81
+ return { status: res.status, body: JSON.parse(res.body) as { result: Record<string, unknown> } };
82
+ };
83
+ const tools = (r: Record<string, unknown>) =>
84
+ Object.fromEntries((r.tools as Tool[]).map((t) => [t.name, t]));
85
+ const outcome = (status: number, r: Record<string, unknown>) => ({
86
+ status,
87
+ text: (r.content as Array<{ text: string }>).map((c) => c.text).join(''),
88
+ isError: r.isError === true,
89
+ });
90
+ return [
91
+ {
92
+ name: '2024-11-05',
93
+ async list() {
94
+ const { body } = await send({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} });
95
+ return tools(body.result);
96
+ },
97
+ async call(tool, args) {
98
+ const { status, body } = await send({
99
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args },
100
+ });
101
+ return outcome(status, body.result);
102
+ },
103
+ },
104
+ {
105
+ name: '2026-07-28',
106
+ async list() {
107
+ const { body } = await send(
108
+ { jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: MODERN_META } },
109
+ { 'MCP-Protocol-Version': '2026-07-28', 'Mcp-Method': 'tools/list' },
110
+ );
111
+ return tools(body.result);
112
+ },
113
+ async call(tool, args) {
114
+ const { status, body } = await send(
115
+ {
116
+ jsonrpc: '2.0', id: 1, method: 'tools/call',
117
+ params: { name: tool, arguments: args, _meta: MODERN_META },
118
+ },
119
+ { 'MCP-Protocol-Version': '2026-07-28', 'Mcp-Method': 'tools/call', 'Mcp-Name': tool },
120
+ );
121
+ return outcome(status, body.result);
122
+ },
123
+ },
124
+ ];
125
+ }
126
+
127
+ describe.each(eras())('positional args over MCP ($name)', (era) => {
128
+ it('tools/list publishes declared positionals as one args array', async () => {
129
+ const tools = await era.list();
130
+
131
+ const add = tools['item.add']!;
132
+ expect(add.description).toBe('Add an item');
133
+ expect(add.inputSchema.properties.args).toEqual({
134
+ type: 'array',
135
+ items: { type: 'string' },
136
+ description: 'Positional arguments in order: name, note?',
137
+ minItems: 1,
138
+ });
139
+ expect(add.inputSchema.properties).toHaveProperty('count');
140
+ expect(add.inputSchema.required).toEqual(['args']);
141
+
142
+ const pin = tools['item.pin']!;
143
+ expect(pin.inputSchema.properties.args?.type).toBe('string');
144
+ expect(pin.inputSchema.required).toBeUndefined();
145
+ expect(pin.description).toBe(
146
+ 'Pin an item Takes positional arguments that cannot be passed over MCP: its --args flag holds the "args" property.',
147
+ );
148
+
149
+ expect(tools['item.tag']!.inputSchema.properties.args).toEqual({
150
+ type: 'array',
151
+ items: { type: 'string' },
152
+ description: 'Positional arguments in order: files',
153
+ minItems: 1,
154
+ });
155
+ });
156
+
157
+ it('tools/call maps args onto positionals in order', async () => {
158
+ let r = await era.call('item.add', { args: ['bolt', 'spare'], count: '2' });
159
+ expect(r).toEqual({ status: 200, text: 'add ["bolt","spare"] x2\n', isError: false });
160
+
161
+ r = await era.call('item.add', { args: ['nut'] });
162
+ expect(r.text).toBe('add ["nut"]\n');
163
+
164
+ r = await era.call('item.tag', { args: ['a', 'b', 'c'] });
165
+ expect(r.text).toBe('tag ["a","b","c"]\n');
166
+ });
167
+
168
+ it('refuses missing or malformed args', async () => {
169
+ for (const args of [{ count: '2' }, { args: [] }]) {
170
+ expect(await era.call('item.add', args)).toEqual({
171
+ status: 200, text: 'missing required argument: name', isError: true,
172
+ });
173
+ }
174
+ for (const args of [{ args: 'bolt' }, { args: [1] }]) {
175
+ const r = await era.call('item.add', args);
176
+ expect(r.isError).toBe(true);
177
+ expect(r.text).toBe('"args" must be an array of strings');
178
+ }
179
+ });
180
+
181
+ it('checks arguments before the confirmation gate', async () => {
182
+ let r = await era.call('item.approve', {});
183
+ expect(r).toEqual({ status: 200, text: 'missing required argument: name', isError: true });
184
+
185
+ r = await era.call('item.approve', { args: ['bolt'] });
186
+ expect(r.status).toBe(428);
187
+ expect(r.isError).toBe(true);
188
+ expect(r.text).toContain('confirmation required');
189
+ });
190
+
191
+ it('an --args flag keeps the name and gets the value as a flag', async () => {
192
+ const r = await era.call('item.pin', { args: 'x' });
193
+ expect(r).toEqual({ status: 200, text: 'pin [] --args=x\n', isError: false });
194
+ });
195
+ });
196
+
197
+ describe('commanderBridge without positionals', () => {
198
+ it('publishes no args property and passes no Invocation.args', async () => {
199
+ const root = new Command('root');
200
+ root.command('ping').description('Ping').option('--count <n>', 'how many');
201
+ let seen: Invocation | undefined;
202
+ const handler = createMcpHandler(
203
+ commanderBridge(root, {
204
+ run: (inv) => {
205
+ seen = inv;
206
+ return { stdout: '', exitCode: 0 };
207
+ },
208
+ }),
209
+ );
210
+ const list = await handler({
211
+ method: 'POST', headers: {}, body: '{"jsonrpc":"2.0","id":1,"method":"tools/list"}',
212
+ });
213
+ expect(list.body).toContain(
214
+ '"inputSchema":{"properties":{"count":{"description":"how many","type":"string"}},"type":"object"}',
215
+ );
216
+ await handler({
217
+ method: 'POST', headers: {},
218
+ body: '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ping","arguments":{"count":"3"}}}',
219
+ });
220
+ expect(seen?.args).toBeUndefined();
221
+ expect(seen?.flags).toEqual({ count: '3' });
222
+ });
223
+ });