@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,870 +0,0 @@
1
- import {
2
- attachConcurrencySlotToResponseLifetime
3
- } from "../chunk-6ekjtvcq.js";
4
- import {
5
- areResourceSubscriptionsAuthorized,
6
- createMcpServer,
7
- hasValidLocalhostRebindingHeaders,
8
- isLoopbackHostname
9
- } from "../chunk-qxwd8est.js";
10
- import"../chunk-taxyscge.js";
11
- import"../chunk-wsnfttyg.js";
12
- import {
13
- resolveOauthNetworkIdentity
14
- } from "../chunk-en76akaq.js";
15
- import"../chunk-88nhf6xt.js";
16
- import"../chunk-3ek3knfm.js";
17
- import {
18
- getSupportedScopes
19
- } from "../chunk-rxnyn7tf.js";
20
- import"../chunk-k6fm3cmk.js";
21
- import"../chunk-3rr24vhh.js";
22
- import"../chunk-xcf742mf.js";
23
-
24
- // src/http/authorization-header.ts
25
- function parseAuthorizationHeader(header) {
26
- if (!header)
27
- return { scheme: undefined, credential: undefined };
28
- const match = /^(\S+)[ \t]+([\s\S]*)$/.exec(header);
29
- if (!match)
30
- return { scheme: undefined, credential: undefined };
31
- return { scheme: match[1], credential: match[2] };
32
- }
33
-
34
- // src/http/grant-revocation-channel.ts
35
- var grantRevocationChannel = "mcp:control:grant-revocations";
36
- var initialRetryDelayMilliseconds = 1000;
37
- var maximumRetryDelayMilliseconds = 30000;
38
- function readUserId(message) {
39
- try {
40
- const parsed = JSON.parse(message);
41
- if (typeof parsed !== "object" || parsed === null)
42
- return;
43
- const userId = parsed.userId;
44
- return typeof userId === "string" && userId.length > 0 ? userId : undefined;
45
- } catch {
46
- return;
47
- }
48
- }
49
-
50
- class GrantRevocationChannel {
51
- closeLocalUser;
52
- messaging;
53
- onError;
54
- retryConfiguration;
55
- unsubscribe;
56
- startup;
57
- closeRequested = false;
58
- finishRetryDelay;
59
- retryDelayMilliseconds;
60
- constructor(closeLocalUser, messaging, onError = () => {}, retryConfiguration = {
61
- initialDelayMilliseconds: initialRetryDelayMilliseconds,
62
- maximumDelayMilliseconds: maximumRetryDelayMilliseconds
63
- }) {
64
- this.closeLocalUser = closeLocalUser;
65
- this.messaging = messaging;
66
- this.onError = onError;
67
- this.retryConfiguration = retryConfiguration;
68
- this.retryDelayMilliseconds = retryConfiguration.initialDelayMilliseconds;
69
- }
70
- async start() {
71
- if (!this.messaging || this.unsubscribe || this.closeRequested)
72
- return;
73
- if (!this.startup) {
74
- const startup = this.subscribe();
75
- this.startup = startup;
76
- startup.finally(() => {
77
- if (this.startup === startup)
78
- this.startup = undefined;
79
- });
80
- }
81
- await this.startup;
82
- }
83
- async publish(userId) {
84
- if (!this.messaging) {
85
- this.runLocalCloser(userId);
86
- return;
87
- }
88
- try {
89
- await this.messaging.publish(grantRevocationChannel, JSON.stringify({ userId }));
90
- } catch (error) {
91
- this.onError(error, userId);
92
- }
93
- this.runLocalCloser(userId);
94
- }
95
- async close() {
96
- this.closeRequested = true;
97
- this.finishRetryDelay?.();
98
- await this.startup;
99
- const unsubscribe = this.unsubscribe;
100
- if (!unsubscribe)
101
- return;
102
- try {
103
- await unsubscribe();
104
- if (this.unsubscribe === unsubscribe)
105
- this.unsubscribe = undefined;
106
- } catch (error) {
107
- this.onError(error);
108
- }
109
- }
110
- async subscribe() {
111
- while (!this.closeRequested && !this.unsubscribe) {
112
- try {
113
- this.unsubscribe = await this.messaging?.subscribe(grantRevocationChannel, (message) => {
114
- const userId = readUserId(message);
115
- if (userId)
116
- this.runLocalCloser(userId);
117
- });
118
- this.retryDelayMilliseconds = this.retryConfiguration.initialDelayMilliseconds;
119
- } catch (error) {
120
- this.onError(error);
121
- if (!this.closeRequested)
122
- await this.waitBeforeRetry();
123
- }
124
- }
125
- }
126
- async waitBeforeRetry() {
127
- const delayMilliseconds = this.retryDelayMilliseconds;
128
- this.retryDelayMilliseconds = Math.min(delayMilliseconds * 2, this.retryConfiguration.maximumDelayMilliseconds);
129
- await new Promise((resolve) => {
130
- const finish = () => {
131
- clearTimeout(timer);
132
- if (this.finishRetryDelay === finish)
133
- this.finishRetryDelay = undefined;
134
- resolve();
135
- };
136
- this.finishRetryDelay = finish;
137
- const timer = setTimeout(finish, delayMilliseconds);
138
- timer.unref?.();
139
- });
140
- }
141
- runLocalCloser(userId) {
142
- Promise.resolve(this.closeLocalUser(userId)).catch((error) => {
143
- this.onError(error, userId);
144
- });
145
- }
146
- }
147
-
148
- // src/http/handler.ts
149
- import { createMcpHandler } from "@modelcontextprotocol/server";
150
-
151
- // src/http/request-context.ts
152
- function buildMcpAuthInfo(input) {
153
- return {
154
- token: input.accessToken,
155
- clientId: input.extra.oauthClientId,
156
- scopes: input.extra.scopes,
157
- expiresAt: Math.floor(input.expiresAt.getTime() / 1000),
158
- resource: new URL(input.extra.resource),
159
- extra: input.extra
160
- };
161
- }
162
- function readMcpRequestAuthExtra(authInfo) {
163
- const extra = authInfo?.extra;
164
- if (!extra || typeof extra !== "object")
165
- return;
166
- const candidate = extra;
167
- if (typeof candidate.userId !== "string")
168
- return;
169
- if (typeof candidate.userProfile?.id !== "string")
170
- return;
171
- return candidate;
172
- }
173
-
174
- // src/http/responses.ts
175
- class McpPayloadTooLargeError extends Error {
176
- }
177
- function createMcpProtocolErrorResponse(input) {
178
- return new Response(JSON.stringify({
179
- error: input.error,
180
- error_description: input.errorDescription,
181
- status: input.status,
182
- ...input.data ? { data: input.data } : {}
183
- }), {
184
- status: input.status,
185
- headers: { "Content-Type": "application/json", ...input.headers ?? {} }
186
- });
187
- }
188
- function createMcpCorsHeaders(request, allowedOrigins) {
189
- const origin = request.headers.get("origin");
190
- if (!origin || origin === "null" || !allowedOrigins.has(origin))
191
- return {};
192
- return {
193
- "Access-Control-Allow-Origin": origin,
194
- Vary: "Origin",
195
- "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
196
- "Access-Control-Allow-Headers": "Content-Type, Authorization, mcp-session-id, mcp-protocol-version, Last-Event-ID",
197
- "Access-Control-Expose-Headers": "mcp-session-id, mcp-protocol-version"
198
- };
199
- }
200
- function isMcpOriginAllowed(request, allowedOrigins) {
201
- const origin = request.headers.get("origin");
202
- return !origin || origin !== "null" && allowedOrigins.has(origin);
203
- }
204
- function createRateLimitedResponse(retryAfterSeconds, headers) {
205
- return createMcpProtocolErrorResponse({
206
- status: 429,
207
- error: "rate_limited",
208
- errorDescription: "Too many requests. Try again later.",
209
- headers: { ...headers, "Retry-After": String(retryAfterSeconds) }
210
- });
211
- }
212
-
213
- // src/http/user-handler-cache.ts
214
- class McpUserHandlerCache {
215
- createEntry;
216
- now;
217
- onError;
218
- entries = new Map;
219
- sweepTimer;
220
- constructor(createEntry, now = Date.now, onError = () => {}) {
221
- this.createEntry = createEntry;
222
- this.now = now;
223
- this.onError = onError;
224
- }
225
- get size() {
226
- return this.entries.size;
227
- }
228
- peek(userId) {
229
- return this.entries.get(userId);
230
- }
231
- get(userId) {
232
- let entry = this.entries.get(userId);
233
- if (!entry) {
234
- entry = {
235
- ...this.createEntry(userId),
236
- lastAccessedAt: this.now(),
237
- activeRequestCount: 0
238
- };
239
- this.entries.set(userId, entry);
240
- return entry;
241
- }
242
- entry.lastAccessedAt = this.now();
243
- return entry;
244
- }
245
- async dispatch(userId, operation) {
246
- const entry = this.get(userId);
247
- entry.activeRequestCount += 1;
248
- try {
249
- return await operation(entry.handler);
250
- } finally {
251
- entry.activeRequestCount -= 1;
252
- entry.lastAccessedAt = this.now();
253
- }
254
- }
255
- evictIdle(idleMilliseconds) {
256
- const cutoff = this.now() - idleMilliseconds;
257
- const evictedUserIds = [];
258
- for (const [userId, entry] of this.entries) {
259
- if (entry.bus.listenerCount === 0 && entry.activeRequestCount === 0 && entry.lastAccessedAt <= cutoff) {
260
- evictedUserIds.push(userId);
261
- }
262
- }
263
- for (const userId of evictedUserIds) {
264
- const entry = this.entries.get(userId);
265
- this.entries.delete(userId);
266
- if (entry) {
267
- entry.handler.close().catch((error) => {
268
- this.onError({ error, userId, operation: "evict" });
269
- });
270
- }
271
- }
272
- return evictedUserIds;
273
- }
274
- async closeUser(userId) {
275
- const entry = this.entries.get(userId);
276
- if (!entry)
277
- return false;
278
- this.entries.delete(userId);
279
- await entry.handler.close().catch((error) => {
280
- this.onError({ error, userId, operation: "revoke" });
281
- });
282
- return true;
283
- }
284
- startSweep(intervalMilliseconds, idleMilliseconds) {
285
- if (this.sweepTimer)
286
- clearInterval(this.sweepTimer);
287
- this.sweepTimer = setInterval(() => this.evictIdle(idleMilliseconds), intervalMilliseconds);
288
- this.sweepTimer.unref?.();
289
- }
290
- async closeAll() {
291
- if (this.sweepTimer) {
292
- clearInterval(this.sweepTimer);
293
- this.sweepTimer = undefined;
294
- }
295
- const closings = [...this.entries.entries()].map(([userId, entry]) => entry.handler.close().catch((error) => {
296
- this.onError({ error, userId, operation: "shutdown" });
297
- }));
298
- this.entries.clear();
299
- await Promise.all(closings);
300
- }
301
- }
302
-
303
- // src/http/user-server-event-bus.ts
304
- import { InMemoryServerEventBus } from "@modelcontextprotocol/server";
305
- var initialRetryDelayMilliseconds2 = 1000;
306
- var maximumRetryDelayMilliseconds2 = 30000;
307
- function channelForUser(userId) {
308
- return `mcp:events:user:${userId}`;
309
- }
310
-
311
- class ServerEventDecodeError extends Error {
312
- constructor() {
313
- super("Invalid MCP server event message.");
314
- this.name = "ServerEventDecodeError";
315
- }
316
- }
317
- function isObjectRecord(value) {
318
- return typeof value === "object" && value !== null && !Array.isArray(value);
319
- }
320
- function decodeServerEvent(value) {
321
- if (!isObjectRecord(value))
322
- throw new ServerEventDecodeError;
323
- switch (value.kind) {
324
- case "tools_list_changed":
325
- case "prompts_list_changed":
326
- case "resources_list_changed":
327
- return { kind: value.kind };
328
- case "resource_updated":
329
- if (typeof value.uri !== "string")
330
- throw new ServerEventDecodeError;
331
- return { kind: value.kind, uri: value.uri };
332
- default:
333
- throw new ServerEventDecodeError;
334
- }
335
- }
336
- function parseServerEventMessage(message) {
337
- try {
338
- return JSON.parse(message);
339
- } catch {
340
- throw new ServerEventDecodeError;
341
- }
342
- }
343
- function readServerEvent(message) {
344
- const parsed = parseServerEventMessage(message);
345
- if (!isObjectRecord(parsed))
346
- throw new ServerEventDecodeError;
347
- if ("event" in parsed) {
348
- if (typeof parsed.sourceId !== "string")
349
- throw new ServerEventDecodeError;
350
- return {
351
- event: decodeServerEvent(parsed.event),
352
- sourceId: parsed.sourceId
353
- };
354
- }
355
- return {
356
- event: decodeServerEvent(parsed),
357
- sourceId: typeof parsed.sourceId === "string" ? parsed.sourceId : undefined
358
- };
359
- }
360
-
361
- class CrossInstanceUserServerEventBus {
362
- userId;
363
- messaging;
364
- onError;
365
- listeners = new Set;
366
- unsubscribeFromMessaging;
367
- transitionQueue = Promise.resolve();
368
- retryTimer;
369
- retryDelayMilliseconds = initialRetryDelayMilliseconds2;
370
- sourceId = crypto.randomUUID();
371
- constructor(userId, messaging, onError = () => {}) {
372
- this.userId = userId;
373
- this.messaging = messaging;
374
- this.onError = onError;
375
- }
376
- get listenerCount() {
377
- return this.listeners.size;
378
- }
379
- publish(event) {
380
- let message;
381
- try {
382
- message = JSON.stringify({ ...event, sourceId: this.sourceId });
383
- } catch (error) {
384
- this.onError({ error, userId: this.userId, operation: "publish" });
385
- return;
386
- }
387
- for (const listener of this.listeners)
388
- listener(event);
389
- this.messaging.publish(channelForUser(this.userId), message).catch((error) => this.onError({ error, userId: this.userId, operation: "publish" }));
390
- }
391
- subscribe(listener) {
392
- this.listeners.add(listener);
393
- this.enqueueTransition();
394
- let live = true;
395
- return () => {
396
- if (!live)
397
- return;
398
- live = false;
399
- this.listeners.delete(listener);
400
- this.enqueueTransition();
401
- };
402
- }
403
- async whenSubscribed() {
404
- await this.transitionQueue;
405
- }
406
- enqueueTransition() {
407
- const transition = this.transitionQueue.then(() => this.reconcileSubscription(), () => this.reconcileSubscription());
408
- this.transitionQueue = transition;
409
- return transition;
410
- }
411
- scheduleRetry() {
412
- if (this.retryTimer)
413
- return;
414
- const delay = this.retryDelayMilliseconds;
415
- this.retryDelayMilliseconds = Math.min(delay * 2, maximumRetryDelayMilliseconds2);
416
- this.retryTimer = setTimeout(() => {
417
- this.retryTimer = undefined;
418
- const subscriptionMatchesDemand = this.listeners.size === 0 && !this.unsubscribeFromMessaging || this.listeners.size > 0 && Boolean(this.unsubscribeFromMessaging);
419
- if (subscriptionMatchesDemand) {
420
- this.retryDelayMilliseconds = initialRetryDelayMilliseconds2;
421
- return;
422
- }
423
- this.enqueueTransition();
424
- }, delay);
425
- this.retryTimer.unref?.();
426
- }
427
- async reconcileSubscription() {
428
- if (this.listeners.size > 0 && !this.unsubscribeFromMessaging) {
429
- try {
430
- this.unsubscribeFromMessaging = await this.messaging.subscribe(channelForUser(this.userId), (message) => {
431
- try {
432
- const received = readServerEvent(message);
433
- if (received && received.sourceId !== this.sourceId) {
434
- for (const listener of this.listeners)
435
- listener(received.event);
436
- }
437
- } catch (error) {
438
- this.onError({ error, userId: this.userId, operation: "deserialize" });
439
- }
440
- });
441
- this.retryDelayMilliseconds = initialRetryDelayMilliseconds2;
442
- } catch (error) {
443
- this.onError({ error, userId: this.userId, operation: "subscribe" });
444
- this.scheduleRetry();
445
- }
446
- return;
447
- }
448
- if (this.listeners.size === 0 && this.unsubscribeFromMessaging) {
449
- const unsubscribe = this.unsubscribeFromMessaging;
450
- try {
451
- await unsubscribe();
452
- if (this.unsubscribeFromMessaging === unsubscribe) {
453
- this.unsubscribeFromMessaging = undefined;
454
- }
455
- this.retryDelayMilliseconds = initialRetryDelayMilliseconds2;
456
- } catch (error) {
457
- this.onError({ error, userId: this.userId, operation: "unsubscribe" });
458
- this.scheduleRetry();
459
- }
460
- }
461
- }
462
- }
463
- function createUserServerEventBus(input) {
464
- return input.messaging ? new CrossInstanceUserServerEventBus(input.userId, input.messaging, input.onError) : new InMemoryServerEventBus;
465
- }
466
-
467
- // src/http/listen-inspection.ts
468
- function readRequestedResourceUris(message) {
469
- const parameters = message.params;
470
- if (typeof parameters !== "object" || parameters === null)
471
- return [];
472
- const notifications = parameters.notifications;
473
- if (typeof notifications !== "object" || notifications === null)
474
- return [];
475
- const uris = notifications.resourceSubscriptions;
476
- return Array.isArray(uris) ? uris.filter((uri) => typeof uri === "string") : [];
477
- }
478
- async function inspectListenRequest(request) {
479
- const none = { isListenRequest: false, requestedResourceUris: [] };
480
- if (!request.body)
481
- return none;
482
- try {
483
- const parsed = await request.json();
484
- const messages = Array.isArray(parsed) ? parsed : [parsed];
485
- const listens = messages.filter((message) => typeof message === "object" && message !== null && message.method === "subscriptions/listen");
486
- return listens.length === 0 ? none : {
487
- isListenRequest: true,
488
- requestedResourceUris: listens.flatMap(readRequestedResourceUris)
489
- };
490
- } catch (error) {
491
- if (error instanceof McpPayloadTooLargeError)
492
- throw error;
493
- return none;
494
- }
495
- }
496
-
497
- // src/http/handler.ts
498
- function payloadTooLargeResponse(error, protocolVersion) {
499
- return createMcpProtocolErrorResponse({
500
- status: 413,
501
- error: "payload_too_large",
502
- errorDescription: error.message,
503
- headers: { "MCP-Protocol-Version": protocolVersion }
504
- });
505
- }
506
- function boundRequestBody(request, maximumBytes) {
507
- const declaredLength = request.headers.get("content-length");
508
- if (declaredLength && (!/^\d+$/.test(declaredLength) || Number(declaredLength) > maximumBytes)) {
509
- throw new McpPayloadTooLargeError(`Request body exceeds the ${maximumBytes}-byte limit.`);
510
- }
511
- if (!request.body)
512
- return request;
513
- const reader = request.body.getReader();
514
- let receivedBytes = 0;
515
- const body = new ReadableStream({
516
- async start(controller) {
517
- try {
518
- while (true) {
519
- const { done, value } = await reader.read();
520
- if (done) {
521
- controller.close();
522
- return;
523
- }
524
- receivedBytes += value.byteLength;
525
- if (receivedBytes > maximumBytes) {
526
- const error = new McpPayloadTooLargeError(`Request body exceeded the ${maximumBytes}-byte limit while streaming.`);
527
- controller.error(error);
528
- await reader.cancel(error).catch(() => {});
529
- return;
530
- }
531
- controller.enqueue(value);
532
- }
533
- } catch (error) {
534
- controller.error(error);
535
- }
536
- },
537
- cancel: (reason) => reader.cancel(reason)
538
- });
539
- return new Request(request.url, {
540
- method: request.method,
541
- headers: request.headers,
542
- body,
543
- duplex: "half",
544
- signal: request.signal
545
- });
546
- }
547
- function createMcpServingHandler(input) {
548
- const { registry, configuration, seams } = input;
549
- if (!seams.messaging)
550
- seams.reportDegradation("single_instance_messaging_fallback");
551
- function createEntry(userId) {
552
- const bus = createUserServerEventBus({
553
- userId,
554
- messaging: seams.messaging,
555
- onError: ({ error, operation }) => seams.onError(error, operation, userId)
556
- });
557
- const handler = createMcpHandler(async (context) => {
558
- const extra = readMcpRequestAuthExtra(context.authInfo);
559
- if (!extra || extra.userId !== userId) {
560
- throw new Error("MCP request authenticated user does not match its routed handler.");
561
- }
562
- return createMcpServer({
563
- userId,
564
- user: extra.userProfile,
565
- requestId: extra.requestId,
566
- enableUiExtension: configuration.enableUiExtension,
567
- enableConformanceMode: configuration.enableConformanceMode,
568
- era: context.era,
569
- publishResourceUpdate: async (uri) => handler.notify.resourceUpdated(uri),
570
- scopes: extra.scopes
571
- }, registry);
572
- }, {
573
- legacy: "stateless",
574
- bus,
575
- maxSubscriptions: configuration.maximumSubscriptionsPerUser,
576
- onerror: (error) => {
577
- seams.recordEvent("transport_failure");
578
- seams.onError(error, "transport", userId);
579
- }
580
- });
581
- return { handler, bus };
582
- }
583
- const cache = new McpUserHandlerCache(createEntry, Date.now, ({ error, operation, userId }) => seams.onError(error, operation, userId));
584
- cache.startSweep(configuration.userHandlerSweepIntervalMilliseconds, configuration.userHandlerIdleMilliseconds);
585
- const revocations = new GrantRevocationChannel((userId) => cache.closeUser(userId), seams.messaging, (error, userId) => seams.onError(error, "grant_revocation", userId));
586
- return {
587
- start: () => revocations.start(),
588
- async handle(request, authInfo) {
589
- const options = { authInfo };
590
- let boundedRequest;
591
- try {
592
- boundedRequest = boundRequestBody(request, configuration.maximumRequestBodyBytes);
593
- } catch (error) {
594
- if (!(error instanceof McpPayloadTooLargeError))
595
- throw error;
596
- return payloadTooLargeResponse(error, configuration.protocolVersion);
597
- }
598
- const extra = readMcpRequestAuthExtra(authInfo);
599
- if (!extra)
600
- throw new Error("MCP request reached the handler without verified auth context.");
601
- try {
602
- const inspection = await inspectListenRequest(boundedRequest.clone());
603
- if (inspection.isListenRequest && !areResourceSubscriptionsAuthorized(inspection.requestedResourceUris, extra.scopes, registry)) {
604
- seams.recordEvent("insufficient_scope");
605
- return createMcpProtocolErrorResponse({
606
- status: 403,
607
- error: "forbidden",
608
- errorDescription: "The access token does not carry the scopes required for the requested resource subscriptions.",
609
- headers: {
610
- "MCP-Protocol-Version": configuration.protocolVersion,
611
- "WWW-Authenticate": `Bearer error="insufficient_scope", scope="${getSupportedScopes(registry).join(" ")}"`
612
- }
613
- });
614
- }
615
- const response = await cache.dispatch(extra.userId, (handler) => handler.fetch(boundedRequest, options));
616
- return inspection.isListenRequest ? seams.markServerOnlyCloseableStream?.(response) ?? response : response;
617
- } catch (error) {
618
- if (!(error instanceof McpPayloadTooLargeError))
619
- throw error;
620
- return payloadTooLargeResponse(error, configuration.protocolVersion);
621
- }
622
- },
623
- publishUserResourceUpdate(userId, uri) {
624
- const existing = cache.peek(userId);
625
- if (existing) {
626
- existing.handler.notify.resourceUpdated(uri);
627
- return;
628
- }
629
- if (seams.messaging) {
630
- createUserServerEventBus({ userId, messaging: seams.messaging }).publish({
631
- kind: "resource_updated",
632
- uri
633
- });
634
- }
635
- },
636
- publishGrantRevocation: (userId) => revocations.publish(userId),
637
- closeUser: (userId) => cache.closeUser(userId),
638
- async shutdown() {
639
- await revocations.close();
640
- await cache.closeAll();
641
- }
642
- };
643
- }
644
-
645
- // src/http/authenticate.ts
646
- function bearerChallenge(configuration, errorCode) {
647
- const resourceMetadataUrl = new URL("/.well-known/oauth-protected-resource/mcp", configuration.resource).href;
648
- const parts = [
649
- ...errorCode ? [`error="${errorCode}"`] : [],
650
- `resource_metadata="${resourceMetadataUrl}"`,
651
- `scope="${configuration.supportedScopes.join(" ")}"`
652
- ];
653
- return `Bearer ${parts.join(", ")}`;
654
- }
655
- function invalidTokenResponse(configuration, corsHeaders) {
656
- return createMcpProtocolErrorResponse({
657
- status: 401,
658
- error: "unauthorized",
659
- errorDescription: "Invalid or expired token.",
660
- headers: {
661
- ...corsHeaders,
662
- "MCP-Protocol-Version": configuration.protocolVersion,
663
- "WWW-Authenticate": bearerChallenge(configuration, "invalid_token")
664
- }
665
- });
666
- }
667
- async function authenticateMcpUser(input) {
668
- const { context, configuration, seams } = input;
669
- const corsHeaders = createMcpCorsHeaders(context.request, configuration.allowedOrigins);
670
- const protocolHeaders = {
671
- ...corsHeaders,
672
- "MCP-Protocol-Version": configuration.protocolVersion
673
- };
674
- if (configuration.dnsRebindingProtection && isLoopbackHostname(context.requestUrl.hostname) && !hasValidLocalhostRebindingHeaders(context.request.headers)) {
675
- return createMcpProtocolErrorResponse({
676
- status: 403,
677
- error: "forbidden",
678
- errorDescription: "Request rejected by localhost DNS rebinding protection.",
679
- headers: protocolHeaders
680
- });
681
- }
682
- if (!isMcpOriginAllowed(context.request, configuration.allowedOrigins)) {
683
- return createMcpProtocolErrorResponse({
684
- status: 403,
685
- error: "forbidden",
686
- errorDescription: "Origin is not allowed for MCP requests.",
687
- headers: protocolHeaders
688
- });
689
- }
690
- if (context.request.method === "OPTIONS") {
691
- return new Response(null, { status: 204, headers: protocolHeaders });
692
- }
693
- const networkIdentity = context.socketAddress ?? "unknown";
694
- const failedAuthenticationCount = await seams.rateLimiter.peek("failed_authentication", networkIdentity);
695
- if (failedAuthenticationCount >= configuration.maximumFailedAuthenticationAttempts) {
696
- return createMcpProtocolErrorResponse({
697
- status: 429,
698
- error: "rate_limited",
699
- errorDescription: "Too many failed authentication attempts. Try again later.",
700
- headers: protocolHeaders
701
- });
702
- }
703
- const { scheme, credential } = parseAuthorizationHeader(context.request.headers.get("authorization"));
704
- if (scheme?.toLowerCase() !== "bearer") {
705
- return createMcpProtocolErrorResponse({
706
- status: 401,
707
- error: "unauthorized",
708
- errorDescription: "Missing or invalid Authorization header.",
709
- headers: {
710
- ...protocolHeaders,
711
- "WWW-Authenticate": bearerChallenge(configuration)
712
- }
713
- });
714
- }
715
- const bearerToken = credential ?? "";
716
- if (bearerToken.length === 0 || bearerToken.length > configuration.maximumBearerTokenLength) {
717
- return createMcpProtocolErrorResponse({
718
- status: 401,
719
- error: "unauthorized",
720
- errorDescription: "Malformed bearer token.",
721
- headers: {
722
- ...protocolHeaders,
723
- "WWW-Authenticate": bearerChallenge(configuration, "invalid_token")
724
- }
725
- });
726
- }
727
- const tokenHash = seams.hashCredential(bearerToken);
728
- const combinedAuthentication = seams.findTokenAndUserProfileByHash ? await seams.findTokenAndUserProfileByHash(tokenHash) : undefined;
729
- const token = seams.findTokenAndUserProfileByHash ? combinedAuthentication?.token ?? null : await seams.tokens.findByHash(tokenHash);
730
- const now = new Date;
731
- if (!token || token.revokedAt || token.expiresAt <= now) {
732
- await seams.rateLimiter.consume("failed_authentication", networkIdentity);
733
- seams.recordEvent("expired_or_invalid_token", context.requestId);
734
- return invalidTokenResponse(configuration, corsHeaders);
735
- }
736
- if (token.resource !== configuration.resource.href) {
737
- await seams.rateLimiter.consume("failed_authentication", networkIdentity);
738
- seams.recordEvent("invalid_resource", context.requestId);
739
- return invalidTokenResponse(configuration, corsHeaders);
740
- }
741
- const profile = seams.findTokenAndUserProfileByHash ? combinedAuthentication?.profile : await seams.resolveUserProfile(token.userId);
742
- if (!profile) {
743
- await seams.rateLimiter.consume("failed_authentication", networkIdentity);
744
- seams.recordEvent("expired_or_invalid_token", context.requestId);
745
- return invalidTokenResponse(configuration, corsHeaders);
746
- }
747
- seams.recordEvent("success", context.requestId);
748
- return buildMcpAuthInfo({
749
- accessToken: bearerToken,
750
- expiresAt: token.expiresAt,
751
- extra: {
752
- userId: token.userId,
753
- userProfile: profile,
754
- oauthClientId: token.clientId,
755
- scopes: (token.scope ?? "").split(" ").filter(Boolean),
756
- resource: token.resource,
757
- networkIdentity,
758
- requestId: context.requestId
759
- }
760
- });
761
- }
762
-
763
- // src/http/serving-layer.ts
764
- function createMcpHttpServingLayer(input) {
765
- return {
766
- async handle(context) {
767
- const networkIdentity = resolveOauthNetworkIdentity({
768
- socketAddress: context.socketAddress,
769
- headers: context.request.headers,
770
- configuration: input.authenticationConfiguration.trustedProxy
771
- });
772
- const resolvedContext = { ...context, socketAddress: networkIdentity };
773
- const corsHeaders = createMcpCorsHeaders(context.request, input.authenticationConfiguration.allowedOrigins);
774
- const protocolHeaders = {
775
- ...corsHeaders,
776
- "MCP-Protocol-Version": input.authenticationConfiguration.protocolVersion
777
- };
778
- if (context.request.method !== "OPTIONS") {
779
- const networkAdmission = await input.rateLimiter.consume("mcp_network", networkIdentity);
780
- if (!networkAdmission.allowed) {
781
- return createRateLimitedResponse(networkAdmission.retryAfterSeconds, protocolHeaders);
782
- }
783
- }
784
- const authentication = await authenticateMcpUser({
785
- context: resolvedContext,
786
- configuration: input.authenticationConfiguration,
787
- seams: input.authenticationSeams
788
- });
789
- if (authentication instanceof Response)
790
- return authentication;
791
- const extra = readMcpRequestAuthExtra(authentication);
792
- if (!extra) {
793
- return createMcpProtocolErrorResponse({
794
- status: 401,
795
- error: "unauthorized",
796
- errorDescription: "Invalid or expired token.",
797
- headers: protocolHeaders
798
- });
799
- }
800
- const userAdmission = await input.rateLimiter.consume("mcp_user", extra.userId);
801
- if (!userAdmission.allowed) {
802
- return createRateLimitedResponse(userAdmission.retryAfterSeconds, protocolHeaders);
803
- }
804
- const concurrencySlot = await input.concurrencyLimiter.acquire(`rate_limit:mcp_concurrent:${extra.userId}`);
805
- if (!concurrencySlot.allowed) {
806
- return createMcpProtocolErrorResponse({
807
- status: 429,
808
- error: "rate_limited",
809
- errorDescription: "Too many concurrent MCP requests for this user.",
810
- headers: protocolHeaders
811
- });
812
- }
813
- try {
814
- const listenProbe = input.markServerOnlyCloseableStream ? context.request.clone() : undefined;
815
- const response = await input.handler.handle(context.request, authentication);
816
- const headers = new Headers(response.headers);
817
- for (const [name, value] of Object.entries(corsHeaders))
818
- headers.set(name, value);
819
- const responseWithCorsHeaders = new Response(response.body, {
820
- status: response.status,
821
- statusText: response.statusText,
822
- headers
823
- });
824
- const settled = attachConcurrencySlotToResponseLifetime(responseWithCorsHeaders, concurrencySlot);
825
- if (listenProbe) {
826
- const isEventStream = (settled.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream");
827
- if (isEventStream) {
828
- if ((await inspectListenRequest(listenProbe)).isListenRequest) {
829
- return input.markServerOnlyCloseableStream?.(settled) ?? settled;
830
- }
831
- } else {
832
- listenProbe.body?.cancel().catch(() => {});
833
- }
834
- }
835
- return settled;
836
- } catch (error) {
837
- await concurrencySlot.release();
838
- throw error;
839
- }
840
- }
841
- };
842
- }
843
-
844
- // src/http/index.ts
845
- var parseAuthorizationHeader2 = parseAuthorizationHeader;
846
- var GrantRevocationChannel2 = GrantRevocationChannel;
847
- var createMcpServingHandler2 = createMcpServingHandler;
848
- var buildMcpAuthInfo2 = buildMcpAuthInfo;
849
- var readMcpRequestAuthExtra2 = readMcpRequestAuthExtra;
850
- var createMcpCorsHeaders2 = createMcpCorsHeaders;
851
- var createMcpProtocolErrorResponse2 = createMcpProtocolErrorResponse;
852
- var isMcpOriginAllowed2 = isMcpOriginAllowed;
853
- var createMcpHttpServingLayer2 = createMcpHttpServingLayer;
854
- var McpUserHandlerCache2 = McpUserHandlerCache;
855
- var createUserServerEventBus2 = createUserServerEventBus;
856
- var CrossInstanceUserServerEventBus2 = CrossInstanceUserServerEventBus;
857
- export {
858
- CrossInstanceUserServerEventBus2 as CrossInstanceUserServerEventBus,
859
- GrantRevocationChannel2 as GrantRevocationChannel,
860
- McpUserHandlerCache2 as McpUserHandlerCache,
861
- buildMcpAuthInfo2 as buildMcpAuthInfo,
862
- createMcpCorsHeaders2 as createMcpCorsHeaders,
863
- createMcpHttpServingLayer2 as createMcpHttpServingLayer,
864
- createMcpProtocolErrorResponse2 as createMcpProtocolErrorResponse,
865
- createMcpServingHandler2 as createMcpServingHandler,
866
- createUserServerEventBus2 as createUserServerEventBus,
867
- isMcpOriginAllowed2 as isMcpOriginAllowed,
868
- parseAuthorizationHeader2 as parseAuthorizationHeader,
869
- readMcpRequestAuthExtra2 as readMcpRequestAuthExtra
870
- };