@lostgradient/mcp 0.1.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -0
  3. package/dist/chunk-mf3t0afg.js +4 -0
  4. package/dist/chunk-psnez3q2.js +111 -0
  5. package/dist/chunk-taxyscge.js +67 -0
  6. package/dist/chunk-v14p4gng.js +25 -0
  7. package/dist/chunk-wmkqd45r.js +14 -0
  8. package/dist/conformance-fixture-registration.d.ts +30 -0
  9. package/dist/conformance-server.d.ts +1 -0
  10. package/dist/env.d.ts +59 -0
  11. package/dist/env.js +9 -0
  12. package/dist/environment-schema.d.ts +29 -0
  13. package/dist/environment-schema.js +6 -0
  14. package/dist/golden-prompts.d.ts +42 -0
  15. package/dist/handler-context.d.ts +16 -0
  16. package/dist/index.d.ts +25 -0
  17. package/dist/index.js +1326 -0
  18. package/dist/localhost-request-validation.d.ts +2 -0
  19. package/dist/logger.d.ts +39 -0
  20. package/dist/logger.js +14 -0
  21. package/dist/long-running-operation-support.d.ts +34 -0
  22. package/dist/metrics.d.ts +64 -0
  23. package/dist/metrics.js +6 -0
  24. package/dist/prompts/index.d.ts +5 -0
  25. package/dist/prompts/summarize.d.ts +4 -0
  26. package/dist/resources/index.d.ts +4 -0
  27. package/dist/resources/user-profile.d.ts +1 -0
  28. package/dist/scope-vocabulary.d.ts +127 -0
  29. package/dist/scopes.d.ts +49 -0
  30. package/dist/server.d.ts +113 -0
  31. package/dist/supported-scopes.d.ts +25 -0
  32. package/dist/template-registry.d.ts +16 -0
  33. package/dist/tool-response.d.ts +94 -0
  34. package/dist/tools/get-user-profile.d.ts +8 -0
  35. package/dist/tools/index.d.ts +16 -0
  36. package/dist/tools/list-audit-events.d.ts +11 -0
  37. package/dist/type-assertions.d.ts +1 -0
  38. package/dist/types/primitives.d.ts +130 -0
  39. package/dist/ui-extension-support.d.ts +20 -0
  40. package/dist/version.d.ts +23 -0
  41. package/dist/version.js +6 -0
  42. package/package.json +73 -0
package/dist/index.js ADDED
@@ -0,0 +1,1326 @@
1
+ import {
2
+ getLogger,
3
+ logger
4
+ } from "./chunk-psnez3q2.js";
5
+ import {
6
+ getEnvironment,
7
+ parseMcpServerEnvironment
8
+ } from "./chunk-v14p4gng.js";
9
+ import {
10
+ metricsCollector
11
+ } from "./chunk-taxyscge.js";
12
+ import"./chunk-wmkqd45r.js";
13
+ import {
14
+ 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
+ }
859
+ // src/tools/get-user-profile.ts
860
+ import { z as z2 } from "zod";
861
+
862
+ // src/tool-response.ts
863
+ var maxToolResultBytes = 256 * 1024;
864
+ function utf8ByteLength(text) {
865
+ let bytes = 0;
866
+ for (const character of text) {
867
+ const codePoint = character.codePointAt(0) ?? 0;
868
+ bytes += codePoint < 128 ? 1 : codePoint < 2048 ? 2 : codePoint < 65536 ? 3 : 4;
869
+ }
870
+ return bytes;
871
+ }
872
+ function exceededByteLength(text) {
873
+ if (text.length * 3 <= maxToolResultBytes)
874
+ return null;
875
+ const byteLength = utf8ByteLength(text);
876
+ return byteLength > maxToolResultBytes ? byteLength : null;
877
+ }
878
+ function boundedTextContent(text) {
879
+ const exceeded = exceededByteLength(text);
880
+ if (exceeded !== null) {
881
+ return {
882
+ content: [
883
+ {
884
+ type: "text",
885
+ text: `Result omitted: exceeded the ${maxToolResultBytes}-byte tool result limit (was ${exceeded} bytes).`
886
+ }
887
+ ]
888
+ };
889
+ }
890
+ return { content: [{ type: "text", text }] };
891
+ }
892
+ function createToolTextResponse(text) {
893
+ const bounded = boundedTextContent(text);
894
+ if (bounded.content[0].text !== text) {
895
+ return { ...bounded, isError: true };
896
+ }
897
+ return bounded;
898
+ }
899
+ function createToolJsonResponse(data) {
900
+ const serialized = JSON.stringify(data) ?? "null";
901
+ const bounded = boundedTextContent(serialized);
902
+ if (bounded.content[0].text !== serialized) {
903
+ return { ...bounded, isError: true };
904
+ }
905
+ return bounded;
906
+ }
907
+ function createToolErrorResponse(message) {
908
+ const bounded = boundedTextContent(message);
909
+ return {
910
+ ...bounded,
911
+ isError: true
912
+ };
913
+ }
914
+ function createToolStructuredResponse(data, summary) {
915
+ const boundedSummary = boundedTextContent(summary);
916
+ if (boundedSummary.content[0].text !== summary) {
917
+ return { ...boundedSummary, isError: true };
918
+ }
919
+ const serialized = JSON.stringify(data) ?? "null";
920
+ const exceededSerialized = exceededByteLength(serialized);
921
+ if (exceededSerialized !== null) {
922
+ return {
923
+ content: [
924
+ {
925
+ type: "text",
926
+ text: `Result omitted: exceeded the ${maxToolResultBytes}-byte tool result limit (was ${exceededSerialized} bytes).`
927
+ }
928
+ ],
929
+ isError: true
930
+ };
931
+ }
932
+ return { ...boundedSummary, structuredContent: data };
933
+ }
934
+
935
+ // src/scope-vocabulary.ts
936
+ function isPlainObject(value) {
937
+ if (typeof value !== "object" || value === null)
938
+ return false;
939
+ const prototype = Object.getPrototypeOf(value);
940
+ return prototype === Object.prototype || prototype === null;
941
+ }
942
+ function deepFreezePlainData(value) {
943
+ if (Array.isArray(value)) {
944
+ for (const entry of value)
945
+ deepFreezePlainData(entry);
946
+ return Object.freeze(value);
947
+ }
948
+ if (isPlainObject(value)) {
949
+ for (const entry of Object.values(value))
950
+ deepFreezePlainData(entry);
951
+ return Object.freeze(value);
952
+ }
953
+ return value;
954
+ }
955
+ function clonePlainData(value) {
956
+ if (Array.isArray(value))
957
+ return value.map(clonePlainData);
958
+ if (isPlainObject(value)) {
959
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clonePlainData(entry)]));
960
+ }
961
+ return value;
962
+ }
963
+ function snapshotDefinition(definition) {
964
+ return deepFreezePlainData(clonePlainData(definition));
965
+ }
966
+ var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
967
+ function defineScopes(descriptions) {
968
+ const scopes = Object.freeze(Object.keys(descriptions));
969
+ if (scopes.length === 0) {
970
+ throw new Error("defineScopes() was given no scopes. If the object literal looked non-empty, check for " + "a key that does not become an own property — `__proto__` is the one that does this.");
971
+ }
972
+ for (const scope of scopes) {
973
+ if (!SCOPE_TOKEN.test(scope)) {
974
+ throw new Error(`Invalid OAuth scope token ${JSON.stringify(scope)}: a scope must match RFC 6749's ` + "`scope-token` (printable ASCII, no space, double quote, or backslash). A scope " + "containing a space would be re-parsed as two scopes wherever scopes are " + "space-delimited, leaving the primitive that requires it impossible to authorize.");
975
+ }
976
+ if (descriptions[scope].trim() === "") {
977
+ throw new Error(`Scope ${JSON.stringify(scope)} has a blank description. The consent screen renders ` + "this text verbatim, so a blank value shows the user an unexplained grant.");
978
+ }
979
+ }
980
+ const membership = new Set(scopes);
981
+ const frozenDescriptions = snapshotDefinition({ ...descriptions });
982
+ function assertDeclared(definition) {
983
+ if (!membership.has(definition.requiredScope)) {
984
+ throw new Error(`${definition.name} requires scope ${JSON.stringify(definition.requiredScope)}, which ` + `this vocabulary does not declare. Declared: ${scopes.join(", ")}.`);
985
+ }
986
+ return definition;
987
+ }
988
+ return Object.freeze({
989
+ scopes,
990
+ descriptions: frozenDescriptions,
991
+ isScope(value) {
992
+ return membership.has(value);
993
+ },
994
+ defineTool: (definition) => assertDeclared(definition),
995
+ defineResource: (definition) => assertDeclared(definition),
996
+ definePrompt: (definition) => assertDeclared(definition),
997
+ defineRegistry: (registry) => {
998
+ for (const tool of registry.tools)
999
+ assertDeclared(tool);
1000
+ for (const resource of registry.resources)
1001
+ assertDeclared(resource);
1002
+ for (const prompt of registry.prompts)
1003
+ assertDeclared(prompt);
1004
+ for (const tool of registry.conformanceOnlyTools ?? [])
1005
+ assertDeclared(tool);
1006
+ return Object.freeze({
1007
+ ...registry,
1008
+ tools: Object.freeze(registry.tools.map(snapshotDefinition)),
1009
+ resources: Object.freeze(registry.resources.map(snapshotDefinition)),
1010
+ prompts: Object.freeze(registry.prompts.map(snapshotDefinition)),
1011
+ ...registry.serverInfo ? { serverInfo: snapshotDefinition(registry.serverInfo) } : {},
1012
+ ...registry.conformanceOnlyTools ? {
1013
+ conformanceOnlyTools: Object.freeze(registry.conformanceOnlyTools.map(snapshotDefinition))
1014
+ } : {}
1015
+ });
1016
+ }
1017
+ });
1018
+ }
1019
+
1020
+ // src/scopes.ts
1021
+ var templateScopeVocabulary = defineScopes({
1022
+ "profile:read": "Read your profile information (name, email, avatar, role).",
1023
+ "audit:read": "Read synthetic audit event history (protocol conformance testing only).",
1024
+ "prompts:read": "Use this server’s prompt templates on your behalf."
1025
+ });
1026
+ var mcpScopes = templateScopeVocabulary.scopes;
1027
+ var mcpScopeDescriptions = templateScopeVocabulary.descriptions;
1028
+ function isMcpScope(value) {
1029
+ return templateScopeVocabulary.isScope(value);
1030
+ }
1031
+ var { defineTool, defineResource, definePrompt } = templateScopeVocabulary;
1032
+
1033
+ // 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()
1040
+ });
1041
+ var getUserProfileTool = defineTool({
1042
+ name: "get_user_profile",
1043
+ title: "Get User Profile",
1044
+ 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({}),
1046
+ outputSchema: getUserProfileOutputSchema,
1047
+ requiredScope: "profile:read",
1048
+ annotations: {
1049
+ readOnlyHint: true,
1050
+ destructiveHint: false,
1051
+ idempotentHint: true,
1052
+ openWorldHint: false
1053
+ },
1054
+ handler: async (_input, context) => {
1055
+ return createToolStructuredResponse(context.user, `Profile for ${context.user.name} <${context.user.email}>.`);
1056
+ }
1057
+ });
1058
+ // src/tools/list-audit-events.ts
1059
+ import { z as z3 } from "zod";
1060
+ var auditEvents = Array.from({ length: 50 }, (_, index) => ({
1061
+ identifier: `event-${String(index + 1).padStart(3, "0")}`,
1062
+ message: `Audit event #${index + 1}`
1063
+ }));
1064
+ var listAuditEventsOutputSchema = z3.object({
1065
+ items: z3.array(z3.object({
1066
+ identifier: z3.string(),
1067
+ message: z3.string()
1068
+ })),
1069
+ next_cursor: z3.string().nullable()
1070
+ });
1071
+ function decodeCursor(cursor) {
1072
+ if (!cursor)
1073
+ return 0;
1074
+ const parsed = Number.parseInt(cursor, 10);
1075
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
1076
+ }
1077
+ var listAuditEventsTool = defineTool({
1078
+ name: "list_audit_events",
1079
+ title: "List Audit Events (Conformance Fixture)",
1080
+ 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).")
1084
+ }),
1085
+ outputSchema: listAuditEventsOutputSchema,
1086
+ requiredScope: "audit:read",
1087
+ annotations: {
1088
+ readOnlyHint: true,
1089
+ destructiveHint: false,
1090
+ idempotentHint: true,
1091
+ openWorldHint: false
1092
+ },
1093
+ handler: async (input) => {
1094
+ const start = decodeCursor(input.cursor);
1095
+ const end = Math.min(start + input.page_size, auditEvents.length);
1096
+ const nextCursor = end < auditEvents.length ? String(end) : null;
1097
+ return {
1098
+ ...createToolTextResponse(`Returned ${end - start} audit events.`),
1099
+ structuredContent: {
1100
+ items: auditEvents.slice(start, end),
1101
+ next_cursor: nextCursor
1102
+ }
1103
+ };
1104
+ }
1105
+ });
1106
+ // src/tools/index.ts
1107
+ var allTools = [getUserProfileTool];
1108
+ var conformanceOnlyTools = [listAuditEventsTool];
1109
+ // src/resources/user-profile.ts
1110
+ var userProfileResource = defineResource({
1111
+ name: "user_profile",
1112
+ title: "User Profile",
1113
+ uri: "user://profile",
1114
+ description: "Exposes the authenticated user's own profile information as a JSON resource.",
1115
+ mimeType: "application/json",
1116
+ requiredScope: "profile:read",
1117
+ handler: async (uri, context) => {
1118
+ return {
1119
+ contents: [
1120
+ {
1121
+ uri: uri.href,
1122
+ mimeType: "application/json",
1123
+ text: JSON.stringify(context.user)
1124
+ }
1125
+ ]
1126
+ };
1127
+ }
1128
+ });
1129
+ // src/resources/index.ts
1130
+ var allResources = [userProfileResource];
1131
+ // src/prompts/summarize.ts
1132
+ import { z as z4 } from "zod";
1133
+ function contentDiagnosticsActive() {
1134
+ const until = getEnvironment().LOG_CONTENT_DIAGNOSTICS_UNTIL;
1135
+ if (!until)
1136
+ return false;
1137
+ return Date.now() < Date.parse(until);
1138
+ }
1139
+ var summarizePrompt = definePrompt({
1140
+ name: "summarize",
1141
+ title: "Summarize Topic",
1142
+ description: "Generates a prompt that asks the assistant to summarize a given topic for the authenticated user.",
1143
+ arguments: {
1144
+ topic: z4.string().describe("The topic to summarize")
1145
+ },
1146
+ requiredScope: "prompts:read",
1147
+ handler: async (arguments_, context) => {
1148
+ const requestLogger = logger.child({
1149
+ prompt: "summarize",
1150
+ userId: context.userId,
1151
+ requestId: context.requestId
1152
+ });
1153
+ const diagnosticsActive = contentDiagnosticsActive();
1154
+ try {
1155
+ if (diagnosticsActive) {
1156
+ requestLogger.warn({ diagnosticsUntil: getEnvironment().LOG_CONTENT_DIAGNOSTICS_UNTIL }, "Content diagnostics mode active: logging raw prompt topic");
1157
+ requestLogger.info({ diagnosticTopic: arguments_.topic }, "Prompt requested");
1158
+ } else {
1159
+ requestLogger.info({ topicLength: arguments_.topic.length }, "Prompt requested");
1160
+ }
1161
+ return {
1162
+ messages: [
1163
+ {
1164
+ role: "user",
1165
+ content: {
1166
+ type: "text",
1167
+ text: `Please provide a concise summary of the following topic: ${arguments_.topic}`
1168
+ }
1169
+ }
1170
+ ]
1171
+ };
1172
+ } catch (error) {
1173
+ requestLogger.error({ err: error }, "Prompt failed");
1174
+ return {
1175
+ messages: [
1176
+ {
1177
+ role: "user",
1178
+ content: {
1179
+ type: "text",
1180
+ text: "An error occurred while generating the prompt."
1181
+ }
1182
+ }
1183
+ ]
1184
+ };
1185
+ }
1186
+ }
1187
+ });
1188
+ // src/prompts/index.ts
1189
+ var allPrompts = [
1190
+ summarizePrompt
1191
+ ];
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
+
1245
+ // src/index.ts
1246
+ import {
1247
+ EXTENSION_ID as extensionId,
1248
+ RESOURCE_MIME_TYPE as resourceMimeType
1249
+ } from "@modelcontextprotocol/ext-apps/server";
1250
+
1251
+ // src/types/primitives.ts
1252
+ function defineTool2(definition) {
1253
+ return definition;
1254
+ }
1255
+ function defineResource2(definition) {
1256
+ return definition;
1257
+ }
1258
+ function definePrompt2(definition) {
1259
+ return definition;
1260
+ }
1261
+ // src/template-registry.ts
1262
+ var templateRegistry = {
1263
+ tools: allTools,
1264
+ resources: allResources,
1265
+ prompts: allPrompts,
1266
+ conformanceOnlyTools
1267
+ };
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();
1278
+ }
1279
+
1280
+ // src/index.ts
1281
+ var EXTENSION_ID2 = extensionId;
1282
+ var RESOURCE_MIME_TYPE2 = resourceMimeType;
1283
+ export {
1284
+ EXTENSION_ID2 as EXTENSION_ID,
1285
+ PACKAGE_VERSION,
1286
+ RESOURCE_MIME_TYPE2 as RESOURCE_MIME_TYPE,
1287
+ allPrompts,
1288
+ allResources,
1289
+ allTools,
1290
+ areResourceSubscriptionsAuthorized,
1291
+ assertSamplingSupport,
1292
+ cancellableOperationTestHooks,
1293
+ createMcpServer,
1294
+ createToolErrorResponse,
1295
+ createToolJsonResponse,
1296
+ createToolStructuredResponse,
1297
+ createToolTextResponse,
1298
+ definePrompt2 as definePrompt,
1299
+ defineResource2 as defineResource,
1300
+ defineScopes,
1301
+ defineTool2 as defineTool,
1302
+ getEnvironment,
1303
+ getLogger,
1304
+ getSupportedScopes,
1305
+ getUserProfileTool,
1306
+ hasRegisteredUiExtensionResource,
1307
+ hasValidLocalhostRebindingHeaders,
1308
+ isLoopbackHostname,
1309
+ isMcpScope,
1310
+ listAuditEventsTool,
1311
+ logger,
1312
+ mcpScopeDescriptions,
1313
+ mcpScopes,
1314
+ metricsCollector,
1315
+ parseMcpServerEnvironment,
1316
+ parseSampledText,
1317
+ readNotificationSender,
1318
+ readProgressToken,
1319
+ readRequestSender,
1320
+ readSessionIdentifier,
1321
+ stringifyUnknown,
1322
+ summarizePrompt,
1323
+ templateRegistry,
1324
+ templateScopeVocabulary,
1325
+ userProfileResource
1326
+ };