@hop-top/kit 0.5.0-alpha.8 → 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.
- package/CHANGELOG.md +22 -0
- package/dist/{chunk-263IZ6Z6.js → chunk-B4ULGCCN.js} +43 -154
- package/dist/{chunk-JTMPNXVQ.js → chunk-P6GRX4RV.js} +486 -83
- package/dist/chunk-UZ65A27P.js +147 -0
- package/dist/{index-B-pqGHhU.d.ts → index-CaOXdl38.d.ts} +337 -24
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -3
- package/dist/mcp/index.d.ts +2 -1
- package/dist/mcp/index.js +31 -2
- package/dist/{toolspec-UrWnoJ3Y.d.ts → toolspec-96rkLfsh.d.ts} +7 -2
- package/dist/toolspec.d.ts +1 -1
- package/dist/toolspec.js +3 -2
- package/package.json +1 -1
- package/src/mcp/README.md +6 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +72 -0
- package/src/mcp/bridge.ts +50 -5
- package/src/mcp/conformance.test.ts +1 -1
- package/src/mcp/dispatch.ts +48 -2
- package/src/mcp/index.ts +33 -1
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +55 -15
- package/src/mcp/modern-confirm.ts +42 -10
- package/src/mcp/modern.ts +99 -35
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +125 -18
- package/src/toolspec-internal.ts +24 -0
- package/src/toolspec-manifest.test.ts +25 -0
- package/src/toolspec-manifest.ts +5 -1
- package/src/toolspec.from-command.test.ts +51 -0
- package/src/toolspec.ts +29 -15
package/src/mcp/stdio.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/stdio
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* The stdio binding for the dual-spec MCP surface: newline-delimited
|
|
6
|
+
* JSON-RPC over a pair of byte streams (by default the process's
|
|
7
|
+
* stdin/stdout), driving the same era dispatch the HTTP handler uses.
|
|
8
|
+
*
|
|
9
|
+
* Wire rules (stdio binding, 2024-11-05 and 2026-07-28):
|
|
10
|
+
* - one JSON-RPC message per line; output lines carry no embedded
|
|
11
|
+
* newline, and the output stream carries nothing but protocol
|
|
12
|
+
* messages — diagnostics go to the log stream (stderr);
|
|
13
|
+
* - a notification (no `id` member) is never answered;
|
|
14
|
+
* - each message is a single request: a JSON array (a batch) is
|
|
15
|
+
* refused with -32600 and `id: null`;
|
|
16
|
+
* - a line that is not JSON is answered -32700 with `id: null`;
|
|
17
|
+
* - requests run concurrently, so replies may arrive out of order —
|
|
18
|
+
* each carries its request's id.
|
|
19
|
+
*
|
|
20
|
+
* stdio has no header layer: era detection uses the body markers only
|
|
21
|
+
* (`params._meta` protocolVersion, `server/discover`), and the
|
|
22
|
+
* 2026-07-28 header checks (V4, V6, V7) do not apply. Gates that read
|
|
23
|
+
* headers see none — see the MCP guide for what that means for
|
|
24
|
+
* auth-required and confirmation-gated tools.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { createInterface } from 'node:readline';
|
|
28
|
+
import type { Readable, Writable } from 'node:stream';
|
|
29
|
+
|
|
30
|
+
import {
|
|
31
|
+
dispatcherFactoryOf,
|
|
32
|
+
McpDispatcher,
|
|
33
|
+
parseJsonRpcRequest,
|
|
34
|
+
type JsonRpcRequest,
|
|
35
|
+
type McpHandler,
|
|
36
|
+
type McpHttpRequest,
|
|
37
|
+
type McpHttpResponse,
|
|
38
|
+
} from './dispatch.js';
|
|
39
|
+
import { errorMessage, goJSONParseMessage } from './legacy.js';
|
|
40
|
+
import {
|
|
41
|
+
encodeEnvelope,
|
|
42
|
+
MCP_ERR_INTERNAL,
|
|
43
|
+
MCP_ERR_INVALID_REQUEST,
|
|
44
|
+
MCP_ERR_PARSE,
|
|
45
|
+
RawJSON,
|
|
46
|
+
resolveMcpConfig,
|
|
47
|
+
type JsonRpcErrorObject,
|
|
48
|
+
type McpBridge,
|
|
49
|
+
type McpMountOptions,
|
|
50
|
+
} from './types.js';
|
|
51
|
+
|
|
52
|
+
/** Options for {@link serveStdio}. */
|
|
53
|
+
export interface McpStdioOptions {
|
|
54
|
+
/** Where requests are read from. Default: `process.stdin`. */
|
|
55
|
+
input?: Readable;
|
|
56
|
+
/** Where replies are written. Default: `process.stdout`. */
|
|
57
|
+
output?: Writable;
|
|
58
|
+
/** Where diagnostics are written. Default: `process.stderr`. */
|
|
59
|
+
log?: Writable;
|
|
60
|
+
/**
|
|
61
|
+
* Mount options, when serving a bridge. A handler from
|
|
62
|
+
* createMcpHandler already carries its own; passing both throws.
|
|
63
|
+
*/
|
|
64
|
+
mount?: McpMountOptions;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A running stdio session. */
|
|
68
|
+
export interface McpStdioServer {
|
|
69
|
+
/**
|
|
70
|
+
* Resolves once input has ended (or {@link close} was called) and
|
|
71
|
+
* every in-flight request has been answered.
|
|
72
|
+
*/
|
|
73
|
+
readonly done: Promise<void>;
|
|
74
|
+
/** Stops reading input; resolves like {@link done}. */
|
|
75
|
+
close(): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type Serve = (req: McpHttpRequest, rpc: JsonRpcRequest) => Promise<McpHttpResponse>;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Serves MCP over stdio for a bridge, or for a handler built by
|
|
82
|
+
* createMcpHandler (its bridge and mount options are reused).
|
|
83
|
+
*
|
|
84
|
+
* A handler built some other way is called with an HTTP-shaped POST
|
|
85
|
+
* per message; that serves the 2024-11-05 era, but such a handler
|
|
86
|
+
* cannot know the request came over stdio, so 2026-07-28 requests fail
|
|
87
|
+
* its header checks. Pass the bridge or a createMcpHandler handler to
|
|
88
|
+
* serve both eras.
|
|
89
|
+
*
|
|
90
|
+
* ```ts
|
|
91
|
+
* import { serveStdio } from '@hop-top/kit/mcp';
|
|
92
|
+
*
|
|
93
|
+
* const server = serveStdio(bridge);
|
|
94
|
+
* await server.done; // the host closed stdin
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export function serveStdio(
|
|
98
|
+
target: McpBridge | McpHandler,
|
|
99
|
+
opts: McpStdioOptions = {},
|
|
100
|
+
): McpStdioServer {
|
|
101
|
+
const serve = resolveServe(target, opts.mount);
|
|
102
|
+
const input = opts.input ?? process.stdin;
|
|
103
|
+
const output = opts.output ?? process.stdout;
|
|
104
|
+
const log = opts.log ?? process.stderr;
|
|
105
|
+
|
|
106
|
+
const inFlight = new Set<Promise<void>>();
|
|
107
|
+
const write = (line: string): void => {
|
|
108
|
+
output.write(line.endsWith('\n') ? line : `${line}\n`);
|
|
109
|
+
};
|
|
110
|
+
const warn = (msg: string): void => {
|
|
111
|
+
log.write(`mcp stdio: ${msg}\n`);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const rl = createInterface({ input, crlfDelay: Infinity, terminal: false });
|
|
115
|
+
rl.on('line', (line) => {
|
|
116
|
+
const task = handleLine(line, serve, write, warn);
|
|
117
|
+
if (task === undefined) return;
|
|
118
|
+
inFlight.add(task);
|
|
119
|
+
void task.finally(() => inFlight.delete(task));
|
|
120
|
+
});
|
|
121
|
+
// A broken stream ends the session instead of crashing the process.
|
|
122
|
+
const onInputError = (err: unknown): void => {
|
|
123
|
+
warn(`input error: ${errorMessage(err)}`);
|
|
124
|
+
rl.close();
|
|
125
|
+
};
|
|
126
|
+
const onOutputError = (err: unknown): void => {
|
|
127
|
+
warn(`output error: ${errorMessage(err)}`);
|
|
128
|
+
rl.close();
|
|
129
|
+
};
|
|
130
|
+
input.on('error', onInputError);
|
|
131
|
+
output.on('error', onOutputError);
|
|
132
|
+
|
|
133
|
+
const done = new Promise<void>((resolve) => {
|
|
134
|
+
rl.once('close', () => {
|
|
135
|
+
void drain(inFlight).then(() => {
|
|
136
|
+
input.off('error', onInputError);
|
|
137
|
+
output.off('error', onOutputError);
|
|
138
|
+
resolve();
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
done,
|
|
145
|
+
close() {
|
|
146
|
+
rl.close();
|
|
147
|
+
return done;
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Picks the dispatch function for a bridge or a handler. */
|
|
153
|
+
function resolveServe(
|
|
154
|
+
target: McpBridge | McpHandler,
|
|
155
|
+
mount: McpMountOptions | undefined,
|
|
156
|
+
): Serve {
|
|
157
|
+
if (typeof target === 'function') {
|
|
158
|
+
if (mount !== undefined) {
|
|
159
|
+
throw new TypeError(
|
|
160
|
+
'serveStdio: mount options apply to a bridge; a handler carries its own',
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const factory = dispatcherFactoryOf(target);
|
|
164
|
+
if (factory !== undefined) {
|
|
165
|
+
const dispatcher = factory('stdio');
|
|
166
|
+
return (req, rpc) => dispatcher.dispatch(req, rpc);
|
|
167
|
+
}
|
|
168
|
+
return (req) => target(req);
|
|
169
|
+
}
|
|
170
|
+
const dispatcher = new McpDispatcher(target, resolveMcpConfig(mount ?? {}), 'stdio');
|
|
171
|
+
return (req, rpc) => dispatcher.dispatch(req, rpc);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Waits until no request is in flight, including ones added meanwhile. */
|
|
175
|
+
async function drain(inFlight: Set<Promise<void>>): Promise<void> {
|
|
176
|
+
while (inFlight.size > 0) {
|
|
177
|
+
await Promise.allSettled([...inFlight]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Frames, parses and dispatches one input line. Returns the pending
|
|
183
|
+
* work for a dispatched message, or undefined when the line was
|
|
184
|
+
* answered (or dropped) synchronously.
|
|
185
|
+
*/
|
|
186
|
+
function handleLine(
|
|
187
|
+
line: string,
|
|
188
|
+
serve: Serve,
|
|
189
|
+
write: (line: string) => void,
|
|
190
|
+
warn: (msg: string) => void,
|
|
191
|
+
): Promise<void> | undefined {
|
|
192
|
+
const text = line.trim();
|
|
193
|
+
if (text === '') return undefined;
|
|
194
|
+
|
|
195
|
+
let decoded: unknown;
|
|
196
|
+
try {
|
|
197
|
+
decoded = JSON.parse(text);
|
|
198
|
+
} catch {
|
|
199
|
+
write(errorLine(null, { code: MCP_ERR_PARSE, message: `parse error: ${goJSONParseMessage(text)}` }));
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
if (Array.isArray(decoded)) {
|
|
203
|
+
write(errorLine(null, {
|
|
204
|
+
code: MCP_ERR_INVALID_REQUEST,
|
|
205
|
+
message: 'invalid request: batch requests are not supported',
|
|
206
|
+
}));
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
if (decoded === null || typeof decoded !== 'object') {
|
|
210
|
+
write(errorLine(null, {
|
|
211
|
+
code: MCP_ERR_INVALID_REQUEST,
|
|
212
|
+
message: 'invalid request: not a JSON-RPC object',
|
|
213
|
+
}));
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const obj = decoded as Record<string, unknown>;
|
|
218
|
+
const rpc = parseJsonRpcRequest(text);
|
|
219
|
+
const isNotification = rpc.id === undefined;
|
|
220
|
+
|
|
221
|
+
if (typeof obj.method !== 'string') {
|
|
222
|
+
// A response (result / error, no method): this server sends no
|
|
223
|
+
// requests, so there is nothing to correlate it with.
|
|
224
|
+
if ('result' in obj || 'error' in obj) {
|
|
225
|
+
warn('ignored a JSON-RPC response from the client');
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
if (isNotification) return undefined;
|
|
229
|
+
write(errorLine(rpc.id, {
|
|
230
|
+
code: MCP_ERR_INVALID_REQUEST,
|
|
231
|
+
message: 'invalid request: missing method',
|
|
232
|
+
}));
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const req: McpHttpRequest = { method: 'POST', body: text };
|
|
237
|
+
return serve(req, rpc).then(
|
|
238
|
+
(res) => {
|
|
239
|
+
// A notification is never answered, whatever the handler said.
|
|
240
|
+
if (isNotification || res.body === '') return;
|
|
241
|
+
write(res.body);
|
|
242
|
+
},
|
|
243
|
+
(err: unknown) => {
|
|
244
|
+
warn(`${rpc.method}: ${errorMessage(err)}`);
|
|
245
|
+
if (isNotification) return;
|
|
246
|
+
write(errorLine(rpc.id, { code: MCP_ERR_INTERNAL, message: 'internal error' }));
|
|
247
|
+
},
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** One JSON-RPC error line; `null` renders `"id":null`. */
|
|
252
|
+
function errorLine(id: RawJSON | null | undefined, error: JsonRpcErrorObject): string {
|
|
253
|
+
return encodeEnvelope({ id: id === null ? new RawJSON('null') : id, error });
|
|
254
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The toolNameSeparator mount option: tool names join the leaf path
|
|
3
|
+
* with it in tools/list, resolve back through it on tools/call (both
|
|
4
|
+
* eras), and a separator a command name contains fails the mount.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it } from 'vitest';
|
|
8
|
+
|
|
9
|
+
import { createMcpHandler } from './dispatch.js';
|
|
10
|
+
import { ElicitationConfirmGate } from './modern-confirm.js';
|
|
11
|
+
import { legacyLockBridge, modernLockBridge } from './testtree.js';
|
|
12
|
+
import {
|
|
13
|
+
pathFromToolName,
|
|
14
|
+
resolveMcpConfig,
|
|
15
|
+
toolName,
|
|
16
|
+
type McpBridge,
|
|
17
|
+
} from './types.js';
|
|
18
|
+
|
|
19
|
+
const MODERN_META = {
|
|
20
|
+
'io.modelcontextprotocol/clientCapabilities': {},
|
|
21
|
+
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function post(body: unknown, headers: Record<string, string> = {}) {
|
|
25
|
+
return { method: 'POST', headers, body: JSON.stringify(body) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function listNames(
|
|
29
|
+
bridge: McpBridge,
|
|
30
|
+
opts: Parameters<typeof createMcpHandler>[1],
|
|
31
|
+
): Promise<string[]> {
|
|
32
|
+
const res = await createMcpHandler(bridge, opts)(
|
|
33
|
+
post({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
|
|
34
|
+
);
|
|
35
|
+
const tools = JSON.parse(res.body).result.tools as Array<{ name: string }>;
|
|
36
|
+
return tools.map((t) => t.name);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A bridge whose leaf `data_sync` and leaf `data sync` read alike under "_". */
|
|
40
|
+
function collidingBridge(): McpBridge {
|
|
41
|
+
return {
|
|
42
|
+
leaves: () => [
|
|
43
|
+
{ path: ['data', 'sync'], description: 'Sync', properties: {} },
|
|
44
|
+
{ path: ['data_sync'], description: 'Sync too', properties: {} },
|
|
45
|
+
],
|
|
46
|
+
invoke: () => ({ exitCode: 0, stdout: '' }),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('toolName / pathFromToolName', () => {
|
|
51
|
+
it('join and split on "." by default', () => {
|
|
52
|
+
expect(toolName(['widget', 'add'])).toBe('widget.add');
|
|
53
|
+
expect(pathFromToolName('widget.add')).toEqual(['widget', 'add']);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('join and split on a given separator symmetrically', () => {
|
|
57
|
+
for (const sep of ['_', '-', '__']) {
|
|
58
|
+
const name = toolName(['widget', 'add'], sep);
|
|
59
|
+
expect(name).toBe(`widget${sep}add`);
|
|
60
|
+
expect(pathFromToolName(name, sep)).toEqual(['widget', 'add']);
|
|
61
|
+
}
|
|
62
|
+
expect(pathFromToolName('', '_')).toEqual([]);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('toolNameSeparator mount option', () => {
|
|
67
|
+
it('defaults to "."', async () => {
|
|
68
|
+
expect(resolveMcpConfig().toolNameSeparator).toBe('.');
|
|
69
|
+
expect(await listNames(legacyLockBridge(), {})).toContain('widget.add');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('renames listed tools', async () => {
|
|
73
|
+
for (const sep of ['_', '-']) {
|
|
74
|
+
const names = await listNames(legacyLockBridge(), { toolNameSeparator: sep });
|
|
75
|
+
expect(names).toContain(`widget${sep}add`);
|
|
76
|
+
expect(names).toContain(`widget${sep}delete`);
|
|
77
|
+
expect(names).toContain('ping');
|
|
78
|
+
expect(names).not.toContain('widget.add');
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('resolves a legacy tools/call through the separator', async () => {
|
|
83
|
+
const handler = createMcpHandler(legacyLockBridge(), { toolNameSeparator: '_' });
|
|
84
|
+
const call = (name: string) =>
|
|
85
|
+
handler(
|
|
86
|
+
post({
|
|
87
|
+
jsonrpc: '2.0',
|
|
88
|
+
id: 2,
|
|
89
|
+
method: 'tools/call',
|
|
90
|
+
params: { name, arguments: { name: 'bolt' } },
|
|
91
|
+
}),
|
|
92
|
+
);
|
|
93
|
+
const ok = JSON.parse((await call('widget_add')).body);
|
|
94
|
+
expect(ok.result.isError).toBe(false);
|
|
95
|
+
const dotted = JSON.parse((await call('widget.add')).body);
|
|
96
|
+
expect(dotted.error.message).toContain('unknown tool: widget.add');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('resolves a modern tools/call through the separator', async () => {
|
|
100
|
+
const handler = createMcpHandler(modernLockBridge(), { toolNameSeparator: '-' });
|
|
101
|
+
const res = await handler(
|
|
102
|
+
post(
|
|
103
|
+
{
|
|
104
|
+
jsonrpc: '2.0',
|
|
105
|
+
id: 3,
|
|
106
|
+
method: 'tools/call',
|
|
107
|
+
params: { name: 'widget-add', arguments: { name: 'bolt' }, _meta: MODERN_META },
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
'MCP-Protocol-Version': '2026-07-28',
|
|
111
|
+
'Mcp-Method': 'tools/call',
|
|
112
|
+
'Mcp-Name': 'widget-add',
|
|
113
|
+
},
|
|
114
|
+
),
|
|
115
|
+
);
|
|
116
|
+
const body = JSON.parse(res.body);
|
|
117
|
+
expect(body.error).toBeUndefined();
|
|
118
|
+
expect(body.result.isError).toBe(false);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('names the tool under the separator in the confirmation prompt', () => {
|
|
122
|
+
const gate = new ElicitationConfirmGate(new TextEncoder().encode('k'), '_');
|
|
123
|
+
const out = gate.inputRequired(
|
|
124
|
+
{ path: ['vault', 'burn'], description: '', properties: {} },
|
|
125
|
+
{ tool: 'vault burn', argsDigest: '', principal: '' },
|
|
126
|
+
) as { inputRequests: { confirm: { params: { message: string } } } };
|
|
127
|
+
expect(out.inputRequests.confirm.params.message).toBe(
|
|
128
|
+
'Approve execution of "vault_burn"?',
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('refuses an empty separator at mount', () => {
|
|
133
|
+
expect(() => createMcpHandler(legacyLockBridge(), { toolNameSeparator: '' })).toThrow(
|
|
134
|
+
'cmdsurface: toolNameSeparator: empty separator',
|
|
135
|
+
);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('refuses a separator a command name contains', () => {
|
|
139
|
+
expect(() => createMcpHandler(collidingBridge(), { toolNameSeparator: '_' })).toThrow(
|
|
140
|
+
'cmdsurface: toolNameSeparator: command "data_sync" in "data_sync" contains separator "_"',
|
|
141
|
+
);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('accepts a separator no command name contains', () => {
|
|
145
|
+
expect(() => createMcpHandler(collidingBridge(), { toolNameSeparator: '-' })).not.toThrow();
|
|
146
|
+
});
|
|
147
|
+
});
|
package/src/mcp/types.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
SERVER_INFO_META_KEY,
|
|
23
23
|
} from '@modelcontextprotocol/server';
|
|
24
24
|
|
|
25
|
+
import { mcpInputSchema, mcpToolDescription } from './args.js';
|
|
25
26
|
import type { McpHttpRequest } from './dispatch.js';
|
|
26
27
|
|
|
27
28
|
// --- protocol constants -------------------------------------------------
|
|
@@ -78,6 +79,8 @@ export type McpCacheScope = 'public' | 'private';
|
|
|
78
79
|
export const DEFAULT_MCP_SERVER_NAME = 'cmdsurface';
|
|
79
80
|
export const DEFAULT_MCP_SERVER_VERSION = '0.0.0';
|
|
80
81
|
export const DEFAULT_MCP_PATH = '/mcp';
|
|
82
|
+
/** Default string joining a leaf path into its MCP tool name. */
|
|
83
|
+
export const DEFAULT_TOOL_NAME_SEPARATOR = '.';
|
|
81
84
|
|
|
82
85
|
// --- safety gate --------------------------------------------------------
|
|
83
86
|
|
|
@@ -190,7 +193,20 @@ export class SurfaceNotEnabledError extends Error {
|
|
|
190
193
|
export interface FlagSchema {
|
|
191
194
|
type: string;
|
|
192
195
|
description: string;
|
|
193
|
-
items?: { type: string };
|
|
196
|
+
items?: { type: string; enum?: string[] };
|
|
197
|
+
/** Allowed values, when the flag declares choices. */
|
|
198
|
+
enum?: string[];
|
|
199
|
+
/** The flag's default, when it is a value of `type`. */
|
|
200
|
+
default?: unknown;
|
|
201
|
+
/** Least array length; set on the positional "args" property. */
|
|
202
|
+
minItems?: number;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** One declared positional argument of a leaf, in declared order. */
|
|
206
|
+
export interface LeafArg {
|
|
207
|
+
name: string;
|
|
208
|
+
/** False/absent for an optional argument. */
|
|
209
|
+
required?: boolean;
|
|
194
210
|
}
|
|
195
211
|
|
|
196
212
|
/**
|
|
@@ -206,6 +222,12 @@ export interface Leaf {
|
|
|
206
222
|
properties: Record<string, FlagSchema>;
|
|
207
223
|
/** Names of required flags, in declaration order. */
|
|
208
224
|
required?: string[];
|
|
225
|
+
/**
|
|
226
|
+
* Declared positional arguments, in order. Published as one "args"
|
|
227
|
+
* string-array property and split back out of tools/call arguments
|
|
228
|
+
* into `Invocation.args` (see mcp/args).
|
|
229
|
+
*/
|
|
230
|
+
args?: LeafArg[];
|
|
209
231
|
/** Safety annotations consulted by the policy gate. */
|
|
210
232
|
class?: SafetyClass;
|
|
211
233
|
/** Surfaces this leaf is exposed on. */
|
|
@@ -244,6 +266,8 @@ export interface InvocationMeta {
|
|
|
244
266
|
/** One leaf invocation. */
|
|
245
267
|
export interface Invocation {
|
|
246
268
|
path: string[];
|
|
269
|
+
/** Positional arguments in declared order, from the "args" property. */
|
|
270
|
+
args?: string[];
|
|
247
271
|
flags?: Record<string, unknown>;
|
|
248
272
|
meta: InvocationMeta;
|
|
249
273
|
}
|
|
@@ -311,6 +335,43 @@ export type McpVerifier = (
|
|
|
311
335
|
/** The challenge a 401 carries in WWW-Authenticate, as Go's api.DefaultAuthChallenge. */
|
|
312
336
|
export const MCP_AUTH_CHALLENGE = 'Bearer';
|
|
313
337
|
|
|
338
|
+
// --- refusal audit ------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* One refusal the surface decided before adopter code ran: the record
|
|
342
|
+
* Go's bridge sinks receive from the MCP surface, reduced to the
|
|
343
|
+
* fields the surface has (a `cmdsurface.Invocation` subset plus the
|
|
344
|
+
* error). No caller, arguments or flags travel on it, so there is
|
|
345
|
+
* nothing to redact.
|
|
346
|
+
*/
|
|
347
|
+
export interface McpAuditRecord {
|
|
348
|
+
/** The resolved leaf path, e.g. `["widget","delete"]`. */
|
|
349
|
+
path: string[];
|
|
350
|
+
surface: 'mcp';
|
|
351
|
+
/** When the refusal was decided. */
|
|
352
|
+
requestedAt: Date;
|
|
353
|
+
/** The protocol revision serving the request. */
|
|
354
|
+
specVersion: string;
|
|
355
|
+
/**
|
|
356
|
+
* Go's sentinel error message for the event, verbatim (see the
|
|
357
|
+
* `MCP_AUDIT_*` constants in `mcp/audit`).
|
|
358
|
+
*/
|
|
359
|
+
error: string;
|
|
360
|
+
/**
|
|
361
|
+
* Always `mcp_spec_version`; `mcp_confirm_rejection` on a rejected
|
|
362
|
+
* `requestState`. Keys are the Go snake_case strings so the records
|
|
363
|
+
* forward to the same audit backends.
|
|
364
|
+
*/
|
|
365
|
+
extra: Record<string, string>;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The mount-level audit hook. Called synchronously once per refusal,
|
|
370
|
+
* after the refusal is decided and before the response is returned.
|
|
371
|
+
* Best-effort: a throwing hook never changes the wire response.
|
|
372
|
+
*/
|
|
373
|
+
export type McpAuditHook = (record: McpAuditRecord) => void;
|
|
374
|
+
|
|
314
375
|
// --- mount options ------------------------------------------------------
|
|
315
376
|
|
|
316
377
|
/**
|
|
@@ -341,6 +402,23 @@ export interface McpMountOptions {
|
|
|
341
402
|
* is established, so every `kit/auth-required` leaf is refused.
|
|
342
403
|
*/
|
|
343
404
|
verifier?: McpVerifier;
|
|
405
|
+
/**
|
|
406
|
+
* Joins a leaf path into its tool name, and splits a called name
|
|
407
|
+
* back. Default ".". `"_"` names the leaf `widget add` `widget_add`,
|
|
408
|
+
* for hosts that admit only `^[A-Za-z0-9_-]{1,64}$`. Empty is a
|
|
409
|
+
* mount-time error, and so is any separator but the default that a
|
|
410
|
+
* command name contains: the name would not map back to one leaf.
|
|
411
|
+
*/
|
|
412
|
+
toolNameSeparator?: string;
|
|
413
|
+
/**
|
|
414
|
+
* Receives one {@link McpAuditRecord} per refusal the surface
|
|
415
|
+
* decides: auth refused, confirmation required / declined / state
|
|
416
|
+
* rejected, destructive ceiling. The counterpart of Go's bridge
|
|
417
|
+
* sinks for the MCP surface. Best-effort: it runs after the refusal
|
|
418
|
+
* is decided, before the response is returned, and a throw is
|
|
419
|
+
* swallowed.
|
|
420
|
+
*/
|
|
421
|
+
audit?: McpAuditHook;
|
|
344
422
|
}
|
|
345
423
|
|
|
346
424
|
/** Resolved, validated mount configuration. */
|
|
@@ -356,6 +434,8 @@ export interface ResolvedMcpConfig {
|
|
|
356
434
|
confirmationKey?: Uint8Array;
|
|
357
435
|
policy: Policy;
|
|
358
436
|
verifier?: McpVerifier;
|
|
437
|
+
toolNameSeparator: string;
|
|
438
|
+
audit?: McpAuditHook;
|
|
359
439
|
}
|
|
360
440
|
|
|
361
441
|
/**
|
|
@@ -419,6 +499,11 @@ export function resolveMcpConfig(
|
|
|
419
499
|
confirmationKey = key;
|
|
420
500
|
}
|
|
421
501
|
|
|
502
|
+
const toolNameSeparator = opts.toolNameSeparator ?? DEFAULT_TOOL_NAME_SEPARATOR;
|
|
503
|
+
if (toolNameSeparator === '') {
|
|
504
|
+
throw new Error('cmdsurface: toolNameSeparator: empty separator');
|
|
505
|
+
}
|
|
506
|
+
|
|
422
507
|
return {
|
|
423
508
|
path: opts.path ?? DEFAULT_MCP_PATH,
|
|
424
509
|
serverName: opts.serverInfo?.name ?? DEFAULT_MCP_SERVER_NAME,
|
|
@@ -431,35 +516,57 @@ export function resolveMcpConfig(
|
|
|
431
516
|
confirmationKey,
|
|
432
517
|
policy: opts.policy ?? defaultPolicy(),
|
|
433
518
|
verifier: opts.verifier,
|
|
519
|
+
toolNameSeparator,
|
|
520
|
+
audit: opts.audit,
|
|
434
521
|
};
|
|
435
522
|
}
|
|
436
523
|
|
|
437
524
|
// --- tool naming --------------------------------------------------------
|
|
438
525
|
|
|
439
|
-
/** Renders a leaf path as
|
|
440
|
-
export function toolName(
|
|
441
|
-
|
|
526
|
+
/** Renders a leaf path as an MCP tool name, joined with `separator`. */
|
|
527
|
+
export function toolName(
|
|
528
|
+
path: string[],
|
|
529
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
530
|
+
): string {
|
|
531
|
+
return path.join(separator);
|
|
442
532
|
}
|
|
443
533
|
|
|
444
|
-
/** Splits
|
|
445
|
-
export function pathFromToolName(
|
|
534
|
+
/** Splits an MCP tool name back into a leaf path on `separator`. */
|
|
535
|
+
export function pathFromToolName(
|
|
536
|
+
name: string,
|
|
537
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
538
|
+
): string[] {
|
|
446
539
|
if (name === '') return [];
|
|
447
|
-
return name.split(
|
|
540
|
+
return name.split(separator);
|
|
448
541
|
}
|
|
449
542
|
|
|
450
|
-
/**
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
543
|
+
/**
|
|
544
|
+
* Refuses, for any separator but the default, a leaf whose command
|
|
545
|
+
* name contains it: its tool name would not split back to one leaf.
|
|
546
|
+
*/
|
|
547
|
+
export function checkToolNameSeparator(leaves: Leaf[], separator: string): void {
|
|
548
|
+
if (separator === DEFAULT_TOOL_NAME_SEPARATOR) return;
|
|
549
|
+
for (const leaf of leaves) {
|
|
550
|
+
for (const seg of leaf.path) {
|
|
551
|
+
if (seg.includes(separator)) {
|
|
552
|
+
throw new Error(
|
|
553
|
+
`cmdsurface: toolNameSeparator: command ${JSON.stringify(seg)} in ` +
|
|
554
|
+
`${JSON.stringify(leaf.path.join(' '))} contains separator ${JSON.stringify(separator)}`,
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
458
558
|
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Renders one leaf as an MCP tool descriptor (shared by both eras). */
|
|
562
|
+
export function buildToolEnvelope(
|
|
563
|
+
leaf: Leaf,
|
|
564
|
+
separator: string = DEFAULT_TOOL_NAME_SEPARATOR,
|
|
565
|
+
): Record<string, unknown> {
|
|
459
566
|
return {
|
|
460
|
-
name: toolName(leaf.path),
|
|
461
|
-
description: leaf
|
|
462
|
-
inputSchema:
|
|
567
|
+
name: toolName(leaf.path, separator),
|
|
568
|
+
description: mcpToolDescription(leaf),
|
|
569
|
+
inputSchema: mcpInputSchema(leaf),
|
|
463
570
|
};
|
|
464
571
|
}
|
|
465
572
|
|
package/src/toolspec-internal.ts
CHANGED
|
@@ -22,6 +22,30 @@ export function splitCSV(s: string | undefined): string[] | undefined {
|
|
|
22
22
|
|
|
23
23
|
// --- commander facts ---
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* cmd's declared positional arguments (commander registeredArguments),
|
|
27
|
+
* in order, `required` set only on required ones. Shared by the
|
|
28
|
+
* toolspec projection and the MCP bridge so both read positionals
|
|
29
|
+
* the same way.
|
|
30
|
+
*/
|
|
31
|
+
export function declaredArgs(
|
|
32
|
+
cmd: CommanderCommand,
|
|
33
|
+
): Array<{ name: string; required?: boolean }> {
|
|
34
|
+
return cmd.registeredArguments.map((a) =>
|
|
35
|
+
a.required ? { name: a.name(), required: true } : { name: a.name() },
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether opt takes no value: a plain boolean flag or a negated one
|
|
41
|
+
* (`--no-x`). commander's isBoolean() is false for negated options,
|
|
42
|
+
* yet they are value-less all the same, so pflag-shaped projections
|
|
43
|
+
* (a `no-x` bool) must not rely on isBoolean() alone.
|
|
44
|
+
*/
|
|
45
|
+
export function takesNoValue(opt: CommanderOption): boolean {
|
|
46
|
+
return !opt.required && !opt.optional;
|
|
47
|
+
}
|
|
48
|
+
|
|
25
49
|
/**
|
|
26
50
|
* Whether cmd has an action handler (cobra Runnable). commander 15
|
|
27
51
|
* exposes no public accessor, so this reads the private field.
|
|
@@ -80,3 +80,28 @@ describe("negotiateSchemaVersion", () => {
|
|
|
80
80
|
expect(SCHEMA_VERSION_ENV).toBe("KIT_TOOLSPEC_SCHEMA");
|
|
81
81
|
});
|
|
82
82
|
});
|
|
83
|
+
|
|
84
|
+
describe("buildManifest negatable flags", () => {
|
|
85
|
+
it("types --no-x bool with default false, as pflag does", () => {
|
|
86
|
+
const program = new Command("t");
|
|
87
|
+
program
|
|
88
|
+
.command("run")
|
|
89
|
+
.option("--no-color", "c")
|
|
90
|
+
.option("--hints", "on")
|
|
91
|
+
.option("--no-hints", "off")
|
|
92
|
+
.action(() => {});
|
|
93
|
+
expect(buildManifest(program, "1.1").commands[0].flags).toEqual([
|
|
94
|
+
{ name: "hints", type: "bool", description: "on", default: "false" },
|
|
95
|
+
{ name: "no-color", type: "bool", description: "c", default: "false" },
|
|
96
|
+
{ name: "no-hints", type: "bool", description: "off", default: "false" },
|
|
97
|
+
]);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("keeps a negated flag's default false whatever commander's default", () => {
|
|
101
|
+
const program = new Command("t");
|
|
102
|
+
program.command("run").option("--no-cache", "nc", true).action(() => {});
|
|
103
|
+
expect(buildManifest(program, "1.1").commands[0].flags).toEqual([
|
|
104
|
+
{ name: "no-cache", type: "bool", description: "nc", default: "false" },
|
|
105
|
+
]);
|
|
106
|
+
});
|
|
107
|
+
});
|