@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.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @module mcp/audit
3
+ * @package @hop-top/kit
4
+ *
5
+ * The refusal audit hook: the counterpart, for the MCP surface, of the
6
+ * bridge sinks Go's `cmdsurface` fans every refusal out to. Go audits
7
+ * each refusal the surface makes before adopter code runs (`Bridge.Audit`
8
+ * from `mcpsdk`'s gates and the bridge's own `refuse`); this port has no
9
+ * sink registry, so one mount-level hook receives the same record.
10
+ *
11
+ * Contract, shared by every kit SDK: the hook is called synchronously
12
+ * after the refusal is decided and before the response is returned (Go's
13
+ * order: audit, then respond); it is best-effort, so a throw is swallowed
14
+ * and the wire response is never affected; and the `error` field carries
15
+ * Go's sentinel message verbatim, so adopters forwarding to a backend
16
+ * that already receives Go's sinks see one vocabulary.
17
+ */
18
+
19
+ import type { McpAuditHook, McpAuditRecord } from './types.js';
20
+
21
+ /** `cmdsurface.ErrAuthRefused`: a `kit/auth-required` leaf, no established caller. */
22
+ export const MCP_AUDIT_AUTH_REFUSED = 'cmdsurface: authentication refused';
23
+
24
+ /** `mcpsdk.ErrConfirmationRequired`: nothing satisfied the confirmation gate. */
25
+ export const MCP_AUDIT_CONFIRMATION_REQUIRED = 'mcpsdk: confirmation required';
26
+
27
+ /** `mcpsdk.ErrConfirmationDeclined`: the client's user declined or dismissed the question. */
28
+ export const MCP_AUDIT_CONFIRMATION_DECLINED = 'mcpsdk: confirmation declined';
29
+
30
+ /** `mcpsdk.ErrConfirmationStateRejected`: a presented `requestState` failed verification. */
31
+ export const MCP_AUDIT_CONFIRMATION_STATE_REJECTED =
32
+ 'mcpsdk: confirmation requestState failed verification';
33
+
34
+ /** `cmdsurface.ErrDestructiveBlocked`: the leaf's destructiveness exceeds the policy ceiling. */
35
+ export const MCP_AUDIT_DESTRUCTIVE_BLOCKED =
36
+ 'cmdsurface: destructive command blocked on this surface';
37
+
38
+ /** The `mcp_confirm_rejection` value a rejected `requestState` carries, as in Go. */
39
+ export const MCP_CONFIRM_REJECTION_STATE = 'request_state_verification_failed';
40
+
41
+ /**
42
+ * Emits one refusal record to `hook`, when there is one. Builds the
43
+ * record here so every call site carries the same shape: the surface
44
+ * pinned to `mcp`, the time the refusal was decided, and `extra`
45
+ * always carrying `mcp_spec_version` ahead of any event-specific key.
46
+ * A throwing hook is swallowed: audit must never turn a refusal into
47
+ * a different refusal.
48
+ */
49
+ export function auditRefusal(
50
+ hook: McpAuditHook | undefined,
51
+ path: string[],
52
+ specVersion: string,
53
+ error: string,
54
+ extra?: Record<string, string>,
55
+ ): void {
56
+ if (hook === undefined) return;
57
+ const record: McpAuditRecord = {
58
+ path: [...path],
59
+ surface: 'mcp',
60
+ requestedAt: new Date(),
61
+ specVersion,
62
+ error,
63
+ extra: { mcp_spec_version: specVersion, ...(extra ?? {}) },
64
+ };
65
+ try {
66
+ hook(record);
67
+ } catch {
68
+ // Best-effort by contract: the response is already decided.
69
+ }
70
+ }
@@ -73,6 +73,78 @@ describe('commanderBridge', () => {
73
73
  expect(add?.properties).not.toHaveProperty('hidden-flag');
74
74
  });
75
75
 
76
+ it('types a negated flag as a boolean under its own long name', () => {
77
+ const root = new Command('root');
78
+ root.command('find').option('--no-color', 'plain output');
79
+ const bridge = commanderBridge(root, { run });
80
+ expect(bridge.leaves()[0]?.properties).toEqual({
81
+ 'no-color': { type: 'boolean', description: 'plain output' },
82
+ });
83
+ });
84
+
85
+ it('keeps a flag and its negation as two booleans', () => {
86
+ const root = new Command('root');
87
+ root.command('find').option('--cache', 'use cache').option('--no-cache', 'skip cache');
88
+ const bridge = commanderBridge(root, { run });
89
+ expect(bridge.leaves()[0]?.properties).toEqual({
90
+ cache: { type: 'boolean', description: 'use cache' },
91
+ 'no-cache': { type: 'boolean', description: 'skip cache' },
92
+ });
93
+ });
94
+
95
+ it('types a repeatable accumulator option as an array of strings', () => {
96
+ const root = new Command('root');
97
+ root
98
+ .command('find')
99
+ .option('-m, --match <p>', 'match pattern', (v: string, p: string[]) => p.concat([v]), []);
100
+ const bridge = commanderBridge(root, { run });
101
+ expect(bridge.leaves()[0]?.properties).toEqual({
102
+ match: {
103
+ type: 'array',
104
+ description: 'match pattern',
105
+ items: { type: 'string' },
106
+ default: [],
107
+ },
108
+ });
109
+ });
110
+
111
+ it('keeps a custom-parsed scalar option a string', () => {
112
+ const root = new Command('root');
113
+ root.command('find').option('--limit <n>', 'max rows', (v: string) => Number(v));
114
+ const bridge = commanderBridge(root, { run });
115
+ expect(bridge.leaves()[0]?.properties).toEqual({
116
+ limit: { type: 'string', description: 'max rows' },
117
+ });
118
+ });
119
+
120
+ it('publishes choices as enum and string defaults as default', () => {
121
+ const root = new Command('root');
122
+ root
123
+ .command('find')
124
+ .addOption(new Option('--color <c>', 'tint').choices(['red', 'blue']).default('red'))
125
+ .addOption(new Option('--tag <t...>', 'tags').choices(['a', 'b']))
126
+ .option('--sort <k>', 'sort key', 'name');
127
+ const bridge = commanderBridge(root, { run });
128
+ expect(bridge.leaves()[0]?.properties).toEqual({
129
+ color: { type: 'string', description: 'tint', enum: ['red', 'blue'], default: 'red' },
130
+ tag: { type: 'array', description: 'tags', items: { type: 'string', enum: ['a', 'b'] } },
131
+ sort: { type: 'string', description: 'sort key', default: 'name' },
132
+ });
133
+ });
134
+
135
+ it('omits a default whose type does not match the schema type', () => {
136
+ const root = new Command('root');
137
+ root
138
+ .command('find')
139
+ .option('--limit <n>', 'max rows', (v: string) => Number(v), 10)
140
+ .option('--fast', 'go fast', false);
141
+ const bridge = commanderBridge(root, { run });
142
+ expect(bridge.leaves()[0]?.properties).toEqual({
143
+ limit: { type: 'string', description: 'max rows' },
144
+ fast: { type: 'boolean', description: 'go fast', default: false },
145
+ });
146
+ });
147
+
76
148
  it('classifies kit annotations into the SafetyClass', () => {
77
149
  const bridge = commanderBridge(buildTree(), { run });
78
150
  const byName = (n: string) =>
package/src/mcp/bridge.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { Command, Option } from 'commander';
20
+ import { declaredArgs, takesNoValue } from '../toolspec-internal.js';
20
21
  import {
21
22
  DestructiveBlockedError,
22
23
  policyAllowed,
@@ -82,6 +83,8 @@ export function commanderBridge(
82
83
  ...collectFlags(cmd),
83
84
  class: classify(cmd as AnnotatedCommand),
84
85
  };
86
+ const args = declaredArgs(cmd);
87
+ if (args.length > 0) leaf.args = args;
85
88
  const en = opts.enabled?.(leaf);
86
89
  if (en) leaf.enabled = en;
87
90
  out.push(leaf);
@@ -230,17 +233,59 @@ function flagProperty(opt: Option): FlagSchema {
230
233
  type,
231
234
  description: opt.description ?? '',
232
235
  };
233
- if (type === 'array') prop.items = { type: 'string' };
236
+ const choices = opt.argChoices;
237
+ if (type === 'array') {
238
+ prop.items = { type: 'string' };
239
+ if (choices && choices.length > 0) prop.items.enum = [...choices];
240
+ } else if (type === 'string' && choices && choices.length > 0) {
241
+ prop.enum = [...choices];
242
+ }
243
+ if (defaultMatches(type, opt.defaultValue)) {
244
+ prop.default = Array.isArray(opt.defaultValue)
245
+ ? [...(opt.defaultValue as string[])]
246
+ : opt.defaultValue;
247
+ }
234
248
  return prop;
235
249
  }
236
250
 
237
251
  /**
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.
252
+ * Maps a commander option to a JSON Schema primitive.
253
+ *
254
+ * - variadic (`<v...>`) and accumulator options (a custom parser
255
+ * with an array default, commander's repeatable idiom) are arrays
256
+ * of strings;
257
+ * - value-less flags are booleans, negated ones (`--no-x`) included:
258
+ * commander's isBoolean() is false for those, but they take no
259
+ * value all the same;
260
+ * - everything else is a string.
261
+ *
262
+ * A negated flag keeps its long name (`no-x`), like every other
263
+ * property, so `{"no-x": true}` maps back to `--no-x` verbatim.
241
264
  */
242
265
  function optionJSONType(opt: Option): string {
243
266
  if (opt.variadic) return 'array';
244
- if (typeof opt.isBoolean === 'function' && opt.isBoolean()) return 'boolean';
267
+ if (opt.parseArg !== undefined && Array.isArray(opt.defaultValue)) {
268
+ return 'array';
269
+ }
270
+ if (takesNoValue(opt)) return 'boolean';
245
271
  return 'string';
246
272
  }
273
+
274
+ /**
275
+ * Reports whether a commander default is publishable as the JSON
276
+ * Schema `default` of a property typed `type`. A default the schema
277
+ * type cannot hold (a parsed number on a string-typed option) is left
278
+ * out rather than published as a value the property would reject.
279
+ */
280
+ function defaultMatches(type: string, value: unknown): boolean {
281
+ switch (type) {
282
+ case 'string':
283
+ return typeof value === 'string';
284
+ case 'boolean':
285
+ return typeof value === 'boolean';
286
+ case 'array':
287
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
288
+ default:
289
+ return false;
290
+ }
291
+ }
@@ -135,7 +135,7 @@ describe('MCP wire conformance (cross-language fixtures)', () => {
135
135
  const doc = loadFixtures();
136
136
 
137
137
  it('loads the full fixture set', () => {
138
- expect(doc.cases.length).toBe(23);
138
+ expect(doc.cases.length).toBe(26);
139
139
  });
140
140
 
141
141
  for (const c of doc.cases) {
@@ -28,6 +28,7 @@ import {
28
28
  META_KEY_PROTOCOL_VERSION,
29
29
  HEADER_MCP_METHOD,
30
30
  HEADER_MCP_NAME,
31
+ checkToolNameSeparator,
31
32
  RawJSON,
32
33
  resolveMcpConfig,
33
34
  type McpBridge,
@@ -97,6 +98,13 @@ export interface JsonRpcRequest {
97
98
  /** Which handler a request routes to. */
98
99
  export type McpEra = 'legacy' | 'modern';
99
100
 
101
+ /**
102
+ * The binding a dispatcher serves. `http` (Streamable HTTP) validates
103
+ * the 2026-07-28 routing headers against the body; `stdio` has no
104
+ * header layer, so the body is the only source of truth.
105
+ */
106
+ export type McpTransport = 'http' | 'stdio';
107
+
100
108
  /**
101
109
  * Implements per-request era detection, precedence D1-D4.
102
110
  * Never fails — it only classifies an already-parsed request; D1
@@ -170,6 +178,30 @@ export type McpHandler = (
170
178
  req: McpHttpRequest,
171
179
  ) => Promise<McpHttpResponse>;
172
180
 
181
+ /**
182
+ * Where createMcpHandler records how to rebuild its dispatcher for
183
+ * another transport, so serveStdio can drive a handler's own bridge and
184
+ * mount options without fabricating HTTP headers.
185
+ */
186
+ export const MCP_DISPATCHER_FACTORY: unique symbol = Symbol.for(
187
+ 'hop-top/kit/mcp/dispatcher-factory',
188
+ );
189
+
190
+ /** A handler built by createMcpHandler. */
191
+ interface FactoryHandler extends McpHandler {
192
+ [MCP_DISPATCHER_FACTORY]?: (transport: McpTransport) => McpDispatcher;
193
+ }
194
+
195
+ /**
196
+ * The dispatcher factory createMcpHandler attached to `handler`, or
197
+ * undefined for a handler built some other way.
198
+ */
199
+ export function dispatcherFactoryOf(
200
+ handler: McpHandler,
201
+ ): ((transport: McpTransport) => McpDispatcher) | undefined {
202
+ return (handler as FactoryHandler)[MCP_DISPATCHER_FACTORY];
203
+ }
204
+
173
205
  /**
174
206
  * Builds the MCP handler for a bridge. Mirrors Go's
175
207
  * `MountMCP(bridge, router, opts...)`, minus the router: the caller
@@ -187,7 +219,10 @@ export function createMcpHandler(
187
219
  ): McpHandler {
188
220
  const cfg = resolveMcpConfig(opts);
189
221
  const dispatcher = new McpDispatcher(bridge, cfg);
190
- return (req) => dispatcher.handle(req);
222
+ const handler: FactoryHandler = (req) => dispatcher.handle(req);
223
+ handler[MCP_DISPATCHER_FACTORY] = (transport) =>
224
+ new McpDispatcher(bridge, cfg, transport);
225
+ return handler;
191
226
  }
192
227
 
193
228
  /** The resolved mount config for a handler, for adopters that need it. */
@@ -208,9 +243,11 @@ export class McpDispatcher {
208
243
  constructor(
209
244
  bridge: McpBridge,
210
245
  private readonly cfg: ResolvedMcpConfig,
246
+ transport: McpTransport = 'http',
211
247
  ) {
248
+ checkToolNameSeparator(bridge.leaves(), cfg.toolNameSeparator);
212
249
  this.legacy = new LegacyMcpHandler(bridge, cfg);
213
- this.modern = new ModernMcpHandler(bridge, cfg);
250
+ this.modern = new ModernMcpHandler(bridge, cfg, transport);
214
251
  }
215
252
 
216
253
  async handle(req: McpHttpRequest): Promise<McpHttpResponse> {
@@ -249,6 +286,15 @@ export class McpDispatcher {
249
286
  return parseErrorResponse(body);
250
287
  }
251
288
 
289
+ return this.dispatch(req, rpc);
290
+ }
291
+
292
+ /**
293
+ * Routes one already-parsed request to its era's handler (D2-D4).
294
+ * The transport-neutral core behind `handle`; stdio calls it directly
295
+ * after doing its own framing and parsing.
296
+ */
297
+ dispatch(req: McpHttpRequest, rpc: JsonRpcRequest): Promise<McpHttpResponse> {
252
298
  // Modern-only mounts route everything to the modern handler and
253
299
  // handle it per the normal V1-V9 order — no special-casing of
254
300
  // initialize anywhere, since D2 exists to hand a confused client
package/src/mcp/index.ts CHANGED
@@ -21,7 +21,9 @@
21
21
  * ```
22
22
  *
23
23
  * The handler is framework-free: binding it to node:http, hono,
24
- * express, fastify, or a Worker is the adopter's job.
24
+ * express, fastify, or a Worker is the adopter's job. For a host that
25
+ * spawns the tool, `serveStdio(bridge)` (or `serveStdio(handler)`)
26
+ * serves the same surface over newline-delimited stdin/stdout.
25
27
  */
26
28
 
27
29
  export {
@@ -37,10 +39,27 @@ export {
37
39
  type McpHandler,
38
40
  type McpHttpRequest,
39
41
  type McpHttpResponse,
42
+ type McpTransport,
40
43
  } from './dispatch.js';
41
44
 
42
45
  export { LegacyMcpHandler } from './legacy.js';
43
46
 
47
+ export {
48
+ auditRefusal,
49
+ MCP_AUDIT_AUTH_REFUSED,
50
+ MCP_AUDIT_CONFIRMATION_DECLINED,
51
+ MCP_AUDIT_CONFIRMATION_REQUIRED,
52
+ MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
53
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED,
54
+ MCP_CONFIRM_REJECTION_STATE,
55
+ } from './audit.js';
56
+
57
+ export {
58
+ serveStdio,
59
+ type McpStdioOptions,
60
+ type McpStdioServer,
61
+ } from './stdio.js';
62
+
44
63
  export {
45
64
  decodeMcpSentinel,
46
65
  ModernMcpHandler,
@@ -85,6 +104,7 @@ export {
85
104
  DEFAULT_MCP_PATH,
86
105
  DEFAULT_MCP_SERVER_NAME,
87
106
  DEFAULT_MCP_SERVER_VERSION,
107
+ DEFAULT_TOOL_NAME_SEPARATOR,
88
108
  defaultPolicy,
89
109
  DestructiveBlockedError,
90
110
  encodeEnvelope,
@@ -126,6 +146,9 @@ export {
126
146
  type InvokeResult,
127
147
  type JsonRpcErrorObject,
128
148
  type Leaf,
149
+ type LeafArg,
150
+ type McpAuditHook,
151
+ type McpAuditRecord,
129
152
  type McpBridge,
130
153
  type McpCacheScope,
131
154
  type McpEstablishment,
@@ -142,3 +165,12 @@ export {
142
165
  export { establishCaller, invocationMeta, SCOPES_EXTRA_KEY } from './identity.js';
143
166
 
144
167
  export { commanderBridge, type CommanderBridgeOptions } from './bridge.js';
168
+
169
+ export {
170
+ MCP_ARGS_PROPERTY,
171
+ mcpArgsPublished,
172
+ mcpInputSchema,
173
+ mcpSplitArguments,
174
+ mcpToolDescription,
175
+ type McpSplitResult,
176
+ } from './args.js';
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Legacy-era notifications and ping.
3
+ *
4
+ * A message with no `id` member is a JSON-RPC notification, which must
5
+ * never be answered: the legacy path acknowledges it with HTTP 202 and
6
+ * an empty body and does not process it. `ping` (a 2024-11-05 utility)
7
+ * must be answered with an empty result. Both hold on the dual-era
8
+ * mount and on a legacy-only mount.
9
+ */
10
+
11
+ import { describe, expect, it } from 'vitest';
12
+
13
+ import { createMcpHandler } from './dispatch.js';
14
+ import { legacyLockBridge } from './testtree.js';
15
+ import type { McpBridge, McpMountOptions } from './types.js';
16
+
17
+ const MOUNTS: Record<string, McpMountOptions> = {
18
+ 'dual-era': {},
19
+ 'legacy-only': { specVersions: ['2024-11-05'] },
20
+ };
21
+
22
+ function countingBridge(): { bridge: McpBridge; calls: () => number } {
23
+ const inner = legacyLockBridge();
24
+ let n = 0;
25
+ const bridge: McpBridge = {
26
+ leaves: () => inner.leaves(),
27
+ invoke: (inv) => {
28
+ n++;
29
+ return inner.invoke(inv);
30
+ },
31
+ };
32
+ return { bridge, calls: () => n };
33
+ }
34
+
35
+ describe.each(Object.entries(MOUNTS))('legacy era (%s mount)', (_name, opts) => {
36
+ it.each([
37
+ '{"jsonrpc":"2.0","method":"notifications/initialized"}',
38
+ '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}',
39
+ '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"ping"}}',
40
+ ])('does not answer the notification %s', async (body) => {
41
+ const { bridge, calls } = countingBridge();
42
+ const handler = createMcpHandler(bridge, opts);
43
+ const res = await handler({ method: 'POST', body });
44
+ expect(res.status).toBe(202);
45
+ expect(res.body).toBe('');
46
+ expect(calls()).toBe(0);
47
+ });
48
+
49
+ it.each([
50
+ ['{"jsonrpc":"2.0","id":7,"method":"ping"}', '{"jsonrpc":"2.0","id":7,"result":{}}\n'],
51
+ ['{"jsonrpc":"2.0","id":"p","method":"ping","params":{}}', '{"jsonrpc":"2.0","id":"p","result":{}}\n'],
52
+ ['{"jsonrpc":"2.0","id":null,"method":"ping"}', '{"jsonrpc":"2.0","id":null,"result":{}}\n'],
53
+ ])('answers ping %s with an empty result', async (body, want) => {
54
+ const handler = createMcpHandler(legacyLockBridge(), opts);
55
+ const res = await handler({ method: 'POST', body });
56
+ expect(res.status).toBe(200);
57
+ expect(res.body).toBe(want);
58
+ });
59
+ });
package/src/mcp/legacy.ts CHANGED
@@ -2,18 +2,21 @@
2
2
  * @module mcp/legacy
3
3
  * @package @hop-top/kit
4
4
  *
5
- * The 2024-11-05 MCP handler: `initialize`, `tools/list`,
5
+ * The 2024-11-05 MCP handler: `initialize`, `ping`, `tools/list`,
6
6
  * `tools/call`, plain JSON-RPC over one POST path, no sessions, no
7
7
  * SSE.
8
8
  *
9
- * This module is byte-for-byte frozen. The dual-spec hard invariant is
10
- * "2024-11-05 behavior is preserved byte-for-byte; additive only; no
11
- * deprecation", and the three-way module split (legacy / modern /
12
- * dispatch) exists precisely so a reviewer can confirm a modern-era
13
- * change did not touch this file. Modern-era behavior belongs in
14
- * modern.ts — never here.
9
+ * This module's wire output is byte-for-byte frozen. The dual-spec hard
10
+ * invariant is "2024-11-05 behavior is preserved byte-for-byte;
11
+ * additive only; no deprecation", and the three-way module split
12
+ * (legacy / modern / dispatch) exists precisely so a reviewer can
13
+ * confirm a modern-era change did not touch this file. Modern-era
14
+ * behavior belongs in modern.ts — never here. The refusal audit hook
15
+ * (mcp/audit) is the one deliberate addition: it observes the
16
+ * refusals this handler already makes and changes no byte of them.
15
17
  */
16
18
 
19
+ import { mcpSplitArguments } from './args.js';
17
20
  import {
18
21
  errorResultBlock,
19
22
  encodeEnvelope,
@@ -39,8 +42,14 @@ import {
39
42
  UnknownCommandError,
40
43
  } from './types.js';
41
44
  import type { JsonRpcRequest, McpHttpRequest, McpHttpResponse } from './dispatch.js';
42
- import { jsonResponse } from './dispatch.js';
45
+ import { acceptedResponse, jsonResponse } from './dispatch.js';
43
46
  import { establishCaller, invocationMeta } from './identity.js';
47
+ import {
48
+ auditRefusal,
49
+ MCP_AUDIT_AUTH_REFUSED,
50
+ MCP_AUDIT_CONFIRMATION_REQUIRED,
51
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED,
52
+ } from './audit.js';
44
53
 
45
54
  /** Writes a successful JSON-RPC envelope. */
46
55
  export function writeResult(
@@ -83,7 +92,7 @@ export function parseErrorResponse(body: string): McpHttpResponse {
83
92
  * whose first key is unquoted (the fixture case `{not json`) that is
84
93
  * "invalid character 'n' looking for beginning of object key string".
85
94
  */
86
- function goJSONParseMessage(body: string): string {
95
+ export function goJSONParseMessage(body: string): string {
87
96
  const trimmed = body.replace(/^[\s]*/, '');
88
97
  if (trimmed.startsWith('{')) {
89
98
  // Scan past the opening brace and any whitespace to the first
@@ -129,9 +138,21 @@ export class LegacyMcpHandler {
129
138
  );
130
139
  }
131
140
 
141
+ // No id member: a notification. JSON-RPC 2.0 forbids any reply, so
142
+ // it is acknowledged with HTTP 202 and an empty body and is not
143
+ // processed — the modern handler's V2 answer. An explicit
144
+ // `"id": null` is a request and is answered.
145
+ if (rpc.id === undefined) {
146
+ return acceptedResponse();
147
+ }
148
+
132
149
  switch (rpc.method) {
133
150
  case 'initialize':
134
151
  return this.handleInitialize(rpc);
152
+ case 'ping':
153
+ // 2024-11-05 utility: the receiver MUST answer with an empty
154
+ // result. Legacy era only; 2026-07-28 removed ping.
155
+ return writeResult(rpc.id, {}, 200);
135
156
  case 'tools/list':
136
157
  return this.handleToolsList(rpc);
137
158
  case 'tools/call':
@@ -173,7 +194,7 @@ export class LegacyMcpHandler {
173
194
  const tools: Array<Record<string, unknown>> = [];
174
195
  for (const leaf of this.bridge.leaves()) {
175
196
  if (!isExposed(leaf)) continue;
176
- tools.push(buildToolEnvelope(leaf));
197
+ tools.push(buildToolEnvelope(leaf, this.cfg.toolNameSeparator));
177
198
  }
178
199
  return tools;
179
200
  }
@@ -201,7 +222,7 @@ export class LegacyMcpHandler {
201
222
  );
202
223
  }
203
224
 
204
- const leaf = resolveLeaf(this.bridge, name);
225
+ const leaf = resolveLeaf(this.bridge, name, this.cfg.toolNameSeparator);
205
226
  if (leaf === undefined || !isExposed(leaf)) {
206
227
  return writeError(
207
228
  rpc.id,
@@ -216,14 +237,22 @@ export class LegacyMcpHandler {
216
237
  // a bare Authorization header does not.
217
238
  const ident = await establishCaller(this.cfg.verifier, req);
218
239
  if (leaf.class?.authRequired && ident === undefined) {
240
+ this.audit(leaf, MCP_AUDIT_AUTH_REFUSED);
219
241
  return unauthenticated(
220
242
  writeResult(rpc.id, errorResultBlock('authentication required'), 401),
221
243
  );
222
244
  }
245
+ // Arguments are checked before the confirmation gate: a person
246
+ // is never asked to approve a call that cannot run as sent.
247
+ const split = mcpSplitArguments(leaf, params.arguments);
248
+ if (split.error !== undefined) {
249
+ return writeResult(rpc.id, errorResultBlock(split.error), 200);
250
+ }
223
251
  if (
224
252
  leaf.class?.requiresConfirmation &&
225
253
  !headerValue(req, 'x-confirm-token')
226
254
  ) {
255
+ this.audit(leaf, MCP_AUDIT_CONFIRMATION_REQUIRED);
227
256
  return writeResult(
228
257
  rpc.id,
229
258
  errorResultBlock('confirmation required'),
@@ -234,7 +263,8 @@ export class LegacyMcpHandler {
234
263
  try {
235
264
  const res = await this.bridge.invoke({
236
265
  path: [...leaf.path],
237
- flags: params.arguments,
266
+ ...(split.args !== undefined ? { args: split.args } : {}),
267
+ flags: split.flags,
238
268
  meta: invocationMeta(ident),
239
269
  });
240
270
  return writeResult(rpc.id, renderCallResult(res), 200);
@@ -250,7 +280,11 @@ export class LegacyMcpHandler {
250
280
  );
251
281
  }
252
282
  // DestructiveBlockedError and every other invoke failure render
253
- // as an isError result at HTTP 200.
283
+ // as an isError result at HTTP 200. Only the ceiling is a
284
+ // refusal the surface audits; a run that failed is the bridge's.
285
+ if (err instanceof DestructiveBlockedError) {
286
+ this.audit(leaf, MCP_AUDIT_DESTRUCTIVE_BLOCKED);
287
+ }
254
288
  return writeResult(
255
289
  rpc.id,
256
290
  errorResultBlock(errorMessage(err)),
@@ -258,6 +292,11 @@ export class LegacyMcpHandler {
258
292
  );
259
293
  }
260
294
  }
295
+
296
+ /** Emits one 2024-11-05 refusal record to the mount's audit hook. */
297
+ private audit(leaf: Leaf, error: string): void {
298
+ auditRefusal(this.cfg.audit, leaf.path, MCP_SPEC_2024_11_05, error);
299
+ }
261
300
  }
262
301
 
263
302
  /**
@@ -278,12 +317,13 @@ export function isExposed(leaf: Leaf): boolean {
278
317
  return leaf.enabled?.[SURFACE_MCP] !== false;
279
318
  }
280
319
 
281
- /** Resolves a dotted tool name to a leaf, or undefined. */
320
+ /** Resolves a tool name, split on `separator`, to a leaf, or undefined. */
282
321
  export function resolveLeaf(
283
322
  bridge: McpBridge,
284
323
  name: string,
324
+ separator?: string,
285
325
  ): Leaf | undefined {
286
- const path = pathFromToolName(name);
326
+ const path = pathFromToolName(name, separator);
287
327
  if (path.length === 0) return undefined;
288
328
  return bridge
289
329
  .leaves()