@lostgradient/mcp 0.2.6 → 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-5444sx3n.js +0 -916
  31. package/dist/chunk-6ekjtvcq.js +0 -273
  32. package/dist/chunk-k6fm3cmk.js +0 -132
  33. package/dist/chunk-r9atew6b.js +0 -449
  34. package/dist/chunk-rxnyn7tf.js +0 -19
  35. package/dist/chunk-taxyscge.js +0 -67
  36. package/dist/chunk-tkn6m6az.js +0 -1107
  37. package/dist/chunk-xcf742mf.js +0 -14
  38. package/dist/chunk-zrrf78wj.js +0 -4
  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
package/dist/index.js DELETED
@@ -1,616 +0,0 @@
1
- import {
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-5444sx3n.js";
15
- import {
16
- metricsCollector
17
- } from "./chunk-taxyscge.js";
18
- import {
19
- PACKAGE_VERSION
20
- } from "./chunk-zrrf78wj.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";
36
- // src/tools/get-user-profile.ts
37
- import { z } from "zod";
38
-
39
- // src/tool-response.ts
40
- var maxToolResultBytes = 256 * 1024;
41
- function utf8ByteLength(text) {
42
- let bytes = 0;
43
- for (const character of text) {
44
- const codePoint = character.codePointAt(0) ?? 0;
45
- bytes += codePoint < 128 ? 1 : codePoint < 2048 ? 2 : codePoint < 65536 ? 3 : 4;
46
- }
47
- return bytes;
48
- }
49
- function exceededByteLength(text) {
50
- if (text.length * 3 <= maxToolResultBytes)
51
- return null;
52
- const byteLength = utf8ByteLength(text);
53
- return byteLength > maxToolResultBytes ? byteLength : null;
54
- }
55
- function boundedTextContent(text) {
56
- const exceeded = exceededByteLength(text);
57
- if (exceeded !== null) {
58
- return {
59
- content: [
60
- {
61
- type: "text",
62
- text: `Result omitted: exceeded the ${maxToolResultBytes}-byte tool result limit (was ${exceeded} bytes).`
63
- }
64
- ]
65
- };
66
- }
67
- return { content: [{ type: "text", text }] };
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
- }
87
- function createToolTextResponse(text) {
88
- const bounded = boundedTextContent(text);
89
- if (bounded.content[0].text !== text) {
90
- return { ...bounded, isError: true };
91
- }
92
- return bounded;
93
- }
94
- function createToolJsonResponse(data) {
95
- const serialized = serializeToolResult(data);
96
- if (serialized === null)
97
- return createSerializationErrorResponse();
98
- const bounded = boundedTextContent(serialized);
99
- if (bounded.content[0].text !== serialized) {
100
- return { ...bounded, isError: true };
101
- }
102
- return bounded;
103
- }
104
- function createToolErrorResponse(message) {
105
- const bounded = boundedTextContent(message);
106
- return {
107
- ...bounded,
108
- isError: true
109
- };
110
- }
111
- function createToolStructuredResponse(data, summary) {
112
- const boundedSummary = boundedTextContent(summary);
113
- if (boundedSummary.content[0].text !== summary) {
114
- return { ...boundedSummary, isError: true };
115
- }
116
- const serialized = serializeToolResult(data);
117
- if (serialized === null)
118
- return createSerializationErrorResponse();
119
- const exceededSerialized = exceededByteLength(serialized);
120
- if (exceededSerialized !== null) {
121
- return {
122
- content: [
123
- {
124
- type: "text",
125
- text: `Result omitted: exceeded the ${maxToolResultBytes}-byte tool result limit (was ${exceededSerialized} bytes).`
126
- }
127
- ],
128
- isError: true
129
- };
130
- }
131
- return { ...boundedSummary, structuredContent: data };
132
- }
133
-
134
- // src/scope-vocabulary.ts
135
- function isPlainObject(value) {
136
- if (typeof value !== "object" || value === null)
137
- return false;
138
- const prototype = Object.getPrototypeOf(value);
139
- return prototype === Object.prototype || prototype === null;
140
- }
141
- function deepFreezePlainData(value) {
142
- if (Array.isArray(value)) {
143
- for (const entry of value)
144
- deepFreezePlainData(entry);
145
- return Object.freeze(value);
146
- }
147
- if (isPlainObject(value)) {
148
- for (const entry of Object.values(value))
149
- deepFreezePlainData(entry);
150
- return Object.freeze(value);
151
- }
152
- return value;
153
- }
154
- function clonePlainData(value) {
155
- if (Array.isArray(value))
156
- return value.map(clonePlainData);
157
- if (isPlainObject(value)) {
158
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clonePlainData(entry)]));
159
- }
160
- return value;
161
- }
162
- function snapshotDefinition(definition) {
163
- return deepFreezePlainData(clonePlainData(definition));
164
- }
165
- var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
166
- function defineScopes(descriptions) {
167
- const scopes = Object.freeze(Object.keys(descriptions));
168
- if (scopes.length === 0) {
169
- 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.");
170
- }
171
- for (const scope of scopes) {
172
- if (!SCOPE_TOKEN.test(scope)) {
173
- 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.");
174
- }
175
- if (descriptions[scope].trim() === "") {
176
- 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.");
177
- }
178
- }
179
- const membership = new Set(scopes);
180
- const frozenDescriptions = snapshotDefinition({ ...descriptions });
181
- function assertDeclared(definition) {
182
- if (!membership.has(definition.requiredScope)) {
183
- throw new Error(`${definition.name} requires scope ${JSON.stringify(definition.requiredScope)}, which ` + `this vocabulary does not declare. Declared: ${scopes.join(", ")}.`);
184
- }
185
- return definition;
186
- }
187
- return Object.freeze({
188
- scopes,
189
- descriptions: frozenDescriptions,
190
- isScope(value) {
191
- return membership.has(value);
192
- },
193
- defineTool: (definition) => assertDeclared(definition),
194
- defineResource: (definition) => assertDeclared(definition),
195
- definePrompt: (definition) => assertDeclared(definition),
196
- defineRegistry: (registry) => {
197
- for (const tool of registry.tools)
198
- assertDeclared(tool);
199
- for (const resource of registry.resources)
200
- assertDeclared(resource);
201
- for (const prompt of registry.prompts)
202
- assertDeclared(prompt);
203
- for (const tool of registry.conformanceOnlyTools ?? [])
204
- assertDeclared(tool);
205
- return Object.freeze({
206
- ...registry,
207
- tools: Object.freeze(registry.tools.map(snapshotDefinition)),
208
- resources: Object.freeze(registry.resources.map(snapshotDefinition)),
209
- prompts: Object.freeze(registry.prompts.map(snapshotDefinition)),
210
- ...registry.serverInfo ? { serverInfo: snapshotDefinition(registry.serverInfo) } : {},
211
- ...registry.conformanceOnlyTools ? {
212
- conformanceOnlyTools: Object.freeze(registry.conformanceOnlyTools.map(snapshotDefinition))
213
- } : {}
214
- });
215
- }
216
- });
217
- }
218
-
219
- // src/scopes.ts
220
- var templateScopeVocabulary = defineScopes({
221
- "profile:read": "Read your profile information (name, email, avatar, role).",
222
- "audit:read": "Read synthetic audit event history (protocol conformance testing only).",
223
- "prompts:read": "Use this server’s prompt templates on your behalf."
224
- });
225
- var mcpScopes = templateScopeVocabulary.scopes;
226
- var mcpScopeDescriptions = templateScopeVocabulary.descriptions;
227
- function isMcpScope(value) {
228
- return templateScopeVocabulary.isScope(value);
229
- }
230
- var { defineTool, defineResource, definePrompt } = templateScopeVocabulary;
231
-
232
- // src/tools/get-user-profile.ts
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()
239
- });
240
- var getUserProfileTool = defineTool({
241
- name: "get_user_profile",
242
- title: "Get User Profile",
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.",
244
- inputSchema: z.object({}),
245
- outputSchema: getUserProfileOutputSchema,
246
- requiredScope: "profile:read",
247
- annotations: {
248
- readOnlyHint: true,
249
- destructiveHint: false,
250
- idempotentHint: true,
251
- openWorldHint: false
252
- },
253
- handler: async (_input, context) => {
254
- return createToolStructuredResponse(context.user, `Profile for ${context.user.name} <${context.user.email}>.`);
255
- }
256
- });
257
- // src/tools/list-audit-events.ts
258
- import { z as z2 } from "zod";
259
- var auditEvents = Array.from({ length: 50 }, (_, index) => ({
260
- identifier: `event-${String(index + 1).padStart(3, "0")}`,
261
- message: `Audit event #${index + 1}`
262
- }));
263
- var listAuditEventsOutputSchema = z2.object({
264
- items: z2.array(z2.object({
265
- identifier: z2.string(),
266
- message: z2.string()
267
- })),
268
- next_cursor: z2.string().nullable()
269
- });
270
- function decodeCursor(cursor) {
271
- if (!cursor)
272
- return 0;
273
- const parsed = Number.parseInt(cursor, 10);
274
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
275
- }
276
- var listAuditEventsTool = defineTool({
277
- name: "list_audit_events",
278
- title: "List Audit Events (Conformance Fixture)",
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.",
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).")
283
- }),
284
- outputSchema: listAuditEventsOutputSchema,
285
- requiredScope: "audit:read",
286
- annotations: {
287
- readOnlyHint: true,
288
- destructiveHint: false,
289
- idempotentHint: true,
290
- openWorldHint: false
291
- },
292
- handler: async (input) => {
293
- const start = decodeCursor(input.cursor);
294
- const end = Math.min(start + input.page_size, auditEvents.length);
295
- const nextCursor = end < auditEvents.length ? String(end) : null;
296
- return {
297
- ...createToolTextResponse(`Returned ${end - start} audit events.`),
298
- structuredContent: {
299
- items: auditEvents.slice(start, end),
300
- next_cursor: nextCursor
301
- }
302
- };
303
- }
304
- });
305
- // src/tools/index.ts
306
- var allTools = [getUserProfileTool];
307
- var conformanceOnlyTools = [listAuditEventsTool];
308
- // src/resources/user-profile.ts
309
- var userProfileResource = defineResource({
310
- name: "user_profile",
311
- title: "User Profile",
312
- uri: "user://profile",
313
- description: "Exposes the authenticated user's own profile information as a JSON resource.",
314
- mimeType: "application/json",
315
- requiredScope: "profile:read",
316
- handler: async (uri, context) => {
317
- return {
318
- contents: [
319
- {
320
- uri: uri.href,
321
- mimeType: "application/json",
322
- text: JSON.stringify(context.user)
323
- }
324
- ]
325
- };
326
- }
327
- });
328
- // src/resources/index.ts
329
- var allResources = [userProfileResource];
330
- // src/prompts/summarize.ts
331
- import { z as z3 } from "zod";
332
- function contentDiagnosticsActive() {
333
- const until = getEnvironment().LOG_CONTENT_DIAGNOSTICS_UNTIL;
334
- if (!until)
335
- return false;
336
- return Date.now() < Date.parse(until);
337
- }
338
- var summarizePrompt = definePrompt({
339
- name: "summarize",
340
- title: "Summarize Topic",
341
- description: "Generates a prompt that asks the assistant to summarize a given topic for the authenticated user.",
342
- arguments: {
343
- topic: z3.string().describe("The topic to summarize")
344
- },
345
- requiredScope: "prompts:read",
346
- handler: async (arguments_, context) => {
347
- const requestLogger = engineLogger.child({
348
- prompt: "summarize",
349
- userId: context.userId,
350
- requestId: context.requestId
351
- });
352
- const diagnosticsActive = contentDiagnosticsActive();
353
- try {
354
- if (diagnosticsActive) {
355
- requestLogger.warn({ diagnosticsUntil: getEnvironment().LOG_CONTENT_DIAGNOSTICS_UNTIL }, "Content diagnostics mode active: logging raw prompt topic");
356
- requestLogger.info({ diagnosticTopic: arguments_.topic }, "Prompt requested");
357
- } else {
358
- requestLogger.info({ topicLength: arguments_.topic.length }, "Prompt requested");
359
- }
360
- return {
361
- messages: [
362
- {
363
- role: "user",
364
- content: {
365
- type: "text",
366
- text: `Please provide a concise summary of the following topic: ${arguments_.topic}`
367
- }
368
- }
369
- ]
370
- };
371
- } catch (error) {
372
- requestLogger.error({ err: error }, "Prompt failed");
373
- return {
374
- messages: [
375
- {
376
- role: "user",
377
- content: {
378
- type: "text",
379
- text: "An error occurred while generating the prompt."
380
- }
381
- }
382
- ]
383
- };
384
- }
385
- }
386
- });
387
- // src/prompts/index.ts
388
- var allPrompts = [
389
- summarizePrompt
390
- ];
391
-
392
- // src/index.ts
393
- import {
394
- EXTENSION_ID as extensionId,
395
- RESOURCE_MIME_TYPE as resourceMimeType
396
- } from "@modelcontextprotocol/ext-apps/server";
397
-
398
- // src/types/primitives.ts
399
- function defineTool2(definition) {
400
- return definition;
401
- }
402
- function defineResource2(definition) {
403
- return definition;
404
- }
405
- function definePrompt2(definition) {
406
- return definition;
407
- }
408
- // src/template-registry.ts
409
- var templateRegistry = {
410
- tools: allTools,
411
- resources: allResources,
412
- prompts: allPrompts,
413
- conformanceOnlyTools
414
- };
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;
564
- }
565
-
566
- // src/index.ts
567
- var EXTENSION_ID = extensionId;
568
- var RESOURCE_MIME_TYPE = resourceMimeType;
569
- export {
570
- EXTENSION_ID,
571
- PACKAGE_VERSION,
572
- RESOURCE_MIME_TYPE,
573
- allPrompts,
574
- allResources,
575
- allTools,
576
- areResourceSubscriptionsAuthorized,
577
- assertSamplingSupport,
578
- cancellableOperationTestHooks,
579
- createConsumerConformanceHandler,
580
- createMcpServer,
581
- createToolErrorResponse,
582
- createToolJsonResponse,
583
- createToolStructuredResponse,
584
- createToolTextResponse,
585
- defineOAuthScopeConfiguration,
586
- definePrompt2 as definePrompt,
587
- defineResource2 as defineResource,
588
- defineScopes,
589
- defineTool2 as defineTool,
590
- getEnvironment,
591
- getLogger,
592
- getSupportedScopes,
593
- getUserProfileTool,
594
- hasRegisteredUiExtensionResource,
595
- hasValidLocalhostRebindingHeaders,
596
- isLoopbackHostname,
597
- isMcpScope,
598
- listAuditEventsTool,
599
- logger,
600
- mcpScopeDescriptions,
601
- mcpScopes,
602
- metricsCollector,
603
- parseMcpServerEnvironment,
604
- parseSampledText,
605
- readNotificationSender,
606
- readProgressToken,
607
- readRequestSender,
608
- readSessionIdentifier,
609
- runMcpConformance,
610
- setLogger,
611
- stringifyUnknown,
612
- summarizePrompt,
613
- templateRegistry,
614
- templateScopeVocabulary,
615
- userProfileResource
616
- };
@@ -1,2 +0,0 @@
1
- export declare function isLoopbackHostname(hostname: string): boolean;
2
- export declare function hasValidLocalhostRebindingHeaders(headers: Headers): boolean;
package/dist/logger.d.ts DELETED
@@ -1,59 +0,0 @@
1
- import pino from 'pino';
2
- import type { DestinationStream } from 'pino';
3
- /**
4
- * The complete logging surface used by the MCP engine. Hosts can satisfy
5
- * this structurally with their existing logger; no pino import or pino type
6
- * is required. A child must preserve the same four-method contract.
7
- */
8
- export interface McpLogger {
9
- info(bindingsOrMessage: Record<string, unknown> | string, message?: string): void;
10
- warn(bindingsOrMessage: Record<string, unknown> | string, message?: string): void;
11
- error(bindingsOrMessage: Record<string, unknown> | string, message?: string): void;
12
- child(bindings: Record<string, unknown>): McpLogger;
13
- }
14
- /**
15
- * OBS-001 / S-14: `logger.ts` previously declared no redaction paths at
16
- * all, so any structured field that happened to carry a credential-shaped
17
- * value would be written verbatim. This template's request boundary
18
- * legitimately handles OAuth authorization codes, PKCE verifiers, access
19
- * and refresh tokens, ID tokens, client secrets, session cookies, database
20
- * and Redis connection strings (which embed credentials in the URL itself),
21
- * and user email addresses — every one of those has a named path here.
22
- *
23
- * Pino's `redact.paths` (backed by `fast-redact`) matches by KEY, not by
24
- * value, and its wildcard (`*`) only spans a single object level — there is
25
- * no recursive `**`. So paths are enumerated at the depths this codebase
26
- * actually logs at: top-level (a call site logs `{ token, ... }` directly),
27
- * one level nested (`{ headers: { authorization } }`,
28
- * `{ client: { client_secret } }`), and the specific two-level `headers.*`
29
- * shape a request-logging call site would use. A secret landing at some
30
- * other, unanticipated depth is not caught by key-path redaction — that gap
31
- * is exactly what `redactSecretValues` below (wired through pino's
32
- * `hooks.streamWrite`) exists to catch by VALUE instead, and
33
- * `redaction.test.ts` proves both mechanisms against a real, unmocked
34
- * logger rather than trusting this list is complete.
35
- */
36
- export declare const redactionPaths: readonly string[];
37
- /**
38
- * A factory, not just a singleton export, so tests can build a real logger
39
- * — the actual redaction config below, not a copy of it — against an
40
- * in-memory destination instead of stdout. Passing `destination` also
41
- * forces plain JSON output (no `pino-pretty` transport): pino refuses to
42
- * combine `options.transport` with a destination stream argument, and
43
- * tests need to parse exactly what was written, not a human-formatted
44
- * approximation of it.
45
- */
46
- export declare function createLogger(options?: {
47
- destination?: DestinationStream;
48
- }): pino.Logger;
49
- /**
50
- * Replaces the engine's logging sink with a host-owned logger. Existing
51
- * callers that never call `setLogger` continue to use the lazy pino logger.
52
- * The exported `logger` and `getLogger()` retain their complete pino contract;
53
- * injection changes only the engine's internal sink.
54
- */
55
- export declare function setLogger(nextLogger: McpLogger): void;
56
- export declare function getLogger(): pino.Logger;
57
- /** Package-internal facade that selects the host sink when one is configured. */
58
- export declare const engineLogger: McpLogger;
59
- export declare const logger: pino.Logger;
package/dist/logger.js DELETED
@@ -1,18 +0,0 @@
1
- import {
2
- createLogger,
3
- engineLogger,
4
- getLogger,
5
- logger,
6
- redactionPaths,
7
- setLogger
8
- } from "./chunk-k6fm3cmk.js";
9
- import"./chunk-3rr24vhh.js";
10
- import"./chunk-xcf742mf.js";
11
- export {
12
- createLogger,
13
- engineLogger,
14
- getLogger,
15
- logger,
16
- redactionPaths,
17
- setLogger
18
- };