@lostgradient/mcp 0.2.3 → 0.2.4

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.
@@ -1,4 +1,4 @@
1
1
  // src/version.ts
2
- var PACKAGE_VERSION = "0.2.3";
2
+ var PACKAGE_VERSION = "0.2.4";
3
3
 
4
4
  export { PACKAGE_VERSION };
@@ -236,6 +236,7 @@ function oauthBodyError(error) {
236
236
  }
237
237
 
238
238
  // src/oauth/network-identity.ts
239
+ import { isIP } from "node:net";
239
240
  function isSocketPeerTrusted(canonicalSocketAddress, configuration) {
240
241
  return configuration.trustedProxyCidrs.some((cidr) => isAddressInCidr(canonicalSocketAddress, cidr));
241
242
  }
@@ -256,6 +257,10 @@ function extractForwardedAddress(headers, configuration) {
256
257
  const value = headers.get("cf-connecting-ip");
257
258
  return value ? stripPort(value) : null;
258
259
  }
260
+ if (configuration.trustedProxyHeader === "fly-client-ip") {
261
+ const value = headers.get("fly-client-ip");
262
+ return value ? stripPort(value) : null;
263
+ }
259
264
  if (configuration.trustedProxyHeader === "x-forwarded-for") {
260
265
  const raw = headers.get("x-forwarded-for");
261
266
  if (!raw)
@@ -284,7 +289,7 @@ function resolveOauthNetworkIdentity(input) {
284
289
  return canonicalSocketAddress ?? "unknown-client";
285
290
  }
286
291
  const forwardedAddress = extractForwardedAddress(input.headers, input.configuration);
287
- if (!forwardedAddress) {
292
+ if (!forwardedAddress || isIP(forwardedAddress) === 0) {
288
293
  return canonicalSocketAddress;
289
294
  }
290
295
  return canonicalizeIpAddress(forwardedAddress);
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-taxyscge.js";
4
4
  import {
5
5
  PACKAGE_VERSION
6
- } from "./chunk-b3560w0q.js";
6
+ } from "./chunk-8rqwa4s9.js";
7
7
  import {
8
8
  hasRegisteredUiExtensionResource
9
9
  } from "./chunk-rxnyn7tf.js";
@@ -886,7 +886,11 @@ function parseHostnameFromOriginHeader(originHeader) {
886
886
  return null;
887
887
  }
888
888
  try {
889
- return new URL(originHeader).hostname;
889
+ const parsedOrigin = new URL(originHeader);
890
+ if (parsedOrigin.origin === "null" || parsedOrigin.origin !== originHeader) {
891
+ return null;
892
+ }
893
+ return parsedOrigin.hostname;
890
894
  } catch {
891
895
  return null;
892
896
  }
@@ -899,9 +903,12 @@ function hasValidLocalhostRebindingHeaders(headers) {
899
903
  if (requestHost && !isLocalhostHostname(requestHost)) {
900
904
  return false;
901
905
  }
902
- const requestOriginHost = parseHostnameFromOriginHeader(headers.get("origin"));
903
- if (requestOriginHost && !isLocalhostHostname(requestOriginHost)) {
904
- return false;
906
+ const requestOrigin = headers.get("origin");
907
+ if (requestOrigin !== null) {
908
+ const requestOriginHost = parseHostnameFromOriginHeader(requestOrigin);
909
+ if (!requestOriginHost || !isLocalhostHostname(requestOriginHost)) {
910
+ return false;
911
+ }
905
912
  }
906
913
  return true;
907
914
  }
@@ -6,12 +6,12 @@ import {
6
6
  createMcpServer,
7
7
  hasValidLocalhostRebindingHeaders,
8
8
  isLoopbackHostname
9
- } from "../chunk-drwp31va.js";
9
+ } from "../chunk-kerzwkj2.js";
10
10
  import"../chunk-taxyscge.js";
11
- import"../chunk-b3560w0q.js";
11
+ import"../chunk-8rqwa4s9.js";
12
12
  import {
13
13
  resolveOauthNetworkIdentity
14
- } from "../chunk-yf4nw40e.js";
14
+ } from "../chunk-en76akaq.js";
15
15
  import"../chunk-88nhf6xt.js";
16
16
  import"../chunk-3ek3knfm.js";
17
17
  import {
@@ -172,6 +172,8 @@ function readMcpRequestAuthExtra(authInfo) {
172
172
  }
173
173
 
174
174
  // src/http/responses.ts
175
+ class McpPayloadTooLargeError extends Error {
176
+ }
175
177
  function createMcpProtocolErrorResponse(input) {
176
178
  return new Response(JSON.stringify({
177
179
  error: input.error,
@@ -453,13 +455,21 @@ async function inspectListenRequest(request) {
453
455
  isListenRequest: true,
454
456
  requestedResourceUris: listens.flatMap(readRequestedResourceUris)
455
457
  };
456
- } catch {
458
+ } catch (error) {
459
+ if (error instanceof McpPayloadTooLargeError)
460
+ throw error;
457
461
  return none;
458
462
  }
459
463
  }
460
464
 
461
465
  // src/http/handler.ts
462
- class McpPayloadTooLargeError extends Error {
466
+ function payloadTooLargeResponse(error, protocolVersion) {
467
+ return createMcpProtocolErrorResponse({
468
+ status: 413,
469
+ error: "payload_too_large",
470
+ errorDescription: error.message,
471
+ headers: { "MCP-Protocol-Version": protocolVersion }
472
+ });
463
473
  }
464
474
  function boundRequestBody(request, maximumBytes) {
465
475
  const declaredLength = request.headers.get("content-length");
@@ -551,31 +561,32 @@ function createMcpServingHandler(input) {
551
561
  } catch (error) {
552
562
  if (!(error instanceof McpPayloadTooLargeError))
553
563
  throw error;
554
- return createMcpProtocolErrorResponse({
555
- status: 413,
556
- error: "payload_too_large",
557
- errorDescription: error.message,
558
- headers: { "MCP-Protocol-Version": configuration.protocolVersion }
559
- });
564
+ return payloadTooLargeResponse(error, configuration.protocolVersion);
560
565
  }
561
566
  const extra = readMcpRequestAuthExtra(authInfo);
562
567
  if (!extra)
563
568
  throw new Error("MCP request reached the handler without verified auth context.");
564
- const inspection = await inspectListenRequest(boundedRequest.clone());
565
- if (inspection.isListenRequest && !areResourceSubscriptionsAuthorized(inspection.requestedResourceUris, extra.scopes, registry)) {
566
- seams.recordEvent("insufficient_scope");
567
- return createMcpProtocolErrorResponse({
568
- status: 403,
569
- error: "forbidden",
570
- errorDescription: "The access token does not carry the scopes required for the requested resource subscriptions.",
571
- headers: {
572
- "MCP-Protocol-Version": configuration.protocolVersion,
573
- "WWW-Authenticate": `Bearer error="insufficient_scope", scope="${getSupportedScopes(registry).join(" ")}"`
574
- }
575
- });
569
+ try {
570
+ const inspection = await inspectListenRequest(boundedRequest.clone());
571
+ if (inspection.isListenRequest && !areResourceSubscriptionsAuthorized(inspection.requestedResourceUris, extra.scopes, registry)) {
572
+ seams.recordEvent("insufficient_scope");
573
+ return createMcpProtocolErrorResponse({
574
+ status: 403,
575
+ error: "forbidden",
576
+ errorDescription: "The access token does not carry the scopes required for the requested resource subscriptions.",
577
+ headers: {
578
+ "MCP-Protocol-Version": configuration.protocolVersion,
579
+ "WWW-Authenticate": `Bearer error="insufficient_scope", scope="${getSupportedScopes(registry).join(" ")}"`
580
+ }
581
+ });
582
+ }
583
+ const response = await cache.dispatch(extra.userId, (handler) => handler.fetch(boundedRequest, options));
584
+ return inspection.isListenRequest ? seams.markServerOnlyCloseableStream?.(response) ?? response : response;
585
+ } catch (error) {
586
+ if (!(error instanceof McpPayloadTooLargeError))
587
+ throw error;
588
+ return payloadTooLargeResponse(error, configuration.protocolVersion);
576
589
  }
577
- const response = await cache.dispatch(extra.userId, (handler) => handler.fetch(boundedRequest, options));
578
- return inspection.isListenRequest ? seams.markServerOnlyCloseableStream?.(response) ?? response : response;
579
590
  },
580
591
  publishUserResourceUpdate(userId, uri) {
581
592
  const existing = cache.peek(userId);
@@ -1,3 +1,5 @@
1
+ export declare class McpPayloadTooLargeError extends Error {
2
+ }
1
3
  export type McpProtocolErrorCode = 'bad_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'session_affinity_required' | 'unsupported_media_type' | 'not_acceptable' | 'rate_limited' | 'payload_too_large' | 'internal_error';
2
4
  export declare function createMcpProtocolErrorResponse(input: {
3
5
  status: number;
package/dist/index.js CHANGED
@@ -11,13 +11,13 @@ import {
11
11
  readRequestSender,
12
12
  readSessionIdentifier,
13
13
  stringifyUnknown
14
- } from "./chunk-drwp31va.js";
14
+ } from "./chunk-kerzwkj2.js";
15
15
  import {
16
16
  metricsCollector
17
17
  } from "./chunk-taxyscge.js";
18
18
  import {
19
19
  PACKAGE_VERSION
20
- } from "./chunk-b3560w0q.js";
20
+ } from "./chunk-8rqwa4s9.js";
21
21
  import {
22
22
  getSupportedScopes,
23
23
  hasRegisteredUiExtensionResource
@@ -20,7 +20,7 @@ export declare const canonicalizeIpAddress: typeof canonicalAddressUtilities.can
20
20
  export declare const expandIpv6Groups: typeof canonicalAddressUtilities.expandIpv6Groups;
21
21
  export declare const stripPort: typeof canonicalAddressUtilities.stripPort;
22
22
  export type { ClientIdMetadataDocument, ClientMetadataDocumentFetchDependencies, DnsLookupAllFunction, SafePublicHttpsFetchOptions, } from './client-metadata-documents.js';
23
- export type TrustedProxyHeader = 'x-forwarded-for' | 'forwarded' | 'cf-connecting-ip';
23
+ export type TrustedProxyHeader = 'x-forwarded-for' | 'forwarded' | 'cf-connecting-ip' | 'fly-client-ip';
24
24
  export type TrustedProxyConfiguration = {
25
25
  /** CIDR blocks whose immediate socket peer may supply the configured forwarding header. */
26
26
  trustedProxyCidrs: string[];
@@ -27,7 +27,7 @@ import {
27
27
  safeFetchPublicHttpsUrl,
28
28
  stripPort,
29
29
  withDeadline
30
- } from "../chunk-yf4nw40e.js";
30
+ } from "../chunk-en76akaq.js";
31
31
  import {
32
32
  constantTimeEquals
33
33
  } from "../chunk-88nhf6xt.js";
@@ -1,4 +1,4 @@
1
- export type TrustedProxyHeader = 'x-forwarded-for' | 'forwarded' | 'cf-connecting-ip';
1
+ export type TrustedProxyHeader = 'x-forwarded-for' | 'forwarded' | 'cf-connecting-ip' | 'fly-client-ip';
2
2
  export type TrustedProxyConfiguration = {
3
3
  /** CIDR blocks (IPv4 or IPv6) whose immediate socket peer is trusted to supply a forwarding header. Empty means nothing is trusted. */
4
4
  trustedProxyCidrs: string[];
@@ -2,6 +2,14 @@ import { sql, type SQL } from 'drizzle-orm';
2
2
  export type PostgresOAuthExecutor = {
3
3
  execute(query: SQL): Promise<unknown>;
4
4
  };
5
+ /**
6
+ * Database connection for the Postgres OAuth stores.
7
+ *
8
+ * Token revocation and rotation require interactive transactions and advisory
9
+ * transaction locks. Use a driver that supports `database.transaction(...)`,
10
+ * such as node-postgres or a Neon serverless WebSocket pool; neon-http is not
11
+ * sufficient because it does not support interactive transactions.
12
+ */
5
13
  export type PostgresOAuthDatabase = PostgresOAuthExecutor & {
6
14
  transaction<T>(callback: (transaction: PostgresOAuthExecutor) => Promise<T>): Promise<T>;
7
15
  };
@@ -8,4 +8,4 @@ export { PostgresClientStore } from './client-store.js';
8
8
  import type { OAuthStores } from '../stores.js';
9
9
  import type { PostgresOAuthDatabase } from './database.js';
10
10
  import type { PostgresOAuthSchema } from './schema.js';
11
- export declare function createPostgresOAuthStores(database: PostgresOAuthDatabase, schema: PostgresOAuthSchema): OAuthStores;
11
+ export declare function createPostgresOAuthStores<TSchema extends PostgresOAuthSchema>(database: PostgresOAuthDatabase, schema: TSchema): OAuthStores;
@@ -44,6 +44,7 @@ function createPostgresOAuthSchema({
44
44
  }, (table) => [
45
45
  index(`${prefix}_transactions_binding_idx`).on(table.consentBindingHash),
46
46
  index(`${prefix}_transactions_user_idx`).on(table.userId),
47
+ index(`${prefix}_transactions_client_idx`).on(table.clientId),
47
48
  index(`${prefix}_transactions_expires_idx`).on(table.expiresAt)
48
49
  ]);
49
50
  const codes = pgTable(`${prefix}_codes`, {
@@ -61,6 +62,7 @@ function createPostgresOAuthSchema({
61
62
  createdAt: timestamp("created_at", { withTimezone: true }).notNull()
62
63
  }, (table) => [
63
64
  index(`${prefix}_codes_user_idx`).on(table.userId),
65
+ index(`${prefix}_codes_client_idx`).on(table.clientId),
64
66
  index(`${prefix}_codes_expires_idx`).on(table.expiresAt)
65
67
  ]);
66
68
  const accessTokens = pgTable(`${prefix}_access_tokens`, {
@@ -74,6 +76,7 @@ function createPostgresOAuthSchema({
74
76
  createdAt: timestamp("created_at", { withTimezone: true }).notNull()
75
77
  }, (table) => [
76
78
  index(`${prefix}_access_user_idx`).on(table.userId),
79
+ index(`${prefix}_access_client_idx`).on(table.clientId),
77
80
  index(`${prefix}_access_expires_idx`).on(table.expiresAt)
78
81
  ]);
79
82
  const refreshTokens = pgTable(`${prefix}_refresh_tokens`, {
@@ -89,6 +92,7 @@ function createPostgresOAuthSchema({
89
92
  createdAt: timestamp("created_at", { withTimezone: true }).notNull()
90
93
  }, (table) => [
91
94
  index(`${prefix}_refresh_user_idx`).on(table.userId),
95
+ index(`${prefix}_refresh_client_idx`).on(table.clientId),
92
96
  index(`${prefix}_refresh_family_idx`).on(table.familyId),
93
97
  index(`${prefix}_refresh_access_idx`).on(table.accessTokenHash),
94
98
  index(`${prefix}_refresh_expires_idx`).on(table.expiresAt)
@@ -1,4 +1,4 @@
1
- import { type PgColumnBuilderBase } from 'drizzle-orm/pg-core';
1
+ import { type AnyPgColumn, type AnyPgTable, type PgColumnBuilderBase } from 'drizzle-orm/pg-core';
2
2
  export type PostgresOAuthSchemaOptions<TUserId extends PgColumnBuilderBase> = {
3
3
  prefix: string;
4
4
  userId: () => TUserId;
@@ -1452,4 +1452,25 @@ export declare function createPostgresOAuthSchema<TUserId extends PgColumnBuilde
1452
1452
  dialect: "pg";
1453
1453
  }>;
1454
1454
  };
1455
- export type PostgresOAuthSchema = ReturnType<typeof createPostgresOAuthSchema>;
1455
+ type OAuthColumnContract<TColumn extends AnyPgColumn> = TColumn extends AnyPgColumn<infer TConfiguration> ? AnyPgColumn<Omit<TConfiguration, 'tableName'>> : never;
1456
+ type OAuthColumnContracts<TColumns extends Record<string, AnyPgColumn>> = {
1457
+ [TKey in keyof TColumns]: OAuthColumnContract<TColumns[TKey]>;
1458
+ };
1459
+ type OAuthTable<TColumns extends Record<string, AnyPgColumn>> = AnyPgTable & TColumns;
1460
+ type OAuthTableColumns<TTable> = TTable extends AnyPgTable<{
1461
+ columns: infer TColumns extends Record<string, AnyPgColumn>;
1462
+ }> ? TColumns : never;
1463
+ type GeneralizeUserId<TColumns extends Record<string, AnyPgColumn>> = Omit<OAuthColumnContracts<TColumns>, 'userId'> & {
1464
+ userId: AnyPgColumn;
1465
+ };
1466
+ type FactoryPostgresOAuthSchema = ReturnType<typeof createPostgresOAuthSchema>;
1467
+ type FactoryOAuthTable<TKey extends keyof FactoryPostgresOAuthSchema> = OAuthTable<OAuthColumnContracts<OAuthTableColumns<FactoryPostgresOAuthSchema[TKey]>>>;
1468
+ type FactoryOAuthTableWithHostUserId<TKey extends keyof FactoryPostgresOAuthSchema> = OAuthTable<GeneralizeUserId<OAuthTableColumns<FactoryPostgresOAuthSchema[TKey]>>>;
1469
+ export type PostgresOAuthSchema = {
1470
+ clients: FactoryOAuthTable<'clients'>;
1471
+ transactions: FactoryOAuthTableWithHostUserId<'transactions'>;
1472
+ codes: FactoryOAuthTableWithHostUserId<'codes'>;
1473
+ accessTokens: FactoryOAuthTableWithHostUserId<'accessTokens'>;
1474
+ refreshTokens: FactoryOAuthTableWithHostUserId<'refreshTokens'>;
1475
+ };
1476
+ export {};
@@ -9,7 +9,7 @@ import {
9
9
  handleOauthRevokePost,
10
10
  handleOauthTokenPost,
11
11
  oauthCorsHeaders
12
- } from "./chunk-yf4nw40e.js";
12
+ } from "./chunk-en76akaq.js";
13
13
  import {
14
14
  isValidCidr
15
15
  } from "./chunk-88nhf6xt.js";
@@ -32,6 +32,7 @@ function setSvelteKitMountState(state) {
32
32
 
33
33
  // src/sveltekit-mount.ts
34
34
  var primedIdentities = new WeakMap;
35
+ var missingRateLimitStoresDiagnostic = "OAuth rate limits are configured without rate-limit stores; OAuth endpoint rate limiting and failed-authentication lockout are disabled.";
35
36
  var requiredOauthSeamFunctions = [
36
37
  "fetchClientIdMetadataDocument",
37
38
  "resolveIdentityBinding",
@@ -61,6 +62,15 @@ function assertOauthStore(stores, name, requiredFunctions) {
61
62
  assertOauthSeamObject(stores[name], `stores.${name}`);
62
63
  assertOauthSeamFunctions(stores[name], `stores.${name}`, requiredFunctions);
63
64
  }
65
+ function warnMissingRateLimitStores() {
66
+ process.stderr.write(`${JSON.stringify({
67
+ level: "warn",
68
+ operation: "sveltekit_mcp_mount",
69
+ protection: "oauth_rate_limits",
70
+ message: missingRateLimitStoresDiagnostic
71
+ })}
72
+ `);
73
+ }
64
74
  function assertRequiredOauthSeams(seams) {
65
75
  for (const name of requiredOauthSeamFunctions) {
66
76
  if (typeof seams[name] !== "function") {
@@ -154,7 +164,7 @@ function assertRequiredOauthSeams(seams) {
154
164
  throw new Error(`The SvelteKit MCP mount requires the OAuth host seam "configuration.trustedProxy.trustedProxyCidrs[${index}]".`);
155
165
  }
156
166
  }
157
- if (configuration.trustedProxy.trustedProxyHeader !== undefined && !["x-forwarded-for", "forwarded", "cf-connecting-ip"].includes(configuration.trustedProxy.trustedProxyHeader)) {
167
+ if (configuration.trustedProxy.trustedProxyHeader !== undefined && !["x-forwarded-for", "forwarded", "cf-connecting-ip", "fly-client-ip"].includes(configuration.trustedProxy.trustedProxyHeader)) {
158
168
  throw new Error('The SvelteKit MCP mount requires the OAuth host seam "configuration.trustedProxy.trustedProxyHeader".');
159
169
  }
160
170
  assertOauthSeamNumber(configuration.trustedProxy.trustedProxyHopCount, "configuration.trustedProxy.trustedProxyHopCount", -1);
@@ -183,7 +193,9 @@ function assertRequiredOauthSeams(seams) {
183
193
  if (typeof configuration.mcpUiExtension.enabled !== "boolean") {
184
194
  throw new Error('The SvelteKit MCP mount requires the OAuth host seam "configuration.mcpUiExtension.enabled".');
185
195
  }
186
- if (configuration.rateLimitStores !== undefined) {
196
+ if (configuration.rateLimitStores === undefined) {
197
+ warnMissingRateLimitStores();
198
+ } else {
187
199
  assertOauthSeamObject(configuration.rateLimitStores, "configuration.rateLimitStores");
188
200
  assertOauthSeamObject(configuration.rateLimitStores.slidingWindow, "configuration.rateLimitStores.slidingWindow");
189
201
  assertOauthSeamFunctions(configuration.rateLimitStores.slidingWindow, "configuration.rateLimitStores.slidingWindow", ["consume", "peek"]);
package/dist/version.d.ts CHANGED
@@ -20,4 +20,4 @@
20
20
  * thing making this approach safe — do not delete it to silence a release
21
21
  * bump; update this constant instead.
22
22
  */
23
- export declare const PACKAGE_VERSION = "0.2.3";
23
+ export declare const PACKAGE_VERSION = "0.2.4";
package/dist/version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PACKAGE_VERSION
3
- } from "./chunk-b3560w0q.js";
3
+ } from "./chunk-8rqwa4s9.js";
4
4
  export {
5
5
  PACKAGE_VERSION
6
6
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lostgradient/mcp",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "A Model Context Protocol server engine: registries, scope vocabularies, and an OAuth-ready request boundary.",
5
5
  "license": "MIT",
6
6
  "author": "Steve Kinney <hello@stevekinney.net>",