@frontmcp/testing 1.10.9-rc.1 → 1.10.9-rc.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/fixtures/index.js CHANGED
@@ -1,4296 +1,32 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // libs/testing/src/fixtures/index.ts
21
- var fixtures_exports = {};
22
- __export(fixtures_exports, {
23
- cleanupSharedResources: () => cleanupSharedResources,
24
- cleanupTestFixtures: () => cleanupTestFixtures,
25
- createTestFixtures: () => createTestFixtures,
26
- initializeSharedResources: () => initializeSharedResources,
27
- test: () => test
28
- });
29
- module.exports = __toCommonJS(fixtures_exports);
30
-
31
- // libs/testing/src/auth/token-factory.ts
32
- var import_jose = require("jose");
33
- var TestTokenFactory = class {
34
- issuer;
35
- audience;
36
- privateKey = null;
37
- publicKey = null;
38
- jwk = null;
39
- keyId;
40
- /** HS256 shared secret (gateway mode). Null → RS256 + JWKS (default). */
41
- hmacSecret;
42
- constructor(options = {}) {
43
- this.issuer = options.issuer ?? "https://test.frontmcp.local";
44
- this.audience = options.audience ?? "frontmcp-test";
45
- this.keyId = `test-key-${Date.now()}`;
46
- this.hmacSecret = options.hmacSecret ? new TextEncoder().encode(options.hmacSecret) : null;
47
- }
48
- /** True when this factory signs HS256 with a shared secret (gateway mode). */
49
- get isHmac() {
50
- return this.hmacSecret !== null;
51
- }
52
- /** The JWS `alg` this factory signs with. */
53
- get alg() {
54
- return this.isHmac ? "HS256" : "RS256";
55
- }
56
- /**
57
- * The signing key: the shared HMAC secret in gateway mode, otherwise the
58
- * generated RSA private key (lazily created via ensureKeys()).
59
- */
60
- signingKey() {
61
- if (this.hmacSecret) return this.hmacSecret;
62
- if (!this.privateKey) {
63
- throw new Error("Private key not initialized");
64
- }
65
- return this.privateKey;
66
- }
67
- /**
68
- * Initialize the key pair (called automatically on first use). No-op in HS256
69
- * mode — there is no asymmetric keypair, just the shared secret.
70
- */
71
- async ensureKeys() {
72
- if (this.isHmac) return;
73
- if (this.privateKey && this.publicKey) return;
74
- const { publicKey, privateKey } = await (0, import_jose.generateKeyPair)("RS256", {
75
- extractable: true
76
- });
77
- this.privateKey = privateKey;
78
- this.publicKey = publicKey;
79
- this.jwk = await (0, import_jose.exportJWK)(publicKey);
80
- this.jwk.kid = this.keyId;
81
- this.jwk.use = "sig";
82
- this.jwk.alg = "RS256";
83
- }
84
- /**
85
- * Create a JWT token with the specified claims
86
- */
87
- async createTestToken(options) {
88
- await this.ensureKeys();
89
- const nowMs = Date.now();
90
- const iat = Math.floor(nowMs / 1e3);
91
- const exp = options.exp ?? 3600;
92
- const payload = {
93
- iss: options.iss ?? this.issuer,
94
- sub: options.sub,
95
- aud: options.aud ?? this.audience,
96
- iat,
97
- exp: Math.ceil(nowMs / 1e3) + exp,
98
- scope: options.scopes?.join(" "),
99
- ...options.claims
100
- };
101
- const header = this.isHmac ? { alg: this.alg, typ: "JWT" } : { alg: this.alg, kid: this.keyId };
102
- const token = await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());
103
- return token;
104
- }
105
- /**
106
- * Create an admin token with full access
107
- */
108
- async createAdminToken(sub = "admin-001") {
109
- return this.createTestToken({
110
- sub,
111
- scopes: ["admin:*", "read", "write", "delete"],
112
- claims: {
113
- email: "admin@test.local",
114
- name: "Test Admin",
115
- role: "admin"
116
- }
117
- });
118
- }
119
- /**
120
- * Create a regular user token
121
- */
122
- async createUserToken(sub = "user-001", scopes2 = ["read", "write"]) {
123
- return this.createTestToken({
124
- sub,
125
- scopes: scopes2,
126
- claims: {
127
- email: "user@test.local",
128
- name: "Test User",
129
- role: "user"
130
- }
131
- });
132
- }
133
- /**
134
- * Create an anonymous user token
135
- */
136
- async createAnonymousToken(expiresIn) {
137
- return this.createTestToken({
138
- sub: `anon:${Date.now()}`,
139
- scopes: ["anonymous"],
140
- exp: expiresIn,
141
- claims: {
142
- name: "Anonymous",
143
- role: "anonymous"
144
- }
145
- });
146
- }
147
- /**
148
- * Create an expired token (for testing token expiration)
149
- */
150
- async createExpiredToken(options) {
151
- await this.ensureKeys();
152
- const now = Math.floor(Date.now() / 1e3);
153
- const payload = {
154
- iss: this.issuer,
155
- sub: options.sub,
156
- aud: this.audience,
157
- iat: now - 7200,
158
- // 2 hours ago
159
- exp: now - 3600
160
- // Expired 1 hour ago
161
- };
162
- const header = this.isHmac ? { alg: this.alg, typ: "JWT" } : { alg: this.alg, kid: this.keyId };
163
- const token = await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());
164
- return token;
165
- }
166
- /**
167
- * Create a token with an invalid signature (for testing signature validation)
168
- */
169
- createTokenWithInvalidSignature(options) {
170
- const now = Math.floor(Date.now() / 1e3);
171
- const headerObj = this.isHmac ? { alg: this.alg, typ: "JWT" } : { alg: this.alg, kid: this.keyId };
172
- const header = Buffer.from(JSON.stringify(headerObj)).toString("base64url");
173
- const payload = Buffer.from(
174
- JSON.stringify({
175
- iss: this.issuer,
176
- sub: options.sub,
177
- aud: this.audience,
178
- iat: now,
179
- exp: now + 3600
180
- })
181
- ).toString("base64url");
182
- const signature = Buffer.from("invalid-signature-" + Date.now()).toString("base64url");
183
- return `${header}.${payload}.${signature}`;
184
- }
185
- /**
186
- * Get the public JWKS for verifying tokens.
187
- *
188
- * Only meaningful in RS256 mode — HS256 (gateway) tokens are verified against
189
- * the shared secret, not a published public key, so there is no JWKS to serve.
190
- */
191
- async getPublicJwks() {
192
- if (this.isHmac) {
193
- throw new Error("getPublicJwks() is not available in HS256 mode (gateway tokens use a shared secret)");
194
- }
195
- await this.ensureKeys();
196
- if (!this.jwk) {
197
- throw new Error("JWK not initialized");
198
- }
199
- return {
200
- keys: [this.jwk]
201
- };
202
- }
203
- /**
204
- * Get the issuer URL
205
- */
206
- getIssuer() {
207
- return this.issuer;
208
- }
209
- /**
210
- * Get the audience
211
- */
212
- getAudience() {
213
- return this.audience;
214
- }
215
- };
216
-
217
- // libs/testing/src/interceptor/mock-registry.ts
218
- var DefaultMockRegistry = class {
219
- mocks = [];
220
- add(mock) {
221
- const entry = {
222
- definition: mock,
223
- callCount: 0,
224
- calls: [],
225
- remainingUses: mock.times ?? Infinity
226
- };
227
- this.mocks.push(entry);
228
- return {
229
- remove: () => {
230
- const index = this.mocks.indexOf(entry);
231
- if (index !== -1) {
232
- this.mocks.splice(index, 1);
233
- }
234
- },
235
- callCount: () => entry.callCount,
236
- calls: () => [...entry.calls]
237
- };
238
- }
239
- clear() {
240
- this.mocks = [];
241
- }
242
- getAll() {
243
- return this.mocks.map((e) => e.definition);
244
- }
245
- match(request) {
246
- for (const entry of this.mocks) {
247
- if (entry.remainingUses <= 0) continue;
248
- const { definition } = entry;
249
- if (definition.method !== request.method) continue;
250
- if (definition.params !== void 0) {
251
- const params = request.params ?? {};
252
- if (typeof definition.params === "function") {
253
- if (!definition.params(params)) continue;
254
- } else {
255
- if (!this.paramsMatch(definition.params, params)) continue;
256
- }
257
- }
258
- entry.callCount++;
259
- entry.calls.push(request);
260
- entry.remainingUses--;
261
- return definition;
262
- }
263
- return void 0;
264
- }
265
- /**
266
- * Check if request params match the mock params definition
267
- */
268
- paramsMatch(expected, actual) {
269
- for (const [key, value] of Object.entries(expected)) {
270
- if (!(key in actual)) return false;
271
- const actualValue = actual[key];
272
- if (Array.isArray(value)) {
273
- if (!Array.isArray(actualValue)) return false;
274
- if (value.length !== actualValue.length) return false;
275
- for (let i = 0; i < value.length; i++) {
276
- const expectedItem = value[i];
277
- const actualItem = actualValue[i];
278
- if (typeof expectedItem === "object" && expectedItem !== null) {
279
- if (typeof actualItem !== "object" || actualItem === null) return false;
280
- if (!this.paramsMatch(expectedItem, actualItem)) {
281
- return false;
282
- }
283
- } else if (actualItem !== expectedItem) {
284
- return false;
285
- }
286
- }
287
- } else if (typeof value === "object" && value !== null) {
288
- if (typeof actualValue !== "object" || actualValue === null) return false;
289
- if (!this.paramsMatch(value, actualValue)) {
290
- return false;
291
- }
292
- } else if (actualValue !== value) {
293
- return false;
294
- }
295
- }
296
- return true;
297
- }
298
- };
299
- var mockResponse = {
300
- /**
301
- * Create a successful JSON-RPC response
302
- */
303
- success(result, id = 1) {
304
- return {
305
- jsonrpc: "2.0",
306
- id,
307
- result
308
- };
309
- },
310
- /**
311
- * Create an error JSON-RPC response
312
- */
313
- error(code, message, data, id = 1) {
314
- return {
315
- jsonrpc: "2.0",
316
- id,
317
- error: { code, message, data }
318
- };
319
- },
320
- /**
321
- * Create a tool result response
322
- */
323
- toolResult(content, id = 1) {
324
- return {
325
- jsonrpc: "2.0",
326
- id,
327
- result: { content }
328
- };
329
- },
330
- /**
331
- * Create a tools/list response
332
- */
333
- toolsList(tools, id = 1) {
334
- return {
335
- jsonrpc: "2.0",
336
- id,
337
- result: { tools }
338
- };
339
- },
340
- /**
341
- * Create a resources/list response
342
- */
343
- resourcesList(resources, id = 1) {
344
- return {
345
- jsonrpc: "2.0",
346
- id,
347
- result: { resources }
348
- };
349
- },
350
- /**
351
- * Create a resources/read response
352
- */
353
- resourceRead(contents, id = 1) {
354
- return {
355
- jsonrpc: "2.0",
356
- id,
357
- result: { contents }
358
- };
359
- },
360
- /**
361
- * Common MCP errors
362
- */
363
- errors: {
364
- methodNotFound: (method, id = 1) => mockResponse.error(-32601, `Method not found: ${method}`, void 0, id),
365
- invalidParams: (message, id = 1) => mockResponse.error(-32602, message, void 0, id),
366
- internalError: (message, id = 1) => mockResponse.error(-32603, message, void 0, id),
367
- resourceNotFound: (uri, id = 1) => mockResponse.error(-32002, `Resource not found: ${uri}`, { uri }, id),
368
- toolNotFound: (name, id = 1) => mockResponse.error(-32601, `Tool not found: ${name}`, { name }, id),
369
- unauthorized: (id = 1) => mockResponse.error(-32001, "Unauthorized", void 0, id),
370
- forbidden: (id = 1) => mockResponse.error(-32003, "Forbidden", void 0, id)
371
- }
372
- };
373
-
374
- // libs/testing/src/interceptor/interceptor-chain.ts
375
- var DefaultInterceptorChain = class {
376
- request = [];
377
- response = [];
378
- mocks;
379
- constructor() {
380
- this.mocks = new DefaultMockRegistry();
381
- }
382
- /**
383
- * Add a request interceptor
384
- */
385
- addRequestInterceptor(interceptor) {
386
- this.request.push(interceptor);
387
- return () => {
388
- const index = this.request.indexOf(interceptor);
389
- if (index !== -1) {
390
- this.request.splice(index, 1);
391
- }
392
- };
393
- }
394
- /**
395
- * Add a response interceptor
396
- */
397
- addResponseInterceptor(interceptor) {
398
- this.response.push(interceptor);
399
- return () => {
400
- const index = this.response.indexOf(interceptor);
401
- if (index !== -1) {
402
- this.response.splice(index, 1);
403
- }
404
- };
405
- }
406
- /**
407
- * Process a request through the interceptor chain
408
- * Returns either:
409
- * - { type: 'continue', request } - continue with (possibly modified) request
410
- * - { type: 'mock', response } - return mock response immediately
411
- * - { type: 'error', error } - throw error
412
- */
413
- async processRequest(request, meta) {
414
- let currentRequest = request;
415
- const mockDef = this.mocks.match(request);
416
- if (mockDef) {
417
- if (mockDef.delay && mockDef.delay > 0) {
418
- await sleep(mockDef.delay);
419
- }
420
- let mockResponse2;
421
- if (typeof mockDef.response === "function") {
422
- mockResponse2 = await mockDef.response(request);
423
- } else {
424
- mockResponse2 = mockDef.response;
425
- }
426
- return {
427
- type: "mock",
428
- response: { ...mockResponse2, id: request.id ?? mockResponse2.id }
429
- };
430
- }
431
- for (const interceptor of this.request) {
432
- const ctx = {
433
- request: currentRequest,
434
- meta
435
- };
436
- const result = await interceptor(ctx);
437
- switch (result.action) {
438
- case "passthrough":
439
- break;
440
- case "modify":
441
- currentRequest = result.request;
442
- break;
443
- case "mock":
444
- return {
445
- type: "mock",
446
- response: { ...result.response, id: request.id ?? result.response.id }
447
- };
448
- case "error":
449
- return { type: "error", error: result.error };
450
- }
451
- }
452
- return { type: "continue", request: currentRequest };
453
- }
454
- /**
455
- * Process a response through the interceptor chain
456
- */
457
- async processResponse(request, response, durationMs) {
458
- let currentResponse = response;
459
- for (const interceptor of this.response) {
460
- const ctx = {
461
- request,
462
- response: currentResponse,
463
- durationMs
464
- };
465
- const result = await interceptor(ctx);
466
- switch (result.action) {
467
- case "passthrough":
468
- break;
469
- case "modify":
470
- currentResponse = result.response;
471
- break;
472
- }
473
- }
474
- return currentResponse;
475
- }
476
- /**
477
- * Clear all interceptors and mocks
478
- */
479
- clear() {
480
- this.request = [];
481
- this.response = [];
482
- this.mocks.clear();
483
- }
484
- };
485
- function sleep(ms) {
486
- return new Promise((resolve) => setTimeout(resolve, ms));
487
- }
488
-
489
- // libs/testing/src/transport/error-utils.ts
490
- function errorName(err) {
491
- if (typeof err !== "object" || err === null) return void 0;
492
- const name = err.name;
493
- return typeof name === "string" ? name : void 0;
494
- }
495
- function isAbortError(err) {
496
- return errorName(err) === "AbortError";
497
- }
498
- function errorMessage(err, fallback = "Unknown error") {
499
- if (typeof err === "string" && err) return err;
500
- if (typeof err === "object" && err !== null) {
501
- const message = err.message;
502
- if (typeof message === "string" && message) return message;
503
- }
504
- return fallback;
505
- }
506
- var interceptedErrors = /* @__PURE__ */ new WeakSet();
507
- function markInterceptedError(err) {
508
- interceptedErrors.add(err);
509
- return err;
510
- }
511
- function isInterceptedError(err) {
512
- return typeof err === "object" && err !== null && interceptedErrors.has(err);
513
- }
514
-
515
- // libs/testing/src/transport/sse.transport.ts
516
- var DEFAULT_TIMEOUT = 3e4;
517
- var SseTransport = class {
518
- baseUrl;
519
- entryPath;
520
- timeout;
521
- authHeaders;
522
- publicMode;
523
- debug;
524
- clientInfo;
525
- notificationHandler;
526
- interceptors;
527
- elicitationHandler;
528
- state = "disconnected";
529
- authToken;
530
- sessionId;
531
- messageEndpoint;
532
- stream;
533
- pending = /* @__PURE__ */ new Map();
534
- connectionCount = 0;
535
- reconnectCount = 0;
536
- lastRequestHeaders = {};
537
- constructor(config) {
538
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
539
- this.entryPath = config.entryPath;
540
- this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
541
- this.authHeaders = config.auth?.headers ?? {};
542
- this.authToken = config.auth?.token;
543
- this.publicMode = config.publicMode ?? false;
544
- this.debug = config.debug ?? false;
545
- this.clientInfo = config.clientInfo;
546
- this.notificationHandler = config.notificationHandler;
547
- this.interceptors = config.interceptors;
548
- this.elicitationHandler = config.elicitationHandler;
549
- }
550
- async connect() {
551
- this.state = "connecting";
552
- this.connectionCount++;
553
- try {
554
- if (!this.publicMode && !this.authToken) {
555
- await this.requestAnonymousToken();
556
- }
557
- await this.openStream();
558
- this.state = "connected";
559
- this.log(`Connected; messages go to ${this.messageEndpoint}`);
560
- } catch (error) {
561
- this.state = "error";
562
- this.stream?.abort();
563
- this.stream = void 0;
564
- throw error;
565
- }
566
- }
567
- async request(message) {
568
- this.ensureConnected();
569
- const startTime = Date.now();
570
- if (this.interceptors) {
571
- const intercepted = await this.interceptors.processRequest(message, {
572
- timestamp: /* @__PURE__ */ new Date(),
573
- transport: "sse",
574
- sessionId: this.sessionId
575
- });
576
- switch (intercepted.type) {
577
- case "mock":
578
- return await this.interceptors.processResponse(
579
- message,
580
- intercepted.response,
581
- Date.now() - startTime
582
- );
583
- case "error":
584
- throw markInterceptedError(intercepted.error);
585
- case "continue":
586
- message = intercepted.request;
587
- break;
588
- }
589
- }
590
- let response;
591
- if (message.id === void 0) {
592
- await this.post(JSON.stringify(message));
593
- response = { jsonrpc: "2.0", id: null, result: void 0 };
594
- } else {
595
- response = await this.postAndAwait(message.id, JSON.stringify(message));
596
- }
597
- if (this.interceptors) {
598
- response = await this.interceptors.processResponse(message, response, Date.now() - startTime);
599
- }
600
- return response;
601
- }
602
- async notify(message) {
603
- this.ensureConnected();
604
- const result = await this.post(JSON.stringify(message));
605
- if (!result.ok) this.log(`HTTP ${result.status} on notification: ${result.body}`);
606
- }
607
- async sendRaw(data) {
608
- this.ensureConnected();
609
- let id;
610
- try {
611
- const parsed = JSON.parse(data);
612
- if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
613
- } catch {
614
- }
615
- if (id !== void 0) return this.postAndAwait(id, data);
616
- const result = await this.post(data);
617
- if (!result.ok) {
618
- return { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error", data: result.body } };
619
- }
620
- return { jsonrpc: "2.0", id: null, result: void 0 };
621
- }
622
- async close() {
623
- this.closeStream("Transport closed");
624
- this.state = "disconnected";
625
- this.sessionId = void 0;
626
- this.messageEndpoint = void 0;
627
- this.log("SSE transport closed");
628
- }
629
- isConnected() {
630
- return this.state === "connected";
631
- }
632
- getState() {
633
- return this.state;
634
- }
635
- getSessionId() {
636
- return this.sessionId;
637
- }
638
- setAuthToken(token) {
639
- this.authToken = token;
640
- }
641
- setTimeout(ms) {
642
- this.timeout = ms;
643
- }
644
- getMessageEndpoint() {
645
- return this.messageEndpoint;
646
- }
647
- getConnectionCount() {
648
- return this.connectionCount;
649
- }
650
- getReconnectCount() {
651
- return this.reconnectCount;
652
- }
653
- getLastRequestHeaders() {
654
- return { ...this.lastRequestHeaders };
655
- }
656
- setInterceptors(interceptors2) {
657
- this.interceptors = interceptors2;
658
- }
659
- getInterceptors() {
660
- return this.interceptors;
661
- }
662
- setElicitationHandler(handler) {
663
- this.elicitationHandler = handler;
664
- }
665
- async simulateDisconnect() {
666
- this.closeStream("Simulated disconnect");
667
- this.state = "disconnected";
668
- this.sessionId = void 0;
669
- this.messageEndpoint = void 0;
670
- }
671
- async waitForReconnect(timeoutMs) {
672
- this.reconnectCount++;
673
- let timer;
674
- try {
675
- await Promise.race([
676
- this.connect(),
677
- new Promise((_, reject) => {
678
- timer = setTimeout(() => reject(new Error("Timeout waiting for reconnection")), timeoutMs);
679
- })
680
- ]);
681
- } finally {
682
- clearTimeout(timer);
683
- }
684
- }
685
- // ═══════════════════════════════════════════════════════════════════
686
- // STREAM
687
- // ═══════════════════════════════════════════════════════════════════
688
- /** Open `GET <entry>/sse` and wait for the `endpoint` event. */
689
- async openStream() {
690
- const controller = new AbortController();
691
- this.stream = controller;
692
- const url = this.sseUrl();
693
- const { "Content-Type": _contentType, ...headers } = this.buildHeaders();
694
- this.log(`GET ${url}`);
695
- const connectTimer = setTimeout(() => controller.abort(), this.timeout);
696
- let response;
697
- try {
698
- response = await fetch(url, {
699
- method: "GET",
700
- headers: { ...headers, Accept: "text/event-stream" },
701
- signal: controller.signal
702
- });
703
- } catch (error) {
704
- clearTimeout(connectTimer);
705
- throw new Error(
706
- isAbortError(error) ? `SSE connection to ${url} timed out after ${this.timeout}ms` : `SSE connection to ${url} failed: ${errorMessage(error)}`,
707
- { cause: error }
708
- );
709
- }
710
- const isEventStream = response.headers.get("content-type")?.includes("text/event-stream") ?? false;
711
- if (!response.ok || !response.body || !isEventStream) {
712
- clearTimeout(connectTimer);
713
- const body = await response.text().catch(() => "");
714
- throw new Error(
715
- `SSE connection to ${url} failed: HTTP ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}. The legacy HTTP+SSE transport needs a server that serves it (@FrontMcp({ transport: { protocol: { legacy: true } } })).`
716
- );
717
- }
718
- const endpoint = new Promise((resolve, reject) => {
719
- const reader = response.body?.getReader();
720
- if (!reader) {
721
- reject(new Error(`SSE connection to ${url} has no body`));
722
- return;
723
- }
724
- void this.readStream(controller, reader, resolve, reject);
725
- });
726
- try {
727
- const data = await endpoint;
728
- const messageUrl = new URL(data, url);
729
- this.messageEndpoint = messageUrl.toString();
730
- this.sessionId = messageUrl.searchParams.get("sessionId") ?? void 0;
731
- } finally {
732
- clearTimeout(connectTimer);
733
- }
734
- }
735
- async readStream(controller, reader, onEndpoint, onEndpointError) {
736
- const decoder = new TextDecoder();
737
- let buffer = "";
738
- let endpointSeen = false;
739
- try {
740
- for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
741
- const { completeEvents, remainder } = splitSSEEvents(buffer + decoder.decode(chunk.value, { stream: true }));
742
- buffer = remainder;
743
- for (const text of completeEvents) {
744
- const event = parseSSEEvent(text);
745
- if (!event) continue;
746
- if (event.type === "endpoint") {
747
- if (!endpointSeen) {
748
- endpointSeen = true;
749
- onEndpoint(event.data);
750
- }
751
- continue;
752
- }
753
- await this.handleMessage(event.data);
754
- }
755
- }
756
- } catch (error) {
757
- if (!controller.signal.aborted) this.log("SSE stream failed:", error);
758
- } finally {
759
- reader.releaseLock();
760
- }
761
- if (!endpointSeen) {
762
- onEndpointError(
763
- new Error(
764
- controller.signal.aborted ? `SSE stream at ${this.sseUrl()} sent no endpoint event within ${this.timeout}ms` : `SSE stream at ${this.sseUrl()} ended before the server sent its endpoint`
765
- )
766
- );
767
- }
768
- if (this.stream === controller) {
769
- this.stream = void 0;
770
- this.rejectPending("SSE stream closed by the server");
771
- if (this.state === "connected") this.state = "disconnected";
772
- }
773
- }
774
- async handleMessage(data) {
775
- let message;
776
- try {
777
- message = JSON.parse(data);
778
- } catch {
779
- this.log("Ignoring SSE event that is not JSON:", data);
780
- return;
781
- }
782
- if (!message || typeof message !== "object") return;
783
- if (typeof message.method === "string") {
784
- const request = message;
785
- if (request.id === void 0 || request.id === null) {
786
- this.notificationHandler?.(request);
787
- return;
788
- }
789
- await this.answerServerRequest(request);
790
- return;
791
- }
792
- if (message.id !== void 0 && message.id !== null) {
793
- const pending = this.pending.get(message.id);
794
- if (pending) {
795
- clearTimeout(pending.timer);
796
- this.pending.delete(message.id);
797
- pending.resolve(message);
798
- }
799
- }
800
- }
801
- /** Server→client requests: elicitation goes to the handler, `ping` is answered, the rest refused. */
802
- async answerServerRequest(request) {
803
- const id = request.id;
804
- let reply;
805
- if (request.method === "elicitation/create") {
806
- reply = { jsonrpc: "2.0", id, result: await this.elicit(request.params) };
807
- } else if (request.method === "ping") {
808
- reply = { jsonrpc: "2.0", id, result: {} };
809
- } else {
810
- reply = { jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${request.method}` } };
811
- }
812
- const result = await this.post(JSON.stringify(reply));
813
- if (!result.ok) this.log(`HTTP ${result.status} answering ${request.method}: ${result.body}`);
814
- }
815
- async elicit(params) {
816
- if (!this.elicitationHandler) return { action: "decline" };
817
- try {
818
- return await this.elicitationHandler(params);
819
- } catch (error) {
820
- this.log("Elicitation handler error:", error);
821
- return { action: "cancel" };
822
- }
823
- }
824
- closeStream(reason) {
825
- const controller = this.stream;
826
- this.stream = void 0;
827
- controller?.abort();
828
- this.rejectPending(reason);
829
- }
830
- rejectPending(reason) {
831
- for (const [id, pending] of this.pending) {
832
- clearTimeout(pending.timer);
833
- pending.resolve({ jsonrpc: "2.0", id, error: { code: -32e3, message: reason } });
834
- }
835
- this.pending.clear();
836
- }
837
- // ═══════════════════════════════════════════════════════════════════
838
- // POSTING
839
- // ═══════════════════════════════════════════════════════════════════
840
- /** POST a message and resolve with the response the stream carries for `id`. */
841
- async postAndAwait(id, body) {
842
- const answer = new Promise((resolve) => {
843
- const timer = setTimeout(() => {
844
- this.pending.delete(id);
845
- resolve({ jsonrpc: "2.0", id, error: { code: -32e3, message: `Request timeout after ${this.timeout}ms` } });
846
- }, this.timeout);
847
- this.pending.set(id, { resolve, timer });
848
- });
849
- const result = await this.post(body);
850
- if (!result.ok) {
851
- const pending = this.pending.get(id);
852
- if (pending) {
853
- clearTimeout(pending.timer);
854
- this.pending.delete(id);
855
- }
856
- return {
857
- jsonrpc: "2.0",
858
- id,
859
- error: { code: -32e3, message: `HTTP ${result.status}: ${result.statusText}`, data: result.body }
860
- };
861
- }
862
- return answer;
863
- }
864
- async post(body) {
865
- const endpoint = this.messageEndpoint;
866
- if (!endpoint) throw new Error("SSE transport has no message endpoint. Call connect() first.");
867
- const headers = this.buildHeaders();
868
- this.lastRequestHeaders = headers;
869
- this.log(`POST ${endpoint}`, body);
870
- const controller = new AbortController();
871
- const timer = setTimeout(() => controller.abort(), this.timeout);
872
- try {
873
- const response = await fetch(endpoint, { method: "POST", headers, body, signal: controller.signal });
874
- const text = await response.text();
875
- return { ok: response.ok, status: response.status, statusText: response.statusText, body: text };
876
- } catch (error) {
877
- if (isAbortError(error)) {
878
- return { ok: false, status: 0, statusText: `timeout after ${this.timeout}ms`, body: "" };
879
- }
880
- throw error;
881
- } finally {
882
- clearTimeout(timer);
883
- }
884
- }
885
- // ═══════════════════════════════════════════════════════════════════
886
- // HELPERS
887
- // ═══════════════════════════════════════════════════════════════════
888
- async requestAnonymousToken() {
889
- const url = new URL(this.baseUrl);
890
- url.pathname = `${url.pathname.replace(/\/+$/, "")}/oauth/token`;
891
- url.search = "";
892
- const tokenUrl = url.toString();
893
- try {
894
- const response = await fetch(tokenUrl, {
895
- method: "POST",
896
- headers: { "Content-Type": "application/json" },
897
- body: JSON.stringify({ grant_type: "anonymous", client_id: crypto.randomUUID(), resource: this.baseUrl })
898
- });
899
- if (!response.ok) {
900
- this.log(`No anonymous token (HTTP ${response.status})`);
901
- return;
902
- }
903
- const token = await response.json();
904
- if (token.access_token) this.authToken = token.access_token;
905
- } catch (error) {
906
- this.log("Error requesting anonymous token:", error);
907
- }
908
- }
909
- /** `<baseUrl><entryPath>/sse`, built from URL parts so query params on `baseUrl` survive. */
910
- sseUrl() {
911
- const url = new URL(this.baseUrl);
912
- const entry = (this.entryPath ?? "").replace(/^\/+|\/+$/g, "");
913
- const basePath = url.pathname.replace(/\/+$/, "");
914
- url.pathname = entry ? `${basePath}/${entry}/sse` : `${basePath}/sse`;
915
- return url.toString();
916
- }
917
- buildHeaders() {
918
- const headers = {
919
- "Content-Type": "application/json",
920
- Accept: "application/json, text/event-stream"
921
- };
922
- if (this.clientInfo) headers["User-Agent"] = `${this.clientInfo.name}/${this.clientInfo.version}`;
923
- if (this.authToken) headers["Authorization"] = `Bearer ${this.authToken}`;
924
- if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
925
- Object.assign(headers, this.authHeaders);
926
- return headers;
927
- }
928
- ensureConnected() {
929
- if (this.state !== "connected") {
930
- throw new Error("Transport not connected. Call connect() first.");
931
- }
932
- }
933
- log(message, data) {
934
- if (this.debug) {
935
- console.log(`[SSE] ${message}`, data ?? "");
936
- }
937
- }
938
- };
939
- function splitSSEEvents(buffer) {
940
- const endsWithCarriageReturn = buffer.endsWith("\r");
941
- const normalized = (endsWithCarriageReturn ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, "\n");
942
- const completeEvents = normalized.split("\n\n");
943
- const remainder = completeEvents.pop() ?? "";
944
- return { completeEvents, remainder: endsWithCarriageReturn ? `${remainder}\r` : remainder };
945
- }
946
- function parseSSEEvent(text) {
947
- let type = "message";
948
- const data = [];
949
- for (const line of text.split("\n")) {
950
- if (line.startsWith(":")) continue;
951
- const colon = line.indexOf(":");
952
- const field = colon === -1 ? line : line.slice(0, colon);
953
- const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
954
- if (field === "event") type = value;
955
- else if (field === "data") data.push(value);
956
- }
957
- return data.length > 0 ? { type, data: data.join("\n") } : void 0;
958
- }
959
-
960
- // libs/testing/src/transport/streamable-http.transport.ts
961
- var DEFAULT_TIMEOUT2 = 3e4;
962
- var NOTIFICATION_STREAM_REOPEN_DELAY_MS = 250;
963
- var StreamableHttpTransport = class {
964
- config;
965
- state = "disconnected";
966
- sessionId;
967
- authToken;
968
- connectionCount = 0;
969
- reconnectCount = 0;
970
- lastRequestHeaders = {};
971
- interceptors;
972
- publicMode;
973
- elicitationHandler;
974
- notificationHandler;
975
- notificationStream;
976
- notificationProtocolVersion = "";
977
- notificationStreamReopenTimer;
978
- constructor(config) {
979
- this.config = {
980
- baseUrl: config.baseUrl.replace(/\/$/, ""),
981
- // Remove trailing slash
982
- entryPath: config.entryPath,
983
- timeout: config.timeout ?? DEFAULT_TIMEOUT2,
984
- auth: config.auth ?? {},
985
- publicMode: config.publicMode ?? false,
986
- debug: config.debug ?? false,
987
- interceptors: config.interceptors,
988
- clientInfo: config.clientInfo
989
- };
990
- this.authToken = config.auth?.token;
991
- this.interceptors = config.interceptors;
992
- this.publicMode = config.publicMode ?? false;
993
- this.elicitationHandler = config.elicitationHandler;
994
- this.notificationHandler = config.notificationHandler;
995
- }
996
- async connect() {
997
- this.state = "connecting";
998
- this.connectionCount++;
999
- try {
1000
- if (this.publicMode) {
1001
- this.log("Public mode: connecting without authentication");
1002
- this.state = "connected";
1003
- return;
1004
- }
1005
- if (!this.authToken) {
1006
- await this.requestAnonymousToken();
1007
- }
1008
- this.state = "connected";
1009
- this.log("Connected to StreamableHTTP transport");
1010
- } catch (error) {
1011
- this.state = "error";
1012
- throw error;
1013
- }
1014
- }
1015
- /**
1016
- * Request an anonymous token from the FrontMCP OAuth endpoint
1017
- * This allows the test client to authenticate without user interaction
1018
- */
1019
- async requestAnonymousToken() {
1020
- const clientId = crypto.randomUUID();
1021
- const tokenUrl = `${this.config.baseUrl}/oauth/token`;
1022
- this.log(`Requesting anonymous token from ${tokenUrl}`);
1023
- try {
1024
- const response = await fetch(tokenUrl, {
1025
- method: "POST",
1026
- headers: {
1027
- "Content-Type": "application/json"
1028
- },
1029
- body: JSON.stringify({
1030
- grant_type: "anonymous",
1031
- client_id: clientId,
1032
- resource: this.config.baseUrl
1033
- })
1034
- });
1035
- if (!response.ok) {
1036
- const errorText = await response.text();
1037
- this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);
1038
- return;
1039
- }
1040
- const tokenResponse = await response.json();
1041
- if (tokenResponse.access_token) {
1042
- this.authToken = tokenResponse.access_token;
1043
- this.log("Anonymous token acquired successfully");
1044
- }
1045
- } catch (error) {
1046
- this.log(`Error requesting anonymous token: ${error}`);
1047
- }
1048
- }
1049
- async request(message) {
1050
- this.ensureConnected();
1051
- const startTime = Date.now();
1052
- if (this.interceptors) {
1053
- const interceptResult = await this.interceptors.processRequest(message, {
1054
- timestamp: /* @__PURE__ */ new Date(),
1055
- transport: "streamable-http",
1056
- sessionId: this.sessionId
1057
- });
1058
- switch (interceptResult.type) {
1059
- case "mock": {
1060
- const mockResponse2 = await this.interceptors.processResponse(
1061
- message,
1062
- interceptResult.response,
1063
- Date.now() - startTime
1064
- );
1065
- return mockResponse2;
1066
- }
1067
- case "error":
1068
- throw markInterceptedError(interceptResult.error);
1069
- case "continue":
1070
- message = interceptResult.request;
1071
- break;
1072
- }
1073
- }
1074
- const headers = this.buildHeaders();
1075
- this.lastRequestHeaders = headers;
1076
- const url = this.mcpUrl();
1077
- this.log(`POST ${url}`, message);
1078
- const controller = new AbortController();
1079
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1080
- try {
1081
- const response = await fetch(url, {
1082
- method: "POST",
1083
- headers,
1084
- body: JSON.stringify(message),
1085
- signal: controller.signal
1086
- });
1087
- const newSessionId = response.headers.get("mcp-session-id");
1088
- if (newSessionId) {
1089
- this.sessionId = newSessionId;
1090
- }
1091
- let jsonResponse;
1092
- if (!response.ok) {
1093
- const errorText = await response.text();
1094
- this.log(`HTTP Error ${response.status}: ${errorText}`);
1095
- jsonResponse = {
1096
- jsonrpc: "2.0",
1097
- id: message.id ?? null,
1098
- error: {
1099
- code: -32e3,
1100
- message: `HTTP ${response.status}: ${response.statusText}`,
1101
- data: errorText
1102
- }
1103
- };
1104
- } else {
1105
- const contentType = response.headers.get("content-type") ?? "";
1106
- if (contentType.includes("text/event-stream")) {
1107
- jsonResponse = await this.handleSSEResponseWithElicitation(response, message);
1108
- } else {
1109
- const text = await response.text();
1110
- this.log("Response:", text);
1111
- if (!text.trim()) {
1112
- jsonResponse = {
1113
- jsonrpc: "2.0",
1114
- id: message.id ?? null,
1115
- result: void 0
1116
- };
1117
- } else {
1118
- jsonResponse = JSON.parse(text);
1119
- }
1120
- }
1121
- }
1122
- if (this.interceptors) {
1123
- jsonResponse = await this.interceptors.processResponse(message, jsonResponse, Date.now() - startTime);
1124
- }
1125
- clearTimeout(timeoutId);
1126
- return jsonResponse;
1127
- } catch (error) {
1128
- clearTimeout(timeoutId);
1129
- if (isAbortError(error)) {
1130
- return {
1131
- jsonrpc: "2.0",
1132
- id: message.id ?? null,
1133
- error: {
1134
- code: -32e3,
1135
- message: `Request timeout after ${this.config.timeout}ms`
1136
- }
1137
- };
1138
- }
1139
- throw error;
1140
- }
1141
- }
1142
- async notify(message) {
1143
- this.ensureConnected();
1144
- const headers = this.buildHeaders();
1145
- this.lastRequestHeaders = headers;
1146
- const url = this.mcpUrl();
1147
- this.log(`POST ${url} (notification)`, message);
1148
- const controller = new AbortController();
1149
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1150
- try {
1151
- const response = await fetch(url, {
1152
- method: "POST",
1153
- headers,
1154
- body: JSON.stringify(message),
1155
- signal: controller.signal
1156
- });
1157
- clearTimeout(timeoutId);
1158
- const newSessionId = response.headers.get("mcp-session-id");
1159
- if (newSessionId) {
1160
- this.sessionId = newSessionId;
1161
- }
1162
- if (!response.ok) {
1163
- const errorText = await response.text();
1164
- this.log(`HTTP Error ${response.status} on notification: ${errorText}`);
1165
- }
1166
- } catch (error) {
1167
- clearTimeout(timeoutId);
1168
- if (!isAbortError(error)) {
1169
- throw error;
1170
- }
1171
- }
1172
- }
1173
- async sendRaw(data) {
1174
- this.ensureConnected();
1175
- const headers = this.buildHeaders();
1176
- this.lastRequestHeaders = headers;
1177
- const url = this.mcpUrl();
1178
- this.log(`POST ${url} (raw)`, data);
1179
- const controller = new AbortController();
1180
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1181
- try {
1182
- const response = await fetch(url, {
1183
- method: "POST",
1184
- headers,
1185
- body: data,
1186
- signal: controller.signal
1187
- });
1188
- clearTimeout(timeoutId);
1189
- const text = await response.text();
1190
- if (!text.trim()) {
1191
- return {
1192
- jsonrpc: "2.0",
1193
- id: null,
1194
- error: {
1195
- code: -32700,
1196
- message: "Parse error"
1197
- }
1198
- };
1199
- }
1200
- return JSON.parse(text);
1201
- } catch (error) {
1202
- clearTimeout(timeoutId);
1203
- return {
1204
- jsonrpc: "2.0",
1205
- id: null,
1206
- error: {
1207
- code: -32700,
1208
- message: "Parse error",
1209
- data: errorMessage(error)
1210
- }
1211
- };
1212
- }
1213
- }
1214
- async openNotificationStream(protocolVersion) {
1215
- this.notificationProtocolVersion = protocolVersion;
1216
- await this.connectNotificationStream();
1217
- }
1218
- async close() {
1219
- this.closeNotificationStream();
1220
- this.state = "disconnected";
1221
- this.sessionId = void 0;
1222
- this.log("StreamableHTTP transport closed");
1223
- }
1224
- isConnected() {
1225
- return this.state === "connected";
1226
- }
1227
- getState() {
1228
- return this.state;
1229
- }
1230
- getSessionId() {
1231
- return this.sessionId;
1232
- }
1233
- setAuthToken(token) {
1234
- this.authToken = token;
1235
- }
1236
- setTimeout(ms) {
1237
- this.config.timeout = ms;
1238
- }
1239
- setInterceptors(interceptors2) {
1240
- this.interceptors = interceptors2;
1241
- }
1242
- getInterceptors() {
1243
- return this.interceptors;
1244
- }
1245
- setElicitationHandler(handler) {
1246
- this.elicitationHandler = handler;
1247
- }
1248
- getConnectionCount() {
1249
- return this.connectionCount;
1250
- }
1251
- getReconnectCount() {
1252
- return this.reconnectCount;
1253
- }
1254
- getLastRequestHeaders() {
1255
- return { ...this.lastRequestHeaders };
1256
- }
1257
- async simulateDisconnect() {
1258
- this.closeNotificationStream();
1259
- this.state = "disconnected";
1260
- this.sessionId = void 0;
1261
- }
1262
- async waitForReconnect(timeoutMs) {
1263
- const deadline = Date.now() + timeoutMs;
1264
- this.reconnectCount++;
1265
- await this.connect();
1266
- while (Date.now() < deadline) {
1267
- if (this.state === "connected") {
1268
- return;
1269
- }
1270
- await new Promise((r) => setTimeout(r, 50));
1271
- }
1272
- throw new Error("Timeout waiting for reconnection");
1273
- }
1274
- // ═══════════════════════════════════════════════════════════════════
1275
- // PRIVATE HELPERS
1276
- // ═══════════════════════════════════════════════════════════════════
1277
- closeNotificationStream() {
1278
- clearTimeout(this.notificationStreamReopenTimer);
1279
- this.notificationStream?.abort();
1280
- this.notificationStream = void 0;
1281
- }
1282
- /** Opens the stream without holding up the caller past the request timeout; close() aborts it at any point. */
1283
- async connectNotificationStream() {
1284
- if (!this.sessionId || this.notificationStream) return;
1285
- const controller = new AbortController();
1286
- this.notificationStream = controller;
1287
- const { "Content-Type": _contentType, ...headers } = this.buildHeaders();
1288
- const established = fetch(this.mcpUrl(), {
1289
- method: "GET",
1290
- headers: { ...headers, Accept: "text/event-stream", "MCP-Protocol-Version": this.notificationProtocolVersion },
1291
- signal: controller.signal
1292
- }).then(
1293
- async (response) => {
1294
- const isEventStream = response.headers.get("content-type")?.includes("text/event-stream") ?? false;
1295
- if (!response.ok || !response.body || !isEventStream) {
1296
- await response.body?.cancel();
1297
- this.log(`Server offers no notification stream (HTTP ${response.status})`);
1298
- this.releaseNotificationStream(controller);
1299
- return;
1300
- }
1301
- void this.readNotificationStream(controller, response.body.getReader());
1302
- },
1303
- (error) => {
1304
- this.log("Failed to open the notification stream:", error);
1305
- this.releaseNotificationStream(controller);
1306
- }
1307
- );
1308
- let establishTimer;
1309
- const establishDeadline = new Promise((resolve) => {
1310
- establishTimer = setTimeout(resolve, this.config.timeout);
1311
- });
1312
- await Promise.race([established, establishDeadline]);
1313
- clearTimeout(establishTimer);
1314
- }
1315
- releaseNotificationStream(controller) {
1316
- if (this.notificationStream === controller) this.notificationStream = void 0;
1317
- }
1318
- async readNotificationStream(controller, reader) {
1319
- const decoder = new TextDecoder();
1320
- let buffer = "";
1321
- try {
1322
- for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
1323
- const { completeEvents, remainder } = splitSSEEvents2(buffer + decoder.decode(chunk.value, { stream: true }));
1324
- buffer = remainder;
1325
- for (const eventText of completeEvents) {
1326
- for (const event of this.parseSSEEvents(eventText, void 0).events) {
1327
- await this.handleSSEEvent(event);
1328
- }
1329
- }
1330
- }
1331
- } catch (error) {
1332
- this.log("Notification stream ended:", error);
1333
- } finally {
1334
- reader.releaseLock();
1335
- }
1336
- if (controller.signal.aborted || this.notificationStream !== controller) return;
1337
- this.releaseNotificationStream(controller);
1338
- this.notificationStreamReopenTimer = setTimeout(
1339
- () => void this.connectNotificationStream(),
1340
- NOTIFICATION_STREAM_REOPEN_DELAY_MS
1341
- );
1342
- }
1343
- /**
1344
- * Handle SSE response with elicitation support.
1345
- *
1346
- * Streams the SSE response, detects elicitation/create requests, and handles them
1347
- * by calling the registered handler and sending the response back to the server.
1348
- */
1349
- async handleSSEResponseWithElicitation(response, originalRequest) {
1350
- this.log("handleSSEResponseWithElicitation: starting", { requestId: originalRequest.id });
1351
- const reader = response.body?.getReader();
1352
- if (!reader) {
1353
- this.log("handleSSEResponseWithElicitation: no response body");
1354
- return {
1355
- jsonrpc: "2.0",
1356
- id: originalRequest.id ?? null,
1357
- error: { code: -32e3, message: "No response body" }
1358
- };
1359
- }
1360
- const decoder = new TextDecoder();
1361
- let buffer = "";
1362
- let finalResponse = null;
1363
- let sseSessionId;
1364
- try {
1365
- let readCount = 0;
1366
- while (true) {
1367
- readCount++;
1368
- this.log(`handleSSEResponseWithElicitation: reading chunk ${readCount}`);
1369
- const { done, value } = await reader.read();
1370
- this.log(`handleSSEResponseWithElicitation: read result`, { done, valueLength: value?.length });
1371
- if (done) {
1372
- if (buffer.trim()) {
1373
- const parsed = this.parseSSEEvents(buffer, originalRequest.id);
1374
- for (const event of parsed.events) {
1375
- const handled = await this.handleSSEEvent(event);
1376
- if (handled.isFinal) {
1377
- finalResponse = handled.response;
1378
- }
1379
- }
1380
- if (parsed.sessionId && !sseSessionId) {
1381
- sseSessionId = parsed.sessionId;
1382
- }
1383
- }
1384
- break;
1385
- }
1386
- buffer += decoder.decode(value, { stream: true });
1387
- const eventEndPattern = /\n\n/g;
1388
- let lastEventEnd = 0;
1389
- let match;
1390
- while ((match = eventEndPattern.exec(buffer)) !== null) {
1391
- const eventText = buffer.slice(lastEventEnd, match.index);
1392
- lastEventEnd = match.index + 2;
1393
- if (eventText.trim()) {
1394
- const parsed = this.parseSSEEvents(eventText, originalRequest.id);
1395
- for (const event of parsed.events) {
1396
- const handled = await this.handleSSEEvent(event);
1397
- if (handled.isFinal) {
1398
- finalResponse = handled.response;
1399
- }
1400
- }
1401
- if (parsed.sessionId && !sseSessionId) {
1402
- sseSessionId = parsed.sessionId;
1403
- }
1404
- }
1405
- }
1406
- buffer = buffer.slice(lastEventEnd);
1407
- }
1408
- } finally {
1409
- reader.releaseLock();
1410
- }
1411
- if (sseSessionId && !this.sessionId) {
1412
- this.sessionId = sseSessionId;
1413
- this.log("Session ID from SSE:", this.sessionId);
1414
- }
1415
- if (finalResponse) {
1416
- return finalResponse;
1417
- }
1418
- return {
1419
- jsonrpc: "2.0",
1420
- id: originalRequest.id ?? null,
1421
- error: { code: -32e3, message: "No final response received in SSE stream" }
1422
- };
1423
- }
1424
- /**
1425
- * Parse SSE event text into structured events
1426
- */
1427
- parseSSEEvents(text, _requestId) {
1428
- const lines = text.split("\n");
1429
- const events = [];
1430
- let currentEvent = { type: "message", data: [] };
1431
- let sessionId;
1432
- for (const line of lines) {
1433
- if (line.startsWith("event: ")) {
1434
- currentEvent.type = line.slice(7);
1435
- } else if (line.startsWith("data: ")) {
1436
- currentEvent.data.push(line.slice(6));
1437
- } else if (line === "data:") {
1438
- currentEvent.data.push("");
1439
- } else if (line.startsWith("id: ")) {
1440
- const idValue = line.slice(4);
1441
- currentEvent.id = idValue;
1442
- const colonIndex = idValue.lastIndexOf(":");
1443
- if (colonIndex > 0) {
1444
- sessionId = idValue.substring(0, colonIndex);
1445
- } else {
1446
- sessionId = idValue;
1447
- }
1448
- } else if (line === "" && currentEvent.data.length > 0) {
1449
- events.push({
1450
- type: currentEvent.type,
1451
- data: currentEvent.data.join("\n"),
1452
- id: currentEvent.id
1453
- });
1454
- currentEvent = { type: "message", data: [] };
1455
- }
1456
- }
1457
- if (currentEvent.data.length > 0) {
1458
- events.push({
1459
- type: currentEvent.type,
1460
- data: currentEvent.data.join("\n"),
1461
- id: currentEvent.id
1462
- });
1463
- }
1464
- return { events, sessionId };
1465
- }
1466
- /**
1467
- * Handle a single SSE event, including elicitation requests
1468
- */
1469
- async handleSSEEvent(event) {
1470
- this.log("SSE Event:", { type: event.type, data: event.data.slice(0, 200) });
1471
- try {
1472
- const parsed = JSON.parse(event.data);
1473
- if ("method" in parsed && parsed.method === "elicitation/create") {
1474
- await this.handleElicitationRequest(parsed);
1475
- return {
1476
- isFinal: false,
1477
- response: { jsonrpc: "2.0", id: null, result: void 0 }
1478
- };
1479
- }
1480
- if ("method" in parsed && parsed.id === void 0) {
1481
- this.notificationHandler?.(parsed);
1482
- return {
1483
- isFinal: false,
1484
- response: { jsonrpc: "2.0", id: null, result: void 0 }
1485
- };
1486
- }
1487
- if ("result" in parsed || "error" in parsed) {
1488
- return { isFinal: true, response: parsed };
1489
- }
1490
- return {
1491
- isFinal: false,
1492
- response: { jsonrpc: "2.0", id: null, result: void 0 }
1493
- };
1494
- } catch {
1495
- this.log("Failed to parse SSE event data:", event.data);
1496
- return {
1497
- isFinal: false,
1498
- response: { jsonrpc: "2.0", id: null, result: void 0 }
1499
- };
1500
- }
1501
- }
1502
- /**
1503
- * Handle an elicitation/create request from the server
1504
- */
1505
- async handleElicitationRequest(request) {
1506
- const params = request.params;
1507
- this.log("Elicitation request received:", {
1508
- mode: params?.mode,
1509
- message: params?.message?.slice(0, 100)
1510
- });
1511
- const requestId = request.id;
1512
- if (requestId === void 0 || requestId === null) {
1513
- this.log("Elicitation request has no ID, cannot respond");
1514
- return;
1515
- }
1516
- if (!this.elicitationHandler) {
1517
- this.log("No elicitation handler registered, sending error");
1518
- await this.sendElicitationResponse(requestId, {
1519
- action: "decline"
1520
- });
1521
- return;
1522
- }
1523
- try {
1524
- const response = await this.elicitationHandler(params);
1525
- this.log("Elicitation handler response:", response);
1526
- await this.sendElicitationResponse(requestId, response);
1527
- } catch (error) {
1528
- this.log("Elicitation handler error:", error);
1529
- await this.sendElicitationResponse(requestId, {
1530
- action: "cancel"
1531
- });
1532
- }
1533
- }
1534
- /**
1535
- * Send an elicitation response back to the server
1536
- */
1537
- async sendElicitationResponse(requestId, response) {
1538
- const headers = this.buildHeaders();
1539
- const url = this.mcpUrl();
1540
- const rpcResponse = {
1541
- jsonrpc: "2.0",
1542
- id: requestId,
1543
- result: response
1544
- };
1545
- this.log("Sending elicitation response:", rpcResponse);
1546
- try {
1547
- const fetchResponse = await fetch(url, {
1548
- method: "POST",
1549
- headers,
1550
- body: JSON.stringify(rpcResponse)
1551
- });
1552
- if (!fetchResponse.ok) {
1553
- this.log(`Elicitation response HTTP error: ${fetchResponse.status}`);
1554
- }
1555
- } catch (error) {
1556
- this.log("Failed to send elicitation response:", error);
1557
- }
1558
- }
1559
- /**
1560
- * The MCP endpoint URL. `entryPath` is where the server mounts MCP; the
1561
- * trailing slash is kept because both hosts normalize it and the original
1562
- * behaviour (`${baseUrl}/`) relied on it (issue #543).
1563
- */
1564
- mcpUrl() {
1565
- const url = new URL(this.config.baseUrl);
1566
- const entry = (this.config.entryPath ?? "").replace(/^\/+|\/+$/g, "");
1567
- const basePath = url.pathname.replace(/\/+$/, "");
1568
- url.pathname = entry ? `${basePath}/${entry}` : `${basePath}/`;
1569
- return url.toString();
1570
- }
1571
- buildHeaders() {
1572
- const headers = {
1573
- "Content-Type": "application/json",
1574
- Accept: "application/json, text/event-stream"
1575
- };
1576
- if (this.config.clientInfo) {
1577
- headers["User-Agent"] = `${this.config.clientInfo.name}/${this.config.clientInfo.version}`;
1578
- }
1579
- if (this.authToken) {
1580
- headers["Authorization"] = `Bearer ${this.authToken}`;
1581
- }
1582
- if (this.sessionId) {
1583
- headers["mcp-session-id"] = this.sessionId;
1584
- }
1585
- if (this.config.auth.headers) {
1586
- Object.assign(headers, this.config.auth.headers);
1587
- }
1588
- return headers;
1589
- }
1590
- ensureConnected() {
1591
- if (this.state !== "connected") {
1592
- throw new Error("Transport not connected. Call connect() first.");
1593
- }
1594
- }
1595
- log(message, data) {
1596
- if (this.config.debug) {
1597
- console.log(`[StreamableHTTP] ${message}`, data ?? "");
1598
- }
1599
- }
1600
- /**
1601
- * Parse SSE (Server-Sent Events) response format with session ID extraction
1602
- * SSE format is:
1603
- * event: message
1604
- * id: sessionId:messageId
1605
- * data: {"jsonrpc":"2.0",...}
1606
- *
1607
- * The id field contains the session ID followed by a colon and the message ID.
1608
- *
1609
- * @param text - The raw SSE response text
1610
- * @param requestId - The original request ID
1611
- * @returns Object with parsed JSON-RPC response and session ID (if found)
1612
- */
1613
- parseSSEResponseWithSession(text, requestId) {
1614
- const lines = text.split("\n");
1615
- const dataLines = [];
1616
- let sseSessionId;
1617
- for (const line of lines) {
1618
- if (line.startsWith("data: ")) {
1619
- dataLines.push(line.slice(6));
1620
- } else if (line === "data:") {
1621
- dataLines.push("");
1622
- } else if (line.startsWith("id: ")) {
1623
- const idValue = line.slice(4);
1624
- const colonIndex = idValue.lastIndexOf(":");
1625
- if (colonIndex > 0) {
1626
- sseSessionId = idValue.substring(0, colonIndex);
1627
- } else {
1628
- sseSessionId = idValue;
1629
- }
1630
- }
1631
- }
1632
- if (dataLines.length > 0) {
1633
- const jsonData = dataLines.join("\n");
1634
- try {
1635
- return {
1636
- response: JSON.parse(jsonData),
1637
- sseSessionId
1638
- };
1639
- } catch {
1640
- this.log("Failed to parse SSE data as JSON:", jsonData);
1641
- }
1642
- }
1643
- return {
1644
- response: {
1645
- jsonrpc: "2.0",
1646
- id: requestId ?? null,
1647
- error: {
1648
- code: -32700,
1649
- message: "Failed to parse SSE response",
1650
- data: text
1651
- }
1652
- },
1653
- sseSessionId
1654
- };
1655
- }
1656
- };
1657
- function splitSSEEvents2(buffer) {
1658
- const endsWithCarriageReturn = buffer.endsWith("\r");
1659
- const normalized = (endsWithCarriageReturn ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, "\n");
1660
- const completeEvents = normalized.split("\n\n");
1661
- const remainder = completeEvents.pop() ?? "";
1662
- return { completeEvents, remainder: endsWithCarriageReturn ? `${remainder}\r` : remainder };
1663
- }
1664
-
1665
- // libs/testing/src/platform/platform-client-info.ts
1666
- var MCP_APPS_EXTENSION_KEY = "io.modelcontextprotocol/ui";
1667
- function getPlatformClientInfo(platform) {
1668
- switch (platform) {
1669
- case "openai":
1670
- return {
1671
- name: "ChatGPT",
1672
- version: "1.0"
1673
- };
1674
- case "ext-apps":
1675
- return {
1676
- name: "mcp-ext-apps",
1677
- version: "1.0"
1678
- };
1679
- case "claude":
1680
- return {
1681
- name: "claude-desktop",
1682
- version: "1.0"
1683
- };
1684
- case "cursor":
1685
- return {
1686
- name: "cursor",
1687
- version: "1.0"
1688
- };
1689
- case "continue":
1690
- return {
1691
- name: "continue",
1692
- version: "1.0"
1693
- };
1694
- case "cody":
1695
- return {
1696
- name: "cody",
1697
- version: "1.0"
1698
- };
1699
- case "gemini":
1700
- return {
1701
- name: "gemini",
1702
- version: "1.0"
1703
- };
1704
- case "generic-mcp":
1705
- return {
1706
- name: "generic-mcp-client",
1707
- version: "1.0"
1708
- };
1709
- case "unknown":
1710
- default:
1711
- return {
1712
- name: "mcp-test-client",
1713
- version: "1.0"
1714
- };
1715
- }
1716
- }
1717
- function getPlatformCapabilities(platform) {
1718
- const baseCapabilities = {
1719
- sampling: {},
1720
- // Include elicitation.form by default for testing elicitation workflows
1721
- // Note: MCP SDK expects form to be an object, not boolean
1722
- elicitation: {
1723
- form: {}
1724
- }
1725
- };
1726
- if (platform === "ext-apps") {
1727
- return {
1728
- ...baseCapabilities,
1729
- experimental: {
1730
- [MCP_APPS_EXTENSION_KEY]: {
1731
- mimeTypes: ["text/html;profile=mcp-app"]
1732
- }
1733
- }
1734
- };
1735
- }
1736
- return baseCapabilities;
1737
- }
1738
-
1739
- // libs/testing/src/client/mcp-test-client.builder.ts
1740
- var McpTestClientBuilder = class {
1741
- config;
1742
- constructor(config) {
1743
- this.config = { ...config };
1744
- }
1745
- /**
1746
- * Set the authentication configuration
1747
- */
1748
- withAuth(auth) {
1749
- this.config.auth = { ...this.config.auth, ...auth };
1750
- return this;
1751
- }
1752
- /**
1753
- * Set the bearer token for authentication
1754
- */
1755
- withToken(token) {
1756
- this.config.auth = { ...this.config.auth, token };
1757
- return this;
1758
- }
1759
- /**
1760
- * Add custom headers to all requests
1761
- */
1762
- withHeaders(headers) {
1763
- this.config.auth = {
1764
- ...this.config.auth,
1765
- headers: { ...this.config.auth?.headers, ...headers }
1766
- };
1767
- return this;
1768
- }
1769
- /**
1770
- * Set the transport type
1771
- */
1772
- withTransport(transport) {
1773
- this.config.transport = transport;
1774
- return this;
1775
- }
1776
- /**
1777
- * Set the request timeout in milliseconds
1778
- */
1779
- withTimeout(timeoutMs) {
1780
- this.config.timeout = timeoutMs;
1781
- return this;
1782
- }
1783
- /**
1784
- * Enable debug logging
1785
- */
1786
- withDebug(enabled = true) {
1787
- this.config.debug = enabled;
1788
- return this;
1789
- }
1790
- /**
1791
- * Enable public mode - skip authentication entirely.
1792
- * When true, no Authorization header is sent and anonymous token is not requested.
1793
- * Use this for testing public/unauthenticated endpoints in CI/CD pipelines.
1794
- */
1795
- withPublicMode(enabled = true) {
1796
- this.config.publicMode = enabled;
1797
- return this;
1798
- }
1799
- /**
1800
- * Set the MCP protocol version to request (default '2025-06-18').
1801
- * '2026-07-28' has no initialize handshake, so `build()` throws for it.
1802
- */
1803
- withProtocolVersion(version) {
1804
- this.config.protocolVersion = version;
1805
- return this;
1806
- }
1807
- /**
1808
- * Set the client info sent during initialization
1809
- */
1810
- withClientInfo(info) {
1811
- this.config.clientInfo = info;
1812
- return this;
1813
- }
1814
- /**
1815
- * Set the platform type for testing platform-specific meta keys.
1816
- * Automatically configures clientInfo and capabilities for platform detection.
1817
- *
1818
- * Platform-specific behavior:
1819
- * - `openai`: Uses openai/* meta keys, sets User-Agent to "ChatGPT/1.0"
1820
- * - `ext-apps`: Uses ui/* meta keys per SEP-1865, sets io.modelcontextprotocol/ui capability
1821
- * - `claude`: Uses frontmcp/* + ui/* keys, sets User-Agent to "claude-desktop/1.0"
1822
- * - `cursor`: Uses frontmcp/* + ui/* keys, sets User-Agent to "cursor/1.0"
1823
- * - Other platforms follow similar patterns
1824
- *
1825
- * @example
1826
- * ```typescript
1827
- * const client = await McpTestClient.create({ baseUrl })
1828
- * .withPlatform('openai')
1829
- * .buildAndConnect();
1830
- *
1831
- * // ext-apps automatically sets the io.modelcontextprotocol/ui capability
1832
- * const extAppsClient = await McpTestClient.create({ baseUrl })
1833
- * .withPlatform('ext-apps')
1834
- * .buildAndConnect();
1835
- * ```
1836
- */
1837
- withPlatform(platform) {
1838
- this.config.platform = platform;
1839
- this.config.clientInfo = getPlatformClientInfo(platform);
1840
- this.config.capabilities = getPlatformCapabilities(platform);
1841
- return this;
1842
- }
1843
- /**
1844
- * Set custom client capabilities for MCP initialization.
1845
- * Use this for fine-grained control over capabilities sent during initialization.
1846
- *
1847
- * @example
1848
- * ```typescript
1849
- * const client = await McpTestClient.create({ baseUrl })
1850
- * .withCapabilities({
1851
- * sampling: {},
1852
- * experimental: {
1853
- * 'io.modelcontextprotocol/ui': { mimeTypes: ['text/html;profile=mcp-app'] }
1854
- * }
1855
- * })
1856
- * .buildAndConnect();
1857
- * ```
1858
- */
1859
- withCapabilities(capabilities) {
1860
- this.config.capabilities = capabilities;
1861
- return this;
1862
- }
1863
- /**
1864
- * Set query parameters to append to the connection URL.
1865
- * Useful for testing mode switches like `?mode=skills_only`.
1866
- *
1867
- * @example
1868
- * ```typescript
1869
- * const client = await McpTestClient.create({ baseUrl })
1870
- * .withQueryParams({ mode: 'skills_only' })
1871
- * .buildAndConnect();
1872
- * ```
1873
- */
1874
- withQueryParams(params) {
1875
- this.config.queryParams = { ...this.config.queryParams, ...params };
1876
- return this;
1877
- }
1878
- /**
1879
- * Build the McpTestClient instance (does not connect)
1880
- */
1881
- build() {
1882
- return new McpTestClient(this.config);
1883
- }
1884
- /**
1885
- * Build the McpTestClient and connect to the server
1886
- */
1887
- async buildAndConnect() {
1888
- const client = this.build();
1889
- await client.connect();
1890
- return client;
1891
- }
1892
- };
1893
-
1894
- // libs/testing/src/client/mcp-test-client.ts
1895
- var DEFAULT_TIMEOUT3 = 3e4;
1896
- var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
1897
- var UNSUPPORTED_PROTOCOL_VERSIONS = ["2026-07-28"];
1898
- var DEFAULT_CLIENT_INFO = {
1899
- name: "@frontmcp/testing",
1900
- version: "0.4.0"
1901
- };
1902
- var MAX_LIST_PAGES = 1e3;
1903
- function isAuthFailure(error) {
1904
- return typeof error?.message === "string" && /^HTTP (401|403)\b/.test(error.message);
1905
- }
1906
- function describeInitializeError(error) {
1907
- const message = error?.message ?? "Unknown error";
1908
- const data = error?.data;
1909
- const detail = typeof data === "string" ? data.trim() : "";
1910
- return detail ? `${message} - ${detail.slice(0, 500)}` : message;
1911
- }
1912
- function extractEntryPaths(data) {
1913
- let payload = data;
1914
- if (typeof payload === "string") {
1915
- try {
1916
- payload = JSON.parse(payload);
1917
- } catch {
1918
- return void 0;
1919
- }
1920
- }
1921
- if (!payload || typeof payload !== "object") return void 0;
1922
- const paths = payload.entryPaths;
1923
- if (!Array.isArray(paths)) return void 0;
1924
- const strings = paths.filter((p) => typeof p === "string");
1925
- return strings.length > 0 ? strings : void 0;
1926
- }
1927
- var McpTestClient = class {
1928
- // Platform, capabilities, and queryParams are optional - only set when needed
1929
- config;
1930
- transport = null;
1931
- initResult = null;
1932
- requestIdCounter = 0;
1933
- _lastRequestId = 0;
1934
- _sessionId;
1935
- /** #543 — discovery is attempted at most once per connect. */
1936
- triedDiscoveredEntryPath = false;
1937
- _sessionInfo = null;
1938
- _authState = { isAnonymous: true, scopes: [] };
1939
- // Logging and tracing
1940
- _logs = [];
1941
- _traces = [];
1942
- _notifications = [];
1943
- _progressUpdates = [];
1944
- collectingProgress = false;
1945
- progressTokenCounter = 0;
1946
- // Interceptor chain
1947
- _interceptors;
1948
- // Elicitation handler for server→client elicit requests
1949
- _elicitationHandler;
1950
- // ═══════════════════════════════════════════════════════════════════
1951
- // CONSTRUCTOR & FACTORY
1952
- // ═══════════════════════════════════════════════════════════════════
1953
- constructor(config) {
1954
- if (config.protocolVersion && UNSUPPORTED_PROTOCOL_VERSIONS.includes(config.protocolVersion)) {
1955
- throw new Error(
1956
- `McpTestClient does not support protocol version ${config.protocolVersion}: it has no initialize handshake. Use ${DEFAULT_PROTOCOL_VERSION} or earlier.`
1957
- );
1958
- }
1959
- this.config = {
1960
- baseUrl: config.baseUrl,
1961
- entryPath: config.entryPath,
1962
- transport: config.transport ?? "streamable-http",
1963
- auth: config.auth ?? {},
1964
- publicMode: config.publicMode ?? false,
1965
- timeout: config.timeout ?? DEFAULT_TIMEOUT3,
1966
- debug: config.debug ?? false,
1967
- protocolVersion: config.protocolVersion ?? DEFAULT_PROTOCOL_VERSION,
1968
- clientInfo: config.clientInfo ?? DEFAULT_CLIENT_INFO,
1969
- platform: config.platform,
1970
- capabilities: config.capabilities,
1971
- queryParams: config.queryParams
1972
- };
1973
- if (config.auth?.token) {
1974
- this._authState = {
1975
- isAnonymous: false,
1976
- token: config.auth.token,
1977
- scopes: this.parseScopesFromToken(config.auth.token),
1978
- user: this.parseUserFromToken(config.auth.token)
1979
- };
1980
- }
1981
- this._interceptors = new DefaultInterceptorChain();
1982
- }
1983
- /**
1984
- * Create a new McpTestClientBuilder for fluent configuration
1985
- */
1986
- static create(config) {
1987
- return new McpTestClientBuilder(config);
1988
- }
1989
- // ═══════════════════════════════════════════════════════════════════
1990
- // CONNECTION & LIFECYCLE
1991
- // ═══════════════════════════════════════════════════════════════════
1992
- /**
1993
- * Connect to the MCP server and perform initialization
1994
- */
1995
- async connect() {
1996
- this.log("debug", `Connecting to ${this.config.baseUrl}...`);
1997
- this.triedDiscoveredEntryPath = false;
1998
- this.initResult = null;
1999
- this.transport = this.createTransport();
2000
- await this.transport.connect();
2001
- const maxRetries = 3;
2002
- const retryDelayMs = 500;
2003
- let lastError;
2004
- let reportedEntryPaths;
2005
- let attemptsMade = 0;
2006
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
2007
- attemptsMade = attempt;
2008
- const initResponse = await this.initialize();
2009
- if (initResponse.success && initResponse.data) {
2010
- this.initResult = initResponse.data;
2011
- break;
2012
- }
2013
- lastError = describeInitializeError(initResponse.error);
2014
- reportedEntryPaths = extractEntryPaths(initResponse.error?.data) ?? reportedEntryPaths;
2015
- if (reportedEntryPaths?.length === 1 && !this.triedDiscoveredEntryPath) {
2016
- this.triedDiscoveredEntryPath = true;
2017
- const discovered = reportedEntryPaths[0];
2018
- this.log("info", `Server serves MCP at ${discovered}; reconnecting there (configured: ${this.mcpPathLabel()})`);
2019
- this.config.entryPath = discovered;
2020
- await this.transport.close();
2021
- this.transport = this.createTransport();
2022
- await this.transport.connect();
2023
- continue;
2024
- }
2025
- if (isAuthFailure(initResponse.error)) break;
2026
- if (attempt < maxRetries) {
2027
- this.log("debug", `MCP init attempt ${attempt} failed (${lastError}), retrying in ${retryDelayMs}ms...`);
2028
- await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
2029
- }
2030
- }
2031
- if (!this.initResult) {
2032
- const served = reportedEntryPaths?.length ? ` The server reports it serves MCP at ${reportedEntryPaths.join(", ")}; set \`entryPath\` in test.use() (or \`http.entryPath\` on the server) to match.` : "";
2033
- throw new Error(
2034
- `Failed to initialize MCP connection to ${this.config.baseUrl}${this.mcpPathLabel()} after ${attemptsMade} attempt${attemptsMade === 1 ? "" : "s"}: ${lastError}.${served}`
2035
- );
2036
- }
2037
- this._sessionId = this.transport.getSessionId();
2038
- this._sessionInfo = {
2039
- id: this._sessionId ?? `session-${Date.now()}`,
2040
- createdAt: /* @__PURE__ */ new Date(),
2041
- lastActivityAt: /* @__PURE__ */ new Date(),
2042
- requestCount: 1
2043
- };
2044
- await this.transport.notify({
2045
- jsonrpc: "2.0",
2046
- method: "notifications/initialized"
2047
- });
2048
- await this.transport.openNotificationStream?.(this.initResult.protocolVersion);
2049
- this.log("info", `Connected to ${this.initResult.serverInfo?.name ?? "MCP Server"}`);
2050
- return this.initResult;
2051
- }
2052
- /**
2053
- * Disconnect from the MCP server
2054
- */
2055
- async disconnect() {
2056
- if (this.transport) {
2057
- await this.transport.close();
2058
- this.transport = null;
2059
- }
2060
- this.initResult = null;
2061
- this.log("info", "Disconnected from MCP server");
2062
- }
2063
- /**
2064
- * Reconnect to the server, optionally with an existing session ID
2065
- */
2066
- async reconnect(options) {
2067
- await this.disconnect();
2068
- if (options?.sessionId && this.transport) {
2069
- this._sessionId = options.sessionId;
2070
- }
2071
- await this.connect();
2072
- }
2073
- /**
2074
- * Check if the client is currently connected
2075
- */
2076
- isConnected() {
2077
- return this.transport?.isConnected() ?? false;
2078
- }
2079
- // ═══════════════════════════════════════════════════════════════════
2080
- // SESSION & AUTH PROPERTIES
2081
- // ═══════════════════════════════════════════════════════════════════
2082
- get sessionId() {
2083
- return this._sessionId ?? "";
2084
- }
2085
- get session() {
2086
- const info = this._sessionInfo ?? {
2087
- id: "",
2088
- createdAt: /* @__PURE__ */ new Date(),
2089
- lastActivityAt: /* @__PURE__ */ new Date(),
2090
- requestCount: 0
2091
- };
2092
- return {
2093
- ...info,
2094
- expire: async () => {
2095
- this._sessionId = void 0;
2096
- this._sessionInfo = null;
2097
- }
2098
- };
2099
- }
2100
- get auth() {
2101
- return this._authState;
2102
- }
2103
- /**
2104
- * Authenticate with a token.
2105
- *
2106
- * When connected, this opens a NEW session with the token (the previous session was created
2107
- * for the previous identity) and rejects if the server refuses it — for example because the
2108
- * token is expired or badly signed. On rejection the client keeps its previous identity and
2109
- * session. The token is kept in the client config, so `reconnect()` keeps using it.
2110
- */
2111
- async authenticate(token) {
2112
- if (typeof token !== "string" || token.trim() === "") {
2113
- throw new Error("authenticate() requires a non-empty token");
2114
- }
2115
- const previousAuthState = this._authState;
2116
- const previousConfigAuth = this.config.auth;
2117
- this.config.auth = { ...previousConfigAuth, token };
2118
- this._authState = {
2119
- isAnonymous: false,
2120
- token,
2121
- scopes: this.parseScopesFromToken(token),
2122
- user: this.parseUserFromToken(token)
2123
- };
2124
- const previousTransport = this.transport;
2125
- if (!previousTransport) {
2126
- this.log("debug", "Authentication updated (not connected yet)");
2127
- return;
2128
- }
2129
- const previousInit = this.initResult;
2130
- const previousSessionId = this._sessionId;
2131
- const previousSessionInfo = this._sessionInfo;
2132
- try {
2133
- await this.connect();
2134
- } catch (err) {
2135
- await this.transport?.close().catch(() => void 0);
2136
- this.transport = previousTransport;
2137
- this.initResult = previousInit;
2138
- this._sessionId = previousSessionId;
2139
- this._sessionInfo = previousSessionInfo;
2140
- this.config.auth = previousConfigAuth;
2141
- this._authState = previousAuthState;
2142
- throw err;
2143
- }
2144
- await previousTransport.close().catch(() => void 0);
2145
- this.log("debug", "Authentication updated");
2146
- }
2147
- // ═══════════════════════════════════════════════════════════════════
2148
- // SERVER INFO & CAPABILITIES
2149
- // ═══════════════════════════════════════════════════════════════════
2150
- get serverInfo() {
2151
- return {
2152
- name: this.initResult?.serverInfo?.name ?? "",
2153
- version: this.initResult?.serverInfo?.version ?? ""
2154
- };
2155
- }
2156
- get protocolVersion() {
2157
- return this.initResult?.protocolVersion ?? "";
2158
- }
2159
- get instructions() {
2160
- return this.initResult?.instructions ?? "";
2161
- }
2162
- get capabilities() {
2163
- return this.initResult?.capabilities ?? {};
2164
- }
2165
- /**
2166
- * Check if server has a specific capability
2167
- */
2168
- hasCapability(name) {
2169
- return !!this.capabilities[name];
2170
- }
2171
- // ═══════════════════════════════════════════════════════════════════
2172
- // TOOLS API
2173
- // ═══════════════════════════════════════════════════════════════════
2174
- tools = {
2175
- /**
2176
- * List all available tools
2177
- */
2178
- list: async () => this.listAllPages(
2179
- "tools/list",
2180
- "tools",
2181
- (cursor) => this.listTools(cursor),
2182
- (page) => page.tools
2183
- ),
2184
- /**
2185
- * Call a tool by name with arguments
2186
- */
2187
- call: async (name, args, options = {}) => {
2188
- const response = await this.callTool(name, args, this.progressTokenFor(options));
2189
- return this.wrapToolResult(response);
2190
- }
2191
- };
2192
- // ═══════════════════════════════════════════════════════════════════
2193
- // RESOURCES API
2194
- // ═══════════════════════════════════════════════════════════════════
2195
- resources = {
2196
- /**
2197
- * List all static resources
2198
- */
2199
- list: async () => this.listAllPages(
2200
- "resources/list",
2201
- "resources",
2202
- (cursor) => this.listResources(cursor),
2203
- (page) => page.resources
2204
- ),
2205
- /**
2206
- * List all resource templates
2207
- */
2208
- listTemplates: async () => this.listAllPages(
2209
- "resources/templates/list",
2210
- "resource templates",
2211
- (cursor) => this.listResourceTemplates(cursor),
2212
- (page) => page.resourceTemplates
2213
- ),
2214
- /**
2215
- * Read a resource by URI
2216
- */
2217
- read: async (uri) => {
2218
- const response = await this.readResource(uri);
2219
- return this.wrapResourceContent(response);
2220
- },
2221
- /**
2222
- * Subscribe to resource changes (placeholder for future implementation)
2223
- */
2224
- subscribe: async (_uri) => {
2225
- this.log("warn", "Resource subscription not yet implemented");
2226
- },
2227
- /**
2228
- * Unsubscribe from resource changes (placeholder for future implementation)
2229
- */
2230
- unsubscribe: async (_uri) => {
2231
- this.log("warn", "Resource unsubscription not yet implemented");
2232
- }
2233
- };
2234
- // ═══════════════════════════════════════════════════════════════════
2235
- // PROMPTS API
2236
- // ═══════════════════════════════════════════════════════════════════
2237
- prompts = {
2238
- /**
2239
- * List all available prompts
2240
- */
2241
- list: async () => this.listAllPages(
2242
- "prompts/list",
2243
- "prompts",
2244
- (cursor) => this.listPrompts(cursor),
2245
- (page) => page.prompts
2246
- ),
2247
- /**
2248
- * Get a prompt with arguments
2249
- */
2250
- get: async (name, args) => {
2251
- const response = await this.getPrompt(name, args);
2252
- return this.wrapPromptResult(response);
2253
- }
2254
- };
2255
- // ═══════════════════════════════════════════════════════════════════
2256
- // RAW PROTOCOL ACCESS
2257
- // ═══════════════════════════════════════════════════════════════════
2258
- raw = {
2259
- /**
2260
- * Send any JSON-RPC request
2261
- */
2262
- request: async (message) => {
2263
- const transport = this.getConnectedTransport();
2264
- const start = Date.now();
2265
- const response = await transport.request(message);
2266
- this.traceRequest(message.method, message.params, message.id, response, Date.now() - start);
2267
- return response;
2268
- },
2269
- /**
2270
- * Send a notification (no response expected)
2271
- */
2272
- notify: async (message) => {
2273
- const transport = this.getConnectedTransport();
2274
- await transport.notify(message);
2275
- },
2276
- /**
2277
- * Send raw string data (for error testing)
2278
- */
2279
- sendRaw: async (data) => {
2280
- const transport = this.getConnectedTransport();
2281
- return transport.sendRaw(data);
2282
- }
2283
- };
2284
- get lastRequestId() {
2285
- return this._lastRequestId;
2286
- }
2287
- // ═══════════════════════════════════════════════════════════════════
2288
- // TRANSPORT INFO
2289
- // ═══════════════════════════════════════════════════════════════════
2290
- /**
2291
- * Get transport information and utilities
2292
- */
2293
- get transport_info() {
2294
- return {
2295
- type: this.config.transport,
2296
- isConnected: () => this.transport?.isConnected() ?? false,
2297
- messageEndpoint: this.transport?.getMessageEndpoint?.(),
2298
- connectionCount: this.transport?.getConnectionCount?.() ?? 0,
2299
- reconnectCount: this.transport?.getReconnectCount?.() ?? 0,
2300
- lastRequestHeaders: this.transport?.getLastRequestHeaders?.() ?? {},
2301
- simulateDisconnect: async () => {
2302
- await this.transport?.simulateDisconnect?.();
2303
- },
2304
- waitForReconnect: async (timeoutMs) => {
2305
- await this.transport?.waitForReconnect?.(timeoutMs);
2306
- }
2307
- };
2308
- }
2309
- // Alias for transport info
2310
- get transport_() {
2311
- return this.transport_info;
2312
- }
2313
- // ═══════════════════════════════════════════════════════════════════
2314
- // NOTIFICATIONS
2315
- // ═══════════════════════════════════════════════════════════════════
2316
- notifications = {
2317
- /**
2318
- * Start collecting server notifications
2319
- */
2320
- collect: () => {
2321
- return new NotificationCollector(this._notifications);
2322
- },
2323
- /**
2324
- * Collect progress notifications specifically
2325
- */
2326
- collectProgress: () => {
2327
- this.collectingProgress = true;
2328
- return new ProgressCollector(this._progressUpdates);
2329
- },
2330
- /**
2331
- * Send a notification to the server
2332
- */
2333
- send: async (method, params) => {
2334
- await this.raw.notify({ jsonrpc: "2.0", method, params });
2335
- }
2336
- };
2337
- // ═══════════════════════════════════════════════════════════════════
2338
- // ELICITATION
2339
- // ═══════════════════════════════════════════════════════════════════
2340
- /**
2341
- * Register a handler for elicitation requests from the server.
2342
- *
2343
- * When a tool calls `this.elicit()` during execution, the server sends an
2344
- * `elicitation/create` request to the client. This handler is called to
2345
- * provide the response that would normally come from user interaction.
2346
- *
2347
- * @param handler - Function that receives the elicitation request and returns a response
2348
- *
2349
- * @example
2350
- * ```typescript
2351
- * // Simple acceptance
2352
- * mcp.onElicitation(async () => ({
2353
- * action: 'accept',
2354
- * content: { confirmed: true }
2355
- * }));
2356
- *
2357
- * // Conditional response based on request
2358
- * mcp.onElicitation(async (request) => {
2359
- * if (request.message.includes('delete')) {
2360
- * return { action: 'decline' };
2361
- * }
2362
- * return { action: 'accept', content: { approved: true } };
2363
- * });
2364
- *
2365
- * // Multi-step wizard
2366
- * let step = 0;
2367
- * mcp.onElicitation(async () => {
2368
- * step++;
2369
- * if (step === 1) return { action: 'accept', content: { name: 'Alice' } };
2370
- * return { action: 'accept', content: { color: 'blue' } };
2371
- * });
2372
- * ```
2373
- */
2374
- onElicitation(handler) {
2375
- this._elicitationHandler = handler;
2376
- if (this.transport?.setElicitationHandler) {
2377
- this.transport.setElicitationHandler(handler);
2378
- }
2379
- this.log("debug", "Elicitation handler registered");
2380
- }
2381
- /**
2382
- * Clear the elicitation handler.
2383
- *
2384
- * After calling this, elicitation requests from the server will not be
2385
- * handled automatically. This can be used to test timeout scenarios.
2386
- */
2387
- clearElicitationHandler() {
2388
- this._elicitationHandler = void 0;
2389
- if (this.transport?.setElicitationHandler) {
2390
- this.transport.setElicitationHandler(void 0);
2391
- }
2392
- this.log("debug", "Elicitation handler cleared");
2393
- }
2394
- // ═══════════════════════════════════════════════════════════════════
2395
- // LOGGING & DEBUGGING
2396
- // ═══════════════════════════════════════════════════════════════════
2397
- logs = {
2398
- all: () => [...this._logs],
2399
- filter: (level) => this._logs.filter((l) => l.level === level),
2400
- search: (text) => this._logs.filter((l) => l.message.includes(text)),
2401
- last: () => this._logs[this._logs.length - 1],
2402
- clear: () => {
2403
- this._logs = [];
2404
- }
2405
- };
2406
- trace = {
2407
- all: () => [...this._traces],
2408
- last: () => this._traces[this._traces.length - 1],
2409
- clear: () => {
2410
- this._traces = [];
2411
- }
2412
- };
2413
- // ═══════════════════════════════════════════════════════════════════
2414
- // MOCKING & INTERCEPTION
2415
- // ═══════════════════════════════════════════════════════════════════
2416
- /**
2417
- * API for mocking MCP requests
2418
- *
2419
- * @example
2420
- * ```typescript
2421
- * // Mock a specific tool call
2422
- * const handle = mcp.mock.tool('my-tool', { result: 'mocked!' });
2423
- *
2424
- * // Mock with params matching
2425
- * mcp.mock.add({
2426
- * method: 'tools/call',
2427
- * params: { name: 'my-tool' },
2428
- * response: mockResponse.toolResult([{ type: 'text', text: 'mocked' }]),
2429
- * });
2430
- *
2431
- * // Clear all mocks after test
2432
- * mcp.mock.clear();
2433
- * ```
2434
- */
2435
- mock = {
2436
- /**
2437
- * Add a mock definition
2438
- */
2439
- add: (mock) => {
2440
- return this._interceptors.mocks.add(mock);
2441
- },
2442
- /**
2443
- * Mock a tools/call request for a specific tool
2444
- */
2445
- tool: (name, result, options) => {
2446
- return this._interceptors.mocks.add({
2447
- method: "tools/call",
2448
- params: { name },
2449
- response: mockResponse.toolResult([
2450
- { type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }
2451
- ]),
2452
- times: options?.times,
2453
- delay: options?.delay
2454
- });
2455
- },
2456
- /**
2457
- * Mock a tools/call request to return an error
2458
- */
2459
- toolError: (name, code, message, options) => {
2460
- return this._interceptors.mocks.add({
2461
- method: "tools/call",
2462
- params: { name },
2463
- response: mockResponse.error(code, message),
2464
- times: options?.times
2465
- });
2466
- },
2467
- /**
2468
- * Mock a resources/read request
2469
- */
2470
- resource: (uri, content, options) => {
2471
- const contentObj = typeof content === "string" ? { uri, text: content } : { uri, ...content };
2472
- return this._interceptors.mocks.add({
2473
- method: "resources/read",
2474
- params: { uri },
2475
- response: mockResponse.resourceRead([contentObj]),
2476
- times: options?.times,
2477
- delay: options?.delay
2478
- });
2479
- },
2480
- /**
2481
- * Mock a resources/read request to return an error
2482
- */
2483
- resourceError: (uri, options) => {
2484
- return this._interceptors.mocks.add({
2485
- method: "resources/read",
2486
- params: { uri },
2487
- response: mockResponse.errors.resourceNotFound(uri),
2488
- times: options?.times
2489
- });
2490
- },
2491
- /**
2492
- * Mock the tools/list response
2493
- */
2494
- toolsList: (tools, options) => {
2495
- return this._interceptors.mocks.add({
2496
- method: "tools/list",
2497
- response: mockResponse.toolsList(tools),
2498
- times: options?.times
2499
- });
2500
- },
2501
- /**
2502
- * Mock the resources/list response
2503
- */
2504
- resourcesList: (resources, options) => {
2505
- return this._interceptors.mocks.add({
2506
- method: "resources/list",
2507
- response: mockResponse.resourcesList(resources),
2508
- times: options?.times
2509
- });
2510
- },
2511
- /**
2512
- * Clear all mocks
2513
- */
2514
- clear: () => {
2515
- this._interceptors.mocks.clear();
2516
- },
2517
- /**
2518
- * Get all active mocks
2519
- */
2520
- all: () => {
2521
- return this._interceptors.mocks.getAll();
2522
- }
2523
- };
2524
- /**
2525
- * API for intercepting requests and responses
2526
- *
2527
- * @example
2528
- * ```typescript
2529
- * // Log all requests
2530
- * const remove = mcp.intercept.request((ctx) => {
2531
- * console.log('Request:', ctx.request.method);
2532
- * return { action: 'passthrough' };
2533
- * });
2534
- *
2535
- * // Modify requests
2536
- * mcp.intercept.request((ctx) => {
2537
- * if (ctx.request.method === 'tools/call') {
2538
- * return {
2539
- * action: 'modify',
2540
- * request: { ...ctx.request, params: { ...ctx.request.params, extra: true } },
2541
- * };
2542
- * }
2543
- * return { action: 'passthrough' };
2544
- * });
2545
- *
2546
- * // Add latency to all requests
2547
- * mcp.intercept.delay(100);
2548
- *
2549
- * // Clean up
2550
- * remove();
2551
- * mcp.intercept.clear();
2552
- * ```
2553
- */
2554
- intercept = {
2555
- /**
2556
- * Add a request interceptor
2557
- * @returns Function to remove the interceptor
2558
- */
2559
- request: (interceptor) => {
2560
- return this._interceptors.addRequestInterceptor(interceptor);
2561
- },
2562
- /**
2563
- * Add a response interceptor
2564
- * @returns Function to remove the interceptor
2565
- */
2566
- response: (interceptor) => {
2567
- return this._interceptors.addResponseInterceptor(interceptor);
2568
- },
2569
- /**
2570
- * Add latency to all requests
2571
- * @returns Function to remove the interceptor
2572
- */
2573
- delay: (ms) => {
2574
- return this._interceptors.addRequestInterceptor(async () => {
2575
- await new Promise((r) => setTimeout(r, ms));
2576
- return { action: "passthrough" };
2577
- });
2578
- },
2579
- /**
2580
- * Fail requests matching a method
2581
- * @returns Function to remove the interceptor
2582
- */
2583
- failMethod: (method, error) => {
2584
- return this._interceptors.addRequestInterceptor((ctx) => {
2585
- if (ctx.request.method === method) {
2586
- return { action: "error", error: new Error(error ?? `Intercepted: ${method}`) };
2587
- }
2588
- return { action: "passthrough" };
2589
- });
2590
- },
2591
- /**
2592
- * Clear all interceptors (but not mocks)
2593
- */
2594
- clear: () => {
2595
- this._interceptors.request = [];
2596
- this._interceptors.response = [];
2597
- },
2598
- /**
2599
- * Clear everything (interceptors and mocks)
2600
- */
2601
- clearAll: () => {
2602
- this._interceptors.clear();
2603
- }
2604
- };
2605
- // ═══════════════════════════════════════════════════════════════════
2606
- // TIMEOUT
2607
- // ═══════════════════════════════════════════════════════════════════
2608
- setTimeout(ms) {
2609
- this.config.timeout = ms;
2610
- if (this.transport) {
2611
- this.transport.setTimeout(ms);
2612
- }
2613
- }
2614
- // ═══════════════════════════════════════════════════════════════════
2615
- // PRIVATE: MCP OPERATIONS
2616
- // ═══════════════════════════════════════════════════════════════════
2617
- async initialize() {
2618
- const capabilities = this.config.capabilities ?? {
2619
- sampling: {},
2620
- elicitation: {
2621
- form: {}
2622
- }
2623
- };
2624
- return this.request("initialize", {
2625
- protocolVersion: this.config.protocolVersion,
2626
- capabilities,
2627
- clientInfo: this.config.clientInfo
2628
- });
2629
- }
2630
- async listTools(cursor) {
2631
- return this.request("tools/list", cursor ? { cursor } : {});
2632
- }
2633
- /**
2634
- * Follow `nextCursor` until the server stops returning one, concatenating the
2635
- * pages. A server that hands back a cursor it already returned, or never stops
2636
- * paging, fails the call rather than looping.
2637
- */
2638
- async listAllPages(method, label, fetchPage, itemsOf) {
2639
- const items = [];
2640
- const seenCursors = /* @__PURE__ */ new Set();
2641
- let cursor;
2642
- for (let page = 0; page < MAX_LIST_PAGES; page++) {
2643
- const response = await fetchPage(cursor);
2644
- if (!response.success || !response.data) {
2645
- throw new Error(`Failed to list ${label}: ${response.error?.message}`);
2646
- }
2647
- items.push(...itemsOf(response.data) ?? []);
2648
- const next = response.data.nextCursor;
2649
- if (!next) return items;
2650
- if (seenCursors.has(next)) {
2651
- throw new Error(`Failed to list ${label}: ${method} returned the cursor "${next}" twice`);
2652
- }
2653
- seenCursors.add(next);
2654
- cursor = next;
2655
- }
2656
- throw new Error(`Failed to list ${label}: ${method} did not finish within ${MAX_LIST_PAGES} pages`);
2657
- }
2658
- async callTool(name, args, progressToken) {
2659
- return this.request("tools/call", {
2660
- name,
2661
- arguments: args ?? {},
2662
- ...progressToken !== void 0 && { _meta: { progressToken } }
2663
- });
2664
- }
2665
- progressTokenFor(options) {
2666
- if (options.progressToken !== void 0) return options.progressToken;
2667
- return this.collectingProgress ? `progress-${++this.progressTokenCounter}` : void 0;
2668
- }
2669
- recordNotification = (notification) => {
2670
- const timestamp = /* @__PURE__ */ new Date();
2671
- this._notifications.push({ method: notification.method, params: notification.params, timestamp });
2672
- if (notification.method !== "notifications/progress") return;
2673
- const { progress, total, progressToken } = notification.params ?? {};
2674
- this._progressUpdates.push({
2675
- progress: Number(progress),
2676
- total: typeof total === "number" ? total : void 0,
2677
- progressToken: typeof progressToken === "string" || typeof progressToken === "number" ? progressToken : void 0,
2678
- timestamp
2679
- });
2680
- };
2681
- async listResources(cursor) {
2682
- return this.request("resources/list", cursor ? { cursor } : {});
2683
- }
2684
- async listResourceTemplates(cursor) {
2685
- return this.request("resources/templates/list", cursor ? { cursor } : {});
2686
- }
2687
- async readResource(uri) {
2688
- return this.request("resources/read", { uri });
2689
- }
2690
- async listPrompts(cursor) {
2691
- return this.request("prompts/list", cursor ? { cursor } : {});
2692
- }
2693
- async getPrompt(name, args) {
2694
- return this.request("prompts/get", {
2695
- name,
2696
- arguments: args ?? {}
2697
- });
2698
- }
2699
- // ═══════════════════════════════════════════════════════════════════
2700
- // PRIVATE: TRANSPORT & REQUEST HELPERS
2701
- // ═══════════════════════════════════════════════════════════════════
2702
- /** The MCP path this client is currently pointed at, for log and error text. */
2703
- mcpPathLabel() {
2704
- const entry = (this.config.entryPath ?? "").replace(/^\/+|\/+$/g, "");
2705
- return entry ? `/${entry}` : "/";
2706
- }
2707
- createTransport() {
2708
- let baseUrl = this.config.baseUrl;
2709
- if (this.config.queryParams && Object.keys(this.config.queryParams).length > 0) {
2710
- const url = new URL(baseUrl);
2711
- Object.entries(this.config.queryParams).forEach(([key, value]) => {
2712
- url.searchParams.set(key, String(value));
2713
- });
2714
- baseUrl = url.toString();
2715
- }
2716
- switch (this.config.transport) {
2717
- case "streamable-http":
2718
- return new StreamableHttpTransport({
2719
- baseUrl,
2720
- entryPath: this.config.entryPath,
2721
- timeout: this.config.timeout,
2722
- auth: this.config.auth,
2723
- publicMode: this.config.publicMode,
2724
- debug: this.config.debug,
2725
- interceptors: this._interceptors,
2726
- clientInfo: this.config.clientInfo,
2727
- elicitationHandler: this._elicitationHandler,
2728
- notificationHandler: this.recordNotification
2729
- });
2730
- case "sse":
2731
- return new SseTransport({
2732
- baseUrl,
2733
- entryPath: this.config.entryPath,
2734
- timeout: this.config.timeout,
2735
- auth: this.config.auth,
2736
- publicMode: this.config.publicMode,
2737
- debug: this.config.debug,
2738
- interceptors: this._interceptors,
2739
- clientInfo: this.config.clientInfo,
2740
- elicitationHandler: this._elicitationHandler,
2741
- notificationHandler: this.recordNotification
2742
- });
2743
- default:
2744
- throw new Error(`Unknown transport type: ${this.config.transport}`);
2745
- }
2746
- }
2747
- async request(method, params) {
2748
- const transport = this.getConnectedTransport();
2749
- const id = ++this.requestIdCounter;
2750
- this._lastRequestId = id;
2751
- const start = Date.now();
2752
- try {
2753
- const response = await transport.request({
2754
- jsonrpc: "2.0",
2755
- id,
2756
- method,
2757
- params
2758
- });
2759
- const durationMs = Date.now() - start;
2760
- this.updateSessionActivity();
2761
- if ("error" in response && response.error) {
2762
- const error = response.error;
2763
- this.traceRequest(method, params, id, response, durationMs);
2764
- return {
2765
- success: false,
2766
- error,
2767
- durationMs,
2768
- requestId: id
2769
- };
2770
- }
2771
- this.traceRequest(method, params, id, response, durationMs);
2772
- return {
2773
- success: true,
2774
- data: response.result,
2775
- durationMs,
2776
- requestId: id
2777
- };
2778
- } catch (err) {
2779
- if (isInterceptedError(err)) throw err;
2780
- const durationMs = Date.now() - start;
2781
- const error = {
2782
- code: -32603,
2783
- message: errorMessage(err)
2784
- };
2785
- return {
2786
- success: false,
2787
- error,
2788
- durationMs,
2789
- requestId: id
2790
- };
2791
- }
2792
- }
2793
- /**
2794
- * Get the transport, throwing if not connected.
2795
- */
2796
- getConnectedTransport() {
2797
- if (!this.transport || !this.transport.isConnected()) {
2798
- throw new Error("Not connected to MCP server. Call connect() first.");
2799
- }
2800
- return this.transport;
2801
- }
2802
- updateSessionActivity() {
2803
- if (this._sessionInfo) {
2804
- this._sessionInfo.lastActivityAt = /* @__PURE__ */ new Date();
2805
- this._sessionInfo.requestCount++;
2806
- }
2807
- }
2808
- // ═══════════════════════════════════════════════════════════════════
2809
- // PRIVATE: RESULT WRAPPERS
2810
- // ═══════════════════════════════════════════════════════════════════
2811
- wrapToolResult(response) {
2812
- const raw = response.data ?? { content: [] };
2813
- const isError = !response.success || raw.isError === true;
2814
- const meta = raw._meta;
2815
- const hasUI = meta?.["ui/html"] !== void 0 || meta?.["ui/component"] !== void 0;
2816
- const structuredContent = raw["structuredContent"];
2817
- return {
2818
- raw,
2819
- isSuccess: !isError,
2820
- isError,
2821
- error: response.error,
2822
- durationMs: response.durationMs,
2823
- json() {
2824
- if (hasUI && structuredContent !== void 0) {
2825
- return structuredContent;
2826
- }
2827
- const textContent = raw.content?.find((c) => c.type === "text");
2828
- if (textContent && "text" in textContent) {
2829
- return JSON.parse(textContent.text);
2830
- }
2831
- throw new Error("No text content to parse as JSON");
2832
- },
2833
- text() {
2834
- const textContent = raw.content?.find((c) => c.type === "text");
2835
- if (textContent && "text" in textContent) {
2836
- return textContent.text;
2837
- }
2838
- return void 0;
2839
- },
2840
- hasTextContent() {
2841
- return raw.content?.some((c) => c.type === "text") ?? false;
2842
- },
2843
- hasImageContent() {
2844
- return raw.content?.some((c) => c.type === "image") ?? false;
2845
- },
2846
- hasResourceContent() {
2847
- return raw.content?.some((c) => c.type === "resource") ?? false;
2848
- },
2849
- hasToolUI() {
2850
- return hasUI;
2851
- }
2852
- };
2853
- }
2854
- wrapResourceContent(response) {
2855
- const raw = response.data ?? { contents: [] };
2856
- const isError = !response.success;
2857
- const firstContent = raw.contents?.[0];
2858
- return {
2859
- raw,
2860
- isSuccess: !isError,
2861
- isError,
2862
- error: response.error,
2863
- durationMs: response.durationMs,
2864
- json() {
2865
- if (firstContent && "text" in firstContent) {
2866
- return JSON.parse(firstContent.text);
2867
- }
2868
- throw new Error("No text content to parse as JSON");
2869
- },
2870
- text() {
2871
- if (firstContent && "text" in firstContent) {
2872
- return firstContent.text;
2873
- }
2874
- return void 0;
2875
- },
2876
- mimeType() {
2877
- return firstContent?.mimeType;
2878
- },
2879
- hasMimeType(type) {
2880
- return firstContent?.mimeType === type;
2881
- }
2882
- };
2883
- }
2884
- wrapPromptResult(response) {
2885
- const raw = response.data ?? { messages: [] };
2886
- const isError = !response.success;
2887
- return {
2888
- raw,
2889
- isSuccess: !isError,
2890
- isError,
2891
- error: response.error,
2892
- durationMs: response.durationMs,
2893
- messages: raw.messages ?? [],
2894
- description: raw.description
2895
- };
2896
- }
2897
- // ═══════════════════════════════════════════════════════════════════
2898
- // PRIVATE: LOGGING & TRACING
2899
- // ═══════════════════════════════════════════════════════════════════
2900
- log(level, message, data) {
2901
- const entry = {
2902
- level,
2903
- message,
2904
- timestamp: /* @__PURE__ */ new Date(),
2905
- data
2906
- };
2907
- this._logs.push(entry);
2908
- if (this.config.debug) {
2909
- console.log(`[${level.toUpperCase()}] ${message}`, data ?? "");
2910
- }
2911
- }
2912
- traceRequest(method, params, id, response, durationMs) {
2913
- this._traces.push({
2914
- request: { method, params, id },
2915
- response: {
2916
- result: "result" in response ? response.result : void 0,
2917
- error: "error" in response ? response.error : void 0
2918
- },
2919
- durationMs,
2920
- timestamp: /* @__PURE__ */ new Date()
2921
- });
2922
- }
2923
- // ═══════════════════════════════════════════════════════════════════
2924
- // PRIVATE: TOKEN PARSING
2925
- // ═══════════════════════════════════════════════════════════════════
2926
- parseScopesFromToken(token) {
2927
- try {
2928
- const payload = this.decodeJwtPayload(token);
2929
- if (!payload) return [];
2930
- const scope = payload["scope"];
2931
- const scopes2 = payload["scopes"];
2932
- if (typeof scope === "string") {
2933
- return scope.split(" ");
2934
- }
2935
- if (Array.isArray(scopes2)) {
2936
- return scopes2;
2937
- }
2938
- return [];
2939
- } catch {
2940
- return [];
2941
- }
2942
- }
2943
- parseUserFromToken(token) {
2944
- try {
2945
- const payload = this.decodeJwtPayload(token);
2946
- const sub = payload?.["sub"];
2947
- if (!sub || typeof sub !== "string") return void 0;
2948
- return {
2949
- sub,
2950
- email: payload["email"],
2951
- name: payload["name"]
2952
- };
2953
- } catch {
2954
- return void 0;
2955
- }
2956
- }
2957
- decodeJwtPayload(token) {
2958
- try {
2959
- const parts = token.split(".");
2960
- if (parts.length !== 3) return null;
2961
- const payload = Buffer.from(parts[1], "base64url").toString("utf-8");
2962
- return JSON.parse(payload);
2963
- } catch {
2964
- return null;
2965
- }
2966
- }
2967
- };
2968
- var NotificationCollector = class {
2969
- constructor(notifications) {
2970
- this.notifications = notifications;
2971
- }
2972
- notifications;
2973
- get received() {
2974
- return [...this.notifications];
2975
- }
2976
- has(method) {
2977
- return this.notifications.some((n) => n.method === method);
2978
- }
2979
- async waitFor(method, timeoutMs) {
2980
- const deadline = Date.now() + timeoutMs;
2981
- while (Date.now() < deadline) {
2982
- const found = this.notifications.find((n) => n.method === method);
2983
- if (found) return found;
2984
- await new Promise((r) => setTimeout(r, 50));
2985
- }
2986
- throw new Error(`Timeout waiting for notification: ${method}`);
2987
- }
2988
- };
2989
- var ProgressCollector = class {
2990
- constructor(updates) {
2991
- this.updates = updates;
2992
- }
2993
- updates;
2994
- get all() {
2995
- return [...this.updates];
2996
- }
2997
- async waitForComplete(timeoutMs) {
2998
- const deadline = Date.now() + timeoutMs;
2999
- while (Date.now() < deadline) {
3000
- const last = this.updates[this.updates.length - 1];
3001
- if (last && last.total !== void 0 && last.progress >= last.total) {
3002
- return;
3003
- }
3004
- await new Promise((r) => setTimeout(r, 50));
3005
- }
3006
- throw new Error("Timeout waiting for progress to complete");
3007
- }
3008
- };
3009
-
3010
- // libs/testing/src/server/test-server.ts
3011
- var import_child_process = require("child_process");
3012
- var import_net2 = require("net");
3013
- var import_utils = require("@frontmcp/utils");
3014
-
3015
- // libs/testing/src/errors/index.ts
3016
- var TestClientError = class extends Error {
3017
- constructor(message) {
3018
- super(message);
3019
- this.name = "TestClientError";
3020
- Object.setPrototypeOf(this, new.target.prototype);
3021
- }
3022
- };
3023
- var ServerStartError = class extends TestClientError {
3024
- constructor(message, cause) {
3025
- super(message);
3026
- this.cause = cause;
3027
- this.name = "ServerStartError";
3028
- Object.setPrototypeOf(this, new.target.prototype);
3029
- }
3030
- cause;
3031
- };
3032
-
3033
- // libs/testing/src/server/port-registry.ts
3034
- var import_net = require("net");
3035
- var E2E_PORT_RANGES = {
3036
- // Core E2E tests (50000-50099)
3037
- "demo-e2e-public": { start: 5e4, size: 10 },
3038
- "demo-e2e-cache": { start: 50010, size: 10 },
3039
- "demo-e2e-config": { start: 50020, size: 10 },
3040
- "demo-e2e-direct": { start: 50030, size: 10 },
3041
- "demo-e2e-errors": { start: 50040, size: 10 },
3042
- "demo-e2e-hooks": { start: 50050, size: 10 },
3043
- "demo-e2e-multiapp": { start: 50060, size: 10 },
3044
- "demo-e2e-notifications": { start: 50070, size: 10 },
3045
- "demo-e2e-providers": { start: 50080, size: 10 },
3046
- "demo-e2e-standalone": { start: 50090, size: 10 },
3047
- // Auth E2E tests (50100-50199)
3048
- "demo-e2e-orchestrated": { start: 50100, size: 10 },
3049
- "demo-e2e-transparent": { start: 50110, size: 10 },
3050
- "demo-e2e-cimd": { start: 50120, size: 10 },
3051
- "demo-e2e-remote-proxy": { start: 50130, size: 10 },
3052
- // Feature E2E tests (50200-50299)
3053
- "demo-e2e-skills": { start: 50200, size: 10 },
3054
- "demo-e2e-remote": { start: 50210, size: 10 },
3055
- "demo-e2e-openapi": { start: 50220, size: 10 },
3056
- "demo-e2e-ui": { start: 50230, size: 10 },
3057
- "demo-e2e-codecall": { start: 50240, size: 10 },
3058
- "demo-e2e-remember": { start: 50250, size: 10 },
3059
- "demo-e2e-elicitation": { start: 50260, size: 10 },
3060
- "demo-e2e-agents": { start: 50270, size: 10 },
3061
- "demo-e2e-transport-recreation": { start: 50280, size: 10 },
3062
- "demo-e2e-jobs": { start: 50290, size: 10 },
3063
- // Infrastructure E2E tests (50300-50409)
3064
- "demo-e2e-redis": { start: 50300, size: 10 },
3065
- "demo-e2e-serverless": { start: 50310, size: 10 },
3066
- "demo-e2e-uipack": { start: 50320, size: 10 },
3067
- "demo-e2e-agent-adapters": { start: 50330, size: 10 },
3068
- "demo-e2e-guard": { start: 50340, size: 10 },
3069
- "demo-e2e-cli-exec": { start: 50350, size: 10 },
3070
- "demo-e2e-env-awareness": { start: 50360, size: 10 },
3071
- "demo-e2e-esm": { start: 50370, size: 10 },
3072
- "demo-e2e-feature-flags": { start: 50380, size: 10 },
3073
- "demo-e2e-resource-providers": { start: 50390, size: 10 },
3074
- // ESM E2E tests (50400-50439)
3075
- "esm-package-server": { start: 50400, size: 10 },
3076
- "esm-package-server-hot-reload": { start: 50410, size: 10 },
3077
- "esm-package-server-cli": { start: 50420, size: 10 },
3078
- "demo-e2e-unix-socket": { start: 50430, size: 10 },
3079
- // Distributed E2E tests (50440-50459)
3080
- "demo-e2e-distributed": { start: 50440, size: 20 },
3081
- // Protocol revision E2E tests (50460-50479)
3082
- "demo-e2e-protocol-20260728": { start: 50460, size: 20 },
3083
- // Testing library E2E tests (50480-50499)
3084
- "demo-e2e-testing": { start: 50480, size: 20 },
3085
- // Mock servers and utilities (50900-50999)
3086
- "mock-oauth": { start: 50900, size: 10 },
3087
- "mock-api": { start: 50910, size: 10 },
3088
- "mock-cimd": { start: 50920, size: 10 },
3089
- // Dynamic/unknown projects (51000+)
3090
- default: { start: 51e3, size: 100 }
3091
- };
3092
- var reservedPorts = /* @__PURE__ */ new Map();
3093
- var lockedPorts = /* @__PURE__ */ new Set();
3094
- var LOCK_MAX_AGE_MS = 10 * 60 * 1e3;
3095
- function lockDir() {
3096
- try {
3097
- const os = require("node:os");
3098
- const path = require("node:path");
3099
- return path.join(os.tmpdir(), "frontmcp-testing-ports");
3100
- } catch {
3101
- return void 0;
3102
- }
3103
- }
3104
- function pidIsAlive(pid) {
3105
- try {
3106
- process.kill(pid, 0);
3107
- return true;
3108
- } catch (error) {
3109
- return error.code === "EPERM";
3110
- }
3111
- }
3112
- function acquirePortLock(port) {
3113
- if (lockedPorts.has(port)) return false;
3114
- let fs;
3115
- let file;
3116
- try {
3117
- fs = require("node:fs");
3118
- const dir = lockDir();
3119
- if (!dir) return true;
3120
- fs.mkdirSync(dir, { recursive: true });
3121
- file = require("node:path").join(dir, `${port}.lock`);
3122
- } catch {
3123
- return true;
3124
- }
3125
- const payload = JSON.stringify({ pid: process.pid, at: Date.now() });
3126
- for (let attempt = 0; attempt < 2; attempt++) {
3127
- try {
3128
- fs.writeFileSync(file, payload, { flag: "wx" });
3129
- lockedPorts.add(port);
3130
- return true;
3131
- } catch (error) {
3132
- if (error.code !== "EEXIST") return true;
3133
- try {
3134
- const held = JSON.parse(fs.readFileSync(file, "utf8"));
3135
- const fresh = typeof held.at === "number" && Date.now() - held.at < LOCK_MAX_AGE_MS;
3136
- if (fresh && typeof held.pid === "number" && pidIsAlive(held.pid)) return false;
3137
- fs.unlinkSync(file);
3138
- } catch {
3139
- }
3140
- }
3141
- }
3142
- return false;
3143
- }
3144
- function releasePortLock(port) {
3145
- if (!lockedPorts.delete(port)) return;
3146
- try {
3147
- const fs = require("node:fs");
3148
- const dir = lockDir();
3149
- if (dir) fs.unlinkSync(require("node:path").join(dir, `${port}.lock`));
3150
- } catch {
3151
- }
3152
- }
3153
- var projectPortIndex = /* @__PURE__ */ new Map();
3154
- function getPortRange(project) {
3155
- const key = project;
3156
- if (key in E2E_PORT_RANGES) {
3157
- return E2E_PORT_RANGES[key];
3158
- }
3159
- return E2E_PORT_RANGES.default;
3160
- }
3161
- async function reservePort(project, preferredPort) {
3162
- const range = getPortRange(project);
3163
- const handle = (port) => ({
3164
- port,
3165
- // Frees the socket only, so the server about to be spawned can bind the port; the lock file stays
3166
- releaseSocket: async () => {
3167
- await releasePort(port);
3168
- },
3169
- release: async () => {
3170
- await releasePort(port);
3171
- releasePortLock(port);
3172
- }
3173
- });
3174
- const wantsSpecificPort = preferredPort !== void 0 && Number.isInteger(preferredPort) && preferredPort > 0;
3175
- if (wantsSpecificPort) {
3176
- const reservation = await tryReservePort(preferredPort, project);
3177
- if (reservation) {
3178
- return handle(preferredPort);
3179
- }
3180
- console.warn(`[PortRegistry] Preferred port ${preferredPort} not available for ${project}, allocating from range`);
3181
- }
3182
- let index = projectPortIndex.get(project) ?? 0;
3183
- const maxAttempts = range.size;
3184
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
3185
- const port = range.start + index % range.size;
3186
- index = (index + 1) % range.size;
3187
- if (reservedPorts.has(port) || lockedPorts.has(port)) {
3188
- continue;
3189
- }
3190
- const reservation = await tryReservePort(port, project);
3191
- if (reservation) {
3192
- projectPortIndex.set(project, index);
3193
- return handle(port);
3194
- }
3195
- }
3196
- for (let port = 51e3; port < 52e3; port++) {
3197
- if (reservedPorts.has(port) || lockedPorts.has(port)) continue;
3198
- if (await tryReservePort(port, project)) {
3199
- return handle(port);
3200
- }
3201
- }
3202
- throw new Error(
3203
- `[PortRegistry] Could not reserve a port for ${project}. Range: ${range.start}-${range.start + range.size - 1}. Currently reserved: ${Array.from(reservedPorts.keys()).join(", ")}`
3204
- );
3205
- }
3206
- async function tryReservePort(port, project) {
3207
- if (!acquirePortLock(port)) {
3208
- return false;
3209
- }
3210
- return new Promise((resolve) => {
3211
- const server = (0, import_net.createServer)();
3212
- server.once("error", () => {
3213
- releasePortLock(port);
3214
- resolve(false);
3215
- });
3216
- server.listen(port, () => {
3217
- reservedPorts.set(port, {
3218
- port,
3219
- project,
3220
- holder: server,
3221
- reservedAt: Date.now()
3222
- });
3223
- resolve(true);
3224
- });
3225
- });
3226
- }
3227
- async function releasePort(port) {
3228
- const reservation = reservedPorts.get(port);
3229
- if (!reservation) {
3230
- return;
3231
- }
3232
- return new Promise((resolve) => {
3233
- reservation.holder.close(() => {
3234
- reservedPorts.delete(port);
3235
- resolve();
3236
- });
3237
- });
3238
- }
3239
-
3240
- // libs/testing/src/server/test-server.ts
3241
- var SERVER_EXIT_TIMEOUT_MS = 12e3;
3242
- var DEBUG_SERVER = process.env["DEBUG_SERVER"] === "1" || process.env["DEBUG"] === "1";
3243
- var TestServer = class _TestServer {
3244
- process = null;
3245
- options;
3246
- _info;
3247
- logs = [];
3248
- /** Frees the port reservation (socket and cross-process lock); held until stop() */
3249
- portRelease = null;
3250
- /** Frees only the reservation socket, just before the server is spawned */
3251
- portReleaseSocket = null;
3252
- constructor(options, port, portRelease, portReleaseSocket) {
3253
- this.options = {
3254
- port,
3255
- project: options.project,
3256
- command: options.command ?? "",
3257
- cwd: options.cwd ?? process.cwd(),
3258
- env: options.env ?? {},
3259
- startupTimeout: options.startupTimeout ?? 3e4,
3260
- healthCheckPath: options.healthCheckPath ?? "/health",
3261
- debug: options.debug ?? DEBUG_SERVER
3262
- };
3263
- this.portRelease = portRelease ?? null;
3264
- this.portReleaseSocket = portReleaseSocket ?? portRelease ?? null;
3265
- this._info = {
3266
- baseUrl: `http://localhost:${port}`,
3267
- port
3268
- };
3269
- }
3270
- /**
3271
- * Start a test server with custom command
3272
- */
3273
- static async start(options) {
3274
- const project = options.project ?? "default";
3275
- const maxAttempts = 3;
3276
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
3277
- const { port, release, releaseSocket } = await reservePort(project, options.port);
3278
- const server = new _TestServer(options, port, release, releaseSocket);
3279
- try {
3280
- await server.startProcess();
3281
- return server;
3282
- } catch (error) {
3283
- try {
3284
- await server.stop();
3285
- } catch (cleanupError) {
3286
- if (options.debug || DEBUG_SERVER) {
3287
- const msg = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
3288
- console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`);
3289
- }
3290
- }
3291
- const isEADDRINUSE = error instanceof Error && (error.message.includes("EADDRINUSE") || server.getLogs().some((l) => l.includes("EADDRINUSE")));
3292
- if (isEADDRINUSE && attempt < maxAttempts) {
3293
- const delayMs = attempt * 500;
3294
- if (options.debug || DEBUG_SERVER) {
3295
- console.warn(
3296
- `[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`
3297
- );
3298
- }
3299
- await sleep2(delayMs);
3300
- continue;
3301
- }
3302
- throw error;
3303
- }
3304
- }
3305
- throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`);
3306
- }
3307
- /**
3308
- * Start an Nx project as test server
3309
- */
3310
- static async startNx(project, options = {}) {
3311
- if (!/^[\w-]+$/.test(project)) {
3312
- throw new Error(
3313
- `Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`
3314
- );
3315
- }
3316
- const maxAttempts = 3;
3317
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
3318
- const { port, release, releaseSocket } = await reservePort(project, options.port);
3319
- const serverOptions = {
3320
- ...options,
3321
- port,
3322
- project,
3323
- command: `npx nx serve ${project} --port ${port}`,
3324
- cwd: options.cwd ?? process.cwd()
3325
- };
3326
- const server = new _TestServer(serverOptions, port, release, releaseSocket);
3327
- try {
3328
- await server.startProcess();
3329
- return server;
3330
- } catch (error) {
3331
- try {
3332
- await server.stop();
3333
- } catch (cleanupError) {
3334
- if (options.debug || DEBUG_SERVER) {
3335
- const msg = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
3336
- console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`);
3337
- }
3338
- }
3339
- const isEADDRINUSE = error instanceof Error && (error.message.includes("EADDRINUSE") || server.getLogs().some((l) => l.includes("EADDRINUSE")));
3340
- if (isEADDRINUSE && attempt < maxAttempts) {
3341
- const delayMs = attempt * 500;
3342
- if (options.debug || DEBUG_SERVER) {
3343
- console.warn(
3344
- `[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`
3345
- );
3346
- }
3347
- await sleep2(delayMs);
3348
- continue;
3349
- }
3350
- throw error;
3351
- }
3352
- }
3353
- throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`);
3354
- }
3355
- /**
3356
- * Create a test server connected to an already running server
3357
- */
3358
- static connect(baseUrl) {
3359
- const url = new URL(baseUrl);
3360
- const port = parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80);
3361
- const server = new _TestServer(
3362
- {
3363
- command: "",
3364
- port
3365
- },
3366
- port
3367
- );
3368
- server._info = {
3369
- baseUrl: baseUrl.replace(/\/$/, ""),
3370
- port
3371
- };
3372
- return server;
3373
- }
3374
- /**
3375
- * Get server information
3376
- */
3377
- get info() {
3378
- return { ...this._info };
3379
- }
3380
- /**
3381
- * Stop the test server
3382
- */
3383
- async stop() {
3384
- try {
3385
- await this.stopProcess();
3386
- } finally {
3387
- if (this.portRelease) {
3388
- await this.portRelease();
3389
- this.portRelease = null;
3390
- }
3391
- this.portReleaseSocket = null;
3392
- }
3393
- }
3394
- async stopProcess() {
3395
- if (this.process) {
3396
- this.log("Stopping server...");
3397
- const serverPid = this._info.pid !== this._info.shellPid ? this._info.pid : void 0;
3398
- if (this.process.exitCode !== null || this.process.signalCode !== null) {
3399
- this.log(`Server already exited (code: ${this.process.exitCode}, signal: ${this.process.signalCode})`);
3400
- this.process = null;
3401
- if (serverPid !== void 0) signalIfRunning(serverPid, "SIGTERM");
3402
- await this.waitForServerGone(serverPid);
3403
- return;
3404
- }
3405
- const pid = this.process.pid;
3406
- try {
3407
- if (pid !== void 0) {
3408
- process.kill(-pid, "SIGTERM");
3409
- } else {
3410
- this.process.kill("SIGTERM");
3411
- }
3412
- } catch {
3413
- this.process.kill("SIGTERM");
3414
- }
3415
- const exitPromise = new Promise((resolve) => {
3416
- if (this.process) {
3417
- this.process.once("exit", () => resolve());
3418
- } else {
3419
- resolve();
3420
- }
3421
- });
3422
- const killTimeout = setTimeout(() => {
3423
- if (this.process) {
3424
- this.log("Force killing server after timeout...");
3425
- const killPid = this.process.pid;
3426
- try {
3427
- if (killPid !== void 0) {
3428
- process.kill(-killPid, "SIGKILL");
3429
- } else {
3430
- this.process.kill("SIGKILL");
3431
- }
3432
- } catch {
3433
- this.process.kill("SIGKILL");
3434
- }
3435
- }
3436
- }, 5e3);
3437
- await exitPromise;
3438
- clearTimeout(killTimeout);
3439
- this.process = null;
3440
- await this.waitForServerGone(serverPid);
3441
- this.log("Server stopped");
3442
- }
3443
- }
3444
- /**
3445
- * Wait until the server process has exited and its port refuses connections. A server that
3446
- * drains on SIGTERM can keep listening after the shell it was started through has exited.
3447
- */
3448
- async waitForServerGone(serverPid) {
3449
- const deadline = Date.now() + SERVER_EXIT_TIMEOUT_MS;
3450
- while (Date.now() < deadline) {
3451
- const serverRunning = serverPid !== void 0 && pidIsAlive(serverPid);
3452
- if (!serverRunning && !await acceptsConnections(this._info.port)) return;
3453
- await sleep2(100);
3454
- }
3455
- if (serverPid !== void 0 && pidIsAlive(serverPid)) {
3456
- this.log("Force killing server process after timeout...");
3457
- signalIfRunning(serverPid, "SIGKILL");
3458
- }
3459
- }
3460
- /**
3461
- * Wait for server to be ready
3462
- */
3463
- async waitForReady(timeout) {
3464
- const timeoutMs = timeout ?? this.options.startupTimeout;
3465
- const deadline = Date.now() + timeoutMs;
3466
- const checkInterval = 100;
3467
- while (Date.now() < deadline) {
3468
- try {
3469
- const response = await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`, {
3470
- method: "GET",
3471
- signal: AbortSignal.timeout(1e3)
3472
- });
3473
- if (response.ok || response.status === 404) {
3474
- this.log("Server is ready");
3475
- return;
3476
- }
3477
- } catch {
3478
- }
3479
- await sleep2(checkInterval);
3480
- }
3481
- throw new Error(`Server did not become ready within ${timeoutMs}ms`);
3482
- }
3483
- /**
3484
- * Restart the server
3485
- */
3486
- async restart() {
3487
- await this.stopProcess();
3488
- await this.startProcess();
3489
- }
3490
- /**
3491
- * Get captured server logs
3492
- */
3493
- getLogs() {
3494
- return [...this.logs];
3495
- }
3496
- /**
3497
- * Clear captured logs
3498
- */
3499
- clearLogs() {
3500
- this.logs = [];
3501
- }
3502
- // ═══════════════════════════════════════════════════════════════════
3503
- // PRIVATE METHODS
3504
- // ═══════════════════════════════════════════════════════════════════
3505
- async startProcess() {
3506
- if (!this.options.command) {
3507
- await this.waitForReady();
3508
- return;
3509
- }
3510
- this.log(`Starting server: ${this.options.command}`);
3511
- const env = {
3512
- ...process.env,
3513
- ...this.options.env,
3514
- PORT: String(this.options.port)
3515
- };
3516
- const runtimeEnv = withWorkspaceProtocolFallback(env, this.options.cwd);
3517
- if (this.portReleaseSocket) {
3518
- await this.portReleaseSocket();
3519
- this.portReleaseSocket = null;
3520
- await sleep2(300);
3521
- }
3522
- this.process = (0, import_child_process.spawn)(this.options.command, [], {
3523
- cwd: this.options.cwd,
3524
- env: runtimeEnv,
3525
- shell: true,
3526
- detached: true,
3527
- stdio: ["pipe", "pipe", "pipe"]
3528
- });
3529
- this._info.pid = this.process.pid;
3530
- this._info.shellPid = this.process.pid;
3531
- let processExited = false;
3532
- let exitCode = null;
3533
- let exitError = null;
3534
- this.process.stdout?.on("data", (data) => {
3535
- const text = data.toString();
3536
- this.logs.push(text);
3537
- if (this.options.debug) {
3538
- console.log("[SERVER]", text);
3539
- }
3540
- });
3541
- this.process.stderr?.on("data", (data) => {
3542
- const text = data.toString();
3543
- this.logs.push(`[ERROR] ${text}`);
3544
- if (this.options.debug) {
3545
- console.error("[SERVER ERROR]", text);
3546
- }
3547
- });
3548
- this.process.on("error", (err) => {
3549
- this.logs.push(`[SPAWN ERROR] ${err.message}`);
3550
- exitError = err;
3551
- if (this.options.debug) {
3552
- console.error("[SERVER SPAWN ERROR]", err);
3553
- }
3554
- });
3555
- this.process.once("exit", (code) => {
3556
- processExited = true;
3557
- exitCode = code;
3558
- this.log(`Server process exited with code ${code}`);
3559
- });
3560
- try {
3561
- await this.waitForReadyWithExitDetection(() => {
3562
- if (exitError) {
3563
- return { exited: true, error: exitError };
3564
- }
3565
- if (processExited) {
3566
- const allLogs = this.logs.join("\n");
3567
- const errorLogs = this.logs.filter((l) => l.includes("[ERROR]") || l.toLowerCase().includes("error")).join("\n");
3568
- return {
3569
- exited: true,
3570
- error: new ServerStartError(
3571
- `Server process exited unexpectedly with code ${exitCode}.
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var fixtures_exports={};__export(fixtures_exports,{cleanupSharedResources:()=>cleanupSharedResources,cleanupTestFixtures:()=>cleanupTestFixtures,createTestFixtures:()=>createTestFixtures,initializeSharedResources:()=>initializeSharedResources,test:()=>test});module.exports=__toCommonJS(fixtures_exports);var import_jose=require("jose");var TestTokenFactory=class{issuer;audience;privateKey=null;publicKey=null;jwk=null;keyId;hmacSecret;constructor(options={}){this.issuer=options.issuer??"https://test.frontmcp.local";this.audience=options.audience??"frontmcp-test";this.keyId=`test-key-${Date.now()}`;this.hmacSecret=options.hmacSecret?new TextEncoder().encode(options.hmacSecret):null}get isHmac(){return this.hmacSecret!==null}get alg(){return this.isHmac?"HS256":"RS256"}signingKey(){if(this.hmacSecret)return this.hmacSecret;if(!this.privateKey){throw new Error("Private key not initialized")}return this.privateKey}async ensureKeys(){if(this.isHmac)return;if(this.privateKey&&this.publicKey)return;const{publicKey,privateKey}=await(0,import_jose.generateKeyPair)("RS256",{extractable:true});this.privateKey=privateKey;this.publicKey=publicKey;this.jwk=await(0,import_jose.exportJWK)(publicKey);this.jwk.kid=this.keyId;this.jwk.use="sig";this.jwk.alg="RS256"}async createTestToken(options){await this.ensureKeys();const nowMs=Date.now();const iat=Math.floor(nowMs/1e3);const exp=options.exp??3600;const payload={iss:options.iss??this.issuer,sub:options.sub,aud:options.aud??this.audience,iat,exp:Math.ceil(nowMs/1e3)+exp,scope:options.scopes?.join(" "),...options.claims};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}async createAdminToken(sub="admin-001"){return this.createTestToken({sub,scopes:["admin:*","read","write","delete"],claims:{email:"admin@test.local",name:"Test Admin",role:"admin"}})}async createUserToken(sub="user-001",scopes2=["read","write"]){return this.createTestToken({sub,scopes:scopes2,claims:{email:"user@test.local",name:"Test User",role:"user"}})}async createAnonymousToken(expiresIn){return this.createTestToken({sub:`anon:${Date.now()}`,scopes:["anonymous"],exp:expiresIn,claims:{name:"Anonymous",role:"anonymous"}})}async createExpiredToken(options){await this.ensureKeys();const now=Math.floor(Date.now()/1e3);const payload={iss:this.issuer,sub:options.sub,aud:this.audience,iat:now-7200,exp:now-3600};const header=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const token=await new import_jose.SignJWT(payload).setProtectedHeader(header).sign(this.signingKey());return token}createTokenWithInvalidSignature(options){const now=Math.floor(Date.now()/1e3);const headerObj=this.isHmac?{alg:this.alg,typ:"JWT"}:{alg:this.alg,kid:this.keyId};const header=Buffer.from(JSON.stringify(headerObj)).toString("base64url");const payload=Buffer.from(JSON.stringify({iss:this.issuer,sub:options.sub,aud:this.audience,iat:now,exp:now+3600})).toString("base64url");const signature=Buffer.from("invalid-signature-"+Date.now()).toString("base64url");return`${header}.${payload}.${signature}`}async getPublicJwks(){if(this.isHmac){throw new Error("getPublicJwks() is not available in HS256 mode (gateway tokens use a shared secret)")}await this.ensureKeys();if(!this.jwk){throw new Error("JWK not initialized")}return{keys:[this.jwk]}}getIssuer(){return this.issuer}getAudience(){return this.audience}};var DefaultMockRegistry=class{mocks=[];add(mock){const entry={definition:mock,callCount:0,calls:[],remainingUses:mock.times??Infinity};this.mocks.push(entry);return{remove:()=>{const index=this.mocks.indexOf(entry);if(index!==-1){this.mocks.splice(index,1)}},callCount:()=>entry.callCount,calls:()=>[...entry.calls]}}clear(){this.mocks=[]}getAll(){return this.mocks.map(e=>e.definition)}match(request){for(const entry of this.mocks){if(entry.remainingUses<=0)continue;const{definition}=entry;if(definition.method!==request.method)continue;if(definition.params!==void 0){const params=request.params??{};if(typeof definition.params==="function"){if(!definition.params(params))continue}else{if(!this.paramsMatch(definition.params,params))continue}}entry.callCount++;entry.calls.push(request);entry.remainingUses--;return definition}return void 0}paramsMatch(expected,actual){for(const[key,value]of Object.entries(expected)){if(!(key in actual))return false;const actualValue=actual[key];if(Array.isArray(value)){if(!Array.isArray(actualValue))return false;if(value.length!==actualValue.length)return false;for(let i=0;i<value.length;i++){const expectedItem=value[i];const actualItem=actualValue[i];if(typeof expectedItem==="object"&&expectedItem!==null){if(typeof actualItem!=="object"||actualItem===null)return false;if(!this.paramsMatch(expectedItem,actualItem)){return false}}else if(actualItem!==expectedItem){return false}}}else if(typeof value==="object"&&value!==null){if(typeof actualValue!=="object"||actualValue===null)return false;if(!this.paramsMatch(value,actualValue)){return false}}else if(actualValue!==value){return false}}return true}};var mockResponse={success(result,id=1){return{jsonrpc:"2.0",id,result}},error(code,message,data,id=1){return{jsonrpc:"2.0",id,error:{code,message,data}}},toolResult(content,id=1){return{jsonrpc:"2.0",id,result:{content}}},toolsList(tools,id=1){return{jsonrpc:"2.0",id,result:{tools}}},resourcesList(resources,id=1){return{jsonrpc:"2.0",id,result:{resources}}},resourceRead(contents,id=1){return{jsonrpc:"2.0",id,result:{contents}}},errors:{methodNotFound:(method,id=1)=>mockResponse.error(-32601,`Method not found: ${method}`,void 0,id),invalidParams:(message,id=1)=>mockResponse.error(-32602,message,void 0,id),internalError:(message,id=1)=>mockResponse.error(-32603,message,void 0,id),resourceNotFound:(uri,id=1)=>mockResponse.error(-32002,`Resource not found: ${uri}`,{uri},id),toolNotFound:(name,id=1)=>mockResponse.error(-32601,`Tool not found: ${name}`,{name},id),unauthorized:(id=1)=>mockResponse.error(-32001,"Unauthorized",void 0,id),forbidden:(id=1)=>mockResponse.error(-32003,"Forbidden",void 0,id)}};var DefaultInterceptorChain=class{request=[];response=[];mocks;constructor(){this.mocks=new DefaultMockRegistry}addRequestInterceptor(interceptor){this.request.push(interceptor);return()=>{const index=this.request.indexOf(interceptor);if(index!==-1){this.request.splice(index,1)}}}addResponseInterceptor(interceptor){this.response.push(interceptor);return()=>{const index=this.response.indexOf(interceptor);if(index!==-1){this.response.splice(index,1)}}}async processRequest(request,meta){let currentRequest=request;const mockDef=this.mocks.match(request);if(mockDef){if(mockDef.delay&&mockDef.delay>0){await sleep(mockDef.delay)}let mockResponse2;if(typeof mockDef.response==="function"){mockResponse2=await mockDef.response(request)}else{mockResponse2=mockDef.response}return{type:"mock",response:{...mockResponse2,id:request.id??mockResponse2.id}}}for(const interceptor of this.request){const ctx={request:currentRequest,meta};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentRequest=result.request;break;case"mock":return{type:"mock",response:{...result.response,id:request.id??result.response.id}};case"error":return{type:"error",error:result.error}}}return{type:"continue",request:currentRequest}}async processResponse(request,response,durationMs){let currentResponse=response;for(const interceptor of this.response){const ctx={request,response:currentResponse,durationMs};const result=await interceptor(ctx);switch(result.action){case"passthrough":break;case"modify":currentResponse=result.response;break}}return currentResponse}clear(){this.request=[];this.response=[];this.mocks.clear()}};function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function errorName(err){if(typeof err!=="object"||err===null)return void 0;const name=err.name;return typeof name==="string"?name:void 0}function isAbortError(err){return errorName(err)==="AbortError"}function errorMessage(err,fallback="Unknown error"){if(typeof err==="string"&&err)return err;if(typeof err==="object"&&err!==null){const message=err.message;if(typeof message==="string"&&message)return message}return fallback}var interceptedErrors=new WeakSet;function markInterceptedError(err){interceptedErrors.add(err);return err}function isInterceptedError(err){return typeof err==="object"&&err!==null&&interceptedErrors.has(err)}var DEFAULT_TIMEOUT=3e4;var SseTransport=class{baseUrl;entryPath;timeout;authHeaders;publicMode;debug;clientInfo;notificationHandler;interceptors;elicitationHandler;state="disconnected";authToken;sessionId;messageEndpoint;stream;pending=new Map;connectionCount=0;reconnectCount=0;lastRequestHeaders={};constructor(config){this.baseUrl=config.baseUrl.replace(/\/$/,"");this.entryPath=config.entryPath;this.timeout=config.timeout??DEFAULT_TIMEOUT;this.authHeaders=config.auth?.headers??{};this.authToken=config.auth?.token;this.publicMode=config.publicMode??false;this.debug=config.debug??false;this.clientInfo=config.clientInfo;this.notificationHandler=config.notificationHandler;this.interceptors=config.interceptors;this.elicitationHandler=config.elicitationHandler}async connect(){this.state="connecting";this.connectionCount++;try{if(!this.publicMode&&!this.authToken){await this.requestAnonymousToken()}await this.openStream();this.state="connected";this.log(`Connected; messages go to ${this.messageEndpoint}`)}catch(error){this.state="error";this.stream?.abort();this.stream=void 0;throw error}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const intercepted=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"sse",sessionId:this.sessionId});switch(intercepted.type){case"mock":return await this.interceptors.processResponse(message,intercepted.response,Date.now()-startTime);case"error":throw markInterceptedError(intercepted.error);case"continue":message=intercepted.request;break}}let response;if(message.id===void 0){await this.post(JSON.stringify(message));response={jsonrpc:"2.0",id:null,result:void 0}}else{response=await this.postAndAwait(message.id,JSON.stringify(message))}if(this.interceptors){response=await this.interceptors.processResponse(message,response,Date.now()-startTime)}return response}async notify(message){this.ensureConnected();const result=await this.post(JSON.stringify(message));if(!result.ok)this.log(`HTTP ${result.status} on notification: ${result.body}`)}async sendRaw(data){this.ensureConnected();let id;try{const parsed=JSON.parse(data);if(typeof parsed.id==="string"||typeof parsed.id==="number")id=parsed.id}catch{}if(id!==void 0)return this.postAndAwait(id,data);const result=await this.post(data);if(!result.ok){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:result.body}}}return{jsonrpc:"2.0",id:null,result:void 0}}async close(){this.closeStream("Transport closed");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0;this.log("SSE transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.timeout=ms}getMessageEndpoint(){return this.messageEndpoint}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}async simulateDisconnect(){this.closeStream("Simulated disconnect");this.state="disconnected";this.sessionId=void 0;this.messageEndpoint=void 0}async waitForReconnect(timeoutMs){this.reconnectCount++;let timer;try{await Promise.race([this.connect(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("Timeout waiting for reconnection")),timeoutMs)})])}finally{clearTimeout(timer)}}async openStream(){const controller=new AbortController;this.stream=controller;const url=this.sseUrl();const{"Content-Type":_contentType,...headers}=this.buildHeaders();this.log(`GET ${url}`);const connectTimer=setTimeout(()=>controller.abort(),this.timeout);let response;try{response=await fetch(url,{method:"GET",headers:{...headers,Accept:"text/event-stream"},signal:controller.signal})}catch(error){clearTimeout(connectTimer);throw new Error(isAbortError(error)?`SSE connection to ${url} timed out after ${this.timeout}ms`:`SSE connection to ${url} failed: ${errorMessage(error)}`,{cause:error})}const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){clearTimeout(connectTimer);const body=await response.text().catch(()=>"");throw new Error(`SSE connection to ${url} failed: HTTP ${response.status} ${response.statusText}${body?` \u2014 ${body}`:""}. The legacy HTTP+SSE transport needs a server that serves it (@FrontMcp({ transport: { protocol: { legacy: true } } })).`)}const endpoint=new Promise((resolve,reject)=>{const reader=response.body?.getReader();if(!reader){reject(new Error(`SSE connection to ${url} has no body`));return}void this.readStream(controller,reader,resolve,reject)});try{const data=await endpoint;const messageUrl=new URL(data,url);this.messageEndpoint=messageUrl.toString();this.sessionId=messageUrl.searchParams.get("sessionId")??void 0}finally{clearTimeout(connectTimer)}}async readStream(controller,reader,onEndpoint,onEndpointError){const decoder=new TextDecoder;let buffer="";let endpointSeen=false;try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){const{completeEvents,remainder}=splitSSEEvents(buffer+decoder.decode(chunk.value,{stream:true}));buffer=remainder;for(const text of completeEvents){const event=parseSSEEvent(text);if(!event)continue;if(event.type==="endpoint"){if(!endpointSeen){endpointSeen=true;onEndpoint(event.data)}continue}await this.handleMessage(event.data)}}}catch(error){if(!controller.signal.aborted)this.log("SSE stream failed:",error)}finally{reader.releaseLock()}if(!endpointSeen){onEndpointError(new Error(controller.signal.aborted?`SSE stream at ${this.sseUrl()} sent no endpoint event within ${this.timeout}ms`:`SSE stream at ${this.sseUrl()} ended before the server sent its endpoint`))}if(this.stream===controller){this.stream=void 0;this.rejectPending("SSE stream closed by the server");if(this.state==="connected")this.state="disconnected"}}async handleMessage(data){let message;try{message=JSON.parse(data)}catch{this.log("Ignoring SSE event that is not JSON:",data);return}if(!message||typeof message!=="object")return;if(typeof message.method==="string"){const request=message;if(request.id===void 0||request.id===null){this.notificationHandler?.(request);return}await this.answerServerRequest(request);return}if(message.id!==void 0&&message.id!==null){const pending=this.pending.get(message.id);if(pending){clearTimeout(pending.timer);this.pending.delete(message.id);pending.resolve(message)}}}async answerServerRequest(request){const id=request.id;let reply;if(request.method==="elicitation/create"){reply={jsonrpc:"2.0",id,result:await this.elicit(request.params)}}else if(request.method==="ping"){reply={jsonrpc:"2.0",id,result:{}}}else{reply={jsonrpc:"2.0",id,error:{code:-32601,message:`Method not found: ${request.method}`}}}const result=await this.post(JSON.stringify(reply));if(!result.ok)this.log(`HTTP ${result.status} answering ${request.method}: ${result.body}`)}async elicit(params){if(!this.elicitationHandler)return{action:"decline"};try{return await this.elicitationHandler(params)}catch(error){this.log("Elicitation handler error:",error);return{action:"cancel"}}}closeStream(reason){const controller=this.stream;this.stream=void 0;controller?.abort();this.rejectPending(reason)}rejectPending(reason){for(const[id,pending]of this.pending){clearTimeout(pending.timer);pending.resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:reason}})}this.pending.clear()}async postAndAwait(id,body){const answer=new Promise(resolve=>{const timer=setTimeout(()=>{this.pending.delete(id);resolve({jsonrpc:"2.0",id,error:{code:-32e3,message:`Request timeout after ${this.timeout}ms`}})},this.timeout);this.pending.set(id,{resolve,timer})});const result=await this.post(body);if(!result.ok){const pending=this.pending.get(id);if(pending){clearTimeout(pending.timer);this.pending.delete(id)}return{jsonrpc:"2.0",id,error:{code:-32e3,message:`HTTP ${result.status}: ${result.statusText}`,data:result.body}}}return answer}async post(body){const endpoint=this.messageEndpoint;if(!endpoint)throw new Error("SSE transport has no message endpoint. Call connect() first.");const headers=this.buildHeaders();this.lastRequestHeaders=headers;this.log(`POST ${endpoint}`,body);const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),this.timeout);try{const response=await fetch(endpoint,{method:"POST",headers,body,signal:controller.signal});const text=await response.text();return{ok:response.ok,status:response.status,statusText:response.statusText,body:text}}catch(error){if(isAbortError(error)){return{ok:false,status:0,statusText:`timeout after ${this.timeout}ms`,body:""}}throw error}finally{clearTimeout(timer)}}async requestAnonymousToken(){const url=new URL(this.baseUrl);url.pathname=`${url.pathname.replace(/\/+$/,"")}/oauth/token`;url.search="";const tokenUrl=url.toString();try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:crypto.randomUUID(),resource:this.baseUrl})});if(!response.ok){this.log(`No anonymous token (HTTP ${response.status})`);return}const token=await response.json();if(token.access_token)this.authToken=token.access_token}catch(error){this.log("Error requesting anonymous token:",error)}}sseUrl(){const url=new URL(this.baseUrl);const entry=(this.entryPath??"").replace(/^\/+|\/+$/g,"");const basePath=url.pathname.replace(/\/+$/,"");url.pathname=entry?`${basePath}/${entry}/sse`:`${basePath}/sse`;return url.toString()}buildHeaders(){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.clientInfo)headers["User-Agent"]=`${this.clientInfo.name}/${this.clientInfo.version}`;if(this.authToken)headers["Authorization"]=`Bearer ${this.authToken}`;if(this.sessionId)headers["mcp-session-id"]=this.sessionId;Object.assign(headers,this.authHeaders);return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.debug){console.log(`[SSE] ${message}`,data??"")}}};function splitSSEEvents(buffer){const endsWithCarriageReturn=buffer.endsWith("\r");const normalized=(endsWithCarriageReturn?buffer.slice(0,-1):buffer).replace(/\r\n?/g,"\n");const completeEvents=normalized.split("\n\n");const remainder=completeEvents.pop()??"";return{completeEvents,remainder:endsWithCarriageReturn?`${remainder}\r`:remainder}}function parseSSEEvent(text){let type="message";const data=[];for(const line of text.split("\n")){if(line.startsWith(":"))continue;const colon=line.indexOf(":");const field=colon===-1?line:line.slice(0,colon);const value=colon===-1?"":line.slice(colon+1).replace(/^ /,"");if(field==="event")type=value;else if(field==="data")data.push(value)}return data.length>0?{type,data:data.join("\n")}:void 0}var DEFAULT_TIMEOUT2=3e4;var NOTIFICATION_STREAM_REOPEN_DELAY_MS=250;var StreamableHttpTransport=class{config;state="disconnected";sessionId;authToken;connectionCount=0;reconnectCount=0;lastRequestHeaders={};interceptors;publicMode;elicitationHandler;notificationHandler;notificationStream;notificationProtocolVersion="";notificationStreamReopenTimer;constructor(config){this.config={baseUrl:config.baseUrl.replace(/\/$/,""),entryPath:config.entryPath,timeout:config.timeout??DEFAULT_TIMEOUT2,auth:config.auth??{},publicMode:config.publicMode??false,debug:config.debug??false,interceptors:config.interceptors,clientInfo:config.clientInfo};this.authToken=config.auth?.token;this.interceptors=config.interceptors;this.publicMode=config.publicMode??false;this.elicitationHandler=config.elicitationHandler;this.notificationHandler=config.notificationHandler}async connect(){this.state="connecting";this.connectionCount++;try{if(this.publicMode){this.log("Public mode: connecting without authentication");this.state="connected";return}if(!this.authToken){await this.requestAnonymousToken()}this.state="connected";this.log("Connected to StreamableHTTP transport")}catch(error){this.state="error";throw error}}async requestAnonymousToken(){const clientId=crypto.randomUUID();const tokenUrl=`${this.config.baseUrl}/oauth/token`;this.log(`Requesting anonymous token from ${tokenUrl}`);try{const response=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"anonymous",client_id:clientId,resource:this.config.baseUrl})});if(!response.ok){const errorText=await response.text();this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);return}const tokenResponse=await response.json();if(tokenResponse.access_token){this.authToken=tokenResponse.access_token;this.log("Anonymous token acquired successfully")}}catch(error){this.log(`Error requesting anonymous token: ${error}`)}}async request(message){this.ensureConnected();const startTime=Date.now();if(this.interceptors){const interceptResult=await this.interceptors.processRequest(message,{timestamp:new Date,transport:"streamable-http",sessionId:this.sessionId});switch(interceptResult.type){case"mock":{const mockResponse2=await this.interceptors.processResponse(message,interceptResult.response,Date.now()-startTime);return mockResponse2}case"error":throw markInterceptedError(interceptResult.error);case"continue":message=interceptResult.request;break}}const headers=this.buildHeaders();this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url}`,message);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(message),signal:controller.signal});const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}let jsonResponse;if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status}: ${errorText}`);jsonResponse={jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`HTTP ${response.status}: ${response.statusText}`,data:errorText}}}else{const contentType=response.headers.get("content-type")??"";if(contentType.includes("text/event-stream")){jsonResponse=await this.handleSSEResponseWithElicitation(response,message)}else{const text=await response.text();this.log("Response:",text);if(!text.trim()){jsonResponse={jsonrpc:"2.0",id:message.id??null,result:void 0}}else{jsonResponse=JSON.parse(text)}}}if(this.interceptors){jsonResponse=await this.interceptors.processResponse(message,jsonResponse,Date.now()-startTime)}clearTimeout(timeoutId);return jsonResponse}catch(error){clearTimeout(timeoutId);if(isAbortError(error)){return{jsonrpc:"2.0",id:message.id??null,error:{code:-32e3,message:`Request timeout after ${this.config.timeout}ms`}}}throw error}}async notify(message){this.ensureConnected();const headers=this.buildHeaders();this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (notification)`,message);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:JSON.stringify(message),signal:controller.signal});clearTimeout(timeoutId);const newSessionId=response.headers.get("mcp-session-id");if(newSessionId){this.sessionId=newSessionId}if(!response.ok){const errorText=await response.text();this.log(`HTTP Error ${response.status} on notification: ${errorText}`)}}catch(error){clearTimeout(timeoutId);if(!isAbortError(error)){throw error}}}async sendRaw(data){this.ensureConnected();const headers=this.buildHeaders();this.lastRequestHeaders=headers;const url=this.mcpUrl();this.log(`POST ${url} (raw)`,data);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),this.config.timeout);try{const response=await fetch(url,{method:"POST",headers,body:data,signal:controller.signal});clearTimeout(timeoutId);const text=await response.text();if(!text.trim()){return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}}}return JSON.parse(text)}catch(error){clearTimeout(timeoutId);return{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error",data:errorMessage(error)}}}}async openNotificationStream(protocolVersion){this.notificationProtocolVersion=protocolVersion;await this.connectNotificationStream()}async close(){this.closeNotificationStream();this.state="disconnected";this.sessionId=void 0;this.log("StreamableHTTP transport closed")}isConnected(){return this.state==="connected"}getState(){return this.state}getSessionId(){return this.sessionId}setAuthToken(token){this.authToken=token}setTimeout(ms){this.config.timeout=ms}setInterceptors(interceptors2){this.interceptors=interceptors2}getInterceptors(){return this.interceptors}setElicitationHandler(handler){this.elicitationHandler=handler}getConnectionCount(){return this.connectionCount}getReconnectCount(){return this.reconnectCount}getLastRequestHeaders(){return{...this.lastRequestHeaders}}async simulateDisconnect(){this.closeNotificationStream();this.state="disconnected";this.sessionId=void 0}async waitForReconnect(timeoutMs){const deadline=Date.now()+timeoutMs;this.reconnectCount++;await this.connect();while(Date.now()<deadline){if(this.state==="connected"){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for reconnection")}closeNotificationStream(){clearTimeout(this.notificationStreamReopenTimer);this.notificationStream?.abort();this.notificationStream=void 0}async connectNotificationStream(){if(!this.sessionId||this.notificationStream)return;const controller=new AbortController;this.notificationStream=controller;const{"Content-Type":_contentType,...headers}=this.buildHeaders();const established=fetch(this.mcpUrl(),{method:"GET",headers:{...headers,Accept:"text/event-stream","MCP-Protocol-Version":this.notificationProtocolVersion},signal:controller.signal}).then(async response=>{const isEventStream=response.headers.get("content-type")?.includes("text/event-stream")??false;if(!response.ok||!response.body||!isEventStream){await response.body?.cancel();this.log(`Server offers no notification stream (HTTP ${response.status})`);this.releaseNotificationStream(controller);return}void this.readNotificationStream(controller,response.body.getReader())},error=>{this.log("Failed to open the notification stream:",error);this.releaseNotificationStream(controller)});let establishTimer;const establishDeadline=new Promise(resolve=>{establishTimer=setTimeout(resolve,this.config.timeout)});await Promise.race([established,establishDeadline]);clearTimeout(establishTimer)}releaseNotificationStream(controller){if(this.notificationStream===controller)this.notificationStream=void 0}async readNotificationStream(controller,reader){const decoder=new TextDecoder;let buffer="";try{for(let chunk=await reader.read();!chunk.done;chunk=await reader.read()){const{completeEvents,remainder}=splitSSEEvents2(buffer+decoder.decode(chunk.value,{stream:true}));buffer=remainder;for(const eventText of completeEvents){for(const event of this.parseSSEEvents(eventText,void 0).events){await this.handleSSEEvent(event)}}}}catch(error){this.log("Notification stream ended:",error)}finally{reader.releaseLock()}if(controller.signal.aborted||this.notificationStream!==controller)return;this.releaseNotificationStream(controller);this.notificationStreamReopenTimer=setTimeout(()=>void this.connectNotificationStream(),NOTIFICATION_STREAM_REOPEN_DELAY_MS)}async handleSSEResponseWithElicitation(response,originalRequest){this.log("handleSSEResponseWithElicitation: starting",{requestId:originalRequest.id});const reader=response.body?.getReader();if(!reader){this.log("handleSSEResponseWithElicitation: no response body");return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No response body"}}}const decoder=new TextDecoder;let buffer="";let finalResponse=null;let sseSessionId;try{let readCount=0;while(true){readCount++;this.log(`handleSSEResponseWithElicitation: reading chunk ${readCount}`);const{done,value}=await reader.read();this.log(`handleSSEResponseWithElicitation: read result`,{done,valueLength:value?.length});if(done){if(buffer.trim()){const parsed=this.parseSSEEvents(buffer,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}break}buffer+=decoder.decode(value,{stream:true});const eventEndPattern=/\n\n/g;let lastEventEnd=0;let match;while((match=eventEndPattern.exec(buffer))!==null){const eventText=buffer.slice(lastEventEnd,match.index);lastEventEnd=match.index+2;if(eventText.trim()){const parsed=this.parseSSEEvents(eventText,originalRequest.id);for(const event of parsed.events){const handled=await this.handleSSEEvent(event);if(handled.isFinal){finalResponse=handled.response}}if(parsed.sessionId&&!sseSessionId){sseSessionId=parsed.sessionId}}}buffer=buffer.slice(lastEventEnd)}}finally{reader.releaseLock()}if(sseSessionId&&!this.sessionId){this.sessionId=sseSessionId;this.log("Session ID from SSE:",this.sessionId)}if(finalResponse){return finalResponse}return{jsonrpc:"2.0",id:originalRequest.id??null,error:{code:-32e3,message:"No final response received in SSE stream"}}}parseSSEEvents(text,_requestId){const lines=text.split("\n");const events=[];let currentEvent={type:"message",data:[]};let sessionId;for(const line of lines){if(line.startsWith("event: ")){currentEvent.type=line.slice(7)}else if(line.startsWith("data: ")){currentEvent.data.push(line.slice(6))}else if(line==="data:"){currentEvent.data.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);currentEvent.id=idValue;const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sessionId=idValue.substring(0,colonIndex)}else{sessionId=idValue}}else if(line===""&&currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id});currentEvent={type:"message",data:[]}}}if(currentEvent.data.length>0){events.push({type:currentEvent.type,data:currentEvent.data.join("\n"),id:currentEvent.id})}return{events,sessionId}}async handleSSEEvent(event){this.log("SSE Event:",{type:event.type,data:event.data.slice(0,200)});try{const parsed=JSON.parse(event.data);if("method"in parsed&&parsed.method==="elicitation/create"){await this.handleElicitationRequest(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("method"in parsed&&parsed.id===void 0){this.notificationHandler?.(parsed);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}if("result"in parsed||"error"in parsed){return{isFinal:true,response:parsed}}return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}catch{this.log("Failed to parse SSE event data:",event.data);return{isFinal:false,response:{jsonrpc:"2.0",id:null,result:void 0}}}}async handleElicitationRequest(request){const params=request.params;this.log("Elicitation request received:",{mode:params?.mode,message:params?.message?.slice(0,100)});const requestId=request.id;if(requestId===void 0||requestId===null){this.log("Elicitation request has no ID, cannot respond");return}if(!this.elicitationHandler){this.log("No elicitation handler registered, sending error");await this.sendElicitationResponse(requestId,{action:"decline"});return}try{const response=await this.elicitationHandler(params);this.log("Elicitation handler response:",response);await this.sendElicitationResponse(requestId,response)}catch(error){this.log("Elicitation handler error:",error);await this.sendElicitationResponse(requestId,{action:"cancel"})}}async sendElicitationResponse(requestId,response){const headers=this.buildHeaders();const url=this.mcpUrl();const rpcResponse={jsonrpc:"2.0",id:requestId,result:response};this.log("Sending elicitation response:",rpcResponse);try{const fetchResponse=await fetch(url,{method:"POST",headers,body:JSON.stringify(rpcResponse)});if(!fetchResponse.ok){this.log(`Elicitation response HTTP error: ${fetchResponse.status}`)}}catch(error){this.log("Failed to send elicitation response:",error)}}mcpUrl(){const url=new URL(this.config.baseUrl);const entry=(this.config.entryPath??"").replace(/^\/+|\/+$/g,"");const basePath=url.pathname.replace(/\/+$/,"");url.pathname=entry?`${basePath}/${entry}`:`${basePath}/`;return url.toString()}buildHeaders(){const headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.config.clientInfo){headers["User-Agent"]=`${this.config.clientInfo.name}/${this.config.clientInfo.version}`}if(this.authToken){headers["Authorization"]=`Bearer ${this.authToken}`}if(this.sessionId){headers["mcp-session-id"]=this.sessionId}if(this.config.auth.headers){Object.assign(headers,this.config.auth.headers)}return headers}ensureConnected(){if(this.state!=="connected"){throw new Error("Transport not connected. Call connect() first.")}}log(message,data){if(this.config.debug){console.log(`[StreamableHTTP] ${message}`,data??"")}}parseSSEResponseWithSession(text,requestId){const lines=text.split("\n");const dataLines=[];let sseSessionId;for(const line of lines){if(line.startsWith("data: ")){dataLines.push(line.slice(6))}else if(line==="data:"){dataLines.push("")}else if(line.startsWith("id: ")){const idValue=line.slice(4);const colonIndex=idValue.lastIndexOf(":");if(colonIndex>0){sseSessionId=idValue.substring(0,colonIndex)}else{sseSessionId=idValue}}}if(dataLines.length>0){const jsonData=dataLines.join("\n");try{return{response:JSON.parse(jsonData),sseSessionId}}catch{this.log("Failed to parse SSE data as JSON:",jsonData)}}return{response:{jsonrpc:"2.0",id:requestId??null,error:{code:-32700,message:"Failed to parse SSE response",data:text}},sseSessionId}}};function splitSSEEvents2(buffer){const endsWithCarriageReturn=buffer.endsWith("\r");const normalized=(endsWithCarriageReturn?buffer.slice(0,-1):buffer).replace(/\r\n?/g,"\n");const completeEvents=normalized.split("\n\n");const remainder=completeEvents.pop()??"";return{completeEvents,remainder:endsWithCarriageReturn?`${remainder}\r`:remainder}}var MCP_APPS_EXTENSION_KEY="io.modelcontextprotocol/ui";function getPlatformClientInfo(platform){switch(platform){case"openai":return{name:"ChatGPT",version:"1.0"};case"ext-apps":return{name:"mcp-ext-apps",version:"1.0"};case"claude":return{name:"claude-desktop",version:"1.0"};case"cursor":return{name:"cursor",version:"1.0"};case"continue":return{name:"continue",version:"1.0"};case"cody":return{name:"cody",version:"1.0"};case"gemini":return{name:"gemini",version:"1.0"};case"generic-mcp":return{name:"generic-mcp-client",version:"1.0"};case"unknown":default:return{name:"mcp-test-client",version:"1.0"}}}function getPlatformCapabilities(platform){const baseCapabilities={sampling:{},elicitation:{form:{}}};if(platform==="ext-apps"){return{...baseCapabilities,experimental:{[MCP_APPS_EXTENSION_KEY]:{mimeTypes:["text/html;profile=mcp-app"]}}}}return baseCapabilities}var McpTestClientBuilder=class{config;constructor(config){this.config={...config}}withAuth(auth){this.config.auth={...this.config.auth,...auth};return this}withToken(token){this.config.auth={...this.config.auth,token};return this}withHeaders(headers){this.config.auth={...this.config.auth,headers:{...this.config.auth?.headers,...headers}};return this}withTransport(transport){this.config.transport=transport;return this}withTimeout(timeoutMs){this.config.timeout=timeoutMs;return this}withDebug(enabled=true){this.config.debug=enabled;return this}withPublicMode(enabled=true){this.config.publicMode=enabled;return this}withProtocolVersion(version){this.config.protocolVersion=version;return this}withClientInfo(info){this.config.clientInfo=info;return this}withPlatform(platform){this.config.platform=platform;this.config.clientInfo=getPlatformClientInfo(platform);this.config.capabilities=getPlatformCapabilities(platform);return this}withCapabilities(capabilities){this.config.capabilities=capabilities;return this}withQueryParams(params){this.config.queryParams={...this.config.queryParams,...params};return this}build(){return new McpTestClient(this.config)}async buildAndConnect(){const client=this.build();await client.connect();return client}};var DEFAULT_TIMEOUT3=3e4;var DEFAULT_PROTOCOL_VERSION="2025-06-18";var UNSUPPORTED_PROTOCOL_VERSIONS=["2026-07-28"];var DEFAULT_CLIENT_INFO={name:"@frontmcp/testing",version:"0.4.0"};var MAX_LIST_PAGES=1e3;function isAuthFailure(error){return typeof error?.message==="string"&&/^HTTP (401|403)\b/.test(error.message)}function describeInitializeError(error){const message=error?.message??"Unknown error";const data=error?.data;const detail=typeof data==="string"?data.trim():"";return detail?`${message} - ${detail.slice(0,500)}`:message}function extractEntryPaths(data){let payload=data;if(typeof payload==="string"){try{payload=JSON.parse(payload)}catch{return void 0}}if(!payload||typeof payload!=="object")return void 0;const paths=payload.entryPaths;if(!Array.isArray(paths))return void 0;const strings=paths.filter(p=>typeof p==="string");return strings.length>0?strings:void 0}var McpTestClient=class{config;transport=null;initResult=null;requestIdCounter=0;_lastRequestId=0;_sessionId;triedDiscoveredEntryPath=false;_sessionInfo=null;_authState={isAnonymous:true,scopes:[]};_logs=[];_traces=[];_notifications=[];_progressUpdates=[];collectingProgress=false;progressTokenCounter=0;_interceptors;_elicitationHandler;constructor(config){if(config.protocolVersion&&UNSUPPORTED_PROTOCOL_VERSIONS.includes(config.protocolVersion)){throw new Error(`McpTestClient does not support protocol version ${config.protocolVersion}: it has no initialize handshake. Use ${DEFAULT_PROTOCOL_VERSION} or earlier.`)}this.config={baseUrl:config.baseUrl,entryPath:config.entryPath,transport:config.transport??"streamable-http",auth:config.auth??{},publicMode:config.publicMode??false,timeout:config.timeout??DEFAULT_TIMEOUT3,debug:config.debug??false,protocolVersion:config.protocolVersion??DEFAULT_PROTOCOL_VERSION,clientInfo:config.clientInfo??DEFAULT_CLIENT_INFO,platform:config.platform,capabilities:config.capabilities,queryParams:config.queryParams};if(config.auth?.token){this._authState={isAnonymous:false,token:config.auth.token,scopes:this.parseScopesFromToken(config.auth.token),user:this.parseUserFromToken(config.auth.token)}}this._interceptors=new DefaultInterceptorChain}static create(config){return new McpTestClientBuilder(config)}async connect(){this.log("debug",`Connecting to ${this.config.baseUrl}...`);this.triedDiscoveredEntryPath=false;this.initResult=null;this.transport=this.createTransport();await this.transport.connect();const maxRetries=3;const retryDelayMs=500;let lastError;let reportedEntryPaths;let attemptsMade=0;for(let attempt=1;attempt<=maxRetries;attempt++){attemptsMade=attempt;const initResponse=await this.initialize();if(initResponse.success&&initResponse.data){this.initResult=initResponse.data;break}lastError=describeInitializeError(initResponse.error);reportedEntryPaths=extractEntryPaths(initResponse.error?.data)??reportedEntryPaths;if(reportedEntryPaths?.length===1&&!this.triedDiscoveredEntryPath){this.triedDiscoveredEntryPath=true;const discovered=reportedEntryPaths[0];this.log("info",`Server serves MCP at ${discovered}; reconnecting there (configured: ${this.mcpPathLabel()})`);this.config.entryPath=discovered;await this.transport.close();this.transport=this.createTransport();await this.transport.connect();continue}if(isAuthFailure(initResponse.error))break;if(attempt<maxRetries){this.log("debug",`MCP init attempt ${attempt} failed (${lastError}), retrying in ${retryDelayMs}ms...`);await new Promise(resolve=>setTimeout(resolve,retryDelayMs))}}if(!this.initResult){const served=reportedEntryPaths?.length?` The server reports it serves MCP at ${reportedEntryPaths.join(", ")}; set \`entryPath\` in test.use() (or \`http.entryPath\` on the server) to match.`:"";throw new Error(`Failed to initialize MCP connection to ${this.config.baseUrl}${this.mcpPathLabel()} after ${attemptsMade} attempt${attemptsMade===1?"":"s"}: ${lastError}.${served}`)}this._sessionId=this.transport.getSessionId();this._sessionInfo={id:this._sessionId??`session-${Date.now()}`,createdAt:new Date,lastActivityAt:new Date,requestCount:1};await this.transport.notify({jsonrpc:"2.0",method:"notifications/initialized"});await this.transport.openNotificationStream?.(this.initResult.protocolVersion);this.log("info",`Connected to ${this.initResult.serverInfo?.name??"MCP Server"}`);return this.initResult}async disconnect(){if(this.transport){await this.transport.close();this.transport=null}this.initResult=null;this.log("info","Disconnected from MCP server")}async reconnect(options){await this.disconnect();if(options?.sessionId&&this.transport){this._sessionId=options.sessionId}await this.connect()}isConnected(){return this.transport?.isConnected()??false}get sessionId(){return this._sessionId??""}get session(){const info=this._sessionInfo??{id:"",createdAt:new Date,lastActivityAt:new Date,requestCount:0};return{...info,expire:async()=>{this._sessionId=void 0;this._sessionInfo=null}}}get auth(){return this._authState}async authenticate(token){if(typeof token!=="string"||token.trim()===""){throw new Error("authenticate() requires a non-empty token")}const previousAuthState=this._authState;const previousConfigAuth=this.config.auth;this.config.auth={...previousConfigAuth,token};this._authState={isAnonymous:false,token,scopes:this.parseScopesFromToken(token),user:this.parseUserFromToken(token)};const previousTransport=this.transport;if(!previousTransport){this.log("debug","Authentication updated (not connected yet)");return}const previousInit=this.initResult;const previousSessionId=this._sessionId;const previousSessionInfo=this._sessionInfo;try{await this.connect()}catch(err){await this.transport?.close().catch(()=>void 0);this.transport=previousTransport;this.initResult=previousInit;this._sessionId=previousSessionId;this._sessionInfo=previousSessionInfo;this.config.auth=previousConfigAuth;this._authState=previousAuthState;throw err}await previousTransport.close().catch(()=>void 0);this.log("debug","Authentication updated")}get serverInfo(){return{name:this.initResult?.serverInfo?.name??"",version:this.initResult?.serverInfo?.version??""}}get protocolVersion(){return this.initResult?.protocolVersion??""}get instructions(){return this.initResult?.instructions??""}get capabilities(){return this.initResult?.capabilities??{}}hasCapability(name){return!!this.capabilities[name]}tools={list:async()=>this.listAllPages("tools/list","tools",cursor=>this.listTools(cursor),page=>page.tools),call:async(name,args,options={})=>{const response=await this.callTool(name,args,this.progressTokenFor(options));return this.wrapToolResult(response)}};resources={list:async()=>this.listAllPages("resources/list","resources",cursor=>this.listResources(cursor),page=>page.resources),listTemplates:async()=>this.listAllPages("resources/templates/list","resource templates",cursor=>this.listResourceTemplates(cursor),page=>page.resourceTemplates),read:async uri=>{const response=await this.readResource(uri);return this.wrapResourceContent(response)},subscribe:async _uri=>{this.log("warn","Resource subscription not yet implemented")},unsubscribe:async _uri=>{this.log("warn","Resource unsubscription not yet implemented")}};prompts={list:async()=>this.listAllPages("prompts/list","prompts",cursor=>this.listPrompts(cursor),page=>page.prompts),get:async(name,args)=>{const response=await this.getPrompt(name,args);return this.wrapPromptResult(response)}};raw={request:async message=>{const transport=this.getConnectedTransport();const start=Date.now();const response=await transport.request(message);this.traceRequest(message.method,message.params,message.id,response,Date.now()-start);return response},notify:async message=>{const transport=this.getConnectedTransport();await transport.notify(message)},sendRaw:async data=>{const transport=this.getConnectedTransport();return transport.sendRaw(data)}};get lastRequestId(){return this._lastRequestId}get transport_info(){return{type:this.config.transport,isConnected:()=>this.transport?.isConnected()??false,messageEndpoint:this.transport?.getMessageEndpoint?.(),connectionCount:this.transport?.getConnectionCount?.()??0,reconnectCount:this.transport?.getReconnectCount?.()??0,lastRequestHeaders:this.transport?.getLastRequestHeaders?.()??{},simulateDisconnect:async()=>{await this.transport?.simulateDisconnect?.()},waitForReconnect:async timeoutMs=>{await this.transport?.waitForReconnect?.(timeoutMs)}}}get transport_(){return this.transport_info}notifications={collect:()=>{return new NotificationCollector(this._notifications)},collectProgress:()=>{this.collectingProgress=true;return new ProgressCollector(this._progressUpdates)},send:async(method,params)=>{await this.raw.notify({jsonrpc:"2.0",method,params})}};onElicitation(handler){this._elicitationHandler=handler;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(handler)}this.log("debug","Elicitation handler registered")}clearElicitationHandler(){this._elicitationHandler=void 0;if(this.transport?.setElicitationHandler){this.transport.setElicitationHandler(void 0)}this.log("debug","Elicitation handler cleared")}logs={all:()=>[...this._logs],filter:level=>this._logs.filter(l=>l.level===level),search:text=>this._logs.filter(l=>l.message.includes(text)),last:()=>this._logs[this._logs.length-1],clear:()=>{this._logs=[]}};trace={all:()=>[...this._traces],last:()=>this._traces[this._traces.length-1],clear:()=>{this._traces=[]}};mock={add:mock=>{return this._interceptors.mocks.add(mock)},tool:(name,result,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.toolResult([{type:"text",text:typeof result==="string"?result:JSON.stringify(result)}]),times:options?.times,delay:options?.delay})},toolError:(name,code,message,options)=>{return this._interceptors.mocks.add({method:"tools/call",params:{name},response:mockResponse.error(code,message),times:options?.times})},resource:(uri,content,options)=>{const contentObj=typeof content==="string"?{uri,text:content}:{uri,...content};return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.resourceRead([contentObj]),times:options?.times,delay:options?.delay})},resourceError:(uri,options)=>{return this._interceptors.mocks.add({method:"resources/read",params:{uri},response:mockResponse.errors.resourceNotFound(uri),times:options?.times})},toolsList:(tools,options)=>{return this._interceptors.mocks.add({method:"tools/list",response:mockResponse.toolsList(tools),times:options?.times})},resourcesList:(resources,options)=>{return this._interceptors.mocks.add({method:"resources/list",response:mockResponse.resourcesList(resources),times:options?.times})},clear:()=>{this._interceptors.mocks.clear()},all:()=>{return this._interceptors.mocks.getAll()}};intercept={request:interceptor=>{return this._interceptors.addRequestInterceptor(interceptor)},response:interceptor=>{return this._interceptors.addResponseInterceptor(interceptor)},delay:ms=>{return this._interceptors.addRequestInterceptor(async()=>{await new Promise(r=>setTimeout(r,ms));return{action:"passthrough"}})},failMethod:(method,error)=>{return this._interceptors.addRequestInterceptor(ctx=>{if(ctx.request.method===method){return{action:"error",error:new Error(error??`Intercepted: ${method}`)}}return{action:"passthrough"}})},clear:()=>{this._interceptors.request=[];this._interceptors.response=[]},clearAll:()=>{this._interceptors.clear()}};setTimeout(ms){this.config.timeout=ms;if(this.transport){this.transport.setTimeout(ms)}}async initialize(){const capabilities=this.config.capabilities??{sampling:{},elicitation:{form:{}}};return this.request("initialize",{protocolVersion:this.config.protocolVersion,capabilities,clientInfo:this.config.clientInfo})}async listTools(cursor){return this.request("tools/list",cursor?{cursor}:{})}async listAllPages(method,label,fetchPage,itemsOf){const items=[];const seenCursors=new Set;let cursor;for(let page=0;page<MAX_LIST_PAGES;page++){const response=await fetchPage(cursor);if(!response.success||!response.data){throw new Error(`Failed to list ${label}: ${response.error?.message}`)}items.push(...itemsOf(response.data)??[]);const next=response.data.nextCursor;if(!next)return items;if(seenCursors.has(next)){throw new Error(`Failed to list ${label}: ${method} returned the cursor "${next}" twice`)}seenCursors.add(next);cursor=next}throw new Error(`Failed to list ${label}: ${method} did not finish within ${MAX_LIST_PAGES} pages`)}async callTool(name,args,progressToken){return this.request("tools/call",{name,arguments:args??{},...progressToken!==void 0&&{_meta:{progressToken}}})}progressTokenFor(options){if(options.progressToken!==void 0)return options.progressToken;return this.collectingProgress?`progress-${++this.progressTokenCounter}`:void 0}recordNotification=notification=>{const timestamp=new Date;this._notifications.push({method:notification.method,params:notification.params,timestamp});if(notification.method!=="notifications/progress")return;const{progress,total,progressToken}=notification.params??{};this._progressUpdates.push({progress:Number(progress),total:typeof total==="number"?total:void 0,progressToken:typeof progressToken==="string"||typeof progressToken==="number"?progressToken:void 0,timestamp})};async listResources(cursor){return this.request("resources/list",cursor?{cursor}:{})}async listResourceTemplates(cursor){return this.request("resources/templates/list",cursor?{cursor}:{})}async readResource(uri){return this.request("resources/read",{uri})}async listPrompts(cursor){return this.request("prompts/list",cursor?{cursor}:{})}async getPrompt(name,args){return this.request("prompts/get",{name,arguments:args??{}})}mcpPathLabel(){const entry=(this.config.entryPath??"").replace(/^\/+|\/+$/g,"");return entry?`/${entry}`:"/"}createTransport(){let baseUrl=this.config.baseUrl;if(this.config.queryParams&&Object.keys(this.config.queryParams).length>0){const url=new URL(baseUrl);Object.entries(this.config.queryParams).forEach(([key,value])=>{url.searchParams.set(key,String(value))});baseUrl=url.toString()}switch(this.config.transport){case"streamable-http":return new StreamableHttpTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification});case"sse":return new SseTransport({baseUrl,entryPath:this.config.entryPath,timeout:this.config.timeout,auth:this.config.auth,publicMode:this.config.publicMode,debug:this.config.debug,interceptors:this._interceptors,clientInfo:this.config.clientInfo,elicitationHandler:this._elicitationHandler,notificationHandler:this.recordNotification});default:throw new Error(`Unknown transport type: ${this.config.transport}`)}}async request(method,params){const transport=this.getConnectedTransport();const id=++this.requestIdCounter;this._lastRequestId=id;const start=Date.now();try{const response=await transport.request({jsonrpc:"2.0",id,method,params});const durationMs=Date.now()-start;this.updateSessionActivity();if("error"in response&&response.error){const error=response.error;this.traceRequest(method,params,id,response,durationMs);return{success:false,error,durationMs,requestId:id}}this.traceRequest(method,params,id,response,durationMs);return{success:true,data:response.result,durationMs,requestId:id}}catch(err){if(isInterceptedError(err))throw err;const durationMs=Date.now()-start;const error={code:-32603,message:errorMessage(err)};return{success:false,error,durationMs,requestId:id}}}getConnectedTransport(){if(!this.transport||!this.transport.isConnected()){throw new Error("Not connected to MCP server. Call connect() first.")}return this.transport}updateSessionActivity(){if(this._sessionInfo){this._sessionInfo.lastActivityAt=new Date;this._sessionInfo.requestCount++}}wrapToolResult(response){const raw=response.data??{content:[]};const isError=!response.success||raw.isError===true;const meta=raw._meta;const hasUI=meta?.["ui/html"]!==void 0||meta?.["ui/component"]!==void 0;const structuredContent=raw["structuredContent"];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(hasUI&&structuredContent!==void 0){return structuredContent}const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return JSON.parse(textContent.text)}throw new Error("No text content to parse as JSON")},text(){const textContent=raw.content?.find(c=>c.type==="text");if(textContent&&"text"in textContent){return textContent.text}return void 0},hasTextContent(){return raw.content?.some(c=>c.type==="text")??false},hasImageContent(){return raw.content?.some(c=>c.type==="image")??false},hasResourceContent(){return raw.content?.some(c=>c.type==="resource")??false},hasToolUI(){return hasUI}}}wrapResourceContent(response){const raw=response.data??{contents:[]};const isError=!response.success;const firstContent=raw.contents?.[0];return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,json(){if(firstContent&&"text"in firstContent){return JSON.parse(firstContent.text)}throw new Error("No text content to parse as JSON")},text(){if(firstContent&&"text"in firstContent){return firstContent.text}return void 0},mimeType(){return firstContent?.mimeType},hasMimeType(type){return firstContent?.mimeType===type}}}wrapPromptResult(response){const raw=response.data??{messages:[]};const isError=!response.success;return{raw,isSuccess:!isError,isError,error:response.error,durationMs:response.durationMs,messages:raw.messages??[],description:raw.description}}log(level,message,data){const entry={level,message,timestamp:new Date,data};this._logs.push(entry);if(this.config.debug){console.log(`[${level.toUpperCase()}] ${message}`,data??"")}}traceRequest(method,params,id,response,durationMs){this._traces.push({request:{method,params,id},response:{result:"result"in response?response.result:void 0,error:"error"in response?response.error:void 0},durationMs,timestamp:new Date})}parseScopesFromToken(token){try{const payload=this.decodeJwtPayload(token);if(!payload)return[];const scope=payload["scope"];const scopes2=payload["scopes"];if(typeof scope==="string"){return scope.split(" ")}if(Array.isArray(scopes2)){return scopes2}return[]}catch{return[]}}parseUserFromToken(token){try{const payload=this.decodeJwtPayload(token);const sub=payload?.["sub"];if(!sub||typeof sub!=="string")return void 0;return{sub,email:payload["email"],name:payload["name"]}}catch{return void 0}}decodeJwtPayload(token){try{const parts=token.split(".");if(parts.length!==3)return null;const payload=Buffer.from(parts[1],"base64url").toString("utf-8");return JSON.parse(payload)}catch{return null}}};var NotificationCollector=class{constructor(notifications){this.notifications=notifications}notifications;get received(){return[...this.notifications]}has(method){return this.notifications.some(n=>n.method===method)}async waitFor(method,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const found=this.notifications.find(n=>n.method===method);if(found)return found;await new Promise(r=>setTimeout(r,50))}throw new Error(`Timeout waiting for notification: ${method}`)}};var ProgressCollector=class{constructor(updates){this.updates=updates}updates;get all(){return[...this.updates]}async waitForComplete(timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const last=this.updates[this.updates.length-1];if(last&&last.total!==void 0&&last.progress>=last.total){return}await new Promise(r=>setTimeout(r,50))}throw new Error("Timeout waiting for progress to complete")}};var import_child_process=require("child_process");var import_net2=require("net");var import_utils=require("@frontmcp/utils");var TestClientError=class extends Error{constructor(message){super(message);this.name="TestClientError";Object.setPrototypeOf(this,new.target.prototype)}};var ServerStartError=class extends TestClientError{constructor(message,cause){super(message);this.cause=cause;this.name="ServerStartError";Object.setPrototypeOf(this,new.target.prototype)}cause};var import_net=require("net");var E2E_PORT_RANGES={"demo-e2e-public":{start:5e4,size:10},"demo-e2e-cache":{start:50010,size:10},"demo-e2e-config":{start:50020,size:10},"demo-e2e-direct":{start:50030,size:10},"demo-e2e-errors":{start:50040,size:10},"demo-e2e-hooks":{start:50050,size:10},"demo-e2e-multiapp":{start:50060,size:10},"demo-e2e-notifications":{start:50070,size:10},"demo-e2e-providers":{start:50080,size:10},"demo-e2e-standalone":{start:50090,size:10},"demo-e2e-orchestrated":{start:50100,size:10},"demo-e2e-transparent":{start:50110,size:10},"demo-e2e-cimd":{start:50120,size:10},"demo-e2e-remote-proxy":{start:50130,size:10},"demo-e2e-skills":{start:50200,size:10},"demo-e2e-remote":{start:50210,size:10},"demo-e2e-openapi":{start:50220,size:10},"demo-e2e-ui":{start:50230,size:10},"demo-e2e-codecall":{start:50240,size:10},"demo-e2e-remember":{start:50250,size:10},"demo-e2e-elicitation":{start:50260,size:10},"demo-e2e-agents":{start:50270,size:10},"demo-e2e-transport-recreation":{start:50280,size:10},"demo-e2e-jobs":{start:50290,size:10},"demo-e2e-redis":{start:50300,size:10},"demo-e2e-serverless":{start:50310,size:10},"demo-e2e-uipack":{start:50320,size:10},"demo-e2e-agent-adapters":{start:50330,size:10},"demo-e2e-guard":{start:50340,size:10},"demo-e2e-cli-exec":{start:50350,size:10},"demo-e2e-env-awareness":{start:50360,size:10},"demo-e2e-esm":{start:50370,size:10},"demo-e2e-feature-flags":{start:50380,size:10},"demo-e2e-resource-providers":{start:50390,size:10},"esm-package-server":{start:50400,size:10},"esm-package-server-hot-reload":{start:50410,size:10},"esm-package-server-cli":{start:50420,size:10},"demo-e2e-unix-socket":{start:50430,size:10},"demo-e2e-distributed":{start:50440,size:20},"demo-e2e-protocol-20260728":{start:50460,size:20},"demo-e2e-testing":{start:50480,size:20},"mock-oauth":{start:50900,size:10},"mock-api":{start:50910,size:10},"mock-cimd":{start:50920,size:10},default:{start:51e3,size:100}};var reservedPorts=new Map;var lockedPorts=new Set;var LOCK_MAX_AGE_MS=10*60*1e3;function lockDir(){try{const os=require("node:os");const path=require("node:path");return path.join(os.tmpdir(),"frontmcp-testing-ports")}catch{return void 0}}function pidIsAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function acquirePortLock(port){if(lockedPorts.has(port))return false;let fs;let file;try{fs=require("node:fs");const dir=lockDir();if(!dir)return true;fs.mkdirSync(dir,{recursive:true});file=require("node:path").join(dir,`${port}.lock`)}catch{return true}const payload=JSON.stringify({pid:process.pid,at:Date.now()});for(let attempt=0;attempt<2;attempt++){try{fs.writeFileSync(file,payload,{flag:"wx"});lockedPorts.add(port);return true}catch(error){if(error.code!=="EEXIST")return true;try{const held=JSON.parse(fs.readFileSync(file,"utf8"));const fresh=typeof held.at==="number"&&Date.now()-held.at<LOCK_MAX_AGE_MS;if(fresh&&typeof held.pid==="number"&&pidIsAlive(held.pid))return false;fs.unlinkSync(file)}catch{}}}return false}function releasePortLock(port){if(!lockedPorts.delete(port))return;try{const fs=require("node:fs");const dir=lockDir();if(dir)fs.unlinkSync(require("node:path").join(dir,`${port}.lock`))}catch{}}var projectPortIndex=new Map;function getPortRange(project){const key=project;if(key in E2E_PORT_RANGES){return E2E_PORT_RANGES[key]}return E2E_PORT_RANGES.default}async function reservePort(project,preferredPort){const range=getPortRange(project);const handle=port=>({port,releaseSocket:async()=>{await releasePort(port)},release:async()=>{await releasePort(port);releasePortLock(port)}});const wantsSpecificPort=preferredPort!==void 0&&Number.isInteger(preferredPort)&&preferredPort>0;if(wantsSpecificPort){const reservation=await tryReservePort(preferredPort,project);if(reservation){return handle(preferredPort)}console.warn(`[PortRegistry] Preferred port ${preferredPort} not available for ${project}, allocating from range`)}let index=projectPortIndex.get(project)??0;const maxAttempts=range.size;for(let attempt=0;attempt<maxAttempts;attempt++){const port=range.start+index%range.size;index=(index+1)%range.size;if(reservedPorts.has(port)||lockedPorts.has(port)){continue}const reservation=await tryReservePort(port,project);if(reservation){projectPortIndex.set(project,index);return handle(port)}}for(let port=51e3;port<52e3;port++){if(reservedPorts.has(port)||lockedPorts.has(port))continue;if(await tryReservePort(port,project)){return handle(port)}}throw new Error(`[PortRegistry] Could not reserve a port for ${project}. Range: ${range.start}-${range.start+range.size-1}. Currently reserved: ${Array.from(reservedPorts.keys()).join(", ")}`)}async function tryReservePort(port,project){if(!acquirePortLock(port)){return false}return new Promise(resolve=>{const server=(0,import_net.createServer)();server.once("error",()=>{releasePortLock(port);resolve(false)});server.listen(port,()=>{reservedPorts.set(port,{port,project,holder:server,reservedAt:Date.now()});resolve(true)})})}async function releasePort(port){const reservation=reservedPorts.get(port);if(!reservation){return}return new Promise(resolve=>{reservation.holder.close(()=>{reservedPorts.delete(port);resolve()})})}var SERVER_EXIT_TIMEOUT_MS=12e3;var DEBUG_SERVER=process.env["DEBUG_SERVER"]==="1"||process.env["DEBUG"]==="1";var TestServer=class _TestServer{process=null;options;_info;logs=[];portRelease=null;portReleaseSocket=null;constructor(options,port,portRelease,portReleaseSocket){this.options={port,project:options.project,command:options.command??"",cwd:options.cwd??process.cwd(),env:options.env??{},startupTimeout:options.startupTimeout??3e4,healthCheckPath:options.healthCheckPath??"/health",debug:options.debug??DEBUG_SERVER};this.portRelease=portRelease??null;this.portReleaseSocket=portReleaseSocket??portRelease??null;this._info={baseUrl:`http://localhost:${port}`,port}}static async start(options){const project=options.project??"default";const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const server=new _TestServer(options,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep2(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static async startNx(project,options={}){if(!/^[\w-]+$/.test(project)){throw new Error(`Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`)}const maxAttempts=3;for(let attempt=1;attempt<=maxAttempts;attempt++){const{port,release,releaseSocket}=await reservePort(project,options.port);const serverOptions={...options,port,project,command:`npx nx serve ${project} --port ${port}`,cwd:options.cwd??process.cwd()};const server=new _TestServer(serverOptions,port,release,releaseSocket);try{await server.startProcess();return server}catch(error){try{await server.stop()}catch(cleanupError){if(options.debug||DEBUG_SERVER){const msg=cleanupError instanceof Error?cleanupError.message:String(cleanupError);console.warn(`[TestServer] Cleanup failed after startup error: ${msg}`)}}const isEADDRINUSE=error instanceof Error&&(error.message.includes("EADDRINUSE")||server.getLogs().some(l=>l.includes("EADDRINUSE")));if(isEADDRINUSE&&attempt<maxAttempts){const delayMs=attempt*500;if(options.debug||DEBUG_SERVER){console.warn(`[TestServer] EADDRINUSE on port ${port}, retrying in ${delayMs}ms (attempt ${attempt}/${maxAttempts})`)}await sleep2(delayMs);continue}throw error}}throw new Error(`[TestServer] Failed to start after ${maxAttempts} attempts`)}static connect(baseUrl){const url=new URL(baseUrl);const port=parseInt(url.port,10)||(url.protocol==="https:"?443:80);const server=new _TestServer({command:"",port},port);server._info={baseUrl:baseUrl.replace(/\/$/,""),port};return server}get info(){return{...this._info}}async stop(){try{await this.stopProcess()}finally{if(this.portRelease){await this.portRelease();this.portRelease=null}this.portReleaseSocket=null}}async stopProcess(){if(this.process){this.log("Stopping server...");const serverPid=this._info.pid!==this._info.shellPid?this._info.pid:void 0;if(this.process.exitCode!==null||this.process.signalCode!==null){this.log(`Server already exited (code: ${this.process.exitCode}, signal: ${this.process.signalCode})`);this.process=null;if(serverPid!==void 0)signalIfRunning(serverPid,"SIGTERM");await this.waitForServerGone(serverPid);return}const pid=this.process.pid;try{if(pid!==void 0){process.kill(-pid,"SIGTERM")}else{this.process.kill("SIGTERM")}}catch{this.process.kill("SIGTERM")}const exitPromise=new Promise(resolve=>{if(this.process){this.process.once("exit",()=>resolve())}else{resolve()}});const killTimeout=setTimeout(()=>{if(this.process){this.log("Force killing server after timeout...");const killPid=this.process.pid;try{if(killPid!==void 0){process.kill(-killPid,"SIGKILL")}else{this.process.kill("SIGKILL")}}catch{this.process.kill("SIGKILL")}}},5e3);await exitPromise;clearTimeout(killTimeout);this.process=null;await this.waitForServerGone(serverPid);this.log("Server stopped")}}async waitForServerGone(serverPid){const deadline=Date.now()+SERVER_EXIT_TIMEOUT_MS;while(Date.now()<deadline){const serverRunning=serverPid!==void 0&&pidIsAlive(serverPid);if(!serverRunning&&!await acceptsConnections(this._info.port))return;await sleep2(100)}if(serverPid!==void 0&&pidIsAlive(serverPid)){this.log("Force killing server process after timeout...");signalIfRunning(serverPid,"SIGKILL")}}async waitForReady(timeout){const timeoutMs=timeout??this.options.startupTimeout;const deadline=Date.now()+timeoutMs;const checkInterval=100;while(Date.now()<deadline){try{const response=await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`,{method:"GET",signal:AbortSignal.timeout(1e3)});if(response.ok||response.status===404){this.log("Server is ready");return}}catch{}await sleep2(checkInterval)}throw new Error(`Server did not become ready within ${timeoutMs}ms`)}async restart(){await this.stopProcess();await this.startProcess()}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}async startProcess(){if(!this.options.command){await this.waitForReady();return}this.log(`Starting server: ${this.options.command}`);const env={...process.env,...this.options.env,PORT:String(this.options.port)};const runtimeEnv=withWorkspaceProtocolFallback(env,this.options.cwd);if(this.portReleaseSocket){await this.portReleaseSocket();this.portReleaseSocket=null;await sleep2(300)}this.process=(0,import_child_process.spawn)(this.options.command,[],{cwd:this.options.cwd,env:runtimeEnv,shell:true,detached:true,stdio:["pipe","pipe","pipe"]});this._info.pid=this.process.pid;this._info.shellPid=this.process.pid;let processExited=false;let exitCode=null;let exitError=null;this.process.stdout?.on("data",data=>{const text=data.toString();this.logs.push(text);if(this.options.debug){console.log("[SERVER]",text)}});this.process.stderr?.on("data",data=>{const text=data.toString();this.logs.push(`[ERROR] ${text}`);if(this.options.debug){console.error("[SERVER ERROR]",text)}});this.process.on("error",err=>{this.logs.push(`[SPAWN ERROR] ${err.message}`);exitError=err;if(this.options.debug){console.error("[SERVER SPAWN ERROR]",err)}});this.process.once("exit",code=>{processExited=true;exitCode=code;this.log(`Server process exited with code ${code}`)});try{await this.waitForReadyWithExitDetection(()=>{if(exitError){return{exited:true,error:exitError}}if(processExited){const allLogs=this.logs.join("\n");const errorLogs=this.logs.filter(l=>l.includes("[ERROR]")||l.toLowerCase().includes("error")).join("\n");return{exited:true,error:new ServerStartError(`Server process exited unexpectedly with code ${exitCode}.
3572
2
 
3573
3
  Command: ${this.options.command}
3574
4
  CWD: ${this.options.cwd}
3575
5
  Port: ${this.options.port}
3576
6
 
3577
7
  === Error Logs ===
3578
- ${errorLogs || "No error logs captured"}
8
+ ${errorLogs||"No error logs captured"}
3579
9
 
3580
10
  === Full Logs ===
3581
- ${allLogs || "No logs captured"}`
3582
- )
3583
- };
3584
- }
3585
- return { exited: false };
3586
- });
3587
- } catch (error) {
3588
- this.printLogsOnFailure("Server startup failed");
3589
- throw error;
3590
- }
3591
- }
3592
- /**
3593
- * Print server logs on failure for debugging
3594
- */
3595
- printLogsOnFailure(context) {
3596
- const allLogs = this.logs.join("\n");
3597
- if (allLogs) {
3598
- console.error(`
3599
- [TestServer] ${context}`);
3600
- console.error(`[TestServer] Command: ${this.options.command}`);
3601
- console.error(`[TestServer] Port: ${this.options.port}`);
3602
- console.error(`[TestServer] CWD: ${this.options.cwd}`);
3603
- console.error(`[TestServer] === Server Logs ===
3604
- ${allLogs}`);
3605
- console.error(`[TestServer] === End Logs ===
3606
- `);
3607
- }
3608
- }
3609
- /**
3610
- * Wait for server to be ready, but also detect early process exit
3611
- */
3612
- async waitForReadyWithExitDetection(checkExit) {
3613
- const timeoutMs = this.options.startupTimeout;
3614
- const deadline = Date.now() + timeoutMs;
3615
- const checkInterval = 100;
3616
- let lastHealthCheckError = null;
3617
- let healthCheckAttempts = 0;
3618
- this.log(`Waiting for server to be ready (timeout: ${timeoutMs}ms)...`);
3619
- while (Date.now() < deadline) {
3620
- const exitStatus = checkExit();
3621
- if (exitStatus.exited) {
3622
- throw exitStatus.error ?? new ServerStartError("Server process exited unexpectedly");
3623
- }
3624
- healthCheckAttempts++;
3625
- try {
3626
- const healthUrl = `${this._info.baseUrl}${this.options.healthCheckPath}`;
3627
- const response = await fetch(healthUrl, {
3628
- method: "GET",
3629
- signal: AbortSignal.timeout(1e3)
3630
- });
3631
- if (response.ok || response.status === 404) {
3632
- this.log(`Server is ready after ${healthCheckAttempts} health check attempts`);
3633
- const listeningPid = await findListeningPid(this.options.port);
3634
- if (listeningPid !== void 0) this._info.pid = listeningPid;
3635
- return;
3636
- }
3637
- lastHealthCheckError = `HTTP ${response.status}: ${response.statusText}`;
3638
- } catch (err) {
3639
- lastHealthCheckError = err instanceof Error ? err.message : String(err);
3640
- }
3641
- const elapsed = Date.now() - (deadline - timeoutMs);
3642
- if (elapsed > 0 && elapsed % 5e3 < checkInterval) {
3643
- this.log(
3644
- `Still waiting for server... (${Math.round(elapsed / 1e3)}s elapsed, last error: ${lastHealthCheckError})`
3645
- );
3646
- }
3647
- await sleep2(checkInterval);
3648
- }
3649
- const finalExitStatus = checkExit();
3650
- if (finalExitStatus.exited) {
3651
- throw finalExitStatus.error ?? new ServerStartError("Server process exited unexpectedly");
3652
- }
3653
- const allLogs = this.logs.join("\n");
3654
- throw new ServerStartError(
3655
- `Server did not become ready within ${timeoutMs}ms.
11
+ ${allLogs||"No logs captured"}`)}}return{exited:false}})}catch(error){this.printLogsOnFailure("Server startup failed");throw error}}printLogsOnFailure(context){const allLogs=this.logs.join("\n");if(allLogs){console.error(`
12
+ [TestServer] ${context}`);console.error(`[TestServer] Command: ${this.options.command}`);console.error(`[TestServer] Port: ${this.options.port}`);console.error(`[TestServer] CWD: ${this.options.cwd}`);console.error(`[TestServer] === Server Logs ===
13
+ ${allLogs}`);console.error(`[TestServer] === End Logs ===
14
+ `)}}async waitForReadyWithExitDetection(checkExit){const timeoutMs=this.options.startupTimeout;const deadline=Date.now()+timeoutMs;const checkInterval=100;let lastHealthCheckError=null;let healthCheckAttempts=0;this.log(`Waiting for server to be ready (timeout: ${timeoutMs}ms)...`);while(Date.now()<deadline){const exitStatus=checkExit();if(exitStatus.exited){throw exitStatus.error??new ServerStartError("Server process exited unexpectedly")}healthCheckAttempts++;try{const healthUrl=`${this._info.baseUrl}${this.options.healthCheckPath}`;const response=await fetch(healthUrl,{method:"GET",signal:AbortSignal.timeout(1e3)});if(response.ok||response.status===404){this.log(`Server is ready after ${healthCheckAttempts} health check attempts`);const listeningPid=await findListeningPid(this.options.port);if(listeningPid!==void 0)this._info.pid=listeningPid;return}lastHealthCheckError=`HTTP ${response.status}: ${response.statusText}`}catch(err){lastHealthCheckError=err instanceof Error?err.message:String(err)}const elapsed=Date.now()-(deadline-timeoutMs);if(elapsed>0&&elapsed%5e3<checkInterval){this.log(`Still waiting for server... (${Math.round(elapsed/1e3)}s elapsed, last error: ${lastHealthCheckError})`)}await sleep2(checkInterval)}const finalExitStatus=checkExit();if(finalExitStatus.exited){throw finalExitStatus.error??new ServerStartError("Server process exited unexpectedly")}const allLogs=this.logs.join("\n");throw new ServerStartError(`Server did not become ready within ${timeoutMs}ms.
3656
15
 
3657
16
  Command: ${this.options.command}
3658
17
  CWD: ${this.options.cwd}
3659
18
  Port: ${this.options.port}
3660
19
  Health check URL: ${this._info.baseUrl}${this.options.healthCheckPath}
3661
20
  Health check attempts: ${healthCheckAttempts}
3662
- Last health check error: ${lastHealthCheckError ?? "none"}
21
+ Last health check error: ${lastHealthCheckError??"none"}
3663
22
 
3664
23
  === Server Logs ===
3665
- ${allLogs || "No logs captured"}
3666
-
3667
- TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`
3668
- );
3669
- }
3670
- log(message) {
3671
- if (this.options.debug) {
3672
- console.log(`[TestServer] ${message}`);
3673
- }
3674
- }
3675
- };
3676
- function sleep2(ms) {
3677
- return new Promise((resolve) => setTimeout(resolve, ms));
3678
- }
3679
- function signalIfRunning(pid, signal) {
3680
- try {
3681
- process.kill(pid, signal);
3682
- } catch (error) {
3683
- if (error.code !== "ESRCH") throw error;
3684
- }
3685
- }
3686
- function acceptsConnections(port) {
3687
- return new Promise((resolve) => {
3688
- const socket = (0, import_net2.connect)(port, "127.0.0.1");
3689
- socket.once("connect", () => {
3690
- socket.destroy();
3691
- resolve(true);
3692
- });
3693
- socket.once("error", () => resolve(false));
3694
- });
3695
- }
3696
- function findListeningPid(port) {
3697
- if (process.platform === "win32") return Promise.resolve(void 0);
3698
- return new Promise((resolve) => {
3699
- (0, import_child_process.execFile)("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { timeout: 2e3 }, (error, stdout) => {
3700
- if (error) {
3701
- resolve(void 0);
3702
- return;
3703
- }
3704
- const pid = parseInt(String(stdout).split("\n")[0] ?? "", 10);
3705
- resolve(Number.isInteger(pid) && pid > 0 ? pid : void 0);
3706
- });
3707
- });
3708
- }
3709
- function withWorkspaceProtocolFallback(env, cwd) {
3710
- if (findInstalledProtocolPackageDir(cwd)) {
3711
- return env;
3712
- }
3713
- try {
3714
- const workspacePackageDir = findWorkspaceProtocolDir(cwd);
3715
- if (!workspacePackageDir) {
3716
- return env;
3717
- }
3718
- ensureWorkspaceProtocolLink(cwd, workspacePackageDir);
3719
- if (findInstalledProtocolPackageDir(cwd)) {
3720
- return env;
3721
- }
3722
- return withProtocolNodePathAlias(env, cwd, workspacePackageDir);
3723
- } catch (err) {
3724
- if (DEBUG_SERVER) {
3725
- console.error(
3726
- `[TestServer] Workspace protocol fallback failed: ${err instanceof Error ? err.message : String(err)}`
3727
- );
3728
- }
3729
- return env;
3730
- }
3731
- }
3732
- function ensureWorkspaceProtocolLink(cwd, workspacePackageDir) {
3733
- const fs = require("node:fs");
3734
- const path = require("node:path");
3735
- const nodeModulesDir = findWorkspaceNodeModulesDir(cwd);
3736
- if (!nodeModulesDir) {
3737
- return;
3738
- }
3739
- const scopeDir = path.join(nodeModulesDir, "@frontmcp");
3740
- const aliasPackageDir = path.join(scopeDir, "protocol");
3741
- if (fs.existsSync(aliasPackageDir)) {
3742
- return;
3743
- }
3744
- fs.mkdirSync(scopeDir, { recursive: true });
3745
- try {
3746
- fs.symlinkSync(workspacePackageDir, aliasPackageDir, process.platform === "win32" ? "junction" : "dir");
3747
- } catch (error) {
3748
- const err = error;
3749
- if (err.code !== "EEXIST") {
3750
- throw error;
3751
- }
3752
- }
3753
- }
3754
- function withProtocolNodePathAlias(env, cwd, workspacePackageDir) {
3755
- const fs = require("node:fs");
3756
- const os = require("node:os");
3757
- const path = require("node:path");
3758
- const aliasRoot = path.join(os.tmpdir(), "frontmcp-test-node-path", (0, import_utils.sha256Hex)(cwd).slice(0, 12));
3759
- const scopeDir = path.join(aliasRoot, "@frontmcp");
3760
- const aliasPackageDir = path.join(scopeDir, "protocol");
3761
- fs.mkdirSync(scopeDir, { recursive: true });
3762
- try {
3763
- if (!fs.existsSync(aliasPackageDir)) {
3764
- fs.symlinkSync(workspacePackageDir, aliasPackageDir, process.platform === "win32" ? "junction" : "dir");
3765
- }
3766
- } catch (error) {
3767
- const err = error;
3768
- if (err.code !== "EEXIST") throw error;
3769
- }
3770
- const existingNodePath = env["NODE_PATH"];
3771
- const nodePathEntries = [aliasRoot, ...existingNodePath ? existingNodePath.split(path.delimiter) : []].filter(
3772
- Boolean
3773
- );
3774
- return {
3775
- ...env,
3776
- NODE_PATH: [...new Set(nodePathEntries)].join(path.delimiter)
3777
- };
3778
- }
3779
- function findUp(startDir, testFn) {
3780
- const path = require("node:path");
3781
- let currentDir = startDir;
3782
- while (true) {
3783
- const result = testFn(currentDir);
3784
- if (result !== void 0) return result;
3785
- const parentDir = path.dirname(currentDir);
3786
- if (parentDir === currentDir) return void 0;
3787
- currentDir = parentDir;
3788
- }
3789
- }
3790
- function findWorkspaceProtocolDir(startDir) {
3791
- const fs = require("node:fs");
3792
- const path = require("node:path");
3793
- return findUp(startDir, (dir) => {
3794
- const candidate = path.join(dir, "libs", "protocol");
3795
- return fs.existsSync(path.join(candidate, "dist", "index.js")) ? candidate : void 0;
3796
- });
3797
- }
3798
- function findInstalledProtocolPackageDir(startDir) {
3799
- const fs = require("node:fs");
3800
- const path = require("node:path");
3801
- return findUp(startDir, (dir) => {
3802
- const candidate = path.join(dir, "node_modules", "@frontmcp", "protocol");
3803
- return fs.existsSync(path.join(candidate, "package.json")) ? candidate : void 0;
3804
- });
3805
- }
3806
- function findWorkspaceNodeModulesDir(startDir) {
3807
- const fs = require("node:fs");
3808
- const path = require("node:path");
3809
- return findUp(startDir, (dir) => {
3810
- const candidate = path.join(dir, "node_modules");
3811
- return fs.existsSync(candidate) ? candidate : void 0;
3812
- });
3813
- }
3814
-
3815
- // libs/testing/src/fixtures/gateway-token-binding.ts
3816
- var import_utils2 = require("@frontmcp/utils");
3817
- function gatewayTokenBinding(serverUrl, entryPath) {
3818
- const base = (0, import_utils2.trimTrailing)(serverUrl, "/");
3819
- const prefix = (0, import_utils2.trimSlashes)(entryPath ?? "");
3820
- const mcpUrl = prefix ? `${base}/${prefix}` : base;
3821
- return { issuer: mcpUrl, audience: mcpUrl };
3822
- }
24
+ ${allLogs||"No logs captured"}
3823
25
 
3824
- // libs/testing/src/fixtures/test-fixture.ts
3825
- var jestApi;
3826
- function jestGlobals() {
3827
- if (jestApi) return jestApi;
3828
- try {
3829
- const api = require("@jest/globals");
3830
- jestApi = {
3831
- describe: api["describe"],
3832
- beforeAll: api["beforeAll"],
3833
- beforeEach: api["beforeEach"],
3834
- afterEach: api["afterEach"],
3835
- afterAll: api["afterAll"],
3836
- it: api["it"]
3837
- };
3838
- return jestApi;
3839
- } catch (error) {
3840
- throw new Error(
3841
- `@frontmcp/testing fixtures ("test", "test.use", ...) can only be used inside a Jest test file: ${error instanceof Error ? error.message : String(error)}`,
3842
- { cause: error }
3843
- );
3844
- }
3845
- }
3846
- function newScope(parent) {
3847
- return {
3848
- skipped: parent?.skipped ?? false,
3849
- reason: parent?.reason,
3850
- config: {},
3851
- envs: [],
3852
- configured: false,
3853
- cleanupRegistered: false,
3854
- beforeEachHooks: [],
3855
- afterEachHooks: []
3856
- };
3857
- }
3858
- var scopes = [newScope()];
3859
- function currentScope() {
3860
- return scopes[scopes.length - 1];
3861
- }
3862
- var serverEntries = /* @__PURE__ */ new Map();
3863
- function resolveConfig(chain) {
3864
- const merged = {};
3865
- for (const scope of chain) {
3866
- Object.assign(merged, scope.config);
3867
- for (const env of scope.envs) merged.env = { ...merged.env, ...env };
3868
- }
3869
- return merged;
3870
- }
3871
- function ownerScopeOf(chain) {
3872
- for (let i = chain.length - 1; i > 0; i--) {
3873
- if (chain[i].configured) return chain[i];
3874
- }
3875
- return chain[0];
3876
- }
3877
- function serverKey(config) {
3878
- const env = Object.fromEntries(Object.entries(config.env ?? {}).sort(([a], [b]) => a.localeCompare(b)));
3879
- return JSON.stringify({
3880
- server: config.server,
3881
- baseUrl: config.baseUrl,
3882
- project: config.project,
3883
- port: config.port,
3884
- entryPath: config.entryPath,
3885
- startupTimeout: config.startupTimeout,
3886
- logLevel: config.logLevel,
3887
- auth: config.auth,
3888
- env
3889
- });
3890
- }
3891
- function serverEnv(config) {
3892
- const extra = {};
3893
- if (config.logLevel) extra["FRONTMCP_LOG_LEVEL"] = config.logLevel;
3894
- if (config.auth?.mode) extra["FRONTMCP_TEST_AUTH_MODE"] = config.auth.mode;
3895
- if (config.auth?.type) extra["FRONTMCP_TEST_AUTH_TYPE"] = config.auth.type;
3896
- if (Object.keys(extra).length === 0 && !config.env) return void 0;
3897
- return { ...extra, ...config.env };
3898
- }
3899
- async function startServerEntry(config, owner) {
3900
- let server;
3901
- let startedByUs = false;
3902
- if (config.baseUrl && !config.server) {
3903
- server = TestServer.connect(config.baseUrl);
3904
- } else if (config.server) {
3905
- const serverCommand = resolveServerCommand(config.server);
3906
- const isDebug = config.logLevel === "debug" || process.env["DEBUG"] === "1" || process.env["DEBUG_SERVER"] === "1";
3907
- if (isDebug) {
3908
- console.log(`[TestFixture] Starting server: ${serverCommand}`);
3909
- }
3910
- try {
3911
- server = await TestServer.start({
3912
- project: config.project,
3913
- port: config.port,
3914
- command: serverCommand,
3915
- env: serverEnv(config),
3916
- startupTimeout: config.startupTimeout ?? 3e4,
3917
- debug: isDebug
3918
- });
3919
- startedByUs = true;
3920
- if (isDebug) {
3921
- console.log(`[TestFixture] Server started at ${server.info.baseUrl}`);
3922
- }
3923
- } catch (error) {
3924
- const errMsg = error instanceof Error ? error.message : String(error);
3925
- throw new Error(
3926
- `Failed to start test server.
26
+ TIP: Set DEBUG_SERVER=1 or DEBUG=1 environment variable for verbose output`)}log(message){if(this.options.debug){console.log(`[TestServer] ${message}`)}}};function sleep2(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function signalIfRunning(pid,signal){try{process.kill(pid,signal)}catch(error){if(error.code!=="ESRCH")throw error}}function acceptsConnections(port){return new Promise(resolve=>{const socket=(0,import_net2.connect)(port,"127.0.0.1");socket.once("connect",()=>{socket.destroy();resolve(true)});socket.once("error",()=>resolve(false))})}function findListeningPid(port){if(process.platform==="win32")return Promise.resolve(void 0);return new Promise(resolve=>{(0,import_child_process.execFile)("lsof",["-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{timeout:2e3},(error,stdout)=>{if(error){resolve(void 0);return}const pid=parseInt(String(stdout).split("\n")[0]??"",10);resolve(Number.isInteger(pid)&&pid>0?pid:void 0)})})}function withWorkspaceProtocolFallback(env,cwd){if(findInstalledProtocolPackageDir(cwd)){return env}try{const workspacePackageDir=findWorkspaceProtocolDir(cwd);if(!workspacePackageDir){return env}ensureWorkspaceProtocolLink(cwd,workspacePackageDir);if(findInstalledProtocolPackageDir(cwd)){return env}return withProtocolNodePathAlias(env,cwd,workspacePackageDir)}catch(err){if(DEBUG_SERVER){console.error(`[TestServer] Workspace protocol fallback failed: ${err instanceof Error?err.message:String(err)}`)}return env}}function ensureWorkspaceProtocolLink(cwd,workspacePackageDir){const fs=require("node:fs");const path=require("node:path");const nodeModulesDir=findWorkspaceNodeModulesDir(cwd);if(!nodeModulesDir){return}const scopeDir=path.join(nodeModulesDir,"@frontmcp");const aliasPackageDir=path.join(scopeDir,"protocol");if(fs.existsSync(aliasPackageDir)){return}fs.mkdirSync(scopeDir,{recursive:true});try{fs.symlinkSync(workspacePackageDir,aliasPackageDir,process.platform==="win32"?"junction":"dir")}catch(error){const err=error;if(err.code!=="EEXIST"){throw error}}}function withProtocolNodePathAlias(env,cwd,workspacePackageDir){const fs=require("node:fs");const os=require("node:os");const path=require("node:path");const aliasRoot=path.join(os.tmpdir(),"frontmcp-test-node-path",(0,import_utils.sha256Hex)(cwd).slice(0,12));const scopeDir=path.join(aliasRoot,"@frontmcp");const aliasPackageDir=path.join(scopeDir,"protocol");fs.mkdirSync(scopeDir,{recursive:true});try{if(!fs.existsSync(aliasPackageDir)){fs.symlinkSync(workspacePackageDir,aliasPackageDir,process.platform==="win32"?"junction":"dir")}}catch(error){const err=error;if(err.code!=="EEXIST")throw error}const existingNodePath=env["NODE_PATH"];const nodePathEntries=[aliasRoot,...existingNodePath?existingNodePath.split(path.delimiter):[]].filter(Boolean);return{...env,NODE_PATH:[...new Set(nodePathEntries)].join(path.delimiter)}}function findUp(startDir,testFn){const path=require("node:path");let currentDir=startDir;while(true){const result=testFn(currentDir);if(result!==void 0)return result;const parentDir=path.dirname(currentDir);if(parentDir===currentDir)return void 0;currentDir=parentDir}}function findWorkspaceProtocolDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"libs","protocol");return fs.existsSync(path.join(candidate,"dist","index.js"))?candidate:void 0})}function findInstalledProtocolPackageDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules","@frontmcp","protocol");return fs.existsSync(path.join(candidate,"package.json"))?candidate:void 0})}function findWorkspaceNodeModulesDir(startDir){const fs=require("node:fs");const path=require("node:path");return findUp(startDir,dir=>{const candidate=path.join(dir,"node_modules");return fs.existsSync(candidate)?candidate:void 0})}var import_utils2=require("@frontmcp/utils");function gatewayTokenBinding(serverUrl,entryPath){const base=(0,import_utils2.trimTrailing)(serverUrl,"/");const prefix=(0,import_utils2.trimSlashes)(entryPath??"");const mcpUrl=prefix?`${base}/${prefix}`:base;return{issuer:mcpUrl,audience:mcpUrl}}var jestApi;function jestGlobals(){if(jestApi)return jestApi;try{const api=require("@jest/globals");jestApi={describe:api["describe"],beforeAll:api["beforeAll"],beforeEach:api["beforeEach"],afterEach:api["afterEach"],afterAll:api["afterAll"],it:api["it"]};return jestApi}catch(error){throw new Error(`@frontmcp/testing fixtures ("test", "test.use", ...) can only be used inside a Jest test file: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}function newScope(parent){return{skipped:parent?.skipped??false,reason:parent?.reason,config:{},envs:[],configured:false,cleanupRegistered:false,beforeEachHooks:[],afterEachHooks:[]}}var scopes=[newScope()];function currentScope(){return scopes[scopes.length-1]}var serverEntries=new Map;function resolveConfig(chain){const merged={};for(const scope of chain){Object.assign(merged,scope.config);for(const env of scope.envs)merged.env={...merged.env,...env}}return merged}function ownerScopeOf(chain){for(let i=chain.length-1;i>0;i--){if(chain[i].configured)return chain[i]}return chain[0]}function serverKey(config){const env=Object.fromEntries(Object.entries(config.env??{}).sort(([a],[b])=>a.localeCompare(b)));return JSON.stringify({server:config.server,baseUrl:config.baseUrl,project:config.project,port:config.port,entryPath:config.entryPath,startupTimeout:config.startupTimeout,logLevel:config.logLevel,auth:config.auth,env})}function serverEnv(config){const extra={};if(config.logLevel)extra["FRONTMCP_LOG_LEVEL"]=config.logLevel;if(config.auth?.mode)extra["FRONTMCP_TEST_AUTH_MODE"]=config.auth.mode;if(config.auth?.type)extra["FRONTMCP_TEST_AUTH_TYPE"]=config.auth.type;if(Object.keys(extra).length===0&&!config.env)return void 0;return{...extra,...config.env}}async function startServerEntry(config,owner){let server;let startedByUs=false;if(config.baseUrl&&!config.server){server=TestServer.connect(config.baseUrl)}else if(config.server){const serverCommand=resolveServerCommand(config.server);const isDebug=config.logLevel==="debug"||process.env["DEBUG"]==="1"||process.env["DEBUG_SERVER"]==="1";if(isDebug){console.log(`[TestFixture] Starting server: ${serverCommand}`)}try{server=await TestServer.start({project:config.project,port:config.port,command:serverCommand,env:serverEnv(config),startupTimeout:config.startupTimeout??3e4,debug:isDebug});startedByUs=true;if(isDebug){console.log(`[TestFixture] Server started at ${server.info.baseUrl}`)}}catch(error){const errMsg=error instanceof Error?error.message:String(error);throw new Error(`Failed to start test server.
3927
27
 
3928
28
  Server entry: ${config.server}
3929
- Project: ${config.project ?? "default"}
29
+ Project: ${config.project??"default"}
3930
30
  Command: ${serverCommand}
3931
31
 
3932
- Error: ${errMsg}`,
3933
- { cause: error }
3934
- );
3935
- }
3936
- } else {
3937
- throw new Error('test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option');
3938
- }
3939
- const sharedSecret = config.env?.["JWT_SECRET"];
3940
- const binding = sharedSecret ? gatewayTokenBinding(config.baseUrl ?? server.info.baseUrl, config.entryPath) : void 0;
3941
- const tokenFactory = new TestTokenFactory(sharedSecret ? { hmacSecret: sharedSecret, ...binding } : {});
3942
- return { server, startedByUs, tokenFactory, owner };
3943
- }
3944
- function acquireServer(chain) {
3945
- const config = resolveConfig(chain);
3946
- const key = serverKey(config);
3947
- let entry = serverEntries.get(key);
3948
- if (!entry) {
3949
- entry = startServerEntry(config, ownerScopeOf(chain));
3950
- serverEntries.set(key, entry);
3951
- entry.catch(() => serverEntries.delete(key));
3952
- }
3953
- return entry;
3954
- }
3955
- async function stopServers(owner) {
3956
- for (const [key, pending] of Array.from(serverEntries)) {
3957
- let entry;
3958
- try {
3959
- entry = await pending;
3960
- } catch {
3961
- serverEntries.delete(key);
3962
- continue;
3963
- }
3964
- if (owner && entry.owner !== owner) continue;
3965
- serverEntries.delete(key);
3966
- if (entry.startedByUs) {
3967
- await entry.server.stop();
3968
- }
3969
- }
3970
- }
3971
- var fixtureContexts = /* @__PURE__ */ new WeakMap();
3972
- async function buildFixtures(chain) {
3973
- const config = resolveConfig(chain);
3974
- const entry = await acquireServer(chain);
3975
- const { server, tokenFactory } = entry;
3976
- const publicMode = config.publicMode ?? config.auth?.mode === "public";
3977
- const clientConfig = { ...config, publicMode };
3978
- const clientInstance = McpTestClient.create({
3979
- baseUrl: resolveClientBaseUrl(server, clientConfig),
3980
- entryPath: clientConfig.entryPath,
3981
- transport: clientConfig.transport ?? "streamable-http",
3982
- publicMode
3983
- }).build();
3984
- try {
3985
- await clientInstance.connect();
3986
- } catch (err) {
3987
- const message = err instanceof Error ? err.message : String(err);
3988
- if (/\b401\b|unauthor/i.test(message)) {
3989
- console.warn(
3990
- `[TestFixture] MCP client could not connect anonymously \u2014 the server requires authentication (${message}). Tests using only the 'server'/'auth' fixtures are unaffected; tests using the 'mcp' fixture must supply a token.`
3991
- );
3992
- } else {
3993
- throw err;
3994
- }
3995
- }
3996
- const context = { extraClients: [] };
3997
- const fixtures = {
3998
- mcp: clientInstance,
3999
- auth: createAuthFixture(tokenFactory),
4000
- server: createServerFixture(server, clientConfig, clientInstance, context)
4001
- };
4002
- fixtureContexts.set(fixtures, context);
4003
- return fixtures;
4004
- }
4005
- async function createTestFixtures() {
4006
- return buildFixtures(scopes.slice());
4007
- }
4008
- async function initializeSharedResources() {
4009
- await acquireServer(scopes.slice());
4010
- }
4011
- async function cleanupTestFixtures(fixtures, testFailed = false) {
4012
- if (testFailed) {
4013
- const logs = fixtures.server.getLogs();
4014
- if (logs.length > 0) {
4015
- console.error("\n[TestFixture] === Server Logs (test failed) ===");
4016
- const recentLogs = logs.slice(-50);
4017
- if (logs.length > 50) {
4018
- console.error(`[TestFixture] (showing last 50 of ${logs.length} log entries)`);
4019
- }
4020
- console.error(recentLogs.join("\n"));
4021
- console.error("[TestFixture] === End Server Logs ===\n");
4022
- }
4023
- }
4024
- const extras = fixtureContexts.get(fixtures)?.extraClients ?? [];
4025
- for (const client of extras) {
4026
- if (client.isConnected()) {
4027
- await client.disconnect().catch(() => void 0);
4028
- }
4029
- }
4030
- if (fixtures.mcp.isConnected()) {
4031
- await fixtures.mcp.disconnect();
4032
- }
4033
- }
4034
- async function cleanupSharedResources() {
4035
- await stopServers();
4036
- }
4037
- function resolveClientBaseUrl(server, config) {
4038
- return config.baseUrl ?? server.info.baseUrl;
4039
- }
4040
- function createAuthFixture(factory) {
4041
- const users = {
4042
- admin: {
4043
- sub: "admin-001",
4044
- scopes: ["admin:*", "read", "write", "delete"],
4045
- email: "admin@test.local",
4046
- name: "Test Admin"
4047
- },
4048
- user: {
4049
- sub: "user-001",
4050
- scopes: ["read", "write"],
4051
- email: "user@test.local",
4052
- name: "Test User"
4053
- },
4054
- readOnly: {
4055
- sub: "readonly-001",
4056
- scopes: ["read"],
4057
- email: "readonly@test.local",
4058
- name: "Read Only User"
4059
- }
4060
- };
4061
- return {
4062
- createToken: (opts) => factory.createTestToken({
4063
- sub: opts.sub,
4064
- scopes: opts.scopes,
4065
- claims: {
4066
- email: opts.email,
4067
- name: opts.name,
4068
- ...opts.claims
4069
- },
4070
- exp: opts.expiresIn
4071
- }),
4072
- createExpiredToken: (opts) => factory.createExpiredToken(opts),
4073
- createInvalidToken: (opts) => factory.createTokenWithInvalidSignature(opts),
4074
- users: {
4075
- admin: users["admin"],
4076
- user: users["user"],
4077
- readOnly: users["readOnly"]
4078
- },
4079
- getJwks: () => factory.getPublicJwks(),
4080
- getIssuer: () => factory.getIssuer(),
4081
- getAudience: () => factory.getAudience()
4082
- };
4083
- }
4084
- function createServerFixture(server, config, mcp, context) {
4085
- return {
4086
- // Live view: `pid` is filled in once the server is listening and follows restarts
4087
- get info() {
4088
- return server.info;
4089
- },
4090
- createClient: async (opts) => {
4091
- const client = await McpTestClient.create({
4092
- baseUrl: resolveClientBaseUrl(server, config),
4093
- entryPath: opts?.entryPath ?? config.entryPath,
4094
- transport: opts?.transport ?? "streamable-http",
4095
- auth: opts?.token ? { token: opts.token } : void 0,
4096
- clientInfo: opts?.clientInfo,
4097
- publicMode: config.publicMode
4098
- }).buildAndConnect();
4099
- context.extraClients.push(client);
4100
- return client;
4101
- },
4102
- createClientBuilder: () => {
4103
- const builder = new McpTestClientBuilder({
4104
- baseUrl: resolveClientBaseUrl(server, config),
4105
- entryPath: config.entryPath,
4106
- publicMode: config.publicMode
4107
- });
4108
- return builder;
4109
- },
4110
- restart: async () => {
4111
- const reconnect = [mcp, ...context.extraClients].filter((client) => client.isConnected());
4112
- await server.restart();
4113
- for (const client of reconnect) {
4114
- await client.reconnect();
4115
- }
4116
- },
4117
- getLogs: () => server.getLogs(),
4118
- clearLogs: () => server.clearLogs()
4119
- };
4120
- }
4121
- function resolveServerCommand(server) {
4122
- if (server.includes(" ")) {
4123
- return server;
4124
- }
4125
- return `npx tsx ${server}`;
4126
- }
4127
- function runWithFixtures(fn, chain) {
4128
- return async (...extra) => {
4129
- const fixtures = await buildFixtures(chain);
4130
- let failure;
4131
- try {
4132
- for (const scope of chain) {
4133
- for (const hook of scope.beforeEachHooks) await hook(fixtures);
4134
- }
4135
- await fn(fixtures, ...extra);
4136
- } catch (error) {
4137
- failure = { error };
4138
- }
4139
- try {
4140
- await runAfterEachHooks(chain, fixtures);
4141
- } catch (error) {
4142
- failure ??= { error };
4143
- }
4144
- await cleanupTestFixtures(fixtures, failure !== void 0);
4145
- if (failure) throw failure.error;
4146
- };
4147
- }
4148
- async function runAfterEachHooks(chain, fixtures) {
4149
- let firstError;
4150
- let failed = false;
4151
- for (let i = chain.length - 1; i >= 0; i--) {
4152
- for (const hook of chain[i].afterEachHooks) {
4153
- try {
4154
- await hook(fixtures);
4155
- } catch (error) {
4156
- if (!failed) firstError = error;
4157
- failed = true;
4158
- }
4159
- }
4160
- }
4161
- if (failed) throw firstError;
4162
- }
4163
- function skipTitle(name, scope) {
4164
- return scope.reason ? `${name} (skipped: ${scope.reason})` : name;
4165
- }
4166
- function testWithFixtures(name, fn) {
4167
- const chain = scopes.slice();
4168
- const scope = currentScope();
4169
- if (scope.skipped) {
4170
- jestGlobals().it.skip(skipTitle(name, scope), runWithFixtures(fn, chain));
4171
- return;
4172
- }
4173
- jestGlobals().it(name, runWithFixtures(fn, chain));
4174
- }
4175
- function use(config) {
4176
- const scope = currentScope();
4177
- const { env, ...rest } = config;
4178
- scope.config = { ...scope.config, ...rest };
4179
- if (env) scope.envs.push(env);
4180
- scope.configured = true;
4181
- if (!scope.cleanupRegistered) {
4182
- scope.cleanupRegistered = true;
4183
- jestGlobals().afterAll(async () => {
4184
- await stopServers(scope === scopes[0] ? void 0 : scope);
4185
- });
4186
- }
4187
- }
4188
- function skip(nameOrCondition, fnOrReason) {
4189
- if (typeof nameOrCondition === "boolean") {
4190
- if (nameOrCondition) {
4191
- const scope = currentScope();
4192
- scope.skipped = true;
4193
- scope.reason = typeof fnOrReason === "string" ? fnOrReason : void 0;
4194
- }
4195
- return;
4196
- }
4197
- if (typeof fnOrReason !== "function") {
4198
- throw new TypeError(
4199
- `test.skip expects either (name: string, fn) or (condition: boolean, reason?: string); received (${typeof nameOrCondition}, ${typeof fnOrReason}).`
4200
- );
4201
- }
4202
- jestGlobals().it.skip(nameOrCondition, runWithFixtures(fnOrReason, scopes.slice()));
4203
- }
4204
- function only(name, fn) {
4205
- const scope = currentScope();
4206
- if (scope.skipped) {
4207
- jestGlobals().it.skip(skipTitle(name, scope), runWithFixtures(fn, scopes.slice()));
4208
- return;
4209
- }
4210
- jestGlobals().it.only(name, runWithFixtures(fn, scopes.slice()));
4211
- }
4212
- function todo(name) {
4213
- jestGlobals().it.todo(name);
4214
- }
4215
- function each(table, ...tagged) {
4216
- const chain = scopes.slice();
4217
- const register = jestGlobals().it.each(table, ...tagged);
4218
- return (name, fn) => {
4219
- const scope = currentScope();
4220
- if (scope.skipped) {
4221
- const skipRegister = jestGlobals().it.skip.each(table, ...tagged);
4222
- skipRegister(skipTitle(name, scope), runWithFixtures(fn, chain));
4223
- return;
4224
- }
4225
- register(name, runWithFixtures(fn, chain));
4226
- };
4227
- }
4228
- function withScope(fn) {
4229
- return (...args) => {
4230
- scopes.push(newScope(currentScope()));
4231
- try {
4232
- fn(...args);
4233
- } finally {
4234
- scopes.pop();
4235
- }
4236
- };
4237
- }
4238
- function scopedRegister(pick) {
4239
- return (name, fn, timeout) => {
4240
- pick()(name, withScope(fn), timeout);
4241
- };
4242
- }
4243
- function scopedEach(pick) {
4244
- return (...eachArgs) => (name, fn, timeout) => {
4245
- const register = pick()(...eachArgs);
4246
- register(name, withScope(fn), timeout);
4247
- };
4248
- }
4249
- var describeWithScope = Object.assign(
4250
- scopedRegister(() => jestGlobals().describe),
4251
- {
4252
- // `describe.skip` still evaluates its callback during collection, so it needs a scope too
4253
- only: Object.assign(
4254
- scopedRegister(() => jestGlobals().describe.only),
4255
- {
4256
- each: scopedEach(() => jestGlobals().describe.only.each)
4257
- }
4258
- ),
4259
- skip: Object.assign(
4260
- scopedRegister(() => jestGlobals().describe.skip),
4261
- {
4262
- each: scopedEach(() => jestGlobals().describe.skip.each)
4263
- }
4264
- ),
4265
- each: scopedEach(() => jestGlobals().describe.each)
4266
- }
4267
- );
4268
- function eachHook(kind) {
4269
- return (fn, timeout) => {
4270
- if (typeof fn === "function" && fn.length > 0) {
4271
- const scope = currentScope();
4272
- (kind === "beforeEach" ? scope.beforeEachHooks : scope.afterEachHooks).push(fn);
4273
- return;
4274
- }
4275
- jestGlobals()[kind](fn, timeout);
4276
- };
4277
- }
4278
- var test = testWithFixtures;
4279
- test.use = use;
4280
- test.describe = describeWithScope;
4281
- test.beforeAll = ((...args) => jestGlobals().beforeAll(...args));
4282
- test.beforeEach = eachHook("beforeEach");
4283
- test.afterEach = eachHook("afterEach");
4284
- test.afterAll = ((...args) => jestGlobals().afterAll(...args));
4285
- test.skip = skip;
4286
- test.only = only;
4287
- test.todo = todo;
4288
- test.each = each;
4289
- // Annotate the CommonJS export names for ESM import in node:
4290
- 0 && (module.exports = {
4291
- cleanupSharedResources,
4292
- cleanupTestFixtures,
4293
- createTestFixtures,
4294
- initializeSharedResources,
4295
- test
4296
- });
32
+ Error: ${errMsg}`,{cause:error})}}else{throw new Error('test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option')}const sharedSecret=config.env?.["JWT_SECRET"];const binding=sharedSecret?gatewayTokenBinding(config.baseUrl??server.info.baseUrl,config.entryPath):void 0;const tokenFactory=new TestTokenFactory(sharedSecret?{hmacSecret:sharedSecret,...binding}:{});return{server,startedByUs,tokenFactory,owner}}function acquireServer(chain){const config=resolveConfig(chain);const key=serverKey(config);let entry=serverEntries.get(key);if(!entry){entry=startServerEntry(config,ownerScopeOf(chain));serverEntries.set(key,entry);entry.catch(()=>serverEntries.delete(key))}return entry}async function stopServers(owner){for(const[key,pending]of Array.from(serverEntries)){let entry;try{entry=await pending}catch{serverEntries.delete(key);continue}if(owner&&entry.owner!==owner)continue;serverEntries.delete(key);if(entry.startedByUs){await entry.server.stop()}}}var fixtureContexts=new WeakMap;async function buildFixtures(chain){const config=resolveConfig(chain);const entry=await acquireServer(chain);const{server,tokenFactory}=entry;const publicMode=config.publicMode??config.auth?.mode==="public";const clientConfig={...config,publicMode};const clientInstance=McpTestClient.create({baseUrl:resolveClientBaseUrl(server,clientConfig),entryPath:clientConfig.entryPath,transport:clientConfig.transport??"streamable-http",publicMode}).build();try{await clientInstance.connect()}catch(err){const message=err instanceof Error?err.message:String(err);if(/\b401\b|unauthor/i.test(message)){console.warn(`[TestFixture] MCP client could not connect anonymously \u2014 the server requires authentication (${message}). Tests using only the 'server'/'auth' fixtures are unaffected; tests using the 'mcp' fixture must supply a token.`)}else{throw err}}const context={extraClients:[]};const fixtures={mcp:clientInstance,auth:createAuthFixture(tokenFactory),server:createServerFixture(server,clientConfig,clientInstance,context)};fixtureContexts.set(fixtures,context);return fixtures}async function createTestFixtures(){return buildFixtures(scopes.slice())}async function initializeSharedResources(){await acquireServer(scopes.slice())}async function cleanupTestFixtures(fixtures,testFailed=false){if(testFailed){const logs=fixtures.server.getLogs();if(logs.length>0){console.error("\n[TestFixture] === Server Logs (test failed) ===");const recentLogs=logs.slice(-50);if(logs.length>50){console.error(`[TestFixture] (showing last 50 of ${logs.length} log entries)`)}console.error(recentLogs.join("\n"));console.error("[TestFixture] === End Server Logs ===\n")}}const extras=fixtureContexts.get(fixtures)?.extraClients??[];for(const client of extras){if(client.isConnected()){await client.disconnect().catch(()=>void 0)}}if(fixtures.mcp.isConnected()){await fixtures.mcp.disconnect()}}async function cleanupSharedResources(){await stopServers()}function resolveClientBaseUrl(server,config){return config.baseUrl??server.info.baseUrl}function createAuthFixture(factory){const users={admin:{sub:"admin-001",scopes:["admin:*","read","write","delete"],email:"admin@test.local",name:"Test Admin"},user:{sub:"user-001",scopes:["read","write"],email:"user@test.local",name:"Test User"},readOnly:{sub:"readonly-001",scopes:["read"],email:"readonly@test.local",name:"Read Only User"}};return{createToken:opts=>factory.createTestToken({sub:opts.sub,scopes:opts.scopes,claims:{email:opts.email,name:opts.name,...opts.claims},exp:opts.expiresIn}),createExpiredToken:opts=>factory.createExpiredToken(opts),createInvalidToken:opts=>factory.createTokenWithInvalidSignature(opts),users:{admin:users["admin"],user:users["user"],readOnly:users["readOnly"]},getJwks:()=>factory.getPublicJwks(),getIssuer:()=>factory.getIssuer(),getAudience:()=>factory.getAudience()}}function createServerFixture(server,config,mcp,context){return{get info(){return server.info},createClient:async opts=>{const client=await McpTestClient.create({baseUrl:resolveClientBaseUrl(server,config),entryPath:opts?.entryPath??config.entryPath,transport:opts?.transport??"streamable-http",auth:opts?.token?{token:opts.token}:void 0,clientInfo:opts?.clientInfo,publicMode:config.publicMode}).buildAndConnect();context.extraClients.push(client);return client},createClientBuilder:()=>{const builder=new McpTestClientBuilder({baseUrl:resolveClientBaseUrl(server,config),entryPath:config.entryPath,publicMode:config.publicMode});return builder},restart:async()=>{const reconnect=[mcp,...context.extraClients].filter(client=>client.isConnected());await server.restart();for(const client of reconnect){await client.reconnect()}},getLogs:()=>server.getLogs(),clearLogs:()=>server.clearLogs()}}function resolveServerCommand(server){if(server.includes(" ")){return server}return`npx tsx ${server}`}function runWithFixtures(fn,chain){return async(...extra)=>{const fixtures=await buildFixtures(chain);let failure;try{for(const scope of chain){for(const hook of scope.beforeEachHooks)await hook(fixtures)}await fn(fixtures,...extra)}catch(error){failure={error}}try{await runAfterEachHooks(chain,fixtures)}catch(error){failure??={error}}await cleanupTestFixtures(fixtures,failure!==void 0);if(failure)throw failure.error}}async function runAfterEachHooks(chain,fixtures){let firstError;let failed=false;for(let i=chain.length-1;i>=0;i--){for(const hook of chain[i].afterEachHooks){try{await hook(fixtures)}catch(error){if(!failed)firstError=error;failed=true}}}if(failed)throw firstError}function skipTitle(name,scope){return scope.reason?`${name} (skipped: ${scope.reason})`:name}function testWithFixtures(name,fn){const chain=scopes.slice();const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,chain));return}jestGlobals().it(name,runWithFixtures(fn,chain))}function use(config){const scope=currentScope();const{env,...rest}=config;scope.config={...scope.config,...rest};if(env)scope.envs.push(env);scope.configured=true;if(!scope.cleanupRegistered){scope.cleanupRegistered=true;jestGlobals().afterAll(async()=>{await stopServers(scope===scopes[0]?void 0:scope)})}}function skip(nameOrCondition,fnOrReason){if(typeof nameOrCondition==="boolean"){if(nameOrCondition){const scope=currentScope();scope.skipped=true;scope.reason=typeof fnOrReason==="string"?fnOrReason:void 0}return}if(typeof fnOrReason!=="function"){throw new TypeError(`test.skip expects either (name: string, fn) or (condition: boolean, reason?: string); received (${typeof nameOrCondition}, ${typeof fnOrReason}).`)}jestGlobals().it.skip(nameOrCondition,runWithFixtures(fnOrReason,scopes.slice()))}function only(name,fn){const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,scopes.slice()));return}jestGlobals().it.only(name,runWithFixtures(fn,scopes.slice()))}function todo(name){jestGlobals().it.todo(name)}function each(table,...tagged){const chain=scopes.slice();const register=jestGlobals().it.each(table,...tagged);return(name,fn)=>{const scope=currentScope();if(scope.skipped){const skipRegister=jestGlobals().it.skip.each(table,...tagged);skipRegister(skipTitle(name,scope),runWithFixtures(fn,chain));return}register(name,runWithFixtures(fn,chain))}}function withScope(fn){return(...args)=>{scopes.push(newScope(currentScope()));try{fn(...args)}finally{scopes.pop()}}}function scopedRegister(pick){return(name,fn,timeout)=>{pick()(name,withScope(fn),timeout)}}function scopedEach(pick){return(...eachArgs)=>(name,fn,timeout)=>{const register=pick()(...eachArgs);register(name,withScope(fn),timeout)}}var describeWithScope=Object.assign(scopedRegister(()=>jestGlobals().describe),{only:Object.assign(scopedRegister(()=>jestGlobals().describe.only),{each:scopedEach(()=>jestGlobals().describe.only.each)}),skip:Object.assign(scopedRegister(()=>jestGlobals().describe.skip),{each:scopedEach(()=>jestGlobals().describe.skip.each)}),each:scopedEach(()=>jestGlobals().describe.each)});function eachHook(kind){return(fn,timeout)=>{if(typeof fn==="function"&&fn.length>0){const scope=currentScope();(kind==="beforeEach"?scope.beforeEachHooks:scope.afterEachHooks).push(fn);return}jestGlobals()[kind](fn,timeout)}}var test=testWithFixtures;test.use=use;test.describe=describeWithScope;test.beforeAll=((...args)=>jestGlobals().beforeAll(...args));test.beforeEach=eachHook("beforeEach");test.afterEach=eachHook("afterEach");test.afterAll=((...args)=>jestGlobals().afterAll(...args));test.skip=skip;test.only=only;test.todo=todo;test.each=each;0&&(module.exports={cleanupSharedResources,cleanupTestFixtures,createTestFixtures,initializeSharedResources,test});