@valbuild/mcp 0.154.1 → 0.154.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @valbuild/mcp
2
2
 
3
+ ## 0.154.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#1087](https://github.com/valbuild/val/pull/1087) [`9e085bc`](https://github.com/valbuild/val/commit/9e085bc2b2104ce2644b4a14948288c799a2ce82) Thanks [@freekh](https://github.com/freekh)! - **A published page no longer loads the Studio, TypeScript, sucrase or prettier.** A site's first request in a fresh server process (on Val's hosting, every request a cold isolate answers) used to evaluate all of Val's server: the Studio's embedded assets (about 22 MB), TypeScript (9 MB), sucrase and the MCP tools. A page only needs that when someone edits it. These now load when they are first used, by the Val API, a draft read, a save or an MCP call, and a visitor's page never loads them.
8
+
9
+ We measured this in a fresh Node process, with the TanStack example app built the way a deployed app is built and running as a deployed site does (`http` mode). The first request for a public page used to load 38.8 MB of modules, take about 1.06 s and leave 170 MB of heap in use. It now loads 5.3 MB, takes about 0.23 s and leaves 38 MB of heap. An isolate counts more than Node does, so treat these heap figures as a lower bound.
10
+
11
+ What changed for an app:
12
+
13
+ - `initValContent` (and `initValRsc` in `@valbuild/next`) no longer start Val's server when they are created. They start it on the first draft read.
14
+ - With TanStack Start, `initValServer` loads the server on its first request in `http` mode, which is what a deployed site runs in. In local development (`fs` mode) and memory mode it still starts with the app. Those modes need the newest build in a process to exist before the previous build answers a request.
15
+ - `initValMcp` from `@valbuild/tanstack/server` loads the MCP tools on the first MCP request. Its `valMcpMetadata` comes from the new `@valbuild/mcp/metadata` entry, which is small.
16
+ - `createPrettierFormatter` now also accepts a loader. **Update your `val.server.ts`** so prettier is loaded by the first save rather than by every page:
17
+
18
+ ```ts
19
+ // before
20
+ import prettier from "prettier";
21
+ formatter: createPrettierFormatter(prettier, { projectRoot: process.cwd() }),
22
+
23
+ // after
24
+ formatter: createPrettierFormatter(() => import("prettier"), {
25
+ projectRoot: process.cwd(),
26
+ }),
27
+ ```
28
+
29
+ Passing `prettier` itself still works.
30
+
31
+ - If your app serves MCP from a TanStack Start route, import the MCP SDK inside the handler (`await import("@modelcontextprotocol/server")`), not at the top of the file. TanStack Start's route tree imports every server route's module on every cold start.
32
+
33
+ - Updated dependencies [[`9e085bc`](https://github.com/valbuild/val/commit/9e085bc2b2104ce2644b4a14948288c799a2ce82), [`d90b9e2`](https://github.com/valbuild/val/commit/d90b9e2f856d4023821698cd22b4fbbab046c2ff)]:
34
+ - @valbuild/server@0.154.2
35
+ - @valbuild/core@0.154.2
36
+ - @valbuild/shared@0.154.2
37
+
3
38
  ## 0.154.1
4
39
 
5
40
  ### Patch Changes
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@valbuild/mcp/metadata`: the OAuth protected-resource document, without the
3
+ * tools.
4
+ *
5
+ * The package root brings Val's whole server with it (the tools run against
6
+ * its data layer), and a framework binding's `initValMcp` is imported by an
7
+ * app's MCP route, which a TanStack Start site's route tree imports on every
8
+ * cold start. The metadata handlers are the one part of `ValMcp` that has to
9
+ * exist synchronously, so they come from here, and the rest is loaded by the
10
+ * first MCP request.
11
+ */
12
+ export { createValMcpMetadata, valMcpMetadataOf, VAL_SCOPES_SUPPORTED, type ValMcpMetadataHandlers, } from "../valMcpMetadata.js";
@@ -33,6 +33,17 @@ export type ValMcpMetadataHandlers = {
33
33
  OPTIONS: (request: Request) => Response;
34
34
  };
35
35
  export declare function createValMcpMetadata(oauth: ValOAuthConfig, scopesSupported: string[]): ValMcpMetadataHandlers;
36
+ /** The scopes an MCP endpoint of Val's supports: read, and write. */
37
+ export declare const VAL_SCOPES_SUPPORTED: string[];
38
+ /**
39
+ * The metadata handlers `initValMcp` serves as `valMcpMetadata`: `null`
40
+ * without an `oauth` config, since a project that has not been told where to
41
+ * authorize must not publish a document claiming it knows.
42
+ *
43
+ * One function, so a framework binding that builds `ValMcp` lazily (to keep
44
+ * the tools out of a site's cold start) answers this the same way.
45
+ */
46
+ export declare function valMcpMetadataOf(oauth: ValOAuthConfig | undefined): ValMcpMetadataHandlers | null;
36
47
  /**
37
48
  * The `WWW-Authenticate` value for a refusal (RFC 6750 section 3, RFC 9728
38
49
  * section 5.1).
@@ -0,0 +1,264 @@
1
+ 'use strict';
2
+
3
+ function _toPrimitive(t, r) {
4
+ if ("object" != typeof t || !t) return t;
5
+ var e = t[Symbol.toPrimitive];
6
+ if (void 0 !== e) {
7
+ var i = e.call(t, r || "default");
8
+ if ("object" != typeof i) return i;
9
+ throw new TypeError("@@toPrimitive must return a primitive value.");
10
+ }
11
+ return ("string" === r ? String : Number)(t);
12
+ }
13
+
14
+ function _toPropertyKey(t) {
15
+ var i = _toPrimitive(t, "string");
16
+ return "symbol" == typeof i ? i : i + "";
17
+ }
18
+
19
+ function _defineProperty(e, r, t) {
20
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
21
+ value: t,
22
+ enumerable: !0,
23
+ configurable: !0,
24
+ writable: !0
25
+ }) : e[r] = t, e;
26
+ }
27
+
28
+ function ownKeys(e, r) {
29
+ var t = Object.keys(e);
30
+ if (Object.getOwnPropertySymbols) {
31
+ var o = Object.getOwnPropertySymbols(e);
32
+ r && (o = o.filter(function (r) {
33
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
34
+ })), t.push.apply(t, o);
35
+ }
36
+ return t;
37
+ }
38
+ function _objectSpread2(e) {
39
+ for (var r = 1; r < arguments.length; r++) {
40
+ var t = null != arguments[r] ? arguments[r] : {};
41
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
42
+ _defineProperty(e, r, t[r]);
43
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
44
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
45
+ });
46
+ }
47
+ return e;
48
+ }
49
+
50
+ /**
51
+ * The public surface of Val's server-side tool registry.
52
+ *
53
+ * Types only, deliberately: this file is the contract that the MCP hosts, the
54
+ * CLI's stdio transport and the tools themselves are all written against, and
55
+ * keeping it free of implementation means those can be built in any order
56
+ * without one of them owning the shape.
57
+ *
58
+ * The design this implements is `docs/plans/mcp.md`, Part A. Two constraints
59
+ * from it are load-bearing and easy to break by accident:
60
+ *
61
+ * 1. **Nothing here may import an MCP SDK.** That is what lets hosts other
62
+ * than the template consume these tools, and it is not hypothetical
63
+ * hygiene — the TypeScript SDK reorganised itself at v2.0.0, and a registry
64
+ * coupled to it would have moved with it.
65
+ * 2. **The result type is deliberately not MCP's `CallToolResult`.** Each host
66
+ * adapts {@link ValToolResult} at its own edge, which is also where an
67
+ * error becomes an in-band `isError` result the model can recover from
68
+ * rather than a transport failure.
69
+ */
70
+
71
+ /** Why a tool call failed, in a form a host can map onto its own errors. */
72
+
73
+ /**
74
+ * The same definition with `inputSchema` as JSON Schema, for hosts that want the
75
+ * wire shape rather than a Standard Schema.
76
+ *
77
+ * Typed as whatever zod's own converter produces, so deriving it needs no cast
78
+ * and no second hand-written description of the same input.
79
+ */
80
+
81
+ /**
82
+ * How the caller was established, and there is one acceptable answer: the host
83
+ * **checked a signature**.
84
+ *
85
+ * A union of one, deliberately. It carried a second variant — a personal access
86
+ * token relayed to the backend unchecked, on the reasoning that the app cannot
87
+ * resolve one and the backend can. The reasoning held; the shape did not. A
88
+ * credential the host cannot check is one it also cannot refuse, so accepting
89
+ * one made "a deployed endpoint that authenticates nobody" a supported
90
+ * configuration, and it let a host serve these tools without ever being told
91
+ * where callers should authorize. The discriminant stays so that adding a
92
+ * second *verified* kind stays a one-line change at every call site.
93
+ */
94
+
95
+ /**
96
+ * Who is calling, established once per request by the host.
97
+ *
98
+ * `null` means local fs mode, where there is no credential to hold and patches
99
+ * are written with no author, exactly as the Studio does locally (D.1). In
100
+ * proxy mode `null` is refused rather than falling back to the app's own API
101
+ * key: that key can do more than any single user, and quietly substituting it
102
+ * would turn a missing credential into full access.
103
+ */
104
+
105
+ /**
106
+ * Brand a verified subject as an {@link AuthorId}.
107
+ *
108
+ * `AuthorId` is a branded string so that an id cannot be conjured from any
109
+ * string that happens to be lying around — which is exactly the mistake this
110
+ * type is guarding against. That makes one assertion unavoidable at the boundary
111
+ * where a real id enters the system, so it lives here, once, with a name that
112
+ * says what makes it legitimate: the caller has *verified* this subject, not
113
+ * received it.
114
+ *
115
+ * Do not reach for this to satisfy a type. If you are holding a string you did
116
+ * not verify, the honest value is `null`.
117
+ */
118
+ function authorIdFromVerifiedSubject(subject) {
119
+ return subject;
120
+ }
121
+
122
+ /** Read access. Every call needs it, the writes included. */
123
+ var VAL_SCOPE_READ = "val:read";
124
+ /** Write access. Needed *in addition* by any tool not marked `readOnlyHint`. */
125
+ var VAL_SCOPE_WRITE = "val:write";
126
+
127
+ /**
128
+ * The failure half of {@link ValToolResult}, on its own.
129
+ *
130
+ * Named because several internal steps can only fail — speculative validation
131
+ * rejecting a patch, an upload that did not land — and typing those as the
132
+ * whole union means the compiler cannot see that an early return is in fact an
133
+ * error return.
134
+ */
135
+
136
+ /**
137
+ * The one document an MCP client needs before it can authorize: RFC 9728
138
+ * Protected Resource Metadata, served by the *resource* server.
139
+ *
140
+ * This is how a client discovers where to authorize. It asks the resource — this
141
+ * app — and the resource names its authorization server. Which is why this
142
+ * belongs here and the RFC 8414 *authorization server* metadata does not: that
143
+ * document lives at the issuer, describes the issuer's own endpoints, and is
144
+ * served by the issuer. An app serving a copy would be asserting the issuer's
145
+ * configuration on its behalf, and would be wrong the moment the issuer changed
146
+ * anything.
147
+ *
148
+ * The flow, so the split reads as a whole:
149
+ *
150
+ * 1. client → `{app}/api/mcp` with no token → `401` naming this document
151
+ * 2. client → `{app}/.well-known/oauth-protected-resource` → the issuer
152
+ * 3. client → `{issuer}/.well-known/oauth-authorization-server` → endpoints
153
+ * 4. client → issuer's `/authorize`, then `/token`
154
+ * 5. client → `{app}/api/mcp` with the token
155
+ */
156
+
157
+ var CORS_HEADERS = {
158
+ // The document is public and contains no secrets — it exists to be read by
159
+ // clients whose origin we cannot know in advance, so `*` is the correct value
160
+ // rather than a lazy one. Note there is no `Access-Control-Allow-Credentials`:
161
+ // with it, `*` would be rejected by browsers, and this document is never
162
+ // fetched with credentials.
163
+ "Access-Control-Allow-Origin": "*",
164
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
165
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, MCP-Protocol-Version",
166
+ "Access-Control-Max-Age": "3600"
167
+ };
168
+ function createValMcpMetadata(oauth, scopesSupported) {
169
+ var document = {
170
+ // The resource identifier, which MUST be the value clients send as
171
+ // `resource` and the value that arrives back in `aud`. Same string as the
172
+ // audience this app verifies against — one value, so the two cannot drift.
173
+ resource: oauth.resource,
174
+ authorization_servers: [oauth.issuer],
175
+ scopes_supported: scopesSupported,
176
+ bearer_methods_supported: ["header"]
177
+ };
178
+ var body = JSON.stringify(document);
179
+ return {
180
+ GET: function GET() {
181
+ return new Response(body, {
182
+ status: 200,
183
+ headers: _objectSpread2({
184
+ "Content-Type": "application/json",
185
+ // Cacheable: it changes only when the app is reconfigured, and a
186
+ // client that re-reads it on every authorization costs a round trip
187
+ // for nothing.
188
+ "Cache-Control": "public, max-age=3600"
189
+ }, CORS_HEADERS)
190
+ });
191
+ },
192
+ OPTIONS: function OPTIONS() {
193
+ return new Response(null, {
194
+ status: 204,
195
+ headers: CORS_HEADERS
196
+ });
197
+ }
198
+ };
199
+ }
200
+
201
+ /** The scopes an MCP endpoint of Val's supports: read, and write. */
202
+ var VAL_SCOPES_SUPPORTED = [VAL_SCOPE_READ, VAL_SCOPE_WRITE];
203
+
204
+ /**
205
+ * The metadata handlers `initValMcp` serves as `valMcpMetadata`: `null`
206
+ * without an `oauth` config, since a project that has not been told where to
207
+ * authorize must not publish a document claiming it knows.
208
+ *
209
+ * One function, so a framework binding that builds `ValMcp` lazily (to keep
210
+ * the tools out of a site's cold start) answers this the same way.
211
+ */
212
+ function valMcpMetadataOf(oauth) {
213
+ return oauth ? createValMcpMetadata(oauth, VAL_SCOPES_SUPPORTED) : null;
214
+ }
215
+
216
+ /**
217
+ * The `WWW-Authenticate` value for a refusal (RFC 6750 section 3, RFC 9728
218
+ * section 5.1).
219
+ *
220
+ * `resource_metadata` is the load-bearing parameter: it is how a client that has
221
+ * never seen this server learns where to authorize. A `401` without it is a dead
222
+ * end — the client knows it needs a token and has no way to find out from where.
223
+ */
224
+ function wwwAuthenticate(oauth, scopesSupported, refusal) {
225
+ var metadataUrl = new URL("/.well-known/oauth-protected-resource", oauth.resource).toString();
226
+ var params = ["resource_metadata=\"".concat(metadataUrl, "\""), "scope=\"".concat(scopesSupported.join(" "), "\"")];
227
+ if (refusal) {
228
+ params.push("error=\"".concat(refusal.error, "\""));
229
+ params.push("error_description=\"".concat(headerSafe(refusal.description), "\""));
230
+ }
231
+ return "Bearer ".concat(params.join(", "));
232
+ }
233
+
234
+ /**
235
+ * Make a string safe to put inside a quoted header parameter.
236
+ *
237
+ * Three classes go, and the third is the one that matters most:
238
+ *
239
+ * - a **quote** would close the parameter early;
240
+ * - a **backslash** would start an escape the rest of the value does not
241
+ * finish;
242
+ * - a **CR or LF** would end the header line, which is response splitting — an
243
+ * attacker-influenced description could inject a header of their own, or a
244
+ * whole second response.
245
+ *
246
+ * The descriptions passed here today are all literals from this package and
247
+ * contain none of it. That is a property of today's callers rather than of the
248
+ * type, and this function exists so it stays true when a future one interpolates
249
+ * something from a request.
250
+ */
251
+ function headerSafe(value) {
252
+ // eslint-disable-next-line no-control-regex -- the point is to remove them
253
+ return value.replace(/["\\]/g, "").replace(/[\u0000-\u001f\u007f]/g, " ");
254
+ }
255
+
256
+ exports.VAL_SCOPES_SUPPORTED = VAL_SCOPES_SUPPORTED;
257
+ exports.VAL_SCOPE_READ = VAL_SCOPE_READ;
258
+ exports.VAL_SCOPE_WRITE = VAL_SCOPE_WRITE;
259
+ exports._defineProperty = _defineProperty;
260
+ exports._objectSpread2 = _objectSpread2;
261
+ exports.authorIdFromVerifiedSubject = authorIdFromVerifiedSubject;
262
+ exports.createValMcpMetadata = createValMcpMetadata;
263
+ exports.valMcpMetadataOf = valMcpMetadataOf;
264
+ exports.wwwAuthenticate = wwwAuthenticate;
@@ -0,0 +1,264 @@
1
+ 'use strict';
2
+
3
+ function _toPrimitive(t, r) {
4
+ if ("object" != typeof t || !t) return t;
5
+ var e = t[Symbol.toPrimitive];
6
+ if (void 0 !== e) {
7
+ var i = e.call(t, r || "default");
8
+ if ("object" != typeof i) return i;
9
+ throw new TypeError("@@toPrimitive must return a primitive value.");
10
+ }
11
+ return ("string" === r ? String : Number)(t);
12
+ }
13
+
14
+ function _toPropertyKey(t) {
15
+ var i = _toPrimitive(t, "string");
16
+ return "symbol" == typeof i ? i : i + "";
17
+ }
18
+
19
+ function _defineProperty(e, r, t) {
20
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
21
+ value: t,
22
+ enumerable: !0,
23
+ configurable: !0,
24
+ writable: !0
25
+ }) : e[r] = t, e;
26
+ }
27
+
28
+ function ownKeys(e, r) {
29
+ var t = Object.keys(e);
30
+ if (Object.getOwnPropertySymbols) {
31
+ var o = Object.getOwnPropertySymbols(e);
32
+ r && (o = o.filter(function (r) {
33
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
34
+ })), t.push.apply(t, o);
35
+ }
36
+ return t;
37
+ }
38
+ function _objectSpread2(e) {
39
+ for (var r = 1; r < arguments.length; r++) {
40
+ var t = null != arguments[r] ? arguments[r] : {};
41
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
42
+ _defineProperty(e, r, t[r]);
43
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
44
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
45
+ });
46
+ }
47
+ return e;
48
+ }
49
+
50
+ /**
51
+ * The public surface of Val's server-side tool registry.
52
+ *
53
+ * Types only, deliberately: this file is the contract that the MCP hosts, the
54
+ * CLI's stdio transport and the tools themselves are all written against, and
55
+ * keeping it free of implementation means those can be built in any order
56
+ * without one of them owning the shape.
57
+ *
58
+ * The design this implements is `docs/plans/mcp.md`, Part A. Two constraints
59
+ * from it are load-bearing and easy to break by accident:
60
+ *
61
+ * 1. **Nothing here may import an MCP SDK.** That is what lets hosts other
62
+ * than the template consume these tools, and it is not hypothetical
63
+ * hygiene — the TypeScript SDK reorganised itself at v2.0.0, and a registry
64
+ * coupled to it would have moved with it.
65
+ * 2. **The result type is deliberately not MCP's `CallToolResult`.** Each host
66
+ * adapts {@link ValToolResult} at its own edge, which is also where an
67
+ * error becomes an in-band `isError` result the model can recover from
68
+ * rather than a transport failure.
69
+ */
70
+
71
+ /** Why a tool call failed, in a form a host can map onto its own errors. */
72
+
73
+ /**
74
+ * The same definition with `inputSchema` as JSON Schema, for hosts that want the
75
+ * wire shape rather than a Standard Schema.
76
+ *
77
+ * Typed as whatever zod's own converter produces, so deriving it needs no cast
78
+ * and no second hand-written description of the same input.
79
+ */
80
+
81
+ /**
82
+ * How the caller was established, and there is one acceptable answer: the host
83
+ * **checked a signature**.
84
+ *
85
+ * A union of one, deliberately. It carried a second variant — a personal access
86
+ * token relayed to the backend unchecked, on the reasoning that the app cannot
87
+ * resolve one and the backend can. The reasoning held; the shape did not. A
88
+ * credential the host cannot check is one it also cannot refuse, so accepting
89
+ * one made "a deployed endpoint that authenticates nobody" a supported
90
+ * configuration, and it let a host serve these tools without ever being told
91
+ * where callers should authorize. The discriminant stays so that adding a
92
+ * second *verified* kind stays a one-line change at every call site.
93
+ */
94
+
95
+ /**
96
+ * Who is calling, established once per request by the host.
97
+ *
98
+ * `null` means local fs mode, where there is no credential to hold and patches
99
+ * are written with no author, exactly as the Studio does locally (D.1). In
100
+ * proxy mode `null` is refused rather than falling back to the app's own API
101
+ * key: that key can do more than any single user, and quietly substituting it
102
+ * would turn a missing credential into full access.
103
+ */
104
+
105
+ /**
106
+ * Brand a verified subject as an {@link AuthorId}.
107
+ *
108
+ * `AuthorId` is a branded string so that an id cannot be conjured from any
109
+ * string that happens to be lying around — which is exactly the mistake this
110
+ * type is guarding against. That makes one assertion unavoidable at the boundary
111
+ * where a real id enters the system, so it lives here, once, with a name that
112
+ * says what makes it legitimate: the caller has *verified* this subject, not
113
+ * received it.
114
+ *
115
+ * Do not reach for this to satisfy a type. If you are holding a string you did
116
+ * not verify, the honest value is `null`.
117
+ */
118
+ function authorIdFromVerifiedSubject(subject) {
119
+ return subject;
120
+ }
121
+
122
+ /** Read access. Every call needs it, the writes included. */
123
+ var VAL_SCOPE_READ = "val:read";
124
+ /** Write access. Needed *in addition* by any tool not marked `readOnlyHint`. */
125
+ var VAL_SCOPE_WRITE = "val:write";
126
+
127
+ /**
128
+ * The failure half of {@link ValToolResult}, on its own.
129
+ *
130
+ * Named because several internal steps can only fail — speculative validation
131
+ * rejecting a patch, an upload that did not land — and typing those as the
132
+ * whole union means the compiler cannot see that an early return is in fact an
133
+ * error return.
134
+ */
135
+
136
+ /**
137
+ * The one document an MCP client needs before it can authorize: RFC 9728
138
+ * Protected Resource Metadata, served by the *resource* server.
139
+ *
140
+ * This is how a client discovers where to authorize. It asks the resource — this
141
+ * app — and the resource names its authorization server. Which is why this
142
+ * belongs here and the RFC 8414 *authorization server* metadata does not: that
143
+ * document lives at the issuer, describes the issuer's own endpoints, and is
144
+ * served by the issuer. An app serving a copy would be asserting the issuer's
145
+ * configuration on its behalf, and would be wrong the moment the issuer changed
146
+ * anything.
147
+ *
148
+ * The flow, so the split reads as a whole:
149
+ *
150
+ * 1. client → `{app}/api/mcp` with no token → `401` naming this document
151
+ * 2. client → `{app}/.well-known/oauth-protected-resource` → the issuer
152
+ * 3. client → `{issuer}/.well-known/oauth-authorization-server` → endpoints
153
+ * 4. client → issuer's `/authorize`, then `/token`
154
+ * 5. client → `{app}/api/mcp` with the token
155
+ */
156
+
157
+ var CORS_HEADERS = {
158
+ // The document is public and contains no secrets — it exists to be read by
159
+ // clients whose origin we cannot know in advance, so `*` is the correct value
160
+ // rather than a lazy one. Note there is no `Access-Control-Allow-Credentials`:
161
+ // with it, `*` would be rejected by browsers, and this document is never
162
+ // fetched with credentials.
163
+ "Access-Control-Allow-Origin": "*",
164
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
165
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, MCP-Protocol-Version",
166
+ "Access-Control-Max-Age": "3600"
167
+ };
168
+ function createValMcpMetadata(oauth, scopesSupported) {
169
+ var document = {
170
+ // The resource identifier, which MUST be the value clients send as
171
+ // `resource` and the value that arrives back in `aud`. Same string as the
172
+ // audience this app verifies against — one value, so the two cannot drift.
173
+ resource: oauth.resource,
174
+ authorization_servers: [oauth.issuer],
175
+ scopes_supported: scopesSupported,
176
+ bearer_methods_supported: ["header"]
177
+ };
178
+ var body = JSON.stringify(document);
179
+ return {
180
+ GET: function GET() {
181
+ return new Response(body, {
182
+ status: 200,
183
+ headers: _objectSpread2({
184
+ "Content-Type": "application/json",
185
+ // Cacheable: it changes only when the app is reconfigured, and a
186
+ // client that re-reads it on every authorization costs a round trip
187
+ // for nothing.
188
+ "Cache-Control": "public, max-age=3600"
189
+ }, CORS_HEADERS)
190
+ });
191
+ },
192
+ OPTIONS: function OPTIONS() {
193
+ return new Response(null, {
194
+ status: 204,
195
+ headers: CORS_HEADERS
196
+ });
197
+ }
198
+ };
199
+ }
200
+
201
+ /** The scopes an MCP endpoint of Val's supports: read, and write. */
202
+ var VAL_SCOPES_SUPPORTED = [VAL_SCOPE_READ, VAL_SCOPE_WRITE];
203
+
204
+ /**
205
+ * The metadata handlers `initValMcp` serves as `valMcpMetadata`: `null`
206
+ * without an `oauth` config, since a project that has not been told where to
207
+ * authorize must not publish a document claiming it knows.
208
+ *
209
+ * One function, so a framework binding that builds `ValMcp` lazily (to keep
210
+ * the tools out of a site's cold start) answers this the same way.
211
+ */
212
+ function valMcpMetadataOf(oauth) {
213
+ return oauth ? createValMcpMetadata(oauth, VAL_SCOPES_SUPPORTED) : null;
214
+ }
215
+
216
+ /**
217
+ * The `WWW-Authenticate` value for a refusal (RFC 6750 section 3, RFC 9728
218
+ * section 5.1).
219
+ *
220
+ * `resource_metadata` is the load-bearing parameter: it is how a client that has
221
+ * never seen this server learns where to authorize. A `401` without it is a dead
222
+ * end — the client knows it needs a token and has no way to find out from where.
223
+ */
224
+ function wwwAuthenticate(oauth, scopesSupported, refusal) {
225
+ var metadataUrl = new URL("/.well-known/oauth-protected-resource", oauth.resource).toString();
226
+ var params = ["resource_metadata=\"".concat(metadataUrl, "\""), "scope=\"".concat(scopesSupported.join(" "), "\"")];
227
+ if (refusal) {
228
+ params.push("error=\"".concat(refusal.error, "\""));
229
+ params.push("error_description=\"".concat(headerSafe(refusal.description), "\""));
230
+ }
231
+ return "Bearer ".concat(params.join(", "));
232
+ }
233
+
234
+ /**
235
+ * Make a string safe to put inside a quoted header parameter.
236
+ *
237
+ * Three classes go, and the third is the one that matters most:
238
+ *
239
+ * - a **quote** would close the parameter early;
240
+ * - a **backslash** would start an escape the rest of the value does not
241
+ * finish;
242
+ * - a **CR or LF** would end the header line, which is response splitting — an
243
+ * attacker-influenced description could inject a header of their own, or a
244
+ * whole second response.
245
+ *
246
+ * The descriptions passed here today are all literals from this package and
247
+ * contain none of it. That is a property of today's callers rather than of the
248
+ * type, and this function exists so it stays true when a future one interpolates
249
+ * something from a request.
250
+ */
251
+ function headerSafe(value) {
252
+ // eslint-disable-next-line no-control-regex -- the point is to remove them
253
+ return value.replace(/["\\]/g, "").replace(/[\u0000-\u001f\u007f]/g, " ");
254
+ }
255
+
256
+ exports.VAL_SCOPES_SUPPORTED = VAL_SCOPES_SUPPORTED;
257
+ exports.VAL_SCOPE_READ = VAL_SCOPE_READ;
258
+ exports.VAL_SCOPE_WRITE = VAL_SCOPE_WRITE;
259
+ exports._defineProperty = _defineProperty;
260
+ exports._objectSpread2 = _objectSpread2;
261
+ exports.authorIdFromVerifiedSubject = authorIdFromVerifiedSubject;
262
+ exports.createValMcpMetadata = createValMcpMetadata;
263
+ exports.valMcpMetadataOf = valMcpMetadataOf;
264
+ exports.wwwAuthenticate = wwwAuthenticate;