@mcpfn/testing 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1171 @@
1
+ // src/assertions.ts
2
+ import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js";
3
+ function stableJson(value) {
4
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
5
+ if (value && typeof value === "object") {
6
+ return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
7
+ }
8
+ return JSON.stringify(value);
9
+ }
10
+ var McpFnAssertionError = class extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "McpFnAssertionError";
14
+ }
15
+ };
16
+ async function assertManifestContract(client, manifest, options = {}) {
17
+ const actual = await client.listTools();
18
+ const actualByName = new Map(actual.map((tool) => [tool.name, tool]));
19
+ const manifestByName = new Map(manifest.tools.map((tool) => [tool.name, tool]));
20
+ const expectedNames = [...options.expectedToolNames ?? manifest.tools.map((tool) => tool.name)].sort();
21
+ const unknownExpectedNames = expectedNames.filter((name) => !manifestByName.has(name));
22
+ if (unknownExpectedNames.length) {
23
+ throw new McpFnAssertionError(
24
+ `Expected visible tools are absent from the manifest: ${stableJson(unknownExpectedNames)}`
25
+ );
26
+ }
27
+ const actualNames = actual.map((tool) => tool.name).sort();
28
+ if (stableJson(expectedNames) !== stableJson(actualNames)) {
29
+ throw new McpFnAssertionError(
30
+ `Tool inventory mismatch
31
+ expected: ${stableJson(expectedNames)}
32
+ actual: ${stableJson(actualNames)}`
33
+ );
34
+ }
35
+ for (const name of expectedNames) {
36
+ const expected = manifestByName.get(name);
37
+ const tool = actualByName.get(expected.name);
38
+ const comparableExpected = {
39
+ name: expected.name,
40
+ description: expected.description,
41
+ inputSchema: expected.inputSchema,
42
+ outputSchema: expected.outputSchema,
43
+ annotations: expected.annotations,
44
+ execution: expected.execution,
45
+ icons: expected.icons,
46
+ title: expected.title,
47
+ _meta: expected.metadata
48
+ };
49
+ const comparableActual = {
50
+ name: tool.name,
51
+ description: tool.description,
52
+ inputSchema: tool.inputSchema,
53
+ outputSchema: tool.outputSchema,
54
+ annotations: tool.annotations,
55
+ execution: tool.execution,
56
+ icons: tool.icons,
57
+ title: tool.title,
58
+ _meta: tool._meta
59
+ };
60
+ if (stableJson(comparableExpected) !== stableJson(comparableActual)) {
61
+ throw new McpFnAssertionError(
62
+ `Contract mismatch for ${expected.name}
63
+ expected: ${stableJson(comparableExpected)}
64
+ actual: ${stableJson(comparableActual)}`
65
+ );
66
+ }
67
+ }
68
+ const actualCapabilities = client.client.getServerCapabilities() ?? {};
69
+ if (stableJson(manifest.capabilities ?? {}) !== stableJson(actualCapabilities)) {
70
+ throw new McpFnAssertionError(
71
+ `Capability mismatch
72
+ expected: ${stableJson(manifest.capabilities ?? {})}
73
+ actual: ${stableJson(actualCapabilities)}`
74
+ );
75
+ }
76
+ const actualResources = actualCapabilities.resources ? await client.listResources() : [];
77
+ const comparableResources = actualResources.map(({ _meta, ...resource }) => ({
78
+ ...resource,
79
+ metadata: _meta
80
+ }));
81
+ const staticResourceUris = new Set(
82
+ (manifest.resources ?? []).map((resource) => resource.uri)
83
+ );
84
+ const resourceTemplates = (manifest.resourceTemplates ?? []).map(
85
+ (template) => new UriTemplate(template.uriTemplate)
86
+ );
87
+ const comparableStaticResources = comparableResources.filter(
88
+ (resource) => staticResourceUris.has(resource.uri) || !resourceTemplates.some((template) => template.match(resource.uri))
89
+ );
90
+ const expectedResources = (manifest.resources ?? []).map(
91
+ ({ subscribable: _subscribable, ...resource }) => resource
92
+ );
93
+ if (stableJson(expectedResources) !== stableJson(comparableStaticResources)) {
94
+ throw new McpFnAssertionError(
95
+ `Resource inventory mismatch
96
+ expected: ${stableJson(expectedResources)}
97
+ actual: ${stableJson(comparableStaticResources)}`
98
+ );
99
+ }
100
+ const actualTemplates = actualCapabilities.resources ? await client.listResourceTemplates() : [];
101
+ const comparableTemplates = actualTemplates.map(({ _meta, ...template }) => ({
102
+ ...template,
103
+ metadata: _meta
104
+ }));
105
+ const expectedTemplates = (manifest.resourceTemplates ?? []).map(
106
+ ({ subscribable: _subscribable, ...template }) => template
107
+ );
108
+ if (stableJson(expectedTemplates) !== stableJson(comparableTemplates)) {
109
+ throw new McpFnAssertionError(
110
+ `Resource template inventory mismatch
111
+ expected: ${stableJson(expectedTemplates)}
112
+ actual: ${stableJson(comparableTemplates)}`
113
+ );
114
+ }
115
+ for (const resource of comparableResources) {
116
+ const expected = (manifest.resources ?? []).find(
117
+ (candidate) => candidate.uri === resource.uri
118
+ ) ?? (manifest.resourceTemplates ?? []).find(
119
+ (candidate) => new UriTemplate(candidate.uriTemplate).match(resource.uri)
120
+ );
121
+ const subscribable = expected?.subscribable === true;
122
+ if (subscribable) {
123
+ try {
124
+ await client.subscribeResource(resource.uri);
125
+ await client.unsubscribeResource(resource.uri);
126
+ } catch (error) {
127
+ throw new McpFnAssertionError(
128
+ `Resource subscription mismatch for ${resource.uri}: expected subscribe and unsubscribe to succeed (${error instanceof Error ? error.message : String(error)})`
129
+ );
130
+ }
131
+ continue;
132
+ }
133
+ let accepted = false;
134
+ try {
135
+ await client.subscribeResource(resource.uri);
136
+ accepted = true;
137
+ await client.unsubscribeResource(resource.uri).catch(() => void 0);
138
+ } catch {
139
+ }
140
+ if (accepted) {
141
+ throw new McpFnAssertionError(
142
+ `Resource subscription mismatch for ${resource.uri}: expected subscribe to be rejected`
143
+ );
144
+ }
145
+ }
146
+ const actualPrompts = actualCapabilities.prompts ? await client.listPrompts() : [];
147
+ const comparablePrompts = actualPrompts.map(({ _meta, ...prompt }) => ({
148
+ ...prompt,
149
+ metadata: _meta
150
+ }));
151
+ const expectedPrompts = (manifest.prompts ?? []).map(({ argumentsSchema: _schema, ...prompt }) => prompt);
152
+ if (stableJson(expectedPrompts) !== stableJson(comparablePrompts)) {
153
+ throw new McpFnAssertionError(
154
+ `Prompt inventory mismatch
155
+ expected: ${stableJson(expectedPrompts)}
156
+ actual: ${stableJson(comparablePrompts)}`
157
+ );
158
+ }
159
+ return actual;
160
+ }
161
+ function assertStructuredTextParity(result) {
162
+ if (!result.structuredContent) {
163
+ throw new McpFnAssertionError("Tool result has no structuredContent");
164
+ }
165
+ const text = (result.content ?? []).find(
166
+ (entry) => !!entry && typeof entry === "object" && entry.type === "text" && typeof entry.text === "string"
167
+ )?.text;
168
+ if (!text) {
169
+ throw new McpFnAssertionError("Tool result has no text content");
170
+ }
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(text);
174
+ } catch {
175
+ throw new McpFnAssertionError("Tool text content is not JSON");
176
+ }
177
+ if (stableJson(parsed) !== stableJson(result.structuredContent)) {
178
+ throw new McpFnAssertionError(
179
+ "Tool text content and structuredContent are not equivalent"
180
+ );
181
+ }
182
+ }
183
+
184
+ // src/auth-core.ts
185
+ var McpFnAuthAssertionError = class extends Error {
186
+ constructor(message) {
187
+ super(message);
188
+ this.name = "McpFnAuthAssertionError";
189
+ }
190
+ };
191
+ function expectedStatus(response, expected, name) {
192
+ const statuses = Array.isArray(expected) ? expected : [expected];
193
+ if (!statuses.includes(response.status)) {
194
+ throw new McpFnAuthAssertionError(
195
+ `${name} expected HTTP ${statuses.join(" or ")}, received ${response.status}`
196
+ );
197
+ }
198
+ }
199
+ function parseBearerChallenge(header) {
200
+ if (!header) return void 0;
201
+ const matches = [...header.matchAll(/(?:^|,)\s*([A-Za-z][A-Za-z0-9_-]*)\s+/g)];
202
+ const selectedIndex = matches.findIndex((entry) => entry[1].toLowerCase() === "bearer");
203
+ if (selectedIndex < 0) return void 0;
204
+ const match = matches[selectedIndex];
205
+ const start = (match.index ?? 0) + match[0].length;
206
+ const end = matches[selectedIndex + 1]?.index ?? header.length;
207
+ const parameters = {};
208
+ const source = header.slice(start, end);
209
+ const pattern = /([A-Za-z][A-Za-z0-9_-]*)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^,\s]+))/g;
210
+ for (const entry of source.matchAll(pattern)) {
211
+ const quoted = entry[2]?.replace(/\\(["\\])/g, "$1");
212
+ parameters[entry[1]] = quoted ?? entry[3] ?? "";
213
+ }
214
+ return { scheme: match[1], parameters };
215
+ }
216
+ function assertBearerResourceChallenge(response, expectedMetadataUrl) {
217
+ const challenge = parseBearerChallenge(response.headers.get("www-authenticate"));
218
+ if (!challenge || challenge.scheme.toLowerCase() !== "bearer") {
219
+ throw new McpFnAuthAssertionError("Expected a Bearer WWW-Authenticate challenge");
220
+ }
221
+ const metadataUrl = challenge.parameters.resource_metadata;
222
+ if (!metadataUrl) {
223
+ throw new McpFnAuthAssertionError(
224
+ "Bearer challenge is missing the resource_metadata parameter"
225
+ );
226
+ }
227
+ try {
228
+ const parsed = new URL(metadataUrl);
229
+ if (!parsed.protocol || !parsed.host) throw new Error("not absolute");
230
+ } catch {
231
+ throw new McpFnAuthAssertionError(
232
+ `Bearer challenge has an invalid resource_metadata URL: ${metadataUrl}`
233
+ );
234
+ }
235
+ if (expectedMetadataUrl && metadataUrl !== expectedMetadataUrl) {
236
+ throw new McpFnAuthAssertionError(
237
+ `Expected resource_metadata=${expectedMetadataUrl}, received ${metadataUrl}`
238
+ );
239
+ }
240
+ return challenge;
241
+ }
242
+ function bearerCredential(token, kind = "oauth") {
243
+ return {
244
+ kind,
245
+ headers: { authorization: `Bearer ${token}` }
246
+ };
247
+ }
248
+ function apiKeyCredential(apiKey, options = {}) {
249
+ const headerName = options.headerName ?? "authorization";
250
+ const value = options.scheme === "" ? apiKey : `${options.scheme ?? "Bearer"} ${apiKey}`;
251
+ return { kind: "api-key", headers: { [headerName]: value } };
252
+ }
253
+ function invalidHeaders(options) {
254
+ return new Headers(options.invalidCredentialHeaders ?? {
255
+ authorization: `Bearer mcpfn-invalid-${options.kind}`
256
+ });
257
+ }
258
+ async function runOne(options, scenario, prepare, expected) {
259
+ let credential;
260
+ try {
261
+ credential = await prepare();
262
+ const headers = credential ? new Headers(credential.headers) : scenario.name === "invalid-credential" ? invalidHeaders(options) : new Headers();
263
+ const response = await options.target.request(headers, scenario);
264
+ expectedStatus(response, expected, scenario.name);
265
+ if (options.kind === "oauth" && scenario.name !== "valid-credential") {
266
+ assertBearerResourceChallenge(
267
+ response,
268
+ options.protectedResourceMetadataUrl
269
+ );
270
+ }
271
+ if (scenario.name === "valid-credential" && credential) {
272
+ await options.verifyAuthenticatedResponse?.(response.clone(), credential);
273
+ }
274
+ return {
275
+ name: scenario.name,
276
+ status: "passed",
277
+ responseStatus: response.status
278
+ };
279
+ } catch (error) {
280
+ return {
281
+ name: scenario.name,
282
+ status: "failed",
283
+ error: error instanceof Error ? error.message : String(error)
284
+ };
285
+ } finally {
286
+ await credential?.dispose?.();
287
+ }
288
+ }
289
+ async function runAuthRegressionSuite(options) {
290
+ const issue = (overrides = {}) => options.provider.issue({
291
+ kind: options.kind,
292
+ scopes: options.requiredScopes,
293
+ resource: options.resource,
294
+ ...overrides
295
+ });
296
+ const results = [];
297
+ results.push(await runOne(
298
+ options,
299
+ { name: "missing-credential", kind: options.kind },
300
+ async () => void 0,
301
+ 401
302
+ ));
303
+ results.push(await runOne(
304
+ options,
305
+ { name: "invalid-credential", kind: options.kind },
306
+ async () => void 0,
307
+ 401
308
+ ));
309
+ results.push(await runOne(
310
+ options,
311
+ { name: "valid-credential", kind: options.kind },
312
+ () => issue(),
313
+ options.expectedAuthenticatedStatuses ?? [200, 201, 202, 204]
314
+ ));
315
+ const capabilities = options.provider.capabilities ?? {};
316
+ if (capabilities.scopes && options.requiredScopes?.length) {
317
+ results.push(await runOne(
318
+ options,
319
+ { name: "insufficient-scope", kind: options.kind },
320
+ () => issue({ scopes: [] }),
321
+ 403
322
+ ));
323
+ }
324
+ if (capabilities.expiration) {
325
+ results.push(await runOne(
326
+ options,
327
+ { name: "expired-credential", kind: options.kind },
328
+ () => issue({ expiresInSeconds: -60 }),
329
+ 401
330
+ ));
331
+ }
332
+ if (capabilities.resourceBinding && options.resource) {
333
+ results.push(await runOne(
334
+ options,
335
+ { name: "missing-resource", kind: options.kind },
336
+ () => issue({ resource: void 0 }),
337
+ 401
338
+ ));
339
+ }
340
+ if (capabilities.resourceBinding && options.wrongResource) {
341
+ results.push(await runOne(
342
+ options,
343
+ { name: "wrong-resource", kind: options.kind },
344
+ () => issue({ resource: options.wrongResource }),
345
+ 401
346
+ ));
347
+ }
348
+ if (capabilities.revocation && options.provider.revoke) {
349
+ results.push(await runOne(
350
+ options,
351
+ { name: "revoked-credential", kind: options.kind },
352
+ async () => {
353
+ const credential = await issue();
354
+ await options.provider.revoke?.(credential);
355
+ return credential;
356
+ },
357
+ 401
358
+ ));
359
+ }
360
+ return results;
361
+ }
362
+ async function assertAuthRegressionSuite(options) {
363
+ const results = await runAuthRegressionSuite(options);
364
+ const failures = results.filter((result) => result.status === "failed");
365
+ if (failures.length) {
366
+ throw new McpFnAuthAssertionError(
367
+ failures.map((failure) => `${failure.name}: ${failure.error}`).join("\n")
368
+ );
369
+ }
370
+ return results;
371
+ }
372
+ function createFetchAuthTarget(options) {
373
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
374
+ if (!fetchImplementation) {
375
+ throw new Error("A fetch implementation is required");
376
+ }
377
+ return {
378
+ async request(authHeaders, scenario) {
379
+ const configured = typeof options.requestInit === "function" ? options.requestInit(scenario) : options.requestInit ?? {};
380
+ const headers = new Headers(configured.headers);
381
+ headers.set("accept", "application/json, text/event-stream");
382
+ headers.set("content-type", "application/json");
383
+ authHeaders.forEach((value, name) => headers.set(name, value));
384
+ return fetchImplementation(options.url, {
385
+ method: "POST",
386
+ body: JSON.stringify({
387
+ jsonrpc: "2.0",
388
+ id: `mcpfn-auth-${scenario.name}`,
389
+ method: "initialize",
390
+ params: {
391
+ protocolVersion: "2025-11-25",
392
+ capabilities: {},
393
+ clientInfo: { name: "mcpfn-auth-test", version: "1.0.0" }
394
+ }
395
+ }),
396
+ ...configured,
397
+ headers
398
+ });
399
+ }
400
+ };
401
+ }
402
+ var MCPFN_OAUTH_EXTENSION_GRANTS = {
403
+ jwtBearer: "urn:ietf:params:oauth:grant-type:jwt-bearer",
404
+ deviceCode: "urn:ietf:params:oauth:grant-type:device_code",
405
+ generic: "urn:example:params:oauth:grant-type:extension"
406
+ };
407
+ function createOAuthClientMetadataFixture(options) {
408
+ return {
409
+ ...options.extraMetadata,
410
+ client_id: new URL(options.clientId).toString(),
411
+ client_name: options.clientName ?? "McpFn OAuth test client",
412
+ redirect_uris: [...new Set(options.redirectUris.map((uri) => new URL(uri).toString()))],
413
+ response_types: ["code"],
414
+ grant_types: [
415
+ "authorization_code",
416
+ "refresh_token",
417
+ ...new Set(options.extraGrantTypes ?? [])
418
+ ],
419
+ token_endpoint_auth_method: "none"
420
+ };
421
+ }
422
+ function createOAuthClientMetadataVariants(baseUrl, redirectUri = new URL("/callback", baseUrl).toString()) {
423
+ const base = new URL(baseUrl);
424
+ const fixture = (name, extraGrantTypes = []) => createOAuthClientMetadataFixture({
425
+ clientId: new URL(`/client-metadata/${name}`, base).toString(),
426
+ redirectUris: [redirectUri],
427
+ clientName: `McpFn ${name} client`,
428
+ extraGrantTypes
429
+ });
430
+ return {
431
+ basic: fixture("basic"),
432
+ jwtBearerExtension: fixture("jwt-bearer-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.jwtBearer]),
433
+ deviceCodeExtension: fixture("device-code-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.deviceCode]),
434
+ genericExtension: fixture("generic-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.generic])
435
+ };
436
+ }
437
+ function assertAuthorizationCodeClientMetadata(metadata, expectedClientId) {
438
+ if (expectedClientId && metadata.client_id !== new URL(expectedClientId).toString()) {
439
+ throw new McpFnAuthAssertionError("OAuth client metadata client_id does not match its document URL");
440
+ }
441
+ if (!metadata.response_types.includes("code")) {
442
+ throw new McpFnAuthAssertionError("OAuth client metadata does not support response_type=code");
443
+ }
444
+ if (!metadata.grant_types.includes("authorization_code")) {
445
+ throw new McpFnAuthAssertionError("OAuth client metadata does not support authorization_code");
446
+ }
447
+ if (!metadata.redirect_uris.length) {
448
+ throw new McpFnAuthAssertionError("OAuth client metadata must declare at least one redirect URI");
449
+ }
450
+ return metadata;
451
+ }
452
+
453
+ // src/mock-oauth-server.ts
454
+ import { createHash, randomBytes, randomUUID } from "crypto";
455
+ import { createServer } from "http";
456
+ function base64Url(value) {
457
+ return value.toString("base64url");
458
+ }
459
+ function createPkcePair() {
460
+ const verifier = base64Url(randomBytes(48));
461
+ return {
462
+ verifier,
463
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
464
+ method: "S256"
465
+ };
466
+ }
467
+ function uniqueScopes(value) {
468
+ return [...new Set((value ?? "").split(/\s+/).filter(Boolean))].sort();
469
+ }
470
+ function json(status, body) {
471
+ return Response.json(body, {
472
+ status,
473
+ headers: { "cache-control": "no-store" }
474
+ });
475
+ }
476
+ function oauthError(status, error, description) {
477
+ return json(status, { error, error_description: description });
478
+ }
479
+ function escapeHtml(value) {
480
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
481
+ }
482
+ function formValue(form, name) {
483
+ const value = form.get(name);
484
+ return value === null || value === "" ? void 0 : value;
485
+ }
486
+ var McpFnMockOAuthAuthorizationServer = class {
487
+ issuer;
488
+ clientId;
489
+ redirectUris;
490
+ scopesSupported;
491
+ clientMetadata;
492
+ codes = /* @__PURE__ */ new Map();
493
+ accessTokens = /* @__PURE__ */ new Map();
494
+ refreshTokens = /* @__PURE__ */ new Map();
495
+ callbacks = [];
496
+ clock;
497
+ accessTokenLifetimeSeconds;
498
+ authorizationCodeLifetimeSeconds;
499
+ refreshTokenLifetimeSeconds;
500
+ constructor(options) {
501
+ this.issuer = new URL(options.issuer);
502
+ this.issuer.pathname = this.issuer.pathname.replace(/\/?$/, "/");
503
+ this.clientId = options.clientId ?? "mcpfn-playwright";
504
+ this.redirectUris = options.redirectUris?.map((uri) => new URL(uri).toString()) ?? [
505
+ new URL("callback", this.issuer).toString()
506
+ ];
507
+ this.scopesSupported = [...new Set(options.scopesSupported ?? ["mcp:read", "mcp:write"])].sort();
508
+ this.clock = options.clock ?? Date.now;
509
+ this.accessTokenLifetimeSeconds = options.accessTokenLifetimeSeconds ?? 300;
510
+ this.authorizationCodeLifetimeSeconds = options.authorizationCodeLifetimeSeconds ?? 120;
511
+ this.refreshTokenLifetimeSeconds = options.refreshTokenLifetimeSeconds ?? 3600;
512
+ this.clientMetadata = createOAuthClientMetadataVariants(
513
+ this.issuer,
514
+ this.redirectUris[0]
515
+ );
516
+ }
517
+ get metadataUrl() {
518
+ return new URL(".well-known/oauth-authorization-server", this.issuer).toString();
519
+ }
520
+ get authorizationEndpoint() {
521
+ return new URL("authorize", this.issuer).toString();
522
+ }
523
+ get tokenEndpoint() {
524
+ return new URL("token", this.issuer).toString();
525
+ }
526
+ get revocationEndpoint() {
527
+ return new URL("revoke", this.issuer).toString();
528
+ }
529
+ get callbackUrl() {
530
+ return this.redirectUris[0];
531
+ }
532
+ clientMetadataUrl(variant) {
533
+ return this.clientMetadata[variant].client_id;
534
+ }
535
+ authorizationUrl(input) {
536
+ const url = new URL(this.authorizationEndpoint);
537
+ url.searchParams.set("response_type", "code");
538
+ url.searchParams.set("client_id", input.clientId ?? this.clientId);
539
+ url.searchParams.set("redirect_uri", input.redirectUri ?? this.callbackUrl);
540
+ url.searchParams.set("code_challenge", input.codeChallenge);
541
+ url.searchParams.set("code_challenge_method", "S256");
542
+ url.searchParams.set("scope", (input.scopes ?? ["mcp:read"]).join(" "));
543
+ if (input.state) url.searchParams.set("state", input.state);
544
+ if (input.resource) url.searchParams.set("resource", input.resource);
545
+ for (const [name, value] of Object.entries(input.extraParameters ?? {})) {
546
+ url.searchParams.set(name, value);
547
+ }
548
+ return url.toString();
549
+ }
550
+ latestCallback() {
551
+ return this.callbacks.at(-1);
552
+ }
553
+ expireAccessToken(token) {
554
+ const record = this.accessTokens.get(token);
555
+ if (record) record.expiresAt = this.nowSeconds() - 1;
556
+ }
557
+ revokeToken(token) {
558
+ const access = this.accessTokens.get(token);
559
+ if (access) access.revoked = true;
560
+ const refresh = this.refreshTokens.get(token);
561
+ if (refresh) refresh.revoked = true;
562
+ }
563
+ async verifyAccessToken(token) {
564
+ const record = this.accessTokens.get(token);
565
+ if (!record || record.revoked || record.expiresAt <= this.nowSeconds()) {
566
+ throw new Error("Invalid access token");
567
+ }
568
+ return {
569
+ token,
570
+ clientId: record.clientId,
571
+ scopes: record.scopes,
572
+ expiresAt: record.expiresAt,
573
+ ...record.resource ? { resource: new URL(record.resource) } : {}
574
+ };
575
+ }
576
+ async handle(request) {
577
+ const url = new URL(request.url);
578
+ const path2 = url.pathname.replace(this.issuer.pathname.replace(/\/$/, ""), "") || "/";
579
+ if (request.method === "GET" && path2 === "/.well-known/oauth-authorization-server") {
580
+ return json(200, {
581
+ issuer: this.issuer.toString(),
582
+ authorization_endpoint: this.authorizationEndpoint,
583
+ token_endpoint: this.tokenEndpoint,
584
+ revocation_endpoint: this.revocationEndpoint,
585
+ response_types_supported: ["code"],
586
+ grant_types_supported: ["authorization_code", "refresh_token"],
587
+ code_challenge_methods_supported: ["S256"],
588
+ token_endpoint_auth_methods_supported: ["none"],
589
+ scopes_supported: this.scopesSupported
590
+ });
591
+ }
592
+ if (request.method === "GET" && path2.startsWith("/client-metadata/")) {
593
+ const metadata = Object.values(this.clientMetadata).find((candidate) => new URL(candidate.client_id).pathname === url.pathname);
594
+ return metadata ? json(200, metadata) : json(404, { error: "not_found" });
595
+ }
596
+ if (request.method === "GET" && path2 === "/authorize") {
597
+ return this.authorize(url);
598
+ }
599
+ if (request.method === "POST" && path2 === "/token") {
600
+ return this.token(await request.text());
601
+ }
602
+ if (request.method === "POST" && path2 === "/revoke") {
603
+ return this.revoke(await request.text());
604
+ }
605
+ if (request.method === "GET" && path2 === "/callback") {
606
+ const parameters = Object.fromEntries(url.searchParams);
607
+ this.callbacks.push({ url: url.toString(), parameters });
608
+ return new Response(
609
+ `<!doctype html><html><body><main><h1>OAuth callback received</h1><pre>${escapeHtml(JSON.stringify(parameters, null, 2))}</pre></main></body></html>`,
610
+ { headers: { "content-type": "text/html; charset=utf-8" } }
611
+ );
612
+ }
613
+ return json(404, { error: "not_found" });
614
+ }
615
+ nowSeconds() {
616
+ return Math.floor(this.clock() / 1e3);
617
+ }
618
+ resolveClient(clientId) {
619
+ if (clientId === this.clientId) {
620
+ return { clientId, redirectUris: this.redirectUris };
621
+ }
622
+ const metadata = Object.values(this.clientMetadata).find((candidate) => candidate.client_id === clientId);
623
+ if (!metadata) return void 0;
624
+ assertAuthorizationCodeClientMetadata(metadata, clientId);
625
+ return { clientId, redirectUris: metadata.redirect_uris };
626
+ }
627
+ authorize(url) {
628
+ const clientId = url.searchParams.get("client_id") ?? "";
629
+ const redirectUri = url.searchParams.get("redirect_uri") ?? "";
630
+ const client = this.resolveClient(clientId);
631
+ if (!client) return oauthError(400, "invalid_client", "Unknown OAuth client");
632
+ if (!client.redirectUris.includes(redirectUri)) {
633
+ return oauthError(400, "invalid_request", "redirect_uri is not registered");
634
+ }
635
+ if (url.searchParams.get("response_type") !== "code") {
636
+ return this.authorizationRedirect(url, redirectUri, "unsupported_response_type");
637
+ }
638
+ const codeChallenge = url.searchParams.get("code_challenge");
639
+ if (!codeChallenge || url.searchParams.get("code_challenge_method") !== "S256") {
640
+ return this.authorizationRedirect(url, redirectUri, "invalid_request", "PKCE S256 is required");
641
+ }
642
+ const requestedScopes = uniqueScopes(url.searchParams.get("scope"));
643
+ if (requestedScopes.some((scope) => !this.scopesSupported.includes(scope))) {
644
+ return this.authorizationRedirect(url, redirectUri, "invalid_scope");
645
+ }
646
+ const decision = url.searchParams.get("decision");
647
+ if (!decision) {
648
+ const hidden = [...url.searchParams].filter(([name]) => name !== "decision").map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
649
+ return new Response(
650
+ `<!doctype html><html><body><main><h1>Authorize MCP client</h1><p>${escapeHtml(clientId)}</p><form method="get" action="${escapeHtml(this.authorizationEndpoint)}">${hidden}<button name="decision" value="approve">Approve</button><button name="decision" value="deny">Deny</button></form></main></body></html>`,
651
+ { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }
652
+ );
653
+ }
654
+ if (decision === "deny") {
655
+ return this.authorizationRedirect(url, redirectUri, "access_denied");
656
+ }
657
+ if (decision !== "approve") {
658
+ return oauthError(400, "invalid_request", "Unknown authorization decision");
659
+ }
660
+ const code = `mcpfn_code_${randomUUID()}`;
661
+ this.codes.set(code, {
662
+ clientId,
663
+ redirectUri,
664
+ codeChallenge,
665
+ scopes: requestedScopes,
666
+ resource: url.searchParams.get("resource") ?? void 0,
667
+ expiresAt: this.nowSeconds() + this.authorizationCodeLifetimeSeconds,
668
+ used: false
669
+ });
670
+ const callback = new URL(redirectUri);
671
+ callback.searchParams.set("code", code);
672
+ const state = url.searchParams.get("state");
673
+ if (state) callback.searchParams.set("state", state);
674
+ return Response.redirect(callback, 302);
675
+ }
676
+ authorizationRedirect(requestUrl, redirectUri, error, description) {
677
+ const callback = new URL(redirectUri);
678
+ callback.searchParams.set("error", error);
679
+ if (description) callback.searchParams.set("error_description", description);
680
+ const state = requestUrl.searchParams.get("state");
681
+ if (state) callback.searchParams.set("state", state);
682
+ return Response.redirect(callback, 302);
683
+ }
684
+ token(source) {
685
+ const form = new URLSearchParams(source);
686
+ const grantType = formValue(form, "grant_type");
687
+ if (grantType === "authorization_code") return this.exchangeAuthorizationCode(form);
688
+ if (grantType === "refresh_token") return this.exchangeRefreshToken(form);
689
+ return oauthError(400, "unsupported_grant_type", "The grant type is not supported");
690
+ }
691
+ exchangeAuthorizationCode(form) {
692
+ const code = formValue(form, "code");
693
+ const record = code ? this.codes.get(code) : void 0;
694
+ if (!record || record.used || record.expiresAt <= this.nowSeconds()) {
695
+ return oauthError(400, "invalid_grant", "Authorization code is invalid or expired");
696
+ }
697
+ if (formValue(form, "client_id") !== record.clientId || formValue(form, "redirect_uri") !== record.redirectUri) {
698
+ return oauthError(400, "invalid_grant", "Authorization code binding does not match");
699
+ }
700
+ const verifier = formValue(form, "code_verifier");
701
+ const challenge = verifier ? createHash("sha256").update(verifier).digest("base64url") : void 0;
702
+ if (challenge !== record.codeChallenge) {
703
+ return oauthError(400, "invalid_grant", "PKCE verification failed");
704
+ }
705
+ record.used = true;
706
+ return json(200, this.issueTokenSet(record));
707
+ }
708
+ exchangeRefreshToken(form) {
709
+ const refreshToken = formValue(form, "refresh_token");
710
+ const record = refreshToken ? this.refreshTokens.get(refreshToken) : void 0;
711
+ if (!record || record.revoked || record.expiresAt <= this.nowSeconds()) {
712
+ return oauthError(400, "invalid_grant", "Refresh token is invalid or expired");
713
+ }
714
+ if (formValue(form, "client_id") !== record.clientId) {
715
+ return oauthError(400, "invalid_grant", "Refresh token client binding does not match");
716
+ }
717
+ const requestedScopes = form.has("scope") ? uniqueScopes(form.get("scope")) : record.scopes;
718
+ if (requestedScopes.some((scope) => !record.scopes.includes(scope))) {
719
+ return oauthError(400, "invalid_scope", "Refresh cannot increase granted scopes");
720
+ }
721
+ record.revoked = true;
722
+ return json(200, this.issueTokenSet({ ...record, scopes: requestedScopes }));
723
+ }
724
+ issueTokenSet(input) {
725
+ const accessToken = `mcpfn_access_${randomUUID()}`;
726
+ const refreshToken = `mcpfn_refresh_${randomUUID()}`;
727
+ this.accessTokens.set(accessToken, {
728
+ ...input,
729
+ expiresAt: this.nowSeconds() + this.accessTokenLifetimeSeconds,
730
+ revoked: false
731
+ });
732
+ this.refreshTokens.set(refreshToken, {
733
+ ...input,
734
+ expiresAt: this.nowSeconds() + this.refreshTokenLifetimeSeconds,
735
+ revoked: false
736
+ });
737
+ return {
738
+ access_token: accessToken,
739
+ token_type: "Bearer",
740
+ expires_in: this.accessTokenLifetimeSeconds,
741
+ refresh_token: refreshToken,
742
+ scope: input.scopes.join(" "),
743
+ ...input.resource ? { resource: input.resource } : {}
744
+ };
745
+ }
746
+ revoke(source) {
747
+ const token = new URLSearchParams(source).get("token");
748
+ if (token) this.revokeToken(token);
749
+ return new Response(null, { status: 200 });
750
+ }
751
+ };
752
+ async function toRequest(req, origin) {
753
+ const chunks = [];
754
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
755
+ const headers = new Headers();
756
+ for (const [name, value] of Object.entries(req.headers)) {
757
+ if (Array.isArray(value)) {
758
+ for (const entry of value) headers.append(name, entry);
759
+ } else if (value !== void 0) {
760
+ headers.set(name, value);
761
+ }
762
+ }
763
+ const body = chunks.length ? Buffer.concat(chunks) : void 0;
764
+ const init = {
765
+ method: req.method,
766
+ headers,
767
+ ...body ? { body, duplex: "half" } : {}
768
+ };
769
+ return new Request(new URL(req.url ?? "/", origin), init);
770
+ }
771
+ async function writeResponse(res, response) {
772
+ res.statusCode = response.status;
773
+ response.headers.forEach((value, name) => res.setHeader(name, value));
774
+ res.end(Buffer.from(await response.arrayBuffer()));
775
+ }
776
+ async function startMockOAuthAuthorizationServer(options = {}) {
777
+ let oauth;
778
+ let origin = "";
779
+ const server = createServer(async (req, res) => {
780
+ try {
781
+ if (!oauth) throw new Error("Mock OAuth server is not initialized");
782
+ await writeResponse(res, await oauth.handle(await toRequest(req, origin)));
783
+ } catch {
784
+ res.statusCode = 500;
785
+ res.setHeader("content-type", "application/json");
786
+ res.end(JSON.stringify({
787
+ error: "server_error",
788
+ error_description: "Internal Server Error"
789
+ }));
790
+ }
791
+ });
792
+ await new Promise((resolve, reject) => {
793
+ server.once("error", reject);
794
+ server.listen(options.port ?? 0, options.hostname ?? "127.0.0.1", () => {
795
+ server.off("error", reject);
796
+ resolve();
797
+ });
798
+ });
799
+ const address = server.address();
800
+ origin = `http://${address.address.includes(":") ? `[${address.address}]` : address.address}:${address.port}`;
801
+ oauth = new McpFnMockOAuthAuthorizationServer({ ...options, issuer: origin });
802
+ return {
803
+ origin,
804
+ oauth,
805
+ close: () => new Promise((resolve, reject) => {
806
+ server.close((error) => error ? reject(error) : resolve());
807
+ })
808
+ };
809
+ }
810
+
811
+ // src/client.ts
812
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
813
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
814
+ import {
815
+ CallToolResultSchema,
816
+ CreateTaskResultSchema
817
+ } from "@modelcontextprotocol/sdk/types.js";
818
+ var McpFnTestClient = class _McpFnTestClient {
819
+ client;
820
+ server;
821
+ closed = false;
822
+ constructor(client, server) {
823
+ this.client = client;
824
+ this.server = server;
825
+ }
826
+ static async connect(server, info = { name: "mcpfn-test-client", version: "1.0.0" }, options = {}) {
827
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
828
+ const client = new Client(info, { capabilities: options.capabilities ?? {} });
829
+ await options.configure?.(client);
830
+ await server.connect(serverTransport);
831
+ await client.connect(clientTransport);
832
+ return new _McpFnTestClient(client, server);
833
+ }
834
+ async listTools() {
835
+ const values = [];
836
+ let cursor;
837
+ do {
838
+ const page = await this.client.listTools(cursor ? { cursor } : void 0);
839
+ values.push(...page.tools);
840
+ cursor = page.nextCursor;
841
+ } while (cursor);
842
+ return values;
843
+ }
844
+ async callTool(name, args = {}) {
845
+ return await this.client.callTool({ name, arguments: args });
846
+ }
847
+ async createToolTask(name, args = {}, options = {}) {
848
+ return this.client.request(
849
+ {
850
+ method: "tools/call",
851
+ params: { name, arguments: args, task: options }
852
+ },
853
+ CreateTaskResultSchema
854
+ );
855
+ }
856
+ getTask(taskId) {
857
+ return this.client.experimental.tasks.getTask(taskId);
858
+ }
859
+ getTaskResult(taskId) {
860
+ return this.client.experimental.tasks.getTaskResult(
861
+ taskId,
862
+ CallToolResultSchema
863
+ );
864
+ }
865
+ listTasks(cursor) {
866
+ return this.client.experimental.tasks.listTasks(cursor);
867
+ }
868
+ cancelTask(taskId) {
869
+ return this.client.experimental.tasks.cancelTask(taskId);
870
+ }
871
+ async listResources() {
872
+ const values = [];
873
+ let cursor;
874
+ do {
875
+ const page = await this.client.listResources(cursor ? { cursor } : void 0);
876
+ values.push(...page.resources);
877
+ cursor = page.nextCursor;
878
+ } while (cursor);
879
+ return values;
880
+ }
881
+ async listResourceTemplates() {
882
+ const values = [];
883
+ let cursor;
884
+ do {
885
+ const page = await this.client.listResourceTemplates(cursor ? { cursor } : void 0);
886
+ values.push(...page.resourceTemplates);
887
+ cursor = page.nextCursor;
888
+ } while (cursor);
889
+ return values;
890
+ }
891
+ readResource(uri) {
892
+ return this.client.readResource({ uri });
893
+ }
894
+ async subscribeResource(uri) {
895
+ await this.client.subscribeResource({ uri });
896
+ }
897
+ async unsubscribeResource(uri) {
898
+ await this.client.unsubscribeResource({ uri });
899
+ }
900
+ async listPrompts() {
901
+ const values = [];
902
+ let cursor;
903
+ do {
904
+ const page = await this.client.listPrompts(cursor ? { cursor } : void 0);
905
+ values.push(...page.prompts);
906
+ cursor = page.nextCursor;
907
+ } while (cursor);
908
+ return values;
909
+ }
910
+ getPrompt(name, args) {
911
+ return this.client.getPrompt({ name, ...args ? { arguments: args } : {} });
912
+ }
913
+ complete(params) {
914
+ return this.client.complete(params);
915
+ }
916
+ async close() {
917
+ if (this.closed) return;
918
+ this.closed = true;
919
+ await this.client.close().catch(() => void 0);
920
+ await this.server.close().catch(() => void 0);
921
+ }
922
+ };
923
+
924
+ // src/conformance.ts
925
+ import { spawn } from "child_process";
926
+ import { existsSync } from "fs";
927
+ import path from "path";
928
+ var OFFICIAL_CONFORMANCE_VERSION = "0.1.16";
929
+ function npxInvocation(args) {
930
+ if (process.platform !== "win32") return { command: "npx", args };
931
+ const npmExecPath = process.env.npm_execpath;
932
+ const candidates = [
933
+ npmExecPath ? path.join(path.dirname(npmExecPath), "npx-cli.js") : void 0,
934
+ path.resolve(path.dirname(process.execPath), "node_modules/npm/bin/npx-cli.js"),
935
+ path.resolve(path.dirname(process.execPath), "../lib/node_modules/npm/bin/npx-cli.js")
936
+ ].filter((candidate) => Boolean(candidate));
937
+ const npxCli = candidates.find((candidate) => existsSync(candidate));
938
+ if (!npxCli) {
939
+ throw new Error("Unable to locate npm's npx-cli.js for the official MCP conformance runner");
940
+ }
941
+ return { command: process.execPath, args: [npxCli, ...args] };
942
+ }
943
+ function buildOfficialConformanceArgs(options) {
944
+ const args = [
945
+ "--yes",
946
+ `@modelcontextprotocol/conformance@${OFFICIAL_CONFORMANCE_VERSION}`,
947
+ "server",
948
+ "--url",
949
+ options.url
950
+ ];
951
+ if (options.suite) args.push("--suite", options.suite);
952
+ if (options.scenario) args.push("--scenario", options.scenario);
953
+ if (options.expectedFailures) {
954
+ args.push("--expected-failures", options.expectedFailures);
955
+ }
956
+ if (options.outputDir) args.push("--output-dir", options.outputDir);
957
+ if (options.specVersion) args.push("--spec-version", options.specVersion);
958
+ if (options.verbose) args.push("--verbose");
959
+ return args;
960
+ }
961
+ async function runOfficialConformance(options) {
962
+ const nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10);
963
+ if (nodeMajor < 22) {
964
+ throw new Error(
965
+ `Official MCP conformance ${OFFICIAL_CONFORMANCE_VERSION} requires Node.js 22 or newer; current runtime is ${process.versions.node}`
966
+ );
967
+ }
968
+ const args = buildOfficialConformanceArgs(options);
969
+ const invocation = npxInvocation(args);
970
+ return await new Promise((resolve, reject) => {
971
+ const child = spawn(invocation.command, invocation.args, {
972
+ cwd: options.cwd,
973
+ env: {
974
+ ...process.env,
975
+ PATH: [path.dirname(process.execPath), process.env.PATH].filter(Boolean).join(path.delimiter)
976
+ },
977
+ stdio: options.stdio === "inherit" ? "inherit" : "pipe"
978
+ });
979
+ let stdout = "";
980
+ let stderr = "";
981
+ child.stdout?.on("data", (chunk) => {
982
+ stdout += chunk.toString();
983
+ });
984
+ child.stderr?.on("data", (chunk) => {
985
+ stderr += chunk.toString();
986
+ });
987
+ child.once("error", reject);
988
+ child.once("close", (code) => {
989
+ resolve({ exitCode: code ?? 1, stdout, stderr });
990
+ });
991
+ });
992
+ }
993
+
994
+ // src/host-profiles.ts
995
+ import {
996
+ MCP_APP_EXTENSION_ID
997
+ } from "@mcpfn/core";
998
+ var MCPFN_HOST_PROFILES = {
999
+ toolsOnly: {
1000
+ id: "mcpfn/tools-only",
1001
+ name: "Tools-only MCP host",
1002
+ protocolVersions: ["2025-03-26", "2025-06-18", "2025-11-25"],
1003
+ serverFeatures: ["tools"]
1004
+ },
1005
+ fullProtocol: {
1006
+ id: "mcpfn/full-protocol",
1007
+ name: "Full protocol MCP host",
1008
+ protocolVersions: ["2025-03-26", "2025-06-18", "2025-11-25"],
1009
+ serverFeatures: ["tools", "resources", "prompts", "completions", "tasks", "logging"],
1010
+ clientFeatures: { sampling: true, elicitation: ["form", "url"], roots: true }
1011
+ },
1012
+ mcpApps: {
1013
+ id: "mcpfn/mcp-apps",
1014
+ name: "Full protocol host with MCP Apps",
1015
+ protocolVersions: ["2025-11-25"],
1016
+ serverFeatures: ["tools", "resources", "prompts", "completions", "tasks", "logging"],
1017
+ clientFeatures: { sampling: true, elicitation: ["form", "url"], roots: true },
1018
+ extensions: [MCP_APP_EXTENSION_ID]
1019
+ }
1020
+ };
1021
+ function checkHostCompatibility(manifest, profile) {
1022
+ const issues = [];
1023
+ if (manifest.protocolVersions?.length && !manifest.protocolVersions.some((version) => profile.protocolVersions.includes(version))) {
1024
+ issues.push({
1025
+ severity: "incompatible",
1026
+ code: "protocol-version-mismatch",
1027
+ path: "protocolVersions",
1028
+ message: `${profile.name} and ${manifest.server.name} have no protocol version in common`
1029
+ });
1030
+ }
1031
+ const supportedServerFeatures = new Set(profile.serverFeatures);
1032
+ for (const feature of Object.keys(manifest.capabilities ?? {})) {
1033
+ if (feature === "experimental" || supportedServerFeatures.has(feature)) continue;
1034
+ issues.push({
1035
+ severity: "degraded",
1036
+ code: "server-feature-unavailable",
1037
+ path: `capabilities.${feature}`,
1038
+ message: `${profile.name} will not expose the server's ${feature} feature`
1039
+ });
1040
+ }
1041
+ const required = manifest.clientRequirements;
1042
+ if (required?.sampling && !profile.clientFeatures?.sampling) {
1043
+ issues.push({
1044
+ severity: "incompatible",
1045
+ code: "sampling-required",
1046
+ path: "clientRequirements.sampling",
1047
+ message: `${manifest.server.name} requires client sampling`
1048
+ });
1049
+ }
1050
+ if (required?.roots && !profile.clientFeatures?.roots) {
1051
+ issues.push({
1052
+ severity: "incompatible",
1053
+ code: "roots-required",
1054
+ path: "clientRequirements.roots",
1055
+ message: `${manifest.server.name} requires client roots`
1056
+ });
1057
+ }
1058
+ for (const mode of required?.elicitation ?? []) {
1059
+ if (!profile.clientFeatures?.elicitation?.includes(mode)) {
1060
+ issues.push({
1061
+ severity: "incompatible",
1062
+ code: "elicitation-required",
1063
+ path: `clientRequirements.elicitation.${mode}`,
1064
+ message: `${manifest.server.name} requires ${mode} elicitation`
1065
+ });
1066
+ }
1067
+ }
1068
+ const extensions = new Set(profile.extensions ?? []);
1069
+ for (const [extension, configuration] of Object.entries(manifest.extensions ?? {})) {
1070
+ if (extensions.has(extension)) continue;
1071
+ const requiredExtension = configuration && typeof configuration === "object" && configuration.required === true;
1072
+ issues.push({
1073
+ severity: requiredExtension ? "incompatible" : "degraded",
1074
+ code: "extension-unavailable",
1075
+ path: `extensions.${extension}`,
1076
+ message: `${profile.name} does not support ${extension}`
1077
+ });
1078
+ }
1079
+ if (!extensions.has(MCP_APP_EXTENSION_ID)) {
1080
+ for (const tool of manifest.tools) {
1081
+ const ui = tool.metadata?.ui;
1082
+ if (ui?.visibility?.length && !ui.visibility.includes("model")) {
1083
+ issues.push({
1084
+ severity: "incompatible",
1085
+ code: "app-only-tool-unavailable",
1086
+ path: `tools.${tool.name}.metadata.ui.visibility`,
1087
+ message: `${tool.name} is app-only but ${profile.name} does not support MCP Apps`
1088
+ });
1089
+ }
1090
+ }
1091
+ }
1092
+ issues.sort((left, right) => left.path.localeCompare(right.path) || left.code.localeCompare(right.code));
1093
+ const status = issues.some((issue) => issue.severity === "incompatible") ? "incompatible" : issues.length ? "degraded" : "compatible";
1094
+ return { status, compatible: status !== "incompatible", issues };
1095
+ }
1096
+
1097
+ // src/scenarios.ts
1098
+ async function runScenarios(client, scenarios) {
1099
+ const results = [];
1100
+ for (const scenario of scenarios) {
1101
+ const startedAt = performance.now();
1102
+ try {
1103
+ const result = await client.callTool(scenario.tool, scenario.arguments);
1104
+ if (result.isError && scenario.expect?.isError === void 0) {
1105
+ throw new McpFnAssertionError(
1106
+ "Tool returned isError=true without an explicit expect.isError=true assertion"
1107
+ );
1108
+ }
1109
+ if (scenario.expect?.isError !== void 0 && Boolean(result.isError) !== scenario.expect.isError) {
1110
+ throw new McpFnAssertionError(
1111
+ `Expected isError=${scenario.expect.isError}, received ${Boolean(result.isError)}`
1112
+ );
1113
+ }
1114
+ if (scenario.expect && Object.prototype.hasOwnProperty.call(scenario.expect, "structuredContent") && stableJson(result.structuredContent) !== stableJson(scenario.expect.structuredContent)) {
1115
+ throw new McpFnAssertionError(
1116
+ `Structured result mismatch
1117
+ expected: ${stableJson(scenario.expect.structuredContent)}
1118
+ actual: ${stableJson(result.structuredContent)}`
1119
+ );
1120
+ }
1121
+ if (scenario.expect?.structuredTextParity) {
1122
+ assertStructuredTextParity(result);
1123
+ }
1124
+ await scenario.verify?.(result);
1125
+ results.push({
1126
+ name: scenario.name,
1127
+ tool: scenario.tool,
1128
+ status: "passed",
1129
+ durationMs: performance.now() - startedAt
1130
+ });
1131
+ } catch (error) {
1132
+ results.push({
1133
+ name: scenario.name,
1134
+ tool: scenario.tool,
1135
+ status: "failed",
1136
+ durationMs: performance.now() - startedAt,
1137
+ error: error instanceof Error ? error.message : String(error)
1138
+ });
1139
+ }
1140
+ }
1141
+ return results;
1142
+ }
1143
+ export {
1144
+ MCPFN_HOST_PROFILES,
1145
+ MCPFN_OAUTH_EXTENSION_GRANTS,
1146
+ McpFnAssertionError,
1147
+ McpFnAuthAssertionError,
1148
+ McpFnMockOAuthAuthorizationServer,
1149
+ McpFnTestClient,
1150
+ OFFICIAL_CONFORMANCE_VERSION,
1151
+ apiKeyCredential,
1152
+ assertAuthRegressionSuite,
1153
+ assertAuthorizationCodeClientMetadata,
1154
+ assertBearerResourceChallenge,
1155
+ assertManifestContract,
1156
+ assertStructuredTextParity,
1157
+ bearerCredential,
1158
+ buildOfficialConformanceArgs,
1159
+ checkHostCompatibility,
1160
+ createFetchAuthTarget,
1161
+ createOAuthClientMetadataFixture,
1162
+ createOAuthClientMetadataVariants,
1163
+ createPkcePair,
1164
+ parseBearerChallenge,
1165
+ runAuthRegressionSuite,
1166
+ runOfficialConformance,
1167
+ runScenarios,
1168
+ stableJson,
1169
+ startMockOAuthAuthorizationServer
1170
+ };
1171
+ //# sourceMappingURL=index.js.map