@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

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 (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -0,0 +1,520 @@
1
+ /**
2
+ * The mount-level audit hook: one record per refusal the surface
3
+ * decides before adopter code runs, mirroring what Go's bridge sinks
4
+ * receive from the MCP surface. Pins, per event and per era, the
5
+ * record's fields, that the wire response is byte-identical with and
6
+ * without the hook, that a throwing hook changes nothing, and that
7
+ * neither a successful call nor an expired-but-authentic state is
8
+ * recorded.
9
+ */
10
+
11
+ import { PassThrough } from 'node:stream';
12
+ import { describe, expect, it } from 'vitest';
13
+
14
+ import {
15
+ MCP_AUDIT_AUTH_REFUSED,
16
+ MCP_AUDIT_CONFIRMATION_DECLINED,
17
+ MCP_AUDIT_CONFIRMATION_REQUIRED,
18
+ MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
19
+ MCP_AUDIT_DESTRUCTIVE_BLOCKED,
20
+ MCP_CONFIRM_REJECTION_STATE,
21
+ } from './audit.js';
22
+ import {
23
+ createMcpHandler,
24
+ mcpMountConfig,
25
+ type McpHttpRequest,
26
+ type McpHttpResponse,
27
+ } from './dispatch.js';
28
+ import {
29
+ ElicitationConfirmGate,
30
+ mcpConfirmArgsDigest,
31
+ mintMcpConfirmState,
32
+ } from './modern-confirm.js';
33
+ import { serveStdio } from './stdio.js';
34
+ import { legacyLockBridge, modernLockBridge, mrtrLockBridge } from './testtree.js';
35
+ import {
36
+ MCP_SPEC_2024_11_05,
37
+ MCP_SPEC_2026_07_28,
38
+ type McpAuditRecord,
39
+ type McpBridge,
40
+ type McpMountOptions,
41
+ } from './types.js';
42
+
43
+ const KEY = 'audit-unit-suite-shared-secret-32';
44
+
45
+ /** Collects every record the hook receives. */
46
+ function recorder(): {
47
+ records: McpAuditRecord[];
48
+ audit: (r: McpAuditRecord) => void;
49
+ } {
50
+ const records: McpAuditRecord[] = [];
51
+ return { records, audit: (r) => records.push(r) };
52
+ }
53
+
54
+ /** A legacy-era tools/call. */
55
+ function legacyCall(
56
+ name: string,
57
+ headers: Record<string, string> = {},
58
+ ): McpHttpRequest {
59
+ return {
60
+ method: 'POST',
61
+ headers: { 'Content-Type': 'application/json', ...headers },
62
+ body: JSON.stringify({
63
+ jsonrpc: '2.0',
64
+ id: 1,
65
+ method: 'tools/call',
66
+ params: { name },
67
+ }),
68
+ };
69
+ }
70
+
71
+ /** The reserved _meta bag, with the client's elicitation declaration. */
72
+ function meta(elicitation?: unknown): Record<string, unknown> {
73
+ const caps: Record<string, unknown> = {};
74
+ if (elicitation !== undefined) caps.elicitation = elicitation;
75
+ return {
76
+ 'io.modelcontextprotocol/clientCapabilities': caps,
77
+ 'io.modelcontextprotocol/protocolVersion': MCP_SPEC_2026_07_28,
78
+ };
79
+ }
80
+
81
+ interface ModernCallOpts {
82
+ id?: number;
83
+ tool: string;
84
+ args?: Record<string, unknown>;
85
+ meta?: Record<string, unknown>;
86
+ state?: string;
87
+ action?: string;
88
+ headers?: Record<string, string>;
89
+ }
90
+
91
+ /** A modern-era tools/call, with optional MRTR retry members. */
92
+ function modernCall(o: ModernCallOpts): McpHttpRequest {
93
+ const params: Record<string, unknown> = {
94
+ name: o.tool,
95
+ _meta: o.meta ?? meta({}),
96
+ };
97
+ if (o.args !== undefined) params.arguments = o.args;
98
+ if (o.state !== undefined) params.requestState = o.state;
99
+ if (o.action !== undefined) {
100
+ params.inputResponses = { confirm: { action: o.action } };
101
+ }
102
+ return {
103
+ method: 'POST',
104
+ headers: {
105
+ 'Content-Type': 'application/json',
106
+ 'MCP-Protocol-Version': MCP_SPEC_2026_07_28,
107
+ 'Mcp-Method': 'tools/call',
108
+ 'Mcp-Name': o.tool,
109
+ ...(o.headers ?? {}),
110
+ },
111
+ body: JSON.stringify({
112
+ jsonrpc: '2.0',
113
+ id: o.id ?? 1,
114
+ method: 'tools/call',
115
+ params,
116
+ }),
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Serves `reqs` in order against two fresh mounts, one silent and one
122
+ * audited, and asserts every response is byte-identical between them.
123
+ * Returns the audited mount's last response and its records.
124
+ */
125
+ async function sameWire(
126
+ make: () => McpBridge,
127
+ opts: McpMountOptions,
128
+ reqs: McpHttpRequest[],
129
+ ): Promise<{ res: McpHttpResponse; records: McpAuditRecord[] }> {
130
+ const silent = createMcpHandler(make(), opts);
131
+ const { records, audit } = recorder();
132
+ const audited = createMcpHandler(make(), { ...opts, audit });
133
+ let last: McpHttpResponse | undefined;
134
+ for (const req of reqs) {
135
+ const a = await silent(req);
136
+ const b = await audited(req);
137
+ expect(b).toEqual(a);
138
+ last = b;
139
+ }
140
+ if (last === undefined) throw new Error('no request served');
141
+ return { res: last, records };
142
+ }
143
+
144
+ /** The one record expected for a refusal, checked field by field. */
145
+ function expectRecord(
146
+ r: McpAuditRecord | undefined,
147
+ want: { path: string[]; specVersion: string; error: string; extra?: Record<string, string> },
148
+ ): void {
149
+ expect(r).toBeDefined();
150
+ if (r === undefined) return;
151
+ expect(r.path).toEqual(want.path);
152
+ expect(r.surface).toBe('mcp');
153
+ expect(r.requestedAt).toBeInstanceOf(Date);
154
+ expect(r.specVersion).toBe(want.specVersion);
155
+ expect(r.error).toBe(want.error);
156
+ expect(r.extra).toEqual({
157
+ mcp_spec_version: want.specVersion,
158
+ ...(want.extra ?? {}),
159
+ });
160
+ }
161
+
162
+ describe('audit hook — 2024-11-05 era', () => {
163
+ it('auth refused: one record, wire unchanged', async () => {
164
+ const { res, records } = await sameWire(legacyLockBridge, {}, [
165
+ legacyCall('secret', { Authorization: 'Bearer presence-only' }),
166
+ ]);
167
+ expect(res.status).toBe(401);
168
+ expect(records).toHaveLength(1);
169
+ expectRecord(records[0], {
170
+ path: ['secret'],
171
+ specVersion: MCP_SPEC_2024_11_05,
172
+ error: MCP_AUDIT_AUTH_REFUSED,
173
+ });
174
+ });
175
+
176
+ it('confirmation required: one record, wire unchanged', async () => {
177
+ const { res, records } = await sameWire(legacyLockBridge, {}, [
178
+ legacyCall('deploy'),
179
+ ]);
180
+ expect(res.status).toBe(428);
181
+ expect(records).toHaveLength(1);
182
+ expectRecord(records[0], {
183
+ path: ['deploy'],
184
+ specVersion: MCP_SPEC_2024_11_05,
185
+ error: MCP_AUDIT_CONFIRMATION_REQUIRED,
186
+ });
187
+ });
188
+
189
+ it('destructive ceiling: one record, wire unchanged', async () => {
190
+ const { res, records } = await sameWire(legacyLockBridge, {}, [
191
+ legacyCall('widget.delete'),
192
+ ]);
193
+ expect(res.status).toBe(200);
194
+ expect(res.body).toContain('destructive command blocked');
195
+ expect(records).toHaveLength(1);
196
+ expectRecord(records[0], {
197
+ path: ['widget', 'delete'],
198
+ specVersion: MCP_SPEC_2024_11_05,
199
+ error: MCP_AUDIT_DESTRUCTIVE_BLOCKED,
200
+ });
201
+ });
202
+
203
+ it('a successful call and a satisfied gate record nothing', async () => {
204
+ const { records } = await sameWire(legacyLockBridge, {}, [
205
+ legacyCall('ping'),
206
+ legacyCall('deploy', { 'X-Confirm-Token': 'yes' }),
207
+ ]);
208
+ expect(records).toEqual([]);
209
+ });
210
+
211
+ it('a throwing hook leaves the response unchanged', async () => {
212
+ const silent = await createMcpHandler(legacyLockBridge())(legacyCall('secret'));
213
+ const loud = await createMcpHandler(legacyLockBridge(), {
214
+ audit: () => {
215
+ throw new Error('sink down');
216
+ },
217
+ })(legacyCall('secret'));
218
+ expect(loud).toEqual(silent);
219
+ });
220
+ });
221
+
222
+ describe('audit hook — 2026-07-28 era', () => {
223
+ it('auth refused: one record, wire unchanged', async () => {
224
+ const { res, records } = await sameWire(modernLockBridge, {}, [
225
+ modernCall({ tool: 'secret', headers: { Authorization: 'Bearer presence-only' } }),
226
+ ]);
227
+ expect(res.status).toBe(401);
228
+ expect(records).toHaveLength(1);
229
+ expectRecord(records[0], {
230
+ path: ['secret'],
231
+ specVersion: MCP_SPEC_2026_07_28,
232
+ error: MCP_AUDIT_AUTH_REFUSED,
233
+ });
234
+ });
235
+
236
+ it('confirmation required (header gate, key-less mount): one record', async () => {
237
+ const { res, records } = await sameWire(modernLockBridge, {}, [
238
+ modernCall({ tool: 'deploy' }),
239
+ ]);
240
+ expect(res.status).toBe(428);
241
+ expect(records).toHaveLength(1);
242
+ expectRecord(records[0], {
243
+ path: ['deploy'],
244
+ specVersion: MCP_SPEC_2026_07_28,
245
+ error: MCP_AUDIT_CONFIRMATION_REQUIRED,
246
+ });
247
+ });
248
+
249
+ it('confirmation required (keyed mount, client without elicitation): one record', async () => {
250
+ const { res, records } = await sameWire(
251
+ () => mrtrLockBridge().bridge,
252
+ { confirmationKey: KEY },
253
+ [modernCall({ tool: 'purge', meta: meta() })],
254
+ );
255
+ expect(res.status).toBe(428);
256
+ expect(records).toHaveLength(1);
257
+ expectRecord(records[0], {
258
+ path: ['purge'],
259
+ specVersion: MCP_SPEC_2026_07_28,
260
+ error: MCP_AUDIT_CONFIRMATION_REQUIRED,
261
+ });
262
+ });
263
+
264
+ for (const action of ['decline', 'cancel']) {
265
+ it(`confirmation declined (${action}): one record, wire unchanged`, async () => {
266
+ const silent = createMcpHandler(mrtrLockBridge().bridge, { confirmationKey: KEY });
267
+ const { records, audit } = recorder();
268
+ const audited = createMcpHandler(mrtrLockBridge().bridge, {
269
+ confirmationKey: KEY,
270
+ audit,
271
+ });
272
+ // The prompt itself is not a refusal: nothing is recorded.
273
+ const r1 = await audited(modernCall({ id: 1, tool: 'purge' }));
274
+ const state = (JSON.parse(r1.body) as { result: { requestState: string } }).result
275
+ .requestState;
276
+ expect(records).toEqual([]);
277
+
278
+ const retry = modernCall({ id: 2, tool: 'purge', state, action });
279
+ const a = await silent(retry);
280
+ const b = await audited(retry);
281
+ expect(b).toEqual(a);
282
+ expect(b.body).toContain('confirmation declined');
283
+ expect(records).toHaveLength(1);
284
+ expectRecord(records[0], {
285
+ path: ['purge'],
286
+ specVersion: MCP_SPEC_2026_07_28,
287
+ error: MCP_AUDIT_CONFIRMATION_DECLINED,
288
+ });
289
+ });
290
+ }
291
+
292
+ it('state rejected: one record carrying mcp_confirm_rejection, wire shape unchanged', async () => {
293
+ const { records, audit } = recorder();
294
+ const handler = createMcpHandler(mrtrLockBridge().bridge, {
295
+ confirmationKey: KEY,
296
+ audit,
297
+ });
298
+ const r1 = await handler(modernCall({ id: 1, tool: 'purge' }));
299
+ const state = (JSON.parse(r1.body) as { result: { requestState: string } }).result
300
+ .requestState;
301
+ const forged = state.slice(0, -1) + (state.endsWith('A') ? 'B' : 'A');
302
+
303
+ const r2 = await handler(modernCall({ id: 2, tool: 'purge', state: forged, action: 'accept' }));
304
+ const result = (JSON.parse(r2.body) as { result: Record<string, unknown> }).result;
305
+ // Re-prompted with fresh state, exactly as without the hook.
306
+ expect(result.resultType).toBe('input_required');
307
+ expect(result.requestState).not.toBe(forged);
308
+ expect(records).toHaveLength(1);
309
+ expectRecord(records[0], {
310
+ path: ['purge'],
311
+ specVersion: MCP_SPEC_2026_07_28,
312
+ error: MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
313
+ extra: { mcp_confirm_rejection: MCP_CONFIRM_REJECTION_STATE },
314
+ });
315
+ });
316
+
317
+ it('an authentic but expired state re-prompts without a record', async () => {
318
+ const { records, audit } = recorder();
319
+ const handler = createMcpHandler(mrtrLockBridge().bridge, {
320
+ confirmationKey: KEY,
321
+ audit,
322
+ });
323
+ // Minted under the mount's key for this exact binding: tool
324
+ // "purge", no arguments, no Authorization header. An hour stale.
325
+ const stale = mintMcpConfirmState(
326
+ new TextEncoder().encode(KEY),
327
+ { tool: 'purge', argsDigest: mcpConfirmArgsDigest({}), principal: '' },
328
+ Math.floor(Date.now() / 1000) - 3600,
329
+ );
330
+ const res = await handler(modernCall({ tool: 'purge', state: stale, action: 'accept' }));
331
+ const result = (JSON.parse(res.body) as { result: Record<string, unknown> }).result;
332
+ expect(result.resultType).toBe('input_required');
333
+ expect(records).toEqual([]);
334
+ });
335
+
336
+ it('destructive ceiling: one record, wire unchanged', async () => {
337
+ const { res, records } = await sameWire(modernLockBridge, {}, [
338
+ modernCall({ tool: 'widget.delete' }),
339
+ ]);
340
+ expect(res.status).toBe(200);
341
+ expect(res.body).toContain('destructive command blocked');
342
+ expect(records).toHaveLength(1);
343
+ expectRecord(records[0], {
344
+ path: ['widget', 'delete'],
345
+ specVersion: MCP_SPEC_2026_07_28,
346
+ error: MCP_AUDIT_DESTRUCTIVE_BLOCKED,
347
+ });
348
+ });
349
+
350
+ it('destructive ceiling behind an accepted confirmation is still recorded', async () => {
351
+ const { records, audit } = recorder();
352
+ const handler = createMcpHandler(mrtrLockBridge().bridge, {
353
+ confirmationKey: KEY,
354
+ audit,
355
+ });
356
+ const r1 = await handler(modernCall({ id: 1, tool: 'vault.burn' }));
357
+ const state = (JSON.parse(r1.body) as { result: { requestState: string } }).result
358
+ .requestState;
359
+ const r2 = await handler(modernCall({ id: 2, tool: 'vault.burn', state, action: 'accept' }));
360
+ expect(r2.body).toContain('destructive command blocked');
361
+ expect(records).toHaveLength(1);
362
+ expectRecord(records[0], {
363
+ path: ['vault', 'burn'],
364
+ specVersion: MCP_SPEC_2026_07_28,
365
+ error: MCP_AUDIT_DESTRUCTIVE_BLOCKED,
366
+ });
367
+ });
368
+
369
+ it('a successful call, a satisfied gate and an accepted prompt record nothing', async () => {
370
+ const { records, audit } = recorder();
371
+ const handler = createMcpHandler(mrtrLockBridge().bridge, {
372
+ confirmationKey: KEY,
373
+ audit,
374
+ });
375
+ const r1 = await handler(modernCall({ id: 1, tool: 'purge' }));
376
+ const state = (JSON.parse(r1.body) as { result: { requestState: string } }).result
377
+ .requestState;
378
+ const r2 = await handler(modernCall({ id: 2, tool: 'purge', state, action: 'accept' }));
379
+ expect(r2.body).toContain('"isError":false');
380
+ const r3 = await handler(
381
+ modernCall({ id: 3, tool: 'purge', meta: meta(), headers: { 'X-Confirm-Token': 'yes' } }),
382
+ );
383
+ expect(r3.body).toContain('"isError":false');
384
+ expect(records).toEqual([]);
385
+
386
+ const { records: plain, audit: auditPlain } = recorder();
387
+ await createMcpHandler(modernLockBridge(), { audit: auditPlain })(modernCall({ tool: 'ping' }));
388
+ expect(plain).toEqual([]);
389
+ });
390
+
391
+ it('a throwing hook leaves the response unchanged', async () => {
392
+ const req = modernCall({ tool: 'secret' });
393
+ const silent = await createMcpHandler(modernLockBridge())(req);
394
+ const loud = await createMcpHandler(modernLockBridge(), {
395
+ audit: () => {
396
+ throw new Error('sink down');
397
+ },
398
+ })(req);
399
+ expect(loud).toEqual(silent);
400
+ });
401
+ });
402
+
403
+ describe('audit hook — ElicitationConfirmGate keeps its in-memory rejections', () => {
404
+ const leaf = {
405
+ path: ['purge'],
406
+ description: 'Purge a target',
407
+ properties: {},
408
+ class: { requiresConfirmation: true },
409
+ };
410
+
411
+ it('a rejected state reaches both the rejections list and the hook', () => {
412
+ const { records, audit } = recorder();
413
+ const gate = new ElicitationConfirmGate(new TextEncoder().encode(KEY), undefined, audit);
414
+ const decision = gate.evaluate(
415
+ { method: 'POST', headers: {}, body: '' },
416
+ leaf,
417
+ { name: 'purge', _meta: meta({}), requestState: 'v1.99999999999.AAAA' },
418
+ );
419
+ expect(decision?.result.resultType).toBe('input_required');
420
+ expect(gate.rejections).toEqual([
421
+ { path: 'purge', mcpConfirmRejection: MCP_CONFIRM_REJECTION_STATE },
422
+ ]);
423
+ expect(records).toHaveLength(1);
424
+ expectRecord(records[0], {
425
+ path: ['purge'],
426
+ specVersion: MCP_SPEC_2026_07_28,
427
+ error: MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
428
+ extra: { mcp_confirm_rejection: MCP_CONFIRM_REJECTION_STATE },
429
+ });
430
+ });
431
+
432
+ it('a throwing hook still records the rejection in memory', () => {
433
+ const gate = new ElicitationConfirmGate(new TextEncoder().encode(KEY), undefined, () => {
434
+ throw new Error('sink down');
435
+ });
436
+ const decision = gate.evaluate(
437
+ { method: 'POST', headers: {}, body: '' },
438
+ leaf,
439
+ { name: 'purge', _meta: meta({}), requestState: 'v1.99999999999.AAAA' },
440
+ );
441
+ expect(decision?.result.resultType).toBe('input_required');
442
+ expect(gate.rejections).toHaveLength(1);
443
+ });
444
+ });
445
+
446
+ describe('audit hook — plumbing', () => {
447
+ it('the resolved mount config carries the hook', () => {
448
+ const { audit } = recorder();
449
+ expect(mcpMountConfig({ audit }).audit).toBe(audit);
450
+ expect(mcpMountConfig({}).audit).toBeUndefined();
451
+ });
452
+
453
+ it('serveStdio records a rejected state for a bridge with mount options', async () => {
454
+ const { records, audit } = recorder();
455
+ const input = new PassThrough();
456
+ const output = new PassThrough();
457
+ let out = '';
458
+ output.on('data', (c: Buffer) => (out += c.toString('utf8')));
459
+ const lines = () => out.split('\n').filter((l) => l !== '');
460
+ const server = serveStdio(mrtrLockBridge().bridge, {
461
+ input,
462
+ output,
463
+ log: new PassThrough(),
464
+ mount: { confirmationKey: KEY, audit },
465
+ });
466
+ const call = (id: number, extra: Record<string, unknown>) =>
467
+ JSON.stringify({
468
+ jsonrpc: '2.0',
469
+ id,
470
+ method: 'tools/call',
471
+ params: { name: 'purge', _meta: meta({}), ...extra },
472
+ });
473
+ const reply = async (n: number) => {
474
+ while (lines().length < n) await new Promise((r) => setTimeout(r, 1));
475
+ return JSON.parse(lines()[n - 1] ?? '{}') as { result: Record<string, unknown> };
476
+ };
477
+
478
+ input.write(`${call(1, {})}\n`);
479
+ const r1 = await reply(1);
480
+ const state = String(r1.result.requestState);
481
+ const forged = state.slice(0, -1) + (state.endsWith('A') ? 'B' : 'A');
482
+ expect(records).toEqual([]);
483
+
484
+ input.write(
485
+ `${call(2, { requestState: forged, inputResponses: { confirm: { action: 'accept' } } })}\n`,
486
+ );
487
+ const r2 = await reply(2);
488
+ expect(r2.result.resultType).toBe('input_required');
489
+ input.end();
490
+ await server.done;
491
+
492
+ expect(records).toHaveLength(1);
493
+ expectRecord(records[0], {
494
+ path: ['purge'],
495
+ specVersion: MCP_SPEC_2026_07_28,
496
+ error: MCP_AUDIT_CONFIRMATION_STATE_REJECTED,
497
+ extra: { mcp_confirm_rejection: MCP_CONFIRM_REJECTION_STATE },
498
+ });
499
+ });
500
+
501
+ it('serveStdio reuses a createMcpHandler handler hook included', async () => {
502
+ const { records, audit } = recorder();
503
+ const handler = createMcpHandler(legacyLockBridge(), { audit });
504
+ const input = new PassThrough();
505
+ const output = new PassThrough();
506
+ let out = '';
507
+ output.on('data', (c: Buffer) => (out += c.toString('utf8')));
508
+ const server = serveStdio(handler, { input, output, log: new PassThrough() });
509
+ input.write('{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"secret"}}\n');
510
+ input.end();
511
+ await server.done;
512
+ expect(out).toContain('authentication required');
513
+ expect(records).toHaveLength(1);
514
+ expectRecord(records[0], {
515
+ path: ['secret'],
516
+ specVersion: MCP_SPEC_2024_11_05,
517
+ error: MCP_AUDIT_AUTH_REFUSED,
518
+ });
519
+ });
520
+ });
@@ -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
+ }