@lostgradient/mcp 0.2.5 → 0.3.0

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 (123) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +15 -173
  3. package/dist/http.d.ts +35 -0
  4. package/dist/http.js +251 -0
  5. package/dist/internal/cryptography/encryption.d.ts +108 -0
  6. package/dist/internal/cryptography/encryption.js +241 -0
  7. package/dist/internal/cryptography/hash.d.ts +72 -0
  8. package/dist/internal/cryptography/hash.js +233 -0
  9. package/dist/internal/cryptography/index.d.ts +4 -0
  10. package/dist/internal/cryptography/index.js +2 -0
  11. package/dist/oauth/canonicalize-ip-address.d.ts +0 -6
  12. package/dist/oauth/canonicalize-ip-address.js +113 -0
  13. package/dist/oauth/client-metadata-documents.d.ts +2 -22
  14. package/dist/oauth/client-metadata-documents.js +205 -19
  15. package/dist/oauth/index.d.ts +9 -213
  16. package/dist/oauth/index.js +6 -69
  17. package/dist/oauth/issuer.d.ts +103 -0
  18. package/dist/oauth/issuer.js +564 -0
  19. package/dist/oauth/postgres.d.ts +12 -0
  20. package/dist/oauth/postgres.js +76 -0
  21. package/dist/oauth/safe-public-https-fetch.d.ts +3 -5
  22. package/dist/oauth/safe-public-https-fetch.js +114 -0
  23. package/dist/oauth/security-utilities.d.ts +0 -3
  24. package/dist/oauth/security-utilities.js +93 -0
  25. package/dist/oauth-store.d.ts +108 -0
  26. package/dist/oauth-store.js +321 -0
  27. package/package.json +50 -124
  28. package/dist/chunk-3ek3knfm.js +0 -73
  29. package/dist/chunk-3rr24vhh.js +0 -28
  30. package/dist/chunk-6ekjtvcq.js +0 -273
  31. package/dist/chunk-88nhf6xt.js +0 -449
  32. package/dist/chunk-en76akaq.js +0 -1107
  33. package/dist/chunk-k6fm3cmk.js +0 -132
  34. package/dist/chunk-qxwd8est.js +0 -916
  35. package/dist/chunk-rxnyn7tf.js +0 -19
  36. package/dist/chunk-taxyscge.js +0 -67
  37. package/dist/chunk-wsnfttyg.js +0 -4
  38. package/dist/chunk-xcf742mf.js +0 -14
  39. package/dist/conformance-fixture-registration.d.ts +0 -30
  40. package/dist/conformance-server.d.ts +0 -1
  41. package/dist/conformance.d.ts +0 -43
  42. package/dist/env.d.ts +0 -59
  43. package/dist/env.js +0 -9
  44. package/dist/environment-schema.d.ts +0 -29
  45. package/dist/environment-schema.js +0 -6
  46. package/dist/golden-prompts.d.ts +0 -42
  47. package/dist/handler-context.d.ts +0 -16
  48. package/dist/http/authenticate.d.ts +0 -35
  49. package/dist/http/authorization-header.d.ts +0 -5
  50. package/dist/http/grant-revocation-channel.d.ts +0 -24
  51. package/dist/http/handler.d.ts +0 -32
  52. package/dist/http/index.d.ts +0 -27
  53. package/dist/http/index.js +0 -870
  54. package/dist/http/listen-inspection.d.ts +0 -11
  55. package/dist/http/request-context.d.ts +0 -17
  56. package/dist/http/responses.d.ts +0 -13
  57. package/dist/http/serving-layer.d.ts +0 -25
  58. package/dist/http/user-handler-cache.d.ts +0 -37
  59. package/dist/http/user-server-event-bus.d.ts +0 -35
  60. package/dist/index.d.ts +0 -29
  61. package/dist/index.js +0 -616
  62. package/dist/localhost-request-validation.d.ts +0 -2
  63. package/dist/logger.d.ts +0 -59
  64. package/dist/logger.js +0 -18
  65. package/dist/long-running-operation-support.d.ts +0 -34
  66. package/dist/metrics.d.ts +0 -64
  67. package/dist/metrics.js +0 -6
  68. package/dist/oauth/authorize-endpoint.d.ts +0 -5
  69. package/dist/oauth/client-authentication.d.ts +0 -10
  70. package/dist/oauth/discovery-metadata.d.ts +0 -19
  71. package/dist/oauth/endpoint-rate-limits.d.ts +0 -10
  72. package/dist/oauth/endpoint-responses.d.ts +0 -10
  73. package/dist/oauth/network-identity.d.ts +0 -32
  74. package/dist/oauth/pkce-validation.d.ts +0 -2
  75. package/dist/oauth/postgres/client-store.d.ts +0 -12
  76. package/dist/oauth/postgres/code-store.d.ts +0 -14
  77. package/dist/oauth/postgres/database.d.ts +0 -59
  78. package/dist/oauth/postgres/index.d.ts +0 -11
  79. package/dist/oauth/postgres/index.js +0 -616
  80. package/dist/oauth/postgres/schema.d.ts +0 -1476
  81. package/dist/oauth/postgres/token-store.d.ts +0 -16
  82. package/dist/oauth/postgres/transaction-store.d.ts +0 -14
  83. package/dist/oauth/redirect-uri-matching.d.ts +0 -2
  84. package/dist/oauth/registration-endpoint.d.ts +0 -2
  85. package/dist/oauth/request-body.d.ts +0 -14
  86. package/dist/oauth/revocation-endpoint.d.ts +0 -2
  87. package/dist/oauth/scope-utilities.d.ts +0 -15
  88. package/dist/oauth/stores.d.ts +0 -225
  89. package/dist/oauth/stores.js +0 -0
  90. package/dist/oauth/testing/contract-fixtures.d.ts +0 -134
  91. package/dist/oauth/testing/index.d.ts +0 -56
  92. package/dist/oauth/testing/index.js +0 -330
  93. package/dist/oauth/token-endpoint.d.ts +0 -2
  94. package/dist/oauth-scope-configuration.d.ts +0 -3
  95. package/dist/prompts/index.d.ts +0 -5
  96. package/dist/prompts/summarize.d.ts +0 -4
  97. package/dist/rate-limit/in-memory-sliding-window-store.d.ts +0 -3
  98. package/dist/rate-limit/index.d.ts +0 -23
  99. package/dist/rate-limit/index.js +0 -29
  100. package/dist/rate-limit/mcp-concurrency-limiter.d.ts +0 -26
  101. package/dist/rate-limit/rate-limit-response.d.ts +0 -1
  102. package/dist/rate-limit/redis-sliding-window-store.d.ts +0 -2
  103. package/dist/rate-limit/request-rate-limiter.d.ts +0 -10
  104. package/dist/rate-limit/sliding-window-rate-limiter.d.ts +0 -16
  105. package/dist/resources/index.d.ts +0 -4
  106. package/dist/resources/user-profile.d.ts +0 -1
  107. package/dist/scope-vocabulary.d.ts +0 -127
  108. package/dist/scopes.d.ts +0 -49
  109. package/dist/server.d.ts +0 -113
  110. package/dist/supported-scopes.d.ts +0 -25
  111. package/dist/sveltekit-mount-state.d.ts +0 -4
  112. package/dist/sveltekit-mount.d.ts +0 -43
  113. package/dist/sveltekit-mount.js +0 -344
  114. package/dist/template-registry.d.ts +0 -16
  115. package/dist/tool-response.d.ts +0 -100
  116. package/dist/tools/get-user-profile.d.ts +0 -8
  117. package/dist/tools/index.d.ts +0 -16
  118. package/dist/tools/list-audit-events.d.ts +0 -11
  119. package/dist/type-assertions.d.ts +0 -1
  120. package/dist/types/primitives.d.ts +0 -130
  121. package/dist/ui-extension-support.d.ts +0 -20
  122. package/dist/version.d.ts +0 -23
  123. package/dist/version.js +0 -6
@@ -1,916 +0,0 @@
1
- import {
2
- metricsCollector
3
- } from "./chunk-taxyscge.js";
4
- import {
5
- PACKAGE_VERSION
6
- } from "./chunk-wsnfttyg.js";
7
- import {
8
- hasRegisteredUiExtensionResource
9
- } from "./chunk-rxnyn7tf.js";
10
- import {
11
- engineLogger
12
- } from "./chunk-k6fm3cmk.js";
13
- import {
14
- getEnvironment
15
- } from "./chunk-3rr24vhh.js";
16
-
17
- // src/handler-context.ts
18
- import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
19
- function readMcpReq(ctx) {
20
- if (!ctx || typeof ctx !== "object")
21
- return;
22
- const mcpReq = ctx.mcpReq;
23
- if (!mcpReq || typeof mcpReq !== "object")
24
- return;
25
- return mcpReq;
26
- }
27
- function readProgressToken(ctx) {
28
- const mcpReq = readMcpReq(ctx);
29
- const meta = mcpReq?._meta;
30
- return meta?.progressToken;
31
- }
32
- function readSessionIdentifier(ctx) {
33
- if (!ctx || typeof ctx !== "object")
34
- return;
35
- return ctx.sessionId;
36
- }
37
- function readNotificationSender(ctx) {
38
- const mcpReq = readMcpReq(ctx);
39
- const notify = mcpReq?.notify;
40
- if (typeof notify !== "function")
41
- return;
42
- return notify;
43
- }
44
- function readRequestSender(ctx) {
45
- const mcpReq = readMcpReq(ctx);
46
- const send = mcpReq?.send;
47
- if (typeof send !== "function")
48
- return;
49
- return send;
50
- }
51
- function stringifyUnknown(value) {
52
- if (typeof value === "string")
53
- return value;
54
- try {
55
- return JSON.stringify(value);
56
- } catch {
57
- return String(value);
58
- }
59
- }
60
- function parseSampledText(result) {
61
- const content = result.content;
62
- if (Array.isArray(content) && content.length > 0) {
63
- const first = content[0];
64
- if (typeof first?.text === "string") {
65
- return first.text;
66
- }
67
- }
68
- if (content && typeof content === "object") {
69
- const text = content.text;
70
- if (typeof text === "string") {
71
- return text;
72
- }
73
- }
74
- return stringifyUnknown(result);
75
- }
76
- function assertSamplingSupport(ctx) {
77
- const requestSender = readRequestSender(ctx);
78
- if (!requestSender) {
79
- throw new ProtocolError(ProtocolErrorCode.InvalidRequest, "Client does not support sampling");
80
- }
81
- }
82
-
83
- // src/conformance-fixture-registration.ts
84
- import { z } from "zod";
85
- import { ResourceTemplate, completable } from "@modelcontextprotocol/server";
86
-
87
- // src/long-running-operation-support.ts
88
- async function runWithStandardizedTimeout(input) {
89
- const timeoutMilliseconds = input.timeoutMilliseconds ?? 30000;
90
- const internalController = new AbortController;
91
- let timeoutIdentifier;
92
- let rejectOnExternalAbort;
93
- const onExternalAbort = () => {
94
- const cancellationError = new Error("Operation cancelled by client.");
95
- internalController.abort(cancellationError);
96
- rejectOnExternalAbort?.(cancellationError);
97
- };
98
- try {
99
- if (input.abortSignal?.aborted) {
100
- onExternalAbort();
101
- throw new Error("Operation cancelled by client.");
102
- }
103
- return await Promise.race([
104
- input.operation(internalController.signal),
105
- new Promise((_, reject) => {
106
- rejectOnExternalAbort = reject;
107
- timeoutIdentifier = setTimeout(() => {
108
- const timeoutError = new Error(`Operation timed out after ${timeoutMilliseconds}ms.`);
109
- internalController.abort(timeoutError);
110
- reject(timeoutError);
111
- }, timeoutMilliseconds);
112
- if (input.abortSignal?.aborted) {
113
- onExternalAbort();
114
- } else {
115
- input.abortSignal?.addEventListener("abort", onExternalAbort, { once: true });
116
- }
117
- })
118
- ]);
119
- } finally {
120
- clearTimeout(timeoutIdentifier);
121
- input.abortSignal?.removeEventListener("abort", onExternalAbort);
122
- if (!internalController.signal.aborted) {
123
- internalController.abort(new Error("Operation settled."));
124
- }
125
- }
126
- }
127
-
128
- // src/conformance-fixture-registration.ts
129
- var oneByOnePngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO5m0QAAAABJRU5ErkJggg==";
130
- var minimalWavBase64 = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAIlYAAESsAAACABAAZGF0YQAAAAA=";
131
- function delay(milliseconds, signal) {
132
- return new Promise((resolve, reject) => {
133
- if (signal?.aborted) {
134
- reject(signal.reason);
135
- return;
136
- }
137
- const timer = setTimeout(resolve, milliseconds);
138
- signal?.addEventListener("abort", () => {
139
- clearTimeout(timer);
140
- reject(signal.reason);
141
- }, { once: true });
142
- });
143
- }
144
- var cancellableOperationTestHooks = {
145
- completedCount: 0,
146
- abortedCount: 0,
147
- reset() {
148
- this.completedCount = 0;
149
- this.abortedCount = 0;
150
- }
151
- };
152
- function registerConformanceFixtures(server, publishResourceUpdate) {
153
- server.registerTool("test_simple_text", { description: "Conformance fixture: returns a single plain-text content block." }, async () => ({
154
- content: [{ type: "text", text: "This is a simple text response." }]
155
- }));
156
- server.registerTool("test_error_handling", { description: "Conformance fixture: always returns a tool-level error result." }, async () => ({
157
- isError: true,
158
- content: [{ type: "text", text: "This is a deliberate test error." }]
159
- }));
160
- server.registerTool("test_image_content", { description: "Conformance fixture: returns an image content block." }, async () => ({
161
- content: [
162
- {
163
- type: "image",
164
- data: oneByOnePngBase64,
165
- mimeType: "image/png"
166
- }
167
- ]
168
- }));
169
- server.registerTool("test_audio_content", { description: "Conformance fixture: returns an audio content block." }, async () => ({
170
- content: [
171
- {
172
- type: "audio",
173
- data: minimalWavBase64,
174
- mimeType: "audio/wav"
175
- }
176
- ]
177
- }));
178
- server.registerTool("test_embedded_resource", { description: "Conformance fixture: returns embedded resource content." }, async () => ({
179
- content: [
180
- {
181
- type: "resource",
182
- resource: {
183
- uri: "test://embedded-resource",
184
- mimeType: "text/plain",
185
- text: "This is an embedded resource content."
186
- }
187
- }
188
- ]
189
- }));
190
- server.registerTool("test_multiple_content_types", { description: "Conformance fixture: returns text, image, and resource content." }, async () => ({
191
- content: [
192
- {
193
- type: "text",
194
- text: "Multiple content types test:"
195
- },
196
- {
197
- type: "image",
198
- data: oneByOnePngBase64,
199
- mimeType: "image/png"
200
- },
201
- {
202
- type: "resource",
203
- resource: {
204
- uri: "test://mixed-content-resource",
205
- mimeType: "application/json",
206
- text: '{"test":"data","value":123}'
207
- }
208
- }
209
- ]
210
- }));
211
- server.registerTool("test_tool_with_logging", {
212
- description: "Conformance fixture: sends logging notifications during execution.",
213
- inputSchema: z.object({})
214
- }, async (_input, ctx) => {
215
- const sendNotification = readNotificationSender(ctx);
216
- if (sendNotification) {
217
- await sendNotification({
218
- method: "notifications/message",
219
- params: { level: "info", data: "Tool execution started" }
220
- });
221
- }
222
- await delay(50);
223
- if (sendNotification) {
224
- await sendNotification({
225
- method: "notifications/message",
226
- params: { level: "info", data: "Tool processing data" }
227
- });
228
- }
229
- await delay(50);
230
- if (sendNotification) {
231
- await sendNotification({
232
- method: "notifications/message",
233
- params: { level: "info", data: "Tool execution completed" }
234
- });
235
- }
236
- return {
237
- content: [
238
- {
239
- type: "text",
240
- text: "Logging tool execution completed."
241
- }
242
- ]
243
- };
244
- });
245
- server.registerTool("test_tool_with_progress", {
246
- description: "Conformance fixture: sends progress notifications during execution.",
247
- inputSchema: z.object({})
248
- }, async (_input, ctx) => {
249
- const progressToken = readProgressToken(ctx);
250
- const sendNotification = readNotificationSender(ctx);
251
- if (progressToken !== undefined && sendNotification) {
252
- await sendNotification({
253
- method: "notifications/progress",
254
- params: { progressToken, progress: 0, total: 100 }
255
- });
256
- await delay(50);
257
- await sendNotification({
258
- method: "notifications/progress",
259
- params: { progressToken, progress: 50, total: 100 }
260
- });
261
- await delay(50);
262
- await sendNotification({
263
- method: "notifications/progress",
264
- params: { progressToken, progress: 100, total: 100 }
265
- });
266
- } else {
267
- await delay(100);
268
- }
269
- return {
270
- content: [
271
- {
272
- type: "text",
273
- text: "Progress tool execution completed."
274
- }
275
- ]
276
- };
277
- });
278
- server.registerTool("test_sampling", {
279
- description: "Conformance fixture: requests client sampling.",
280
- inputSchema: z.object({
281
- prompt: z.string().describe("Prompt to send to sampling/createMessage")
282
- })
283
- }, async (input, ctx) => {
284
- const sendRequest = readRequestSender(ctx);
285
- if (!sendRequest) {
286
- return {
287
- content: [
288
- {
289
- type: "text",
290
- text: "Sampling is not supported by this client."
291
- }
292
- ],
293
- isError: true
294
- };
295
- }
296
- try {
297
- const sampledResult = await sendRequest({
298
- method: "sampling/createMessage",
299
- params: {
300
- messages: [
301
- {
302
- role: "user",
303
- content: {
304
- type: "text",
305
- text: input.prompt
306
- }
307
- }
308
- ],
309
- maxTokens: 100
310
- }
311
- });
312
- return {
313
- content: [
314
- {
315
- type: "text",
316
- text: `LLM response: ${parseSampledText(sampledResult)}`
317
- }
318
- ]
319
- };
320
- } catch {
321
- return {
322
- content: [
323
- {
324
- type: "text",
325
- text: "Sampling is not supported by this client."
326
- }
327
- ],
328
- isError: true
329
- };
330
- }
331
- });
332
- server.registerTool("test_elicitation", {
333
- description: "Conformance fixture: requests elicitation from client.",
334
- inputSchema: z.object({
335
- message: z.string().describe("Prompt message shown to user")
336
- })
337
- }, async (input, ctx) => {
338
- const sendRequest = readRequestSender(ctx);
339
- if (!sendRequest) {
340
- return {
341
- content: [
342
- { type: "text", text: "Elicitation is not supported by this client." }
343
- ],
344
- isError: true
345
- };
346
- }
347
- try {
348
- const elicitationResult = await sendRequest({
349
- method: "elicitation/create",
350
- params: {
351
- message: input.message,
352
- requestedSchema: {
353
- type: "object",
354
- properties: {
355
- username: {
356
- type: "string",
357
- description: "User's response"
358
- },
359
- email: {
360
- type: "string",
361
- description: "User's email address"
362
- }
363
- },
364
- required: ["username", "email"]
365
- }
366
- }
367
- });
368
- return {
369
- content: [
370
- {
371
- type: "text",
372
- text: `User response: action=${elicitationResult.action}, content=${stringifyUnknown(elicitationResult.content ?? {})}`
373
- }
374
- ]
375
- };
376
- } catch {
377
- return {
378
- content: [
379
- { type: "text", text: "Elicitation is not supported by this client." }
380
- ],
381
- isError: true
382
- };
383
- }
384
- });
385
- server.registerTool("test_elicitation_sep1034_defaults", {
386
- description: "Conformance fixture: elicitation defaults for SEP-1034.",
387
- inputSchema: z.object({})
388
- }, async (_input, ctx) => {
389
- const sendRequest = readRequestSender(ctx);
390
- if (!sendRequest) {
391
- return {
392
- content: [
393
- { type: "text", text: "Elicitation is not supported by this client." }
394
- ],
395
- isError: true
396
- };
397
- }
398
- try {
399
- const result = await sendRequest({
400
- method: "elicitation/create",
401
- params: {
402
- message: "Provide defaults confirmation",
403
- requestedSchema: {
404
- type: "object",
405
- properties: {
406
- name: { type: "string", default: "John Doe" },
407
- age: { type: "integer", default: 30 },
408
- score: { type: "number", default: 95.5 },
409
- status: {
410
- type: "string",
411
- enum: ["active", "inactive", "pending"],
412
- default: "active"
413
- },
414
- verified: { type: "boolean", default: true }
415
- },
416
- required: ["name", "age", "score", "status", "verified"]
417
- }
418
- }
419
- });
420
- return {
421
- content: [
422
- {
423
- type: "text",
424
- text: `Elicitation completed: action=${result.action}, content=${stringifyUnknown(result.content ?? {})}`
425
- }
426
- ]
427
- };
428
- } catch {
429
- return {
430
- content: [
431
- { type: "text", text: "Elicitation is not supported by this client." }
432
- ],
433
- isError: true
434
- };
435
- }
436
- });
437
- server.registerTool("test_elicitation_sep1330_enums", {
438
- description: "Conformance fixture: enum variants for SEP-1330.",
439
- inputSchema: z.object({})
440
- }, async (_input, ctx) => {
441
- const sendRequest = readRequestSender(ctx);
442
- if (!sendRequest) {
443
- return {
444
- content: [
445
- { type: "text", text: "Elicitation is not supported by this client." }
446
- ],
447
- isError: true
448
- };
449
- }
450
- try {
451
- const result = await sendRequest({
452
- method: "elicitation/create",
453
- params: {
454
- message: "Choose enum variants",
455
- requestedSchema: {
456
- type: "object",
457
- properties: {
458
- untitledSingle: {
459
- type: "string",
460
- enum: ["option1", "option2", "option3"]
461
- },
462
- titledSingle: {
463
- type: "string",
464
- oneOf: [
465
- { const: "value1", title: "First Option" },
466
- { const: "value2", title: "Second Option" },
467
- { const: "value3", title: "Third Option" }
468
- ]
469
- },
470
- legacyEnum: {
471
- type: "string",
472
- enum: ["opt1", "opt2", "opt3"],
473
- enumNames: ["Option One", "Option Two", "Option Three"]
474
- },
475
- untitledMulti: {
476
- type: "array",
477
- items: {
478
- type: "string",
479
- enum: ["option1", "option2", "option3"]
480
- }
481
- },
482
- titledMulti: {
483
- type: "array",
484
- items: {
485
- anyOf: [
486
- { const: "value1", title: "First Choice" },
487
- { const: "value2", title: "Second Choice" },
488
- { const: "value3", title: "Third Choice" }
489
- ]
490
- }
491
- }
492
- },
493
- required: [
494
- "untitledSingle",
495
- "titledSingle",
496
- "legacyEnum",
497
- "untitledMulti",
498
- "titledMulti"
499
- ]
500
- }
501
- }
502
- });
503
- return {
504
- content: [
505
- {
506
- type: "text",
507
- text: `Elicitation completed: action=${result.action}, content=${stringifyUnknown(result.content ?? {})}`
508
- }
509
- ]
510
- };
511
- } catch {
512
- return {
513
- content: [
514
- { type: "text", text: "Elicitation is not supported by this client." }
515
- ],
516
- isError: true
517
- };
518
- }
519
- });
520
- server.registerResource("test_static_text_resource", "test://static-text", { description: "Conformance fixture static text resource", mimeType: "text/plain" }, async () => ({
521
- contents: [
522
- {
523
- uri: "test://static-text",
524
- mimeType: "text/plain",
525
- text: "This is the content of the static text resource."
526
- }
527
- ]
528
- }));
529
- server.registerResource("test_static_binary_resource", "test://static-binary", { description: "Conformance fixture static binary resource", mimeType: "image/png" }, async () => ({
530
- contents: [
531
- {
532
- uri: "test://static-binary",
533
- mimeType: "image/png",
534
- blob: oneByOnePngBase64
535
- }
536
- ]
537
- }));
538
- server.registerResource("test_template_resource", new ResourceTemplate("test://template/{id}/data", {
539
- list: async () => ({
540
- resources: [
541
- {
542
- uri: "test://template/123/data",
543
- name: "template-data-123",
544
- mimeType: "application/json"
545
- }
546
- ]
547
- })
548
- }), { description: "Conformance fixture template resource", mimeType: "application/json" }, async (_uri, variables) => {
549
- const identifier = String(variables.id ?? "");
550
- return {
551
- contents: [
552
- {
553
- uri: `test://template/${identifier}/data`,
554
- mimeType: "application/json",
555
- text: `{"id":"${identifier}","templateTest":true,"data":"Data for ID: ${identifier}"}`
556
- }
557
- ]
558
- };
559
- });
560
- server.registerPrompt("test_simple_prompt", { description: "Conformance fixture simple prompt." }, async () => ({
561
- messages: [
562
- {
563
- role: "user",
564
- content: {
565
- type: "text",
566
- text: "This is a simple prompt for testing."
567
- }
568
- }
569
- ]
570
- }));
571
- server.registerPrompt("test_prompt_with_arguments", {
572
- description: "Conformance fixture prompt with arguments.",
573
- argsSchema: z.object({
574
- arg1: completable(z.string().describe("First test argument"), async (value) => {
575
- const query = String(value ?? "").toLowerCase();
576
- const values = ["paris", "park", "party"];
577
- return values.filter((item) => item.startsWith(query));
578
- }),
579
- arg2: z.string().describe("Second test argument")
580
- })
581
- }, async (arguments_) => ({
582
- messages: [
583
- {
584
- role: "user",
585
- content: {
586
- type: "text",
587
- text: `Prompt with arguments: arg1='${arguments_.arg1}', arg2='${arguments_.arg2}'`
588
- }
589
- }
590
- ]
591
- }));
592
- server.registerPrompt("test_prompt_with_embedded_resource", {
593
- description: "Conformance fixture prompt with embedded resource.",
594
- argsSchema: z.object({
595
- resourceUri: z.string().describe("URI of resource to embed")
596
- })
597
- }, async (arguments_) => ({
598
- messages: [
599
- {
600
- role: "user",
601
- content: {
602
- type: "resource",
603
- resource: {
604
- uri: arguments_.resourceUri,
605
- mimeType: "text/plain",
606
- text: "Embedded resource content for testing."
607
- }
608
- }
609
- },
610
- {
611
- role: "user",
612
- content: {
613
- type: "text",
614
- text: "Please process the embedded resource above."
615
- }
616
- }
617
- ]
618
- }));
619
- server.registerPrompt("test_prompt_with_image", {
620
- description: "Conformance fixture prompt with image content."
621
- }, async () => ({
622
- messages: [
623
- {
624
- role: "user",
625
- content: {
626
- type: "image",
627
- data: oneByOnePngBase64,
628
- mimeType: "image/png"
629
- }
630
- },
631
- {
632
- role: "user",
633
- content: {
634
- type: "text",
635
- text: "Please analyze the image above."
636
- }
637
- }
638
- ]
639
- }));
640
- server.registerTool("test_watched_resource_update", {
641
- description: "Conformance fixture helper that publishes a resource update notification for the given URI, scoped to this connection.",
642
- inputSchema: z.object({
643
- uri: z.string().describe("The resource URI to publish an update for.")
644
- })
645
- }, async (input) => {
646
- if (publishResourceUpdate) {
647
- await publishResourceUpdate(input.uri);
648
- } else {
649
- await server.server.sendResourceUpdated({ uri: input.uri });
650
- }
651
- return {
652
- content: [
653
- {
654
- type: "text",
655
- text: `Sent a resource update notification for ${input.uri}.`
656
- }
657
- ]
658
- };
659
- });
660
- server.registerTool("test_cancellable_operation", {
661
- 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.",
662
- inputSchema: z.object({
663
- delayMilliseconds: z.number().int().positive().max(60000).describe("How long the underlying operation sleeps before resolving.")
664
- })
665
- }, async (input, ctx) => {
666
- try {
667
- await runWithStandardizedTimeout({
668
- operation: (signal) => delay(input.delayMilliseconds, signal),
669
- abortSignal: ctx.mcpReq.signal,
670
- timeoutMilliseconds: input.delayMilliseconds + 60000
671
- });
672
- cancellableOperationTestHooks.completedCount += 1;
673
- } catch (error) {
674
- cancellableOperationTestHooks.abortedCount += 1;
675
- return {
676
- content: [
677
- {
678
- type: "text",
679
- text: `Cancelled: ${error instanceof Error ? error.message : String(error)}`
680
- }
681
- ],
682
- isError: true
683
- };
684
- }
685
- return {
686
- content: [{ type: "text", text: "Cancellable operation completed." }]
687
- };
688
- });
689
- }
690
-
691
- // src/server.ts
692
- import { McpServer, ProtocolError as ProtocolError2 } from "@modelcontextprotocol/server";
693
-
694
- // src/instructions.md
695
- 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";
696
-
697
- // src/server.ts
698
- import { EXTENSION_ID } from "@modelcontextprotocol/ext-apps/server";
699
- function buildServerCapabilities(input) {
700
- return {
701
- ...input.families.tools ? { tools: { listChanged: false } } : {},
702
- ...input.families.resources ? {
703
- resources: {
704
- listChanged: false,
705
- ...input.subscriptionsEnabled ? { subscribe: true } : {}
706
- }
707
- } : {},
708
- ...input.families.prompts ? { prompts: { listChanged: false } } : {},
709
- experimental: input.experimentalCapabilities,
710
- ...input.enableConformanceMode ? { logging: {} } : {}
711
- };
712
- }
713
- var mcpInsufficientScopeErrorCode = -32003;
714
- function insufficientScopeChallenge(requiredScope) {
715
- return `Bearer error="insufficient_scope", scope="${requiredScope}"`;
716
- }
717
- function hasRequiredScope(grantedScopes, requiredScope) {
718
- return grantedScopes.includes(requiredScope);
719
- }
720
- function areResourceSubscriptionsAuthorized(uris, scopes, registry) {
721
- return uris.every((uri) => {
722
- const resource = registry.resources.find((definition) => definition.uri === uri);
723
- return resource !== undefined && hasRequiredScope(scopes, resource.requiredScope);
724
- });
725
- }
726
- function createMcpServer(context, registry) {
727
- const era = context.era ?? "legacy";
728
- const enableConformanceMode = context.enableConformanceMode ?? getEnvironment().MCP_CONFORMANCE_MODE;
729
- const experimentalCapabilities = {};
730
- if (context.enableUiExtension && hasRegisteredUiExtensionResource(registry)) {
731
- experimentalCapabilities[EXTENSION_ID] = { version: "1.0.0" };
732
- }
733
- const serverInfo = registry.serverInfo ?? {
734
- name: getEnvironment().MCP_SERVER_NAME,
735
- version: PACKAGE_VERSION
736
- };
737
- const server = new McpServer({
738
- name: serverInfo.name,
739
- version: serverInfo.version
740
- }, {
741
- instructions: registry.instructions ?? instructions_default,
742
- capabilities: buildServerCapabilities({
743
- families: {
744
- tools: enableConformanceMode || registry.tools.length > 0,
745
- resources: enableConformanceMode || registry.resources.length > 0,
746
- prompts: enableConformanceMode || registry.prompts.length > 0
747
- },
748
- enableConformanceMode,
749
- experimentalCapabilities,
750
- subscriptionsEnabled: era === "modern" && context.publishResourceUpdate !== undefined
751
- })
752
- });
753
- function registerToolDefinition(tool) {
754
- server.registerTool(tool.name, {
755
- title: tool.title,
756
- description: tool.description,
757
- inputSchema: tool.inputSchema,
758
- ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
759
- annotations: tool.annotations,
760
- ...tool._meta ? { _meta: tool._meta } : {}
761
- }, async (input, ctx) => {
762
- if (!hasRequiredScope(context.scopes, tool.requiredScope)) {
763
- engineLogger.warn({
764
- event: "mcp_tool_call",
765
- outcome: "insufficient_scope",
766
- tool: tool.name,
767
- requiredScope: tool.requiredScope,
768
- userId: context.userId,
769
- requestId: context.requestId
770
- }, "MCP tool call rejected: insufficient scope");
771
- metricsCollector.recordToolInvocation(tool.name, 0, true);
772
- metricsCollector.recordEvent("mcp_method", "insufficient_scope");
773
- return {
774
- content: [
775
- {
776
- type: "text",
777
- text: `Insufficient scope: this tool requires '${tool.requiredScope}'.`
778
- }
779
- ],
780
- isError: true,
781
- _meta: { "mcp/www_authenticate": insufficientScopeChallenge(tool.requiredScope) }
782
- };
783
- }
784
- const start = Date.now();
785
- let result;
786
- try {
787
- result = await tool.handler(input, {
788
- ...context,
789
- signal: ctx.mcpReq.signal
790
- });
791
- } catch (error) {
792
- metricsCollector.recordToolInvocation(tool.name, Date.now() - start, true);
793
- engineLogger.warn({
794
- event: "mcp_tool_call",
795
- outcome: "tool_failure",
796
- tool: tool.name,
797
- userId: context.userId,
798
- requestId: context.requestId
799
- }, "MCP tool handler threw");
800
- metricsCollector.recordEvent("mcp_method", "tool_failure");
801
- throw error;
802
- }
803
- const isError = "isError" in result && result.isError === true;
804
- metricsCollector.recordToolInvocation(tool.name, Date.now() - start, isError);
805
- if (isError) {
806
- engineLogger.warn({
807
- event: "mcp_tool_call",
808
- outcome: "tool_failure",
809
- tool: tool.name,
810
- userId: context.userId,
811
- requestId: context.requestId
812
- }, "MCP tool call returned an error result");
813
- metricsCollector.recordEvent("mcp_method", "tool_failure");
814
- }
815
- return result;
816
- });
817
- }
818
- for (const tool of registry.tools) {
819
- registerToolDefinition(tool);
820
- }
821
- function assertRequiredScope(definition) {
822
- if (hasRequiredScope(context.scopes, definition.requiredScope))
823
- return;
824
- throw new ProtocolError2(mcpInsufficientScopeErrorCode, `Insufficient scope: '${definition.name}' requires '${definition.requiredScope}'.`, {
825
- requiredScope: definition.requiredScope,
826
- _meta: { "mcp/www_authenticate": insufficientScopeChallenge(definition.requiredScope) }
827
- });
828
- }
829
- for (const resource of registry.resources) {
830
- server.registerResource(resource.name, resource.uri, { title: resource.title, description: resource.description, mimeType: resource.mimeType }, async (uri, ctx) => {
831
- assertRequiredScope(resource);
832
- return resource.handler(uri, { ...context, signal: ctx.mcpReq.signal });
833
- });
834
- }
835
- for (const prompt of registry.prompts) {
836
- server.registerPrompt(prompt.name, {
837
- title: prompt.title,
838
- description: prompt.description,
839
- ...prompt.arguments ? { argsSchema: prompt.arguments } : {}
840
- }, async (arguments_, ctx) => {
841
- assertRequiredScope(prompt);
842
- return prompt.handler(arguments_, { ...context, signal: ctx.mcpReq.signal });
843
- });
844
- }
845
- server.server.setRequestHandler("resources/subscribe", async () => ({}));
846
- server.server.setRequestHandler("resources/unsubscribe", async () => ({}));
847
- if (enableConformanceMode) {
848
- for (const tool of registry.conformanceOnlyTools ?? []) {
849
- registerToolDefinition(tool);
850
- }
851
- registerConformanceFixtures(server, context.publishResourceUpdate);
852
- }
853
- return server;
854
- }
855
-
856
- // src/localhost-request-validation.ts
857
- var localhostHostnames = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
858
- function normalizeHostname(hostname) {
859
- return hostname.trim().toLowerCase();
860
- }
861
- function isLocalhostHostname(hostname) {
862
- return localhostHostnames.has(normalizeHostname(hostname));
863
- }
864
- function parseHostnameFromHostHeader(hostHeader) {
865
- if (!hostHeader) {
866
- return null;
867
- }
868
- const firstValue = hostHeader.split(",")[0].trim();
869
- if (firstValue.length === 0) {
870
- return null;
871
- }
872
- if (firstValue.startsWith("[")) {
873
- const endIndex = firstValue.indexOf("]");
874
- if (endIndex === -1)
875
- return null;
876
- return firstValue.slice(0, endIndex + 1);
877
- }
878
- const separatorIndex = firstValue.indexOf(":");
879
- if (separatorIndex === -1) {
880
- return firstValue;
881
- }
882
- return firstValue.slice(0, separatorIndex);
883
- }
884
- function parseHostnameFromOriginHeader(originHeader) {
885
- if (!originHeader || originHeader === "null") {
886
- return null;
887
- }
888
- try {
889
- const parsedOrigin = new URL(originHeader);
890
- if (parsedOrigin.origin === "null" || parsedOrigin.origin !== originHeader) {
891
- return null;
892
- }
893
- return parsedOrigin.hostname;
894
- } catch {
895
- return null;
896
- }
897
- }
898
- function isLoopbackHostname(hostname) {
899
- return isLocalhostHostname(hostname);
900
- }
901
- function hasValidLocalhostRebindingHeaders(headers) {
902
- const requestHost = parseHostnameFromHostHeader(headers.get("host"));
903
- if (requestHost && !isLocalhostHostname(requestHost)) {
904
- return false;
905
- }
906
- const requestOrigin = headers.get("origin");
907
- if (requestOrigin !== null) {
908
- const requestOriginHost = parseHostnameFromOriginHeader(requestOrigin);
909
- if (!requestOriginHost || !isLocalhostHostname(requestOriginHost)) {
910
- return false;
911
- }
912
- }
913
- return true;
914
- }
915
-
916
- export { readProgressToken, readSessionIdentifier, readNotificationSender, readRequestSender, stringifyUnknown, parseSampledText, assertSamplingSupport, cancellableOperationTestHooks, areResourceSubscriptionsAuthorized, createMcpServer, isLoopbackHostname, hasValidLocalhostRebindingHeaders };