@frontmcp/testing 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/esm/fixtures/index.mjs +2377 -0
  2. package/esm/index.mjs +4768 -0
  3. package/esm/matchers/index.mjs +646 -0
  4. package/esm/package.json +122 -0
  5. package/esm/playwright/index.mjs +19 -0
  6. package/esm/setup.mjs +680 -0
  7. package/fixtures/index.js +2418 -0
  8. package/index.js +4866 -0
  9. package/jest-preset.js +3 -3
  10. package/matchers/index.js +673 -0
  11. package/package.json +51 -23
  12. package/playwright/index.js +46 -0
  13. package/setup.js +651 -0
  14. package/src/assertions/index.js +0 -18
  15. package/src/assertions/index.js.map +0 -1
  16. package/src/assertions/mcp-assertions.js +0 -220
  17. package/src/assertions/mcp-assertions.js.map +0 -1
  18. package/src/auth/auth-headers.js +0 -62
  19. package/src/auth/auth-headers.js.map +0 -1
  20. package/src/auth/index.js +0 -15
  21. package/src/auth/index.js.map +0 -1
  22. package/src/auth/mock-api-server.js +0 -200
  23. package/src/auth/mock-api-server.js.map +0 -1
  24. package/src/auth/mock-oauth-server.js +0 -253
  25. package/src/auth/mock-oauth-server.js.map +0 -1
  26. package/src/auth/token-factory.js +0 -181
  27. package/src/auth/token-factory.js.map +0 -1
  28. package/src/auth/user-fixtures.js +0 -92
  29. package/src/auth/user-fixtures.js.map +0 -1
  30. package/src/client/index.js +0 -12
  31. package/src/client/index.js.map +0 -1
  32. package/src/client/mcp-test-client.builder.js +0 -163
  33. package/src/client/mcp-test-client.builder.js.map +0 -1
  34. package/src/client/mcp-test-client.js +0 -937
  35. package/src/client/mcp-test-client.js.map +0 -1
  36. package/src/client/mcp-test-client.types.js +0 -16
  37. package/src/client/mcp-test-client.types.js.map +0 -1
  38. package/src/errors/index.js +0 -85
  39. package/src/errors/index.js.map +0 -1
  40. package/src/example-tools/index.js +0 -40
  41. package/src/example-tools/index.js.map +0 -1
  42. package/src/example-tools/tool-configs.js +0 -222
  43. package/src/example-tools/tool-configs.js.map +0 -1
  44. package/src/expect.js +0 -31
  45. package/src/expect.js.map +0 -1
  46. package/src/fixtures/fixture-types.js +0 -7
  47. package/src/fixtures/fixture-types.js.map +0 -1
  48. package/src/fixtures/index.js +0 -16
  49. package/src/fixtures/index.js.map +0 -1
  50. package/src/fixtures/test-fixture.js +0 -311
  51. package/src/fixtures/test-fixture.js.map +0 -1
  52. package/src/http-mock/http-mock.js +0 -544
  53. package/src/http-mock/http-mock.js.map +0 -1
  54. package/src/http-mock/http-mock.types.js +0 -10
  55. package/src/http-mock/http-mock.types.js.map +0 -1
  56. package/src/http-mock/index.js +0 -11
  57. package/src/http-mock/index.js.map +0 -1
  58. package/src/index.js +0 -167
  59. package/src/index.js.map +0 -1
  60. package/src/interceptor/index.js +0 -15
  61. package/src/interceptor/index.js.map +0 -1
  62. package/src/interceptor/interceptor-chain.js +0 -207
  63. package/src/interceptor/interceptor-chain.js.map +0 -1
  64. package/src/interceptor/interceptor.types.js +0 -7
  65. package/src/interceptor/interceptor.types.js.map +0 -1
  66. package/src/interceptor/mock-registry.js +0 -189
  67. package/src/interceptor/mock-registry.js.map +0 -1
  68. package/src/matchers/index.js +0 -12
  69. package/src/matchers/index.js.map +0 -1
  70. package/src/matchers/matcher-types.js +0 -10
  71. package/src/matchers/matcher-types.js.map +0 -1
  72. package/src/matchers/mcp-matchers.js +0 -395
  73. package/src/matchers/mcp-matchers.js.map +0 -1
  74. package/src/platform/index.js +0 -47
  75. package/src/platform/index.js.map +0 -1
  76. package/src/platform/platform-client-info.js +0 -155
  77. package/src/platform/platform-client-info.js.map +0 -1
  78. package/src/platform/platform-types.js +0 -110
  79. package/src/platform/platform-types.js.map +0 -1
  80. package/src/playwright/index.js +0 -49
  81. package/src/playwright/index.js.map +0 -1
  82. package/src/server/index.js +0 -10
  83. package/src/server/index.js.map +0 -1
  84. package/src/server/test-server.js +0 -341
  85. package/src/server/test-server.js.map +0 -1
  86. package/src/setup.js +0 -30
  87. package/src/setup.js.map +0 -1
  88. package/src/transport/index.js +0 -10
  89. package/src/transport/index.js.map +0 -1
  90. package/src/transport/streamable-http.transport.js +0 -438
  91. package/src/transport/streamable-http.transport.js.map +0 -1
  92. package/src/transport/transport.interface.js +0 -7
  93. package/src/transport/transport.interface.js.map +0 -1
  94. package/src/ui/index.js +0 -23
  95. package/src/ui/index.js.map +0 -1
  96. package/src/ui/ui-assertions.js +0 -367
  97. package/src/ui/ui-assertions.js.map +0 -1
  98. package/src/ui/ui-matchers.js +0 -493
  99. package/src/ui/ui-matchers.js.map +0 -1
  100. /package/{src/assertions → assertions}/index.d.ts +0 -0
  101. /package/{src/assertions → assertions}/mcp-assertions.d.ts +0 -0
  102. /package/{src/auth → auth}/auth-headers.d.ts +0 -0
  103. /package/{src/auth → auth}/index.d.ts +0 -0
  104. /package/{src/auth → auth}/mock-api-server.d.ts +0 -0
  105. /package/{src/auth → auth}/mock-oauth-server.d.ts +0 -0
  106. /package/{src/auth → auth}/token-factory.d.ts +0 -0
  107. /package/{src/auth → auth}/user-fixtures.d.ts +0 -0
  108. /package/{src/client → client}/index.d.ts +0 -0
  109. /package/{src/client → client}/mcp-test-client.builder.d.ts +0 -0
  110. /package/{src/client → client}/mcp-test-client.d.ts +0 -0
  111. /package/{src/client → client}/mcp-test-client.types.d.ts +0 -0
  112. /package/{src/errors → errors}/index.d.ts +0 -0
  113. /package/{src/example-tools → example-tools}/index.d.ts +0 -0
  114. /package/{src/example-tools → example-tools}/tool-configs.d.ts +0 -0
  115. /package/{src/expect.d.ts → expect.d.ts} +0 -0
  116. /package/{src/fixtures → fixtures}/fixture-types.d.ts +0 -0
  117. /package/{src/fixtures → fixtures}/index.d.ts +0 -0
  118. /package/{src/fixtures → fixtures}/test-fixture.d.ts +0 -0
  119. /package/{src/http-mock → http-mock}/http-mock.d.ts +0 -0
  120. /package/{src/http-mock → http-mock}/http-mock.types.d.ts +0 -0
  121. /package/{src/http-mock → http-mock}/index.d.ts +0 -0
  122. /package/{src/index.d.ts → index.d.ts} +0 -0
  123. /package/{src/interceptor → interceptor}/index.d.ts +0 -0
  124. /package/{src/interceptor → interceptor}/interceptor-chain.d.ts +0 -0
  125. /package/{src/interceptor → interceptor}/interceptor.types.d.ts +0 -0
  126. /package/{src/interceptor → interceptor}/mock-registry.d.ts +0 -0
  127. /package/{src/matchers → matchers}/index.d.ts +0 -0
  128. /package/{src/matchers → matchers}/matcher-types.d.ts +0 -0
  129. /package/{src/matchers → matchers}/mcp-matchers.d.ts +0 -0
  130. /package/{src/platform → platform}/index.d.ts +0 -0
  131. /package/{src/platform → platform}/platform-client-info.d.ts +0 -0
  132. /package/{src/platform → platform}/platform-types.d.ts +0 -0
  133. /package/{src/playwright → playwright}/index.d.ts +0 -0
  134. /package/{src/server → server}/index.d.ts +0 -0
  135. /package/{src/server → server}/test-server.d.ts +0 -0
  136. /package/{src/setup.d.ts → setup.d.ts} +0 -0
  137. /package/{src/transport → transport}/index.d.ts +0 -0
  138. /package/{src/transport → transport}/streamable-http.transport.d.ts +0 -0
  139. /package/{src/transport → transport}/transport.interface.d.ts +0 -0
  140. /package/{src/ui → ui}/index.d.ts +0 -0
  141. /package/{src/ui → ui}/ui-assertions.d.ts +0 -0
  142. /package/{src/ui → ui}/ui-matchers.d.ts +0 -0
@@ -0,0 +1,2377 @@
1
+ // libs/testing/src/platform/platform-client-info.ts
2
+ var MCP_APPS_EXTENSION_KEY = "io.modelcontextprotocol/ui";
3
+ function getPlatformClientInfo(platform) {
4
+ switch (platform) {
5
+ case "openai":
6
+ return {
7
+ name: "ChatGPT",
8
+ version: "1.0"
9
+ };
10
+ case "ext-apps":
11
+ return {
12
+ name: "mcp-ext-apps",
13
+ version: "1.0"
14
+ };
15
+ case "claude":
16
+ return {
17
+ name: "claude-desktop",
18
+ version: "1.0"
19
+ };
20
+ case "cursor":
21
+ return {
22
+ name: "cursor",
23
+ version: "1.0"
24
+ };
25
+ case "continue":
26
+ return {
27
+ name: "continue",
28
+ version: "1.0"
29
+ };
30
+ case "cody":
31
+ return {
32
+ name: "cody",
33
+ version: "1.0"
34
+ };
35
+ case "gemini":
36
+ return {
37
+ name: "gemini",
38
+ version: "1.0"
39
+ };
40
+ case "generic-mcp":
41
+ return {
42
+ name: "generic-mcp-client",
43
+ version: "1.0"
44
+ };
45
+ case "unknown":
46
+ default:
47
+ return {
48
+ name: "mcp-test-client",
49
+ version: "1.0"
50
+ };
51
+ }
52
+ }
53
+ function getPlatformCapabilities(platform) {
54
+ const baseCapabilities = {
55
+ sampling: {}
56
+ };
57
+ if (platform === "ext-apps") {
58
+ return {
59
+ ...baseCapabilities,
60
+ experimental: {
61
+ [MCP_APPS_EXTENSION_KEY]: {
62
+ mimeTypes: ["text/html+mcp"]
63
+ }
64
+ }
65
+ };
66
+ }
67
+ return baseCapabilities;
68
+ }
69
+
70
+ // libs/testing/src/client/mcp-test-client.builder.ts
71
+ var McpTestClientBuilder = class {
72
+ config;
73
+ constructor(config) {
74
+ this.config = { ...config };
75
+ }
76
+ /**
77
+ * Set the authentication configuration
78
+ */
79
+ withAuth(auth) {
80
+ this.config.auth = { ...this.config.auth, ...auth };
81
+ return this;
82
+ }
83
+ /**
84
+ * Set the bearer token for authentication
85
+ */
86
+ withToken(token) {
87
+ this.config.auth = { ...this.config.auth, token };
88
+ return this;
89
+ }
90
+ /**
91
+ * Add custom headers to all requests
92
+ */
93
+ withHeaders(headers) {
94
+ this.config.auth = {
95
+ ...this.config.auth,
96
+ headers: { ...this.config.auth?.headers, ...headers }
97
+ };
98
+ return this;
99
+ }
100
+ /**
101
+ * Set the transport type
102
+ */
103
+ withTransport(transport) {
104
+ this.config.transport = transport;
105
+ return this;
106
+ }
107
+ /**
108
+ * Set the request timeout in milliseconds
109
+ */
110
+ withTimeout(timeoutMs) {
111
+ this.config.timeout = timeoutMs;
112
+ return this;
113
+ }
114
+ /**
115
+ * Enable debug logging
116
+ */
117
+ withDebug(enabled = true) {
118
+ this.config.debug = enabled;
119
+ return this;
120
+ }
121
+ /**
122
+ * Enable public mode - skip authentication entirely.
123
+ * When true, no Authorization header is sent and anonymous token is not requested.
124
+ * Use this for testing public/unauthenticated endpoints in CI/CD pipelines.
125
+ */
126
+ withPublicMode(enabled = true) {
127
+ this.config.publicMode = enabled;
128
+ return this;
129
+ }
130
+ /**
131
+ * Set the MCP protocol version to request
132
+ */
133
+ withProtocolVersion(version) {
134
+ this.config.protocolVersion = version;
135
+ return this;
136
+ }
137
+ /**
138
+ * Set the client info sent during initialization
139
+ */
140
+ withClientInfo(info) {
141
+ this.config.clientInfo = info;
142
+ return this;
143
+ }
144
+ /**
145
+ * Set the platform type for testing platform-specific meta keys.
146
+ * Automatically configures clientInfo and capabilities for platform detection.
147
+ *
148
+ * Platform-specific behavior:
149
+ * - `openai`: Uses openai/* meta keys, sets User-Agent to "ChatGPT/1.0"
150
+ * - `ext-apps`: Uses ui/* meta keys per SEP-1865, sets io.modelcontextprotocol/ui capability
151
+ * - `claude`: Uses frontmcp/* + ui/* keys, sets User-Agent to "claude-desktop/1.0"
152
+ * - `cursor`: Uses frontmcp/* + ui/* keys, sets User-Agent to "cursor/1.0"
153
+ * - Other platforms follow similar patterns
154
+ *
155
+ * @example
156
+ * ```typescript
157
+ * const client = await McpTestClient.create({ baseUrl })
158
+ * .withPlatform('openai')
159
+ * .buildAndConnect();
160
+ *
161
+ * // ext-apps automatically sets the io.modelcontextprotocol/ui capability
162
+ * const extAppsClient = await McpTestClient.create({ baseUrl })
163
+ * .withPlatform('ext-apps')
164
+ * .buildAndConnect();
165
+ * ```
166
+ */
167
+ withPlatform(platform) {
168
+ this.config.platform = platform;
169
+ this.config.clientInfo = getPlatformClientInfo(platform);
170
+ this.config.capabilities = getPlatformCapabilities(platform);
171
+ return this;
172
+ }
173
+ /**
174
+ * Set custom client capabilities for MCP initialization.
175
+ * Use this for fine-grained control over capabilities sent during initialization.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * const client = await McpTestClient.create({ baseUrl })
180
+ * .withCapabilities({
181
+ * sampling: {},
182
+ * experimental: {
183
+ * 'io.modelcontextprotocol/ui': { mimeTypes: ['text/html+mcp'] }
184
+ * }
185
+ * })
186
+ * .buildAndConnect();
187
+ * ```
188
+ */
189
+ withCapabilities(capabilities) {
190
+ this.config.capabilities = capabilities;
191
+ return this;
192
+ }
193
+ /**
194
+ * Build the McpTestClient instance (does not connect)
195
+ */
196
+ build() {
197
+ return new McpTestClient(this.config);
198
+ }
199
+ /**
200
+ * Build the McpTestClient and connect to the server
201
+ */
202
+ async buildAndConnect() {
203
+ const client = this.build();
204
+ await client.connect();
205
+ return client;
206
+ }
207
+ };
208
+
209
+ // libs/testing/src/transport/streamable-http.transport.ts
210
+ var DEFAULT_TIMEOUT = 3e4;
211
+ var StreamableHttpTransport = class {
212
+ config;
213
+ state = "disconnected";
214
+ sessionId;
215
+ authToken;
216
+ connectionCount = 0;
217
+ reconnectCount = 0;
218
+ lastRequestHeaders = {};
219
+ interceptors;
220
+ publicMode;
221
+ constructor(config) {
222
+ this.config = {
223
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
224
+ // Remove trailing slash
225
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
226
+ auth: config.auth ?? {},
227
+ publicMode: config.publicMode ?? false,
228
+ debug: config.debug ?? false,
229
+ interceptors: config.interceptors,
230
+ clientInfo: config.clientInfo
231
+ };
232
+ this.authToken = config.auth?.token;
233
+ this.interceptors = config.interceptors;
234
+ this.publicMode = config.publicMode ?? false;
235
+ }
236
+ async connect() {
237
+ this.state = "connecting";
238
+ this.connectionCount++;
239
+ try {
240
+ if (this.publicMode) {
241
+ this.log("Public mode: connecting without authentication");
242
+ this.state = "connected";
243
+ return;
244
+ }
245
+ if (!this.authToken) {
246
+ await this.requestAnonymousToken();
247
+ }
248
+ this.state = "connected";
249
+ this.log("Connected to StreamableHTTP transport");
250
+ } catch (error) {
251
+ this.state = "error";
252
+ throw error;
253
+ }
254
+ }
255
+ /**
256
+ * Request an anonymous token from the FrontMCP OAuth endpoint
257
+ * This allows the test client to authenticate without user interaction
258
+ */
259
+ async requestAnonymousToken() {
260
+ const clientId = crypto.randomUUID();
261
+ const tokenUrl = `${this.config.baseUrl}/oauth/token`;
262
+ this.log(`Requesting anonymous token from ${tokenUrl}`);
263
+ try {
264
+ const response = await fetch(tokenUrl, {
265
+ method: "POST",
266
+ headers: {
267
+ "Content-Type": "application/json"
268
+ },
269
+ body: JSON.stringify({
270
+ grant_type: "anonymous",
271
+ client_id: clientId,
272
+ resource: this.config.baseUrl
273
+ })
274
+ });
275
+ if (!response.ok) {
276
+ const errorText = await response.text();
277
+ this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);
278
+ return;
279
+ }
280
+ const tokenResponse = await response.json();
281
+ if (tokenResponse.access_token) {
282
+ this.authToken = tokenResponse.access_token;
283
+ this.log("Anonymous token acquired successfully");
284
+ }
285
+ } catch (error) {
286
+ this.log(`Error requesting anonymous token: ${error}`);
287
+ }
288
+ }
289
+ async request(message) {
290
+ this.ensureConnected();
291
+ const startTime = Date.now();
292
+ if (this.interceptors) {
293
+ const interceptResult = await this.interceptors.processRequest(message, {
294
+ timestamp: /* @__PURE__ */ new Date(),
295
+ transport: "streamable-http",
296
+ sessionId: this.sessionId
297
+ });
298
+ switch (interceptResult.type) {
299
+ case "mock": {
300
+ const mockResponse2 = await this.interceptors.processResponse(
301
+ message,
302
+ interceptResult.response,
303
+ Date.now() - startTime
304
+ );
305
+ return mockResponse2;
306
+ }
307
+ case "error":
308
+ throw interceptResult.error;
309
+ case "continue":
310
+ message = interceptResult.request;
311
+ break;
312
+ }
313
+ }
314
+ const headers = this.buildHeaders();
315
+ this.lastRequestHeaders = headers;
316
+ const url = `${this.config.baseUrl}/`;
317
+ this.log(`POST ${url}`, message);
318
+ const controller = new AbortController();
319
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
320
+ try {
321
+ const response = await fetch(url, {
322
+ method: "POST",
323
+ headers,
324
+ body: JSON.stringify(message),
325
+ signal: controller.signal
326
+ });
327
+ clearTimeout(timeoutId);
328
+ const newSessionId = response.headers.get("mcp-session-id");
329
+ if (newSessionId) {
330
+ this.sessionId = newSessionId;
331
+ }
332
+ let jsonResponse;
333
+ if (!response.ok) {
334
+ const errorText = await response.text();
335
+ this.log(`HTTP Error ${response.status}: ${errorText}`);
336
+ jsonResponse = {
337
+ jsonrpc: "2.0",
338
+ id: message.id ?? null,
339
+ error: {
340
+ code: -32e3,
341
+ message: `HTTP ${response.status}: ${response.statusText}`,
342
+ data: errorText
343
+ }
344
+ };
345
+ } else {
346
+ const contentType = response.headers.get("content-type") ?? "";
347
+ const text = await response.text();
348
+ this.log("Response:", text);
349
+ if (!text.trim()) {
350
+ jsonResponse = {
351
+ jsonrpc: "2.0",
352
+ id: message.id ?? null,
353
+ result: void 0
354
+ };
355
+ } else if (contentType.includes("text/event-stream")) {
356
+ const { response: sseResponse, sseSessionId } = this.parseSSEResponseWithSession(text, message.id);
357
+ jsonResponse = sseResponse;
358
+ if (sseSessionId && !this.sessionId) {
359
+ this.sessionId = sseSessionId;
360
+ this.log("Session ID from SSE:", this.sessionId);
361
+ }
362
+ } else {
363
+ jsonResponse = JSON.parse(text);
364
+ }
365
+ }
366
+ if (this.interceptors) {
367
+ jsonResponse = await this.interceptors.processResponse(message, jsonResponse, Date.now() - startTime);
368
+ }
369
+ return jsonResponse;
370
+ } catch (error) {
371
+ clearTimeout(timeoutId);
372
+ if (error instanceof Error && error.name === "AbortError") {
373
+ return {
374
+ jsonrpc: "2.0",
375
+ id: message.id ?? null,
376
+ error: {
377
+ code: -32e3,
378
+ message: `Request timeout after ${this.config.timeout}ms`
379
+ }
380
+ };
381
+ }
382
+ throw error;
383
+ }
384
+ }
385
+ async notify(message) {
386
+ this.ensureConnected();
387
+ const headers = this.buildHeaders();
388
+ this.lastRequestHeaders = headers;
389
+ const url = `${this.config.baseUrl}/`;
390
+ this.log(`POST ${url} (notification)`, message);
391
+ const controller = new AbortController();
392
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
393
+ try {
394
+ const response = await fetch(url, {
395
+ method: "POST",
396
+ headers,
397
+ body: JSON.stringify(message),
398
+ signal: controller.signal
399
+ });
400
+ clearTimeout(timeoutId);
401
+ const newSessionId = response.headers.get("mcp-session-id");
402
+ if (newSessionId) {
403
+ this.sessionId = newSessionId;
404
+ }
405
+ if (!response.ok) {
406
+ const errorText = await response.text();
407
+ this.log(`HTTP Error ${response.status} on notification: ${errorText}`);
408
+ }
409
+ } catch (error) {
410
+ clearTimeout(timeoutId);
411
+ if (error instanceof Error && error.name !== "AbortError") {
412
+ throw error;
413
+ }
414
+ }
415
+ }
416
+ async sendRaw(data) {
417
+ this.ensureConnected();
418
+ const headers = this.buildHeaders();
419
+ this.lastRequestHeaders = headers;
420
+ const url = `${this.config.baseUrl}/`;
421
+ this.log(`POST ${url} (raw)`, data);
422
+ const controller = new AbortController();
423
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
424
+ try {
425
+ const response = await fetch(url, {
426
+ method: "POST",
427
+ headers,
428
+ body: data,
429
+ signal: controller.signal
430
+ });
431
+ clearTimeout(timeoutId);
432
+ const text = await response.text();
433
+ if (!text.trim()) {
434
+ return {
435
+ jsonrpc: "2.0",
436
+ id: null,
437
+ error: {
438
+ code: -32700,
439
+ message: "Parse error"
440
+ }
441
+ };
442
+ }
443
+ return JSON.parse(text);
444
+ } catch (error) {
445
+ clearTimeout(timeoutId);
446
+ return {
447
+ jsonrpc: "2.0",
448
+ id: null,
449
+ error: {
450
+ code: -32700,
451
+ message: "Parse error",
452
+ data: error instanceof Error ? error.message : "Unknown error"
453
+ }
454
+ };
455
+ }
456
+ }
457
+ async close() {
458
+ this.state = "disconnected";
459
+ this.sessionId = void 0;
460
+ this.log("StreamableHTTP transport closed");
461
+ }
462
+ isConnected() {
463
+ return this.state === "connected";
464
+ }
465
+ getState() {
466
+ return this.state;
467
+ }
468
+ getSessionId() {
469
+ return this.sessionId;
470
+ }
471
+ setAuthToken(token) {
472
+ this.authToken = token;
473
+ }
474
+ setTimeout(ms) {
475
+ this.config.timeout = ms;
476
+ }
477
+ setInterceptors(interceptors2) {
478
+ this.interceptors = interceptors2;
479
+ }
480
+ getInterceptors() {
481
+ return this.interceptors;
482
+ }
483
+ getConnectionCount() {
484
+ return this.connectionCount;
485
+ }
486
+ getReconnectCount() {
487
+ return this.reconnectCount;
488
+ }
489
+ getLastRequestHeaders() {
490
+ return { ...this.lastRequestHeaders };
491
+ }
492
+ async simulateDisconnect() {
493
+ this.state = "disconnected";
494
+ this.sessionId = void 0;
495
+ }
496
+ async waitForReconnect(timeoutMs) {
497
+ const deadline = Date.now() + timeoutMs;
498
+ this.reconnectCount++;
499
+ await this.connect();
500
+ while (Date.now() < deadline) {
501
+ if (this.state === "connected") {
502
+ return;
503
+ }
504
+ await new Promise((r) => setTimeout(r, 50));
505
+ }
506
+ throw new Error("Timeout waiting for reconnection");
507
+ }
508
+ // ═══════════════════════════════════════════════════════════════════
509
+ // PRIVATE HELPERS
510
+ // ═══════════════════════════════════════════════════════════════════
511
+ buildHeaders() {
512
+ const headers = {
513
+ "Content-Type": "application/json",
514
+ Accept: "application/json, text/event-stream"
515
+ };
516
+ if (this.config.clientInfo) {
517
+ headers["User-Agent"] = `${this.config.clientInfo.name}/${this.config.clientInfo.version}`;
518
+ }
519
+ if (this.authToken && !this.publicMode) {
520
+ headers["Authorization"] = `Bearer ${this.authToken}`;
521
+ }
522
+ if (this.sessionId) {
523
+ headers["mcp-session-id"] = this.sessionId;
524
+ }
525
+ if (this.config.auth.headers) {
526
+ Object.assign(headers, this.config.auth.headers);
527
+ }
528
+ return headers;
529
+ }
530
+ ensureConnected() {
531
+ if (this.state !== "connected") {
532
+ throw new Error("Transport not connected. Call connect() first.");
533
+ }
534
+ }
535
+ log(message, data) {
536
+ if (this.config.debug) {
537
+ console.log(`[StreamableHTTP] ${message}`, data ?? "");
538
+ }
539
+ }
540
+ /**
541
+ * Parse SSE (Server-Sent Events) response format with session ID extraction
542
+ * SSE format is:
543
+ * event: message
544
+ * id: sessionId:messageId
545
+ * data: {"jsonrpc":"2.0",...}
546
+ *
547
+ * The id field contains the session ID followed by a colon and the message ID.
548
+ *
549
+ * @param text - The raw SSE response text
550
+ * @param requestId - The original request ID
551
+ * @returns Object with parsed JSON-RPC response and session ID (if found)
552
+ */
553
+ parseSSEResponseWithSession(text, requestId) {
554
+ const lines = text.split("\n");
555
+ const dataLines = [];
556
+ let sseSessionId;
557
+ for (const line of lines) {
558
+ if (line.startsWith("data: ")) {
559
+ dataLines.push(line.slice(6));
560
+ } else if (line === "data:") {
561
+ dataLines.push("");
562
+ } else if (line.startsWith("id: ")) {
563
+ const idValue = line.slice(4);
564
+ const colonIndex = idValue.lastIndexOf(":");
565
+ if (colonIndex > 0) {
566
+ sseSessionId = idValue.substring(0, colonIndex);
567
+ } else {
568
+ sseSessionId = idValue;
569
+ }
570
+ }
571
+ }
572
+ if (dataLines.length > 0) {
573
+ const jsonData = dataLines.join("\n");
574
+ try {
575
+ return {
576
+ response: JSON.parse(jsonData),
577
+ sseSessionId
578
+ };
579
+ } catch {
580
+ this.log("Failed to parse SSE data as JSON:", jsonData);
581
+ }
582
+ }
583
+ return {
584
+ response: {
585
+ jsonrpc: "2.0",
586
+ id: requestId ?? null,
587
+ error: {
588
+ code: -32700,
589
+ message: "Failed to parse SSE response",
590
+ data: text
591
+ }
592
+ },
593
+ sseSessionId
594
+ };
595
+ }
596
+ };
597
+
598
+ // libs/testing/src/interceptor/mock-registry.ts
599
+ var DefaultMockRegistry = class {
600
+ mocks = [];
601
+ add(mock) {
602
+ const entry = {
603
+ definition: mock,
604
+ callCount: 0,
605
+ calls: [],
606
+ remainingUses: mock.times ?? Infinity
607
+ };
608
+ this.mocks.push(entry);
609
+ return {
610
+ remove: () => {
611
+ const index = this.mocks.indexOf(entry);
612
+ if (index !== -1) {
613
+ this.mocks.splice(index, 1);
614
+ }
615
+ },
616
+ callCount: () => entry.callCount,
617
+ calls: () => [...entry.calls]
618
+ };
619
+ }
620
+ clear() {
621
+ this.mocks = [];
622
+ }
623
+ getAll() {
624
+ return this.mocks.map((e) => e.definition);
625
+ }
626
+ match(request) {
627
+ for (const entry of this.mocks) {
628
+ if (entry.remainingUses <= 0) continue;
629
+ const { definition } = entry;
630
+ if (definition.method !== request.method) continue;
631
+ if (definition.params !== void 0) {
632
+ const params = request.params ?? {};
633
+ if (typeof definition.params === "function") {
634
+ if (!definition.params(params)) continue;
635
+ } else {
636
+ if (!this.paramsMatch(definition.params, params)) continue;
637
+ }
638
+ }
639
+ entry.callCount++;
640
+ entry.calls.push(request);
641
+ entry.remainingUses--;
642
+ return definition;
643
+ }
644
+ return void 0;
645
+ }
646
+ /**
647
+ * Check if request params match the mock params definition
648
+ */
649
+ paramsMatch(expected, actual) {
650
+ for (const [key, value] of Object.entries(expected)) {
651
+ if (!(key in actual)) return false;
652
+ const actualValue = actual[key];
653
+ if (Array.isArray(value)) {
654
+ if (!Array.isArray(actualValue)) return false;
655
+ if (value.length !== actualValue.length) return false;
656
+ for (let i = 0; i < value.length; i++) {
657
+ const expectedItem = value[i];
658
+ const actualItem = actualValue[i];
659
+ if (typeof expectedItem === "object" && expectedItem !== null) {
660
+ if (typeof actualItem !== "object" || actualItem === null) return false;
661
+ if (!this.paramsMatch(expectedItem, actualItem)) {
662
+ return false;
663
+ }
664
+ } else if (actualItem !== expectedItem) {
665
+ return false;
666
+ }
667
+ }
668
+ } else if (typeof value === "object" && value !== null) {
669
+ if (typeof actualValue !== "object" || actualValue === null) return false;
670
+ if (!this.paramsMatch(value, actualValue)) {
671
+ return false;
672
+ }
673
+ } else if (actualValue !== value) {
674
+ return false;
675
+ }
676
+ }
677
+ return true;
678
+ }
679
+ };
680
+ var mockResponse = {
681
+ /**
682
+ * Create a successful JSON-RPC response
683
+ */
684
+ success(result, id = 1) {
685
+ return {
686
+ jsonrpc: "2.0",
687
+ id,
688
+ result
689
+ };
690
+ },
691
+ /**
692
+ * Create an error JSON-RPC response
693
+ */
694
+ error(code, message, data, id = 1) {
695
+ return {
696
+ jsonrpc: "2.0",
697
+ id,
698
+ error: { code, message, data }
699
+ };
700
+ },
701
+ /**
702
+ * Create a tool result response
703
+ */
704
+ toolResult(content, id = 1) {
705
+ return {
706
+ jsonrpc: "2.0",
707
+ id,
708
+ result: { content }
709
+ };
710
+ },
711
+ /**
712
+ * Create a tools/list response
713
+ */
714
+ toolsList(tools, id = 1) {
715
+ return {
716
+ jsonrpc: "2.0",
717
+ id,
718
+ result: { tools }
719
+ };
720
+ },
721
+ /**
722
+ * Create a resources/list response
723
+ */
724
+ resourcesList(resources, id = 1) {
725
+ return {
726
+ jsonrpc: "2.0",
727
+ id,
728
+ result: { resources }
729
+ };
730
+ },
731
+ /**
732
+ * Create a resources/read response
733
+ */
734
+ resourceRead(contents, id = 1) {
735
+ return {
736
+ jsonrpc: "2.0",
737
+ id,
738
+ result: { contents }
739
+ };
740
+ },
741
+ /**
742
+ * Common MCP errors
743
+ */
744
+ errors: {
745
+ methodNotFound: (method, id = 1) => mockResponse.error(-32601, `Method not found: ${method}`, void 0, id),
746
+ invalidParams: (message, id = 1) => mockResponse.error(-32602, message, void 0, id),
747
+ internalError: (message, id = 1) => mockResponse.error(-32603, message, void 0, id),
748
+ resourceNotFound: (uri, id = 1) => mockResponse.error(-32002, `Resource not found: ${uri}`, { uri }, id),
749
+ toolNotFound: (name, id = 1) => mockResponse.error(-32601, `Tool not found: ${name}`, { name }, id),
750
+ unauthorized: (id = 1) => mockResponse.error(-32001, "Unauthorized", void 0, id),
751
+ forbidden: (id = 1) => mockResponse.error(-32003, "Forbidden", void 0, id)
752
+ }
753
+ };
754
+
755
+ // libs/testing/src/interceptor/interceptor-chain.ts
756
+ var DefaultInterceptorChain = class {
757
+ request = [];
758
+ response = [];
759
+ mocks;
760
+ constructor() {
761
+ this.mocks = new DefaultMockRegistry();
762
+ }
763
+ /**
764
+ * Add a request interceptor
765
+ */
766
+ addRequestInterceptor(interceptor) {
767
+ this.request.push(interceptor);
768
+ return () => {
769
+ const index = this.request.indexOf(interceptor);
770
+ if (index !== -1) {
771
+ this.request.splice(index, 1);
772
+ }
773
+ };
774
+ }
775
+ /**
776
+ * Add a response interceptor
777
+ */
778
+ addResponseInterceptor(interceptor) {
779
+ this.response.push(interceptor);
780
+ return () => {
781
+ const index = this.response.indexOf(interceptor);
782
+ if (index !== -1) {
783
+ this.response.splice(index, 1);
784
+ }
785
+ };
786
+ }
787
+ /**
788
+ * Process a request through the interceptor chain
789
+ * Returns either:
790
+ * - { type: 'continue', request } - continue with (possibly modified) request
791
+ * - { type: 'mock', response } - return mock response immediately
792
+ * - { type: 'error', error } - throw error
793
+ */
794
+ async processRequest(request, meta) {
795
+ let currentRequest = request;
796
+ const mockDef = this.mocks.match(request);
797
+ if (mockDef) {
798
+ if (mockDef.delay && mockDef.delay > 0) {
799
+ await sleep(mockDef.delay);
800
+ }
801
+ let mockResponse2;
802
+ if (typeof mockDef.response === "function") {
803
+ mockResponse2 = await mockDef.response(request);
804
+ } else {
805
+ mockResponse2 = mockDef.response;
806
+ }
807
+ return {
808
+ type: "mock",
809
+ response: { ...mockResponse2, id: request.id ?? mockResponse2.id }
810
+ };
811
+ }
812
+ for (const interceptor of this.request) {
813
+ const ctx = {
814
+ request: currentRequest,
815
+ meta
816
+ };
817
+ const result = await interceptor(ctx);
818
+ switch (result.action) {
819
+ case "passthrough":
820
+ break;
821
+ case "modify":
822
+ currentRequest = result.request;
823
+ break;
824
+ case "mock":
825
+ return {
826
+ type: "mock",
827
+ response: { ...result.response, id: request.id ?? result.response.id }
828
+ };
829
+ case "error":
830
+ return { type: "error", error: result.error };
831
+ }
832
+ }
833
+ return { type: "continue", request: currentRequest };
834
+ }
835
+ /**
836
+ * Process a response through the interceptor chain
837
+ */
838
+ async processResponse(request, response, durationMs) {
839
+ let currentResponse = response;
840
+ for (const interceptor of this.response) {
841
+ const ctx = {
842
+ request,
843
+ response: currentResponse,
844
+ durationMs
845
+ };
846
+ const result = await interceptor(ctx);
847
+ switch (result.action) {
848
+ case "passthrough":
849
+ break;
850
+ case "modify":
851
+ currentResponse = result.response;
852
+ break;
853
+ }
854
+ }
855
+ return currentResponse;
856
+ }
857
+ /**
858
+ * Clear all interceptors and mocks
859
+ */
860
+ clear() {
861
+ this.request = [];
862
+ this.response = [];
863
+ this.mocks.clear();
864
+ }
865
+ };
866
+ function sleep(ms) {
867
+ return new Promise((resolve) => setTimeout(resolve, ms));
868
+ }
869
+
870
+ // libs/testing/src/client/mcp-test-client.ts
871
+ var DEFAULT_TIMEOUT2 = 3e4;
872
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
873
+ var DEFAULT_CLIENT_INFO = {
874
+ name: "@frontmcp/testing",
875
+ version: "0.4.0"
876
+ };
877
+ var McpTestClient = class {
878
+ // Platform and capabilities are optional - only set when testing platform-specific behavior
879
+ config;
880
+ transport = null;
881
+ initResult = null;
882
+ requestIdCounter = 0;
883
+ _lastRequestId = 0;
884
+ _sessionId;
885
+ _sessionInfo = null;
886
+ _authState = { isAnonymous: true, scopes: [] };
887
+ // Logging and tracing
888
+ _logs = [];
889
+ _traces = [];
890
+ _notifications = [];
891
+ _progressUpdates = [];
892
+ // Interceptor chain
893
+ _interceptors;
894
+ // ═══════════════════════════════════════════════════════════════════
895
+ // CONSTRUCTOR & FACTORY
896
+ // ═══════════════════════════════════════════════════════════════════
897
+ constructor(config) {
898
+ this.config = {
899
+ baseUrl: config.baseUrl,
900
+ transport: config.transport ?? "streamable-http",
901
+ auth: config.auth ?? {},
902
+ publicMode: config.publicMode ?? false,
903
+ timeout: config.timeout ?? DEFAULT_TIMEOUT2,
904
+ debug: config.debug ?? false,
905
+ protocolVersion: config.protocolVersion ?? DEFAULT_PROTOCOL_VERSION,
906
+ clientInfo: config.clientInfo ?? DEFAULT_CLIENT_INFO,
907
+ platform: config.platform,
908
+ capabilities: config.capabilities
909
+ };
910
+ if (config.auth?.token) {
911
+ this._authState = {
912
+ isAnonymous: false,
913
+ token: config.auth.token,
914
+ scopes: this.parseScopesFromToken(config.auth.token),
915
+ user: this.parseUserFromToken(config.auth.token)
916
+ };
917
+ }
918
+ this._interceptors = new DefaultInterceptorChain();
919
+ }
920
+ /**
921
+ * Create a new McpTestClientBuilder for fluent configuration
922
+ */
923
+ static create(config) {
924
+ return new McpTestClientBuilder(config);
925
+ }
926
+ // ═══════════════════════════════════════════════════════════════════
927
+ // CONNECTION & LIFECYCLE
928
+ // ═══════════════════════════════════════════════════════════════════
929
+ /**
930
+ * Connect to the MCP server and perform initialization
931
+ */
932
+ async connect() {
933
+ this.log("debug", `Connecting to ${this.config.baseUrl}...`);
934
+ this.transport = this.createTransport();
935
+ await this.transport.connect();
936
+ const initResponse = await this.initialize();
937
+ if (!initResponse.success || !initResponse.data) {
938
+ throw new Error(`Failed to initialize MCP connection: ${initResponse.error?.message ?? "Unknown error"}`);
939
+ }
940
+ this.initResult = initResponse.data;
941
+ this._sessionId = this.transport.getSessionId();
942
+ this._sessionInfo = {
943
+ id: this._sessionId ?? `session-${Date.now()}`,
944
+ createdAt: /* @__PURE__ */ new Date(),
945
+ lastActivityAt: /* @__PURE__ */ new Date(),
946
+ requestCount: 1
947
+ };
948
+ await this.transport.notify({
949
+ jsonrpc: "2.0",
950
+ method: "notifications/initialized"
951
+ });
952
+ this.log("info", `Connected to ${this.initResult.serverInfo?.name ?? "MCP Server"}`);
953
+ return this.initResult;
954
+ }
955
+ /**
956
+ * Disconnect from the MCP server
957
+ */
958
+ async disconnect() {
959
+ if (this.transport) {
960
+ await this.transport.close();
961
+ this.transport = null;
962
+ }
963
+ this.initResult = null;
964
+ this.log("info", "Disconnected from MCP server");
965
+ }
966
+ /**
967
+ * Reconnect to the server, optionally with an existing session ID
968
+ */
969
+ async reconnect(options) {
970
+ await this.disconnect();
971
+ if (options?.sessionId && this.transport) {
972
+ this._sessionId = options.sessionId;
973
+ }
974
+ await this.connect();
975
+ }
976
+ /**
977
+ * Check if the client is currently connected
978
+ */
979
+ isConnected() {
980
+ return this.transport?.isConnected() ?? false;
981
+ }
982
+ // ═══════════════════════════════════════════════════════════════════
983
+ // SESSION & AUTH PROPERTIES
984
+ // ═══════════════════════════════════════════════════════════════════
985
+ get sessionId() {
986
+ return this._sessionId ?? "";
987
+ }
988
+ get session() {
989
+ const info = this._sessionInfo ?? {
990
+ id: "",
991
+ createdAt: /* @__PURE__ */ new Date(),
992
+ lastActivityAt: /* @__PURE__ */ new Date(),
993
+ requestCount: 0
994
+ };
995
+ return {
996
+ ...info,
997
+ expire: async () => {
998
+ this._sessionId = void 0;
999
+ this._sessionInfo = null;
1000
+ }
1001
+ };
1002
+ }
1003
+ get auth() {
1004
+ return this._authState;
1005
+ }
1006
+ /**
1007
+ * Authenticate with a token
1008
+ */
1009
+ async authenticate(token) {
1010
+ this._authState = {
1011
+ isAnonymous: false,
1012
+ token,
1013
+ scopes: this.parseScopesFromToken(token),
1014
+ user: this.parseUserFromToken(token)
1015
+ };
1016
+ if (this.transport) {
1017
+ this.transport.setAuthToken(token);
1018
+ }
1019
+ this.log("debug", "Authentication updated");
1020
+ }
1021
+ // ═══════════════════════════════════════════════════════════════════
1022
+ // SERVER INFO & CAPABILITIES
1023
+ // ═══════════════════════════════════════════════════════════════════
1024
+ get serverInfo() {
1025
+ return {
1026
+ name: this.initResult?.serverInfo?.name ?? "",
1027
+ version: this.initResult?.serverInfo?.version ?? ""
1028
+ };
1029
+ }
1030
+ get protocolVersion() {
1031
+ return this.initResult?.protocolVersion ?? "";
1032
+ }
1033
+ get instructions() {
1034
+ return this.initResult?.instructions ?? "";
1035
+ }
1036
+ get capabilities() {
1037
+ return this.initResult?.capabilities ?? {};
1038
+ }
1039
+ /**
1040
+ * Check if server has a specific capability
1041
+ */
1042
+ hasCapability(name) {
1043
+ return !!this.capabilities[name];
1044
+ }
1045
+ // ═══════════════════════════════════════════════════════════════════
1046
+ // TOOLS API
1047
+ // ═══════════════════════════════════════════════════════════════════
1048
+ tools = {
1049
+ /**
1050
+ * List all available tools
1051
+ */
1052
+ list: async () => {
1053
+ const response = await this.listTools();
1054
+ if (!response.success || !response.data) {
1055
+ throw new Error(`Failed to list tools: ${response.error?.message}`);
1056
+ }
1057
+ return response.data.tools;
1058
+ },
1059
+ /**
1060
+ * Call a tool by name with arguments
1061
+ */
1062
+ call: async (name, args) => {
1063
+ const response = await this.callTool(name, args);
1064
+ return this.wrapToolResult(response);
1065
+ }
1066
+ };
1067
+ // ═══════════════════════════════════════════════════════════════════
1068
+ // RESOURCES API
1069
+ // ═══════════════════════════════════════════════════════════════════
1070
+ resources = {
1071
+ /**
1072
+ * List all static resources
1073
+ */
1074
+ list: async () => {
1075
+ const response = await this.listResources();
1076
+ if (!response.success || !response.data) {
1077
+ throw new Error(`Failed to list resources: ${response.error?.message}`);
1078
+ }
1079
+ return response.data.resources;
1080
+ },
1081
+ /**
1082
+ * List all resource templates
1083
+ */
1084
+ listTemplates: async () => {
1085
+ const response = await this.listResourceTemplates();
1086
+ if (!response.success || !response.data) {
1087
+ throw new Error(`Failed to list resource templates: ${response.error?.message}`);
1088
+ }
1089
+ return response.data.resourceTemplates;
1090
+ },
1091
+ /**
1092
+ * Read a resource by URI
1093
+ */
1094
+ read: async (uri) => {
1095
+ const response = await this.readResource(uri);
1096
+ return this.wrapResourceContent(response);
1097
+ },
1098
+ /**
1099
+ * Subscribe to resource changes (placeholder for future implementation)
1100
+ */
1101
+ subscribe: async (_uri) => {
1102
+ this.log("warn", "Resource subscription not yet implemented");
1103
+ },
1104
+ /**
1105
+ * Unsubscribe from resource changes (placeholder for future implementation)
1106
+ */
1107
+ unsubscribe: async (_uri) => {
1108
+ this.log("warn", "Resource unsubscription not yet implemented");
1109
+ }
1110
+ };
1111
+ // ═══════════════════════════════════════════════════════════════════
1112
+ // PROMPTS API
1113
+ // ═══════════════════════════════════════════════════════════════════
1114
+ prompts = {
1115
+ /**
1116
+ * List all available prompts
1117
+ */
1118
+ list: async () => {
1119
+ const response = await this.listPrompts();
1120
+ if (!response.success || !response.data) {
1121
+ throw new Error(`Failed to list prompts: ${response.error?.message}`);
1122
+ }
1123
+ return response.data.prompts;
1124
+ },
1125
+ /**
1126
+ * Get a prompt with arguments
1127
+ */
1128
+ get: async (name, args) => {
1129
+ const response = await this.getPrompt(name, args);
1130
+ return this.wrapPromptResult(response);
1131
+ }
1132
+ };
1133
+ // ═══════════════════════════════════════════════════════════════════
1134
+ // RAW PROTOCOL ACCESS
1135
+ // ═══════════════════════════════════════════════════════════════════
1136
+ raw = {
1137
+ /**
1138
+ * Send any JSON-RPC request
1139
+ */
1140
+ request: async (message) => {
1141
+ this.ensureConnected();
1142
+ const start = Date.now();
1143
+ const response = await this.transport.request(message);
1144
+ this.traceRequest(message.method, message.params, message.id, response, Date.now() - start);
1145
+ return response;
1146
+ },
1147
+ /**
1148
+ * Send a notification (no response expected)
1149
+ */
1150
+ notify: async (message) => {
1151
+ this.ensureConnected();
1152
+ await this.transport.notify(message);
1153
+ },
1154
+ /**
1155
+ * Send raw string data (for error testing)
1156
+ */
1157
+ sendRaw: async (data) => {
1158
+ this.ensureConnected();
1159
+ return this.transport.sendRaw(data);
1160
+ }
1161
+ };
1162
+ get lastRequestId() {
1163
+ return this._lastRequestId;
1164
+ }
1165
+ // ═══════════════════════════════════════════════════════════════════
1166
+ // TRANSPORT INFO
1167
+ // ═══════════════════════════════════════════════════════════════════
1168
+ /**
1169
+ * Get transport information and utilities
1170
+ */
1171
+ get transport_info() {
1172
+ return {
1173
+ type: this.config.transport,
1174
+ isConnected: () => this.transport?.isConnected() ?? false,
1175
+ messageEndpoint: this.transport?.getMessageEndpoint?.(),
1176
+ connectionCount: this.transport?.getConnectionCount?.() ?? 0,
1177
+ reconnectCount: this.transport?.getReconnectCount?.() ?? 0,
1178
+ lastRequestHeaders: this.transport?.getLastRequestHeaders?.() ?? {},
1179
+ simulateDisconnect: async () => {
1180
+ await this.transport?.simulateDisconnect?.();
1181
+ },
1182
+ waitForReconnect: async (timeoutMs) => {
1183
+ await this.transport?.waitForReconnect?.(timeoutMs);
1184
+ }
1185
+ };
1186
+ }
1187
+ // Alias for transport info
1188
+ get transport_() {
1189
+ return this.transport_info;
1190
+ }
1191
+ // ═══════════════════════════════════════════════════════════════════
1192
+ // NOTIFICATIONS
1193
+ // ═══════════════════════════════════════════════════════════════════
1194
+ notifications = {
1195
+ /**
1196
+ * Start collecting server notifications
1197
+ */
1198
+ collect: () => {
1199
+ return new NotificationCollector(this._notifications);
1200
+ },
1201
+ /**
1202
+ * Collect progress notifications specifically
1203
+ */
1204
+ collectProgress: () => {
1205
+ return new ProgressCollector(this._progressUpdates);
1206
+ },
1207
+ /**
1208
+ * Send a notification to the server
1209
+ */
1210
+ send: async (method, params) => {
1211
+ await this.raw.notify({ jsonrpc: "2.0", method, params });
1212
+ }
1213
+ };
1214
+ // ═══════════════════════════════════════════════════════════════════
1215
+ // LOGGING & DEBUGGING
1216
+ // ═══════════════════════════════════════════════════════════════════
1217
+ logs = {
1218
+ all: () => [...this._logs],
1219
+ filter: (level) => this._logs.filter((l) => l.level === level),
1220
+ search: (text) => this._logs.filter((l) => l.message.includes(text)),
1221
+ last: () => this._logs[this._logs.length - 1],
1222
+ clear: () => {
1223
+ this._logs = [];
1224
+ }
1225
+ };
1226
+ trace = {
1227
+ all: () => [...this._traces],
1228
+ last: () => this._traces[this._traces.length - 1],
1229
+ clear: () => {
1230
+ this._traces = [];
1231
+ }
1232
+ };
1233
+ // ═══════════════════════════════════════════════════════════════════
1234
+ // MOCKING & INTERCEPTION
1235
+ // ═══════════════════════════════════════════════════════════════════
1236
+ /**
1237
+ * API for mocking MCP requests
1238
+ *
1239
+ * @example
1240
+ * ```typescript
1241
+ * // Mock a specific tool call
1242
+ * const handle = mcp.mock.tool('my-tool', { result: 'mocked!' });
1243
+ *
1244
+ * // Mock with params matching
1245
+ * mcp.mock.add({
1246
+ * method: 'tools/call',
1247
+ * params: { name: 'my-tool' },
1248
+ * response: mockResponse.toolResult([{ type: 'text', text: 'mocked' }]),
1249
+ * });
1250
+ *
1251
+ * // Clear all mocks after test
1252
+ * mcp.mock.clear();
1253
+ * ```
1254
+ */
1255
+ mock = {
1256
+ /**
1257
+ * Add a mock definition
1258
+ */
1259
+ add: (mock) => {
1260
+ return this._interceptors.mocks.add(mock);
1261
+ },
1262
+ /**
1263
+ * Mock a tools/call request for a specific tool
1264
+ */
1265
+ tool: (name, result, options) => {
1266
+ return this._interceptors.mocks.add({
1267
+ method: "tools/call",
1268
+ params: { name },
1269
+ response: mockResponse.toolResult([
1270
+ { type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }
1271
+ ]),
1272
+ times: options?.times,
1273
+ delay: options?.delay
1274
+ });
1275
+ },
1276
+ /**
1277
+ * Mock a tools/call request to return an error
1278
+ */
1279
+ toolError: (name, code, message, options) => {
1280
+ return this._interceptors.mocks.add({
1281
+ method: "tools/call",
1282
+ params: { name },
1283
+ response: mockResponse.error(code, message),
1284
+ times: options?.times
1285
+ });
1286
+ },
1287
+ /**
1288
+ * Mock a resources/read request
1289
+ */
1290
+ resource: (uri, content, options) => {
1291
+ const contentObj = typeof content === "string" ? { uri, text: content } : { uri, ...content };
1292
+ return this._interceptors.mocks.add({
1293
+ method: "resources/read",
1294
+ params: { uri },
1295
+ response: mockResponse.resourceRead([contentObj]),
1296
+ times: options?.times,
1297
+ delay: options?.delay
1298
+ });
1299
+ },
1300
+ /**
1301
+ * Mock a resources/read request to return an error
1302
+ */
1303
+ resourceError: (uri, options) => {
1304
+ return this._interceptors.mocks.add({
1305
+ method: "resources/read",
1306
+ params: { uri },
1307
+ response: mockResponse.errors.resourceNotFound(uri),
1308
+ times: options?.times
1309
+ });
1310
+ },
1311
+ /**
1312
+ * Mock the tools/list response
1313
+ */
1314
+ toolsList: (tools, options) => {
1315
+ return this._interceptors.mocks.add({
1316
+ method: "tools/list",
1317
+ response: mockResponse.toolsList(tools),
1318
+ times: options?.times
1319
+ });
1320
+ },
1321
+ /**
1322
+ * Mock the resources/list response
1323
+ */
1324
+ resourcesList: (resources, options) => {
1325
+ return this._interceptors.mocks.add({
1326
+ method: "resources/list",
1327
+ response: mockResponse.resourcesList(resources),
1328
+ times: options?.times
1329
+ });
1330
+ },
1331
+ /**
1332
+ * Clear all mocks
1333
+ */
1334
+ clear: () => {
1335
+ this._interceptors.mocks.clear();
1336
+ },
1337
+ /**
1338
+ * Get all active mocks
1339
+ */
1340
+ all: () => {
1341
+ return this._interceptors.mocks.getAll();
1342
+ }
1343
+ };
1344
+ /**
1345
+ * API for intercepting requests and responses
1346
+ *
1347
+ * @example
1348
+ * ```typescript
1349
+ * // Log all requests
1350
+ * const remove = mcp.intercept.request((ctx) => {
1351
+ * console.log('Request:', ctx.request.method);
1352
+ * return { action: 'passthrough' };
1353
+ * });
1354
+ *
1355
+ * // Modify requests
1356
+ * mcp.intercept.request((ctx) => {
1357
+ * if (ctx.request.method === 'tools/call') {
1358
+ * return {
1359
+ * action: 'modify',
1360
+ * request: { ...ctx.request, params: { ...ctx.request.params, extra: true } },
1361
+ * };
1362
+ * }
1363
+ * return { action: 'passthrough' };
1364
+ * });
1365
+ *
1366
+ * // Add latency to all requests
1367
+ * mcp.intercept.delay(100);
1368
+ *
1369
+ * // Clean up
1370
+ * remove();
1371
+ * mcp.intercept.clear();
1372
+ * ```
1373
+ */
1374
+ intercept = {
1375
+ /**
1376
+ * Add a request interceptor
1377
+ * @returns Function to remove the interceptor
1378
+ */
1379
+ request: (interceptor) => {
1380
+ return this._interceptors.addRequestInterceptor(interceptor);
1381
+ },
1382
+ /**
1383
+ * Add a response interceptor
1384
+ * @returns Function to remove the interceptor
1385
+ */
1386
+ response: (interceptor) => {
1387
+ return this._interceptors.addResponseInterceptor(interceptor);
1388
+ },
1389
+ /**
1390
+ * Add latency to all requests
1391
+ * @returns Function to remove the interceptor
1392
+ */
1393
+ delay: (ms) => {
1394
+ return this._interceptors.addRequestInterceptor(async () => {
1395
+ await new Promise((r) => setTimeout(r, ms));
1396
+ return { action: "passthrough" };
1397
+ });
1398
+ },
1399
+ /**
1400
+ * Fail requests matching a method
1401
+ * @returns Function to remove the interceptor
1402
+ */
1403
+ failMethod: (method, error) => {
1404
+ return this._interceptors.addRequestInterceptor((ctx) => {
1405
+ if (ctx.request.method === method) {
1406
+ return { action: "error", error: new Error(error ?? `Intercepted: ${method}`) };
1407
+ }
1408
+ return { action: "passthrough" };
1409
+ });
1410
+ },
1411
+ /**
1412
+ * Clear all interceptors (but not mocks)
1413
+ */
1414
+ clear: () => {
1415
+ this._interceptors.request = [];
1416
+ this._interceptors.response = [];
1417
+ },
1418
+ /**
1419
+ * Clear everything (interceptors and mocks)
1420
+ */
1421
+ clearAll: () => {
1422
+ this._interceptors.clear();
1423
+ }
1424
+ };
1425
+ // ═══════════════════════════════════════════════════════════════════
1426
+ // TIMEOUT
1427
+ // ═══════════════════════════════════════════════════════════════════
1428
+ setTimeout(ms) {
1429
+ this.config.timeout = ms;
1430
+ if (this.transport) {
1431
+ this.transport.setTimeout(ms);
1432
+ }
1433
+ }
1434
+ // ═══════════════════════════════════════════════════════════════════
1435
+ // PRIVATE: MCP OPERATIONS
1436
+ // ═══════════════════════════════════════════════════════════════════
1437
+ async initialize() {
1438
+ const capabilities = this.config.capabilities ?? {
1439
+ sampling: {}
1440
+ };
1441
+ return this.request("initialize", {
1442
+ protocolVersion: this.config.protocolVersion,
1443
+ capabilities,
1444
+ clientInfo: this.config.clientInfo
1445
+ });
1446
+ }
1447
+ async listTools() {
1448
+ return this.request("tools/list", {});
1449
+ }
1450
+ async callTool(name, args) {
1451
+ return this.request("tools/call", {
1452
+ name,
1453
+ arguments: args ?? {}
1454
+ });
1455
+ }
1456
+ async listResources() {
1457
+ return this.request("resources/list", {});
1458
+ }
1459
+ async listResourceTemplates() {
1460
+ return this.request("resources/templates/list", {});
1461
+ }
1462
+ async readResource(uri) {
1463
+ return this.request("resources/read", { uri });
1464
+ }
1465
+ async listPrompts() {
1466
+ return this.request("prompts/list", {});
1467
+ }
1468
+ async getPrompt(name, args) {
1469
+ return this.request("prompts/get", {
1470
+ name,
1471
+ arguments: args ?? {}
1472
+ });
1473
+ }
1474
+ // ═══════════════════════════════════════════════════════════════════
1475
+ // PRIVATE: TRANSPORT & REQUEST HELPERS
1476
+ // ═══════════════════════════════════════════════════════════════════
1477
+ createTransport() {
1478
+ switch (this.config.transport) {
1479
+ case "streamable-http":
1480
+ return new StreamableHttpTransport({
1481
+ baseUrl: this.config.baseUrl,
1482
+ timeout: this.config.timeout,
1483
+ auth: this.config.auth,
1484
+ publicMode: this.config.publicMode,
1485
+ debug: this.config.debug,
1486
+ interceptors: this._interceptors,
1487
+ clientInfo: this.config.clientInfo
1488
+ });
1489
+ case "sse":
1490
+ throw new Error("SSE transport not yet implemented");
1491
+ default:
1492
+ throw new Error(`Unknown transport type: ${this.config.transport}`);
1493
+ }
1494
+ }
1495
+ async request(method, params) {
1496
+ this.ensureConnected();
1497
+ const id = ++this.requestIdCounter;
1498
+ this._lastRequestId = id;
1499
+ const start = Date.now();
1500
+ try {
1501
+ const response = await this.transport.request({
1502
+ jsonrpc: "2.0",
1503
+ id,
1504
+ method,
1505
+ params
1506
+ });
1507
+ const durationMs = Date.now() - start;
1508
+ this.updateSessionActivity();
1509
+ if ("error" in response && response.error) {
1510
+ const error = response.error;
1511
+ this.traceRequest(method, params, id, response, durationMs);
1512
+ return {
1513
+ success: false,
1514
+ error,
1515
+ durationMs,
1516
+ requestId: id
1517
+ };
1518
+ }
1519
+ this.traceRequest(method, params, id, response, durationMs);
1520
+ return {
1521
+ success: true,
1522
+ data: response.result,
1523
+ durationMs,
1524
+ requestId: id
1525
+ };
1526
+ } catch (err) {
1527
+ const durationMs = Date.now() - start;
1528
+ const error = {
1529
+ code: -32603,
1530
+ message: err instanceof Error ? err.message : "Unknown error"
1531
+ };
1532
+ return {
1533
+ success: false,
1534
+ error,
1535
+ durationMs,
1536
+ requestId: id
1537
+ };
1538
+ }
1539
+ }
1540
+ ensureConnected() {
1541
+ if (!this.transport?.isConnected()) {
1542
+ throw new Error("Not connected to MCP server. Call connect() first.");
1543
+ }
1544
+ }
1545
+ updateSessionActivity() {
1546
+ if (this._sessionInfo) {
1547
+ this._sessionInfo.lastActivityAt = /* @__PURE__ */ new Date();
1548
+ this._sessionInfo.requestCount++;
1549
+ }
1550
+ }
1551
+ // ═══════════════════════════════════════════════════════════════════
1552
+ // PRIVATE: RESULT WRAPPERS
1553
+ // ═══════════════════════════════════════════════════════════════════
1554
+ wrapToolResult(response) {
1555
+ const raw = response.data ?? { content: [] };
1556
+ const isError = !response.success || raw.isError === true;
1557
+ const meta = raw._meta;
1558
+ const hasUI = meta?.["ui/html"] !== void 0 || meta?.["ui/component"] !== void 0 || meta?.["openai/html"] !== void 0 || meta?.["frontmcp/html"] !== void 0;
1559
+ const structuredContent = raw["structuredContent"];
1560
+ return {
1561
+ raw,
1562
+ isSuccess: !isError,
1563
+ isError,
1564
+ error: response.error,
1565
+ durationMs: response.durationMs,
1566
+ json() {
1567
+ if (hasUI && structuredContent !== void 0) {
1568
+ return structuredContent;
1569
+ }
1570
+ const textContent = raw.content?.find((c) => c.type === "text");
1571
+ if (textContent && "text" in textContent) {
1572
+ return JSON.parse(textContent.text);
1573
+ }
1574
+ throw new Error("No text content to parse as JSON");
1575
+ },
1576
+ text() {
1577
+ const textContent = raw.content?.find((c) => c.type === "text");
1578
+ if (textContent && "text" in textContent) {
1579
+ return textContent.text;
1580
+ }
1581
+ return void 0;
1582
+ },
1583
+ hasTextContent() {
1584
+ return raw.content?.some((c) => c.type === "text") ?? false;
1585
+ },
1586
+ hasImageContent() {
1587
+ return raw.content?.some((c) => c.type === "image") ?? false;
1588
+ },
1589
+ hasResourceContent() {
1590
+ return raw.content?.some((c) => c.type === "resource") ?? false;
1591
+ },
1592
+ hasToolUI() {
1593
+ return hasUI;
1594
+ }
1595
+ };
1596
+ }
1597
+ wrapResourceContent(response) {
1598
+ const raw = response.data ?? { contents: [] };
1599
+ const isError = !response.success;
1600
+ const firstContent = raw.contents?.[0];
1601
+ return {
1602
+ raw,
1603
+ isSuccess: !isError,
1604
+ isError,
1605
+ error: response.error,
1606
+ durationMs: response.durationMs,
1607
+ json() {
1608
+ if (firstContent && "text" in firstContent) {
1609
+ return JSON.parse(firstContent.text);
1610
+ }
1611
+ throw new Error("No text content to parse as JSON");
1612
+ },
1613
+ text() {
1614
+ if (firstContent && "text" in firstContent) {
1615
+ return firstContent.text;
1616
+ }
1617
+ return void 0;
1618
+ },
1619
+ mimeType() {
1620
+ return firstContent?.mimeType;
1621
+ },
1622
+ hasMimeType(type) {
1623
+ return firstContent?.mimeType === type;
1624
+ }
1625
+ };
1626
+ }
1627
+ wrapPromptResult(response) {
1628
+ const raw = response.data ?? { messages: [] };
1629
+ const isError = !response.success;
1630
+ return {
1631
+ raw,
1632
+ isSuccess: !isError,
1633
+ isError,
1634
+ error: response.error,
1635
+ durationMs: response.durationMs,
1636
+ messages: raw.messages ?? [],
1637
+ description: raw.description
1638
+ };
1639
+ }
1640
+ // ═══════════════════════════════════════════════════════════════════
1641
+ // PRIVATE: LOGGING & TRACING
1642
+ // ═══════════════════════════════════════════════════════════════════
1643
+ log(level, message, data) {
1644
+ const entry = {
1645
+ level,
1646
+ message,
1647
+ timestamp: /* @__PURE__ */ new Date(),
1648
+ data
1649
+ };
1650
+ this._logs.push(entry);
1651
+ if (this.config.debug) {
1652
+ console.log(`[${level.toUpperCase()}] ${message}`, data ?? "");
1653
+ }
1654
+ }
1655
+ traceRequest(method, params, id, response, durationMs) {
1656
+ this._traces.push({
1657
+ request: { method, params, id },
1658
+ response: {
1659
+ result: "result" in response ? response.result : void 0,
1660
+ error: "error" in response ? response.error : void 0
1661
+ },
1662
+ durationMs,
1663
+ timestamp: /* @__PURE__ */ new Date()
1664
+ });
1665
+ }
1666
+ // ═══════════════════════════════════════════════════════════════════
1667
+ // PRIVATE: TOKEN PARSING
1668
+ // ═══════════════════════════════════════════════════════════════════
1669
+ parseScopesFromToken(token) {
1670
+ try {
1671
+ const payload = this.decodeJwtPayload(token);
1672
+ if (!payload) return [];
1673
+ const scope = payload["scope"];
1674
+ const scopes = payload["scopes"];
1675
+ if (typeof scope === "string") {
1676
+ return scope.split(" ");
1677
+ }
1678
+ if (Array.isArray(scopes)) {
1679
+ return scopes;
1680
+ }
1681
+ return [];
1682
+ } catch {
1683
+ return [];
1684
+ }
1685
+ }
1686
+ parseUserFromToken(token) {
1687
+ try {
1688
+ const payload = this.decodeJwtPayload(token);
1689
+ const sub = payload?.["sub"];
1690
+ if (!sub || typeof sub !== "string") return void 0;
1691
+ return {
1692
+ sub,
1693
+ email: payload["email"],
1694
+ name: payload["name"]
1695
+ };
1696
+ } catch {
1697
+ return void 0;
1698
+ }
1699
+ }
1700
+ decodeJwtPayload(token) {
1701
+ try {
1702
+ const parts = token.split(".");
1703
+ if (parts.length !== 3) return null;
1704
+ const payload = Buffer.from(parts[1], "base64url").toString("utf-8");
1705
+ return JSON.parse(payload);
1706
+ } catch {
1707
+ return null;
1708
+ }
1709
+ }
1710
+ };
1711
+ var NotificationCollector = class {
1712
+ constructor(notifications) {
1713
+ this.notifications = notifications;
1714
+ }
1715
+ get received() {
1716
+ return [...this.notifications];
1717
+ }
1718
+ has(method) {
1719
+ return this.notifications.some((n) => n.method === method);
1720
+ }
1721
+ async waitFor(method, timeoutMs) {
1722
+ const deadline = Date.now() + timeoutMs;
1723
+ while (Date.now() < deadline) {
1724
+ const found = this.notifications.find((n) => n.method === method);
1725
+ if (found) return found;
1726
+ await new Promise((r) => setTimeout(r, 50));
1727
+ }
1728
+ throw new Error(`Timeout waiting for notification: ${method}`);
1729
+ }
1730
+ };
1731
+ var ProgressCollector = class {
1732
+ constructor(updates) {
1733
+ this.updates = updates;
1734
+ }
1735
+ get all() {
1736
+ return [...this.updates];
1737
+ }
1738
+ async waitForComplete(timeoutMs) {
1739
+ const deadline = Date.now() + timeoutMs;
1740
+ while (Date.now() < deadline) {
1741
+ const last = this.updates[this.updates.length - 1];
1742
+ if (last && last.total !== void 0 && last.progress >= last.total) {
1743
+ return;
1744
+ }
1745
+ await new Promise((r) => setTimeout(r, 50));
1746
+ }
1747
+ throw new Error("Timeout waiting for progress to complete");
1748
+ }
1749
+ };
1750
+
1751
+ // libs/testing/src/auth/token-factory.ts
1752
+ import { SignJWT, generateKeyPair, exportJWK } from "jose";
1753
+ var TestTokenFactory = class {
1754
+ issuer;
1755
+ audience;
1756
+ privateKey = null;
1757
+ publicKey = null;
1758
+ jwk = null;
1759
+ keyId;
1760
+ constructor(options = {}) {
1761
+ this.issuer = options.issuer ?? "https://test.frontmcp.local";
1762
+ this.audience = options.audience ?? "frontmcp-test";
1763
+ this.keyId = `test-key-${Date.now()}`;
1764
+ }
1765
+ /**
1766
+ * Initialize the key pair (called automatically on first use)
1767
+ */
1768
+ async ensureKeys() {
1769
+ if (this.privateKey && this.publicKey) return;
1770
+ const { publicKey, privateKey } = await generateKeyPair("RS256", {
1771
+ extractable: true
1772
+ });
1773
+ this.privateKey = privateKey;
1774
+ this.publicKey = publicKey;
1775
+ this.jwk = await exportJWK(publicKey);
1776
+ this.jwk.kid = this.keyId;
1777
+ this.jwk.use = "sig";
1778
+ this.jwk.alg = "RS256";
1779
+ }
1780
+ /**
1781
+ * Create a JWT token with the specified claims
1782
+ */
1783
+ async createTestToken(options) {
1784
+ await this.ensureKeys();
1785
+ const now = Math.floor(Date.now() / 1e3);
1786
+ const exp = options.exp ?? 3600;
1787
+ const payload = {
1788
+ iss: options.iss ?? this.issuer,
1789
+ sub: options.sub,
1790
+ aud: options.aud ?? this.audience,
1791
+ iat: now,
1792
+ exp: now + exp,
1793
+ scope: options.scopes?.join(" "),
1794
+ ...options.claims
1795
+ };
1796
+ const token = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: this.keyId }).sign(this.privateKey);
1797
+ return token;
1798
+ }
1799
+ /**
1800
+ * Create an admin token with full access
1801
+ */
1802
+ async createAdminToken(sub = "admin-001") {
1803
+ return this.createTestToken({
1804
+ sub,
1805
+ scopes: ["admin:*", "read", "write", "delete"],
1806
+ claims: {
1807
+ email: "admin@test.local",
1808
+ name: "Test Admin",
1809
+ role: "admin"
1810
+ }
1811
+ });
1812
+ }
1813
+ /**
1814
+ * Create a regular user token
1815
+ */
1816
+ async createUserToken(sub = "user-001", scopes = ["read", "write"]) {
1817
+ return this.createTestToken({
1818
+ sub,
1819
+ scopes,
1820
+ claims: {
1821
+ email: "user@test.local",
1822
+ name: "Test User",
1823
+ role: "user"
1824
+ }
1825
+ });
1826
+ }
1827
+ /**
1828
+ * Create an anonymous user token
1829
+ */
1830
+ async createAnonymousToken() {
1831
+ return this.createTestToken({
1832
+ sub: `anon:${Date.now()}`,
1833
+ scopes: ["anonymous"],
1834
+ claims: {
1835
+ name: "Anonymous",
1836
+ role: "anonymous"
1837
+ }
1838
+ });
1839
+ }
1840
+ /**
1841
+ * Create an expired token (for testing token expiration)
1842
+ */
1843
+ async createExpiredToken(options) {
1844
+ await this.ensureKeys();
1845
+ const now = Math.floor(Date.now() / 1e3);
1846
+ const payload = {
1847
+ iss: this.issuer,
1848
+ sub: options.sub,
1849
+ aud: this.audience,
1850
+ iat: now - 7200,
1851
+ // 2 hours ago
1852
+ exp: now - 3600
1853
+ // Expired 1 hour ago
1854
+ };
1855
+ const token = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: this.keyId }).sign(this.privateKey);
1856
+ return token;
1857
+ }
1858
+ /**
1859
+ * Create a token with an invalid signature (for testing signature validation)
1860
+ */
1861
+ createTokenWithInvalidSignature(options) {
1862
+ const now = Math.floor(Date.now() / 1e3);
1863
+ const header = Buffer.from(JSON.stringify({ alg: "RS256", kid: this.keyId })).toString("base64url");
1864
+ const payload = Buffer.from(
1865
+ JSON.stringify({
1866
+ iss: this.issuer,
1867
+ sub: options.sub,
1868
+ aud: this.audience,
1869
+ iat: now,
1870
+ exp: now + 3600
1871
+ })
1872
+ ).toString("base64url");
1873
+ const signature = Buffer.from("invalid-signature-" + Date.now()).toString("base64url");
1874
+ return `${header}.${payload}.${signature}`;
1875
+ }
1876
+ /**
1877
+ * Get the public JWKS for verifying tokens
1878
+ */
1879
+ async getPublicJwks() {
1880
+ await this.ensureKeys();
1881
+ return {
1882
+ keys: [this.jwk]
1883
+ };
1884
+ }
1885
+ /**
1886
+ * Get the issuer URL
1887
+ */
1888
+ getIssuer() {
1889
+ return this.issuer;
1890
+ }
1891
+ /**
1892
+ * Get the audience
1893
+ */
1894
+ getAudience() {
1895
+ return this.audience;
1896
+ }
1897
+ };
1898
+
1899
+ // libs/testing/src/server/test-server.ts
1900
+ import { spawn } from "child_process";
1901
+ var TestServer = class _TestServer {
1902
+ process = null;
1903
+ options;
1904
+ _info;
1905
+ logs = [];
1906
+ constructor(options, port) {
1907
+ this.options = {
1908
+ port,
1909
+ command: options.command ?? "",
1910
+ cwd: options.cwd ?? process.cwd(),
1911
+ env: options.env ?? {},
1912
+ startupTimeout: options.startupTimeout ?? 3e4,
1913
+ healthCheckPath: options.healthCheckPath ?? "/health",
1914
+ debug: options.debug ?? false
1915
+ };
1916
+ this._info = {
1917
+ baseUrl: `http://localhost:${port}`,
1918
+ port
1919
+ };
1920
+ }
1921
+ /**
1922
+ * Start a test server with custom command
1923
+ */
1924
+ static async start(options) {
1925
+ const port = options.port ?? await findAvailablePort();
1926
+ const server = new _TestServer(options, port);
1927
+ try {
1928
+ await server.startProcess();
1929
+ } catch (error) {
1930
+ await server.stop();
1931
+ throw error;
1932
+ }
1933
+ return server;
1934
+ }
1935
+ /**
1936
+ * Start an Nx project as test server
1937
+ */
1938
+ static async startNx(project, options = {}) {
1939
+ if (!/^[\w-]+$/.test(project)) {
1940
+ throw new Error(
1941
+ `Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`
1942
+ );
1943
+ }
1944
+ const port = options.port ?? await findAvailablePort();
1945
+ const serverOptions = {
1946
+ ...options,
1947
+ port,
1948
+ command: `npx nx serve ${project} --port ${port}`,
1949
+ cwd: options.cwd ?? process.cwd()
1950
+ };
1951
+ const server = new _TestServer(serverOptions, port);
1952
+ try {
1953
+ await server.startProcess();
1954
+ } catch (error) {
1955
+ await server.stop();
1956
+ throw error;
1957
+ }
1958
+ return server;
1959
+ }
1960
+ /**
1961
+ * Create a test server connected to an already running server
1962
+ */
1963
+ static connect(baseUrl) {
1964
+ const url = new URL(baseUrl);
1965
+ const port = parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80);
1966
+ const server = new _TestServer(
1967
+ {
1968
+ command: "",
1969
+ port
1970
+ },
1971
+ port
1972
+ );
1973
+ server._info = {
1974
+ baseUrl: baseUrl.replace(/\/$/, ""),
1975
+ port
1976
+ };
1977
+ return server;
1978
+ }
1979
+ /**
1980
+ * Get server information
1981
+ */
1982
+ get info() {
1983
+ return { ...this._info };
1984
+ }
1985
+ /**
1986
+ * Stop the test server
1987
+ */
1988
+ async stop() {
1989
+ if (this.process) {
1990
+ this.log("Stopping server...");
1991
+ this.process.kill("SIGTERM");
1992
+ const exitPromise = new Promise((resolve) => {
1993
+ if (this.process) {
1994
+ this.process.once("exit", () => resolve());
1995
+ } else {
1996
+ resolve();
1997
+ }
1998
+ });
1999
+ const killTimeout = setTimeout(() => {
2000
+ if (this.process) {
2001
+ this.log("Force killing server after timeout...");
2002
+ this.process.kill("SIGKILL");
2003
+ }
2004
+ }, 5e3);
2005
+ await exitPromise;
2006
+ clearTimeout(killTimeout);
2007
+ this.process = null;
2008
+ this.log("Server stopped");
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Wait for server to be ready
2013
+ */
2014
+ async waitForReady(timeout) {
2015
+ const timeoutMs = timeout ?? this.options.startupTimeout;
2016
+ const deadline = Date.now() + timeoutMs;
2017
+ const checkInterval = 100;
2018
+ while (Date.now() < deadline) {
2019
+ try {
2020
+ const response = await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`, {
2021
+ method: "GET",
2022
+ signal: AbortSignal.timeout(1e3)
2023
+ });
2024
+ if (response.ok || response.status === 404) {
2025
+ this.log("Server is ready");
2026
+ return;
2027
+ }
2028
+ } catch {
2029
+ }
2030
+ await sleep2(checkInterval);
2031
+ }
2032
+ throw new Error(`Server did not become ready within ${timeoutMs}ms`);
2033
+ }
2034
+ /**
2035
+ * Restart the server
2036
+ */
2037
+ async restart() {
2038
+ await this.stop();
2039
+ await this.startProcess();
2040
+ }
2041
+ /**
2042
+ * Get captured server logs
2043
+ */
2044
+ getLogs() {
2045
+ return [...this.logs];
2046
+ }
2047
+ /**
2048
+ * Clear captured logs
2049
+ */
2050
+ clearLogs() {
2051
+ this.logs = [];
2052
+ }
2053
+ // ═══════════════════════════════════════════════════════════════════
2054
+ // PRIVATE METHODS
2055
+ // ═══════════════════════════════════════════════════════════════════
2056
+ async startProcess() {
2057
+ if (!this.options.command) {
2058
+ await this.waitForReady();
2059
+ return;
2060
+ }
2061
+ this.log(`Starting server: ${this.options.command}`);
2062
+ const env = {
2063
+ ...process.env,
2064
+ ...this.options.env,
2065
+ PORT: String(this.options.port)
2066
+ };
2067
+ this.process = spawn(this.options.command, [], {
2068
+ cwd: this.options.cwd,
2069
+ env,
2070
+ shell: true,
2071
+ stdio: ["pipe", "pipe", "pipe"]
2072
+ });
2073
+ if (this.process.pid !== void 0) {
2074
+ this._info.pid = this.process.pid;
2075
+ }
2076
+ let processExited = false;
2077
+ let exitCode = null;
2078
+ let exitError = null;
2079
+ this.process.stdout?.on("data", (data) => {
2080
+ const text = data.toString();
2081
+ this.logs.push(text);
2082
+ if (this.options.debug) {
2083
+ console.log("[SERVER]", text);
2084
+ }
2085
+ });
2086
+ this.process.stderr?.on("data", (data) => {
2087
+ const text = data.toString();
2088
+ this.logs.push(`[ERROR] ${text}`);
2089
+ if (this.options.debug) {
2090
+ console.error("[SERVER ERROR]", text);
2091
+ }
2092
+ });
2093
+ this.process.on("error", (err) => {
2094
+ this.logs.push(`[SPAWN ERROR] ${err.message}`);
2095
+ exitError = err;
2096
+ if (this.options.debug) {
2097
+ console.error("[SERVER SPAWN ERROR]", err);
2098
+ }
2099
+ });
2100
+ this.process.once("exit", (code) => {
2101
+ processExited = true;
2102
+ exitCode = code;
2103
+ this.log(`Server process exited with code ${code}`);
2104
+ });
2105
+ await this.waitForReadyWithExitDetection(() => {
2106
+ if (exitError) {
2107
+ return { exited: true, error: exitError };
2108
+ }
2109
+ if (processExited) {
2110
+ const recentLogs = this.logs.slice(-10).join("\n");
2111
+ return {
2112
+ exited: true,
2113
+ error: new Error(`Server process exited unexpectedly with code ${exitCode}.
2114
+
2115
+ Recent logs:
2116
+ ${recentLogs}`)
2117
+ };
2118
+ }
2119
+ return { exited: false };
2120
+ });
2121
+ }
2122
+ /**
2123
+ * Wait for server to be ready, but also detect early process exit
2124
+ */
2125
+ async waitForReadyWithExitDetection(checkExit) {
2126
+ const timeoutMs = this.options.startupTimeout;
2127
+ const deadline = Date.now() + timeoutMs;
2128
+ const checkInterval = 100;
2129
+ while (Date.now() < deadline) {
2130
+ const exitStatus = checkExit();
2131
+ if (exitStatus.exited) {
2132
+ throw exitStatus.error ?? new Error("Server process exited unexpectedly");
2133
+ }
2134
+ try {
2135
+ const response = await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`, {
2136
+ method: "GET",
2137
+ signal: AbortSignal.timeout(1e3)
2138
+ });
2139
+ if (response.ok || response.status === 404) {
2140
+ this.log("Server is ready");
2141
+ return;
2142
+ }
2143
+ } catch {
2144
+ }
2145
+ await sleep2(checkInterval);
2146
+ }
2147
+ const finalExitStatus = checkExit();
2148
+ if (finalExitStatus.exited) {
2149
+ throw finalExitStatus.error ?? new Error("Server process exited unexpectedly");
2150
+ }
2151
+ throw new Error(`Server did not become ready within ${timeoutMs}ms`);
2152
+ }
2153
+ log(message) {
2154
+ if (this.options.debug) {
2155
+ console.log(`[TestServer] ${message}`);
2156
+ }
2157
+ }
2158
+ };
2159
+ async function findAvailablePort() {
2160
+ const { createServer } = await import("net");
2161
+ return new Promise((resolve, reject) => {
2162
+ const server = createServer();
2163
+ server.listen(0, () => {
2164
+ const address = server.address();
2165
+ if (address && typeof address !== "string") {
2166
+ const port = address.port;
2167
+ server.close(() => resolve(port));
2168
+ } else {
2169
+ reject(new Error("Could not get port"));
2170
+ }
2171
+ });
2172
+ server.on("error", reject);
2173
+ });
2174
+ }
2175
+ function sleep2(ms) {
2176
+ return new Promise((resolve) => setTimeout(resolve, ms));
2177
+ }
2178
+
2179
+ // libs/testing/src/fixtures/test-fixture.ts
2180
+ var currentConfig = {};
2181
+ var serverInstance = null;
2182
+ var tokenFactory = null;
2183
+ var serverStartedByUs = false;
2184
+ async function initializeSharedResources() {
2185
+ if (!tokenFactory) {
2186
+ tokenFactory = new TestTokenFactory();
2187
+ }
2188
+ if (!serverInstance) {
2189
+ if (currentConfig.baseUrl) {
2190
+ serverInstance = TestServer.connect(currentConfig.baseUrl);
2191
+ serverStartedByUs = false;
2192
+ } else if (currentConfig.server) {
2193
+ serverInstance = await TestServer.start({
2194
+ port: currentConfig.port,
2195
+ command: resolveServerCommand(currentConfig.server),
2196
+ env: currentConfig.env,
2197
+ startupTimeout: currentConfig.startupTimeout ?? 3e4,
2198
+ debug: currentConfig.logLevel === "debug"
2199
+ });
2200
+ serverStartedByUs = true;
2201
+ } else {
2202
+ throw new Error(
2203
+ 'test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option'
2204
+ );
2205
+ }
2206
+ }
2207
+ }
2208
+ async function createTestFixtures() {
2209
+ await initializeSharedResources();
2210
+ const clientInstance = await McpTestClient.create({
2211
+ baseUrl: serverInstance.info.baseUrl,
2212
+ transport: currentConfig.transport ?? "streamable-http",
2213
+ publicMode: currentConfig.publicMode
2214
+ }).buildAndConnect();
2215
+ const auth = createAuthFixture(tokenFactory);
2216
+ const server = createServerFixture(serverInstance);
2217
+ return {
2218
+ mcp: clientInstance,
2219
+ auth,
2220
+ server
2221
+ };
2222
+ }
2223
+ async function cleanupTestFixtures(fixtures, _testFailed = false) {
2224
+ if (fixtures.mcp.isConnected()) {
2225
+ await fixtures.mcp.disconnect();
2226
+ }
2227
+ }
2228
+ async function cleanupSharedResources() {
2229
+ if (serverInstance && serverStartedByUs) {
2230
+ await serverInstance.stop();
2231
+ }
2232
+ serverInstance = null;
2233
+ tokenFactory = null;
2234
+ serverStartedByUs = false;
2235
+ }
2236
+ function createAuthFixture(factory) {
2237
+ const users = {
2238
+ admin: {
2239
+ sub: "admin-001",
2240
+ scopes: ["admin:*", "read", "write", "delete"],
2241
+ email: "admin@test.local",
2242
+ name: "Test Admin"
2243
+ },
2244
+ user: {
2245
+ sub: "user-001",
2246
+ scopes: ["read", "write"],
2247
+ email: "user@test.local",
2248
+ name: "Test User"
2249
+ },
2250
+ readOnly: {
2251
+ sub: "readonly-001",
2252
+ scopes: ["read"],
2253
+ email: "readonly@test.local",
2254
+ name: "Read Only User"
2255
+ }
2256
+ };
2257
+ return {
2258
+ createToken: (opts) => factory.createTestToken({
2259
+ sub: opts.sub,
2260
+ scopes: opts.scopes,
2261
+ claims: {
2262
+ email: opts.email,
2263
+ name: opts.name,
2264
+ ...opts.claims
2265
+ },
2266
+ exp: opts.expiresIn
2267
+ }),
2268
+ createExpiredToken: (opts) => factory.createExpiredToken(opts),
2269
+ createInvalidToken: (opts) => factory.createTokenWithInvalidSignature(opts),
2270
+ users: {
2271
+ admin: users["admin"],
2272
+ user: users["user"],
2273
+ readOnly: users["readOnly"]
2274
+ },
2275
+ getJwks: () => factory.getPublicJwks(),
2276
+ getIssuer: () => factory.getIssuer(),
2277
+ getAudience: () => factory.getAudience()
2278
+ };
2279
+ }
2280
+ function createServerFixture(server) {
2281
+ return {
2282
+ info: server.info,
2283
+ createClient: async (opts) => {
2284
+ return McpTestClient.create({
2285
+ baseUrl: server.info.baseUrl,
2286
+ transport: opts?.transport ?? "streamable-http",
2287
+ auth: opts?.token ? { token: opts.token } : void 0,
2288
+ clientInfo: opts?.clientInfo,
2289
+ publicMode: currentConfig.publicMode
2290
+ }).buildAndConnect();
2291
+ },
2292
+ createClientBuilder: () => {
2293
+ const builder = new McpTestClientBuilder({
2294
+ baseUrl: server.info.baseUrl,
2295
+ publicMode: currentConfig.publicMode
2296
+ });
2297
+ return builder;
2298
+ },
2299
+ restart: () => server.restart(),
2300
+ getLogs: () => server.getLogs(),
2301
+ clearLogs: () => server.clearLogs()
2302
+ };
2303
+ }
2304
+ function resolveServerCommand(server) {
2305
+ if (server.includes(" ")) {
2306
+ return server;
2307
+ }
2308
+ return `npx tsx ${server}`;
2309
+ }
2310
+ function testWithFixtures(name, fn) {
2311
+ it(name, async () => {
2312
+ const fixtures = await createTestFixtures();
2313
+ let testFailed = false;
2314
+ try {
2315
+ await fn(fixtures);
2316
+ } catch (error) {
2317
+ testFailed = true;
2318
+ throw error;
2319
+ } finally {
2320
+ await cleanupTestFixtures(fixtures, testFailed);
2321
+ }
2322
+ });
2323
+ }
2324
+ function use(config) {
2325
+ currentConfig = { ...currentConfig, ...config };
2326
+ afterAll(async () => {
2327
+ await cleanupSharedResources();
2328
+ });
2329
+ }
2330
+ function skip(name, fn) {
2331
+ it.skip(name, async () => {
2332
+ const fixtures = await createTestFixtures();
2333
+ let testFailed = false;
2334
+ try {
2335
+ await fn(fixtures);
2336
+ } catch (error) {
2337
+ testFailed = true;
2338
+ throw error;
2339
+ } finally {
2340
+ await cleanupTestFixtures(fixtures, testFailed);
2341
+ }
2342
+ });
2343
+ }
2344
+ function only(name, fn) {
2345
+ it.only(name, async () => {
2346
+ const fixtures = await createTestFixtures();
2347
+ let testFailed = false;
2348
+ try {
2349
+ await fn(fixtures);
2350
+ } catch (error) {
2351
+ testFailed = true;
2352
+ throw error;
2353
+ } finally {
2354
+ await cleanupTestFixtures(fixtures, testFailed);
2355
+ }
2356
+ });
2357
+ }
2358
+ function todo(name) {
2359
+ it.todo(name);
2360
+ }
2361
+ var test = testWithFixtures;
2362
+ test.use = use;
2363
+ test.describe = describe;
2364
+ test.beforeAll = beforeAll;
2365
+ test.beforeEach = beforeEach;
2366
+ test.afterEach = afterEach;
2367
+ test.afterAll = afterAll;
2368
+ test.skip = skip;
2369
+ test.only = only;
2370
+ test.todo = todo;
2371
+ export {
2372
+ cleanupSharedResources,
2373
+ cleanupTestFixtures,
2374
+ createTestFixtures,
2375
+ initializeSharedResources,
2376
+ test
2377
+ };