@lostgradient/mcp 0.1.0 → 0.2.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.
Files changed (84) hide show
  1. package/README.md +68 -8
  2. package/dist/chunk-3ek3knfm.js +73 -0
  3. package/dist/{chunk-v14p4gng.js → chunk-3rr24vhh.js} +4 -1
  4. package/dist/chunk-6ekjtvcq.js +273 -0
  5. package/dist/chunk-7dpts3r9.js +909 -0
  6. package/dist/chunk-88nhf6xt.js +449 -0
  7. package/dist/{chunk-psnez3q2.js → chunk-k6fm3cmk.js} +23 -2
  8. package/dist/chunk-rxnyn7tf.js +19 -0
  9. package/dist/{chunk-mf3t0afg.js → chunk-wfty87ws.js} +1 -1
  10. package/dist/{chunk-wmkqd45r.js → chunk-xcf742mf.js} +1 -1
  11. package/dist/chunk-yf4nw40e.js +1102 -0
  12. package/dist/conformance.d.ts +43 -0
  13. package/dist/env.d.ts +1 -1
  14. package/dist/env.js +2 -2
  15. package/dist/environment-schema.d.ts +1 -1
  16. package/dist/environment-schema.js +1 -1
  17. package/dist/http/authenticate.d.ts +35 -0
  18. package/dist/http/authorization-header.d.ts +5 -0
  19. package/dist/http/grant-revocation-channel.d.ts +24 -0
  20. package/dist/http/handler.d.ts +32 -0
  21. package/dist/http/index.d.ts +27 -0
  22. package/dist/http/index.js +813 -0
  23. package/dist/http/request-context.d.ts +17 -0
  24. package/dist/http/responses.d.ts +11 -0
  25. package/dist/http/serving-layer.d.ts +18 -0
  26. package/dist/http/user-handler-cache.d.ts +37 -0
  27. package/dist/http/user-server-event-bus.d.ts +35 -0
  28. package/dist/index.d.ts +5 -1
  29. package/dist/index.js +230 -940
  30. package/dist/logger.d.ts +20 -0
  31. package/dist/logger.js +9 -5
  32. package/dist/oauth/authorize-endpoint.d.ts +5 -0
  33. package/dist/oauth/canonicalize-ip-address.d.ts +20 -0
  34. package/dist/oauth/client-authentication.d.ts +10 -0
  35. package/dist/oauth/client-metadata-documents.d.ts +52 -0
  36. package/dist/oauth/client-metadata-documents.js +19 -0
  37. package/dist/oauth/discovery-metadata.d.ts +19 -0
  38. package/dist/oauth/endpoint-rate-limits.d.ts +10 -0
  39. package/dist/oauth/endpoint-responses.d.ts +10 -0
  40. package/dist/oauth/index.d.ts +214 -0
  41. package/dist/oauth/index.js +69 -0
  42. package/dist/oauth/network-identity.d.ts +32 -0
  43. package/dist/oauth/pkce-validation.d.ts +2 -0
  44. package/dist/oauth/postgres/client-store.d.ts +12 -0
  45. package/dist/oauth/postgres/code-store.d.ts +14 -0
  46. package/dist/oauth/postgres/database.d.ts +18 -0
  47. package/dist/oauth/postgres/index.d.ts +11 -0
  48. package/dist/oauth/postgres/index.js +584 -0
  49. package/dist/oauth/postgres/schema.d.ts +1455 -0
  50. package/dist/oauth/postgres/token-store.d.ts +16 -0
  51. package/dist/oauth/postgres/transaction-store.d.ts +14 -0
  52. package/dist/oauth/redirect-uri-matching.d.ts +2 -0
  53. package/dist/oauth/registration-endpoint.d.ts +2 -0
  54. package/dist/oauth/request-body.d.ts +14 -0
  55. package/dist/oauth/revocation-endpoint.d.ts +2 -0
  56. package/dist/oauth/safe-public-https-fetch.d.ts +28 -0
  57. package/dist/oauth/scope-utilities.d.ts +15 -0
  58. package/dist/oauth/security-utilities.d.ts +8 -0
  59. package/dist/oauth/stores.d.ts +225 -0
  60. package/dist/oauth/stores.js +0 -0
  61. package/dist/oauth/testing/contract-fixtures.d.ts +134 -0
  62. package/dist/oauth/testing/index.d.ts +56 -0
  63. package/dist/oauth/testing/index.js +330 -0
  64. package/dist/oauth/token-endpoint.d.ts +2 -0
  65. package/dist/oauth-scope-configuration.d.ts +3 -0
  66. package/dist/rate-limit/in-memory-sliding-window-store.d.ts +3 -0
  67. package/dist/rate-limit/index.d.ts +23 -0
  68. package/dist/rate-limit/index.js +29 -0
  69. package/dist/rate-limit/mcp-concurrency-limiter.d.ts +26 -0
  70. package/dist/rate-limit/rate-limit-response.d.ts +1 -0
  71. package/dist/rate-limit/redis-sliding-window-store.d.ts +2 -0
  72. package/dist/rate-limit/request-rate-limiter.d.ts +10 -0
  73. package/dist/rate-limit/sliding-window-rate-limiter.d.ts +16 -0
  74. package/dist/scopes.d.ts +1 -1
  75. package/dist/server.d.ts +1 -1
  76. package/dist/sveltekit-mount-state.d.ts +4 -0
  77. package/dist/sveltekit-mount.d.ts +43 -0
  78. package/dist/sveltekit-mount.js +332 -0
  79. package/dist/tool-response.d.ts +6 -0
  80. package/dist/types/primitives.d.ts +1 -1
  81. package/dist/ui-extension-support.d.ts +2 -2
  82. package/dist/version.d.ts +1 -1
  83. package/dist/version.js +1 -1
  84. package/package.json +56 -4
package/dist/index.js CHANGED
@@ -1,863 +1,40 @@
1
1
  import {
2
- getLogger,
3
- logger
4
- } from "./chunk-psnez3q2.js";
5
- import {
6
- getEnvironment,
7
- parseMcpServerEnvironment
8
- } from "./chunk-v14p4gng.js";
2
+ areResourceSubscriptionsAuthorized,
3
+ assertSamplingSupport,
4
+ cancellableOperationTestHooks,
5
+ createMcpServer,
6
+ hasValidLocalhostRebindingHeaders,
7
+ isLoopbackHostname,
8
+ parseSampledText,
9
+ readNotificationSender,
10
+ readProgressToken,
11
+ readRequestSender,
12
+ readSessionIdentifier,
13
+ stringifyUnknown
14
+ } from "./chunk-7dpts3r9.js";
9
15
  import {
10
16
  metricsCollector
11
17
  } from "./chunk-taxyscge.js";
12
- import"./chunk-wmkqd45r.js";
13
18
  import {
14
19
  PACKAGE_VERSION
15
- } from "./chunk-mf3t0afg.js";
16
-
17
- // src/server.ts
18
- import { McpServer, ProtocolError as ProtocolError2 } from "@modelcontextprotocol/server";
19
-
20
- // src/instructions.md
21
- var instructions_default = "This is a Model Context Protocol (MCP) server built from the Bun + Svelte MCP Template. It exposes read-only account tools, a JSON resource, and a summarization prompt over Streamable HTTP, secured by OAuth 2.1 with PKCE. Every call must carry a bearer token issued through this server's own /oauth/authorize and /oauth/token endpoints; there is no anonymous or service-account access. Every operation acts only on the authenticated caller's own account.\n\n## Available capability families\n\n- **Tools** — `get_user_profile` is read-only and idempotent. It returns the authenticated caller's own id, email, name, avatar image, and role. It never accepts a target user identifier and never reads or modifies another account.\n- **Resources** — `user_profile` (`user://profile`) exposes the same caller-scoped profile as a JSON document, for clients that prefer reading a resource over calling a tool.\n- **Prompts** — `summarize` builds a reusable \"summarize this topic\" message for the authenticated caller, given a `topic` argument.\n\n## Authentication and boundaries\n\nEvery request to `/mcp` requires a bearer token obtained through this server's own OAuth authorization code flow with PKCE (`S256`). Tokens are scoped to the account that authorized them; there is no way to act as, or read data belonging to, a different user through any tool, resource, or prompt in this template's default set. None of the default operations are destructive — nothing here deletes or overwrites account data. Rate limits apply to every endpoint; a client that exceeds them receives `429` with a `Retry-After` header rather than a silent failure.\n\n## Workflow examples\n\nTo identify the current user before personalizing a response, call the tool directly:\n\n```\ntools/call { \"name\": \"get_user_profile\", \"arguments\": {} }\n```\n\nTo read the same data as a resource instead of a tool call:\n\n```\nresources/read { \"uri\": \"user://profile\" }\n```\n\nTo ask the assistant to summarize a topic on the caller's behalf:\n\n```\nprompts/get { \"name\": \"summarize\", \"arguments\": { \"topic\": \"quarterly revenue trends\" } }\n```\n";
22
-
23
- // src/server.ts
24
- import { EXTENSION_ID } from "@modelcontextprotocol/ext-apps/server";
25
-
26
- // src/conformance-fixture-registration.ts
27
- import { z } from "zod";
28
- import { ResourceTemplate, completable } from "@modelcontextprotocol/server";
29
-
30
- // src/handler-context.ts
31
- import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
32
- function readMcpReq(ctx) {
33
- if (!ctx || typeof ctx !== "object")
34
- return;
35
- const mcpReq = ctx.mcpReq;
36
- if (!mcpReq || typeof mcpReq !== "object")
37
- return;
38
- return mcpReq;
39
- }
40
- function readProgressToken(ctx) {
41
- const mcpReq = readMcpReq(ctx);
42
- const meta = mcpReq?._meta;
43
- return meta?.progressToken;
44
- }
45
- function readSessionIdentifier(ctx) {
46
- if (!ctx || typeof ctx !== "object")
47
- return;
48
- return ctx.sessionId;
49
- }
50
- function readNotificationSender(ctx) {
51
- const mcpReq = readMcpReq(ctx);
52
- const notify = mcpReq?.notify;
53
- if (typeof notify !== "function")
54
- return;
55
- return notify;
56
- }
57
- function readRequestSender(ctx) {
58
- const mcpReq = readMcpReq(ctx);
59
- const send = mcpReq?.send;
60
- if (typeof send !== "function")
61
- return;
62
- return send;
63
- }
64
- function stringifyUnknown(value) {
65
- if (typeof value === "string")
66
- return value;
67
- try {
68
- return JSON.stringify(value);
69
- } catch {
70
- return String(value);
71
- }
72
- }
73
- function parseSampledText(result) {
74
- const content = result.content;
75
- if (Array.isArray(content) && content.length > 0) {
76
- const first = content[0];
77
- if (typeof first?.text === "string") {
78
- return first.text;
79
- }
80
- }
81
- if (content && typeof content === "object") {
82
- const text = content.text;
83
- if (typeof text === "string") {
84
- return text;
85
- }
86
- }
87
- return stringifyUnknown(result);
88
- }
89
- function assertSamplingSupport(ctx) {
90
- const requestSender = readRequestSender(ctx);
91
- if (!requestSender) {
92
- throw new ProtocolError(ProtocolErrorCode.InvalidRequest, "Client does not support sampling");
93
- }
94
- }
95
-
96
- // src/long-running-operation-support.ts
97
- async function runWithStandardizedTimeout(input) {
98
- const timeoutMilliseconds = input.timeoutMilliseconds ?? 30000;
99
- const internalController = new AbortController;
100
- let timeoutIdentifier;
101
- let rejectOnExternalAbort;
102
- const onExternalAbort = () => {
103
- const cancellationError = new Error("Operation cancelled by client.");
104
- internalController.abort(cancellationError);
105
- rejectOnExternalAbort?.(cancellationError);
106
- };
107
- try {
108
- return await Promise.race([
109
- input.operation(internalController.signal),
110
- new Promise((_, reject) => {
111
- rejectOnExternalAbort = reject;
112
- timeoutIdentifier = setTimeout(() => {
113
- const timeoutError = new Error(`Operation timed out after ${timeoutMilliseconds}ms.`);
114
- internalController.abort(timeoutError);
115
- reject(timeoutError);
116
- }, timeoutMilliseconds);
117
- if (input.abortSignal?.aborted) {
118
- onExternalAbort();
119
- } else {
120
- input.abortSignal?.addEventListener("abort", onExternalAbort, { once: true });
121
- }
122
- })
123
- ]);
124
- } finally {
125
- clearTimeout(timeoutIdentifier);
126
- input.abortSignal?.removeEventListener("abort", onExternalAbort);
127
- if (!internalController.signal.aborted) {
128
- internalController.abort(new Error("Operation settled."));
129
- }
130
- }
131
- }
132
-
133
- // src/conformance-fixture-registration.ts
134
- var oneByOnePngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO5m0QAAAABJRU5ErkJggg==";
135
- var minimalWavBase64 = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAIlYAAESsAAACABAAZGF0YQAAAAA=";
136
- function delay(milliseconds, signal) {
137
- return new Promise((resolve, reject) => {
138
- if (signal?.aborted) {
139
- reject(signal.reason);
140
- return;
141
- }
142
- const timer = setTimeout(resolve, milliseconds);
143
- signal?.addEventListener("abort", () => {
144
- clearTimeout(timer);
145
- reject(signal.reason);
146
- }, { once: true });
147
- });
148
- }
149
- var cancellableOperationTestHooks = {
150
- completedCount: 0,
151
- abortedCount: 0,
152
- reset() {
153
- this.completedCount = 0;
154
- this.abortedCount = 0;
155
- }
156
- };
157
- function registerConformanceFixtures(server, publishResourceUpdate) {
158
- server.registerTool("test_simple_text", { description: "Conformance fixture: returns a single plain-text content block." }, async () => ({
159
- content: [{ type: "text", text: "This is a simple text response." }]
160
- }));
161
- server.registerTool("test_error_handling", { description: "Conformance fixture: always returns a tool-level error result." }, async () => ({
162
- isError: true,
163
- content: [{ type: "text", text: "This is a deliberate test error." }]
164
- }));
165
- server.registerTool("test_image_content", { description: "Conformance fixture: returns an image content block." }, async () => ({
166
- content: [
167
- {
168
- type: "image",
169
- data: oneByOnePngBase64,
170
- mimeType: "image/png"
171
- }
172
- ]
173
- }));
174
- server.registerTool("test_audio_content", { description: "Conformance fixture: returns an audio content block." }, async () => ({
175
- content: [
176
- {
177
- type: "audio",
178
- data: minimalWavBase64,
179
- mimeType: "audio/wav"
180
- }
181
- ]
182
- }));
183
- server.registerTool("test_embedded_resource", { description: "Conformance fixture: returns embedded resource content." }, async () => ({
184
- content: [
185
- {
186
- type: "resource",
187
- resource: {
188
- uri: "test://embedded-resource",
189
- mimeType: "text/plain",
190
- text: "This is an embedded resource content."
191
- }
192
- }
193
- ]
194
- }));
195
- server.registerTool("test_multiple_content_types", { description: "Conformance fixture: returns text, image, and resource content." }, async () => ({
196
- content: [
197
- {
198
- type: "text",
199
- text: "Multiple content types test:"
200
- },
201
- {
202
- type: "image",
203
- data: oneByOnePngBase64,
204
- mimeType: "image/png"
205
- },
206
- {
207
- type: "resource",
208
- resource: {
209
- uri: "test://mixed-content-resource",
210
- mimeType: "application/json",
211
- text: '{"test":"data","value":123}'
212
- }
213
- }
214
- ]
215
- }));
216
- server.registerTool("test_tool_with_logging", {
217
- description: "Conformance fixture: sends logging notifications during execution.",
218
- inputSchema: z.object({})
219
- }, async (_input, ctx) => {
220
- const sendNotification = readNotificationSender(ctx);
221
- if (sendNotification) {
222
- await sendNotification({
223
- method: "notifications/message",
224
- params: { level: "info", data: "Tool execution started" }
225
- });
226
- }
227
- await delay(50);
228
- if (sendNotification) {
229
- await sendNotification({
230
- method: "notifications/message",
231
- params: { level: "info", data: "Tool processing data" }
232
- });
233
- }
234
- await delay(50);
235
- if (sendNotification) {
236
- await sendNotification({
237
- method: "notifications/message",
238
- params: { level: "info", data: "Tool execution completed" }
239
- });
240
- }
241
- return {
242
- content: [
243
- {
244
- type: "text",
245
- text: "Logging tool execution completed."
246
- }
247
- ]
248
- };
249
- });
250
- server.registerTool("test_tool_with_progress", {
251
- description: "Conformance fixture: sends progress notifications during execution.",
252
- inputSchema: z.object({})
253
- }, async (_input, ctx) => {
254
- const progressToken = readProgressToken(ctx);
255
- const sendNotification = readNotificationSender(ctx);
256
- if (progressToken !== undefined && sendNotification) {
257
- await sendNotification({
258
- method: "notifications/progress",
259
- params: { progressToken, progress: 0, total: 100 }
260
- });
261
- await delay(50);
262
- await sendNotification({
263
- method: "notifications/progress",
264
- params: { progressToken, progress: 50, total: 100 }
265
- });
266
- await delay(50);
267
- await sendNotification({
268
- method: "notifications/progress",
269
- params: { progressToken, progress: 100, total: 100 }
270
- });
271
- } else {
272
- await delay(100);
273
- }
274
- return {
275
- content: [
276
- {
277
- type: "text",
278
- text: "Progress tool execution completed."
279
- }
280
- ]
281
- };
282
- });
283
- server.registerTool("test_sampling", {
284
- description: "Conformance fixture: requests client sampling.",
285
- inputSchema: z.object({
286
- prompt: z.string().describe("Prompt to send to sampling/createMessage")
287
- })
288
- }, async (input, ctx) => {
289
- const sendRequest = readRequestSender(ctx);
290
- if (!sendRequest) {
291
- return {
292
- content: [
293
- {
294
- type: "text",
295
- text: "Sampling is not supported by this client."
296
- }
297
- ],
298
- isError: true
299
- };
300
- }
301
- try {
302
- const sampledResult = await sendRequest({
303
- method: "sampling/createMessage",
304
- params: {
305
- messages: [
306
- {
307
- role: "user",
308
- content: {
309
- type: "text",
310
- text: input.prompt
311
- }
312
- }
313
- ],
314
- maxTokens: 100
315
- }
316
- });
317
- return {
318
- content: [
319
- {
320
- type: "text",
321
- text: `LLM response: ${parseSampledText(sampledResult)}`
322
- }
323
- ]
324
- };
325
- } catch {
326
- return {
327
- content: [
328
- {
329
- type: "text",
330
- text: "Sampling is not supported by this client."
331
- }
332
- ],
333
- isError: true
334
- };
335
- }
336
- });
337
- server.registerTool("test_elicitation", {
338
- description: "Conformance fixture: requests elicitation from client.",
339
- inputSchema: z.object({
340
- message: z.string().describe("Prompt message shown to user")
341
- })
342
- }, async (input, ctx) => {
343
- const sendRequest = readRequestSender(ctx);
344
- if (!sendRequest) {
345
- return {
346
- content: [
347
- { type: "text", text: "Elicitation is not supported by this client." }
348
- ],
349
- isError: true
350
- };
351
- }
352
- try {
353
- const elicitationResult = await sendRequest({
354
- method: "elicitation/create",
355
- params: {
356
- message: input.message,
357
- requestedSchema: {
358
- type: "object",
359
- properties: {
360
- username: {
361
- type: "string",
362
- description: "User's response"
363
- },
364
- email: {
365
- type: "string",
366
- description: "User's email address"
367
- }
368
- },
369
- required: ["username", "email"]
370
- }
371
- }
372
- });
373
- return {
374
- content: [
375
- {
376
- type: "text",
377
- text: `User response: action=${elicitationResult.action}, content=${stringifyUnknown(elicitationResult.content ?? {})}`
378
- }
379
- ]
380
- };
381
- } catch {
382
- return {
383
- content: [
384
- { type: "text", text: "Elicitation is not supported by this client." }
385
- ],
386
- isError: true
387
- };
388
- }
389
- });
390
- server.registerTool("test_elicitation_sep1034_defaults", {
391
- description: "Conformance fixture: elicitation defaults for SEP-1034.",
392
- inputSchema: z.object({})
393
- }, async (_input, ctx) => {
394
- const sendRequest = readRequestSender(ctx);
395
- if (!sendRequest) {
396
- return {
397
- content: [
398
- { type: "text", text: "Elicitation is not supported by this client." }
399
- ],
400
- isError: true
401
- };
402
- }
403
- try {
404
- const result = await sendRequest({
405
- method: "elicitation/create",
406
- params: {
407
- message: "Provide defaults confirmation",
408
- requestedSchema: {
409
- type: "object",
410
- properties: {
411
- name: { type: "string", default: "John Doe" },
412
- age: { type: "integer", default: 30 },
413
- score: { type: "number", default: 95.5 },
414
- status: {
415
- type: "string",
416
- enum: ["active", "inactive", "pending"],
417
- default: "active"
418
- },
419
- verified: { type: "boolean", default: true }
420
- },
421
- required: ["name", "age", "score", "status", "verified"]
422
- }
423
- }
424
- });
425
- return {
426
- content: [
427
- {
428
- type: "text",
429
- text: `Elicitation completed: action=${result.action}, content=${stringifyUnknown(result.content ?? {})}`
430
- }
431
- ]
432
- };
433
- } catch {
434
- return {
435
- content: [
436
- { type: "text", text: "Elicitation is not supported by this client." }
437
- ],
438
- isError: true
439
- };
440
- }
441
- });
442
- server.registerTool("test_elicitation_sep1330_enums", {
443
- description: "Conformance fixture: enum variants for SEP-1330.",
444
- inputSchema: z.object({})
445
- }, async (_input, ctx) => {
446
- const sendRequest = readRequestSender(ctx);
447
- if (!sendRequest) {
448
- return {
449
- content: [
450
- { type: "text", text: "Elicitation is not supported by this client." }
451
- ],
452
- isError: true
453
- };
454
- }
455
- try {
456
- const result = await sendRequest({
457
- method: "elicitation/create",
458
- params: {
459
- message: "Choose enum variants",
460
- requestedSchema: {
461
- type: "object",
462
- properties: {
463
- untitledSingle: {
464
- type: "string",
465
- enum: ["option1", "option2", "option3"]
466
- },
467
- titledSingle: {
468
- type: "string",
469
- oneOf: [
470
- { const: "value1", title: "First Option" },
471
- { const: "value2", title: "Second Option" },
472
- { const: "value3", title: "Third Option" }
473
- ]
474
- },
475
- legacyEnum: {
476
- type: "string",
477
- enum: ["opt1", "opt2", "opt3"],
478
- enumNames: ["Option One", "Option Two", "Option Three"]
479
- },
480
- untitledMulti: {
481
- type: "array",
482
- items: {
483
- type: "string",
484
- enum: ["option1", "option2", "option3"]
485
- }
486
- },
487
- titledMulti: {
488
- type: "array",
489
- items: {
490
- anyOf: [
491
- { const: "value1", title: "First Choice" },
492
- { const: "value2", title: "Second Choice" },
493
- { const: "value3", title: "Third Choice" }
494
- ]
495
- }
496
- }
497
- },
498
- required: [
499
- "untitledSingle",
500
- "titledSingle",
501
- "legacyEnum",
502
- "untitledMulti",
503
- "titledMulti"
504
- ]
505
- }
506
- }
507
- });
508
- return {
509
- content: [
510
- {
511
- type: "text",
512
- text: `Elicitation completed: action=${result.action}, content=${stringifyUnknown(result.content ?? {})}`
513
- }
514
- ]
515
- };
516
- } catch {
517
- return {
518
- content: [
519
- { type: "text", text: "Elicitation is not supported by this client." }
520
- ],
521
- isError: true
522
- };
523
- }
524
- });
525
- server.registerResource("test_static_text_resource", "test://static-text", { description: "Conformance fixture static text resource", mimeType: "text/plain" }, async () => ({
526
- contents: [
527
- {
528
- uri: "test://static-text",
529
- mimeType: "text/plain",
530
- text: "This is the content of the static text resource."
531
- }
532
- ]
533
- }));
534
- server.registerResource("test_static_binary_resource", "test://static-binary", { description: "Conformance fixture static binary resource", mimeType: "image/png" }, async () => ({
535
- contents: [
536
- {
537
- uri: "test://static-binary",
538
- mimeType: "image/png",
539
- blob: oneByOnePngBase64
540
- }
541
- ]
542
- }));
543
- server.registerResource("test_template_resource", new ResourceTemplate("test://template/{id}/data", {
544
- list: async () => ({
545
- resources: [
546
- {
547
- uri: "test://template/123/data",
548
- name: "template-data-123",
549
- mimeType: "application/json"
550
- }
551
- ]
552
- })
553
- }), { description: "Conformance fixture template resource", mimeType: "application/json" }, async (_uri, variables) => {
554
- const identifier = String(variables.id ?? "");
555
- return {
556
- contents: [
557
- {
558
- uri: `test://template/${identifier}/data`,
559
- mimeType: "application/json",
560
- text: `{"id":"${identifier}","templateTest":true,"data":"Data for ID: ${identifier}"}`
561
- }
562
- ]
563
- };
564
- });
565
- server.registerPrompt("test_simple_prompt", { description: "Conformance fixture simple prompt." }, async () => ({
566
- messages: [
567
- {
568
- role: "user",
569
- content: {
570
- type: "text",
571
- text: "This is a simple prompt for testing."
572
- }
573
- }
574
- ]
575
- }));
576
- server.registerPrompt("test_prompt_with_arguments", {
577
- description: "Conformance fixture prompt with arguments.",
578
- argsSchema: z.object({
579
- arg1: completable(z.string().describe("First test argument"), async (value) => {
580
- const query = String(value ?? "").toLowerCase();
581
- const values = ["paris", "park", "party"];
582
- return values.filter((item) => item.startsWith(query));
583
- }),
584
- arg2: z.string().describe("Second test argument")
585
- })
586
- }, async (arguments_) => ({
587
- messages: [
588
- {
589
- role: "user",
590
- content: {
591
- type: "text",
592
- text: `Prompt with arguments: arg1='${arguments_.arg1}', arg2='${arguments_.arg2}'`
593
- }
594
- }
595
- ]
596
- }));
597
- server.registerPrompt("test_prompt_with_embedded_resource", {
598
- description: "Conformance fixture prompt with embedded resource.",
599
- argsSchema: z.object({
600
- resourceUri: z.string().describe("URI of resource to embed")
601
- })
602
- }, async (arguments_) => ({
603
- messages: [
604
- {
605
- role: "user",
606
- content: {
607
- type: "resource",
608
- resource: {
609
- uri: arguments_.resourceUri,
610
- mimeType: "text/plain",
611
- text: "Embedded resource content for testing."
612
- }
613
- }
614
- },
615
- {
616
- role: "user",
617
- content: {
618
- type: "text",
619
- text: "Please process the embedded resource above."
620
- }
621
- }
622
- ]
623
- }));
624
- server.registerPrompt("test_prompt_with_image", {
625
- description: "Conformance fixture prompt with image content."
626
- }, async () => ({
627
- messages: [
628
- {
629
- role: "user",
630
- content: {
631
- type: "image",
632
- data: oneByOnePngBase64,
633
- mimeType: "image/png"
634
- }
635
- },
636
- {
637
- role: "user",
638
- content: {
639
- type: "text",
640
- text: "Please analyze the image above."
641
- }
642
- }
643
- ]
644
- }));
645
- server.registerTool("test_watched_resource_update", {
646
- description: "Conformance fixture helper that publishes a resource update notification for the given URI, scoped to this connection.",
647
- inputSchema: z.object({
648
- uri: z.string().describe("The resource URI to publish an update for.")
649
- })
650
- }, async (input) => {
651
- if (publishResourceUpdate) {
652
- await publishResourceUpdate(input.uri);
653
- } else {
654
- await server.server.sendResourceUpdated({ uri: input.uri });
655
- }
656
- return {
657
- content: [
658
- {
659
- type: "text",
660
- text: `Sent a resource update notification for ${input.uri}.`
661
- }
662
- ]
663
- };
664
- });
665
- server.registerTool("test_cancellable_operation", {
666
- description: "Conformance fixture: awaits a slow operation through runWithStandardizedTimeout, " + "threaded from the request's own AbortSignal, to prove disconnecting the caller " + "genuinely aborts the underlying work rather than only abandoning a wrapper promise.",
667
- inputSchema: z.object({
668
- delayMilliseconds: z.number().int().positive().max(60000).describe("How long the underlying operation sleeps before resolving.")
669
- })
670
- }, async (input, ctx) => {
671
- try {
672
- await runWithStandardizedTimeout({
673
- operation: (signal) => delay(input.delayMilliseconds, signal),
674
- abortSignal: ctx.mcpReq.signal,
675
- timeoutMilliseconds: input.delayMilliseconds + 60000
676
- });
677
- cancellableOperationTestHooks.completedCount += 1;
678
- } catch (error) {
679
- cancellableOperationTestHooks.abortedCount += 1;
680
- return {
681
- content: [
682
- {
683
- type: "text",
684
- text: `Cancelled: ${error instanceof Error ? error.message : String(error)}`
685
- }
686
- ],
687
- isError: true
688
- };
689
- }
690
- return {
691
- content: [{ type: "text", text: "Cancellable operation completed." }]
692
- };
693
- });
694
- }
695
-
696
- // src/ui-extension-support.ts
697
- import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
698
- function hasRegisteredUiExtensionResource(registry) {
699
- return registry.resources.some((resource) => resource.mimeType === RESOURCE_MIME_TYPE);
700
- }
701
-
702
- // src/server.ts
703
- function buildServerCapabilities(input) {
704
- return {
705
- ...input.families.tools ? { tools: { listChanged: false } } : {},
706
- ...input.families.resources ? {
707
- resources: {
708
- listChanged: false,
709
- ...input.subscriptionsEnabled ? { subscribe: true } : {}
710
- }
711
- } : {},
712
- ...input.families.prompts ? { prompts: { listChanged: false } } : {},
713
- experimental: input.experimentalCapabilities,
714
- ...input.enableConformanceMode ? { logging: {} } : {}
715
- };
716
- }
717
- var mcpInsufficientScopeErrorCode = -32003;
718
- function insufficientScopeChallenge(requiredScope) {
719
- return `Bearer error="insufficient_scope", scope="${requiredScope}"`;
720
- }
721
- function hasRequiredScope(grantedScopes, requiredScope) {
722
- return grantedScopes.includes(requiredScope);
723
- }
724
- function areResourceSubscriptionsAuthorized(uris, scopes, registry) {
725
- return uris.every((uri) => {
726
- const resource = registry.resources.find((definition) => definition.uri === uri);
727
- return resource !== undefined && hasRequiredScope(scopes, resource.requiredScope);
728
- });
729
- }
730
- function createMcpServer(context, registry) {
731
- const era = context.era ?? "legacy";
732
- const enableConformanceMode = context.enableConformanceMode ?? getEnvironment().MCP_CONFORMANCE_MODE;
733
- const experimentalCapabilities = {};
734
- if (context.enableUiExtension && hasRegisteredUiExtensionResource(registry)) {
735
- experimentalCapabilities[EXTENSION_ID] = { version: "1.0.0" };
736
- }
737
- const serverInfo = registry.serverInfo ?? {
738
- name: getEnvironment().MCP_SERVER_NAME,
739
- version: PACKAGE_VERSION
740
- };
741
- const server = new McpServer({
742
- name: serverInfo.name,
743
- version: serverInfo.version
744
- }, {
745
- instructions: registry.instructions ?? instructions_default,
746
- capabilities: buildServerCapabilities({
747
- families: {
748
- tools: enableConformanceMode || registry.tools.length > 0,
749
- resources: enableConformanceMode || registry.resources.length > 0,
750
- prompts: enableConformanceMode || registry.prompts.length > 0
751
- },
752
- enableConformanceMode,
753
- experimentalCapabilities,
754
- subscriptionsEnabled: era === "modern" && context.publishResourceUpdate !== undefined
755
- })
756
- });
757
- function registerToolDefinition(tool) {
758
- server.registerTool(tool.name, {
759
- title: tool.title,
760
- description: tool.description,
761
- inputSchema: tool.inputSchema,
762
- ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
763
- annotations: tool.annotations,
764
- ...tool._meta ? { _meta: tool._meta } : {}
765
- }, async (input, ctx) => {
766
- if (!hasRequiredScope(context.scopes, tool.requiredScope)) {
767
- logger.warn({
768
- event: "mcp_tool_call",
769
- outcome: "insufficient_scope",
770
- tool: tool.name,
771
- requiredScope: tool.requiredScope,
772
- userId: context.userId,
773
- requestId: context.requestId
774
- }, "MCP tool call rejected: insufficient scope");
775
- metricsCollector.recordToolInvocation(tool.name, 0, true);
776
- metricsCollector.recordEvent("mcp_method", "insufficient_scope");
777
- return {
778
- content: [
779
- {
780
- type: "text",
781
- text: `Insufficient scope: this tool requires '${tool.requiredScope}'.`
782
- }
783
- ],
784
- isError: true,
785
- _meta: { "mcp/www_authenticate": insufficientScopeChallenge(tool.requiredScope) }
786
- };
787
- }
788
- const start = Date.now();
789
- let result;
790
- try {
791
- result = await tool.handler(input, {
792
- ...context,
793
- signal: ctx.mcpReq.signal
794
- });
795
- } catch (error) {
796
- metricsCollector.recordToolInvocation(tool.name, Date.now() - start, true);
797
- logger.warn({
798
- event: "mcp_tool_call",
799
- outcome: "tool_exception",
800
- tool: tool.name,
801
- userId: context.userId,
802
- requestId: context.requestId
803
- }, "MCP tool handler threw");
804
- metricsCollector.recordEvent("mcp_method", "tool_exception");
805
- throw error;
806
- }
807
- const isError = "isError" in result && result.isError === true;
808
- metricsCollector.recordToolInvocation(tool.name, Date.now() - start, isError);
809
- if (isError) {
810
- logger.warn({
811
- event: "mcp_tool_call",
812
- outcome: "tool_failure",
813
- tool: tool.name,
814
- userId: context.userId,
815
- requestId: context.requestId
816
- }, "MCP tool call returned an error result");
817
- metricsCollector.recordEvent("mcp_method", "tool_failure");
818
- }
819
- return result;
820
- });
821
- }
822
- for (const tool of registry.tools) {
823
- registerToolDefinition(tool);
824
- }
825
- function assertRequiredScope(definition) {
826
- if (hasRequiredScope(context.scopes, definition.requiredScope))
827
- return;
828
- throw new ProtocolError2(mcpInsufficientScopeErrorCode, `Insufficient scope: '${definition.name}' requires '${definition.requiredScope}'.`, {
829
- requiredScope: definition.requiredScope,
830
- _meta: { "mcp/www_authenticate": insufficientScopeChallenge(definition.requiredScope) }
831
- });
832
- }
833
- for (const resource of registry.resources) {
834
- server.registerResource(resource.name, resource.uri, { title: resource.title, description: resource.description, mimeType: resource.mimeType }, async (uri, ctx) => {
835
- assertRequiredScope(resource);
836
- return resource.handler(uri, { ...context, signal: ctx.mcpReq.signal });
837
- });
838
- }
839
- for (const prompt of registry.prompts) {
840
- server.registerPrompt(prompt.name, {
841
- title: prompt.title,
842
- description: prompt.description,
843
- ...prompt.arguments ? { argsSchema: prompt.arguments } : {}
844
- }, async (arguments_, ctx) => {
845
- assertRequiredScope(prompt);
846
- return prompt.handler(arguments_, { ...context, signal: ctx.mcpReq.signal });
847
- });
848
- }
849
- server.server.setRequestHandler("resources/subscribe", async () => ({}));
850
- server.server.setRequestHandler("resources/unsubscribe", async () => ({}));
851
- if (enableConformanceMode) {
852
- for (const tool of registry.conformanceOnlyTools ?? []) {
853
- registerToolDefinition(tool);
854
- }
855
- registerConformanceFixtures(server, context.publishResourceUpdate);
856
- }
857
- return server;
858
- }
20
+ } from "./chunk-wfty87ws.js";
21
+ import {
22
+ getSupportedScopes,
23
+ hasRegisteredUiExtensionResource
24
+ } from "./chunk-rxnyn7tf.js";
25
+ import {
26
+ engineLogger,
27
+ getLogger,
28
+ logger,
29
+ setLogger
30
+ } from "./chunk-k6fm3cmk.js";
31
+ import {
32
+ getEnvironment,
33
+ parseMcpServerEnvironment
34
+ } from "./chunk-3rr24vhh.js";
35
+ import"./chunk-xcf742mf.js";
859
36
  // src/tools/get-user-profile.ts
860
- import { z as z2 } from "zod";
37
+ import { z } from "zod";
861
38
 
862
39
  // src/tool-response.ts
863
40
  var maxToolResultBytes = 256 * 1024;
@@ -889,6 +66,24 @@ function boundedTextContent(text) {
889
66
  }
890
67
  return { content: [{ type: "text", text }] };
891
68
  }
69
+ function createSerializationErrorResponse() {
70
+ return {
71
+ content: [
72
+ {
73
+ type: "text",
74
+ text: "Result omitted: tool result could not be serialized as JSON."
75
+ }
76
+ ],
77
+ isError: true
78
+ };
79
+ }
80
+ function serializeToolResult(data) {
81
+ try {
82
+ return JSON.stringify(data) ?? "null";
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
892
87
  function createToolTextResponse(text) {
893
88
  const bounded = boundedTextContent(text);
894
89
  if (bounded.content[0].text !== text) {
@@ -897,7 +92,9 @@ function createToolTextResponse(text) {
897
92
  return bounded;
898
93
  }
899
94
  function createToolJsonResponse(data) {
900
- const serialized = JSON.stringify(data) ?? "null";
95
+ const serialized = serializeToolResult(data);
96
+ if (serialized === null)
97
+ return createSerializationErrorResponse();
901
98
  const bounded = boundedTextContent(serialized);
902
99
  if (bounded.content[0].text !== serialized) {
903
100
  return { ...bounded, isError: true };
@@ -916,7 +113,9 @@ function createToolStructuredResponse(data, summary) {
916
113
  if (boundedSummary.content[0].text !== summary) {
917
114
  return { ...boundedSummary, isError: true };
918
115
  }
919
- const serialized = JSON.stringify(data) ?? "null";
116
+ const serialized = serializeToolResult(data);
117
+ if (serialized === null)
118
+ return createSerializationErrorResponse();
920
119
  const exceededSerialized = exceededByteLength(serialized);
921
120
  if (exceededSerialized !== null) {
922
121
  return {
@@ -1031,18 +230,18 @@ function isMcpScope(value) {
1031
230
  var { defineTool, defineResource, definePrompt } = templateScopeVocabulary;
1032
231
 
1033
232
  // src/tools/get-user-profile.ts
1034
- var getUserProfileOutputSchema = z2.object({
1035
- id: z2.string(),
1036
- email: z2.string(),
1037
- name: z2.string(),
1038
- image: z2.string().nullable(),
1039
- role: z2.string()
233
+ var getUserProfileOutputSchema = z.object({
234
+ id: z.string(),
235
+ email: z.string(),
236
+ name: z.string(),
237
+ image: z.string().nullable(),
238
+ role: z.string()
1040
239
  });
1041
240
  var getUserProfileTool = defineTool({
1042
241
  name: "get_user_profile",
1043
242
  title: "Get User Profile",
1044
243
  description: "Returns the authenticated user's own profile (id, email, name, avatar image, role). Use this when a request needs to know who the current user is or display their identity — it never accepts a target user and never reads anyone else's profile.",
1045
- inputSchema: z2.object({}),
244
+ inputSchema: z.object({}),
1046
245
  outputSchema: getUserProfileOutputSchema,
1047
246
  requiredScope: "profile:read",
1048
247
  annotations: {
@@ -1056,17 +255,17 @@ var getUserProfileTool = defineTool({
1056
255
  }
1057
256
  });
1058
257
  // src/tools/list-audit-events.ts
1059
- import { z as z3 } from "zod";
258
+ import { z as z2 } from "zod";
1060
259
  var auditEvents = Array.from({ length: 50 }, (_, index) => ({
1061
260
  identifier: `event-${String(index + 1).padStart(3, "0")}`,
1062
261
  message: `Audit event #${index + 1}`
1063
262
  }));
1064
- var listAuditEventsOutputSchema = z3.object({
1065
- items: z3.array(z3.object({
1066
- identifier: z3.string(),
1067
- message: z3.string()
263
+ var listAuditEventsOutputSchema = z2.object({
264
+ items: z2.array(z2.object({
265
+ identifier: z2.string(),
266
+ message: z2.string()
1068
267
  })),
1069
- next_cursor: z3.string().nullable()
268
+ next_cursor: z2.string().nullable()
1070
269
  });
1071
270
  function decodeCursor(cursor) {
1072
271
  if (!cursor)
@@ -1078,9 +277,9 @@ var listAuditEventsTool = defineTool({
1078
277
  name: "list_audit_events",
1079
278
  title: "List Audit Events (Conformance Fixture)",
1080
279
  description: "Returns deterministic, cursor-paginated synthetic audit events. This is a protocol conformance fixture for exercising pagination flows, not a real audit log — the data is generated in memory and never reflects actual account activity.",
1081
- inputSchema: z3.object({
1082
- cursor: z3.string().optional().describe("Opaque pagination cursor from a previous call's next_cursor. Omit for the first page."),
1083
- page_size: z3.number().int().min(1).max(25).optional().default(10).describe("Number of events to return per page (1-25, default 10).")
280
+ inputSchema: z2.object({
281
+ cursor: z2.string().optional().describe("Opaque pagination cursor from a previous call's next_cursor. Omit for the first page."),
282
+ page_size: z2.number().int().min(1).max(25).optional().default(10).describe("Number of events to return per page (1-25, default 10).")
1084
283
  }),
1085
284
  outputSchema: listAuditEventsOutputSchema,
1086
285
  requiredScope: "audit:read",
@@ -1129,7 +328,7 @@ var userProfileResource = defineResource({
1129
328
  // src/resources/index.ts
1130
329
  var allResources = [userProfileResource];
1131
330
  // src/prompts/summarize.ts
1132
- import { z as z4 } from "zod";
331
+ import { z as z3 } from "zod";
1133
332
  function contentDiagnosticsActive() {
1134
333
  const until = getEnvironment().LOG_CONTENT_DIAGNOSTICS_UNTIL;
1135
334
  if (!until)
@@ -1141,11 +340,11 @@ var summarizePrompt = definePrompt({
1141
340
  title: "Summarize Topic",
1142
341
  description: "Generates a prompt that asks the assistant to summarize a given topic for the authenticated user.",
1143
342
  arguments: {
1144
- topic: z4.string().describe("The topic to summarize")
343
+ topic: z3.string().describe("The topic to summarize")
1145
344
  },
1146
345
  requiredScope: "prompts:read",
1147
346
  handler: async (arguments_, context) => {
1148
- const requestLogger = logger.child({
347
+ const requestLogger = engineLogger.child({
1149
348
  prompt: "summarize",
1150
349
  userId: context.userId,
1151
350
  requestId: context.requestId
@@ -1189,58 +388,6 @@ var summarizePrompt = definePrompt({
1189
388
  var allPrompts = [
1190
389
  summarizePrompt
1191
390
  ];
1192
- // src/localhost-request-validation.ts
1193
- var localhostHostnames = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1194
- function normalizeHostname(hostname) {
1195
- return hostname.trim().toLowerCase();
1196
- }
1197
- function isLocalhostHostname(hostname) {
1198
- return localhostHostnames.has(normalizeHostname(hostname));
1199
- }
1200
- function parseHostnameFromHostHeader(hostHeader) {
1201
- if (!hostHeader) {
1202
- return null;
1203
- }
1204
- const firstValue = hostHeader.split(",")[0].trim();
1205
- if (firstValue.length === 0) {
1206
- return null;
1207
- }
1208
- if (firstValue.startsWith("[")) {
1209
- const endIndex = firstValue.indexOf("]");
1210
- if (endIndex === -1)
1211
- return null;
1212
- return firstValue.slice(0, endIndex + 1);
1213
- }
1214
- const separatorIndex = firstValue.indexOf(":");
1215
- if (separatorIndex === -1) {
1216
- return firstValue;
1217
- }
1218
- return firstValue.slice(0, separatorIndex);
1219
- }
1220
- function parseHostnameFromOriginHeader(originHeader) {
1221
- if (!originHeader || originHeader === "null") {
1222
- return null;
1223
- }
1224
- try {
1225
- return new URL(originHeader).hostname;
1226
- } catch {
1227
- return null;
1228
- }
1229
- }
1230
- function isLoopbackHostname(hostname) {
1231
- return isLocalhostHostname(hostname);
1232
- }
1233
- function hasValidLocalhostRebindingHeaders(headers) {
1234
- const requestHost = parseHostnameFromHostHeader(headers.get("host"));
1235
- if (requestHost && !isLocalhostHostname(requestHost)) {
1236
- return false;
1237
- }
1238
- const requestOriginHost = parseHostnameFromOriginHeader(headers.get("origin"));
1239
- if (requestOriginHost && !isLocalhostHostname(requestOriginHost)) {
1240
- return false;
1241
- }
1242
- return true;
1243
- }
1244
391
 
1245
392
  // src/index.ts
1246
393
  import {
@@ -1265,36 +412,177 @@ var templateRegistry = {
1265
412
  prompts: allPrompts,
1266
413
  conformanceOnlyTools
1267
414
  };
1268
- // src/supported-scopes.ts
1269
- function getSupportedScopes(registry) {
1270
- const scopes = new Set;
1271
- for (const tool of registry.tools)
1272
- scopes.add(tool.requiredScope);
1273
- for (const resource of registry.resources)
1274
- scopes.add(resource.requiredScope);
1275
- for (const prompt of registry.prompts)
1276
- scopes.add(prompt.requiredScope);
1277
- return [...scopes].sort();
415
+ // src/oauth-scope-configuration.ts
416
+ function defineOAuthScopeConfiguration(configuration) {
417
+ for (const scope of configuration.supportedScopes) {
418
+ if (!configuration.vocabulary.isScope(scope)) {
419
+ throw new Error(`Unsupported OAuth scope ${JSON.stringify(scope)}.`);
420
+ }
421
+ }
422
+ return Object.freeze({
423
+ vocabulary: configuration.vocabulary,
424
+ supportedScopes: Object.freeze([...configuration.supportedScopes])
425
+ });
426
+ }
427
+ // src/conformance.ts
428
+ import { randomUUID } from "node:crypto";
429
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
430
+ import { createMcpHandler } from "@modelcontextprotocol/server";
431
+ function conformanceUser(userId) {
432
+ return {
433
+ id: userId,
434
+ email: "conformance@localhost",
435
+ name: "Conformance User",
436
+ image: null,
437
+ role: "user"
438
+ };
439
+ }
440
+ function createConsumerConformanceHandler(options) {
441
+ const defaultUserId = randomUUID();
442
+ const identity = options.identity ?? {
443
+ userId: defaultUserId,
444
+ user: conformanceUser(defaultUserId)
445
+ };
446
+ const handler = createMcpHandler((requestContext) => {
447
+ return createMcpServer({
448
+ userId: identity.userId,
449
+ user: identity.user,
450
+ enableUiExtension: false,
451
+ enableConformanceMode: options.enableConformanceMode ?? false,
452
+ era: requestContext.era,
453
+ scopes: options.scopeVocabulary.scopes,
454
+ ...options.enableConformanceMode ? {
455
+ publishResourceUpdate: async (uri) => {
456
+ handler.notify.resourceUpdated(uri);
457
+ }
458
+ } : {}
459
+ }, options.registry);
460
+ }, { legacy: "stateless" });
461
+ return {
462
+ async fetch(request) {
463
+ if (new URL(request.url).pathname !== "/mcp") {
464
+ return new Response("Not found", { status: 404 });
465
+ }
466
+ if (!hasValidLocalhostRebindingHeaders(request.headers)) {
467
+ return new Response("Forbidden", { status: 403 });
468
+ }
469
+ return handler.fetch(request);
470
+ }
471
+ };
472
+ }
473
+ function errorMessage(error) {
474
+ return error instanceof Error ? error.message : String(error);
475
+ }
476
+ async function recordBehavior(era, name, behavior) {
477
+ try {
478
+ await behavior();
479
+ return { era, name, status: "passed" };
480
+ } catch (error) {
481
+ return { era, name, status: "failed", error: errorMessage(error) };
482
+ }
483
+ }
484
+ async function runMcpConformance(options) {
485
+ const handler = createConsumerConformanceHandler({
486
+ registry: options.registry,
487
+ scopeVocabulary: options.scopeVocabulary,
488
+ enableConformanceMode: false,
489
+ ...options.identity ? { identity: options.identity } : {}
490
+ });
491
+ const client = new Client({ name: "consumer-conformance-client", version: "1.0.0" }, options.era === "modern" ? { versionNegotiation: { mode: { pin: "2026-07-28" } } } : undefined);
492
+ const transport = new StreamableHTTPClientTransport(new URL("http://localhost/mcp"), {
493
+ fetch: (input, init) => {
494
+ const request = new Request(input, init);
495
+ request.headers.set("host", "localhost");
496
+ return handler.fetch(request);
497
+ }
498
+ });
499
+ const results = [];
500
+ let connected = false;
501
+ results.push(await recordBehavior(options.era, "connection", async () => {
502
+ await client.connect(transport);
503
+ if (client.getProtocolEra() !== options.era) {
504
+ throw new Error(`Expected ${options.era} protocol era, received ${String(client.getProtocolEra())}.`);
505
+ }
506
+ connected = true;
507
+ }));
508
+ if (!connected) {
509
+ await client.close();
510
+ return results;
511
+ }
512
+ try {
513
+ if (options.registry.tools.length > 0) {
514
+ results.push(await recordBehavior(options.era, "tools/list", async () => {
515
+ const listed = await client.listTools();
516
+ const expectedNames = options.registry.tools.map((tool) => tool.name).sort();
517
+ const actualNames = listed.tools.map((tool) => tool.name).sort();
518
+ if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
519
+ throw new Error(`Expected tools ${JSON.stringify(expectedNames)}, received ${JSON.stringify(actualNames)}.`);
520
+ }
521
+ }));
522
+ }
523
+ for (const [toolName, arguments_] of Object.entries(options.toolProbes ?? {}).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)) {
524
+ results.push(await recordBehavior(options.era, `tools/call:${toolName}`, async () => {
525
+ const result = await client.callTool({ name: toolName, arguments: arguments_ });
526
+ if (result.isError)
527
+ throw new Error(`Tool ${toolName} returned an error result.`);
528
+ }));
529
+ }
530
+ if (options.registry.resources.length > 0) {
531
+ results.push(await recordBehavior(options.era, "resources/list", async () => {
532
+ const listed = await client.listResources();
533
+ const expectedUris = options.registry.resources.map((resource) => resource.uri).sort();
534
+ const actualUris = listed.resources.map((resource) => resource.uri).sort();
535
+ if (JSON.stringify(actualUris) !== JSON.stringify(expectedUris)) {
536
+ throw new Error(`Expected resources ${JSON.stringify(expectedUris)}, received ${JSON.stringify(actualUris)}.`);
537
+ }
538
+ }));
539
+ }
540
+ for (const uri of [...options.resourceProbes ?? []].sort()) {
541
+ results.push(await recordBehavior(options.era, `resources/read:${uri}`, async () => {
542
+ await client.readResource({ uri });
543
+ }));
544
+ }
545
+ if (options.registry.prompts.length > 0) {
546
+ results.push(await recordBehavior(options.era, "prompts/list", async () => {
547
+ const listed = await client.listPrompts();
548
+ const expectedNames = options.registry.prompts.map((prompt) => prompt.name).sort();
549
+ const actualNames = listed.prompts.map((prompt) => prompt.name).sort();
550
+ if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
551
+ throw new Error(`Expected prompts ${JSON.stringify(expectedNames)}, received ${JSON.stringify(actualNames)}.`);
552
+ }
553
+ }));
554
+ }
555
+ for (const [promptName, arguments_] of Object.entries(options.promptProbes ?? {}).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)) {
556
+ results.push(await recordBehavior(options.era, `prompts/get:${promptName}`, async () => {
557
+ await client.getPrompt({ name: promptName, arguments: arguments_ });
558
+ }));
559
+ }
560
+ } finally {
561
+ await client.close();
562
+ }
563
+ return results;
1278
564
  }
1279
565
 
1280
566
  // src/index.ts
1281
- var EXTENSION_ID2 = extensionId;
1282
- var RESOURCE_MIME_TYPE2 = resourceMimeType;
567
+ var EXTENSION_ID = extensionId;
568
+ var RESOURCE_MIME_TYPE = resourceMimeType;
1283
569
  export {
1284
- EXTENSION_ID2 as EXTENSION_ID,
570
+ EXTENSION_ID,
1285
571
  PACKAGE_VERSION,
1286
- RESOURCE_MIME_TYPE2 as RESOURCE_MIME_TYPE,
572
+ RESOURCE_MIME_TYPE,
1287
573
  allPrompts,
1288
574
  allResources,
1289
575
  allTools,
1290
576
  areResourceSubscriptionsAuthorized,
1291
577
  assertSamplingSupport,
1292
578
  cancellableOperationTestHooks,
579
+ createConsumerConformanceHandler,
1293
580
  createMcpServer,
1294
581
  createToolErrorResponse,
1295
582
  createToolJsonResponse,
1296
583
  createToolStructuredResponse,
1297
584
  createToolTextResponse,
585
+ defineOAuthScopeConfiguration,
1298
586
  definePrompt2 as definePrompt,
1299
587
  defineResource2 as defineResource,
1300
588
  defineScopes,
@@ -1318,6 +606,8 @@ export {
1318
606
  readProgressToken,
1319
607
  readRequestSender,
1320
608
  readSessionIdentifier,
609
+ runMcpConformance,
610
+ setLogger,
1321
611
  stringifyUnknown,
1322
612
  summarizePrompt,
1323
613
  templateRegistry,