@lostgradient/mcp 0.2.1 → 0.2.3

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.1";
2
+ var PACKAGE_VERSION = "0.2.3";
3
3
 
4
4
  export { PACKAGE_VERSION };
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-taxyscge.js";
4
4
  import {
5
5
  PACKAGE_VERSION
6
- } from "./chunk-wfty87ws.js";
6
+ } from "./chunk-b3560w0q.js";
7
7
  import {
8
8
  hasRegisteredUiExtensionResource
9
9
  } from "./chunk-rxnyn7tf.js";
@@ -6,9 +6,9 @@ import {
6
6
  createMcpServer,
7
7
  hasValidLocalhostRebindingHeaders,
8
8
  isLoopbackHostname
9
- } from "../chunk-7dpts3r9.js";
9
+ } from "../chunk-drwp31va.js";
10
10
  import"../chunk-taxyscge.js";
11
- import"../chunk-wfty87ws.js";
11
+ import"../chunk-b3560w0q.js";
12
12
  import {
13
13
  resolveOauthNetworkIdentity
14
14
  } from "../chunk-yf4nw40e.js";
@@ -430,6 +430,34 @@ function createUserServerEventBus(input) {
430
430
  return input.messaging ? new CrossInstanceUserServerEventBus(input.userId, input.messaging, input.onError) : new InMemoryServerEventBus;
431
431
  }
432
432
 
433
+ // src/http/listen-inspection.ts
434
+ function readRequestedResourceUris(message) {
435
+ const parameters = message.params;
436
+ if (typeof parameters !== "object" || parameters === null)
437
+ return [];
438
+ const notifications = parameters.notifications;
439
+ if (typeof notifications !== "object" || notifications === null)
440
+ return [];
441
+ const uris = notifications.resourceSubscriptions;
442
+ return Array.isArray(uris) ? uris.filter((uri) => typeof uri === "string") : [];
443
+ }
444
+ async function inspectListenRequest(request) {
445
+ const none = { isListenRequest: false, requestedResourceUris: [] };
446
+ if (!request.body)
447
+ return none;
448
+ try {
449
+ const parsed = await request.json();
450
+ const messages = Array.isArray(parsed) ? parsed : [parsed];
451
+ const listens = messages.filter((message) => typeof message === "object" && message !== null && message.method === "subscriptions/listen");
452
+ return listens.length === 0 ? none : {
453
+ isListenRequest: true,
454
+ requestedResourceUris: listens.flatMap(readRequestedResourceUris)
455
+ };
456
+ } catch {
457
+ return none;
458
+ }
459
+ }
460
+
433
461
  // src/http/handler.ts
434
462
  class McpPayloadTooLargeError extends Error {
435
463
  }
@@ -474,32 +502,6 @@ function boundRequestBody(request, maximumBytes) {
474
502
  signal: request.signal
475
503
  });
476
504
  }
477
- function readRequestedResourceUris(message) {
478
- const parameters = message.params;
479
- if (typeof parameters !== "object" || parameters === null)
480
- return [];
481
- const notifications = parameters.notifications;
482
- if (typeof notifications !== "object" || notifications === null)
483
- return [];
484
- const uris = notifications.resourceSubscriptions;
485
- return Array.isArray(uris) ? uris.filter((uri) => typeof uri === "string") : [];
486
- }
487
- async function inspectListenRequest(request) {
488
- const none = { isListenRequest: false, requestedResourceUris: [] };
489
- if (!request.body)
490
- return none;
491
- try {
492
- const parsed = await request.clone().json();
493
- const messages = Array.isArray(parsed) ? parsed : [parsed];
494
- const listens = messages.filter((message) => typeof message === "object" && message !== null && message.method === "subscriptions/listen");
495
- return listens.length === 0 ? none : {
496
- isListenRequest: true,
497
- requestedResourceUris: listens.flatMap(readRequestedResourceUris)
498
- };
499
- } catch {
500
- return none;
501
- }
502
- }
503
505
  function createMcpServingHandler(input) {
504
506
  const { registry, configuration, seams } = input;
505
507
  if (!seams.messaging)
@@ -559,7 +561,7 @@ function createMcpServingHandler(input) {
559
561
  const extra = readMcpRequestAuthExtra(authInfo);
560
562
  if (!extra)
561
563
  throw new Error("MCP request reached the handler without verified auth context.");
562
- const inspection = await inspectListenRequest(boundedRequest);
564
+ const inspection = await inspectListenRequest(boundedRequest.clone());
563
565
  if (inspection.isListenRequest && !areResourceSubscriptionsAuthorized(inspection.requestedResourceUris, extra.scopes, registry)) {
564
566
  seams.recordEvent("insufficient_scope");
565
567
  return createMcpProtocolErrorResponse({
@@ -766,6 +768,7 @@ function createMcpHttpServingLayer(input) {
766
768
  });
767
769
  }
768
770
  try {
771
+ const listenProbe = input.markServerOnlyCloseableStream ? context.request.clone() : undefined;
769
772
  const response = await input.handler.handle(context.request, authentication);
770
773
  const headers = new Headers(response.headers);
771
774
  for (const [name, value] of Object.entries(corsHeaders))
@@ -775,7 +778,18 @@ function createMcpHttpServingLayer(input) {
775
778
  statusText: response.statusText,
776
779
  headers
777
780
  });
778
- return attachConcurrencySlotToResponseLifetime(responseWithCorsHeaders, concurrencySlot);
781
+ const settled = attachConcurrencySlotToResponseLifetime(responseWithCorsHeaders, concurrencySlot);
782
+ if (listenProbe) {
783
+ const isEventStream = (settled.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream");
784
+ if (isEventStream) {
785
+ if ((await inspectListenRequest(listenProbe)).isListenRequest) {
786
+ return input.markServerOnlyCloseableStream?.(settled) ?? settled;
787
+ }
788
+ } else {
789
+ listenProbe.body?.cancel().catch(() => {});
790
+ }
791
+ }
792
+ return settled;
779
793
  } catch (error) {
780
794
  await concurrencySlot.release();
781
795
  throw error;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Detects the `subscriptions/listen` request whose response the transport must
3
+ * not force-close on graceful shutdown. Shared by the serving handler (for
4
+ * subscription-scope authorization) and the serving layer (to tag the final
5
+ * response), so neither needs a runtime dependency on the other (TRI-128).
6
+ */
7
+ export type ListenInspection = {
8
+ isListenRequest: boolean;
9
+ requestedResourceUris: string[];
10
+ };
11
+ export declare function inspectListenRequest(request: Request): Promise<ListenInspection>;
@@ -15,4 +15,11 @@ export declare function createMcpHttpServingLayer(input: {
15
15
  rateLimiter: Pick<RequestRateLimiter, 'consume'>;
16
16
  concurrencyLimiter: Pick<McpConcurrencyLimiter, 'acquire'>;
17
17
  handler: Pick<McpServingHandler, 'handle'>;
18
+ /**
19
+ * Applied to the FINAL response for a `subscriptions/listen` request so a
20
+ * graceful-shutdown drain can exclude it. Provided here (not read off the
21
+ * handler) because this layer owns the response after its CORS and
22
+ * concurrency re-wraps, which replace the object the handler could tag.
23
+ */
24
+ markServerOnlyCloseableStream?: (response: Response) => Response;
18
25
  }): McpHttpServingLayer;
package/dist/index.js CHANGED
@@ -11,13 +11,13 @@ import {
11
11
  readRequestSender,
12
12
  readSessionIdentifier,
13
13
  stringifyUnknown
14
- } from "./chunk-7dpts3r9.js";
14
+ } from "./chunk-drwp31va.js";
15
15
  import {
16
16
  metricsCollector
17
17
  } from "./chunk-taxyscge.js";
18
18
  import {
19
19
  PACKAGE_VERSION
20
- } from "./chunk-wfty87ws.js";
20
+ } from "./chunk-b3560w0q.js";
21
21
  import {
22
22
  getSupportedScopes,
23
23
  hasRegisteredUiExtensionResource
@@ -7,6 +7,39 @@ export type PostgresOAuthDatabase = PostgresOAuthExecutor & {
7
7
  };
8
8
  export declare function hashOpaqueValue(value: string): string;
9
9
  export declare function resultRows<T>(result: unknown): T[];
10
+ /**
11
+ * Coerces a driver timestamp value to a Date.
12
+ *
13
+ * The read paths in these stores call `database.execute(sql`…`)`, which bypasses
14
+ * drizzle's typed column mapping. Every drizzle pg-family driver — node-postgres,
15
+ * neon-serverless, and pglite alike — overrides the `timestamptz`/`timestamp`/
16
+ * `date` type parser to return the raw string so that its column `mode` can do
17
+ * the conversion, but `execute` never reaches that mapping. So these columns
18
+ * arrive as strings even though the store types declare `Date`, and a consumer
19
+ * calling a `Date` method on one (for example the resource-server auth building
20
+ * `expiresAt.getTime()`, or the client-secret expiry check) throws in
21
+ * production. A value already a `Date` (a driver without the override) passes
22
+ * through unchanged.
23
+ *
24
+ * Fails loudly rather than coercing silently: a `NOT NULL` column that comes
25
+ * back null would make `new Date(null)` the Unix epoch, and an unparseable
26
+ * string would make an `Invalid Date` — both still `Date` instances that would
27
+ * corrupt `expiresAt`/`createdAt` or propagate `NaN` downstream. So null,
28
+ * undefined, and unparseable values throw here instead.
29
+ */
30
+ export declare function toDate(value: unknown): Date;
31
+ /**
32
+ * Null-safe {@link toDate} for nullable timestamp columns: null and undefined
33
+ * map to null, and any present value is validated by {@link toDate}.
34
+ */
35
+ export declare function toNullableDate(value: unknown): Date | null;
36
+ /**
37
+ * Coerces the named timestamp columns on a result row to `Date` in place and
38
+ * returns the row. `required` columns are `NOT NULL`; `nullable` columns may be
39
+ * null. Keeps the raw-SQL read paths' declared return types honest without
40
+ * threading a bespoke mapper through every store.
41
+ */
42
+ export declare function coerceRowDates<T>(row: T, required: readonly (keyof T)[], nullable?: readonly (keyof T)[]): T;
10
43
  export declare function affectedRows(result: unknown): number;
11
44
  export declare function countRows(result: unknown): number;
12
45
  export declare function columnIdentifier(column: {
@@ -109,6 +109,27 @@ function resultRows(result) {
109
109
  }
110
110
  return [];
111
111
  }
112
+ function toDate(value) {
113
+ if (value === null || value === undefined) {
114
+ throw new TypeError("OAuth store timestamp column was null; expected a NOT NULL timestamp.");
115
+ }
116
+ const date = value instanceof Date ? value : new Date(value);
117
+ if (Number.isNaN(date.getTime())) {
118
+ throw new TypeError(`OAuth store timestamp could not be parsed: ${String(value)}`);
119
+ }
120
+ return date;
121
+ }
122
+ function toNullableDate(value) {
123
+ return value === null || value === undefined ? null : toDate(value);
124
+ }
125
+ function coerceRowDates(row, required, nullable = []) {
126
+ const record = row;
127
+ for (const key of required)
128
+ record[key] = toDate(record[key]);
129
+ for (const key of nullable)
130
+ record[key] = toNullableDate(record[key]);
131
+ return row;
132
+ }
112
133
  function affectedRows(result) {
113
134
  if (result && typeof result === "object" && "rowCount" in result && typeof result.rowCount === "number") {
114
135
  return result.rowCount;
@@ -160,7 +181,8 @@ class PostgresTransactionStore {
160
181
  client_id AS "clientId", redirect_uri AS "redirectUri", code_challenge AS "codeChallenge",
161
182
  code_challenge_method AS "codeChallengeMethod", state, issuer, resource, scope,
162
183
  expires_at AS "expiresAt", consumed_at AS "consumedAt", created_at AS "createdAt"`);
163
- return resultRows(result)[0] ?? null;
184
+ const row = resultRows(result)[0];
185
+ return row ? coerceRowDates(row, ["expiresAt", "consumedAt", "createdAt"]) : null;
164
186
  }
165
187
  async unconsume(transactionId, consumedAt) {
166
188
  return affectedRows(await this.database.execute(sql`UPDATE ${this.schema.transactions} SET consumed_at = NULL
@@ -203,13 +225,15 @@ class PostgresCodeStore {
203
225
  async findByHash(codeHash) {
204
226
  const userId = columnIdentifier(this.schema.codes.userId);
205
227
  const result = await this.database.execute(sql`SELECT ${returnedCode(userId)} FROM ${this.schema.codes} WHERE code_hash = ${codeHash}`);
206
- return resultRows(result)[0] ?? null;
228
+ const row = resultRows(result)[0];
229
+ return row ? coerceRowDates(row, ["expiresAt", "createdAt"], ["usedAt"]) : null;
207
230
  }
208
231
  async consume(codeHash, now) {
209
232
  const userId = columnIdentifier(this.schema.codes.userId);
210
233
  const result = await this.database.execute(sql`UPDATE ${this.schema.codes} SET used_at = date_trunc('milliseconds', clock_timestamp())
211
234
  WHERE code_hash = ${codeHash} AND used_at IS NULL AND expires_at > ${now} RETURNING ${returnedCode(userId)}`);
212
- return resultRows(result)[0] ?? null;
235
+ const row = resultRows(result)[0];
236
+ return row ? coerceRowDates(row, ["expiresAt", "usedAt", "createdAt"]) : null;
213
237
  }
214
238
  async unconsume(codeHash, usedAt) {
215
239
  return affectedRows(await this.database.execute(sql`UPDATE ${this.schema.codes} SET used_at = NULL
@@ -254,7 +278,8 @@ class PostgresTokenStore {
254
278
  const userId = columnIdentifier(this.schema.accessTokens.userId);
255
279
  const result = await this.database.execute(sql`SELECT ${returnedAccessToken(userId)} FROM ${this.schema.accessTokens}
256
280
  WHERE access_token_hash = ${tokenHash}`);
257
- return resultRows(result)[0] ?? null;
281
+ const row = resultRows(result)[0];
282
+ return row ? coerceRowDates(row, ["expiresAt", "createdAt"], ["revokedAt"]) : null;
258
283
  }
259
284
  async rotateRefreshToken(input) {
260
285
  return this.database.transaction(async (transaction) => {
@@ -517,7 +542,10 @@ class PostgresClientStore {
517
542
  async findById(clientId) {
518
543
  const result = await this.database.execute(sql`SELECT ${returnedClient} FROM ${this.schema.clients} WHERE client_id = ${clientId}`);
519
544
  const client = resultRows(result)[0];
520
- return client ? structuredClone(client) : null;
545
+ if (!client)
546
+ return null;
547
+ coerceRowDates(client, ["createdAt", "updatedAt"], ["clientSecretExpiresAt"]);
548
+ return structuredClone(client);
521
549
  }
522
550
  async update(clientId, patch) {
523
551
  const columns = {
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.1";
23
+ export declare const PACKAGE_VERSION = "0.2.3";
package/dist/version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PACKAGE_VERSION
3
- } from "./chunk-wfty87ws.js";
3
+ } from "./chunk-b3560w0q.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.1",
3
+ "version": "0.2.3",
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>",