@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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Steve Kinney
3
+ Copyright (c) 2024–2026 Steve Kinney
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,185 +1,27 @@
1
- # @lostgradient/mcp
1
+ # Protected MCP HTTP
2
2
 
3
- A [Model Context Protocol](https://modelcontextprotocol.io) server engine: tool, resource, and prompt registries; a consumer-defined OAuth scope vocabulary; and the request-boundary pieces a host needs to serve MCP over HTTP.
3
+ `@lostgradient/mcp/http` wraps a Fetch dispatcher with protected-resource discovery and bearer admission. Configure a canonical HTTPS origin, resource path, external issuer, advertised scopes, a verifier, and a current-principal resolver. The verifier must authenticate the token using the issuer's keys or authenticated introspection and return its issuer, audience, subject, scopes, and expiration in Unix milliseconds. The principal resolver must consult current membership and return its delegable scopes. The handler checks the configured issuer, audience, and expiration and does not accept cookies or API keys as bearer credentials.
4
4
 
5
- The engine is deliberately unopinionated about identity and storage. `McpContext` is a plain pre-fetched object with no database handle and no ambient service locator, and `McpUserProfile` is `{ id, email, name, image, role }` — generic, not tied to any identity provider.
5
+ The dispatcher receives the verified grant. Immediately before invoking an operation, await `context.requireScopes(requiredScopes)` and return `decision.response` when `decision.ok` is false. When it succeeds, use `decision.principal` for that operation. The decision resolves current membership and refuses canceled requests; a missing scope produces an upgrade challenge only when the principal can delegate it. The dispatcher owns operation authorization and must propagate the request's cancellation signal to its work. Response streams are cancelled on client cancellation and their chunks are released only while the token and membership remain current. Public discovery URLs always use the configured origin, never forwarded host headers. `allowedOrigins` admits browser origins; by default no browser origin is admitted. `maximumRequestBytes` bounds request bodies and defaults to one mebibyte.
6
6
 
7
- ## Install
7
+ `@lostgradient/mcp/oauth` supplies `hostedOAuth` and an `OAuthStore`. Supply the issuer and resource URLs, scope descriptions, explicit starting scopes, storage, and application functions for the browser session, sign-in, and current membership. Mount the returned Fetch handler at the issuer and pass its `verifyAccessToken` to the protected HTTP handler. Each consent creates its own grant, and the verifier checks current membership before admitting a token. Store credentials only in the issuer; never put browser cookies, client secrets, or verifiers in application logs.
8
8
 
9
- ```sh
10
- npm install @lostgradient/mcp
11
- ```
12
-
13
- Requires Node 22 or later, or Bun. The package is ESM-only.
14
-
15
- ## Defining a server
16
-
17
- Scopes come first, because every tool, resource, and prompt has to declare one. `defineScopes` returns definers bound to your vocabulary, so a mistyped scope is a compile error on the primitive itself rather than a runtime surprise later.
18
-
19
- ```ts
20
- import { defineScopes, createMcpServer } from '@lostgradient/mcp';
21
- import { z } from 'zod';
22
-
23
- const scopes = defineScopes({
24
- 'repositories:read': 'Read repository metadata.',
25
- });
26
-
27
- const listRepositories = scopes.defineTool({
28
- name: 'list_repositories',
29
- title: 'List repositories',
30
- description: 'Lists repositories the signed-in user can access.',
31
- inputSchema: z.object({}),
32
- annotations: {
33
- readOnlyHint: true,
34
- destructiveHint: false,
35
- idempotentHint: true,
36
- openWorldHint: false,
37
- },
38
- requiredScope: 'repositories:read',
39
- handler: async () => ({ content: [] }),
40
- });
41
-
42
- const registry = scopes.defineRegistry({
43
- tools: [listRepositories],
44
- resources: [],
45
- prompts: [],
46
- serverInfo: { name: 'my-server', version: '1.0.0' },
47
- // Supply your own. Without this, the server advertises instructions
48
- // describing a different server's tools and endpoints — see below.
49
- instructions: 'Lists repositories the signed-in user can access.',
50
- });
51
- ```
52
-
53
- ## Constructing a server
54
-
55
- `createMcpServer` takes a context describing the current request. There is no ambient state: everything it needs is passed in, which is what lets the engine be embedded without knowing how you authenticate or store anything.
56
-
57
- ```ts
58
- const server = createMcpServer(
59
- {
60
- userId: user.id,
61
- user, // { id, email, name, image, role }
62
- scopes: grantedScopes, // the scopes this request's token actually carries
63
- enableUiExtension: false,
64
- // Supplied so construction never reads the ambient environment; see
65
- // "Construction and the ambient environment" below.
66
- enableConformanceMode: false,
67
- // Optional: `requestId` to trace one action through your logs, `era` to
68
- // pin the protocol revision, `publishResourceUpdate` to fan subscription
69
- // events out across replicas.
70
- },
71
- registry,
72
- );
73
- ```
74
-
75
- `scopes` is the request's granted scopes, not your vocabulary — the server compares each operation's `requiredScope` against it, so passing the full vocabulary here would authorize everything.
76
-
77
- > **Always set `instructions` on your registry.** When it is absent, the server falls back to instructions bundled with this package, which describe a different server: its own demo tools, its own OAuth endpoints, and an assertion that every operation is read-only. A client would receive a confident, wrong description of what your server does.
78
-
79
- ### Construction and the ambient environment
80
-
81
- Importing this package reads nothing from `process.env`. **Constructing a server can**, through two fallbacks, and both are worth supplying explicitly:
82
-
83
- | Omitted | What happens |
84
- | ------------------------------- | --------------------------------------------------------- |
85
- | `context.enableConformanceMode` | falls back to `MCP_CONFORMANCE_MODE` from the environment |
86
- | `registry.serverInfo` | falls back to `MCP_SERVER_NAME` from the environment |
87
-
88
- Each fallback calls the environment parser, which requires `NODE_ENV`. So in a plain Node process with `NODE_ENV` unset, omitting **either** makes `createMcpServer` throw before returning — supplying only one is not enough. The example above supplies both, which is why it runs anywhere.
89
-
90
- If you would rather rely on the environment, set `NODE_ENV` (and any other variable the schema requires) before constructing, and validate it yourself with `parseMcpServerEnvironment` so the failure is yours to report rather than a throw from inside the factory.
91
-
92
- `getSupportedScopes(registry)` returns the sorted union of every scope your registry actually requires. Use it for the `scopes_supported` field of your OAuth metadata documents and for the `scope` attribute on a `401` challenge, rather than maintaining that list by hand.
93
-
94
- ## Running protocol conformance
95
-
96
- `runMcpConformance` runs either protocol era against your registry. Discovery is checked automatically. Supply valid arguments only for the tools or prompts you want invoked, and resource URIs only for the resources you want read—the harness cannot safely invent valid consumer input.
97
-
98
- ```ts
99
- import { runMcpConformance } from '@lostgradient/mcp';
9
+ The `./oauth` entry also runs on Cloudflare Workers with the `nodejs_compat` compatibility flag. Client-ID metadata documents require a DNS lookup before their URL is fetched; Workers must provide that lookup through `clientMetadataDocumentFetch.lookupImpl` (for example, with DNS over HTTPS). The issuer validates every returned address before making the HTTPS request, so the supplied resolver must return the complete address set.
100
10
 
101
- const results = await runMcpConformance({
102
- era: 'modern', // or 'legacy'
103
- registry,
104
- scopeVocabulary: scopes,
105
- identity: { userId: user.id, user },
106
- toolProbes: { list_repositories: {} },
107
- });
11
+ `@lostgradient/mcp/oauth/postgres` supplies `createPostgresOAuthStores`, backed by the existing PostgreSQL storage adapter. That entry is the only one that needs `@lostgradient/storage-postgres` and `pg`; both are optional peer dependencies, so a consumer of `./oauth` alone (a Worker, for one) installs neither. Point each instance at the same primary and table and dispose the returned store when the host stops. Run `bun run --cwd packages/mcp test:oauth:postgres` with a loopback PostgreSQL URL in `WEFT_TEST_POSTGRES_URL`, or with `initdb` and `pg_ctl` on `PATH`, to exercise the live cross-instance contract.
108
12
 
109
- for (const result of results) {
110
- console.log(result.name, result.status, result.error ?? '');
111
- }
112
- ```
113
-
114
- Each result has a stable behavior name and its own `passed` or `failed` status. One failed tool, resource, or prompt probe does not hide the results of the remaining behaviors. Supply the same application identity every probe should use; otherwise the harness creates one stable synthetic identity for the run. The runner disables package-owned conformance fixtures so discovery reflects only the supplied registry. `createConsumerConformanceHandler` exposes the lower-level request handler when a consumer needs to drive its own client or explicitly enable those fixtures, including watched-resource notifications. Its localhost DNS-rebinding check runs independently of `enableConformanceMode`.
115
-
116
- ## Environment
13
+ The same entry provides `createPostgresGrantRevocationChannel`. Pass its `publish` callback to the hosted issuer as `notifyGrantRevoked` and its `subscribe` callback to the protected HTTP handler as `subscribeGrantRevocation`. Dispose the channel on shutdown. A lost notification cannot release private output because the handler rechecks the durable grant before each chunk.
117
14
 
118
- Importing this package reads nothing from `process.env` and cannot throw, whatever the ambient environment. That is deliberate: a library which validates its host's environment during module evaluation cannot be embedded, because the host can neither catch the failure nor supply a different environment nor decide whether it wants a server at all.
15
+ ## Hosted connector probes
119
16
 
120
- Parse explicitly instead:
17
+ These independent probes exercise a public deployment before you test a Claude or ChatGPT connector. Set `MCP_PUBLIC_ORIGIN` to the canonical HTTPS origin, `MCP_RESOURCE_PATH` to the absolute MCP mount path, and `MCP_READ_SCOPE` and `MCP_WRITE_SCOPE` to the deployment's scope names. For the OAuth probe, set `MCP_IDENTITY_ORIGIN` to the expected browser identity provider origin. Run the commands from `packages/mcp`.
121
18
 
122
- ```ts
123
- import { parseMcpServerEnvironment, getEnvironment } from '@lostgradient/mcp';
124
-
125
- const environment = parseMcpServerEnvironment(process.env);
19
+ ```bash
20
+ bun run test:deployed-smoke -- "$MCP_PUBLIC_ORIGIN" "$MCP_RESOURCE_PATH" "$MCP_READ_SCOPE" "$MCP_WRITE_SCOPE"
21
+ bun run test:connector:inspector -- "$MCP_PUBLIC_ORIGIN" "$MCP_RESOURCE_PATH" "$MCP_READ_SCOPE" "$MCP_WRITE_SCOPE"
22
+ bun run test:deployed-oauth -- "$MCP_PUBLIC_ORIGIN" "$MCP_RESOURCE_PATH" "$MCP_READ_SCOPE" "$MCP_WRITE_SCOPE" --identity-origin "$MCP_IDENTITY_ORIGIN"
126
23
  ```
127
24
 
128
- `getEnvironment()` is the lazy, memoized equivalent for callers happy to read `process.env` on first use.
129
-
130
- ## Authorizing subscriptions
131
-
132
- `areResourceSubscriptionsAuthorized(uris, scopes, registry)` is exported because `subscriptions/listen` is decided at the HTTP boundary, before a request reaches the server instance — so a host that mounts this engine must call it there. Omitting it means a client with any valid token can observe updates for a resource whose scope it was never granted.
133
-
134
- ## Rate limiting and concurrency
135
-
136
- `@lostgradient/mcp/rate-limit` provides the protocol-level sliding-window policy, in-memory and Redis stores, MCP concurrency slots, and the standard `429` response. The Redis factories accept the `MinimalRedisClient` seam from `@lostgradient/mcp/oauth`; they do not require a particular Redis package or a full client object.
137
-
138
- The shared `RateLimitConfiguration` owns exactly eight protocol categories: OAuth authorize, registration, token network, token client, and revocation; MCP network and user; and failed authentication. Host-only routes such as sign-in, session creation, health, and metrics should use `SlidingWindowRateLimiter` directly with host-owned categories rather than extending the protocol category union.
139
-
140
- Concurrency is a resource-lifetime concern, not a handler-promise concern. For a streaming response, pass the acquired slot to `attachConcurrencySlotToResponseLifetime` so it renews while the body remains open and releases only when the body closes, is canceled, or errors. A host that separately tracks requests must follow the same rule; Tribunal's other implementation is `applications/web/src/lib/in-flight-request-tracker.ts`.
141
-
142
- ## Host logging
143
-
144
- Call `setLogger(hostLogger)` before serving requests to route every engine log record through the host's existing sink and redaction policy. The logger is structural and deliberately small: `info`, `warn`, `error`, and `child`. A host does not need to import pino or implement any other pino API. The exported `logger` and `getLogger()` remain the package's full pino-backed logger for compatibility; injection changes the engine's internal sink. If `setLogger` is not called, engine records use that same lazy pino logger and existing behavior.
145
-
146
- ## Required server identity in 0.2.0
147
-
148
- `MCP_SERVER_NAME` is required starting in 0.2.0. The package no longer defaults to the template-branded `template-mcp-server` identity because that fallback was silently advertised to every connected MCP client. Set the explicit server name before constructing a server.
149
-
150
- ## Mounting in SvelteKit
151
-
152
- `@lostgradient/mcp/sveltekit` provides a dependency-free adapter for a SvelteKit `handle` chain. Call `createSvelteKitMcpMount` once in a long-lived server process, pass the OAuth seams and MCP runtime, and delegate each request to the returned `handle`. The adapter claims its process lifecycle synchronously: a second mount fails, disposal is permanent, and failed startup cannot be retried in the same process.
153
-
154
- The host's identity handle must run first and call `primeSvelteKitMcpIdentity(event, identity)` for every request, including anonymous requests with `null`. The mount rejects a request when that handle was skipped or sequenced after it. It reads `event.getClientAddress()` for each request so the OAuth and MCP serving layers receive the immediate socket peer rather than a construction-time value.
155
-
156
- The host still owns the network listener, signal handling, request draining, and process termination. It must dispose the mount only after response bodies, including long-lived MCP streams, have closed or been canceled. Request-scoped edge and serverless runtimes cannot preserve the mount's subscriptions and must not set `longLivedProcess` to true. Adapter-node deployment behavior is intentionally left to the first host integration rather than claimed by this package contract.
157
-
158
- ## Client ID Metadata Documents
159
-
160
- `@lostgradient/mcp/oauth` exports Client ID Metadata Document fetching and the shared OAuth security utilities. Use `safeFetchPublicHttpsUrl` for any client-supplied metadata URL. It applies the complete SSRF boundary as one operation: the URL must use HTTPS, literal private addresses are rejected, every DNS result must be public, and redirects are disabled. Do not recreate those checks at a host call site.
161
-
162
- The dedicated `@lostgradient/mcp/oauth/client-metadata-documents` subpath exposes the same safe fetch together with `fetchClientIdMetadataDocument` and `isClientIdMetadataDocumentUrl`. The general `/oauth` entry point also owns `isAddressInCidr`, `isValidCidr`, `isValidRedirectUri`, `isValidClientName`, `isExactContentType`, `withDeadline`, and IP canonicalization so an embedding host does not maintain a second security implementation.
163
-
164
- ## Subpaths
165
-
166
- | Subpath | Contents |
167
- | --------------------------------------------------- | ---------------------------------------------------------------------- |
168
- | `@lostgradient/mcp` | The engine: server factory, registries, scope vocabularies, primitives |
169
- | `@lostgradient/mcp/logger` | Host logger injection and the lazy default pino logger |
170
- | `@lostgradient/mcp/env` | `parseMcpServerEnvironment` and `getEnvironment` |
171
- | `@lostgradient/mcp/environment-schema` | The raw Zod shape, side-effect free |
172
- | `@lostgradient/mcp/metrics` | The in-process metrics collector |
173
- | `@lostgradient/mcp/oauth` | OAuth contracts, metadata fetching, and shared security utilities |
174
- | `@lostgradient/mcp/oauth/stores` | Type-only contracts for durable OAuth storage |
175
- | `@lostgradient/mcp/oauth/testing` | In-memory OAuth stores for tests |
176
- | `@lostgradient/mcp/oauth/postgres` | PostgreSQL OAuth store implementations |
177
- | `@lostgradient/mcp/oauth/client-metadata-documents` | Client ID Metadata Document validation and SSRF-safe fetching |
178
- | `@lostgradient/mcp/rate-limit` | Sliding-window policy, stores, concurrency slots, and `429` responses |
179
- | `@lostgradient/mcp/http` | Ordered MCP HTTP serving and per-user handler lifecycle |
180
- | `@lostgradient/mcp/sveltekit` | Host-agnostic SvelteKit handle-chain mount |
181
- | `@lostgradient/mcp/version` | The advertised package version |
182
-
183
- ## License
25
+ The smoke probe checks public DNS, TLS, discovery, audience, scopes, and the unauthenticated challenge. Inspector runs the pinned Inspector CLI without stored authorization and prints its interactive continuation. The OAuth probe dynamically registers a public client, checks an invalid grant and the redirect to the expected identity provider, then listens on loopback while the operator signs in and approves consent. It exchanges the code, initializes MCP, and revokes the token without printing it. Each invocation creates a persistent registered client. Pass `--prepare-only` to stop before interactive sign-in, then rerun without that flag to complete it. Use a test identity and confirm the selected consent subject before approving.
184
26
 
185
- MIT
27
+ For hosted Claude and ChatGPT acceptance, sign in, call the tools, test permission changes, and revoke access in each real client against each deployed resource.
package/dist/http.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ export interface VerifiedGrant {
2
+ issuer: string;
3
+ audience: string | readonly string[];
4
+ expiresAt: number;
5
+ subject: string;
6
+ grantId?: string;
7
+ clientId?: string;
8
+ tenant?: string;
9
+ scopes: readonly string[];
10
+ }
11
+ export interface Principal {
12
+ delegableScopes: readonly string[];
13
+ }
14
+ export interface ProtectedHttpOptions<T extends Principal> {
15
+ origin: string;
16
+ resourcePath: string;
17
+ issuer: string;
18
+ scopes: readonly string[];
19
+ allowedOrigins?: readonly string[];
20
+ maximumRequestBytes?: number;
21
+ verifyAccessToken(token: string): Promise<VerifiedGrant | null>;
22
+ subscribeGrantRevocation?(grantId: string, listener: () => void): () => void;
23
+ resolvePrincipal(grant: VerifiedGrant): Promise<T | null>;
24
+ dispatch(request: Request, context: {
25
+ grant: VerifiedGrant;
26
+ requireScopes(scopes: readonly string[]): Promise<{
27
+ ok: true;
28
+ principal: T;
29
+ } | {
30
+ ok: false;
31
+ response: Response;
32
+ }>;
33
+ }): Response | Promise<Response>;
34
+ }
35
+ export declare function createProtectedHttpHandler<T extends Principal>(options: ProtectedHttpOptions<T>): (request: Request) => Promise<Response>;
package/dist/http.js ADDED
@@ -0,0 +1,251 @@
1
+ export function createProtectedHttpHandler(options) {
2
+ options = {
3
+ ...options,
4
+ scopes: [...options.scopes],
5
+ allowedOrigins: [...(options.allowedOrigins ?? [])],
6
+ };
7
+ const origin = new URL(options.origin);
8
+ if (origin.protocol !== 'https:' ||
9
+ origin.origin !== options.origin ||
10
+ !options.resourcePath.startsWith('/') ||
11
+ options.resourcePath.startsWith('//') ||
12
+ new URL(options.resourcePath, origin).pathname !== options.resourcePath)
13
+ throw new TypeError('Invalid public resource configuration');
14
+ const issuer = new URL(options.issuer);
15
+ if (issuer.protocol !== 'https:' ||
16
+ issuer.hash ||
17
+ issuer.search ||
18
+ issuer.username ||
19
+ issuer.password ||
20
+ options.scopes.some((scope) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)) ||
21
+ !Number.isSafeInteger(options.maximumRequestBytes ?? 1024 * 1024) ||
22
+ (options.maximumRequestBytes ?? 1024 * 1024) < 0)
23
+ throw new TypeError('Invalid authorization configuration');
24
+ const resource = new URL(options.resourcePath, origin).href;
25
+ const metadataPath = `/.well-known/oauth-protected-resource${options.resourcePath}`;
26
+ const metadata = new URL(metadataPath, origin).href;
27
+ const challenge = (error, scopes) => `Bearer resource_metadata="${metadata}"${error ? `, error="${error}"` : ''}${scopes ? `, scope="${scopes.join(' ')}"` : ''}`;
28
+ const handle = async (request) => {
29
+ const path = new URL(request.url).pathname;
30
+ if (path === metadataPath && request.method === 'GET')
31
+ return Response.json({
32
+ resource,
33
+ authorization_servers: [options.issuer],
34
+ scopes_supported: options.scopes,
35
+ });
36
+ if (path !== options.resourcePath)
37
+ return new Response(null, { status: 404 });
38
+ const requestOrigin = request.headers.get('origin');
39
+ if (requestOrigin &&
40
+ requestOrigin !== origin.origin &&
41
+ !options.allowedOrigins.includes(requestOrigin))
42
+ return new Response(null, { status: 403 });
43
+ if (request.method === 'OPTIONS')
44
+ return new Response(null, {
45
+ status: 204,
46
+ headers: requestOrigin
47
+ ? {
48
+ 'access-control-allow-origin': requestOrigin,
49
+ 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
50
+ 'access-control-allow-headers': 'authorization, content-type, mcp-protocol-version, mcp-session-id',
51
+ }
52
+ : {},
53
+ });
54
+ const authorization = request.headers.get('authorization');
55
+ const match = authorization?.match(/^Bearer ([A-Za-z0-9\-._~+/]+=*)$/i);
56
+ const unauthorized = () => new Response(null, {
57
+ status: 401,
58
+ headers: { 'www-authenticate': challenge(authorization ? 'invalid_token' : undefined) },
59
+ });
60
+ if (!match || match[1].length > 8192)
61
+ return unauthorized();
62
+ let grant;
63
+ try {
64
+ grant = await options.verifyAccessToken(match[1]);
65
+ }
66
+ catch {
67
+ return unauthorized();
68
+ }
69
+ if (!grant ||
70
+ grant.issuer !== options.issuer ||
71
+ !(typeof grant.audience === 'string'
72
+ ? grant.audience === resource
73
+ : grant.audience.includes(resource)) ||
74
+ !Number.isFinite(grant.expiresAt) ||
75
+ grant.expiresAt <= Date.now())
76
+ return unauthorized();
77
+ grant = Object.freeze({
78
+ ...grant,
79
+ audience: typeof grant.audience === 'string' ? grant.audience : Object.freeze([...grant.audience]),
80
+ scopes: Object.freeze([...grant.scopes]),
81
+ });
82
+ const binding = {
83
+ issuer: grant.issuer,
84
+ subject: grant.subject,
85
+ grantId: grant.grantId,
86
+ clientId: grant.clientId,
87
+ tenant: grant.tenant,
88
+ audience: JSON.stringify(grant.audience),
89
+ scopes: [...grant.scopes],
90
+ };
91
+ if (!(await options.resolvePrincipal(grant)))
92
+ return unauthorized();
93
+ const maximum = options.maximumRequestBytes ?? 1024 * 1024;
94
+ if (Number(request.headers.get('content-length')) > maximum)
95
+ return new Response(null, { status: 413 });
96
+ if (request.body) {
97
+ const reader = request.body.getReader();
98
+ const chunks = [];
99
+ let length = 0;
100
+ while (true) {
101
+ const result = await reader.read();
102
+ if (result.done)
103
+ break;
104
+ length += result.value.byteLength;
105
+ if (length > maximum) {
106
+ await reader.cancel();
107
+ return new Response(null, { status: 413 });
108
+ }
109
+ chunks.push(new Uint8Array(result.value));
110
+ }
111
+ request = new Request(request, { method: request.method, body: new Blob(chunks) });
112
+ }
113
+ if (request.signal.aborted)
114
+ return new Response(null, { status: 499 });
115
+ const token = match[1];
116
+ const requiredScopes = new Set();
117
+ const current = async () => {
118
+ try {
119
+ const fresh = await options.verifyAccessToken(token);
120
+ if (!fresh ||
121
+ fresh.issuer !== binding.issuer ||
122
+ fresh.subject !== binding.subject ||
123
+ fresh.grantId !== binding.grantId ||
124
+ fresh.clientId !== binding.clientId ||
125
+ fresh.tenant !== binding.tenant ||
126
+ JSON.stringify(fresh.audience) !== binding.audience ||
127
+ !Number.isFinite(fresh.expiresAt) ||
128
+ fresh.expiresAt <= Date.now() ||
129
+ !binding.scopes.every((scope) => fresh.scopes.includes(scope)))
130
+ return null;
131
+ const currentPrincipal = await options.resolvePrincipal(fresh);
132
+ if (!currentPrincipal ||
133
+ ![...requiredScopes].every((scope) => currentPrincipal.delegableScopes.includes(scope)))
134
+ return null;
135
+ return { ...currentPrincipal, delegableScopes: [...currentPrincipal.delegableScopes] };
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ };
141
+ if (!(await current()) || request.signal.aborted)
142
+ return unauthorized();
143
+ const response = await options.dispatch(request, {
144
+ grant,
145
+ async requireScopes(scopes) {
146
+ const requested = [...scopes];
147
+ if (requested.some((scope) => !options.scopes.includes(scope)))
148
+ return { ok: false, response: new Response(null, { status: 403 }) };
149
+ const principal = await current();
150
+ if (!principal || request.signal.aborted)
151
+ return { ok: false, response: unauthorized() };
152
+ const missing = requested.filter((scope) => !binding.scopes.includes(scope));
153
+ if (requested.some((scope) => !principal.delegableScopes.includes(scope)))
154
+ return { ok: false, response: new Response(null, { status: 403 }) };
155
+ if (missing.length)
156
+ return {
157
+ ok: false,
158
+ response: new Response(null, {
159
+ status: 403,
160
+ headers: { 'www-authenticate': challenge('insufficient_scope', missing) },
161
+ }),
162
+ };
163
+ for (const scope of requested)
164
+ requiredScopes.add(scope);
165
+ return { ok: true, principal };
166
+ },
167
+ });
168
+ if (!response.body)
169
+ return response;
170
+ const reader = response.body.getReader();
171
+ let closed = false;
172
+ let cancelled = false;
173
+ let finished = false;
174
+ let output;
175
+ let unsubscribe = () => { };
176
+ const finish = () => {
177
+ if (finished || cancelled)
178
+ return;
179
+ finished = true;
180
+ unsubscribe();
181
+ request.signal.removeEventListener('abort', abort);
182
+ output.close();
183
+ };
184
+ const close = async () => {
185
+ if (closed)
186
+ return;
187
+ closed = true;
188
+ await reader.cancel();
189
+ };
190
+ const abort = () => {
191
+ void close().then(finish);
192
+ };
193
+ request.signal.addEventListener('abort', abort, { once: true });
194
+ const body = new ReadableStream({
195
+ start(controller) {
196
+ output = controller;
197
+ if (binding.grantId && options.subscribeGrantRevocation) {
198
+ unsubscribe = options.subscribeGrantRevocation(binding.grantId, () => {
199
+ void close().then(finish);
200
+ });
201
+ }
202
+ },
203
+ async pull(controller) {
204
+ const beforeRead = await current();
205
+ if (closed || request.signal.aborted || !beforeRead) {
206
+ await close();
207
+ finish();
208
+ return;
209
+ }
210
+ const result = await reader.read();
211
+ const beforeRelease = await current();
212
+ if (closed || request.signal.aborted || !beforeRelease) {
213
+ await close();
214
+ finish();
215
+ }
216
+ else if (result.done) {
217
+ closed = true;
218
+ finish();
219
+ }
220
+ else
221
+ controller.enqueue(result.value);
222
+ },
223
+ async cancel() {
224
+ cancelled = true;
225
+ unsubscribe();
226
+ request.signal.removeEventListener('abort', abort);
227
+ await close();
228
+ },
229
+ });
230
+ return new Response(body, {
231
+ status: response.status,
232
+ statusText: response.statusText,
233
+ headers: response.headers,
234
+ });
235
+ };
236
+ return async (request) => {
237
+ const response = await handle(request);
238
+ const requestOrigin = request.headers.get('origin');
239
+ if (!requestOrigin || !options.allowedOrigins.includes(requestOrigin))
240
+ return response;
241
+ const headers = new Headers(response.headers);
242
+ headers.set('access-control-allow-origin', requestOrigin);
243
+ headers.append('vary', 'Origin');
244
+ headers.set('access-control-expose-headers', 'WWW-Authenticate, MCP-Session-Id, MCP-Protocol-Version');
245
+ return new Response(response.body, {
246
+ status: response.status,
247
+ statusText: response.statusText,
248
+ headers,
249
+ });
250
+ };
251
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Authenticated encryption for stored secrets: AES-256-GCM through Web Crypto, with a keyring so a
3
+ * key can be rotated without losing values written under the old one.
4
+ *
5
+ * Design, in the order a reviewer is likely to ask:
6
+ *
7
+ * - **Fresh IV per encryption.** Every `encrypt` draws a new random 96-bit IV from
8
+ * `crypto.getRandomValues`; an IV is never derived, counted, or reused. With random 96-bit IVs the
9
+ * collision risk stays negligible up to roughly 2^32 encryptions under one key, so rotate a key
10
+ * long before it has sealed that many values.
11
+ * - **Key id.** A key's id is `hex(SHA-256("corvidae.cryptography.key-id.v1" || rawKey))`
12
+ * truncated to 12 bytes: 24 lowercase hexadecimal characters, which is a valid Bungalow secret-name
13
+ * suffix (`answer-encryption-key-<keyId>`). SHA-256 is preimage-resistant and the key is 256 bits of entropy, so the
14
+ * id reveals nothing usable about the key, and it is derived rather than stored, so a host can
15
+ * recompute the id (and the Bungalow secret name that embeds it) from the key alone.
16
+ * - **Additional authenticated data.** The version tag and the key id are bound into the GCM
17
+ * additional data, so rewriting either on a stored value fails authentication instead of silently
18
+ * selecting a different key or algorithm.
19
+ * - **Version.** Stored values carry `version: 1`. It is the only hook for a future algorithm
20
+ * change, and a stored value is long-lived, so the tag is cheap insurance on a persisted shape.
21
+ * - **Errors.** Every failure is a {@link CryptographyError} with a fixed message and a code. No
22
+ * message contains key material or plaintext, and WebCrypto's own error is never re-thrown.
23
+ */
24
+ /** Why a cryptographic operation failed. */
25
+ export type CryptographyErrorCode =
26
+ /** The stored value names a key id that is not in the keyring. */
27
+ 'secret-unavailable'
28
+ /** Authentication failed: the ciphertext, iv, key id, or version was altered, or the key is wrong. */
29
+ | 'authentication-failed'
30
+ /** The stored value is not shaped like output of {@link encrypt}. */
31
+ | 'malformed-secret'
32
+ /** The stored value carries a version this module does not understand. */
33
+ | 'unsupported-version'
34
+ /** An encoded key is not a valid base64url 256-bit key, or cannot be exported. */
35
+ | 'invalid-key'
36
+ /** Text that cannot round-trip: a string with a lone surrogate, or decrypted bytes that are not UTF-8. */
37
+ | 'invalid-text';
38
+ /** An error from this module. The message is fixed text and never contains key material or plaintext. */
39
+ export declare class CryptographyError extends Error {
40
+ /** The category of failure, for programmatic handling. */
41
+ readonly code: CryptographyErrorCode;
42
+ /** For `secret-unavailable`, the key id that the keyring could not supply. Not secret. */
43
+ readonly keyId: string | undefined;
44
+ /** Creates an error with a fixed message for the given code. */
45
+ constructor(code: CryptographyErrorCode, keyId?: string);
46
+ }
47
+ /** An AES-256-GCM key together with its derived id. Treat it as opaque; import or generate it. */
48
+ export type EncryptionKey = {
49
+ /** Identifier derived from the key (see the module notes); safe to store and log. */
50
+ readonly keyId: string;
51
+ /** The Web Crypto key. Imported keys are non-extractable unless requested otherwise. */
52
+ readonly cryptoKey: CryptoKey;
53
+ };
54
+ /** The current key plus retired keys, so values written before a rotation stay readable. */
55
+ export type Keyring = {
56
+ /** Encrypts new values; also decrypts values that name its id. */
57
+ readonly current: EncryptionKey;
58
+ /** Former keys, decrypt-only. Order does not matter. */
59
+ readonly retired?: readonly EncryptionKey[];
60
+ };
61
+ /** A stored encrypted value. All binary fields are base64url without padding. */
62
+ export type EncryptedValue = {
63
+ /** Shape version; always `1` today. */
64
+ readonly version: 1;
65
+ /** The ciphertext followed by the 128-bit authentication tag. */
66
+ readonly ciphertext: string;
67
+ /** The 96-bit initialization vector, unique to this encryption. */
68
+ readonly iv: string;
69
+ /** Id of the key that encrypted the value. */
70
+ readonly keyId: string;
71
+ };
72
+ /** Options for {@link importEncryptionKey}. */
73
+ export type ImportEncryptionKeyOptions = {
74
+ /** Allow {@link exportEncryptionKey} on the result. Defaults to `false`. */
75
+ readonly extractable?: boolean;
76
+ };
77
+ /**
78
+ * Generates a new random AES-256 key. The result is extractable so the host can persist it with
79
+ * {@link exportEncryptionKey}.
80
+ */
81
+ export declare function generateEncryptionKey(): Promise<EncryptionKey>;
82
+ /**
83
+ * Imports a key previously produced by {@link exportEncryptionKey}: base64url of exactly 32 bytes.
84
+ * Throws `invalid-key` for anything else.
85
+ */
86
+ export declare function importEncryptionKey(encoded: string, options?: ImportEncryptionKeyOptions): Promise<EncryptionKey>;
87
+ /**
88
+ * Exports a key as base64url of its 32 raw bytes, for storage as a secret. The result is key
89
+ * material: never log it. Throws `invalid-key` when the key was imported without `extractable`.
90
+ */
91
+ export declare function exportEncryptionKey(key: EncryptionKey): Promise<string>;
92
+ /**
93
+ * Encrypts text (UTF-8) or bytes under `key` with a fresh random IV. The result is safe to persist
94
+ * as JSON.
95
+ */
96
+ export declare function encrypt(plaintext: string | Uint8Array, key: EncryptionKey): Promise<EncryptedValue>;
97
+ /**
98
+ * Decrypts a value written by {@link encrypt} to bytes, using whichever keyring entry its `keyId`
99
+ * names. Throws a {@link CryptographyError}: `malformed-secret` or `unsupported-version` for a
100
+ * misshapen value, `secret-unavailable` when the keyring lacks the key, `authentication-failed` when
101
+ * any field was altered.
102
+ */
103
+ export declare function decryptBytes(value: EncryptedValue, keyring: Keyring): Promise<Uint8Array>;
104
+ /**
105
+ * Like {@link decryptBytes}, then decodes the result as UTF-8, keeping a leading U+FEFF so the text
106
+ * round-trips exactly; throws `invalid-text` if the bytes are not UTF-8.
107
+ */
108
+ export declare function decrypt(value: EncryptedValue, keyring: Keyring): Promise<string>;