@hop-top/kit 0.5.0-alpha.0 → 0.5.0-alpha.2
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/CHANGELOG.md +98 -0
- package/README.md +237 -9
- package/dist/aim-CTp-kJW2.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/alias-dhhr08Ei.d.ts +88 -0
- package/dist/alias.d.ts +2 -73
- package/dist/api-miiso81x.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/cli-DgOEOsPB.d.ts +450 -0
- package/dist/cli.d.ts +5 -309
- package/dist/cli.js +250 -62
- package/dist/config-BUY7_W2n.d.ts +103 -0
- package/dist/config.d.ts +1 -97
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/id/index.d.ts +2 -83
- package/dist/index--C7Mtsmm.d.ts +328 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-MLrRDvEG.d.ts +1073 -0
- package/dist/index-QSffbLnj.d.ts +94 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +5863 -0
- package/dist/llm-B5XUWH8T.d.ts +231 -0
- package/dist/llm.d.ts +1 -188
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +1453 -0
- package/dist/netpolicy-asvCfwi8.d.ts +138 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +118 -0
- package/dist/output-VFFLqor9.d.ts +521 -0
- package/dist/output.d.ts +2 -213
- package/dist/output.js +554 -43
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/routellm-PGSt2D1y.d.ts +75 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/rpc-D5xLEf8V.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +12 -1
- package/dist/tui/index.d.ts +4 -298
- package/dist/tui/index.js +61 -9
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/package.json +65 -25
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.ts +112 -12
- package/src/index.test.ts +58 -0
- package/src/index.ts +36 -0
- package/src/log.parity.test.ts +105 -0
- package/src/log.ts +64 -13
- package/src/mcp/bridge.test.ts +150 -0
- package/src/mcp/bridge.ts +246 -0
- package/src/mcp/conformance.test.ts +336 -0
- package/src/mcp/dispatch.ts +313 -0
- package/src/mcp/index.ts +138 -0
- package/src/mcp/legacy.ts +314 -0
- package/src/mcp/mcp.test.ts +697 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +452 -0
- package/src/mcp/modern.ts +723 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/types.ts +504 -0
- package/src/netpolicy.test.ts +202 -0
- package/src/netpolicy.ts +231 -0
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +293 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +39 -3
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +7 -1
- package/src/telemetry/offline.test.ts +64 -0
- package/src/tui/parity.test.ts +142 -0
- package/src/tui/parity.ts +59 -13
- package/test/output/csv.test.ts +164 -0
- package/test/output/error.test.ts +241 -0
package/src/log.ts
CHANGED
|
@@ -5,10 +5,16 @@
|
|
|
5
5
|
* API: `logger.info('msg', 'key', val, 'key2', val2)` (variadic key-value)
|
|
6
6
|
* This matches Go's charm/log API, not pino's native object API.
|
|
7
7
|
* Pino handles transports, serialization, and performance under the hood.
|
|
8
|
+
*
|
|
9
|
+
* The `-V` count → level mapping and the `--quiet` override both come from
|
|
10
|
+
* the parity contract (`parity.json` verbosity block), so the level
|
|
11
|
+
* vocabulary stays identical across the Go, TypeScript and Python ports.
|
|
8
12
|
*/
|
|
9
13
|
|
|
10
14
|
import pino from 'pino';
|
|
11
15
|
|
|
16
|
+
import { parity, type ParityData } from './tui/parity.js';
|
|
17
|
+
|
|
12
18
|
// ---------------------------------------------------------------------------
|
|
13
19
|
// Types
|
|
14
20
|
// ---------------------------------------------------------------------------
|
|
@@ -96,6 +102,55 @@ function kvToObj(keyvals: any[]): Record<string, any> {
|
|
|
96
102
|
return obj;
|
|
97
103
|
}
|
|
98
104
|
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Parity contract → pino level names
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
/** Pino level names the contract's level vocabulary may resolve to. */
|
|
110
|
+
const PINO_LEVELS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Resolve a contract level name to a pino level name.
|
|
114
|
+
*
|
|
115
|
+
* The names are the cross-language vocabulary declared in `parity.json`;
|
|
116
|
+
* pino happens to use the same spellings, so this is a membership check
|
|
117
|
+
* rather than a translation table (Go needs one because charm/log has no
|
|
118
|
+
* `trace`).
|
|
119
|
+
*/
|
|
120
|
+
function levelByName(name: string): string | undefined {
|
|
121
|
+
return PINO_LEVELS.has(name) ? name : undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Resolve a `-V` count against a parity contract's `verbosity.levels`
|
|
126
|
+
* table. Counts above the highest declared key clamp to that key's level;
|
|
127
|
+
* an empty or unresolvable table falls back to `info`.
|
|
128
|
+
*
|
|
129
|
+
* Taking the contract as a parameter (rather than reading the module-level
|
|
130
|
+
* `parity`) keeps the mapping testable against a constructed `ParityData`
|
|
131
|
+
* without mutating the shared `parity.json`.
|
|
132
|
+
*/
|
|
133
|
+
export function verbosityLevel(d: ParityData, verbose: number): string {
|
|
134
|
+
const levels = d.verbosity?.levels ?? {};
|
|
135
|
+
// Highest declared count at or below `verbose` wins.
|
|
136
|
+
let best = -1;
|
|
137
|
+
for (const key of Object.keys(levels)) {
|
|
138
|
+
const n = Number(key);
|
|
139
|
+
if (!Number.isInteger(n)) continue;
|
|
140
|
+
if (n <= verbose && n > best) best = n;
|
|
141
|
+
}
|
|
142
|
+
if (best < 0) return 'info';
|
|
143
|
+
return levelByName(levels[String(best)]) ?? 'info';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Resolve a parity contract's `verbosity.quiet_override` to a pino level
|
|
148
|
+
* name. An unrecognized or absent override falls back to `warn`.
|
|
149
|
+
*/
|
|
150
|
+
export function quietLevel(d: ParityData): string {
|
|
151
|
+
return levelByName(d.verbosity?.quiet_override ?? '') ?? 'warn';
|
|
152
|
+
}
|
|
153
|
+
|
|
99
154
|
// ---------------------------------------------------------------------------
|
|
100
155
|
// Factory
|
|
101
156
|
// ---------------------------------------------------------------------------
|
|
@@ -104,8 +159,12 @@ export function createLogger(opts?: LoggerOptions): Logger {
|
|
|
104
159
|
const quiet = opts?.quiet ?? false;
|
|
105
160
|
const noColor = opts?.noColor ?? false;
|
|
106
161
|
|
|
162
|
+
// Note: the non-quiet level here is `debug`, NOT the contract's
|
|
163
|
+
// zero-verbosity level. createLogger predates the verbosity contract and
|
|
164
|
+
// is deliberately chattier than `withVerbose({ verbose: 0 })`; only the
|
|
165
|
+
// quiet override is contract-declared, so only it is wired.
|
|
107
166
|
const p = pino({
|
|
108
|
-
level: quiet ?
|
|
167
|
+
level: quiet ? quietLevel(parity) : 'debug',
|
|
109
168
|
}, kitTransport(noColor));
|
|
110
169
|
|
|
111
170
|
return {
|
|
@@ -122,8 +181,9 @@ export function createLogger(opts?: LoggerOptions): Logger {
|
|
|
122
181
|
// ---------------------------------------------------------------------------
|
|
123
182
|
|
|
124
183
|
/**
|
|
125
|
-
* Map verbose count to pino level
|
|
126
|
-
* Quiet overrides to
|
|
184
|
+
* Map verbose count to a pino level through the parity contract's
|
|
185
|
+
* `verbosity.levels` table. Quiet overrides to the contract's
|
|
186
|
+
* `quiet_override` level regardless of verbose count.
|
|
127
187
|
*/
|
|
128
188
|
export function withVerbose(
|
|
129
189
|
opts: LoggerOptions & { verbose?: number },
|
|
@@ -132,16 +192,7 @@ export function withVerbose(
|
|
|
132
192
|
const noColor = opts.noColor ?? false;
|
|
133
193
|
const v = opts.verbose ?? 0;
|
|
134
194
|
|
|
135
|
-
|
|
136
|
-
if (quiet) {
|
|
137
|
-
level = 'warn';
|
|
138
|
-
} else if (v >= 2) {
|
|
139
|
-
level = 'trace';
|
|
140
|
-
} else if (v >= 1) {
|
|
141
|
-
level = 'debug';
|
|
142
|
-
} else {
|
|
143
|
-
level = 'info';
|
|
144
|
-
}
|
|
195
|
+
const level = quiet ? quietLevel(parity) : verbosityLevel(parity, v);
|
|
145
196
|
|
|
146
197
|
const p = pino({ level }, kitTransport(noColor));
|
|
147
198
|
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coverage for the commander bridge adapter: leaf enumeration, flag
|
|
3
|
+
* schema derivation, annotation classification, and the destructive
|
|
4
|
+
* ceiling on the invoke path.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { Command, Option } from 'commander';
|
|
8
|
+
import { describe, expect, it } from 'vitest';
|
|
9
|
+
|
|
10
|
+
import { commanderBridge, type AnnotatedCommand } from './bridge.js';
|
|
11
|
+
import { createMcpHandler } from './dispatch.js';
|
|
12
|
+
import { SURFACE_MCP, type InvokeResult } from './types.js';
|
|
13
|
+
|
|
14
|
+
function annotate(cmd: Command, ann: Record<string, string>): Command {
|
|
15
|
+
(cmd as AnnotatedCommand).annotations = ann;
|
|
16
|
+
return cmd;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** root ├── widget {add,delete} ├── secret ├── ping */
|
|
20
|
+
function buildTree(): Command {
|
|
21
|
+
const root = new Command('root');
|
|
22
|
+
|
|
23
|
+
const widget = new Command('widget');
|
|
24
|
+
const add = new Command('add').description('Add a widget');
|
|
25
|
+
add.requiredOption('--name <n>', 'widget name');
|
|
26
|
+
add.option('--count <n>', 'widget count');
|
|
27
|
+
add.option('--force', 'force flag');
|
|
28
|
+
add.option('--tag <t...>', 'tag list');
|
|
29
|
+
const hidden = new Option('--hidden-flag <v>', 'should be hidden').hideHelp();
|
|
30
|
+
add.addOption(hidden);
|
|
31
|
+
annotate(add, { 'kit/side-effect': 'write' });
|
|
32
|
+
widget.addCommand(add);
|
|
33
|
+
|
|
34
|
+
const del = new Command('delete').description('Delete a widget');
|
|
35
|
+
annotate(del, { 'kit/side-effect': 'destructive' });
|
|
36
|
+
widget.addCommand(del);
|
|
37
|
+
root.addCommand(widget);
|
|
38
|
+
|
|
39
|
+
const secret = new Command('secret').description('Locked');
|
|
40
|
+
annotate(secret, { 'kit/auth-required': 'true' });
|
|
41
|
+
root.addCommand(secret);
|
|
42
|
+
|
|
43
|
+
const ping = new Command('ping').description('Ping the server');
|
|
44
|
+
annotate(ping, { 'kit/side-effect': 'read' });
|
|
45
|
+
root.addCommand(ping);
|
|
46
|
+
|
|
47
|
+
return root;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const run = (): InvokeResult => ({ stdout: 'ok\n', exitCode: 0 });
|
|
51
|
+
|
|
52
|
+
describe('commanderBridge', () => {
|
|
53
|
+
it('enumerates leaves as dotted paths, excluding groups and the root', () => {
|
|
54
|
+
const bridge = commanderBridge(buildTree(), { run });
|
|
55
|
+
expect(bridge.leaves().map((l) => l.path.join('.'))).toEqual([
|
|
56
|
+
'widget.add',
|
|
57
|
+
'widget.delete',
|
|
58
|
+
'secret',
|
|
59
|
+
'ping',
|
|
60
|
+
]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('derives a JSON Schema from options, excluding hidden ones', () => {
|
|
64
|
+
const bridge = commanderBridge(buildTree(), { run });
|
|
65
|
+
const add = bridge.leaves().find((l) => l.path.join('.') === 'widget.add');
|
|
66
|
+
expect(add?.properties).toEqual({
|
|
67
|
+
name: { type: 'string', description: 'widget name' },
|
|
68
|
+
count: { type: 'string', description: 'widget count' },
|
|
69
|
+
force: { type: 'boolean', description: 'force flag' },
|
|
70
|
+
tag: { type: 'array', description: 'tag list', items: { type: 'string' } },
|
|
71
|
+
});
|
|
72
|
+
expect(add?.required).toEqual(['name']);
|
|
73
|
+
expect(add?.properties).not.toHaveProperty('hidden-flag');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('classifies kit annotations into the SafetyClass', () => {
|
|
77
|
+
const bridge = commanderBridge(buildTree(), { run });
|
|
78
|
+
const byName = (n: string) =>
|
|
79
|
+
bridge.leaves().find((l) => l.path.join('.') === n);
|
|
80
|
+
expect(byName('widget.delete')?.class?.destructive).toBe(true);
|
|
81
|
+
expect(byName('secret')?.class?.authRequired).toBe(true);
|
|
82
|
+
expect(byName('ping')?.class?.destructive).toBeUndefined();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('blocks a destructive leaf on MCP under the default policy', async () => {
|
|
86
|
+
const bridge = commanderBridge(buildTree(), { run });
|
|
87
|
+
await expect(
|
|
88
|
+
bridge.invoke({
|
|
89
|
+
path: ['widget', 'delete'],
|
|
90
|
+
meta: { surface: SURFACE_MCP, requestedAt: new Date() },
|
|
91
|
+
}),
|
|
92
|
+
).rejects.toThrow(/destructive command blocked on this surface/);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('allows the same leaf once MCP is named in allowDestructiveOn', async () => {
|
|
96
|
+
const bridge = commanderBridge(buildTree(), {
|
|
97
|
+
run,
|
|
98
|
+
policy: { allowDestructiveOn: [SURFACE_MCP] },
|
|
99
|
+
});
|
|
100
|
+
await expect(
|
|
101
|
+
bridge.invoke({
|
|
102
|
+
path: ['widget', 'delete'],
|
|
103
|
+
meta: { surface: SURFACE_MCP, requestedAt: new Date() },
|
|
104
|
+
}),
|
|
105
|
+
).resolves.toEqual({ stdout: 'ok\n', exitCode: 0 });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('rejects an unknown leaf path', async () => {
|
|
109
|
+
const bridge = commanderBridge(buildTree(), { run });
|
|
110
|
+
await expect(
|
|
111
|
+
bridge.invoke({
|
|
112
|
+
path: ['nope'],
|
|
113
|
+
meta: { surface: SURFACE_MCP, requestedAt: new Date() },
|
|
114
|
+
}),
|
|
115
|
+
).rejects.toThrow(/unknown command/);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('serves a real tools/list through the MCP handler', async () => {
|
|
119
|
+
const handler = createMcpHandler(commanderBridge(buildTree(), { run }));
|
|
120
|
+
const res = await handler({
|
|
121
|
+
method: 'POST',
|
|
122
|
+
headers: {},
|
|
123
|
+
body: '{"jsonrpc":"2.0","id":1,"method":"tools/list"}',
|
|
124
|
+
});
|
|
125
|
+
expect(res.status).toBe(200);
|
|
126
|
+
const body = JSON.parse(res.body) as {
|
|
127
|
+
result: { tools: Array<{ name: string }> };
|
|
128
|
+
};
|
|
129
|
+
expect(body.result.tools.map((t) => t.name)).toEqual([
|
|
130
|
+
'widget.add',
|
|
131
|
+
'widget.delete',
|
|
132
|
+
'secret',
|
|
133
|
+
'ping',
|
|
134
|
+
]);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('renders a destructive block as an isError result at HTTP 200', async () => {
|
|
138
|
+
const handler = createMcpHandler(commanderBridge(buildTree(), { run }));
|
|
139
|
+
const res = await handler({
|
|
140
|
+
method: 'POST',
|
|
141
|
+
headers: {},
|
|
142
|
+
body: '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"widget.delete"}}',
|
|
143
|
+
});
|
|
144
|
+
expect(res.status).toBe(200);
|
|
145
|
+
expect(res.body).toContain('"isError":true');
|
|
146
|
+
expect(res.body).toContain(
|
|
147
|
+
'destructive command blocked on this surface: widget delete on mcp',
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/bridge
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* A commander adapter for the MCP surface's `McpBridge` interface.
|
|
6
|
+
*
|
|
7
|
+
* The surface itself never imports commander — that is what keeps
|
|
8
|
+
* the handler framework-free and lets adopters on another command
|
|
9
|
+
* framework implement `McpBridge` directly. This adapter is the
|
|
10
|
+
* convenience path for the commander trees the TS SDK's own `cli`
|
|
11
|
+
* module builds.
|
|
12
|
+
*
|
|
13
|
+
* The safety gate lives here, on the invoke path, so BOTH eras
|
|
14
|
+
* inherit one destructive ceiling from one place: there is no way to
|
|
15
|
+
* reach a leaf through the modern handler that the legacy handler
|
|
16
|
+
* would have blocked.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { Command, Option } from 'commander';
|
|
20
|
+
import {
|
|
21
|
+
DestructiveBlockedError,
|
|
22
|
+
policyAllowed,
|
|
23
|
+
SurfaceNotEnabledError,
|
|
24
|
+
toolName,
|
|
25
|
+
UnknownCommandError,
|
|
26
|
+
defaultPolicy,
|
|
27
|
+
type FlagSchema,
|
|
28
|
+
type Invocation,
|
|
29
|
+
type InvokeResult,
|
|
30
|
+
type Leaf,
|
|
31
|
+
type McpBridge,
|
|
32
|
+
type Policy,
|
|
33
|
+
type SafetyClass,
|
|
34
|
+
type Surface,
|
|
35
|
+
} from './types.js';
|
|
36
|
+
|
|
37
|
+
/** Annotation keys read off a command, matching the kit/ vocabulary. */
|
|
38
|
+
const ANN_SIDE_EFFECT = 'kit/side-effect';
|
|
39
|
+
const ANN_AUTH_REQUIRED = 'kit/auth-required';
|
|
40
|
+
const ANN_REQUIRES_CONFIRM = 'kit/requires-confirmation';
|
|
41
|
+
const ANN_PERMISSIONS = 'kit/permissions';
|
|
42
|
+
const ANN_EXIT_CODES = 'kit/exit-codes';
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A command carrying kit annotations. commander has no annotations
|
|
46
|
+
* concept, so they ride an optional property the CLI builder sets.
|
|
47
|
+
*/
|
|
48
|
+
export interface AnnotatedCommand extends Command {
|
|
49
|
+
annotations?: Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface CommanderBridgeOptions {
|
|
53
|
+
/** Policy gate. Defaults to defaultPolicy() (block remote destructive). */
|
|
54
|
+
policy?: Policy;
|
|
55
|
+
/**
|
|
56
|
+
* Runs one leaf and returns its result. Adopters supply this
|
|
57
|
+
* because kit does not dictate how a command's output is captured.
|
|
58
|
+
*/
|
|
59
|
+
run: (inv: Invocation, cmd: Command) => Promise<InvokeResult> | InvokeResult;
|
|
60
|
+
/** Per-leaf surface enablement override. */
|
|
61
|
+
enabled?: (leaf: Leaf) => Partial<Record<Surface, boolean>> | undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Builds an `McpBridge` over a commander tree. Leaves are the
|
|
66
|
+
* commands with no subcommands, enumerated depth-first in
|
|
67
|
+
* declaration order, with the root's own name excluded from the path
|
|
68
|
+
* (so `root widget add` is the tool `widget.add`).
|
|
69
|
+
*/
|
|
70
|
+
export function commanderBridge(
|
|
71
|
+
root: Command,
|
|
72
|
+
opts: CommanderBridgeOptions,
|
|
73
|
+
): McpBridge {
|
|
74
|
+
const policy = opts.policy ?? defaultPolicy();
|
|
75
|
+
|
|
76
|
+
const leaves = (): Leaf[] => {
|
|
77
|
+
const out: Leaf[] = [];
|
|
78
|
+
walkLeaves(root, [], (cmd, path) => {
|
|
79
|
+
const leaf: Leaf = {
|
|
80
|
+
path,
|
|
81
|
+
description: cmd.description() ?? '',
|
|
82
|
+
...collectFlags(cmd),
|
|
83
|
+
class: classify(cmd as AnnotatedCommand),
|
|
84
|
+
};
|
|
85
|
+
const en = opts.enabled?.(leaf);
|
|
86
|
+
if (en) leaf.enabled = en;
|
|
87
|
+
out.push(leaf);
|
|
88
|
+
});
|
|
89
|
+
return out;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
leaves,
|
|
94
|
+
async invoke(inv: Invocation): Promise<InvokeResult> {
|
|
95
|
+
const target = leaves().find(
|
|
96
|
+
(l) =>
|
|
97
|
+
l.path.length === inv.path.length &&
|
|
98
|
+
l.path.every((seg, i) => seg === inv.path[i]),
|
|
99
|
+
);
|
|
100
|
+
if (target === undefined) {
|
|
101
|
+
throw new UnknownCommandError(
|
|
102
|
+
`unknown command: ${toolName(inv.path)}`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
if (target.enabled?.[inv.meta.surface] === false) {
|
|
106
|
+
throw new SurfaceNotEnabledError(
|
|
107
|
+
`surface not enabled: ${inv.meta.surface}`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
// The destructive ceiling. Empty allowDestructiveOn means
|
|
111
|
+
// block-all, so a destructive leaf is unreachable on MCP unless
|
|
112
|
+
// the adopter explicitly opts that surface in.
|
|
113
|
+
if (!policyAllowed(policy, target.class ?? {}, inv.meta.surface)) {
|
|
114
|
+
throw new DestructiveBlockedError(
|
|
115
|
+
target.path.join(' '),
|
|
116
|
+
inv.meta.surface,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
const cmd = findCommand(root, target.path);
|
|
120
|
+
if (cmd === undefined) {
|
|
121
|
+
throw new UnknownCommandError(
|
|
122
|
+
`unknown command: ${toolName(inv.path)}`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return opts.run(inv, cmd);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Reads a command's kit annotations into a SafetyClass. */
|
|
131
|
+
export function classify(cmd: AnnotatedCommand): SafetyClass {
|
|
132
|
+
const ann = cmd.annotations ?? {};
|
|
133
|
+
const cls: SafetyClass = {};
|
|
134
|
+
switch (ann[ANN_SIDE_EFFECT]) {
|
|
135
|
+
case 'destructive':
|
|
136
|
+
case 'destructive-local':
|
|
137
|
+
case 'destructive-shared':
|
|
138
|
+
cls.destructive = true;
|
|
139
|
+
break;
|
|
140
|
+
default:
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
if (ann[ANN_AUTH_REQUIRED] === 'true') cls.authRequired = true;
|
|
144
|
+
if (ann[ANN_REQUIRES_CONFIRM] === 'true') cls.requiresConfirmation = true;
|
|
145
|
+
const perms = splitCSV(ann[ANN_PERMISSIONS]);
|
|
146
|
+
if (perms) cls.permissions = perms;
|
|
147
|
+
const codes = splitCSV(ann[ANN_EXIT_CODES]);
|
|
148
|
+
if (codes) cls.exitCodes = codes;
|
|
149
|
+
return cls;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Parses a comma-separated annotation value, dropping empty entries. */
|
|
153
|
+
function splitCSV(s: string | undefined): string[] | undefined {
|
|
154
|
+
if (!s) return undefined;
|
|
155
|
+
const out = s
|
|
156
|
+
.split(',')
|
|
157
|
+
.map((p) => p.trim())
|
|
158
|
+
.filter((p) => p !== '');
|
|
159
|
+
return out.length > 0 ? out : undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Walks the tree depth-first, invoking `visit` for each leaf (a
|
|
164
|
+
* command with no subcommands). The root's own name is not part of
|
|
165
|
+
* any path.
|
|
166
|
+
*/
|
|
167
|
+
function walkLeaves(
|
|
168
|
+
cmd: Command,
|
|
169
|
+
path: string[],
|
|
170
|
+
visit: (cmd: Command, path: string[]) => void,
|
|
171
|
+
): void {
|
|
172
|
+
const subs = cmd.commands as Command[];
|
|
173
|
+
if (subs.length === 0) {
|
|
174
|
+
if (path.length > 0) visit(cmd, path);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
for (const sub of subs) {
|
|
178
|
+
walkLeaves(sub, [...path, sub.name()], visit);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Resolves a leaf path back to its commander Command. */
|
|
183
|
+
function findCommand(root: Command, path: string[]): Command | undefined {
|
|
184
|
+
let cur: Command = root;
|
|
185
|
+
for (const seg of path) {
|
|
186
|
+
const next = (cur.commands as Command[]).find((c) => c.name() === seg);
|
|
187
|
+
if (next === undefined) return undefined;
|
|
188
|
+
cur = next;
|
|
189
|
+
}
|
|
190
|
+
return cur;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Maps a command's options to JSON Schema properties plus the
|
|
195
|
+
* required-name list, filtering out hidden options. Long-flag names
|
|
196
|
+
* are used verbatim (`--dry-run` → `dry-run`), matching the Go
|
|
197
|
+
* surface's use of the pflag name rather than a camelCased accessor.
|
|
198
|
+
*/
|
|
199
|
+
export function collectFlags(cmd: Command): {
|
|
200
|
+
properties: Record<string, FlagSchema>;
|
|
201
|
+
required?: string[];
|
|
202
|
+
} {
|
|
203
|
+
const properties: Record<string, FlagSchema> = {};
|
|
204
|
+
const required: string[] = [];
|
|
205
|
+
const seen = new Set<string>();
|
|
206
|
+
|
|
207
|
+
for (const opt of cmd.options as Option[]) {
|
|
208
|
+
if (opt.hidden) continue;
|
|
209
|
+
const name = optionName(opt);
|
|
210
|
+
if (name === '' || seen.has(name)) continue;
|
|
211
|
+
seen.add(name);
|
|
212
|
+
properties[name] = flagProperty(opt);
|
|
213
|
+
if (opt.mandatory) required.push(name);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return required.length > 0 ? { properties, required } : { properties };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The schema property name for an option: its long flag, undashed. */
|
|
220
|
+
function optionName(opt: Option): string {
|
|
221
|
+
const long = opt.long;
|
|
222
|
+
if (long) return long.replace(/^--/, '');
|
|
223
|
+
return (opt.short ?? '').replace(/^-/, '');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Maps one option to a JSON Schema property object. */
|
|
227
|
+
function flagProperty(opt: Option): FlagSchema {
|
|
228
|
+
const type = optionJSONType(opt);
|
|
229
|
+
const prop: FlagSchema = {
|
|
230
|
+
type,
|
|
231
|
+
description: opt.description ?? '',
|
|
232
|
+
};
|
|
233
|
+
if (type === 'array') prop.items = { type: 'string' };
|
|
234
|
+
return prop;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Maps a commander option to a JSON Schema primitive. Variadic
|
|
239
|
+
* options are arrays; boolean flags are booleans; everything else is
|
|
240
|
+
* a string unless the adopter declared a numeric parser.
|
|
241
|
+
*/
|
|
242
|
+
function optionJSONType(opt: Option): string {
|
|
243
|
+
if (opt.variadic) return 'array';
|
|
244
|
+
if (typeof opt.isBoolean === 'function' && opt.isBoolean()) return 'boolean';
|
|
245
|
+
return 'string';
|
|
246
|
+
}
|