@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
package/index.js ADDED
@@ -0,0 +1,4866 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // libs/testing/src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AssertionError: () => AssertionError,
34
+ AuthHeaders: () => AuthHeaders,
35
+ BASIC_UI_TOOL_CONFIG: () => BASIC_UI_TOOL_CONFIG,
36
+ ConnectionError: () => ConnectionError,
37
+ DefaultInterceptorChain: () => DefaultInterceptorChain,
38
+ DefaultMockRegistry: () => DefaultMockRegistry,
39
+ EXPECTED_EXTAPPS_TOOLS_LIST_META_KEYS: () => EXPECTED_EXTAPPS_TOOLS_LIST_META_KEYS,
40
+ EXPECTED_EXTAPPS_TOOL_CALL_META_KEYS: () => EXPECTED_EXTAPPS_TOOL_CALL_META_KEYS,
41
+ EXPECTED_FRONTMCP_TOOLS_LIST_META_KEYS: () => EXPECTED_FRONTMCP_TOOLS_LIST_META_KEYS,
42
+ EXPECTED_FRONTMCP_TOOL_CALL_META_KEYS: () => EXPECTED_FRONTMCP_TOOL_CALL_META_KEYS,
43
+ EXPECTED_OPENAI_TOOLS_LIST_META_KEYS: () => EXPECTED_OPENAI_TOOLS_LIST_META_KEYS,
44
+ EXPECTED_OPENAI_TOOL_CALL_META_KEYS: () => EXPECTED_OPENAI_TOOL_CALL_META_KEYS,
45
+ FULL_UI_TOOL_CONFIG: () => FULL_UI_TOOL_CONFIG,
46
+ McpAssertions: () => McpAssertions,
47
+ McpProtocolError: () => McpProtocolError,
48
+ McpTestClient: () => McpTestClient,
49
+ McpTestClientBuilder: () => McpTestClientBuilder,
50
+ MockAPIServer: () => MockAPIServer,
51
+ MockOAuthServer: () => MockOAuthServer,
52
+ PLATFORM_DETECTION_PATTERNS: () => PLATFORM_DETECTION_PATTERNS,
53
+ ServerStartError: () => ServerStartError,
54
+ StreamableHttpTransport: () => StreamableHttpTransport,
55
+ TestClientError: () => TestClientError,
56
+ TestServer: () => TestServer,
57
+ TestTokenFactory: () => TestTokenFactory,
58
+ TestUsers: () => TestUsers,
59
+ TimeoutError: () => TimeoutError,
60
+ UIAssertions: () => UIAssertions,
61
+ basicUIToolInputSchema: () => basicUIToolInputSchema,
62
+ basicUIToolOutputSchema: () => basicUIToolOutputSchema,
63
+ buildUserAgent: () => buildUserAgent,
64
+ containsPrompt: () => containsPrompt,
65
+ containsResource: () => containsResource,
66
+ containsResourceTemplate: () => containsResourceTemplate,
67
+ containsTool: () => containsTool,
68
+ createTestUser: () => createTestUser,
69
+ expect: () => expect,
70
+ fullUIToolInputSchema: () => fullUIToolInputSchema,
71
+ fullUIToolOutputSchema: () => fullUIToolOutputSchema,
72
+ generateBasicUIToolOutput: () => generateBasicUIToolOutput,
73
+ generateFullUIToolOutput: () => generateFullUIToolOutput,
74
+ getForbiddenMetaPrefixes: () => getForbiddenMetaPrefixes,
75
+ getPlatformClientInfo: () => getPlatformClientInfo,
76
+ getPlatformMetaNamespace: () => getPlatformMetaNamespace,
77
+ getPlatformMimeType: () => getPlatformMimeType,
78
+ getPlatformUserAgent: () => getPlatformUserAgent,
79
+ getToolCallMetaPrefixes: () => getToolCallMetaPrefixes,
80
+ getToolsListMetaPrefixes: () => getToolsListMetaPrefixes,
81
+ hasMimeType: () => hasMimeType,
82
+ hasTextContent: () => hasTextContent,
83
+ httpMock: () => httpMock,
84
+ httpResponse: () => httpResponse,
85
+ interceptors: () => interceptors,
86
+ isError: () => isError,
87
+ isExtAppsPlatform: () => isExtAppsPlatform,
88
+ isFrontmcpPlatform: () => isFrontmcpPlatform,
89
+ isOpenAIPlatform: () => isOpenAIPlatform,
90
+ isSuccessful: () => isSuccessful,
91
+ mcpMatchers: () => mcpMatchers,
92
+ mockResponse: () => mockResponse,
93
+ test: () => test,
94
+ uiMatchers: () => uiMatchers
95
+ });
96
+ module.exports = __toCommonJS(index_exports);
97
+
98
+ // libs/testing/src/platform/platform-client-info.ts
99
+ var MCP_APPS_EXTENSION_KEY = "io.modelcontextprotocol/ui";
100
+ function getPlatformClientInfo(platform) {
101
+ switch (platform) {
102
+ case "openai":
103
+ return {
104
+ name: "ChatGPT",
105
+ version: "1.0"
106
+ };
107
+ case "ext-apps":
108
+ return {
109
+ name: "mcp-ext-apps",
110
+ version: "1.0"
111
+ };
112
+ case "claude":
113
+ return {
114
+ name: "claude-desktop",
115
+ version: "1.0"
116
+ };
117
+ case "cursor":
118
+ return {
119
+ name: "cursor",
120
+ version: "1.0"
121
+ };
122
+ case "continue":
123
+ return {
124
+ name: "continue",
125
+ version: "1.0"
126
+ };
127
+ case "cody":
128
+ return {
129
+ name: "cody",
130
+ version: "1.0"
131
+ };
132
+ case "gemini":
133
+ return {
134
+ name: "gemini",
135
+ version: "1.0"
136
+ };
137
+ case "generic-mcp":
138
+ return {
139
+ name: "generic-mcp-client",
140
+ version: "1.0"
141
+ };
142
+ case "unknown":
143
+ default:
144
+ return {
145
+ name: "mcp-test-client",
146
+ version: "1.0"
147
+ };
148
+ }
149
+ }
150
+ function buildUserAgent(clientInfo) {
151
+ return `${clientInfo.name}/${clientInfo.version}`;
152
+ }
153
+ function getPlatformUserAgent(platform) {
154
+ return buildUserAgent(getPlatformClientInfo(platform));
155
+ }
156
+ var PLATFORM_DETECTION_PATTERNS = {
157
+ openai: /chatgpt/i,
158
+ "ext-apps": /mcp-ext-apps/i,
159
+ // Note: Actual detection uses capabilities
160
+ claude: /claude|claude-desktop/i,
161
+ cursor: /cursor/i,
162
+ continue: /continue/i,
163
+ cody: /cody/i,
164
+ gemini: /gemini/i,
165
+ "generic-mcp": /generic-mcp/i,
166
+ unknown: /.*/
167
+ // Matches anything (fallback)
168
+ };
169
+ function getPlatformCapabilities(platform) {
170
+ const baseCapabilities = {
171
+ sampling: {}
172
+ };
173
+ if (platform === "ext-apps") {
174
+ return {
175
+ ...baseCapabilities,
176
+ experimental: {
177
+ [MCP_APPS_EXTENSION_KEY]: {
178
+ mimeTypes: ["text/html+mcp"]
179
+ }
180
+ }
181
+ };
182
+ }
183
+ return baseCapabilities;
184
+ }
185
+
186
+ // libs/testing/src/client/mcp-test-client.builder.ts
187
+ var McpTestClientBuilder = class {
188
+ config;
189
+ constructor(config) {
190
+ this.config = { ...config };
191
+ }
192
+ /**
193
+ * Set the authentication configuration
194
+ */
195
+ withAuth(auth) {
196
+ this.config.auth = { ...this.config.auth, ...auth };
197
+ return this;
198
+ }
199
+ /**
200
+ * Set the bearer token for authentication
201
+ */
202
+ withToken(token) {
203
+ this.config.auth = { ...this.config.auth, token };
204
+ return this;
205
+ }
206
+ /**
207
+ * Add custom headers to all requests
208
+ */
209
+ withHeaders(headers) {
210
+ this.config.auth = {
211
+ ...this.config.auth,
212
+ headers: { ...this.config.auth?.headers, ...headers }
213
+ };
214
+ return this;
215
+ }
216
+ /**
217
+ * Set the transport type
218
+ */
219
+ withTransport(transport) {
220
+ this.config.transport = transport;
221
+ return this;
222
+ }
223
+ /**
224
+ * Set the request timeout in milliseconds
225
+ */
226
+ withTimeout(timeoutMs) {
227
+ this.config.timeout = timeoutMs;
228
+ return this;
229
+ }
230
+ /**
231
+ * Enable debug logging
232
+ */
233
+ withDebug(enabled = true) {
234
+ this.config.debug = enabled;
235
+ return this;
236
+ }
237
+ /**
238
+ * Enable public mode - skip authentication entirely.
239
+ * When true, no Authorization header is sent and anonymous token is not requested.
240
+ * Use this for testing public/unauthenticated endpoints in CI/CD pipelines.
241
+ */
242
+ withPublicMode(enabled = true) {
243
+ this.config.publicMode = enabled;
244
+ return this;
245
+ }
246
+ /**
247
+ * Set the MCP protocol version to request
248
+ */
249
+ withProtocolVersion(version) {
250
+ this.config.protocolVersion = version;
251
+ return this;
252
+ }
253
+ /**
254
+ * Set the client info sent during initialization
255
+ */
256
+ withClientInfo(info) {
257
+ this.config.clientInfo = info;
258
+ return this;
259
+ }
260
+ /**
261
+ * Set the platform type for testing platform-specific meta keys.
262
+ * Automatically configures clientInfo and capabilities for platform detection.
263
+ *
264
+ * Platform-specific behavior:
265
+ * - `openai`: Uses openai/* meta keys, sets User-Agent to "ChatGPT/1.0"
266
+ * - `ext-apps`: Uses ui/* meta keys per SEP-1865, sets io.modelcontextprotocol/ui capability
267
+ * - `claude`: Uses frontmcp/* + ui/* keys, sets User-Agent to "claude-desktop/1.0"
268
+ * - `cursor`: Uses frontmcp/* + ui/* keys, sets User-Agent to "cursor/1.0"
269
+ * - Other platforms follow similar patterns
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * const client = await McpTestClient.create({ baseUrl })
274
+ * .withPlatform('openai')
275
+ * .buildAndConnect();
276
+ *
277
+ * // ext-apps automatically sets the io.modelcontextprotocol/ui capability
278
+ * const extAppsClient = await McpTestClient.create({ baseUrl })
279
+ * .withPlatform('ext-apps')
280
+ * .buildAndConnect();
281
+ * ```
282
+ */
283
+ withPlatform(platform) {
284
+ this.config.platform = platform;
285
+ this.config.clientInfo = getPlatformClientInfo(platform);
286
+ this.config.capabilities = getPlatformCapabilities(platform);
287
+ return this;
288
+ }
289
+ /**
290
+ * Set custom client capabilities for MCP initialization.
291
+ * Use this for fine-grained control over capabilities sent during initialization.
292
+ *
293
+ * @example
294
+ * ```typescript
295
+ * const client = await McpTestClient.create({ baseUrl })
296
+ * .withCapabilities({
297
+ * sampling: {},
298
+ * experimental: {
299
+ * 'io.modelcontextprotocol/ui': { mimeTypes: ['text/html+mcp'] }
300
+ * }
301
+ * })
302
+ * .buildAndConnect();
303
+ * ```
304
+ */
305
+ withCapabilities(capabilities) {
306
+ this.config.capabilities = capabilities;
307
+ return this;
308
+ }
309
+ /**
310
+ * Build the McpTestClient instance (does not connect)
311
+ */
312
+ build() {
313
+ return new McpTestClient(this.config);
314
+ }
315
+ /**
316
+ * Build the McpTestClient and connect to the server
317
+ */
318
+ async buildAndConnect() {
319
+ const client = this.build();
320
+ await client.connect();
321
+ return client;
322
+ }
323
+ };
324
+
325
+ // libs/testing/src/transport/streamable-http.transport.ts
326
+ var DEFAULT_TIMEOUT = 3e4;
327
+ var StreamableHttpTransport = class {
328
+ config;
329
+ state = "disconnected";
330
+ sessionId;
331
+ authToken;
332
+ connectionCount = 0;
333
+ reconnectCount = 0;
334
+ lastRequestHeaders = {};
335
+ interceptors;
336
+ publicMode;
337
+ constructor(config) {
338
+ this.config = {
339
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
340
+ // Remove trailing slash
341
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
342
+ auth: config.auth ?? {},
343
+ publicMode: config.publicMode ?? false,
344
+ debug: config.debug ?? false,
345
+ interceptors: config.interceptors,
346
+ clientInfo: config.clientInfo
347
+ };
348
+ this.authToken = config.auth?.token;
349
+ this.interceptors = config.interceptors;
350
+ this.publicMode = config.publicMode ?? false;
351
+ }
352
+ async connect() {
353
+ this.state = "connecting";
354
+ this.connectionCount++;
355
+ try {
356
+ if (this.publicMode) {
357
+ this.log("Public mode: connecting without authentication");
358
+ this.state = "connected";
359
+ return;
360
+ }
361
+ if (!this.authToken) {
362
+ await this.requestAnonymousToken();
363
+ }
364
+ this.state = "connected";
365
+ this.log("Connected to StreamableHTTP transport");
366
+ } catch (error) {
367
+ this.state = "error";
368
+ throw error;
369
+ }
370
+ }
371
+ /**
372
+ * Request an anonymous token from the FrontMCP OAuth endpoint
373
+ * This allows the test client to authenticate without user interaction
374
+ */
375
+ async requestAnonymousToken() {
376
+ const clientId = crypto.randomUUID();
377
+ const tokenUrl = `${this.config.baseUrl}/oauth/token`;
378
+ this.log(`Requesting anonymous token from ${tokenUrl}`);
379
+ try {
380
+ const response = await fetch(tokenUrl, {
381
+ method: "POST",
382
+ headers: {
383
+ "Content-Type": "application/json"
384
+ },
385
+ body: JSON.stringify({
386
+ grant_type: "anonymous",
387
+ client_id: clientId,
388
+ resource: this.config.baseUrl
389
+ })
390
+ });
391
+ if (!response.ok) {
392
+ const errorText = await response.text();
393
+ this.log(`Failed to get anonymous token: ${response.status} ${errorText}`);
394
+ return;
395
+ }
396
+ const tokenResponse = await response.json();
397
+ if (tokenResponse.access_token) {
398
+ this.authToken = tokenResponse.access_token;
399
+ this.log("Anonymous token acquired successfully");
400
+ }
401
+ } catch (error) {
402
+ this.log(`Error requesting anonymous token: ${error}`);
403
+ }
404
+ }
405
+ async request(message) {
406
+ this.ensureConnected();
407
+ const startTime = Date.now();
408
+ if (this.interceptors) {
409
+ const interceptResult = await this.interceptors.processRequest(message, {
410
+ timestamp: /* @__PURE__ */ new Date(),
411
+ transport: "streamable-http",
412
+ sessionId: this.sessionId
413
+ });
414
+ switch (interceptResult.type) {
415
+ case "mock": {
416
+ const mockResponse2 = await this.interceptors.processResponse(
417
+ message,
418
+ interceptResult.response,
419
+ Date.now() - startTime
420
+ );
421
+ return mockResponse2;
422
+ }
423
+ case "error":
424
+ throw interceptResult.error;
425
+ case "continue":
426
+ message = interceptResult.request;
427
+ break;
428
+ }
429
+ }
430
+ const headers = this.buildHeaders();
431
+ this.lastRequestHeaders = headers;
432
+ const url = `${this.config.baseUrl}/`;
433
+ this.log(`POST ${url}`, message);
434
+ const controller = new AbortController();
435
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
436
+ try {
437
+ const response = await fetch(url, {
438
+ method: "POST",
439
+ headers,
440
+ body: JSON.stringify(message),
441
+ signal: controller.signal
442
+ });
443
+ clearTimeout(timeoutId);
444
+ const newSessionId = response.headers.get("mcp-session-id");
445
+ if (newSessionId) {
446
+ this.sessionId = newSessionId;
447
+ }
448
+ let jsonResponse;
449
+ if (!response.ok) {
450
+ const errorText = await response.text();
451
+ this.log(`HTTP Error ${response.status}: ${errorText}`);
452
+ jsonResponse = {
453
+ jsonrpc: "2.0",
454
+ id: message.id ?? null,
455
+ error: {
456
+ code: -32e3,
457
+ message: `HTTP ${response.status}: ${response.statusText}`,
458
+ data: errorText
459
+ }
460
+ };
461
+ } else {
462
+ const contentType = response.headers.get("content-type") ?? "";
463
+ const text = await response.text();
464
+ this.log("Response:", text);
465
+ if (!text.trim()) {
466
+ jsonResponse = {
467
+ jsonrpc: "2.0",
468
+ id: message.id ?? null,
469
+ result: void 0
470
+ };
471
+ } else if (contentType.includes("text/event-stream")) {
472
+ const { response: sseResponse, sseSessionId } = this.parseSSEResponseWithSession(text, message.id);
473
+ jsonResponse = sseResponse;
474
+ if (sseSessionId && !this.sessionId) {
475
+ this.sessionId = sseSessionId;
476
+ this.log("Session ID from SSE:", this.sessionId);
477
+ }
478
+ } else {
479
+ jsonResponse = JSON.parse(text);
480
+ }
481
+ }
482
+ if (this.interceptors) {
483
+ jsonResponse = await this.interceptors.processResponse(message, jsonResponse, Date.now() - startTime);
484
+ }
485
+ return jsonResponse;
486
+ } catch (error) {
487
+ clearTimeout(timeoutId);
488
+ if (error instanceof Error && error.name === "AbortError") {
489
+ return {
490
+ jsonrpc: "2.0",
491
+ id: message.id ?? null,
492
+ error: {
493
+ code: -32e3,
494
+ message: `Request timeout after ${this.config.timeout}ms`
495
+ }
496
+ };
497
+ }
498
+ throw error;
499
+ }
500
+ }
501
+ async notify(message) {
502
+ this.ensureConnected();
503
+ const headers = this.buildHeaders();
504
+ this.lastRequestHeaders = headers;
505
+ const url = `${this.config.baseUrl}/`;
506
+ this.log(`POST ${url} (notification)`, message);
507
+ const controller = new AbortController();
508
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
509
+ try {
510
+ const response = await fetch(url, {
511
+ method: "POST",
512
+ headers,
513
+ body: JSON.stringify(message),
514
+ signal: controller.signal
515
+ });
516
+ clearTimeout(timeoutId);
517
+ const newSessionId = response.headers.get("mcp-session-id");
518
+ if (newSessionId) {
519
+ this.sessionId = newSessionId;
520
+ }
521
+ if (!response.ok) {
522
+ const errorText = await response.text();
523
+ this.log(`HTTP Error ${response.status} on notification: ${errorText}`);
524
+ }
525
+ } catch (error) {
526
+ clearTimeout(timeoutId);
527
+ if (error instanceof Error && error.name !== "AbortError") {
528
+ throw error;
529
+ }
530
+ }
531
+ }
532
+ async sendRaw(data) {
533
+ this.ensureConnected();
534
+ const headers = this.buildHeaders();
535
+ this.lastRequestHeaders = headers;
536
+ const url = `${this.config.baseUrl}/`;
537
+ this.log(`POST ${url} (raw)`, data);
538
+ const controller = new AbortController();
539
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
540
+ try {
541
+ const response = await fetch(url, {
542
+ method: "POST",
543
+ headers,
544
+ body: data,
545
+ signal: controller.signal
546
+ });
547
+ clearTimeout(timeoutId);
548
+ const text = await response.text();
549
+ if (!text.trim()) {
550
+ return {
551
+ jsonrpc: "2.0",
552
+ id: null,
553
+ error: {
554
+ code: -32700,
555
+ message: "Parse error"
556
+ }
557
+ };
558
+ }
559
+ return JSON.parse(text);
560
+ } catch (error) {
561
+ clearTimeout(timeoutId);
562
+ return {
563
+ jsonrpc: "2.0",
564
+ id: null,
565
+ error: {
566
+ code: -32700,
567
+ message: "Parse error",
568
+ data: error instanceof Error ? error.message : "Unknown error"
569
+ }
570
+ };
571
+ }
572
+ }
573
+ async close() {
574
+ this.state = "disconnected";
575
+ this.sessionId = void 0;
576
+ this.log("StreamableHTTP transport closed");
577
+ }
578
+ isConnected() {
579
+ return this.state === "connected";
580
+ }
581
+ getState() {
582
+ return this.state;
583
+ }
584
+ getSessionId() {
585
+ return this.sessionId;
586
+ }
587
+ setAuthToken(token) {
588
+ this.authToken = token;
589
+ }
590
+ setTimeout(ms) {
591
+ this.config.timeout = ms;
592
+ }
593
+ setInterceptors(interceptors2) {
594
+ this.interceptors = interceptors2;
595
+ }
596
+ getInterceptors() {
597
+ return this.interceptors;
598
+ }
599
+ getConnectionCount() {
600
+ return this.connectionCount;
601
+ }
602
+ getReconnectCount() {
603
+ return this.reconnectCount;
604
+ }
605
+ getLastRequestHeaders() {
606
+ return { ...this.lastRequestHeaders };
607
+ }
608
+ async simulateDisconnect() {
609
+ this.state = "disconnected";
610
+ this.sessionId = void 0;
611
+ }
612
+ async waitForReconnect(timeoutMs) {
613
+ const deadline = Date.now() + timeoutMs;
614
+ this.reconnectCount++;
615
+ await this.connect();
616
+ while (Date.now() < deadline) {
617
+ if (this.state === "connected") {
618
+ return;
619
+ }
620
+ await new Promise((r) => setTimeout(r, 50));
621
+ }
622
+ throw new Error("Timeout waiting for reconnection");
623
+ }
624
+ // ═══════════════════════════════════════════════════════════════════
625
+ // PRIVATE HELPERS
626
+ // ═══════════════════════════════════════════════════════════════════
627
+ buildHeaders() {
628
+ const headers = {
629
+ "Content-Type": "application/json",
630
+ Accept: "application/json, text/event-stream"
631
+ };
632
+ if (this.config.clientInfo) {
633
+ headers["User-Agent"] = `${this.config.clientInfo.name}/${this.config.clientInfo.version}`;
634
+ }
635
+ if (this.authToken && !this.publicMode) {
636
+ headers["Authorization"] = `Bearer ${this.authToken}`;
637
+ }
638
+ if (this.sessionId) {
639
+ headers["mcp-session-id"] = this.sessionId;
640
+ }
641
+ if (this.config.auth.headers) {
642
+ Object.assign(headers, this.config.auth.headers);
643
+ }
644
+ return headers;
645
+ }
646
+ ensureConnected() {
647
+ if (this.state !== "connected") {
648
+ throw new Error("Transport not connected. Call connect() first.");
649
+ }
650
+ }
651
+ log(message, data) {
652
+ if (this.config.debug) {
653
+ console.log(`[StreamableHTTP] ${message}`, data ?? "");
654
+ }
655
+ }
656
+ /**
657
+ * Parse SSE (Server-Sent Events) response format with session ID extraction
658
+ * SSE format is:
659
+ * event: message
660
+ * id: sessionId:messageId
661
+ * data: {"jsonrpc":"2.0",...}
662
+ *
663
+ * The id field contains the session ID followed by a colon and the message ID.
664
+ *
665
+ * @param text - The raw SSE response text
666
+ * @param requestId - The original request ID
667
+ * @returns Object with parsed JSON-RPC response and session ID (if found)
668
+ */
669
+ parseSSEResponseWithSession(text, requestId) {
670
+ const lines = text.split("\n");
671
+ const dataLines = [];
672
+ let sseSessionId;
673
+ for (const line of lines) {
674
+ if (line.startsWith("data: ")) {
675
+ dataLines.push(line.slice(6));
676
+ } else if (line === "data:") {
677
+ dataLines.push("");
678
+ } else if (line.startsWith("id: ")) {
679
+ const idValue = line.slice(4);
680
+ const colonIndex = idValue.lastIndexOf(":");
681
+ if (colonIndex > 0) {
682
+ sseSessionId = idValue.substring(0, colonIndex);
683
+ } else {
684
+ sseSessionId = idValue;
685
+ }
686
+ }
687
+ }
688
+ if (dataLines.length > 0) {
689
+ const jsonData = dataLines.join("\n");
690
+ try {
691
+ return {
692
+ response: JSON.parse(jsonData),
693
+ sseSessionId
694
+ };
695
+ } catch {
696
+ this.log("Failed to parse SSE data as JSON:", jsonData);
697
+ }
698
+ }
699
+ return {
700
+ response: {
701
+ jsonrpc: "2.0",
702
+ id: requestId ?? null,
703
+ error: {
704
+ code: -32700,
705
+ message: "Failed to parse SSE response",
706
+ data: text
707
+ }
708
+ },
709
+ sseSessionId
710
+ };
711
+ }
712
+ };
713
+
714
+ // libs/testing/src/interceptor/mock-registry.ts
715
+ var DefaultMockRegistry = class {
716
+ mocks = [];
717
+ add(mock) {
718
+ const entry = {
719
+ definition: mock,
720
+ callCount: 0,
721
+ calls: [],
722
+ remainingUses: mock.times ?? Infinity
723
+ };
724
+ this.mocks.push(entry);
725
+ return {
726
+ remove: () => {
727
+ const index = this.mocks.indexOf(entry);
728
+ if (index !== -1) {
729
+ this.mocks.splice(index, 1);
730
+ }
731
+ },
732
+ callCount: () => entry.callCount,
733
+ calls: () => [...entry.calls]
734
+ };
735
+ }
736
+ clear() {
737
+ this.mocks = [];
738
+ }
739
+ getAll() {
740
+ return this.mocks.map((e) => e.definition);
741
+ }
742
+ match(request) {
743
+ for (const entry of this.mocks) {
744
+ if (entry.remainingUses <= 0) continue;
745
+ const { definition } = entry;
746
+ if (definition.method !== request.method) continue;
747
+ if (definition.params !== void 0) {
748
+ const params = request.params ?? {};
749
+ if (typeof definition.params === "function") {
750
+ if (!definition.params(params)) continue;
751
+ } else {
752
+ if (!this.paramsMatch(definition.params, params)) continue;
753
+ }
754
+ }
755
+ entry.callCount++;
756
+ entry.calls.push(request);
757
+ entry.remainingUses--;
758
+ return definition;
759
+ }
760
+ return void 0;
761
+ }
762
+ /**
763
+ * Check if request params match the mock params definition
764
+ */
765
+ paramsMatch(expected, actual) {
766
+ for (const [key, value] of Object.entries(expected)) {
767
+ if (!(key in actual)) return false;
768
+ const actualValue = actual[key];
769
+ if (Array.isArray(value)) {
770
+ if (!Array.isArray(actualValue)) return false;
771
+ if (value.length !== actualValue.length) return false;
772
+ for (let i = 0; i < value.length; i++) {
773
+ const expectedItem = value[i];
774
+ const actualItem = actualValue[i];
775
+ if (typeof expectedItem === "object" && expectedItem !== null) {
776
+ if (typeof actualItem !== "object" || actualItem === null) return false;
777
+ if (!this.paramsMatch(expectedItem, actualItem)) {
778
+ return false;
779
+ }
780
+ } else if (actualItem !== expectedItem) {
781
+ return false;
782
+ }
783
+ }
784
+ } else if (typeof value === "object" && value !== null) {
785
+ if (typeof actualValue !== "object" || actualValue === null) return false;
786
+ if (!this.paramsMatch(value, actualValue)) {
787
+ return false;
788
+ }
789
+ } else if (actualValue !== value) {
790
+ return false;
791
+ }
792
+ }
793
+ return true;
794
+ }
795
+ };
796
+ var mockResponse = {
797
+ /**
798
+ * Create a successful JSON-RPC response
799
+ */
800
+ success(result, id = 1) {
801
+ return {
802
+ jsonrpc: "2.0",
803
+ id,
804
+ result
805
+ };
806
+ },
807
+ /**
808
+ * Create an error JSON-RPC response
809
+ */
810
+ error(code, message, data, id = 1) {
811
+ return {
812
+ jsonrpc: "2.0",
813
+ id,
814
+ error: { code, message, data }
815
+ };
816
+ },
817
+ /**
818
+ * Create a tool result response
819
+ */
820
+ toolResult(content, id = 1) {
821
+ return {
822
+ jsonrpc: "2.0",
823
+ id,
824
+ result: { content }
825
+ };
826
+ },
827
+ /**
828
+ * Create a tools/list response
829
+ */
830
+ toolsList(tools, id = 1) {
831
+ return {
832
+ jsonrpc: "2.0",
833
+ id,
834
+ result: { tools }
835
+ };
836
+ },
837
+ /**
838
+ * Create a resources/list response
839
+ */
840
+ resourcesList(resources, id = 1) {
841
+ return {
842
+ jsonrpc: "2.0",
843
+ id,
844
+ result: { resources }
845
+ };
846
+ },
847
+ /**
848
+ * Create a resources/read response
849
+ */
850
+ resourceRead(contents, id = 1) {
851
+ return {
852
+ jsonrpc: "2.0",
853
+ id,
854
+ result: { contents }
855
+ };
856
+ },
857
+ /**
858
+ * Common MCP errors
859
+ */
860
+ errors: {
861
+ methodNotFound: (method, id = 1) => mockResponse.error(-32601, `Method not found: ${method}`, void 0, id),
862
+ invalidParams: (message, id = 1) => mockResponse.error(-32602, message, void 0, id),
863
+ internalError: (message, id = 1) => mockResponse.error(-32603, message, void 0, id),
864
+ resourceNotFound: (uri, id = 1) => mockResponse.error(-32002, `Resource not found: ${uri}`, { uri }, id),
865
+ toolNotFound: (name, id = 1) => mockResponse.error(-32601, `Tool not found: ${name}`, { name }, id),
866
+ unauthorized: (id = 1) => mockResponse.error(-32001, "Unauthorized", void 0, id),
867
+ forbidden: (id = 1) => mockResponse.error(-32003, "Forbidden", void 0, id)
868
+ }
869
+ };
870
+
871
+ // libs/testing/src/interceptor/interceptor-chain.ts
872
+ var DefaultInterceptorChain = class {
873
+ request = [];
874
+ response = [];
875
+ mocks;
876
+ constructor() {
877
+ this.mocks = new DefaultMockRegistry();
878
+ }
879
+ /**
880
+ * Add a request interceptor
881
+ */
882
+ addRequestInterceptor(interceptor) {
883
+ this.request.push(interceptor);
884
+ return () => {
885
+ const index = this.request.indexOf(interceptor);
886
+ if (index !== -1) {
887
+ this.request.splice(index, 1);
888
+ }
889
+ };
890
+ }
891
+ /**
892
+ * Add a response interceptor
893
+ */
894
+ addResponseInterceptor(interceptor) {
895
+ this.response.push(interceptor);
896
+ return () => {
897
+ const index = this.response.indexOf(interceptor);
898
+ if (index !== -1) {
899
+ this.response.splice(index, 1);
900
+ }
901
+ };
902
+ }
903
+ /**
904
+ * Process a request through the interceptor chain
905
+ * Returns either:
906
+ * - { type: 'continue', request } - continue with (possibly modified) request
907
+ * - { type: 'mock', response } - return mock response immediately
908
+ * - { type: 'error', error } - throw error
909
+ */
910
+ async processRequest(request, meta) {
911
+ let currentRequest = request;
912
+ const mockDef = this.mocks.match(request);
913
+ if (mockDef) {
914
+ if (mockDef.delay && mockDef.delay > 0) {
915
+ await sleep(mockDef.delay);
916
+ }
917
+ let mockResponse2;
918
+ if (typeof mockDef.response === "function") {
919
+ mockResponse2 = await mockDef.response(request);
920
+ } else {
921
+ mockResponse2 = mockDef.response;
922
+ }
923
+ return {
924
+ type: "mock",
925
+ response: { ...mockResponse2, id: request.id ?? mockResponse2.id }
926
+ };
927
+ }
928
+ for (const interceptor of this.request) {
929
+ const ctx = {
930
+ request: currentRequest,
931
+ meta
932
+ };
933
+ const result = await interceptor(ctx);
934
+ switch (result.action) {
935
+ case "passthrough":
936
+ break;
937
+ case "modify":
938
+ currentRequest = result.request;
939
+ break;
940
+ case "mock":
941
+ return {
942
+ type: "mock",
943
+ response: { ...result.response, id: request.id ?? result.response.id }
944
+ };
945
+ case "error":
946
+ return { type: "error", error: result.error };
947
+ }
948
+ }
949
+ return { type: "continue", request: currentRequest };
950
+ }
951
+ /**
952
+ * Process a response through the interceptor chain
953
+ */
954
+ async processResponse(request, response, durationMs) {
955
+ let currentResponse = response;
956
+ for (const interceptor of this.response) {
957
+ const ctx = {
958
+ request,
959
+ response: currentResponse,
960
+ durationMs
961
+ };
962
+ const result = await interceptor(ctx);
963
+ switch (result.action) {
964
+ case "passthrough":
965
+ break;
966
+ case "modify":
967
+ currentResponse = result.response;
968
+ break;
969
+ }
970
+ }
971
+ return currentResponse;
972
+ }
973
+ /**
974
+ * Clear all interceptors and mocks
975
+ */
976
+ clear() {
977
+ this.request = [];
978
+ this.response = [];
979
+ this.mocks.clear();
980
+ }
981
+ };
982
+ function sleep(ms) {
983
+ return new Promise((resolve) => setTimeout(resolve, ms));
984
+ }
985
+ var interceptors = {
986
+ /**
987
+ * Create an interceptor that logs all requests
988
+ */
989
+ logger(logFn = console.log) {
990
+ return (ctx) => {
991
+ logFn(`[MCP Request] ${ctx.request.method}`, ctx.request.params);
992
+ return { action: "passthrough" };
993
+ };
994
+ },
995
+ /**
996
+ * Create an interceptor that adds latency to all requests
997
+ */
998
+ delay(ms) {
999
+ return async () => {
1000
+ await sleep(ms);
1001
+ return { action: "passthrough" };
1002
+ };
1003
+ },
1004
+ /**
1005
+ * Create an interceptor that fails requests matching a condition
1006
+ */
1007
+ failWhen(condition, error) {
1008
+ return (ctx) => {
1009
+ if (condition(ctx)) {
1010
+ const err = typeof error === "string" ? new Error(error) : error;
1011
+ return { action: "error", error: err };
1012
+ }
1013
+ return { action: "passthrough" };
1014
+ };
1015
+ },
1016
+ /**
1017
+ * Create an interceptor that modifies specific methods
1018
+ */
1019
+ modifyMethod(method, modifier) {
1020
+ return (ctx) => {
1021
+ if (ctx.request.method === method) {
1022
+ return { action: "modify", request: modifier(ctx.request) };
1023
+ }
1024
+ return { action: "passthrough" };
1025
+ };
1026
+ },
1027
+ /**
1028
+ * Create a response interceptor that logs responses
1029
+ */
1030
+ responseLogger(logFn = console.log) {
1031
+ return (ctx) => {
1032
+ const status = ctx.response.error ? "ERROR" : "OK";
1033
+ logFn(`[MCP Response] ${ctx.request.method} ${status} (${ctx.durationMs}ms)`, ctx.response);
1034
+ return { action: "passthrough" };
1035
+ };
1036
+ },
1037
+ /**
1038
+ * Create a response interceptor that modifies specific responses
1039
+ */
1040
+ modifyResponse(method, modifier) {
1041
+ return (ctx) => {
1042
+ if (ctx.request.method === method) {
1043
+ return { action: "modify", response: modifier(ctx.response) };
1044
+ }
1045
+ return { action: "passthrough" };
1046
+ };
1047
+ }
1048
+ };
1049
+
1050
+ // libs/testing/src/client/mcp-test-client.ts
1051
+ var DEFAULT_TIMEOUT2 = 3e4;
1052
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
1053
+ var DEFAULT_CLIENT_INFO = {
1054
+ name: "@frontmcp/testing",
1055
+ version: "0.4.0"
1056
+ };
1057
+ var McpTestClient = class {
1058
+ // Platform and capabilities are optional - only set when testing platform-specific behavior
1059
+ config;
1060
+ transport = null;
1061
+ initResult = null;
1062
+ requestIdCounter = 0;
1063
+ _lastRequestId = 0;
1064
+ _sessionId;
1065
+ _sessionInfo = null;
1066
+ _authState = { isAnonymous: true, scopes: [] };
1067
+ // Logging and tracing
1068
+ _logs = [];
1069
+ _traces = [];
1070
+ _notifications = [];
1071
+ _progressUpdates = [];
1072
+ // Interceptor chain
1073
+ _interceptors;
1074
+ // ═══════════════════════════════════════════════════════════════════
1075
+ // CONSTRUCTOR & FACTORY
1076
+ // ═══════════════════════════════════════════════════════════════════
1077
+ constructor(config) {
1078
+ this.config = {
1079
+ baseUrl: config.baseUrl,
1080
+ transport: config.transport ?? "streamable-http",
1081
+ auth: config.auth ?? {},
1082
+ publicMode: config.publicMode ?? false,
1083
+ timeout: config.timeout ?? DEFAULT_TIMEOUT2,
1084
+ debug: config.debug ?? false,
1085
+ protocolVersion: config.protocolVersion ?? DEFAULT_PROTOCOL_VERSION,
1086
+ clientInfo: config.clientInfo ?? DEFAULT_CLIENT_INFO,
1087
+ platform: config.platform,
1088
+ capabilities: config.capabilities
1089
+ };
1090
+ if (config.auth?.token) {
1091
+ this._authState = {
1092
+ isAnonymous: false,
1093
+ token: config.auth.token,
1094
+ scopes: this.parseScopesFromToken(config.auth.token),
1095
+ user: this.parseUserFromToken(config.auth.token)
1096
+ };
1097
+ }
1098
+ this._interceptors = new DefaultInterceptorChain();
1099
+ }
1100
+ /**
1101
+ * Create a new McpTestClientBuilder for fluent configuration
1102
+ */
1103
+ static create(config) {
1104
+ return new McpTestClientBuilder(config);
1105
+ }
1106
+ // ═══════════════════════════════════════════════════════════════════
1107
+ // CONNECTION & LIFECYCLE
1108
+ // ═══════════════════════════════════════════════════════════════════
1109
+ /**
1110
+ * Connect to the MCP server and perform initialization
1111
+ */
1112
+ async connect() {
1113
+ this.log("debug", `Connecting to ${this.config.baseUrl}...`);
1114
+ this.transport = this.createTransport();
1115
+ await this.transport.connect();
1116
+ const initResponse = await this.initialize();
1117
+ if (!initResponse.success || !initResponse.data) {
1118
+ throw new Error(`Failed to initialize MCP connection: ${initResponse.error?.message ?? "Unknown error"}`);
1119
+ }
1120
+ this.initResult = initResponse.data;
1121
+ this._sessionId = this.transport.getSessionId();
1122
+ this._sessionInfo = {
1123
+ id: this._sessionId ?? `session-${Date.now()}`,
1124
+ createdAt: /* @__PURE__ */ new Date(),
1125
+ lastActivityAt: /* @__PURE__ */ new Date(),
1126
+ requestCount: 1
1127
+ };
1128
+ await this.transport.notify({
1129
+ jsonrpc: "2.0",
1130
+ method: "notifications/initialized"
1131
+ });
1132
+ this.log("info", `Connected to ${this.initResult.serverInfo?.name ?? "MCP Server"}`);
1133
+ return this.initResult;
1134
+ }
1135
+ /**
1136
+ * Disconnect from the MCP server
1137
+ */
1138
+ async disconnect() {
1139
+ if (this.transport) {
1140
+ await this.transport.close();
1141
+ this.transport = null;
1142
+ }
1143
+ this.initResult = null;
1144
+ this.log("info", "Disconnected from MCP server");
1145
+ }
1146
+ /**
1147
+ * Reconnect to the server, optionally with an existing session ID
1148
+ */
1149
+ async reconnect(options) {
1150
+ await this.disconnect();
1151
+ if (options?.sessionId && this.transport) {
1152
+ this._sessionId = options.sessionId;
1153
+ }
1154
+ await this.connect();
1155
+ }
1156
+ /**
1157
+ * Check if the client is currently connected
1158
+ */
1159
+ isConnected() {
1160
+ return this.transport?.isConnected() ?? false;
1161
+ }
1162
+ // ═══════════════════════════════════════════════════════════════════
1163
+ // SESSION & AUTH PROPERTIES
1164
+ // ═══════════════════════════════════════════════════════════════════
1165
+ get sessionId() {
1166
+ return this._sessionId ?? "";
1167
+ }
1168
+ get session() {
1169
+ const info = this._sessionInfo ?? {
1170
+ id: "",
1171
+ createdAt: /* @__PURE__ */ new Date(),
1172
+ lastActivityAt: /* @__PURE__ */ new Date(),
1173
+ requestCount: 0
1174
+ };
1175
+ return {
1176
+ ...info,
1177
+ expire: async () => {
1178
+ this._sessionId = void 0;
1179
+ this._sessionInfo = null;
1180
+ }
1181
+ };
1182
+ }
1183
+ get auth() {
1184
+ return this._authState;
1185
+ }
1186
+ /**
1187
+ * Authenticate with a token
1188
+ */
1189
+ async authenticate(token) {
1190
+ this._authState = {
1191
+ isAnonymous: false,
1192
+ token,
1193
+ scopes: this.parseScopesFromToken(token),
1194
+ user: this.parseUserFromToken(token)
1195
+ };
1196
+ if (this.transport) {
1197
+ this.transport.setAuthToken(token);
1198
+ }
1199
+ this.log("debug", "Authentication updated");
1200
+ }
1201
+ // ═══════════════════════════════════════════════════════════════════
1202
+ // SERVER INFO & CAPABILITIES
1203
+ // ═══════════════════════════════════════════════════════════════════
1204
+ get serverInfo() {
1205
+ return {
1206
+ name: this.initResult?.serverInfo?.name ?? "",
1207
+ version: this.initResult?.serverInfo?.version ?? ""
1208
+ };
1209
+ }
1210
+ get protocolVersion() {
1211
+ return this.initResult?.protocolVersion ?? "";
1212
+ }
1213
+ get instructions() {
1214
+ return this.initResult?.instructions ?? "";
1215
+ }
1216
+ get capabilities() {
1217
+ return this.initResult?.capabilities ?? {};
1218
+ }
1219
+ /**
1220
+ * Check if server has a specific capability
1221
+ */
1222
+ hasCapability(name) {
1223
+ return !!this.capabilities[name];
1224
+ }
1225
+ // ═══════════════════════════════════════════════════════════════════
1226
+ // TOOLS API
1227
+ // ═══════════════════════════════════════════════════════════════════
1228
+ tools = {
1229
+ /**
1230
+ * List all available tools
1231
+ */
1232
+ list: async () => {
1233
+ const response = await this.listTools();
1234
+ if (!response.success || !response.data) {
1235
+ throw new Error(`Failed to list tools: ${response.error?.message}`);
1236
+ }
1237
+ return response.data.tools;
1238
+ },
1239
+ /**
1240
+ * Call a tool by name with arguments
1241
+ */
1242
+ call: async (name, args) => {
1243
+ const response = await this.callTool(name, args);
1244
+ return this.wrapToolResult(response);
1245
+ }
1246
+ };
1247
+ // ═══════════════════════════════════════════════════════════════════
1248
+ // RESOURCES API
1249
+ // ═══════════════════════════════════════════════════════════════════
1250
+ resources = {
1251
+ /**
1252
+ * List all static resources
1253
+ */
1254
+ list: async () => {
1255
+ const response = await this.listResources();
1256
+ if (!response.success || !response.data) {
1257
+ throw new Error(`Failed to list resources: ${response.error?.message}`);
1258
+ }
1259
+ return response.data.resources;
1260
+ },
1261
+ /**
1262
+ * List all resource templates
1263
+ */
1264
+ listTemplates: async () => {
1265
+ const response = await this.listResourceTemplates();
1266
+ if (!response.success || !response.data) {
1267
+ throw new Error(`Failed to list resource templates: ${response.error?.message}`);
1268
+ }
1269
+ return response.data.resourceTemplates;
1270
+ },
1271
+ /**
1272
+ * Read a resource by URI
1273
+ */
1274
+ read: async (uri) => {
1275
+ const response = await this.readResource(uri);
1276
+ return this.wrapResourceContent(response);
1277
+ },
1278
+ /**
1279
+ * Subscribe to resource changes (placeholder for future implementation)
1280
+ */
1281
+ subscribe: async (_uri) => {
1282
+ this.log("warn", "Resource subscription not yet implemented");
1283
+ },
1284
+ /**
1285
+ * Unsubscribe from resource changes (placeholder for future implementation)
1286
+ */
1287
+ unsubscribe: async (_uri) => {
1288
+ this.log("warn", "Resource unsubscription not yet implemented");
1289
+ }
1290
+ };
1291
+ // ═══════════════════════════════════════════════════════════════════
1292
+ // PROMPTS API
1293
+ // ═══════════════════════════════════════════════════════════════════
1294
+ prompts = {
1295
+ /**
1296
+ * List all available prompts
1297
+ */
1298
+ list: async () => {
1299
+ const response = await this.listPrompts();
1300
+ if (!response.success || !response.data) {
1301
+ throw new Error(`Failed to list prompts: ${response.error?.message}`);
1302
+ }
1303
+ return response.data.prompts;
1304
+ },
1305
+ /**
1306
+ * Get a prompt with arguments
1307
+ */
1308
+ get: async (name, args) => {
1309
+ const response = await this.getPrompt(name, args);
1310
+ return this.wrapPromptResult(response);
1311
+ }
1312
+ };
1313
+ // ═══════════════════════════════════════════════════════════════════
1314
+ // RAW PROTOCOL ACCESS
1315
+ // ═══════════════════════════════════════════════════════════════════
1316
+ raw = {
1317
+ /**
1318
+ * Send any JSON-RPC request
1319
+ */
1320
+ request: async (message) => {
1321
+ this.ensureConnected();
1322
+ const start = Date.now();
1323
+ const response = await this.transport.request(message);
1324
+ this.traceRequest(message.method, message.params, message.id, response, Date.now() - start);
1325
+ return response;
1326
+ },
1327
+ /**
1328
+ * Send a notification (no response expected)
1329
+ */
1330
+ notify: async (message) => {
1331
+ this.ensureConnected();
1332
+ await this.transport.notify(message);
1333
+ },
1334
+ /**
1335
+ * Send raw string data (for error testing)
1336
+ */
1337
+ sendRaw: async (data) => {
1338
+ this.ensureConnected();
1339
+ return this.transport.sendRaw(data);
1340
+ }
1341
+ };
1342
+ get lastRequestId() {
1343
+ return this._lastRequestId;
1344
+ }
1345
+ // ═══════════════════════════════════════════════════════════════════
1346
+ // TRANSPORT INFO
1347
+ // ═══════════════════════════════════════════════════════════════════
1348
+ /**
1349
+ * Get transport information and utilities
1350
+ */
1351
+ get transport_info() {
1352
+ return {
1353
+ type: this.config.transport,
1354
+ isConnected: () => this.transport?.isConnected() ?? false,
1355
+ messageEndpoint: this.transport?.getMessageEndpoint?.(),
1356
+ connectionCount: this.transport?.getConnectionCount?.() ?? 0,
1357
+ reconnectCount: this.transport?.getReconnectCount?.() ?? 0,
1358
+ lastRequestHeaders: this.transport?.getLastRequestHeaders?.() ?? {},
1359
+ simulateDisconnect: async () => {
1360
+ await this.transport?.simulateDisconnect?.();
1361
+ },
1362
+ waitForReconnect: async (timeoutMs) => {
1363
+ await this.transport?.waitForReconnect?.(timeoutMs);
1364
+ }
1365
+ };
1366
+ }
1367
+ // Alias for transport info
1368
+ get transport_() {
1369
+ return this.transport_info;
1370
+ }
1371
+ // ═══════════════════════════════════════════════════════════════════
1372
+ // NOTIFICATIONS
1373
+ // ═══════════════════════════════════════════════════════════════════
1374
+ notifications = {
1375
+ /**
1376
+ * Start collecting server notifications
1377
+ */
1378
+ collect: () => {
1379
+ return new NotificationCollector(this._notifications);
1380
+ },
1381
+ /**
1382
+ * Collect progress notifications specifically
1383
+ */
1384
+ collectProgress: () => {
1385
+ return new ProgressCollector(this._progressUpdates);
1386
+ },
1387
+ /**
1388
+ * Send a notification to the server
1389
+ */
1390
+ send: async (method, params) => {
1391
+ await this.raw.notify({ jsonrpc: "2.0", method, params });
1392
+ }
1393
+ };
1394
+ // ═══════════════════════════════════════════════════════════════════
1395
+ // LOGGING & DEBUGGING
1396
+ // ═══════════════════════════════════════════════════════════════════
1397
+ logs = {
1398
+ all: () => [...this._logs],
1399
+ filter: (level) => this._logs.filter((l) => l.level === level),
1400
+ search: (text) => this._logs.filter((l) => l.message.includes(text)),
1401
+ last: () => this._logs[this._logs.length - 1],
1402
+ clear: () => {
1403
+ this._logs = [];
1404
+ }
1405
+ };
1406
+ trace = {
1407
+ all: () => [...this._traces],
1408
+ last: () => this._traces[this._traces.length - 1],
1409
+ clear: () => {
1410
+ this._traces = [];
1411
+ }
1412
+ };
1413
+ // ═══════════════════════════════════════════════════════════════════
1414
+ // MOCKING & INTERCEPTION
1415
+ // ═══════════════════════════════════════════════════════════════════
1416
+ /**
1417
+ * API for mocking MCP requests
1418
+ *
1419
+ * @example
1420
+ * ```typescript
1421
+ * // Mock a specific tool call
1422
+ * const handle = mcp.mock.tool('my-tool', { result: 'mocked!' });
1423
+ *
1424
+ * // Mock with params matching
1425
+ * mcp.mock.add({
1426
+ * method: 'tools/call',
1427
+ * params: { name: 'my-tool' },
1428
+ * response: mockResponse.toolResult([{ type: 'text', text: 'mocked' }]),
1429
+ * });
1430
+ *
1431
+ * // Clear all mocks after test
1432
+ * mcp.mock.clear();
1433
+ * ```
1434
+ */
1435
+ mock = {
1436
+ /**
1437
+ * Add a mock definition
1438
+ */
1439
+ add: (mock) => {
1440
+ return this._interceptors.mocks.add(mock);
1441
+ },
1442
+ /**
1443
+ * Mock a tools/call request for a specific tool
1444
+ */
1445
+ tool: (name, result, options) => {
1446
+ return this._interceptors.mocks.add({
1447
+ method: "tools/call",
1448
+ params: { name },
1449
+ response: mockResponse.toolResult([
1450
+ { type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }
1451
+ ]),
1452
+ times: options?.times,
1453
+ delay: options?.delay
1454
+ });
1455
+ },
1456
+ /**
1457
+ * Mock a tools/call request to return an error
1458
+ */
1459
+ toolError: (name, code, message, options) => {
1460
+ return this._interceptors.mocks.add({
1461
+ method: "tools/call",
1462
+ params: { name },
1463
+ response: mockResponse.error(code, message),
1464
+ times: options?.times
1465
+ });
1466
+ },
1467
+ /**
1468
+ * Mock a resources/read request
1469
+ */
1470
+ resource: (uri, content, options) => {
1471
+ const contentObj = typeof content === "string" ? { uri, text: content } : { uri, ...content };
1472
+ return this._interceptors.mocks.add({
1473
+ method: "resources/read",
1474
+ params: { uri },
1475
+ response: mockResponse.resourceRead([contentObj]),
1476
+ times: options?.times,
1477
+ delay: options?.delay
1478
+ });
1479
+ },
1480
+ /**
1481
+ * Mock a resources/read request to return an error
1482
+ */
1483
+ resourceError: (uri, options) => {
1484
+ return this._interceptors.mocks.add({
1485
+ method: "resources/read",
1486
+ params: { uri },
1487
+ response: mockResponse.errors.resourceNotFound(uri),
1488
+ times: options?.times
1489
+ });
1490
+ },
1491
+ /**
1492
+ * Mock the tools/list response
1493
+ */
1494
+ toolsList: (tools, options) => {
1495
+ return this._interceptors.mocks.add({
1496
+ method: "tools/list",
1497
+ response: mockResponse.toolsList(tools),
1498
+ times: options?.times
1499
+ });
1500
+ },
1501
+ /**
1502
+ * Mock the resources/list response
1503
+ */
1504
+ resourcesList: (resources, options) => {
1505
+ return this._interceptors.mocks.add({
1506
+ method: "resources/list",
1507
+ response: mockResponse.resourcesList(resources),
1508
+ times: options?.times
1509
+ });
1510
+ },
1511
+ /**
1512
+ * Clear all mocks
1513
+ */
1514
+ clear: () => {
1515
+ this._interceptors.mocks.clear();
1516
+ },
1517
+ /**
1518
+ * Get all active mocks
1519
+ */
1520
+ all: () => {
1521
+ return this._interceptors.mocks.getAll();
1522
+ }
1523
+ };
1524
+ /**
1525
+ * API for intercepting requests and responses
1526
+ *
1527
+ * @example
1528
+ * ```typescript
1529
+ * // Log all requests
1530
+ * const remove = mcp.intercept.request((ctx) => {
1531
+ * console.log('Request:', ctx.request.method);
1532
+ * return { action: 'passthrough' };
1533
+ * });
1534
+ *
1535
+ * // Modify requests
1536
+ * mcp.intercept.request((ctx) => {
1537
+ * if (ctx.request.method === 'tools/call') {
1538
+ * return {
1539
+ * action: 'modify',
1540
+ * request: { ...ctx.request, params: { ...ctx.request.params, extra: true } },
1541
+ * };
1542
+ * }
1543
+ * return { action: 'passthrough' };
1544
+ * });
1545
+ *
1546
+ * // Add latency to all requests
1547
+ * mcp.intercept.delay(100);
1548
+ *
1549
+ * // Clean up
1550
+ * remove();
1551
+ * mcp.intercept.clear();
1552
+ * ```
1553
+ */
1554
+ intercept = {
1555
+ /**
1556
+ * Add a request interceptor
1557
+ * @returns Function to remove the interceptor
1558
+ */
1559
+ request: (interceptor) => {
1560
+ return this._interceptors.addRequestInterceptor(interceptor);
1561
+ },
1562
+ /**
1563
+ * Add a response interceptor
1564
+ * @returns Function to remove the interceptor
1565
+ */
1566
+ response: (interceptor) => {
1567
+ return this._interceptors.addResponseInterceptor(interceptor);
1568
+ },
1569
+ /**
1570
+ * Add latency to all requests
1571
+ * @returns Function to remove the interceptor
1572
+ */
1573
+ delay: (ms) => {
1574
+ return this._interceptors.addRequestInterceptor(async () => {
1575
+ await new Promise((r) => setTimeout(r, ms));
1576
+ return { action: "passthrough" };
1577
+ });
1578
+ },
1579
+ /**
1580
+ * Fail requests matching a method
1581
+ * @returns Function to remove the interceptor
1582
+ */
1583
+ failMethod: (method, error) => {
1584
+ return this._interceptors.addRequestInterceptor((ctx) => {
1585
+ if (ctx.request.method === method) {
1586
+ return { action: "error", error: new Error(error ?? `Intercepted: ${method}`) };
1587
+ }
1588
+ return { action: "passthrough" };
1589
+ });
1590
+ },
1591
+ /**
1592
+ * Clear all interceptors (but not mocks)
1593
+ */
1594
+ clear: () => {
1595
+ this._interceptors.request = [];
1596
+ this._interceptors.response = [];
1597
+ },
1598
+ /**
1599
+ * Clear everything (interceptors and mocks)
1600
+ */
1601
+ clearAll: () => {
1602
+ this._interceptors.clear();
1603
+ }
1604
+ };
1605
+ // ═══════════════════════════════════════════════════════════════════
1606
+ // TIMEOUT
1607
+ // ═══════════════════════════════════════════════════════════════════
1608
+ setTimeout(ms) {
1609
+ this.config.timeout = ms;
1610
+ if (this.transport) {
1611
+ this.transport.setTimeout(ms);
1612
+ }
1613
+ }
1614
+ // ═══════════════════════════════════════════════════════════════════
1615
+ // PRIVATE: MCP OPERATIONS
1616
+ // ═══════════════════════════════════════════════════════════════════
1617
+ async initialize() {
1618
+ const capabilities = this.config.capabilities ?? {
1619
+ sampling: {}
1620
+ };
1621
+ return this.request("initialize", {
1622
+ protocolVersion: this.config.protocolVersion,
1623
+ capabilities,
1624
+ clientInfo: this.config.clientInfo
1625
+ });
1626
+ }
1627
+ async listTools() {
1628
+ return this.request("tools/list", {});
1629
+ }
1630
+ async callTool(name, args) {
1631
+ return this.request("tools/call", {
1632
+ name,
1633
+ arguments: args ?? {}
1634
+ });
1635
+ }
1636
+ async listResources() {
1637
+ return this.request("resources/list", {});
1638
+ }
1639
+ async listResourceTemplates() {
1640
+ return this.request("resources/templates/list", {});
1641
+ }
1642
+ async readResource(uri) {
1643
+ return this.request("resources/read", { uri });
1644
+ }
1645
+ async listPrompts() {
1646
+ return this.request("prompts/list", {});
1647
+ }
1648
+ async getPrompt(name, args) {
1649
+ return this.request("prompts/get", {
1650
+ name,
1651
+ arguments: args ?? {}
1652
+ });
1653
+ }
1654
+ // ═══════════════════════════════════════════════════════════════════
1655
+ // PRIVATE: TRANSPORT & REQUEST HELPERS
1656
+ // ═══════════════════════════════════════════════════════════════════
1657
+ createTransport() {
1658
+ switch (this.config.transport) {
1659
+ case "streamable-http":
1660
+ return new StreamableHttpTransport({
1661
+ baseUrl: this.config.baseUrl,
1662
+ timeout: this.config.timeout,
1663
+ auth: this.config.auth,
1664
+ publicMode: this.config.publicMode,
1665
+ debug: this.config.debug,
1666
+ interceptors: this._interceptors,
1667
+ clientInfo: this.config.clientInfo
1668
+ });
1669
+ case "sse":
1670
+ throw new Error("SSE transport not yet implemented");
1671
+ default:
1672
+ throw new Error(`Unknown transport type: ${this.config.transport}`);
1673
+ }
1674
+ }
1675
+ async request(method, params) {
1676
+ this.ensureConnected();
1677
+ const id = ++this.requestIdCounter;
1678
+ this._lastRequestId = id;
1679
+ const start = Date.now();
1680
+ try {
1681
+ const response = await this.transport.request({
1682
+ jsonrpc: "2.0",
1683
+ id,
1684
+ method,
1685
+ params
1686
+ });
1687
+ const durationMs = Date.now() - start;
1688
+ this.updateSessionActivity();
1689
+ if ("error" in response && response.error) {
1690
+ const error = response.error;
1691
+ this.traceRequest(method, params, id, response, durationMs);
1692
+ return {
1693
+ success: false,
1694
+ error,
1695
+ durationMs,
1696
+ requestId: id
1697
+ };
1698
+ }
1699
+ this.traceRequest(method, params, id, response, durationMs);
1700
+ return {
1701
+ success: true,
1702
+ data: response.result,
1703
+ durationMs,
1704
+ requestId: id
1705
+ };
1706
+ } catch (err) {
1707
+ const durationMs = Date.now() - start;
1708
+ const error = {
1709
+ code: -32603,
1710
+ message: err instanceof Error ? err.message : "Unknown error"
1711
+ };
1712
+ return {
1713
+ success: false,
1714
+ error,
1715
+ durationMs,
1716
+ requestId: id
1717
+ };
1718
+ }
1719
+ }
1720
+ ensureConnected() {
1721
+ if (!this.transport?.isConnected()) {
1722
+ throw new Error("Not connected to MCP server. Call connect() first.");
1723
+ }
1724
+ }
1725
+ updateSessionActivity() {
1726
+ if (this._sessionInfo) {
1727
+ this._sessionInfo.lastActivityAt = /* @__PURE__ */ new Date();
1728
+ this._sessionInfo.requestCount++;
1729
+ }
1730
+ }
1731
+ // ═══════════════════════════════════════════════════════════════════
1732
+ // PRIVATE: RESULT WRAPPERS
1733
+ // ═══════════════════════════════════════════════════════════════════
1734
+ wrapToolResult(response) {
1735
+ const raw = response.data ?? { content: [] };
1736
+ const isError2 = !response.success || raw.isError === true;
1737
+ const meta = raw._meta;
1738
+ const hasUI = meta?.["ui/html"] !== void 0 || meta?.["ui/component"] !== void 0 || meta?.["openai/html"] !== void 0 || meta?.["frontmcp/html"] !== void 0;
1739
+ const structuredContent = raw["structuredContent"];
1740
+ return {
1741
+ raw,
1742
+ isSuccess: !isError2,
1743
+ isError: isError2,
1744
+ error: response.error,
1745
+ durationMs: response.durationMs,
1746
+ json() {
1747
+ if (hasUI && structuredContent !== void 0) {
1748
+ return structuredContent;
1749
+ }
1750
+ const textContent = raw.content?.find((c) => c.type === "text");
1751
+ if (textContent && "text" in textContent) {
1752
+ return JSON.parse(textContent.text);
1753
+ }
1754
+ throw new Error("No text content to parse as JSON");
1755
+ },
1756
+ text() {
1757
+ const textContent = raw.content?.find((c) => c.type === "text");
1758
+ if (textContent && "text" in textContent) {
1759
+ return textContent.text;
1760
+ }
1761
+ return void 0;
1762
+ },
1763
+ hasTextContent() {
1764
+ return raw.content?.some((c) => c.type === "text") ?? false;
1765
+ },
1766
+ hasImageContent() {
1767
+ return raw.content?.some((c) => c.type === "image") ?? false;
1768
+ },
1769
+ hasResourceContent() {
1770
+ return raw.content?.some((c) => c.type === "resource") ?? false;
1771
+ },
1772
+ hasToolUI() {
1773
+ return hasUI;
1774
+ }
1775
+ };
1776
+ }
1777
+ wrapResourceContent(response) {
1778
+ const raw = response.data ?? { contents: [] };
1779
+ const isError2 = !response.success;
1780
+ const firstContent = raw.contents?.[0];
1781
+ return {
1782
+ raw,
1783
+ isSuccess: !isError2,
1784
+ isError: isError2,
1785
+ error: response.error,
1786
+ durationMs: response.durationMs,
1787
+ json() {
1788
+ if (firstContent && "text" in firstContent) {
1789
+ return JSON.parse(firstContent.text);
1790
+ }
1791
+ throw new Error("No text content to parse as JSON");
1792
+ },
1793
+ text() {
1794
+ if (firstContent && "text" in firstContent) {
1795
+ return firstContent.text;
1796
+ }
1797
+ return void 0;
1798
+ },
1799
+ mimeType() {
1800
+ return firstContent?.mimeType;
1801
+ },
1802
+ hasMimeType(type) {
1803
+ return firstContent?.mimeType === type;
1804
+ }
1805
+ };
1806
+ }
1807
+ wrapPromptResult(response) {
1808
+ const raw = response.data ?? { messages: [] };
1809
+ const isError2 = !response.success;
1810
+ return {
1811
+ raw,
1812
+ isSuccess: !isError2,
1813
+ isError: isError2,
1814
+ error: response.error,
1815
+ durationMs: response.durationMs,
1816
+ messages: raw.messages ?? [],
1817
+ description: raw.description
1818
+ };
1819
+ }
1820
+ // ═══════════════════════════════════════════════════════════════════
1821
+ // PRIVATE: LOGGING & TRACING
1822
+ // ═══════════════════════════════════════════════════════════════════
1823
+ log(level, message, data) {
1824
+ const entry = {
1825
+ level,
1826
+ message,
1827
+ timestamp: /* @__PURE__ */ new Date(),
1828
+ data
1829
+ };
1830
+ this._logs.push(entry);
1831
+ if (this.config.debug) {
1832
+ console.log(`[${level.toUpperCase()}] ${message}`, data ?? "");
1833
+ }
1834
+ }
1835
+ traceRequest(method, params, id, response, durationMs) {
1836
+ this._traces.push({
1837
+ request: { method, params, id },
1838
+ response: {
1839
+ result: "result" in response ? response.result : void 0,
1840
+ error: "error" in response ? response.error : void 0
1841
+ },
1842
+ durationMs,
1843
+ timestamp: /* @__PURE__ */ new Date()
1844
+ });
1845
+ }
1846
+ // ═══════════════════════════════════════════════════════════════════
1847
+ // PRIVATE: TOKEN PARSING
1848
+ // ═══════════════════════════════════════════════════════════════════
1849
+ parseScopesFromToken(token) {
1850
+ try {
1851
+ const payload = this.decodeJwtPayload(token);
1852
+ if (!payload) return [];
1853
+ const scope = payload["scope"];
1854
+ const scopes = payload["scopes"];
1855
+ if (typeof scope === "string") {
1856
+ return scope.split(" ");
1857
+ }
1858
+ if (Array.isArray(scopes)) {
1859
+ return scopes;
1860
+ }
1861
+ return [];
1862
+ } catch {
1863
+ return [];
1864
+ }
1865
+ }
1866
+ parseUserFromToken(token) {
1867
+ try {
1868
+ const payload = this.decodeJwtPayload(token);
1869
+ const sub = payload?.["sub"];
1870
+ if (!sub || typeof sub !== "string") return void 0;
1871
+ return {
1872
+ sub,
1873
+ email: payload["email"],
1874
+ name: payload["name"]
1875
+ };
1876
+ } catch {
1877
+ return void 0;
1878
+ }
1879
+ }
1880
+ decodeJwtPayload(token) {
1881
+ try {
1882
+ const parts = token.split(".");
1883
+ if (parts.length !== 3) return null;
1884
+ const payload = Buffer.from(parts[1], "base64url").toString("utf-8");
1885
+ return JSON.parse(payload);
1886
+ } catch {
1887
+ return null;
1888
+ }
1889
+ }
1890
+ };
1891
+ var NotificationCollector = class {
1892
+ constructor(notifications) {
1893
+ this.notifications = notifications;
1894
+ }
1895
+ get received() {
1896
+ return [...this.notifications];
1897
+ }
1898
+ has(method) {
1899
+ return this.notifications.some((n) => n.method === method);
1900
+ }
1901
+ async waitFor(method, timeoutMs) {
1902
+ const deadline = Date.now() + timeoutMs;
1903
+ while (Date.now() < deadline) {
1904
+ const found = this.notifications.find((n) => n.method === method);
1905
+ if (found) return found;
1906
+ await new Promise((r) => setTimeout(r, 50));
1907
+ }
1908
+ throw new Error(`Timeout waiting for notification: ${method}`);
1909
+ }
1910
+ };
1911
+ var ProgressCollector = class {
1912
+ constructor(updates) {
1913
+ this.updates = updates;
1914
+ }
1915
+ get all() {
1916
+ return [...this.updates];
1917
+ }
1918
+ async waitForComplete(timeoutMs) {
1919
+ const deadline = Date.now() + timeoutMs;
1920
+ while (Date.now() < deadline) {
1921
+ const last = this.updates[this.updates.length - 1];
1922
+ if (last && last.total !== void 0 && last.progress >= last.total) {
1923
+ return;
1924
+ }
1925
+ await new Promise((r) => setTimeout(r, 50));
1926
+ }
1927
+ throw new Error("Timeout waiting for progress to complete");
1928
+ }
1929
+ };
1930
+
1931
+ // libs/testing/src/auth/token-factory.ts
1932
+ var import_jose = require("jose");
1933
+ var TestTokenFactory = class {
1934
+ issuer;
1935
+ audience;
1936
+ privateKey = null;
1937
+ publicKey = null;
1938
+ jwk = null;
1939
+ keyId;
1940
+ constructor(options = {}) {
1941
+ this.issuer = options.issuer ?? "https://test.frontmcp.local";
1942
+ this.audience = options.audience ?? "frontmcp-test";
1943
+ this.keyId = `test-key-${Date.now()}`;
1944
+ }
1945
+ /**
1946
+ * Initialize the key pair (called automatically on first use)
1947
+ */
1948
+ async ensureKeys() {
1949
+ if (this.privateKey && this.publicKey) return;
1950
+ const { publicKey, privateKey } = await (0, import_jose.generateKeyPair)("RS256", {
1951
+ extractable: true
1952
+ });
1953
+ this.privateKey = privateKey;
1954
+ this.publicKey = publicKey;
1955
+ this.jwk = await (0, import_jose.exportJWK)(publicKey);
1956
+ this.jwk.kid = this.keyId;
1957
+ this.jwk.use = "sig";
1958
+ this.jwk.alg = "RS256";
1959
+ }
1960
+ /**
1961
+ * Create a JWT token with the specified claims
1962
+ */
1963
+ async createTestToken(options) {
1964
+ await this.ensureKeys();
1965
+ const now = Math.floor(Date.now() / 1e3);
1966
+ const exp = options.exp ?? 3600;
1967
+ const payload = {
1968
+ iss: options.iss ?? this.issuer,
1969
+ sub: options.sub,
1970
+ aud: options.aud ?? this.audience,
1971
+ iat: now,
1972
+ exp: now + exp,
1973
+ scope: options.scopes?.join(" "),
1974
+ ...options.claims
1975
+ };
1976
+ const token = await new import_jose.SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: this.keyId }).sign(this.privateKey);
1977
+ return token;
1978
+ }
1979
+ /**
1980
+ * Create an admin token with full access
1981
+ */
1982
+ async createAdminToken(sub = "admin-001") {
1983
+ return this.createTestToken({
1984
+ sub,
1985
+ scopes: ["admin:*", "read", "write", "delete"],
1986
+ claims: {
1987
+ email: "admin@test.local",
1988
+ name: "Test Admin",
1989
+ role: "admin"
1990
+ }
1991
+ });
1992
+ }
1993
+ /**
1994
+ * Create a regular user token
1995
+ */
1996
+ async createUserToken(sub = "user-001", scopes = ["read", "write"]) {
1997
+ return this.createTestToken({
1998
+ sub,
1999
+ scopes,
2000
+ claims: {
2001
+ email: "user@test.local",
2002
+ name: "Test User",
2003
+ role: "user"
2004
+ }
2005
+ });
2006
+ }
2007
+ /**
2008
+ * Create an anonymous user token
2009
+ */
2010
+ async createAnonymousToken() {
2011
+ return this.createTestToken({
2012
+ sub: `anon:${Date.now()}`,
2013
+ scopes: ["anonymous"],
2014
+ claims: {
2015
+ name: "Anonymous",
2016
+ role: "anonymous"
2017
+ }
2018
+ });
2019
+ }
2020
+ /**
2021
+ * Create an expired token (for testing token expiration)
2022
+ */
2023
+ async createExpiredToken(options) {
2024
+ await this.ensureKeys();
2025
+ const now = Math.floor(Date.now() / 1e3);
2026
+ const payload = {
2027
+ iss: this.issuer,
2028
+ sub: options.sub,
2029
+ aud: this.audience,
2030
+ iat: now - 7200,
2031
+ // 2 hours ago
2032
+ exp: now - 3600
2033
+ // Expired 1 hour ago
2034
+ };
2035
+ const token = await new import_jose.SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: this.keyId }).sign(this.privateKey);
2036
+ return token;
2037
+ }
2038
+ /**
2039
+ * Create a token with an invalid signature (for testing signature validation)
2040
+ */
2041
+ createTokenWithInvalidSignature(options) {
2042
+ const now = Math.floor(Date.now() / 1e3);
2043
+ const header = Buffer.from(JSON.stringify({ alg: "RS256", kid: this.keyId })).toString("base64url");
2044
+ const payload = Buffer.from(
2045
+ JSON.stringify({
2046
+ iss: this.issuer,
2047
+ sub: options.sub,
2048
+ aud: this.audience,
2049
+ iat: now,
2050
+ exp: now + 3600
2051
+ })
2052
+ ).toString("base64url");
2053
+ const signature = Buffer.from("invalid-signature-" + Date.now()).toString("base64url");
2054
+ return `${header}.${payload}.${signature}`;
2055
+ }
2056
+ /**
2057
+ * Get the public JWKS for verifying tokens
2058
+ */
2059
+ async getPublicJwks() {
2060
+ await this.ensureKeys();
2061
+ return {
2062
+ keys: [this.jwk]
2063
+ };
2064
+ }
2065
+ /**
2066
+ * Get the issuer URL
2067
+ */
2068
+ getIssuer() {
2069
+ return this.issuer;
2070
+ }
2071
+ /**
2072
+ * Get the audience
2073
+ */
2074
+ getAudience() {
2075
+ return this.audience;
2076
+ }
2077
+ };
2078
+
2079
+ // libs/testing/src/auth/auth-headers.ts
2080
+ var AuthHeaders = {
2081
+ /**
2082
+ * Create Authorization header with Bearer token
2083
+ */
2084
+ bearer(token) {
2085
+ return {
2086
+ Authorization: `Bearer ${token}`
2087
+ };
2088
+ },
2089
+ /**
2090
+ * Create headers with no authentication
2091
+ */
2092
+ noAuth() {
2093
+ return {};
2094
+ },
2095
+ /**
2096
+ * Create full MCP request headers with auth and session
2097
+ */
2098
+ mcpRequest(token, sessionId) {
2099
+ const headers = {
2100
+ "Content-Type": "application/json",
2101
+ Accept: "application/json",
2102
+ Authorization: `Bearer ${token}`
2103
+ };
2104
+ if (sessionId) {
2105
+ headers["mcp-session-id"] = sessionId;
2106
+ }
2107
+ return headers;
2108
+ },
2109
+ /**
2110
+ * Create headers for public mode (no auth required)
2111
+ */
2112
+ publicMode(sessionId) {
2113
+ const headers = {
2114
+ "Content-Type": "application/json",
2115
+ Accept: "application/json"
2116
+ };
2117
+ if (sessionId) {
2118
+ headers["mcp-session-id"] = sessionId;
2119
+ }
2120
+ return headers;
2121
+ },
2122
+ /**
2123
+ * Create headers with custom auth header value
2124
+ */
2125
+ custom(headerName, headerValue) {
2126
+ return {
2127
+ [headerName]: headerValue
2128
+ };
2129
+ }
2130
+ };
2131
+
2132
+ // libs/testing/src/auth/user-fixtures.ts
2133
+ var TestUsers = {
2134
+ /**
2135
+ * Admin user with full access
2136
+ */
2137
+ admin: {
2138
+ sub: "admin-001",
2139
+ email: "admin@test.local",
2140
+ name: "Test Admin",
2141
+ scopes: ["admin:*", "read", "write", "delete"],
2142
+ role: "admin"
2143
+ },
2144
+ /**
2145
+ * Regular user with read/write access
2146
+ */
2147
+ user: {
2148
+ sub: "user-001",
2149
+ email: "user@test.local",
2150
+ name: "Test User",
2151
+ scopes: ["read", "write"],
2152
+ role: "user"
2153
+ },
2154
+ /**
2155
+ * Read-only user
2156
+ */
2157
+ readOnly: {
2158
+ sub: "readonly-001",
2159
+ email: "readonly@test.local",
2160
+ name: "Read Only User",
2161
+ scopes: ["read"],
2162
+ role: "readonly"
2163
+ },
2164
+ /**
2165
+ * Anonymous user
2166
+ */
2167
+ anonymous: {
2168
+ sub: "anon:001",
2169
+ name: "Anonymous",
2170
+ scopes: ["anonymous"],
2171
+ role: "anonymous"
2172
+ },
2173
+ /**
2174
+ * User with no scopes (for testing access denied)
2175
+ */
2176
+ noScopes: {
2177
+ sub: "noscopes-001",
2178
+ email: "noscopes@test.local",
2179
+ name: "No Scopes User",
2180
+ scopes: [],
2181
+ role: "user"
2182
+ },
2183
+ /**
2184
+ * User with only tool execution scope
2185
+ */
2186
+ toolsOnly: {
2187
+ sub: "toolsonly-001",
2188
+ email: "toolsonly@test.local",
2189
+ name: "Tools Only User",
2190
+ scopes: ["tools:execute"],
2191
+ role: "user"
2192
+ },
2193
+ /**
2194
+ * User with only resource read scope
2195
+ */
2196
+ resourcesOnly: {
2197
+ sub: "resourcesonly-001",
2198
+ email: "resourcesonly@test.local",
2199
+ name: "Resources Only User",
2200
+ scopes: ["resources:read"],
2201
+ role: "user"
2202
+ }
2203
+ };
2204
+ function createTestUser(overrides) {
2205
+ return {
2206
+ scopes: [],
2207
+ ...overrides
2208
+ };
2209
+ }
2210
+
2211
+ // libs/testing/src/auth/mock-oauth-server.ts
2212
+ var import_http = require("http");
2213
+ var MockOAuthServer = class {
2214
+ tokenFactory;
2215
+ options;
2216
+ server = null;
2217
+ _info = null;
2218
+ connections = /* @__PURE__ */ new Set();
2219
+ constructor(tokenFactory2, options = {}) {
2220
+ this.tokenFactory = tokenFactory2;
2221
+ this.options = options;
2222
+ }
2223
+ /**
2224
+ * Start the mock OAuth server
2225
+ */
2226
+ async start() {
2227
+ if (this.server) {
2228
+ throw new Error("Mock OAuth server is already running");
2229
+ }
2230
+ const port = this.options.port ?? 0;
2231
+ return new Promise((resolve, reject) => {
2232
+ const server = (0, import_http.createServer)(this.handleRequest.bind(this));
2233
+ this.server = server;
2234
+ server.on("connection", (socket) => {
2235
+ this.connections.add(socket);
2236
+ socket.on("close", () => this.connections.delete(socket));
2237
+ });
2238
+ server.on("error", (err) => {
2239
+ this.log(`Server error: ${err.message}`);
2240
+ reject(err);
2241
+ });
2242
+ server.listen(port, () => {
2243
+ const address = server.address();
2244
+ if (!address || typeof address === "string") {
2245
+ reject(new Error("Failed to get server address"));
2246
+ return;
2247
+ }
2248
+ const actualPort = address.port;
2249
+ const issuer = this.options.issuer ?? `http://localhost:${actualPort}`;
2250
+ this._info = {
2251
+ baseUrl: `http://localhost:${actualPort}`,
2252
+ port: actualPort,
2253
+ issuer,
2254
+ jwksUrl: `http://localhost:${actualPort}/.well-known/jwks.json`
2255
+ };
2256
+ this.log(`Mock OAuth server started at ${this._info.baseUrl}`);
2257
+ resolve(this._info);
2258
+ });
2259
+ });
2260
+ }
2261
+ /**
2262
+ * Stop the mock OAuth server
2263
+ */
2264
+ async stop() {
2265
+ const server = this.server;
2266
+ if (!server) {
2267
+ return;
2268
+ }
2269
+ for (const socket of this.connections) {
2270
+ socket.destroy();
2271
+ }
2272
+ this.connections.clear();
2273
+ return new Promise((resolve, reject) => {
2274
+ server.close((err) => {
2275
+ if (err) {
2276
+ reject(err);
2277
+ } else {
2278
+ this.server = null;
2279
+ this._info = null;
2280
+ this.log("Mock OAuth server stopped");
2281
+ resolve();
2282
+ }
2283
+ });
2284
+ });
2285
+ }
2286
+ /**
2287
+ * Get server info
2288
+ */
2289
+ get info() {
2290
+ if (!this._info) {
2291
+ throw new Error("Mock OAuth server is not running");
2292
+ }
2293
+ return this._info;
2294
+ }
2295
+ /**
2296
+ * Get the token factory (for creating tokens)
2297
+ */
2298
+ getTokenFactory() {
2299
+ return this.tokenFactory;
2300
+ }
2301
+ // ═══════════════════════════════════════════════════════════════════
2302
+ // PRIVATE
2303
+ // ═══════════════════════════════════════════════════════════════════
2304
+ async handleRequest(req, res) {
2305
+ const url = req.url ?? "/";
2306
+ this.log(`${req.method} ${url}`);
2307
+ res.setHeader("Access-Control-Allow-Origin", "*");
2308
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
2309
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
2310
+ if (req.method === "OPTIONS") {
2311
+ res.writeHead(204);
2312
+ res.end();
2313
+ return;
2314
+ }
2315
+ try {
2316
+ if (url === "/.well-known/jwks.json" || url === "/.well-known/jwks") {
2317
+ await this.handleJwks(req, res);
2318
+ } else if (url === "/.well-known/openid-configuration") {
2319
+ await this.handleOidcConfig(req, res);
2320
+ } else if (url === "/.well-known/oauth-authorization-server") {
2321
+ await this.handleOAuthMetadata(req, res);
2322
+ } else if (url === "/oauth/token") {
2323
+ await this.handleTokenEndpoint(req, res);
2324
+ } else {
2325
+ res.writeHead(404, { "Content-Type": "application/json" });
2326
+ res.end(JSON.stringify({ error: "not_found", error_description: "Endpoint not found" }));
2327
+ }
2328
+ } catch (error) {
2329
+ this.log(`Error handling request: ${error}`);
2330
+ res.writeHead(500, { "Content-Type": "application/json" });
2331
+ res.end(JSON.stringify({ error: "server_error", error_description: "Internal server error" }));
2332
+ }
2333
+ }
2334
+ async handleJwks(_req, res) {
2335
+ const jwks = await this.tokenFactory.getPublicJwks();
2336
+ res.writeHead(200, { "Content-Type": "application/json" });
2337
+ res.end(JSON.stringify(jwks));
2338
+ this.log("Served JWKS");
2339
+ }
2340
+ async handleOidcConfig(_req, res) {
2341
+ const issuer = this._info?.issuer ?? "http://localhost";
2342
+ const config = {
2343
+ issuer,
2344
+ authorization_endpoint: `${issuer}/oauth/authorize`,
2345
+ token_endpoint: `${issuer}/oauth/token`,
2346
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
2347
+ response_types_supported: ["code", "token"],
2348
+ subject_types_supported: ["public"],
2349
+ id_token_signing_alg_values_supported: ["RS256"],
2350
+ scopes_supported: ["openid", "profile", "email"],
2351
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
2352
+ claims_supported: ["sub", "iss", "aud", "exp", "iat", "email", "name"],
2353
+ grant_types_supported: ["authorization_code", "refresh_token", "client_credentials", "anonymous"]
2354
+ };
2355
+ res.writeHead(200, { "Content-Type": "application/json" });
2356
+ res.end(JSON.stringify(config));
2357
+ this.log("Served OIDC configuration");
2358
+ }
2359
+ async handleOAuthMetadata(_req, res) {
2360
+ const issuer = this._info?.issuer ?? "http://localhost";
2361
+ const metadata = {
2362
+ issuer,
2363
+ authorization_endpoint: `${issuer}/oauth/authorize`,
2364
+ token_endpoint: `${issuer}/oauth/token`,
2365
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
2366
+ response_types_supported: ["code", "token"],
2367
+ grant_types_supported: ["authorization_code", "refresh_token", "client_credentials", "anonymous"],
2368
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
2369
+ scopes_supported: ["openid", "profile", "email", "anonymous"]
2370
+ };
2371
+ res.writeHead(200, { "Content-Type": "application/json" });
2372
+ res.end(JSON.stringify(metadata));
2373
+ this.log("Served OAuth metadata");
2374
+ }
2375
+ async handleTokenEndpoint(req, res) {
2376
+ const body = await this.readBody(req);
2377
+ const params = new URLSearchParams(body);
2378
+ const grantType = params.get("grant_type");
2379
+ if (grantType === "anonymous") {
2380
+ const token = await this.tokenFactory.createAnonymousToken();
2381
+ res.writeHead(200, { "Content-Type": "application/json" });
2382
+ res.end(
2383
+ JSON.stringify({
2384
+ access_token: token,
2385
+ token_type: "Bearer",
2386
+ expires_in: 3600
2387
+ })
2388
+ );
2389
+ this.log("Issued anonymous token");
2390
+ } else {
2391
+ res.writeHead(400, { "Content-Type": "application/json" });
2392
+ res.end(
2393
+ JSON.stringify({
2394
+ error: "unsupported_grant_type",
2395
+ error_description: "Only anonymous grant type is supported in mock server"
2396
+ })
2397
+ );
2398
+ }
2399
+ }
2400
+ readBody(req) {
2401
+ return new Promise((resolve, reject) => {
2402
+ const chunks = [];
2403
+ req.on("data", (chunk) => chunks.push(chunk));
2404
+ req.on("end", () => resolve(Buffer.concat(chunks).toString()));
2405
+ req.on("error", reject);
2406
+ });
2407
+ }
2408
+ log(message) {
2409
+ if (this.options.debug) {
2410
+ console.log(`[MockOAuthServer] ${message}`);
2411
+ }
2412
+ }
2413
+ };
2414
+
2415
+ // libs/testing/src/auth/mock-api-server.ts
2416
+ var import_http2 = require("http");
2417
+ var MockAPIServer = class {
2418
+ options;
2419
+ server = null;
2420
+ _info = null;
2421
+ routes;
2422
+ constructor(options) {
2423
+ this.options = options;
2424
+ this.routes = options.routes ?? [];
2425
+ }
2426
+ /**
2427
+ * Start the mock API server
2428
+ */
2429
+ async start() {
2430
+ if (this.server) {
2431
+ throw new Error("Mock API server is already running");
2432
+ }
2433
+ const port = this.options.port ?? 0;
2434
+ return new Promise((resolve, reject) => {
2435
+ this.server = (0, import_http2.createServer)(this.handleRequest.bind(this));
2436
+ this.server.on("error", (err) => {
2437
+ this.log(`Server error: ${err.message}`);
2438
+ reject(err);
2439
+ });
2440
+ this.server.listen(port, () => {
2441
+ const address = this.server.address();
2442
+ if (!address || typeof address === "string") {
2443
+ reject(new Error("Failed to get server address"));
2444
+ return;
2445
+ }
2446
+ const actualPort = address.port;
2447
+ this._info = {
2448
+ baseUrl: `http://localhost:${actualPort}`,
2449
+ port: actualPort,
2450
+ specUrl: `http://localhost:${actualPort}/openapi.json`
2451
+ };
2452
+ this.log(`Mock API server started at ${this._info.baseUrl}`);
2453
+ resolve(this._info);
2454
+ });
2455
+ });
2456
+ }
2457
+ /**
2458
+ * Stop the mock API server
2459
+ */
2460
+ async stop() {
2461
+ if (!this.server) {
2462
+ return;
2463
+ }
2464
+ return new Promise((resolve, reject) => {
2465
+ this.server.close((err) => {
2466
+ if (err) {
2467
+ reject(err);
2468
+ } else {
2469
+ this.server = null;
2470
+ this._info = null;
2471
+ this.log("Mock API server stopped");
2472
+ resolve();
2473
+ }
2474
+ });
2475
+ });
2476
+ }
2477
+ /**
2478
+ * Get server info
2479
+ */
2480
+ get info() {
2481
+ if (!this._info) {
2482
+ throw new Error("Mock API server is not running");
2483
+ }
2484
+ return this._info;
2485
+ }
2486
+ /**
2487
+ * Add a route dynamically
2488
+ */
2489
+ addRoute(route) {
2490
+ this.routes.push(route);
2491
+ }
2492
+ /**
2493
+ * Clear all routes
2494
+ */
2495
+ clearRoutes() {
2496
+ this.routes = [];
2497
+ }
2498
+ // ═══════════════════════════════════════════════════════════════════
2499
+ // PRIVATE
2500
+ // ═══════════════════════════════════════════════════════════════════
2501
+ async handleRequest(req, res) {
2502
+ const url = req.url ?? "/";
2503
+ const method = (req.method ?? "GET").toUpperCase();
2504
+ this.log(`${method} ${url}`);
2505
+ res.setHeader("Access-Control-Allow-Origin", "*");
2506
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
2507
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
2508
+ if (method === "OPTIONS") {
2509
+ res.writeHead(204);
2510
+ res.end();
2511
+ return;
2512
+ }
2513
+ try {
2514
+ if (url === "/openapi.json" || url === "/openapi.yaml") {
2515
+ res.writeHead(200, { "Content-Type": "application/json" });
2516
+ res.end(JSON.stringify(this.options.openApiSpec));
2517
+ this.log("Served OpenAPI spec");
2518
+ return;
2519
+ }
2520
+ const route = this.findRoute(method, url);
2521
+ if (route) {
2522
+ const status = route.response.status ?? 200;
2523
+ const headers = {
2524
+ "Content-Type": "application/json",
2525
+ ...route.response.headers
2526
+ };
2527
+ res.writeHead(status, headers);
2528
+ res.end(JSON.stringify(route.response.body));
2529
+ this.log(`Matched route: ${method} ${route.path} -> ${status}`);
2530
+ return;
2531
+ }
2532
+ res.writeHead(404, { "Content-Type": "application/json" });
2533
+ res.end(JSON.stringify({ error: "not_found", message: `No mock for ${method} ${url}` }));
2534
+ } catch (error) {
2535
+ this.log(`Error handling request: ${error}`);
2536
+ res.writeHead(500, { "Content-Type": "application/json" });
2537
+ res.end(JSON.stringify({ error: "server_error", message: "Internal server error" }));
2538
+ }
2539
+ }
2540
+ findRoute(method, url) {
2541
+ const path = url.split("?")[0];
2542
+ return this.routes.find((route) => {
2543
+ if (route.method !== method) return false;
2544
+ if (route.path === path) return true;
2545
+ const routeParts = route.path.split("/");
2546
+ const urlParts = path.split("/");
2547
+ if (routeParts.length !== urlParts.length) return false;
2548
+ return routeParts.every((part, i) => {
2549
+ if (part.startsWith(":")) return true;
2550
+ return part === urlParts[i];
2551
+ });
2552
+ });
2553
+ }
2554
+ log(message) {
2555
+ if (this.options.debug) {
2556
+ console.log(`[MockAPIServer] ${message}`);
2557
+ }
2558
+ }
2559
+ };
2560
+
2561
+ // libs/testing/src/server/test-server.ts
2562
+ var import_child_process = require("child_process");
2563
+ var TestServer = class _TestServer {
2564
+ process = null;
2565
+ options;
2566
+ _info;
2567
+ logs = [];
2568
+ constructor(options, port) {
2569
+ this.options = {
2570
+ port,
2571
+ command: options.command ?? "",
2572
+ cwd: options.cwd ?? process.cwd(),
2573
+ env: options.env ?? {},
2574
+ startupTimeout: options.startupTimeout ?? 3e4,
2575
+ healthCheckPath: options.healthCheckPath ?? "/health",
2576
+ debug: options.debug ?? false
2577
+ };
2578
+ this._info = {
2579
+ baseUrl: `http://localhost:${port}`,
2580
+ port
2581
+ };
2582
+ }
2583
+ /**
2584
+ * Start a test server with custom command
2585
+ */
2586
+ static async start(options) {
2587
+ const port = options.port ?? await findAvailablePort();
2588
+ const server = new _TestServer(options, port);
2589
+ try {
2590
+ await server.startProcess();
2591
+ } catch (error) {
2592
+ await server.stop();
2593
+ throw error;
2594
+ }
2595
+ return server;
2596
+ }
2597
+ /**
2598
+ * Start an Nx project as test server
2599
+ */
2600
+ static async startNx(project, options = {}) {
2601
+ if (!/^[\w-]+$/.test(project)) {
2602
+ throw new Error(
2603
+ `Invalid project name: ${project}. Must contain only alphanumeric, underscore, and hyphen characters.`
2604
+ );
2605
+ }
2606
+ const port = options.port ?? await findAvailablePort();
2607
+ const serverOptions = {
2608
+ ...options,
2609
+ port,
2610
+ command: `npx nx serve ${project} --port ${port}`,
2611
+ cwd: options.cwd ?? process.cwd()
2612
+ };
2613
+ const server = new _TestServer(serverOptions, port);
2614
+ try {
2615
+ await server.startProcess();
2616
+ } catch (error) {
2617
+ await server.stop();
2618
+ throw error;
2619
+ }
2620
+ return server;
2621
+ }
2622
+ /**
2623
+ * Create a test server connected to an already running server
2624
+ */
2625
+ static connect(baseUrl) {
2626
+ const url = new URL(baseUrl);
2627
+ const port = parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80);
2628
+ const server = new _TestServer(
2629
+ {
2630
+ command: "",
2631
+ port
2632
+ },
2633
+ port
2634
+ );
2635
+ server._info = {
2636
+ baseUrl: baseUrl.replace(/\/$/, ""),
2637
+ port
2638
+ };
2639
+ return server;
2640
+ }
2641
+ /**
2642
+ * Get server information
2643
+ */
2644
+ get info() {
2645
+ return { ...this._info };
2646
+ }
2647
+ /**
2648
+ * Stop the test server
2649
+ */
2650
+ async stop() {
2651
+ if (this.process) {
2652
+ this.log("Stopping server...");
2653
+ this.process.kill("SIGTERM");
2654
+ const exitPromise = new Promise((resolve) => {
2655
+ if (this.process) {
2656
+ this.process.once("exit", () => resolve());
2657
+ } else {
2658
+ resolve();
2659
+ }
2660
+ });
2661
+ const killTimeout = setTimeout(() => {
2662
+ if (this.process) {
2663
+ this.log("Force killing server after timeout...");
2664
+ this.process.kill("SIGKILL");
2665
+ }
2666
+ }, 5e3);
2667
+ await exitPromise;
2668
+ clearTimeout(killTimeout);
2669
+ this.process = null;
2670
+ this.log("Server stopped");
2671
+ }
2672
+ }
2673
+ /**
2674
+ * Wait for server to be ready
2675
+ */
2676
+ async waitForReady(timeout) {
2677
+ const timeoutMs = timeout ?? this.options.startupTimeout;
2678
+ const deadline = Date.now() + timeoutMs;
2679
+ const checkInterval = 100;
2680
+ while (Date.now() < deadline) {
2681
+ try {
2682
+ const response = await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`, {
2683
+ method: "GET",
2684
+ signal: AbortSignal.timeout(1e3)
2685
+ });
2686
+ if (response.ok || response.status === 404) {
2687
+ this.log("Server is ready");
2688
+ return;
2689
+ }
2690
+ } catch {
2691
+ }
2692
+ await sleep2(checkInterval);
2693
+ }
2694
+ throw new Error(`Server did not become ready within ${timeoutMs}ms`);
2695
+ }
2696
+ /**
2697
+ * Restart the server
2698
+ */
2699
+ async restart() {
2700
+ await this.stop();
2701
+ await this.startProcess();
2702
+ }
2703
+ /**
2704
+ * Get captured server logs
2705
+ */
2706
+ getLogs() {
2707
+ return [...this.logs];
2708
+ }
2709
+ /**
2710
+ * Clear captured logs
2711
+ */
2712
+ clearLogs() {
2713
+ this.logs = [];
2714
+ }
2715
+ // ═══════════════════════════════════════════════════════════════════
2716
+ // PRIVATE METHODS
2717
+ // ═══════════════════════════════════════════════════════════════════
2718
+ async startProcess() {
2719
+ if (!this.options.command) {
2720
+ await this.waitForReady();
2721
+ return;
2722
+ }
2723
+ this.log(`Starting server: ${this.options.command}`);
2724
+ const env = {
2725
+ ...process.env,
2726
+ ...this.options.env,
2727
+ PORT: String(this.options.port)
2728
+ };
2729
+ this.process = (0, import_child_process.spawn)(this.options.command, [], {
2730
+ cwd: this.options.cwd,
2731
+ env,
2732
+ shell: true,
2733
+ stdio: ["pipe", "pipe", "pipe"]
2734
+ });
2735
+ if (this.process.pid !== void 0) {
2736
+ this._info.pid = this.process.pid;
2737
+ }
2738
+ let processExited = false;
2739
+ let exitCode = null;
2740
+ let exitError = null;
2741
+ this.process.stdout?.on("data", (data) => {
2742
+ const text = data.toString();
2743
+ this.logs.push(text);
2744
+ if (this.options.debug) {
2745
+ console.log("[SERVER]", text);
2746
+ }
2747
+ });
2748
+ this.process.stderr?.on("data", (data) => {
2749
+ const text = data.toString();
2750
+ this.logs.push(`[ERROR] ${text}`);
2751
+ if (this.options.debug) {
2752
+ console.error("[SERVER ERROR]", text);
2753
+ }
2754
+ });
2755
+ this.process.on("error", (err) => {
2756
+ this.logs.push(`[SPAWN ERROR] ${err.message}`);
2757
+ exitError = err;
2758
+ if (this.options.debug) {
2759
+ console.error("[SERVER SPAWN ERROR]", err);
2760
+ }
2761
+ });
2762
+ this.process.once("exit", (code) => {
2763
+ processExited = true;
2764
+ exitCode = code;
2765
+ this.log(`Server process exited with code ${code}`);
2766
+ });
2767
+ await this.waitForReadyWithExitDetection(() => {
2768
+ if (exitError) {
2769
+ return { exited: true, error: exitError };
2770
+ }
2771
+ if (processExited) {
2772
+ const recentLogs = this.logs.slice(-10).join("\n");
2773
+ return {
2774
+ exited: true,
2775
+ error: new Error(`Server process exited unexpectedly with code ${exitCode}.
2776
+
2777
+ Recent logs:
2778
+ ${recentLogs}`)
2779
+ };
2780
+ }
2781
+ return { exited: false };
2782
+ });
2783
+ }
2784
+ /**
2785
+ * Wait for server to be ready, but also detect early process exit
2786
+ */
2787
+ async waitForReadyWithExitDetection(checkExit) {
2788
+ const timeoutMs = this.options.startupTimeout;
2789
+ const deadline = Date.now() + timeoutMs;
2790
+ const checkInterval = 100;
2791
+ while (Date.now() < deadline) {
2792
+ const exitStatus = checkExit();
2793
+ if (exitStatus.exited) {
2794
+ throw exitStatus.error ?? new Error("Server process exited unexpectedly");
2795
+ }
2796
+ try {
2797
+ const response = await fetch(`${this._info.baseUrl}${this.options.healthCheckPath}`, {
2798
+ method: "GET",
2799
+ signal: AbortSignal.timeout(1e3)
2800
+ });
2801
+ if (response.ok || response.status === 404) {
2802
+ this.log("Server is ready");
2803
+ return;
2804
+ }
2805
+ } catch {
2806
+ }
2807
+ await sleep2(checkInterval);
2808
+ }
2809
+ const finalExitStatus = checkExit();
2810
+ if (finalExitStatus.exited) {
2811
+ throw finalExitStatus.error ?? new Error("Server process exited unexpectedly");
2812
+ }
2813
+ throw new Error(`Server did not become ready within ${timeoutMs}ms`);
2814
+ }
2815
+ log(message) {
2816
+ if (this.options.debug) {
2817
+ console.log(`[TestServer] ${message}`);
2818
+ }
2819
+ }
2820
+ };
2821
+ async function findAvailablePort() {
2822
+ const { createServer: createServer3 } = await import("net");
2823
+ return new Promise((resolve, reject) => {
2824
+ const server = createServer3();
2825
+ server.listen(0, () => {
2826
+ const address = server.address();
2827
+ if (address && typeof address !== "string") {
2828
+ const port = address.port;
2829
+ server.close(() => resolve(port));
2830
+ } else {
2831
+ reject(new Error("Could not get port"));
2832
+ }
2833
+ });
2834
+ server.on("error", reject);
2835
+ });
2836
+ }
2837
+ function sleep2(ms) {
2838
+ return new Promise((resolve) => setTimeout(resolve, ms));
2839
+ }
2840
+
2841
+ // libs/testing/src/assertions/mcp-assertions.ts
2842
+ var McpAssertions = {
2843
+ /**
2844
+ * Assert that an MCP response was successful and return the data
2845
+ * @throws Error if response was not successful
2846
+ */
2847
+ assertSuccess(response, message) {
2848
+ if (!response.success) {
2849
+ const errorMsg = response.error?.message ?? "Unknown error";
2850
+ throw new Error(message ?? `Expected success but got error: ${errorMsg} (code: ${response.error?.code})`);
2851
+ }
2852
+ if (response.data === void 0) {
2853
+ throw new Error(message ?? "Expected data but got undefined");
2854
+ }
2855
+ return response.data;
2856
+ },
2857
+ /**
2858
+ * Assert that an MCP response was an error
2859
+ * @param expectedCode Optional expected error code
2860
+ */
2861
+ assertError(response, expectedCode) {
2862
+ if (response.success) {
2863
+ throw new Error("Expected error but got success");
2864
+ }
2865
+ if (!response.error) {
2866
+ throw new Error("Expected error info but got undefined");
2867
+ }
2868
+ if (expectedCode !== void 0 && response.error.code !== expectedCode) {
2869
+ throw new Error(`Expected error code ${expectedCode} but got ${response.error.code}: ${response.error.message}`);
2870
+ }
2871
+ return response.error;
2872
+ },
2873
+ /**
2874
+ * Assert that a tool call was successful (not isError)
2875
+ */
2876
+ assertToolSuccess(result) {
2877
+ if ("raw" in result) {
2878
+ if (result.isError) {
2879
+ throw new Error(`Tool call failed: ${result.error?.message ?? "Unknown error"}`);
2880
+ }
2881
+ } else {
2882
+ if (!result.success) {
2883
+ throw new Error(`Tool call failed: ${result.error?.message ?? "Unknown error"}`);
2884
+ }
2885
+ if (result.data?.isError) {
2886
+ throw new Error("Tool returned isError=true");
2887
+ }
2888
+ }
2889
+ },
2890
+ /**
2891
+ * Assert that a tool result has specific content type
2892
+ */
2893
+ assertToolContent(result, type) {
2894
+ let content;
2895
+ if ("raw" in result) {
2896
+ content = result.raw.content;
2897
+ } else {
2898
+ if (!result.success || !result.data) {
2899
+ throw new Error("Tool call was not successful");
2900
+ }
2901
+ content = result.data.content;
2902
+ }
2903
+ const hasContent = content?.some((c) => c.type === type);
2904
+ if (!hasContent) {
2905
+ throw new Error(`Expected tool result to have ${type} content`);
2906
+ }
2907
+ },
2908
+ /**
2909
+ * Assert that a resource read was successful and return the text content
2910
+ */
2911
+ assertTextResource(response) {
2912
+ if ("raw" in response) {
2913
+ if (response.isError) {
2914
+ throw new Error(`Resource read failed: ${response.error?.message ?? "Unknown error"}`);
2915
+ }
2916
+ const text = response.text();
2917
+ if (text === void 0) {
2918
+ throw new Error("Expected text content but got undefined");
2919
+ }
2920
+ return text;
2921
+ } else {
2922
+ if (!response.success || !response.data) {
2923
+ throw new Error(`Resource read failed: ${response.error?.message ?? "Unknown error"}`);
2924
+ }
2925
+ const content = response.data.contents?.[0];
2926
+ if (!content || !("text" in content)) {
2927
+ throw new Error("Expected text content but got undefined");
2928
+ }
2929
+ return content.text;
2930
+ }
2931
+ },
2932
+ /**
2933
+ * Assert that tools array contains a tool with given name
2934
+ */
2935
+ assertContainsTool(tools, name) {
2936
+ const tool = tools.find((t) => t.name === name);
2937
+ if (!tool) {
2938
+ const available = tools.map((t) => t.name).join(", ");
2939
+ throw new Error(`Expected to find tool "${name}" but got: [${available}]`);
2940
+ }
2941
+ return tool;
2942
+ },
2943
+ /**
2944
+ * Assert that resources array contains a resource with given URI
2945
+ */
2946
+ assertContainsResource(resources, uri) {
2947
+ const resource = resources.find((r) => r.uri === uri);
2948
+ if (!resource) {
2949
+ const available = resources.map((r) => r.uri).join(", ");
2950
+ throw new Error(`Expected to find resource "${uri}" but got: [${available}]`);
2951
+ }
2952
+ return resource;
2953
+ },
2954
+ /**
2955
+ * Assert that resource templates array contains a template with given URI template
2956
+ */
2957
+ assertContainsResourceTemplate(templates, uriTemplate) {
2958
+ const template = templates.find((t) => t.uriTemplate === uriTemplate);
2959
+ if (!template) {
2960
+ const available = templates.map((t) => t.uriTemplate).join(", ");
2961
+ throw new Error(`Expected to find resource template "${uriTemplate}" but got: [${available}]`);
2962
+ }
2963
+ return template;
2964
+ },
2965
+ /**
2966
+ * Assert that prompts array contains a prompt with given name
2967
+ */
2968
+ assertContainsPrompt(prompts, name) {
2969
+ const prompt = prompts.find((p) => p.name === name);
2970
+ if (!prompt) {
2971
+ const available = prompts.map((p) => p.name).join(", ");
2972
+ throw new Error(`Expected to find prompt "${name}" but got: [${available}]`);
2973
+ }
2974
+ return prompt;
2975
+ }
2976
+ };
2977
+ function containsTool(tools, name) {
2978
+ return tools.some((t) => t.name === name);
2979
+ }
2980
+ function containsResource(resources, uri) {
2981
+ return resources.some((r) => r.uri === uri);
2982
+ }
2983
+ function containsResourceTemplate(templates, uriTemplate) {
2984
+ return templates.some((t) => t.uriTemplate === uriTemplate);
2985
+ }
2986
+ function containsPrompt(prompts, name) {
2987
+ return prompts.some((p) => p.name === name);
2988
+ }
2989
+ function isSuccessful(result) {
2990
+ return result.isSuccess;
2991
+ }
2992
+ function isError(result, expectedCode) {
2993
+ if (!result.isError) return false;
2994
+ if (expectedCode !== void 0) {
2995
+ return result.error?.code === expectedCode;
2996
+ }
2997
+ return true;
2998
+ }
2999
+ function hasTextContent(result) {
3000
+ return result.hasTextContent();
3001
+ }
3002
+ function hasMimeType(result, mimeType) {
3003
+ return result.hasMimeType(mimeType);
3004
+ }
3005
+
3006
+ // libs/testing/src/errors/index.ts
3007
+ var TestClientError = class extends Error {
3008
+ constructor(message) {
3009
+ super(message);
3010
+ this.name = "TestClientError";
3011
+ Object.setPrototypeOf(this, new.target.prototype);
3012
+ }
3013
+ };
3014
+ var ConnectionError = class extends TestClientError {
3015
+ constructor(message, cause) {
3016
+ super(message);
3017
+ this.cause = cause;
3018
+ this.name = "ConnectionError";
3019
+ Object.setPrototypeOf(this, new.target.prototype);
3020
+ }
3021
+ };
3022
+ var TimeoutError = class extends TestClientError {
3023
+ constructor(message, timeoutMs) {
3024
+ super(message);
3025
+ this.timeoutMs = timeoutMs;
3026
+ this.name = "TimeoutError";
3027
+ Object.setPrototypeOf(this, new.target.prototype);
3028
+ }
3029
+ };
3030
+ var McpProtocolError = class extends TestClientError {
3031
+ constructor(message, code, data) {
3032
+ super(message);
3033
+ this.code = code;
3034
+ this.data = data;
3035
+ this.name = "McpProtocolError";
3036
+ Object.setPrototypeOf(this, new.target.prototype);
3037
+ }
3038
+ };
3039
+ var ServerStartError = class extends TestClientError {
3040
+ constructor(message, cause) {
3041
+ super(message);
3042
+ this.cause = cause;
3043
+ this.name = "ServerStartError";
3044
+ Object.setPrototypeOf(this, new.target.prototype);
3045
+ }
3046
+ };
3047
+ var AssertionError = class extends TestClientError {
3048
+ constructor(message) {
3049
+ super(message);
3050
+ this.name = "AssertionError";
3051
+ Object.setPrototypeOf(this, new.target.prototype);
3052
+ }
3053
+ };
3054
+
3055
+ // libs/testing/src/fixtures/test-fixture.ts
3056
+ var currentConfig = {};
3057
+ var serverInstance = null;
3058
+ var tokenFactory = null;
3059
+ var serverStartedByUs = false;
3060
+ async function initializeSharedResources() {
3061
+ if (!tokenFactory) {
3062
+ tokenFactory = new TestTokenFactory();
3063
+ }
3064
+ if (!serverInstance) {
3065
+ if (currentConfig.baseUrl) {
3066
+ serverInstance = TestServer.connect(currentConfig.baseUrl);
3067
+ serverStartedByUs = false;
3068
+ } else if (currentConfig.server) {
3069
+ serverInstance = await TestServer.start({
3070
+ port: currentConfig.port,
3071
+ command: resolveServerCommand(currentConfig.server),
3072
+ env: currentConfig.env,
3073
+ startupTimeout: currentConfig.startupTimeout ?? 3e4,
3074
+ debug: currentConfig.logLevel === "debug"
3075
+ });
3076
+ serverStartedByUs = true;
3077
+ } else {
3078
+ throw new Error(
3079
+ 'test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option'
3080
+ );
3081
+ }
3082
+ }
3083
+ }
3084
+ async function createTestFixtures() {
3085
+ await initializeSharedResources();
3086
+ const clientInstance = await McpTestClient.create({
3087
+ baseUrl: serverInstance.info.baseUrl,
3088
+ transport: currentConfig.transport ?? "streamable-http",
3089
+ publicMode: currentConfig.publicMode
3090
+ }).buildAndConnect();
3091
+ const auth = createAuthFixture(tokenFactory);
3092
+ const server = createServerFixture(serverInstance);
3093
+ return {
3094
+ mcp: clientInstance,
3095
+ auth,
3096
+ server
3097
+ };
3098
+ }
3099
+ async function cleanupTestFixtures(fixtures, _testFailed = false) {
3100
+ if (fixtures.mcp.isConnected()) {
3101
+ await fixtures.mcp.disconnect();
3102
+ }
3103
+ }
3104
+ async function cleanupSharedResources() {
3105
+ if (serverInstance && serverStartedByUs) {
3106
+ await serverInstance.stop();
3107
+ }
3108
+ serverInstance = null;
3109
+ tokenFactory = null;
3110
+ serverStartedByUs = false;
3111
+ }
3112
+ function createAuthFixture(factory) {
3113
+ const users = {
3114
+ admin: {
3115
+ sub: "admin-001",
3116
+ scopes: ["admin:*", "read", "write", "delete"],
3117
+ email: "admin@test.local",
3118
+ name: "Test Admin"
3119
+ },
3120
+ user: {
3121
+ sub: "user-001",
3122
+ scopes: ["read", "write"],
3123
+ email: "user@test.local",
3124
+ name: "Test User"
3125
+ },
3126
+ readOnly: {
3127
+ sub: "readonly-001",
3128
+ scopes: ["read"],
3129
+ email: "readonly@test.local",
3130
+ name: "Read Only User"
3131
+ }
3132
+ };
3133
+ return {
3134
+ createToken: (opts) => factory.createTestToken({
3135
+ sub: opts.sub,
3136
+ scopes: opts.scopes,
3137
+ claims: {
3138
+ email: opts.email,
3139
+ name: opts.name,
3140
+ ...opts.claims
3141
+ },
3142
+ exp: opts.expiresIn
3143
+ }),
3144
+ createExpiredToken: (opts) => factory.createExpiredToken(opts),
3145
+ createInvalidToken: (opts) => factory.createTokenWithInvalidSignature(opts),
3146
+ users: {
3147
+ admin: users["admin"],
3148
+ user: users["user"],
3149
+ readOnly: users["readOnly"]
3150
+ },
3151
+ getJwks: () => factory.getPublicJwks(),
3152
+ getIssuer: () => factory.getIssuer(),
3153
+ getAudience: () => factory.getAudience()
3154
+ };
3155
+ }
3156
+ function createServerFixture(server) {
3157
+ return {
3158
+ info: server.info,
3159
+ createClient: async (opts) => {
3160
+ return McpTestClient.create({
3161
+ baseUrl: server.info.baseUrl,
3162
+ transport: opts?.transport ?? "streamable-http",
3163
+ auth: opts?.token ? { token: opts.token } : void 0,
3164
+ clientInfo: opts?.clientInfo,
3165
+ publicMode: currentConfig.publicMode
3166
+ }).buildAndConnect();
3167
+ },
3168
+ createClientBuilder: () => {
3169
+ const builder = new McpTestClientBuilder({
3170
+ baseUrl: server.info.baseUrl,
3171
+ publicMode: currentConfig.publicMode
3172
+ });
3173
+ return builder;
3174
+ },
3175
+ restart: () => server.restart(),
3176
+ getLogs: () => server.getLogs(),
3177
+ clearLogs: () => server.clearLogs()
3178
+ };
3179
+ }
3180
+ function resolveServerCommand(server) {
3181
+ if (server.includes(" ")) {
3182
+ return server;
3183
+ }
3184
+ return `npx tsx ${server}`;
3185
+ }
3186
+ function testWithFixtures(name, fn) {
3187
+ it(name, async () => {
3188
+ const fixtures = await createTestFixtures();
3189
+ let testFailed = false;
3190
+ try {
3191
+ await fn(fixtures);
3192
+ } catch (error) {
3193
+ testFailed = true;
3194
+ throw error;
3195
+ } finally {
3196
+ await cleanupTestFixtures(fixtures, testFailed);
3197
+ }
3198
+ });
3199
+ }
3200
+ function use(config) {
3201
+ currentConfig = { ...currentConfig, ...config };
3202
+ afterAll(async () => {
3203
+ await cleanupSharedResources();
3204
+ });
3205
+ }
3206
+ function skip(name, fn) {
3207
+ it.skip(name, async () => {
3208
+ const fixtures = await createTestFixtures();
3209
+ let testFailed = false;
3210
+ try {
3211
+ await fn(fixtures);
3212
+ } catch (error) {
3213
+ testFailed = true;
3214
+ throw error;
3215
+ } finally {
3216
+ await cleanupTestFixtures(fixtures, testFailed);
3217
+ }
3218
+ });
3219
+ }
3220
+ function only(name, fn) {
3221
+ it.only(name, async () => {
3222
+ const fixtures = await createTestFixtures();
3223
+ let testFailed = false;
3224
+ try {
3225
+ await fn(fixtures);
3226
+ } catch (error) {
3227
+ testFailed = true;
3228
+ throw error;
3229
+ } finally {
3230
+ await cleanupTestFixtures(fixtures, testFailed);
3231
+ }
3232
+ });
3233
+ }
3234
+ function todo(name) {
3235
+ it.todo(name);
3236
+ }
3237
+ var test = testWithFixtures;
3238
+ test.use = use;
3239
+ test.describe = describe;
3240
+ test.beforeAll = beforeAll;
3241
+ test.beforeEach = beforeEach;
3242
+ test.afterEach = afterEach;
3243
+ test.afterAll = afterAll;
3244
+ test.skip = skip;
3245
+ test.only = only;
3246
+ test.todo = todo;
3247
+
3248
+ // libs/testing/src/expect.ts
3249
+ var import_globals = require("@jest/globals");
3250
+ var expect = import_globals.expect;
3251
+
3252
+ // libs/testing/src/platform/platform-types.ts
3253
+ function getPlatformMetaNamespace(platform) {
3254
+ switch (platform) {
3255
+ case "openai":
3256
+ return "openai";
3257
+ case "ext-apps":
3258
+ return "ui";
3259
+ default:
3260
+ return "frontmcp";
3261
+ }
3262
+ }
3263
+ function getPlatformMimeType(platform) {
3264
+ return platform === "openai" ? "text/html+skybridge" : "text/html+mcp";
3265
+ }
3266
+ function isOpenAIPlatform(platform) {
3267
+ return platform === "openai";
3268
+ }
3269
+ function isExtAppsPlatform(platform) {
3270
+ return platform === "ext-apps";
3271
+ }
3272
+ function isFrontmcpPlatform(platform) {
3273
+ return platform !== "openai" && platform !== "ext-apps";
3274
+ }
3275
+ function getToolsListMetaPrefixes(platform) {
3276
+ switch (platform) {
3277
+ case "openai":
3278
+ return ["openai/"];
3279
+ case "ext-apps":
3280
+ return ["ui/"];
3281
+ default:
3282
+ return ["frontmcp/", "ui/"];
3283
+ }
3284
+ }
3285
+ function getToolCallMetaPrefixes(platform) {
3286
+ switch (platform) {
3287
+ case "openai":
3288
+ return ["openai/"];
3289
+ case "ext-apps":
3290
+ return ["ui/"];
3291
+ default:
3292
+ return ["frontmcp/", "ui/"];
3293
+ }
3294
+ }
3295
+ function getForbiddenMetaPrefixes(platform) {
3296
+ switch (platform) {
3297
+ case "openai":
3298
+ return ["ui/", "frontmcp/"];
3299
+ case "ext-apps":
3300
+ return ["openai/", "frontmcp/"];
3301
+ default:
3302
+ return ["openai/"];
3303
+ }
3304
+ }
3305
+
3306
+ // libs/testing/src/ui/ui-matchers.ts
3307
+ function escapeRegex(str) {
3308
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3309
+ }
3310
+ function extractUiHtml(received) {
3311
+ if (typeof received === "string") {
3312
+ return received;
3313
+ }
3314
+ const wrapper = received;
3315
+ const meta = wrapper?.raw?._meta || wrapper?._meta;
3316
+ if (meta && typeof meta === "object") {
3317
+ const uiHtml = meta["ui/html"];
3318
+ if (typeof uiHtml === "string") {
3319
+ return uiHtml;
3320
+ }
3321
+ }
3322
+ return void 0;
3323
+ }
3324
+ function extractMeta(received) {
3325
+ const wrapper = received;
3326
+ const meta = wrapper?.raw?._meta || wrapper?._meta;
3327
+ if (meta && typeof meta === "object") {
3328
+ return meta;
3329
+ }
3330
+ return void 0;
3331
+ }
3332
+ var toHaveRenderedHtml = function(received) {
3333
+ const html = extractUiHtml(received);
3334
+ const hasHtml = html !== void 0 && html.length > 0;
3335
+ const isFallback = hasHtml && html.includes("mdx-fallback");
3336
+ const pass = hasHtml && !isFallback;
3337
+ return {
3338
+ pass,
3339
+ message: () => {
3340
+ if (isFallback) {
3341
+ return "Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed.";
3342
+ }
3343
+ if (!hasHtml) {
3344
+ return "Expected _meta to have ui/html property with rendered HTML";
3345
+ }
3346
+ return "Expected result not to have rendered HTML";
3347
+ }
3348
+ };
3349
+ };
3350
+ var toContainHtmlElement = function(received, tag) {
3351
+ const html = extractUiHtml(received);
3352
+ if (!html) {
3353
+ return {
3354
+ pass: false,
3355
+ message: () => `Expected to find <${tag}> element, but no HTML content found`
3356
+ };
3357
+ }
3358
+ const regex = new RegExp(`<${escapeRegex(tag)}[\\s>]`, "i");
3359
+ const pass = regex.test(html);
3360
+ return {
3361
+ pass,
3362
+ message: () => pass ? `Expected HTML not to contain <${tag}> element` : `Expected HTML to contain <${tag}> element`
3363
+ };
3364
+ };
3365
+ var toContainBoundValue = function(received, value) {
3366
+ const html = extractUiHtml(received);
3367
+ if (!html) {
3368
+ return {
3369
+ pass: false,
3370
+ message: () => `Expected HTML to contain bound value "${value}", but no HTML content found`
3371
+ };
3372
+ }
3373
+ const stringValue = String(value);
3374
+ const pass = html.includes(stringValue);
3375
+ return {
3376
+ pass,
3377
+ message: () => pass ? `Expected HTML not to contain bound value "${stringValue}"` : `Expected HTML to contain bound value "${stringValue}"`
3378
+ };
3379
+ };
3380
+ var toBeXssSafe = function(received) {
3381
+ const html = extractUiHtml(received);
3382
+ if (!html) {
3383
+ return {
3384
+ pass: true,
3385
+ message: () => "Expected HTML to be XSS unsafe (no HTML found)"
3386
+ };
3387
+ }
3388
+ const hasScript = /<script[\s>]/i.test(html);
3389
+ const hasOnHandler = /\son\w+\s*=/i.test(html);
3390
+ const hasJavascriptUri = /javascript:/i.test(html);
3391
+ const issues = [];
3392
+ if (hasScript) issues.push("<script> tag");
3393
+ if (hasOnHandler) issues.push("inline event handler (onclick, etc.)");
3394
+ if (hasJavascriptUri) issues.push("javascript: URI");
3395
+ const pass = !hasScript && !hasOnHandler && !hasJavascriptUri;
3396
+ return {
3397
+ pass,
3398
+ message: () => pass ? "Expected HTML not to be XSS safe" : `Expected HTML to be XSS safe, but found: ${issues.join(", ")}`
3399
+ };
3400
+ };
3401
+ var toHaveWidgetMetadata = function(received) {
3402
+ const meta = extractMeta(received);
3403
+ if (!meta) {
3404
+ return {
3405
+ pass: false,
3406
+ message: () => "Expected _meta to have widget metadata, but no _meta found"
3407
+ };
3408
+ }
3409
+ const hasUiHtml = Boolean(meta["ui/html"]);
3410
+ const hasOutputTemplate = Boolean(meta["openai/outputTemplate"]);
3411
+ const hasMimeType2 = Boolean(meta["ui/mimeType"]);
3412
+ const pass = hasUiHtml || hasOutputTemplate || hasMimeType2;
3413
+ return {
3414
+ pass,
3415
+ message: () => pass ? "Expected result not to have widget metadata" : "Expected _meta to have widget metadata (ui/html, openai/outputTemplate, or ui/mimeType)"
3416
+ };
3417
+ };
3418
+ var toHaveCssClass = function(received, className) {
3419
+ const html = extractUiHtml(received);
3420
+ if (!html) {
3421
+ return {
3422
+ pass: false,
3423
+ message: () => `Expected HTML to have CSS class "${className}", but no HTML content found`
3424
+ };
3425
+ }
3426
+ const classRegex = new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`, "i");
3427
+ const pass = classRegex.test(html);
3428
+ return {
3429
+ pass,
3430
+ message: () => pass ? `Expected HTML not to have CSS class "${className}"` : `Expected HTML to have CSS class "${className}"`
3431
+ };
3432
+ };
3433
+ var toNotContainRawContent = function(received, content) {
3434
+ const html = extractUiHtml(received);
3435
+ if (!html) {
3436
+ return {
3437
+ pass: true,
3438
+ message: () => `Expected HTML to contain raw content "${content}", but no HTML found`
3439
+ };
3440
+ }
3441
+ const pass = !html.includes(content);
3442
+ return {
3443
+ pass,
3444
+ message: () => pass ? `Expected HTML to contain raw content "${content}"` : `Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`
3445
+ };
3446
+ };
3447
+ var toHaveProperHtmlStructure = function(received) {
3448
+ const html = extractUiHtml(received);
3449
+ if (!html) {
3450
+ return {
3451
+ pass: false,
3452
+ message: () => "Expected proper HTML structure, but no HTML content found"
3453
+ };
3454
+ }
3455
+ const hasEscapedTags = html.includes("&lt;") && html.includes("&gt;");
3456
+ const hasHtmlTags = /<[a-z]/i.test(html);
3457
+ const pass = hasHtmlTags && !hasEscapedTags;
3458
+ return {
3459
+ pass,
3460
+ message: () => {
3461
+ if (hasEscapedTags) {
3462
+ return "Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered";
3463
+ }
3464
+ if (!hasHtmlTags) {
3465
+ return "Expected proper HTML structure, but found no HTML tags";
3466
+ }
3467
+ return "Expected result not to have proper HTML structure";
3468
+ }
3469
+ };
3470
+ };
3471
+ var toHavePlatformMeta = function(received, platform) {
3472
+ const meta = extractMeta(received);
3473
+ if (!meta) {
3474
+ return {
3475
+ pass: false,
3476
+ message: () => `Expected _meta to have platform meta for "${platform}", but no _meta found`
3477
+ };
3478
+ }
3479
+ const expectedPrefixes = getToolCallMetaPrefixes(platform);
3480
+ const forbiddenPrefixes = getForbiddenMetaPrefixes(platform);
3481
+ const metaKeys = Object.keys(meta);
3482
+ const hasExpectedPrefix = metaKeys.some((key) => expectedPrefixes.some((prefix) => key.startsWith(prefix)));
3483
+ const forbiddenKeys = metaKeys.filter((key) => forbiddenPrefixes.some((prefix) => key.startsWith(prefix)));
3484
+ const pass = hasExpectedPrefix && forbiddenKeys.length === 0;
3485
+ return {
3486
+ pass,
3487
+ message: () => {
3488
+ if (!hasExpectedPrefix) {
3489
+ return `Expected _meta to have keys with prefixes [${expectedPrefixes.join(
3490
+ ", "
3491
+ )}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`;
3492
+ }
3493
+ if (forbiddenKeys.length > 0) {
3494
+ return `Expected _meta NOT to have keys [${forbiddenKeys.join(
3495
+ ", "
3496
+ )}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`;
3497
+ }
3498
+ return `Expected result not to have platform meta for "${platform}"`;
3499
+ }
3500
+ };
3501
+ };
3502
+ var toHaveMetaKey = function(received, key) {
3503
+ const meta = extractMeta(received);
3504
+ if (!meta) {
3505
+ return {
3506
+ pass: false,
3507
+ message: () => `Expected _meta to have key "${key}", but no _meta found`
3508
+ };
3509
+ }
3510
+ const pass = key in meta;
3511
+ return {
3512
+ pass,
3513
+ message: () => pass ? `Expected _meta not to have key "${key}"` : `Expected _meta to have key "${key}"`
3514
+ };
3515
+ };
3516
+ var toHaveMetaValue = function(received, key, value) {
3517
+ const meta = extractMeta(received);
3518
+ if (!meta) {
3519
+ return {
3520
+ pass: false,
3521
+ message: () => `Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`
3522
+ };
3523
+ }
3524
+ const actualValue = meta[key];
3525
+ const pass = JSON.stringify(actualValue) === JSON.stringify(value);
3526
+ return {
3527
+ pass,
3528
+ message: () => pass ? `Expected _meta["${key}"] not to equal ${JSON.stringify(value)}` : `Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`
3529
+ };
3530
+ };
3531
+ var toNotHaveMetaKey = function(received, key) {
3532
+ const meta = extractMeta(received);
3533
+ if (!meta) {
3534
+ return {
3535
+ pass: true,
3536
+ message: () => `Expected _meta to have key "${key}", but no _meta found`
3537
+ };
3538
+ }
3539
+ const pass = !(key in meta);
3540
+ return {
3541
+ pass,
3542
+ message: () => pass ? `Expected _meta to have key "${key}"` : `Expected _meta not to have key "${key}"`
3543
+ };
3544
+ };
3545
+ var toHaveOnlyNamespacedMeta = function(received, namespace) {
3546
+ const meta = extractMeta(received);
3547
+ if (!meta) {
3548
+ return {
3549
+ pass: false,
3550
+ message: () => `Expected _meta to have keys with namespace "${namespace}", but no _meta found`
3551
+ };
3552
+ }
3553
+ const metaKeys = Object.keys(meta);
3554
+ const wrongKeys = metaKeys.filter((key) => !key.startsWith(namespace));
3555
+ const pass = wrongKeys.length === 0 && metaKeys.length > 0;
3556
+ return {
3557
+ pass,
3558
+ message: () => {
3559
+ if (metaKeys.length === 0) {
3560
+ return `Expected _meta to have keys with namespace "${namespace}", but _meta is empty`;
3561
+ }
3562
+ if (wrongKeys.length > 0) {
3563
+ return `Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`;
3564
+ }
3565
+ return `Expected _meta not to have only keys with namespace "${namespace}"`;
3566
+ }
3567
+ };
3568
+ };
3569
+ var toHavePlatformMimeType = function(received, platform) {
3570
+ const meta = extractMeta(received);
3571
+ const expectedMimeType = getPlatformMimeType(platform);
3572
+ if (!meta) {
3573
+ return {
3574
+ pass: false,
3575
+ message: () => `Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`
3576
+ };
3577
+ }
3578
+ let mimeTypeKey;
3579
+ switch (platform) {
3580
+ case "openai":
3581
+ mimeTypeKey = "openai/mimeType";
3582
+ break;
3583
+ case "ext-apps":
3584
+ mimeTypeKey = "ui/mimeType";
3585
+ break;
3586
+ default:
3587
+ mimeTypeKey = "frontmcp/mimeType";
3588
+ }
3589
+ const actualMimeType = meta[mimeTypeKey];
3590
+ const pass = actualMimeType === expectedMimeType;
3591
+ return {
3592
+ pass,
3593
+ message: () => pass ? `Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"` : `Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`
3594
+ };
3595
+ };
3596
+ var toHavePlatformHtml = function(received, platform) {
3597
+ const meta = extractMeta(received);
3598
+ if (!meta) {
3599
+ return {
3600
+ pass: false,
3601
+ message: () => `Expected _meta to have platform HTML for "${platform}", but no _meta found`
3602
+ };
3603
+ }
3604
+ let htmlKey;
3605
+ switch (platform) {
3606
+ case "openai":
3607
+ htmlKey = "openai/html";
3608
+ break;
3609
+ case "ext-apps":
3610
+ htmlKey = "ui/html";
3611
+ break;
3612
+ default:
3613
+ htmlKey = "frontmcp/html";
3614
+ }
3615
+ const html = meta[htmlKey];
3616
+ const pass = typeof html === "string" && html.length > 0;
3617
+ return {
3618
+ pass,
3619
+ message: () => pass ? `Expected _meta not to have platform HTML in "${htmlKey}"` : `Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html === void 0 ? "key not found" : `got ${typeof html}`}`
3620
+ };
3621
+ };
3622
+ var uiMatchers = {
3623
+ // Existing HTML matchers
3624
+ toHaveRenderedHtml,
3625
+ toContainHtmlElement,
3626
+ toContainBoundValue,
3627
+ toBeXssSafe,
3628
+ toHaveWidgetMetadata,
3629
+ toHaveCssClass,
3630
+ toNotContainRawContent,
3631
+ toHaveProperHtmlStructure,
3632
+ // Platform meta matchers
3633
+ toHavePlatformMeta,
3634
+ toHaveMetaKey,
3635
+ toHaveMetaValue,
3636
+ toNotHaveMetaKey,
3637
+ toHaveOnlyNamespacedMeta,
3638
+ toHavePlatformMimeType,
3639
+ toHavePlatformHtml
3640
+ };
3641
+
3642
+ // libs/testing/src/matchers/mcp-matchers.ts
3643
+ var toContainTool = function(received, toolName) {
3644
+ const tools = received;
3645
+ if (!Array.isArray(tools)) {
3646
+ return {
3647
+ pass: false,
3648
+ message: () => `Expected an array of tools, but received ${typeof received}`
3649
+ };
3650
+ }
3651
+ const pass = tools.some((t) => t.name === toolName);
3652
+ const availableTools = tools.map((t) => t.name).join(", ");
3653
+ return {
3654
+ pass,
3655
+ message: () => pass ? `Expected tools not to contain "${toolName}"` : `Expected tools to contain "${toolName}", but got: [${availableTools}]`
3656
+ };
3657
+ };
3658
+ var toBeSuccessful = function(received) {
3659
+ const result = received;
3660
+ if (typeof result !== "object" || result === null || !("isSuccess" in result)) {
3661
+ return {
3662
+ pass: false,
3663
+ message: () => `Expected a result wrapper object with isSuccess property`
3664
+ };
3665
+ }
3666
+ const pass = result.isSuccess;
3667
+ return {
3668
+ pass,
3669
+ message: () => pass ? "Expected result not to be successful" : `Expected result to be successful, but got error: ${result.error?.message ?? "unknown error"}`
3670
+ };
3671
+ };
3672
+ var toBeError = function(received, expectedCode) {
3673
+ const result = received;
3674
+ if (typeof result !== "object" || result === null || !("isError" in result)) {
3675
+ return {
3676
+ pass: false,
3677
+ message: () => `Expected a result wrapper object with isError property`
3678
+ };
3679
+ }
3680
+ let pass = result.isError;
3681
+ if (pass && expectedCode !== void 0) {
3682
+ pass = result.error?.code === expectedCode;
3683
+ }
3684
+ return {
3685
+ pass,
3686
+ message: () => {
3687
+ if (!result.isError) {
3688
+ return "Expected result to be an error, but it was successful";
3689
+ }
3690
+ if (expectedCode !== void 0 && result.error?.code !== expectedCode) {
3691
+ return `Expected error code ${expectedCode}, but got ${result.error?.code}`;
3692
+ }
3693
+ return "Expected result not to be an error";
3694
+ }
3695
+ };
3696
+ };
3697
+ var toHaveTextContent = function(received, expectedText) {
3698
+ const result = received;
3699
+ if (typeof result !== "object" || result === null || !("text" in result)) {
3700
+ return {
3701
+ pass: false,
3702
+ message: () => `Expected a ToolResultWrapper or ResourceContentWrapper object with text method`
3703
+ };
3704
+ }
3705
+ const text = result.text();
3706
+ const hasText = "hasTextContent" in result ? result.hasTextContent() : text !== void 0;
3707
+ let pass = hasText;
3708
+ if (pass && expectedText !== void 0) {
3709
+ pass = text?.includes(expectedText) ?? false;
3710
+ }
3711
+ return {
3712
+ pass,
3713
+ message: () => {
3714
+ if (!hasText) {
3715
+ return "Expected result to have text content";
3716
+ }
3717
+ if (expectedText !== void 0 && !text?.includes(expectedText)) {
3718
+ return `Expected text to contain "${expectedText}", but got: "${text}"`;
3719
+ }
3720
+ return "Expected result not to have text content";
3721
+ }
3722
+ };
3723
+ };
3724
+ var toHaveImageContent = function(received) {
3725
+ const result = received;
3726
+ if (typeof result !== "object" || result === null || !("hasImageContent" in result)) {
3727
+ return {
3728
+ pass: false,
3729
+ message: () => `Expected a ToolResultWrapper object with hasImageContent method`
3730
+ };
3731
+ }
3732
+ const pass = result.hasImageContent();
3733
+ return {
3734
+ pass,
3735
+ message: () => pass ? "Expected result not to have image content" : "Expected result to have image content"
3736
+ };
3737
+ };
3738
+ var toHaveResourceContent = function(received) {
3739
+ const result = received;
3740
+ if (typeof result !== "object" || result === null || !("hasResourceContent" in result)) {
3741
+ return {
3742
+ pass: false,
3743
+ message: () => `Expected a ToolResultWrapper object with hasResourceContent method`
3744
+ };
3745
+ }
3746
+ const pass = result.hasResourceContent();
3747
+ return {
3748
+ pass,
3749
+ message: () => pass ? "Expected result not to have resource content" : "Expected result to have resource content"
3750
+ };
3751
+ };
3752
+ var toContainResource = function(received, uri) {
3753
+ const resources = received;
3754
+ if (!Array.isArray(resources)) {
3755
+ return {
3756
+ pass: false,
3757
+ message: () => `Expected an array of resources, but received ${typeof received}`
3758
+ };
3759
+ }
3760
+ const pass = resources.some((r) => r.uri === uri);
3761
+ const availableUris = resources.map((r) => r.uri).join(", ");
3762
+ return {
3763
+ pass,
3764
+ message: () => pass ? `Expected resources not to contain "${uri}"` : `Expected resources to contain "${uri}", but got: [${availableUris}]`
3765
+ };
3766
+ };
3767
+ var toContainResourceTemplate = function(received, uriTemplate) {
3768
+ const templates = received;
3769
+ if (!Array.isArray(templates)) {
3770
+ return {
3771
+ pass: false,
3772
+ message: () => `Expected an array of resource templates, but received ${typeof received}`
3773
+ };
3774
+ }
3775
+ const pass = templates.some((t) => t.uriTemplate === uriTemplate);
3776
+ const availableTemplates = templates.map((t) => t.uriTemplate).join(", ");
3777
+ return {
3778
+ pass,
3779
+ message: () => pass ? `Expected templates not to contain "${uriTemplate}"` : `Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`
3780
+ };
3781
+ };
3782
+ var toHaveMimeType = function(received, mimeType) {
3783
+ const result = received;
3784
+ if (typeof result !== "object" || result === null || !("hasMimeType" in result)) {
3785
+ return {
3786
+ pass: false,
3787
+ message: () => `Expected a ResourceContentWrapper object with hasMimeType method`
3788
+ };
3789
+ }
3790
+ const pass = result.hasMimeType(mimeType);
3791
+ const actualMimeType = result.mimeType();
3792
+ return {
3793
+ pass,
3794
+ message: () => pass ? `Expected content not to have MIME type "${mimeType}"` : `Expected MIME type "${mimeType}", but got "${actualMimeType}"`
3795
+ };
3796
+ };
3797
+ var toContainPrompt = function(received, name) {
3798
+ const prompts = received;
3799
+ if (!Array.isArray(prompts)) {
3800
+ return {
3801
+ pass: false,
3802
+ message: () => `Expected an array of prompts, but received ${typeof received}`
3803
+ };
3804
+ }
3805
+ const pass = prompts.some((p) => p.name === name);
3806
+ const availablePrompts = prompts.map((p) => p.name).join(", ");
3807
+ return {
3808
+ pass,
3809
+ message: () => pass ? `Expected prompts not to contain "${name}"` : `Expected prompts to contain "${name}", but got: [${availablePrompts}]`
3810
+ };
3811
+ };
3812
+ var toHaveMessages = function(received, count) {
3813
+ const result = received;
3814
+ if (typeof result !== "object" || result === null || !("messages" in result)) {
3815
+ return {
3816
+ pass: false,
3817
+ message: () => `Expected a PromptResultWrapper object with messages property`
3818
+ };
3819
+ }
3820
+ const actualCount = result.messages?.length ?? 0;
3821
+ const pass = actualCount === count;
3822
+ return {
3823
+ pass,
3824
+ message: () => pass ? `Expected prompt not to have ${count} messages` : `Expected prompt to have ${count} messages, but got ${actualCount}`
3825
+ };
3826
+ };
3827
+ var toBeValidJsonRpc = function(received) {
3828
+ const response = received;
3829
+ if (typeof response !== "object" || response === null) {
3830
+ return {
3831
+ pass: false,
3832
+ message: () => `Expected an object, but received ${typeof received}`
3833
+ };
3834
+ }
3835
+ const hasJsonRpc = response["jsonrpc"] === "2.0";
3836
+ const hasId = "id" in response;
3837
+ const hasResult = "result" in response;
3838
+ const hasError = "error" in response;
3839
+ const hasExactlyOneResultOrError = (hasResult || hasError) && !(hasResult && hasError);
3840
+ const pass = hasJsonRpc && hasId && hasExactlyOneResultOrError;
3841
+ return {
3842
+ pass,
3843
+ message: () => {
3844
+ if (pass) {
3845
+ return "Expected response not to be valid JSON-RPC";
3846
+ }
3847
+ const issues = [];
3848
+ if (!hasJsonRpc) issues.push('missing or invalid "jsonrpc": "2.0"');
3849
+ if (!hasId) issues.push('missing "id" field');
3850
+ if (!hasExactlyOneResultOrError) {
3851
+ if (!hasResult && !hasError) issues.push('missing "result" or "error"');
3852
+ else issues.push('cannot have both "result" and "error"');
3853
+ }
3854
+ return `Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`;
3855
+ }
3856
+ };
3857
+ };
3858
+ var toHaveResult = function(received) {
3859
+ const response = received;
3860
+ if (typeof response !== "object" || response === null) {
3861
+ return {
3862
+ pass: false,
3863
+ message: () => `Expected an object, but received ${typeof received}`
3864
+ };
3865
+ }
3866
+ const pass = "result" in response;
3867
+ return {
3868
+ pass,
3869
+ message: () => pass ? "Expected response not to have result" : "Expected response to have result"
3870
+ };
3871
+ };
3872
+ var toHaveError = function(received) {
3873
+ const response = received;
3874
+ if (typeof response !== "object" || response === null) {
3875
+ return {
3876
+ pass: false,
3877
+ message: () => `Expected an object, but received ${typeof received}`
3878
+ };
3879
+ }
3880
+ const pass = "error" in response;
3881
+ return {
3882
+ pass,
3883
+ message: () => pass ? "Expected response not to have error" : "Expected response to have error"
3884
+ };
3885
+ };
3886
+ var toHaveErrorCode = function(received, code) {
3887
+ const response = received;
3888
+ if (typeof response !== "object" || response === null) {
3889
+ return {
3890
+ pass: false,
3891
+ message: () => `Expected an object, but received ${typeof received}`
3892
+ };
3893
+ }
3894
+ const actualCode = response.error?.code;
3895
+ const pass = actualCode === code;
3896
+ return {
3897
+ pass,
3898
+ message: () => pass ? `Expected response not to have error code ${code}` : `Expected error code ${code}, but got ${actualCode ?? "no error"}`
3899
+ };
3900
+ };
3901
+ var mcpMatchers = {
3902
+ // Tool matchers
3903
+ toContainTool,
3904
+ toBeSuccessful,
3905
+ toBeError,
3906
+ toHaveTextContent,
3907
+ toHaveImageContent,
3908
+ toHaveResourceContent,
3909
+ // Resource matchers
3910
+ toContainResource,
3911
+ toContainResourceTemplate,
3912
+ toHaveMimeType,
3913
+ // Prompt matchers
3914
+ toContainPrompt,
3915
+ toHaveMessages,
3916
+ // Protocol matchers
3917
+ toBeValidJsonRpc,
3918
+ toHaveResult,
3919
+ toHaveError,
3920
+ toHaveErrorCode,
3921
+ // UI matchers (for testing tool UI responses)
3922
+ ...uiMatchers
3923
+ };
3924
+
3925
+ // libs/testing/src/http-mock/http-mock.ts
3926
+ var originalFetch = null;
3927
+ var mockingEnabled = false;
3928
+ var activeInterceptors = [];
3929
+ var HttpInterceptorImpl = class {
3930
+ mocks = [];
3931
+ _allowPassthrough = false;
3932
+ _isActive = true;
3933
+ mock(definition) {
3934
+ const entry = {
3935
+ definition,
3936
+ callCount: 0,
3937
+ calls: [],
3938
+ remainingUses: definition.times ?? Infinity
3939
+ };
3940
+ this.mocks.push(entry);
3941
+ return {
3942
+ remove: () => {
3943
+ const index = this.mocks.indexOf(entry);
3944
+ if (index !== -1) {
3945
+ this.mocks.splice(index, 1);
3946
+ }
3947
+ },
3948
+ callCount: () => entry.callCount,
3949
+ calls: () => [...entry.calls],
3950
+ waitForCalls: async (count, timeoutMs = 5e3) => {
3951
+ const deadline = Date.now() + timeoutMs;
3952
+ while (Date.now() < deadline) {
3953
+ if (entry.callCount >= count) {
3954
+ return entry.calls.slice(0, count);
3955
+ }
3956
+ await sleep3(50);
3957
+ }
3958
+ throw new Error(`Timeout waiting for ${count} calls, got ${entry.callCount}`);
3959
+ }
3960
+ };
3961
+ }
3962
+ get(url, response) {
3963
+ return this.mock({
3964
+ match: { url, method: "GET" },
3965
+ response: normalizeResponse(response)
3966
+ });
3967
+ }
3968
+ post(url, response) {
3969
+ return this.mock({
3970
+ match: { url, method: "POST" },
3971
+ response: normalizeResponse(response)
3972
+ });
3973
+ }
3974
+ put(url, response) {
3975
+ return this.mock({
3976
+ match: { url, method: "PUT" },
3977
+ response: normalizeResponse(response)
3978
+ });
3979
+ }
3980
+ delete(url, response) {
3981
+ return this.mock({
3982
+ match: { url, method: "DELETE" },
3983
+ response: normalizeResponse(response)
3984
+ });
3985
+ }
3986
+ any(url, response) {
3987
+ return this.mock({
3988
+ match: { url },
3989
+ response: normalizeResponse(response)
3990
+ });
3991
+ }
3992
+ clear() {
3993
+ this.mocks = [];
3994
+ }
3995
+ pending() {
3996
+ return this.mocks.filter((m) => m.remainingUses > 0).map((m) => m.definition);
3997
+ }
3998
+ isDone() {
3999
+ return this.mocks.every((m) => m.remainingUses <= 0 || m.definition.times === void 0);
4000
+ }
4001
+ assertDone() {
4002
+ const pending = this.pending().filter((m) => m.times !== void 0);
4003
+ if (pending.length > 0) {
4004
+ const descriptions = pending.map((m) => {
4005
+ const url = m.match.url instanceof RegExp ? m.match.url.toString() : m.match.url;
4006
+ return ` - ${m.match.method ?? "ANY"} ${url}`;
4007
+ });
4008
+ throw new Error(`Unused HTTP mocks:
4009
+ ${descriptions.join("\n")}`);
4010
+ }
4011
+ }
4012
+ allowPassthrough(allow) {
4013
+ this._allowPassthrough = allow;
4014
+ }
4015
+ restore() {
4016
+ this._isActive = false;
4017
+ const index = activeInterceptors.indexOf(this);
4018
+ if (index !== -1) {
4019
+ activeInterceptors.splice(index, 1);
4020
+ }
4021
+ }
4022
+ // Internal methods
4023
+ isActive() {
4024
+ return this._isActive;
4025
+ }
4026
+ canPassthrough() {
4027
+ return this._allowPassthrough;
4028
+ }
4029
+ /**
4030
+ * Try to match a request against mocks in this scope
4031
+ */
4032
+ async matchRequest(info) {
4033
+ if (!this._isActive) return null;
4034
+ for (const entry of this.mocks) {
4035
+ if (entry.remainingUses <= 0) continue;
4036
+ if (this.requestMatches(info, entry.definition.match)) {
4037
+ entry.callCount++;
4038
+ entry.calls.push(info);
4039
+ entry.remainingUses--;
4040
+ let mockResponse2;
4041
+ if (typeof entry.definition.response === "function") {
4042
+ mockResponse2 = await entry.definition.response(info);
4043
+ } else {
4044
+ mockResponse2 = entry.definition.response;
4045
+ }
4046
+ if (mockResponse2.delay && mockResponse2.delay > 0) {
4047
+ await sleep3(mockResponse2.delay);
4048
+ }
4049
+ return createMockResponse(mockResponse2);
4050
+ }
4051
+ }
4052
+ return null;
4053
+ }
4054
+ requestMatches(info, matcher) {
4055
+ if (!this.urlMatches(info.url, matcher.url)) {
4056
+ return false;
4057
+ }
4058
+ if (matcher.method) {
4059
+ const methods = Array.isArray(matcher.method) ? matcher.method : [matcher.method];
4060
+ if (!methods.includes(info.method)) {
4061
+ return false;
4062
+ }
4063
+ }
4064
+ if (matcher.headers) {
4065
+ for (const [key, expected] of Object.entries(matcher.headers)) {
4066
+ const actual = info.headers[key.toLowerCase()];
4067
+ if (!actual) return false;
4068
+ if (expected instanceof RegExp) {
4069
+ if (!expected.test(actual)) return false;
4070
+ } else if (actual !== expected) {
4071
+ return false;
4072
+ }
4073
+ }
4074
+ }
4075
+ if (matcher.body !== void 0) {
4076
+ if (!this.bodyMatches(info.body, matcher.body)) {
4077
+ return false;
4078
+ }
4079
+ }
4080
+ return true;
4081
+ }
4082
+ urlMatches(url, matcher) {
4083
+ if (typeof matcher === "string") {
4084
+ return url === matcher || url.includes(matcher);
4085
+ } else if (matcher instanceof RegExp) {
4086
+ return matcher.test(url);
4087
+ } else {
4088
+ return matcher(url);
4089
+ }
4090
+ }
4091
+ bodyMatches(actual, expected) {
4092
+ if (typeof expected === "function") {
4093
+ return expected(actual);
4094
+ }
4095
+ if (typeof expected === "string") {
4096
+ const actualStr = typeof actual === "string" ? actual : JSON.stringify(actual);
4097
+ return actualStr === expected || actualStr.includes(expected);
4098
+ }
4099
+ if (expected instanceof RegExp) {
4100
+ const actualStr = typeof actual === "string" ? actual : JSON.stringify(actual);
4101
+ return expected.test(actualStr);
4102
+ }
4103
+ if (typeof actual !== "object" || actual === null) {
4104
+ return false;
4105
+ }
4106
+ for (const [key, value] of Object.entries(expected)) {
4107
+ const actualValue = actual[key];
4108
+ if (typeof value === "object" && value !== null) {
4109
+ if (!this.bodyMatches(actualValue, value)) {
4110
+ return false;
4111
+ }
4112
+ } else if (actualValue !== value) {
4113
+ return false;
4114
+ }
4115
+ }
4116
+ return true;
4117
+ }
4118
+ };
4119
+ async function interceptedFetch(input, init) {
4120
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
4121
+ const method = (init?.method ?? "GET").toUpperCase();
4122
+ const headers = {};
4123
+ if (init?.headers) {
4124
+ if (init.headers instanceof Headers) {
4125
+ init.headers.forEach((value, key) => {
4126
+ headers[key.toLowerCase()] = value;
4127
+ });
4128
+ } else if (Array.isArray(init.headers)) {
4129
+ for (const [key, value] of init.headers) {
4130
+ headers[key.toLowerCase()] = value;
4131
+ }
4132
+ } else {
4133
+ for (const [key, value] of Object.entries(init.headers)) {
4134
+ headers[key.toLowerCase()] = value;
4135
+ }
4136
+ }
4137
+ }
4138
+ let body;
4139
+ let rawBody;
4140
+ if (init?.body) {
4141
+ if (typeof init.body === "string") {
4142
+ rawBody = init.body;
4143
+ try {
4144
+ body = JSON.parse(init.body);
4145
+ } catch {
4146
+ body = init.body;
4147
+ }
4148
+ } else if (init.body instanceof ArrayBuffer || init.body instanceof Uint8Array) {
4149
+ rawBody = new TextDecoder().decode(init.body);
4150
+ try {
4151
+ body = JSON.parse(rawBody);
4152
+ } catch {
4153
+ body = rawBody;
4154
+ }
4155
+ } else {
4156
+ body = init.body;
4157
+ }
4158
+ }
4159
+ const requestInfo = {
4160
+ url,
4161
+ method,
4162
+ headers,
4163
+ body,
4164
+ rawBody
4165
+ };
4166
+ for (let i = activeInterceptors.length - 1; i >= 0; i--) {
4167
+ const interceptor = activeInterceptors[i];
4168
+ if (!interceptor.isActive()) continue;
4169
+ const mockResponse2 = await interceptor.matchRequest(requestInfo);
4170
+ if (mockResponse2) {
4171
+ return mockResponse2;
4172
+ }
4173
+ }
4174
+ for (const interceptor of activeInterceptors) {
4175
+ if (interceptor.isActive() && interceptor.canPassthrough()) {
4176
+ if (originalFetch) {
4177
+ return originalFetch(input, init);
4178
+ }
4179
+ }
4180
+ }
4181
+ throw new Error(
4182
+ `No HTTP mock found for ${method} ${url}
4183
+ Add a mock using httpMock.interceptor().${method.toLowerCase()}('${url}', { body: ... })`
4184
+ );
4185
+ }
4186
+ function normalizeResponse(response) {
4187
+ if (!("status" in response) && !("body" in response) && !("headers" in response)) {
4188
+ return { body: response };
4189
+ }
4190
+ return response;
4191
+ }
4192
+ function createMockResponse(mock) {
4193
+ const mockAny = mock;
4194
+ if (mockAny._throwError) {
4195
+ const body2 = mock.body;
4196
+ const message = body2 && typeof body2 === "object" && "message" in body2 ? String(body2["message"]) : "Network error";
4197
+ throw new TypeError(`fetch failed: ${message}`);
4198
+ }
4199
+ const status = mock.status ?? 200;
4200
+ const statusText = mock.statusText ?? "OK";
4201
+ const headers = new Headers(mock.headers ?? {});
4202
+ let body = null;
4203
+ if (mock.body !== void 0) {
4204
+ if (typeof mock.body === "string") {
4205
+ body = mock.body;
4206
+ if (!headers.has("content-type")) {
4207
+ headers.set("content-type", "text/plain");
4208
+ }
4209
+ } else if (mock.body instanceof ArrayBuffer) {
4210
+ body = mock.body;
4211
+ } else if (Buffer.isBuffer(mock.body)) {
4212
+ body = new Uint8Array(mock.body).buffer;
4213
+ } else {
4214
+ body = JSON.stringify(mock.body);
4215
+ if (!headers.has("content-type")) {
4216
+ headers.set("content-type", "application/json");
4217
+ }
4218
+ }
4219
+ }
4220
+ return new Response(body, { status, statusText, headers });
4221
+ }
4222
+ function sleep3(ms) {
4223
+ return new Promise((resolve) => setTimeout(resolve, ms));
4224
+ }
4225
+ var HttpMockManagerImpl = class {
4226
+ interceptor() {
4227
+ if (!mockingEnabled) {
4228
+ this.enable();
4229
+ }
4230
+ const interceptor = new HttpInterceptorImpl();
4231
+ activeInterceptors.push(interceptor);
4232
+ return interceptor;
4233
+ }
4234
+ enable() {
4235
+ if (mockingEnabled) return;
4236
+ if (typeof globalThis.fetch === "function") {
4237
+ originalFetch = globalThis.fetch;
4238
+ globalThis.fetch = interceptedFetch;
4239
+ }
4240
+ mockingEnabled = true;
4241
+ }
4242
+ disable() {
4243
+ if (!mockingEnabled) return;
4244
+ if (originalFetch) {
4245
+ globalThis.fetch = originalFetch;
4246
+ originalFetch = null;
4247
+ }
4248
+ activeInterceptors.length = 0;
4249
+ mockingEnabled = false;
4250
+ }
4251
+ isEnabled() {
4252
+ return mockingEnabled;
4253
+ }
4254
+ clearAll() {
4255
+ for (const interceptor of activeInterceptors) {
4256
+ interceptor.clear();
4257
+ }
4258
+ activeInterceptors.length = 0;
4259
+ }
4260
+ };
4261
+ var httpMock = new HttpMockManagerImpl();
4262
+ var httpResponse = {
4263
+ /** Create a JSON response */
4264
+ json(data, status = 200) {
4265
+ return {
4266
+ status,
4267
+ headers: { "content-type": "application/json" },
4268
+ body: data
4269
+ };
4270
+ },
4271
+ /** Create a text response */
4272
+ text(data, status = 200) {
4273
+ return {
4274
+ status,
4275
+ headers: { "content-type": "text/plain" },
4276
+ body: data
4277
+ };
4278
+ },
4279
+ /** Create an HTML response */
4280
+ html(data, status = 200) {
4281
+ return {
4282
+ status,
4283
+ headers: { "content-type": "text/html" },
4284
+ body: data
4285
+ };
4286
+ },
4287
+ /** Create an error response */
4288
+ error(status, message) {
4289
+ return {
4290
+ status,
4291
+ statusText: message ?? getStatusText(status),
4292
+ body: message ? { error: message } : void 0
4293
+ };
4294
+ },
4295
+ /** Create a 404 Not Found response */
4296
+ notFound(message = "Not Found") {
4297
+ return httpResponse.error(404, message);
4298
+ },
4299
+ /** Create a 500 Internal Server Error response */
4300
+ serverError(message = "Internal Server Error") {
4301
+ return httpResponse.error(500, message);
4302
+ },
4303
+ /** Create a 401 Unauthorized response */
4304
+ unauthorized(message = "Unauthorized") {
4305
+ return httpResponse.error(401, message);
4306
+ },
4307
+ /** Create a 403 Forbidden response */
4308
+ forbidden(message = "Forbidden") {
4309
+ return httpResponse.error(403, message);
4310
+ },
4311
+ /**
4312
+ * Create a network error that causes fetch to reject
4313
+ * This simulates real network failures where fetch throws instead of returning a Response
4314
+ */
4315
+ networkError(message = "Network error") {
4316
+ return {
4317
+ status: 0,
4318
+ body: { _networkError: true, message },
4319
+ // Mark this as a network error for the interceptor to throw
4320
+ _throwError: true
4321
+ };
4322
+ },
4323
+ /** Create a delayed response */
4324
+ delayed(data, delayMs, status = 200) {
4325
+ return {
4326
+ status,
4327
+ body: data,
4328
+ delay: delayMs
4329
+ };
4330
+ }
4331
+ };
4332
+ function getStatusText(status) {
4333
+ const texts = {
4334
+ 200: "OK",
4335
+ 201: "Created",
4336
+ 204: "No Content",
4337
+ 400: "Bad Request",
4338
+ 401: "Unauthorized",
4339
+ 403: "Forbidden",
4340
+ 404: "Not Found",
4341
+ 500: "Internal Server Error",
4342
+ 502: "Bad Gateway",
4343
+ 503: "Service Unavailable"
4344
+ };
4345
+ return texts[status] ?? "Unknown";
4346
+ }
4347
+
4348
+ // libs/testing/src/ui/ui-assertions.ts
4349
+ function escapeRegex2(str) {
4350
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4351
+ }
4352
+ var UIAssertions = {
4353
+ /**
4354
+ * Assert tool result has valid rendered UI HTML.
4355
+ * @param result - The tool result wrapper
4356
+ * @returns The rendered HTML string
4357
+ * @throws Error if no UI HTML found or if mdx-fallback detected
4358
+ */
4359
+ assertRenderedUI(result) {
4360
+ const meta = result.raw._meta;
4361
+ if (!meta) {
4362
+ throw new Error("Expected tool result to have _meta, but _meta is undefined");
4363
+ }
4364
+ const html = meta["ui/html"];
4365
+ if (!html) {
4366
+ throw new Error("Expected tool result to have ui/html in _meta, but it is missing");
4367
+ }
4368
+ if (typeof html !== "string") {
4369
+ throw new Error(`Expected ui/html to be a string, but got ${typeof html}`);
4370
+ }
4371
+ if (html.includes("mdx-fallback")) {
4372
+ throw new Error(
4373
+ "Got mdx-fallback instead of rendered HTML - MDX/React rendering failed. Check that @mdx-js/mdx is installed and the template syntax is valid."
4374
+ );
4375
+ }
4376
+ return html;
4377
+ },
4378
+ /**
4379
+ * Assert HTML contains all expected bound values from tool output.
4380
+ * @param html - The rendered HTML string
4381
+ * @param output - The tool output object
4382
+ * @param keys - Array of keys whose values should appear in the HTML
4383
+ * @throws Error if any expected value is missing from the HTML
4384
+ */
4385
+ assertDataBinding(html, output, keys) {
4386
+ const missingKeys = [];
4387
+ for (const key of keys) {
4388
+ const value = output[key];
4389
+ if (value === void 0 || value === null) {
4390
+ continue;
4391
+ }
4392
+ const stringValue = String(value);
4393
+ if (!html.includes(stringValue)) {
4394
+ missingKeys.push(`${key}="${stringValue}"`);
4395
+ }
4396
+ }
4397
+ if (missingKeys.length > 0) {
4398
+ throw new Error(
4399
+ `Expected HTML to contain bound values for: ${missingKeys.join(", ")}. Data binding may have failed.`
4400
+ );
4401
+ }
4402
+ },
4403
+ /**
4404
+ * Assert HTML is XSS-safe (no scripts, event handlers, or javascript: URIs).
4405
+ * @param html - The rendered HTML string
4406
+ * @throws Error if potential XSS vulnerabilities are detected
4407
+ */
4408
+ assertXssSafe(html) {
4409
+ const vulnerabilities = [];
4410
+ if (/<script[\s>]/i.test(html)) {
4411
+ vulnerabilities.push("<script> tag detected");
4412
+ }
4413
+ if (/\son\w+\s*=/i.test(html)) {
4414
+ vulnerabilities.push("inline event handler detected (onclick, onerror, etc.)");
4415
+ }
4416
+ if (/javascript:/i.test(html)) {
4417
+ vulnerabilities.push("javascript: URI detected");
4418
+ }
4419
+ if (vulnerabilities.length > 0) {
4420
+ throw new Error(`Potential XSS vulnerabilities found: ${vulnerabilities.join("; ")}`);
4421
+ }
4422
+ },
4423
+ /**
4424
+ * Assert HTML has proper structure (not escaped raw content).
4425
+ * @param html - The rendered HTML string
4426
+ * @throws Error if HTML appears to be raw/unrendered content
4427
+ */
4428
+ assertProperHtmlStructure(html) {
4429
+ if (html.includes("&lt;") && html.includes("&gt;")) {
4430
+ throw new Error(
4431
+ "HTML contains escaped HTML entities (&lt;, &gt;) - content was likely not rendered. Check that the template is being processed correctly."
4432
+ );
4433
+ }
4434
+ if (!/<[a-z]/i.test(html)) {
4435
+ throw new Error("HTML contains no HTML tags - content may be plain text or rendering failed.");
4436
+ }
4437
+ },
4438
+ /**
4439
+ * Assert HTML contains a specific element.
4440
+ * @param html - The rendered HTML string
4441
+ * @param tag - The HTML tag name to look for
4442
+ * @throws Error if the element is not found
4443
+ */
4444
+ assertContainsElement(html, tag) {
4445
+ const regex = new RegExp(`<${escapeRegex2(tag)}[\\s>]`, "i");
4446
+ if (!regex.test(html)) {
4447
+ throw new Error(`Expected HTML to contain <${tag}> element`);
4448
+ }
4449
+ },
4450
+ /**
4451
+ * Assert HTML contains a specific CSS class.
4452
+ * @param html - The rendered HTML string
4453
+ * @param className - The CSS class name to look for
4454
+ * @throws Error if the class is not found
4455
+ */
4456
+ assertHasCssClass(html, className) {
4457
+ const classRegex = new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex2(className)}\\b[^"']*["']`, "i");
4458
+ if (!classRegex.test(html)) {
4459
+ throw new Error(`Expected HTML to have CSS class "${className}"`);
4460
+ }
4461
+ },
4462
+ /**
4463
+ * Assert HTML does NOT contain specific content.
4464
+ * Useful for verifying custom components were rendered, not left as raw tags.
4465
+ * @param html - The rendered HTML string
4466
+ * @param content - The content that should NOT appear
4467
+ * @throws Error if the content is found
4468
+ */
4469
+ assertNotContainsRaw(html, content) {
4470
+ if (html.includes(content)) {
4471
+ throw new Error(
4472
+ `HTML contains raw content "${content}" - this component may not have been rendered. Check that all custom components are properly passed to the renderer.`
4473
+ );
4474
+ }
4475
+ },
4476
+ /**
4477
+ * Assert that widget metadata is present in the result.
4478
+ * Checks for ui/html, openai/outputTemplate, or ui/mimeType.
4479
+ * @param result - The tool result wrapper
4480
+ * @throws Error if widget metadata is missing
4481
+ */
4482
+ assertWidgetMetadata(result) {
4483
+ const meta = result.raw._meta;
4484
+ if (!meta) {
4485
+ throw new Error("Expected tool result to have _meta with widget metadata");
4486
+ }
4487
+ const hasUiHtml = Boolean(meta["ui/html"]);
4488
+ const hasOutputTemplate = Boolean(meta["openai/outputTemplate"]);
4489
+ const hasMimeType2 = Boolean(meta["ui/mimeType"]);
4490
+ if (!hasUiHtml && !hasOutputTemplate && !hasMimeType2) {
4491
+ throw new Error("Expected _meta to have widget metadata (ui/html, openai/outputTemplate, or ui/mimeType)");
4492
+ }
4493
+ },
4494
+ /**
4495
+ * Comprehensive UI validation that runs all checks.
4496
+ * @param result - The tool result wrapper
4497
+ * @param boundKeys - Optional array of output keys to check for data binding
4498
+ * @returns The rendered HTML string
4499
+ * @throws Error if any validation fails
4500
+ */
4501
+ assertValidUI(result, boundKeys) {
4502
+ const html = UIAssertions.assertRenderedUI(result);
4503
+ UIAssertions.assertProperHtmlStructure(html);
4504
+ UIAssertions.assertXssSafe(html);
4505
+ if (boundKeys && boundKeys.length > 0) {
4506
+ try {
4507
+ const output = JSON.parse(result.text() || "{}");
4508
+ UIAssertions.assertDataBinding(html, output, boundKeys);
4509
+ } catch {
4510
+ }
4511
+ }
4512
+ return html;
4513
+ },
4514
+ // ═══════════════════════════════════════════════════════════════════
4515
+ // PLATFORM META ASSERTIONS
4516
+ // ═══════════════════════════════════════════════════════════════════
4517
+ /**
4518
+ * Assert tool result has correct meta keys for OpenAI platform.
4519
+ * Verifies openai/* keys are present and ui/*, frontmcp/* keys are absent.
4520
+ * @param result - The tool result wrapper
4521
+ * @throws Error if meta keys don't match OpenAI expectations
4522
+ */
4523
+ assertOpenAIMeta(result) {
4524
+ UIAssertions.assertPlatformMeta(result, "openai");
4525
+ },
4526
+ /**
4527
+ * Assert tool result has correct meta keys for ext-apps platform (SEP-1865).
4528
+ * Verifies ui/* keys are present and openai/*, frontmcp/* keys are absent.
4529
+ * @param result - The tool result wrapper
4530
+ * @throws Error if meta keys don't match ext-apps expectations
4531
+ */
4532
+ assertExtAppsMeta(result) {
4533
+ UIAssertions.assertPlatformMeta(result, "ext-apps");
4534
+ },
4535
+ /**
4536
+ * Assert tool result has correct meta keys for FrontMCP platforms (Claude, Cursor, etc.).
4537
+ * Verifies frontmcp/* + ui/* keys are present and openai/* keys are absent.
4538
+ * @param result - The tool result wrapper
4539
+ * @throws Error if meta keys don't match FrontMCP expectations
4540
+ */
4541
+ assertFrontmcpMeta(result) {
4542
+ UIAssertions.assertPlatformMeta(result, "claude");
4543
+ },
4544
+ /**
4545
+ * Assert tool result has correct meta keys for a specific platform.
4546
+ * @param result - The tool result wrapper
4547
+ * @param platform - The platform type to check for
4548
+ * @throws Error if meta keys don't match platform expectations
4549
+ */
4550
+ assertPlatformMeta(result, platform) {
4551
+ const meta = result.raw._meta;
4552
+ if (!meta) {
4553
+ throw new Error(`Expected tool result to have _meta with platform meta for "${platform}"`);
4554
+ }
4555
+ const expectedPrefixes = getToolCallMetaPrefixes(platform);
4556
+ const forbiddenPrefixes = getForbiddenMetaPrefixes(platform);
4557
+ const metaKeys = Object.keys(meta);
4558
+ const hasExpectedPrefix = metaKeys.some((key) => expectedPrefixes.some((prefix) => key.startsWith(prefix)));
4559
+ if (!hasExpectedPrefix) {
4560
+ throw new Error(
4561
+ `Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`
4562
+ );
4563
+ }
4564
+ const forbiddenKeys = metaKeys.filter((key) => forbiddenPrefixes.some((prefix) => key.startsWith(prefix)));
4565
+ if (forbiddenKeys.length > 0) {
4566
+ throw new Error(
4567
+ `Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`
4568
+ );
4569
+ }
4570
+ },
4571
+ /**
4572
+ * Assert that no cross-namespace pollution exists in meta.
4573
+ * @param result - The tool result wrapper
4574
+ * @param expectedNamespace - The namespace that SHOULD be present
4575
+ * @throws Error if other namespaces are found
4576
+ */
4577
+ assertNoMixedNamespaces(result, expectedNamespace) {
4578
+ const meta = result.raw._meta;
4579
+ if (!meta) {
4580
+ throw new Error(`Expected tool result to have _meta with namespace "${expectedNamespace}"`);
4581
+ }
4582
+ const metaKeys = Object.keys(meta);
4583
+ const wrongKeys = metaKeys.filter((key) => !key.startsWith(expectedNamespace));
4584
+ if (wrongKeys.length > 0) {
4585
+ throw new Error(
4586
+ `Expected _meta to ONLY have keys with namespace "${expectedNamespace}", but found: [${wrongKeys.join(", ")}]`
4587
+ );
4588
+ }
4589
+ },
4590
+ /**
4591
+ * Assert that _meta has the correct MIME type for a platform.
4592
+ * @param result - The tool result wrapper
4593
+ * @param platform - The platform type to check for
4594
+ * @throws Error if MIME type doesn't match platform expectations
4595
+ */
4596
+ assertPlatformMimeType(result, platform) {
4597
+ const meta = result.raw._meta;
4598
+ const expectedMimeType = getPlatformMimeType(platform);
4599
+ if (!meta) {
4600
+ throw new Error(`Expected tool result to have _meta with MIME type for platform "${platform}"`);
4601
+ }
4602
+ let mimeTypeKey;
4603
+ switch (platform) {
4604
+ case "openai":
4605
+ mimeTypeKey = "openai/mimeType";
4606
+ break;
4607
+ case "ext-apps":
4608
+ mimeTypeKey = "ui/mimeType";
4609
+ break;
4610
+ default:
4611
+ mimeTypeKey = "frontmcp/mimeType";
4612
+ }
4613
+ const actualMimeType = meta[mimeTypeKey];
4614
+ if (actualMimeType !== expectedMimeType) {
4615
+ throw new Error(
4616
+ `Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`
4617
+ );
4618
+ }
4619
+ },
4620
+ /**
4621
+ * Assert that _meta has HTML in the correct platform-specific key.
4622
+ * @param result - The tool result wrapper
4623
+ * @param platform - The platform type to check for
4624
+ * @returns The HTML string
4625
+ * @throws Error if HTML is missing or in wrong key
4626
+ */
4627
+ assertPlatformHtml(result, platform) {
4628
+ const meta = result.raw._meta;
4629
+ if (!meta) {
4630
+ throw new Error(`Expected tool result to have _meta with platform HTML for "${platform}"`);
4631
+ }
4632
+ let htmlKey;
4633
+ switch (platform) {
4634
+ case "openai":
4635
+ htmlKey = "openai/html";
4636
+ break;
4637
+ case "ext-apps":
4638
+ htmlKey = "ui/html";
4639
+ break;
4640
+ default:
4641
+ htmlKey = "frontmcp/html";
4642
+ }
4643
+ const html = meta[htmlKey];
4644
+ if (typeof html !== "string" || html.length === 0) {
4645
+ throw new Error(
4646
+ `Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html === void 0 ? "key not found" : `got ${typeof html}`}`
4647
+ );
4648
+ }
4649
+ return html;
4650
+ },
4651
+ /**
4652
+ * Comprehensive platform meta validation.
4653
+ * @param result - The tool result wrapper
4654
+ * @param platform - The platform type to validate for
4655
+ * @returns The platform-specific HTML string
4656
+ * @throws Error if any platform-specific validation fails
4657
+ */
4658
+ assertValidPlatformMeta(result, platform) {
4659
+ UIAssertions.assertPlatformMeta(result, platform);
4660
+ UIAssertions.assertPlatformMimeType(result, platform);
4661
+ return UIAssertions.assertPlatformHtml(result, platform);
4662
+ }
4663
+ };
4664
+
4665
+ // libs/testing/src/example-tools/tool-configs.ts
4666
+ var import_zod = require("zod");
4667
+ var basicUIToolInputSchema = import_zod.z.object({
4668
+ name: import_zod.z.string().optional().default("World")
4669
+ });
4670
+ var basicUIToolOutputSchema = import_zod.z.object({
4671
+ message: import_zod.z.string(),
4672
+ timestamp: import_zod.z.number()
4673
+ });
4674
+ var BASIC_UI_TOOL_CONFIG = {
4675
+ name: "platform-test-basic",
4676
+ description: "Basic UI tool for platform testing",
4677
+ inputSchema: basicUIToolInputSchema,
4678
+ outputSchema: basicUIToolOutputSchema,
4679
+ ui: {
4680
+ /**
4681
+ * Simple template that displays the output.
4682
+ * Works with all platforms.
4683
+ */
4684
+ template: `
4685
+ <div class="platform-test-basic">
4686
+ <h1>Platform Test - Basic</h1>
4687
+ <p>Message: {output.message}</p>
4688
+ <p>Timestamp: {output.timestamp}</p>
4689
+ </div>
4690
+ `.trim()
4691
+ }
4692
+ };
4693
+ var fullUIToolInputSchema = import_zod.z.object({
4694
+ name: import_zod.z.string().optional().default("World"),
4695
+ count: import_zod.z.number().optional().default(1)
4696
+ });
4697
+ var fullUIToolOutputSchema = import_zod.z.object({
4698
+ message: import_zod.z.string(),
4699
+ count: import_zod.z.number(),
4700
+ items: import_zod.z.array(import_zod.z.string()),
4701
+ timestamp: import_zod.z.number()
4702
+ });
4703
+ var FULL_UI_TOOL_CONFIG = {
4704
+ name: "platform-test-full",
4705
+ description: "Full UI tool with all options for comprehensive platform testing",
4706
+ inputSchema: fullUIToolInputSchema,
4707
+ outputSchema: fullUIToolOutputSchema,
4708
+ ui: {
4709
+ /**
4710
+ * Template with more complex UI elements.
4711
+ */
4712
+ template: `
4713
+ <div class="platform-test-full">
4714
+ <h1>Platform Test - Full</h1>
4715
+ <div class="message-box">
4716
+ <strong>Message:</strong> {output.message}
4717
+ </div>
4718
+ <div class="count-box">
4719
+ <strong>Count:</strong> {output.count}
4720
+ </div>
4721
+ <div class="items-list">
4722
+ <strong>Items:</strong>
4723
+ <ul>
4724
+ {output.items.map(item => <li key={item}>{item}</li>)}
4725
+ </ul>
4726
+ </div>
4727
+ <footer>
4728
+ <small>Generated at: {new Date(output.timestamp).toISOString()}</small>
4729
+ </footer>
4730
+ </div>
4731
+ `.trim(),
4732
+ /**
4733
+ * Widget is accessible for callback invocations.
4734
+ */
4735
+ widgetAccessible: true,
4736
+ /**
4737
+ * Invocation status messages for OpenAI.
4738
+ */
4739
+ invocationStatus: {
4740
+ invoking: "Processing request...",
4741
+ invoked: "Request completed"
4742
+ },
4743
+ /**
4744
+ * Content Security Policy configuration.
4745
+ */
4746
+ csp: {
4747
+ connectDomains: ["https://api.example.com"],
4748
+ resourceDomains: ["https://cdn.example.com"]
4749
+ },
4750
+ /**
4751
+ * Display mode for the widget.
4752
+ */
4753
+ displayMode: "inline",
4754
+ /**
4755
+ * Prefers border around the widget.
4756
+ */
4757
+ prefersBorder: true,
4758
+ /**
4759
+ * Custom sandbox domain.
4760
+ */
4761
+ sandboxDomain: "sandbox.example.com"
4762
+ }
4763
+ };
4764
+ function generateBasicUIToolOutput(input) {
4765
+ return {
4766
+ message: `Hello, ${input.name}!`,
4767
+ timestamp: Date.now()
4768
+ };
4769
+ }
4770
+ function generateFullUIToolOutput(input) {
4771
+ const items = [];
4772
+ for (let i = 1; i <= input.count; i++) {
4773
+ items.push(`Item ${i}`);
4774
+ }
4775
+ return {
4776
+ message: `Hello, ${input.name}! You requested ${input.count} item(s).`,
4777
+ count: input.count,
4778
+ items,
4779
+ timestamp: Date.now()
4780
+ };
4781
+ }
4782
+ var EXPECTED_OPENAI_TOOLS_LIST_META_KEYS = [
4783
+ "openai/outputTemplate",
4784
+ "openai/resultCanProduceWidget",
4785
+ "openai/widgetAccessible"
4786
+ ];
4787
+ var EXPECTED_OPENAI_TOOL_CALL_META_KEYS = ["openai/html", "openai/mimeType", "openai/type"];
4788
+ var EXPECTED_EXTAPPS_TOOLS_LIST_META_KEYS = ["ui/resourceUri", "ui/mimeType", "ui/cdn", "ui/type"];
4789
+ var EXPECTED_EXTAPPS_TOOL_CALL_META_KEYS = ["ui/html", "ui/mimeType", "ui/type"];
4790
+ var EXPECTED_FRONTMCP_TOOLS_LIST_META_KEYS = [
4791
+ "frontmcp/outputTemplate",
4792
+ "frontmcp/resultCanProduceWidget",
4793
+ "ui/cdn",
4794
+ "ui/type"
4795
+ ];
4796
+ var EXPECTED_FRONTMCP_TOOL_CALL_META_KEYS = [
4797
+ "frontmcp/html",
4798
+ "frontmcp/mimeType",
4799
+ "ui/html",
4800
+ "ui/mimeType"
4801
+ ];
4802
+ // Annotate the CommonJS export names for ESM import in node:
4803
+ 0 && (module.exports = {
4804
+ AssertionError,
4805
+ AuthHeaders,
4806
+ BASIC_UI_TOOL_CONFIG,
4807
+ ConnectionError,
4808
+ DefaultInterceptorChain,
4809
+ DefaultMockRegistry,
4810
+ EXPECTED_EXTAPPS_TOOLS_LIST_META_KEYS,
4811
+ EXPECTED_EXTAPPS_TOOL_CALL_META_KEYS,
4812
+ EXPECTED_FRONTMCP_TOOLS_LIST_META_KEYS,
4813
+ EXPECTED_FRONTMCP_TOOL_CALL_META_KEYS,
4814
+ EXPECTED_OPENAI_TOOLS_LIST_META_KEYS,
4815
+ EXPECTED_OPENAI_TOOL_CALL_META_KEYS,
4816
+ FULL_UI_TOOL_CONFIG,
4817
+ McpAssertions,
4818
+ McpProtocolError,
4819
+ McpTestClient,
4820
+ McpTestClientBuilder,
4821
+ MockAPIServer,
4822
+ MockOAuthServer,
4823
+ PLATFORM_DETECTION_PATTERNS,
4824
+ ServerStartError,
4825
+ StreamableHttpTransport,
4826
+ TestClientError,
4827
+ TestServer,
4828
+ TestTokenFactory,
4829
+ TestUsers,
4830
+ TimeoutError,
4831
+ UIAssertions,
4832
+ basicUIToolInputSchema,
4833
+ basicUIToolOutputSchema,
4834
+ buildUserAgent,
4835
+ containsPrompt,
4836
+ containsResource,
4837
+ containsResourceTemplate,
4838
+ containsTool,
4839
+ createTestUser,
4840
+ expect,
4841
+ fullUIToolInputSchema,
4842
+ fullUIToolOutputSchema,
4843
+ generateBasicUIToolOutput,
4844
+ generateFullUIToolOutput,
4845
+ getForbiddenMetaPrefixes,
4846
+ getPlatformClientInfo,
4847
+ getPlatformMetaNamespace,
4848
+ getPlatformMimeType,
4849
+ getPlatformUserAgent,
4850
+ getToolCallMetaPrefixes,
4851
+ getToolsListMetaPrefixes,
4852
+ hasMimeType,
4853
+ hasTextContent,
4854
+ httpMock,
4855
+ httpResponse,
4856
+ interceptors,
4857
+ isError,
4858
+ isExtAppsPlatform,
4859
+ isFrontmcpPlatform,
4860
+ isOpenAIPlatform,
4861
+ isSuccessful,
4862
+ mcpMatchers,
4863
+ mockResponse,
4864
+ test,
4865
+ uiMatchers
4866
+ });