@hop-top/kit 0.5.0-alpha.0 → 0.5.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/README.md +237 -9
- package/dist/aim-CTp-kJW2.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/alias-dhhr08Ei.d.ts +88 -0
- package/dist/alias.d.ts +2 -73
- package/dist/api-miiso81x.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/cli-DgOEOsPB.d.ts +450 -0
- package/dist/cli.d.ts +5 -309
- package/dist/cli.js +250 -62
- package/dist/config-BUY7_W2n.d.ts +103 -0
- package/dist/config.d.ts +1 -97
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/id/index.d.ts +2 -83
- package/dist/index--C7Mtsmm.d.ts +328 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-MLrRDvEG.d.ts +1073 -0
- package/dist/index-QSffbLnj.d.ts +94 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +5863 -0
- package/dist/llm-B5XUWH8T.d.ts +231 -0
- package/dist/llm.d.ts +1 -188
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +1453 -0
- package/dist/netpolicy-asvCfwi8.d.ts +138 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +118 -0
- package/dist/output-VFFLqor9.d.ts +521 -0
- package/dist/output.d.ts +2 -213
- package/dist/output.js +554 -43
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/routellm-PGSt2D1y.d.ts +75 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/rpc-D5xLEf8V.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +12 -1
- package/dist/tui/index.d.ts +4 -298
- package/dist/tui/index.js +61 -9
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/package.json +65 -25
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.ts +112 -12
- package/src/index.test.ts +58 -0
- package/src/index.ts +36 -0
- package/src/log.parity.test.ts +105 -0
- package/src/log.ts +64 -13
- package/src/mcp/bridge.test.ts +150 -0
- package/src/mcp/bridge.ts +246 -0
- package/src/mcp/conformance.test.ts +336 -0
- package/src/mcp/dispatch.ts +313 -0
- package/src/mcp/index.ts +138 -0
- package/src/mcp/legacy.ts +314 -0
- package/src/mcp/mcp.test.ts +697 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +452 -0
- package/src/mcp/modern.ts +723 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/types.ts +504 -0
- package/src/netpolicy.test.ts +202 -0
- package/src/netpolicy.ts +231 -0
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +293 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +39 -3
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +7 -1
- package/src/telemetry/offline.test.ts +64 -0
- package/src/tui/parity.test.ts +142 -0
- package/src/tui/parity.ts +59 -13
- package/test/output/csv.test.ts +164 -0
- package/test/output/error.test.ts +241 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-language MCP wire conformance.
|
|
3
|
+
*
|
|
4
|
+
* Replays every case in sdk/tests/cross-lang/fixtures/mcp-wire.json —
|
|
5
|
+
* generated from the live Go surface — against this port and asserts
|
|
6
|
+
* the response is byte-identical and the HTTP status matches.
|
|
7
|
+
*
|
|
8
|
+
* Byte-identical means exactly that: the fixture body is compared to
|
|
9
|
+
* the handler's body as a string, with NO JSON decode/re-encode on
|
|
10
|
+
* either side. Go emits objects with lexicographically sorted keys
|
|
11
|
+
* and a trailing newline; a serializer that differs must reorder to
|
|
12
|
+
* match, not normalize the comparison away.
|
|
13
|
+
*
|
|
14
|
+
* The fixtures are the parity contract. Where ADR 0042/0043 and these
|
|
15
|
+
* bytes disagree, the bytes win.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { describe, expect, it } from 'vitest';
|
|
21
|
+
|
|
22
|
+
import { createMcpHandler } from './dispatch.js';
|
|
23
|
+
import {
|
|
24
|
+
legacyLockBridge,
|
|
25
|
+
modernLockBridge,
|
|
26
|
+
mrtrLockBridge,
|
|
27
|
+
} from './testtree.js';
|
|
28
|
+
|
|
29
|
+
interface WireCase {
|
|
30
|
+
name: string;
|
|
31
|
+
era: 'legacy' | 'modern';
|
|
32
|
+
why?: string;
|
|
33
|
+
mount?: string[];
|
|
34
|
+
headers?: Record<string, string>;
|
|
35
|
+
request: string;
|
|
36
|
+
status: number;
|
|
37
|
+
response: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface WireStep {
|
|
41
|
+
name: string;
|
|
42
|
+
request: string;
|
|
43
|
+
status: number;
|
|
44
|
+
response: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface WireSequence {
|
|
48
|
+
name: string;
|
|
49
|
+
era: 'legacy' | 'modern';
|
|
50
|
+
why?: string;
|
|
51
|
+
mount?: string[];
|
|
52
|
+
headers?: Record<string, string>;
|
|
53
|
+
steps: WireStep[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The multi-round-trip confirmation exchange. Unlike `cases` and
|
|
58
|
+
* `sequences` this is not byte-exact end to end: round 1 mints a
|
|
59
|
+
* fresh, time-bound `requestState` whose MAC differs every run, so
|
|
60
|
+
* only its framing is checkable. Round 2 echoes that state back and IS
|
|
61
|
+
* byte-exact.
|
|
62
|
+
*/
|
|
63
|
+
interface WireMRTR {
|
|
64
|
+
why?: string;
|
|
65
|
+
confirmation_key: string;
|
|
66
|
+
round1_headers: Record<string, string>;
|
|
67
|
+
round1_request: string;
|
|
68
|
+
round1_status: number;
|
|
69
|
+
round1_must_have: Record<string, string>;
|
|
70
|
+
round1_must_not_have: string[];
|
|
71
|
+
state_framing: string;
|
|
72
|
+
round2_headers: Record<string, string>;
|
|
73
|
+
round2_request_template: string;
|
|
74
|
+
round2_status: number;
|
|
75
|
+
round2_response: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface WireDoc {
|
|
79
|
+
command_tree: string;
|
|
80
|
+
cases: WireCase[];
|
|
81
|
+
sequences?: WireSequence[];
|
|
82
|
+
mrtr?: WireMRTR;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const FIXTURE_PATH = join(
|
|
86
|
+
__dirname,
|
|
87
|
+
'..',
|
|
88
|
+
'..',
|
|
89
|
+
'..',
|
|
90
|
+
'tests',
|
|
91
|
+
'cross-lang',
|
|
92
|
+
'fixtures',
|
|
93
|
+
'mcp-wire.json',
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
function loadFixtures(): WireDoc {
|
|
97
|
+
return JSON.parse(readFileSync(FIXTURE_PATH, 'utf8')) as WireDoc;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The Go generator builds a fresh server per case, over one of two
|
|
102
|
+
* command trees: the legacy lock tree for the legacy cases, the
|
|
103
|
+
* modern lock tree for the modern ones. The trees differ — the
|
|
104
|
+
* legacy tree's `widget add` carries extra `force`/`tag` flags the
|
|
105
|
+
* modern tree omits — so the fixtures cannot be served from a single
|
|
106
|
+
* shared tree. Each case is otherwise independent: no state carries
|
|
107
|
+
* from one case to the next.
|
|
108
|
+
*/
|
|
109
|
+
function bridgeFor(c: { name: string }) {
|
|
110
|
+
return c.name.startsWith('legacy/') ? legacyLockBridge() : modernLockBridge();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
describe('MCP wire conformance (cross-language fixtures)', () => {
|
|
114
|
+
const doc = loadFixtures();
|
|
115
|
+
|
|
116
|
+
it('loads the full fixture set', () => {
|
|
117
|
+
expect(doc.cases.length).toBe(18);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
for (const c of doc.cases) {
|
|
121
|
+
it(`${c.name} — ${c.why ?? ''}`, async () => {
|
|
122
|
+
const handler = createMcpHandler(bridgeFor(c));
|
|
123
|
+
const res = await handler({
|
|
124
|
+
method: 'POST',
|
|
125
|
+
headers: { 'Content-Type': 'application/json', ...(c.headers ?? {}) },
|
|
126
|
+
body: c.request,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Status first: a status mismatch explains a body mismatch.
|
|
130
|
+
expect(res.status, `status for ${c.name}`).toBe(c.status);
|
|
131
|
+
// Byte-exact: raw string compare, no JSON round-trip.
|
|
132
|
+
expect(res.body, `body for ${c.name}`).toBe(c.response);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Sequences pin behavior that no single request can express: state
|
|
139
|
+
* that legitimately accumulates on a LONG-LIVED mount. Each sequence
|
|
140
|
+
* gets ONE handler, and its steps are posted in order against it.
|
|
141
|
+
*
|
|
142
|
+
* This is the counterpart to `cases`, not a replacement: cases assert
|
|
143
|
+
* that a request's response does not depend on request history, and
|
|
144
|
+
* sequences assert that where Go's response DOES depend on history,
|
|
145
|
+
* this port depends on it identically. Adopters serve from persistent
|
|
146
|
+
* processes, so a port that rebuilt its command tree per request
|
|
147
|
+
* would pass every case and still diverge here.
|
|
148
|
+
*/
|
|
149
|
+
describe('MCP wire conformance — sequences (one long-lived mount)', () => {
|
|
150
|
+
const doc = loadFixtures();
|
|
151
|
+
const sequences = doc.sequences ?? [];
|
|
152
|
+
|
|
153
|
+
it('loads the full sequence set', () => {
|
|
154
|
+
expect(sequences.length).toBe(1);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
for (const seq of sequences) {
|
|
158
|
+
it(`${seq.name} — ${seq.why ?? ''}`, async () => {
|
|
159
|
+
// ONE handler for the whole sequence: the state under test is
|
|
160
|
+
// exactly what survives between steps.
|
|
161
|
+
const handler = createMcpHandler(bridgeFor(seq));
|
|
162
|
+
|
|
163
|
+
for (const [i, step] of seq.steps.entries()) {
|
|
164
|
+
const res = await handler({
|
|
165
|
+
method: 'POST',
|
|
166
|
+
headers: {
|
|
167
|
+
'Content-Type': 'application/json',
|
|
168
|
+
...(seq.headers ?? {}),
|
|
169
|
+
},
|
|
170
|
+
body: step.request,
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const label = `${seq.name} step ${i} (${step.name})`;
|
|
174
|
+
expect(res.status, `status for ${label}`).toBe(step.status);
|
|
175
|
+
expect(res.body, `body for ${label}`).toBe(step.response);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The MRTR confirmation loop: the third fixture section, and the only
|
|
183
|
+
* one that is not byte-exact end to end.
|
|
184
|
+
*
|
|
185
|
+
* Round 1 mints a fresh, time-bound `requestState` whose MAC differs
|
|
186
|
+
* every run, so only its SHAPE is assertable — the fixture says which
|
|
187
|
+
* members must be present and which must never appear. Round 2 echoes
|
|
188
|
+
* that state back into a template and IS byte-exact, which is what
|
|
189
|
+
* makes the whole exchange verifiable rather than merely plausible: a
|
|
190
|
+
* port that fabricated a plausible-looking round 1 could not produce a
|
|
191
|
+
* state its own round 2 accepts AND land on Go's exact bytes.
|
|
192
|
+
*
|
|
193
|
+
* Both rounds run against ONE mount, keyed with the fixture's
|
|
194
|
+
* `confirmation_key`. The state is a MAC over that key, so a mount with
|
|
195
|
+
* a different key cannot replay round 2.
|
|
196
|
+
*/
|
|
197
|
+
describe('MCP wire conformance — MRTR confirmation loop', () => {
|
|
198
|
+
const doc = loadFixtures();
|
|
199
|
+
const mrtr = doc.mrtr;
|
|
200
|
+
|
|
201
|
+
it('loads the mrtr section', () => {
|
|
202
|
+
expect(mrtr).toBeDefined();
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it(`mrtr round trip — ${mrtr?.why ?? ''}`, async () => {
|
|
206
|
+
if (mrtr === undefined) throw new Error('fixture has no mrtr section');
|
|
207
|
+
|
|
208
|
+
const { bridge, executions } = mrtrLockBridge();
|
|
209
|
+
const handler = createMcpHandler(bridge, {
|
|
210
|
+
confirmationKey: mrtr.confirmation_key,
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// --- Round 1: the prompt -------------------------------------------
|
|
214
|
+
const r1 = await handler({
|
|
215
|
+
method: 'POST',
|
|
216
|
+
headers: {
|
|
217
|
+
'Content-Type': 'application/json',
|
|
218
|
+
...mrtr.round1_headers,
|
|
219
|
+
},
|
|
220
|
+
body: mrtr.round1_request,
|
|
221
|
+
});
|
|
222
|
+
expect(r1.status, 'round1 status').toBe(mrtr.round1_status);
|
|
223
|
+
|
|
224
|
+
const body1 = JSON.parse(r1.body) as {
|
|
225
|
+
result?: Record<string, unknown>;
|
|
226
|
+
};
|
|
227
|
+
const res1 = body1.result;
|
|
228
|
+
expect(res1, 'round1 carries a result').toBeDefined();
|
|
229
|
+
if (res1 === undefined) return;
|
|
230
|
+
|
|
231
|
+
// The leaf must NOT have run: that is the entire defect this
|
|
232
|
+
// section exists to catch. A port gating on X-Confirm-Token alone
|
|
233
|
+
// would have refused at 428 above; a port with no gate at all would
|
|
234
|
+
// have executed here.
|
|
235
|
+
expect(executions(), 'leaf executed before confirmation').toBe(0);
|
|
236
|
+
|
|
237
|
+
for (const [path, want] of Object.entries(mrtr.round1_must_have)) {
|
|
238
|
+
expect(dig(res1, path), `round1 ${path}`).toBe(want);
|
|
239
|
+
}
|
|
240
|
+
for (const absent of mrtr.round1_must_not_have) {
|
|
241
|
+
expect(absent in res1, `round1 must not carry ${absent}`).toBe(false);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Exactly one entry, under the reserved "confirm" key.
|
|
245
|
+
const requests = res1.inputRequests as Record<string, unknown>;
|
|
246
|
+
expect(Object.keys(requests), 'inputRequests keys').toEqual(['confirm']);
|
|
247
|
+
|
|
248
|
+
// `v1.<expiry-base10>.<mac>` — three dot-separated parts. The MAC
|
|
249
|
+
// is production-derived and never compared.
|
|
250
|
+
const state = res1.requestState;
|
|
251
|
+
expect(typeof state, 'requestState is a string').toBe('string');
|
|
252
|
+
const parts = String(state).split('.');
|
|
253
|
+
expect(parts.length, 'requestState part count').toBe(3);
|
|
254
|
+
expect(parts[0], 'requestState version').toBe('v1');
|
|
255
|
+
expect(parts[1], 'requestState expiry is base-10').toMatch(/^\d+$/);
|
|
256
|
+
expect(parts[2].length, 'requestState mac is non-empty').toBeGreaterThan(0);
|
|
257
|
+
|
|
258
|
+
// --- Round 2: the accepted retry, byte-exact ------------------------
|
|
259
|
+
const r2 = await handler({
|
|
260
|
+
method: 'POST',
|
|
261
|
+
headers: {
|
|
262
|
+
'Content-Type': 'application/json',
|
|
263
|
+
...mrtr.round2_headers,
|
|
264
|
+
},
|
|
265
|
+
body: mrtr.round2_request_template.replace(
|
|
266
|
+
'{{requestState}}',
|
|
267
|
+
String(state),
|
|
268
|
+
),
|
|
269
|
+
});
|
|
270
|
+
expect(r2.status, 'round2 status').toBe(mrtr.round2_status);
|
|
271
|
+
expect(r2.body, 'round2 body').toBe(mrtr.round2_response);
|
|
272
|
+
expect(executions(), 'executions after accept').toBe(1);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A state minted under a different key cannot replay round 2.
|
|
277
|
+
*
|
|
278
|
+
* The happy-path exchange above only ever presents a genuine state,
|
|
279
|
+
* so on its own it cannot tell a mount that verifies the MAC from one
|
|
280
|
+
* that waves any well-formed token through. Here the token is
|
|
281
|
+
* correctly framed and correctly bound to the call — only the key
|
|
282
|
+
* behind the MAC differs — and it must still be refused.
|
|
283
|
+
*
|
|
284
|
+
* Re-prompting rather than erroring is the deliberate choice: the
|
|
285
|
+
* user can still approve, and a token error is not actionable by
|
|
286
|
+
* them. What must never happen is the leaf running.
|
|
287
|
+
*/
|
|
288
|
+
it('refuses a retry whose state was minted under another key', async () => {
|
|
289
|
+
if (mrtr === undefined) throw new Error('fixture has no mrtr section');
|
|
290
|
+
|
|
291
|
+
// The forger's mount: same tree, same call, different secret.
|
|
292
|
+
const forger = createMcpHandler(mrtrLockBridge().bridge, {
|
|
293
|
+
confirmationKey: 'a-different-suite-shared-secret!!',
|
|
294
|
+
});
|
|
295
|
+
const minted = await forger({
|
|
296
|
+
method: 'POST',
|
|
297
|
+
headers: { 'Content-Type': 'application/json', ...mrtr.round1_headers },
|
|
298
|
+
body: mrtr.round1_request,
|
|
299
|
+
});
|
|
300
|
+
const state = (JSON.parse(minted.body) as { result?: { requestState?: unknown } })
|
|
301
|
+
.result?.requestState;
|
|
302
|
+
expect(typeof state, 'foreign round1 minted a state string').toBe('string');
|
|
303
|
+
|
|
304
|
+
// The real mount, keyed by the fixture.
|
|
305
|
+
const { bridge, executions } = mrtrLockBridge();
|
|
306
|
+
const handler = createMcpHandler(bridge, {
|
|
307
|
+
confirmationKey: mrtr.confirmation_key,
|
|
308
|
+
});
|
|
309
|
+
const res = await handler({
|
|
310
|
+
method: 'POST',
|
|
311
|
+
headers: { 'Content-Type': 'application/json', ...mrtr.round2_headers },
|
|
312
|
+
body: mrtr.round2_request_template.replace(
|
|
313
|
+
'{{requestState}}',
|
|
314
|
+
String(state),
|
|
315
|
+
),
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
const result = (JSON.parse(res.body) as { result?: Record<string, unknown> })
|
|
319
|
+
.result;
|
|
320
|
+
expect(result, 'foreign round2 carries a result').toBeDefined();
|
|
321
|
+
expect(result?.resultType, 'foreign round2 must re-prompt').toBe(
|
|
322
|
+
'input_required',
|
|
323
|
+
);
|
|
324
|
+
expect(executions(), 'leaf ran on a state minted under another key').toBe(0);
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
/** Reads a dotted path out of a decoded result, for the fixture's assertions. */
|
|
329
|
+
function dig(root: Record<string, unknown>, path: string): unknown {
|
|
330
|
+
let cur: unknown = root;
|
|
331
|
+
for (const seg of path.split('.')) {
|
|
332
|
+
if (cur === null || typeof cur !== 'object') return undefined;
|
|
333
|
+
cur = (cur as Record<string, unknown>)[seg];
|
|
334
|
+
}
|
|
335
|
+
return cur;
|
|
336
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module mcp/dispatch
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* Era detection + dispatch for the dual-spec MCP surface, plus the
|
|
6
|
+
* framework-free handler export.
|
|
7
|
+
*
|
|
8
|
+
* Hosting model (ADR 0043 §2): this module exports a
|
|
9
|
+
* transport-agnostic request handler, not a server. Binding it to
|
|
10
|
+
* node:http, hono, express, fastify, or a Worker is the adopter's
|
|
11
|
+
* job — kit does not own the adopter's HTTP stack, and a pure
|
|
12
|
+
* request→response function is directly testable against the wire
|
|
13
|
+
* fixtures with no socket.
|
|
14
|
+
*
|
|
15
|
+
* Detection implements ADR 0042's normative rules literally: the
|
|
16
|
+
* marker set M1-M4, the two deliberate non-markers, and the
|
|
17
|
+
* precedence chain D1-D4. It deliberately does NOT delegate to the
|
|
18
|
+
* v2 SDK's own `classifyInboundRequest`: that classifier treats a
|
|
19
|
+
* modern `MCP-Protocol-Version` header as a routing signal and
|
|
20
|
+
* routes `initialize`-plus-modern-envelope to the modern era, both
|
|
21
|
+
* of which contradict ADR 0042 (and the wire fixtures, which are the
|
|
22
|
+
* parity contract). The SDK is still the source of the protocol
|
|
23
|
+
* constants and error codes — see types.ts.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
MCP_ERR_INTERNAL,
|
|
28
|
+
META_KEY_PROTOCOL_VERSION,
|
|
29
|
+
HEADER_MCP_METHOD,
|
|
30
|
+
HEADER_MCP_NAME,
|
|
31
|
+
RawJSON,
|
|
32
|
+
resolveMcpConfig,
|
|
33
|
+
type McpBridge,
|
|
34
|
+
type McpMountOptions,
|
|
35
|
+
type ResolvedMcpConfig,
|
|
36
|
+
} from './types.js';
|
|
37
|
+
import {
|
|
38
|
+
headerValues,
|
|
39
|
+
LegacyMcpHandler,
|
|
40
|
+
parseErrorResponse,
|
|
41
|
+
writeError,
|
|
42
|
+
} from './legacy.js';
|
|
43
|
+
import { ModernMcpHandler } from './modern.js';
|
|
44
|
+
|
|
45
|
+
// --- normalized request / response --------------------------------------
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A normalized inbound request: method, headers, and body bytes. A
|
|
49
|
+
* header may repeat, which the modern header checks treat as
|
|
50
|
+
* significant, so values may be an array.
|
|
51
|
+
*/
|
|
52
|
+
export interface McpHttpRequest {
|
|
53
|
+
/** HTTP method, e.g. "POST". */
|
|
54
|
+
method: string;
|
|
55
|
+
/** Header names are matched case-insensitively. */
|
|
56
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
57
|
+
/** Raw body bytes, exactly as received — never re-encoded. */
|
|
58
|
+
body?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A normalized response: status, headers, and body bytes. */
|
|
62
|
+
export interface McpHttpResponse {
|
|
63
|
+
status: number;
|
|
64
|
+
headers: Record<string, string>;
|
|
65
|
+
body: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Builds a JSON response with the surface's standard content type. */
|
|
69
|
+
export function jsonResponse(status: number, body: string): McpHttpResponse {
|
|
70
|
+
return {
|
|
71
|
+
status,
|
|
72
|
+
headers: { 'Content-Type': 'application/json' },
|
|
73
|
+
body,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The 202 a modern notification receives: empty body, not processed. */
|
|
78
|
+
export function acceptedResponse(): McpHttpResponse {
|
|
79
|
+
return { status: 202, headers: {}, body: '' };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// --- parsed request -----------------------------------------------------
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A decoded JSON-RPC request envelope. `id` is kept as a raw JSON
|
|
86
|
+
* fragment so it round-trips byte-for-byte (Go uses json.RawMessage
|
|
87
|
+
* for exactly this reason), and its absence is distinguishable from
|
|
88
|
+
* an explicit null.
|
|
89
|
+
*/
|
|
90
|
+
export interface JsonRpcRequest {
|
|
91
|
+
jsonrpc?: string;
|
|
92
|
+
id?: RawJSON;
|
|
93
|
+
method: string;
|
|
94
|
+
params?: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Which handler a request routes to. */
|
|
98
|
+
export type McpEra = 'legacy' | 'modern';
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Implements ADR 0042's per-request era detection, precedence D1-D4.
|
|
102
|
+
* Never fails — it only classifies an already-parsed request; D1
|
|
103
|
+
* (parse) is the caller's responsibility.
|
|
104
|
+
*
|
|
105
|
+
* Markers:
|
|
106
|
+
* M1 — Mcp-Method header present
|
|
107
|
+
* M2 — Mcp-Name header present
|
|
108
|
+
* M3 — params._meta contains the reserved protocolVersion key
|
|
109
|
+
* (key presence only; the value is not inspected here)
|
|
110
|
+
* M4 — method == "server/discover"
|
|
111
|
+
*
|
|
112
|
+
* Deliberate non-markers, both of which are the subtle part and the
|
|
113
|
+
* most likely source of silent divergence:
|
|
114
|
+
* - Bare params._meta. 2024-11-05 clients legitimately send
|
|
115
|
+
* _meta.progressToken and OTel traceparent; only the reserved
|
|
116
|
+
* protocolVersion key signals modern.
|
|
117
|
+
* - The MCP-Protocol-Version header, at any value. It predates
|
|
118
|
+
* 2026-07-28, so clients that negotiated down to legacy send it
|
|
119
|
+
* on every subsequent request; treating it as a modern signal
|
|
120
|
+
* would serve their handshake and then brick the session.
|
|
121
|
+
*/
|
|
122
|
+
export function detectMcpEra(
|
|
123
|
+
req: McpHttpRequest,
|
|
124
|
+
rpc: JsonRpcRequest,
|
|
125
|
+
): McpEra {
|
|
126
|
+
// D2 — initialize is legacy, unconditionally, even when modern
|
|
127
|
+
// markers are present. The spec's dual-era rule says initialize
|
|
128
|
+
// selects legacy semantics; a confused client gets a working legacy
|
|
129
|
+
// handshake, the most recoverable outcome.
|
|
130
|
+
if (rpc.method === 'initialize') return 'legacy';
|
|
131
|
+
|
|
132
|
+
// M4 — method == "server/discover".
|
|
133
|
+
if (rpc.method === 'server/discover') return 'modern';
|
|
134
|
+
|
|
135
|
+
// M1 / M2 — header presence.
|
|
136
|
+
if (headerValues(req, HEADER_MCP_METHOD).length > 0) return 'modern';
|
|
137
|
+
if (headerValues(req, HEADER_MCP_NAME).length > 0) return 'modern';
|
|
138
|
+
|
|
139
|
+
// M3 — params._meta carries the reserved protocolVersion key.
|
|
140
|
+
if (hasModernMetaMarker(rpc.params)) return 'modern';
|
|
141
|
+
|
|
142
|
+
// D4 — no markers: legacy. This is the byte-for-byte preservation
|
|
143
|
+
// path: every request a legacy client can send takes today's exact
|
|
144
|
+
// code path.
|
|
145
|
+
return 'legacy';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* M3: whether params._meta carries the reserved protocolVersion key.
|
|
150
|
+
* Only key presence is tested; the value is never inspected at
|
|
151
|
+
* detection time. Malformed or non-object params/_meta are treated as
|
|
152
|
+
* "no marker" — detection never fails, and shape errors are the
|
|
153
|
+
* handlers' business.
|
|
154
|
+
*/
|
|
155
|
+
export function hasModernMetaMarker(params: unknown): boolean {
|
|
156
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
const meta = (params as Record<string, unknown>)._meta;
|
|
160
|
+
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
return META_KEY_PROTOCOL_VERSION in (meta as Record<string, unknown>);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// --- handler ------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
/** A framework-free MCP request handler. */
|
|
169
|
+
export type McpHandler = (
|
|
170
|
+
req: McpHttpRequest,
|
|
171
|
+
) => Promise<McpHttpResponse>;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Builds the MCP handler for a bridge. Mirrors Go's
|
|
175
|
+
* `MountMCP(bridge, router, opts...)`, minus the router: the caller
|
|
176
|
+
* binds the returned function to whatever HTTP stack it uses.
|
|
177
|
+
*
|
|
178
|
+
* Defaults match Go exactly: both eras enabled, path "/mcp", empty
|
|
179
|
+
* origin allowlist, cache hints ttlMs=0 / cacheScope="private".
|
|
180
|
+
* The two mount-time errors are reproduced rather than absorbed —
|
|
181
|
+
* an explicit empty spec-version set, and a negative ttl or
|
|
182
|
+
* unrecognized cache scope, both throw here.
|
|
183
|
+
*/
|
|
184
|
+
export function createMcpHandler(
|
|
185
|
+
bridge: McpBridge,
|
|
186
|
+
opts: McpMountOptions = {},
|
|
187
|
+
): McpHandler {
|
|
188
|
+
const cfg = resolveMcpConfig(opts);
|
|
189
|
+
const dispatcher = new McpDispatcher(bridge, cfg);
|
|
190
|
+
return (req) => dispatcher.handle(req);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The resolved mount config for a handler, for adopters that need it. */
|
|
194
|
+
export function mcpMountConfig(
|
|
195
|
+
opts: McpMountOptions = {},
|
|
196
|
+
): ResolvedMcpConfig {
|
|
197
|
+
return resolveMcpConfig(opts);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Routes each request to exactly one era's handler. Holds no mutable
|
|
202
|
+
* per-request state; both handlers are safe to share concurrently.
|
|
203
|
+
*/
|
|
204
|
+
export class McpDispatcher {
|
|
205
|
+
private readonly legacy: LegacyMcpHandler;
|
|
206
|
+
private readonly modern: ModernMcpHandler;
|
|
207
|
+
|
|
208
|
+
constructor(
|
|
209
|
+
bridge: McpBridge,
|
|
210
|
+
private readonly cfg: ResolvedMcpConfig,
|
|
211
|
+
) {
|
|
212
|
+
this.legacy = new LegacyMcpHandler(bridge, cfg);
|
|
213
|
+
this.modern = new ModernMcpHandler(bridge, cfg);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async handle(req: McpHttpRequest): Promise<McpHttpResponse> {
|
|
217
|
+
const verb = (req.method || 'POST').toUpperCase();
|
|
218
|
+
if (verb !== 'POST') {
|
|
219
|
+
// GET and DELETE answer 405 when the modern era is enabled
|
|
220
|
+
// (spec SHOULD for post-session servers). With only the legacy
|
|
221
|
+
// era mounted there is no such route at all, matching Go, where
|
|
222
|
+
// those verbs are simply never registered.
|
|
223
|
+
if (this.cfg.modernEnabled && (verb === 'GET' || verb === 'DELETE')) {
|
|
224
|
+
return methodNotAllowedResponse();
|
|
225
|
+
}
|
|
226
|
+
return methodNotAllowedResponse();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// D1 — read and parse the body once. An unreadable body is
|
|
230
|
+
// -32603 @ 400; unparseable JSON is -32700 @ 400 — both
|
|
231
|
+
// byte-identical to the legacy responses, regardless of any
|
|
232
|
+
// headers present.
|
|
233
|
+
const body = req.body;
|
|
234
|
+
if (body === undefined) {
|
|
235
|
+
return writeError(
|
|
236
|
+
undefined,
|
|
237
|
+
{
|
|
238
|
+
code: MCP_ERR_INTERNAL,
|
|
239
|
+
message: 'read request body: unexpected EOF',
|
|
240
|
+
},
|
|
241
|
+
400,
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
let rpc: JsonRpcRequest;
|
|
246
|
+
try {
|
|
247
|
+
rpc = parseJsonRpcRequest(body);
|
|
248
|
+
} catch {
|
|
249
|
+
return parseErrorResponse(body);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Modern-only mounts route everything to the modern handler and
|
|
253
|
+
// handle it per the normal V1-V9 order — no special-casing of
|
|
254
|
+
// initialize anywhere, since D2 exists to hand a confused client
|
|
255
|
+
// to a legacy handler that is not mounted here.
|
|
256
|
+
if (this.cfg.modernEnabled && !this.cfg.legacyEnabled) {
|
|
257
|
+
return this.modern.serve(req, rpc);
|
|
258
|
+
}
|
|
259
|
+
// Legacy-only mounts ignore markers exactly as the pre-dual-spec
|
|
260
|
+
// surface did.
|
|
261
|
+
if (this.cfg.legacyEnabled && !this.cfg.modernEnabled) {
|
|
262
|
+
return this.legacy.serve(req, rpc);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
switch (detectMcpEra(req, rpc)) {
|
|
266
|
+
case 'modern':
|
|
267
|
+
return this.modern.serve(req, rpc);
|
|
268
|
+
default:
|
|
269
|
+
return this.legacy.serve(req, rpc);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The 405 GET/DELETE answer at the mount path. */
|
|
275
|
+
export function methodNotAllowedResponse(): McpHttpResponse {
|
|
276
|
+
return jsonResponse(
|
|
277
|
+
405,
|
|
278
|
+
'{"jsonrpc":"2.0","error":{"code":-32600,"message":"method not allowed"}}\n',
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Parses one JSON-RPC request, preserving the `id` as raw bytes.
|
|
284
|
+
* Throws on unparseable JSON so the caller can render D1's -32700.
|
|
285
|
+
*/
|
|
286
|
+
export function parseJsonRpcRequest(body: string): JsonRpcRequest {
|
|
287
|
+
const decoded: unknown = JSON.parse(body);
|
|
288
|
+
if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded)) {
|
|
289
|
+
// Go decodes a non-object body into its request struct and fails,
|
|
290
|
+
// which surfaces as a parse error at the same place.
|
|
291
|
+
throw new SyntaxError('not a JSON-RPC object');
|
|
292
|
+
}
|
|
293
|
+
const obj = decoded as Record<string, unknown>;
|
|
294
|
+
const out: JsonRpcRequest = {
|
|
295
|
+
method: typeof obj.method === 'string' ? obj.method : '',
|
|
296
|
+
};
|
|
297
|
+
if (typeof obj.jsonrpc === 'string') out.jsonrpc = obj.jsonrpc;
|
|
298
|
+
if ('id' in obj) out.id = new RawJSON(rawIdBytes(body, obj.id));
|
|
299
|
+
if ('params' in obj) out.params = obj.params;
|
|
300
|
+
return out;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Re-serializes the request id. The id shapes JSON-RPC permits
|
|
305
|
+
* (string, number, null) all round-trip identically through
|
|
306
|
+
* JSON.stringify, which is what Go's json.RawMessage echo produces
|
|
307
|
+
* for the same inputs. `_body` is accepted so a future
|
|
308
|
+
* exactness-sensitive change (e.g. preserving a number's original
|
|
309
|
+
* literal spelling) has the source text to work from.
|
|
310
|
+
*/
|
|
311
|
+
function rawIdBytes(_body: string, id: unknown): string {
|
|
312
|
+
return JSON.stringify(id) ?? 'null';
|
|
313
|
+
}
|