@lovable.dev/mcp-js 0.22.0 → 0.22.1-rc.1

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 (87) hide show
  1. package/dist/authorize-CumVyk7p.d.cts +27 -0
  2. package/dist/authorize-D6p4-9_D.d.ts +27 -0
  3. package/dist/base-DCe0kP79.d.cts +29 -0
  4. package/dist/base-DCe0kP79.d.ts +29 -0
  5. package/dist/cli/extract-manifest.cjs +116 -201
  6. package/dist/cli/extract-manifest.d.cts +1 -1
  7. package/dist/cli/extract-manifest.d.ts +1 -1
  8. package/dist/cli/extract-manifest.js +117 -156
  9. package/dist/content-D5LJAHyM.js +12 -0
  10. package/dist/content-NCYIGgOb.cjs +17 -0
  11. package/dist/context-BweeEcoA.cjs +56 -0
  12. package/dist/context-CIpPzN7P.js +51 -0
  13. package/dist/cors-BxwVxCm3.cjs +913 -0
  14. package/dist/cors-CJRL7tyh.js +830 -0
  15. package/dist/forwarded--h4efJy-.js +43 -0
  16. package/dist/forwarded-Pi8Hs5Ps.cjs +48 -0
  17. package/dist/fs-errors-CWNzOV75.cjs +11 -0
  18. package/dist/fs-errors-PA2t1TIp.js +6 -0
  19. package/dist/index.cjs +129 -329
  20. package/dist/index.d.cts +26 -26
  21. package/dist/index.d.ts +26 -26
  22. package/dist/index.js +118 -177
  23. package/dist/{io-D4srzRKc.d.ts → io-CfSPxeBN.d.ts} +6 -4
  24. package/dist/io-DPYvBqET.d.cts +15 -0
  25. package/dist/list-tools-B4TTPEl1.d.cts +8 -0
  26. package/dist/list-tools-Duj1zT0T.js +46 -0
  27. package/dist/list-tools-_Hh_o_mD.cjs +57 -0
  28. package/dist/list-tools-bh6-eqZM.d.ts +8 -0
  29. package/dist/logger-2OXtfiIW.js +141 -0
  30. package/dist/logger-BqPOa_E1.cjs +194 -0
  31. package/dist/mcp--iewDKrV.cjs +128 -0
  32. package/dist/mcp-CALHyhDi.js +123 -0
  33. package/dist/metadata-path-CAkNcfyY.js +12 -0
  34. package/dist/metadata-path-zd7NSNoa.cjs +17 -0
  35. package/dist/package-CLTXgGyU.cjs +9 -0
  36. package/dist/package-g7-GHkOW.js +4 -0
  37. package/dist/paths-IS65L6TA.js +7 -0
  38. package/dist/paths-OP318a6c.cjs +18 -0
  39. package/dist/protocols/mcp/index.cjs +3 -750
  40. package/dist/protocols/mcp/index.d.cts +6 -7
  41. package/dist/protocols/mcp/index.d.ts +6 -7
  42. package/dist/protocols/mcp/index.js +2 -12
  43. package/dist/protocols/oauth-metadata.cjs +48 -539
  44. package/dist/protocols/oauth-metadata.d.cts +5 -6
  45. package/dist/protocols/oauth-metadata.d.ts +5 -6
  46. package/dist/protocols/oauth-metadata.js +52 -10
  47. package/dist/protocols/rest/index.cjs +5 -843
  48. package/dist/protocols/rest/index.d.cts +7 -10
  49. package/dist/protocols/rest/index.d.ts +7 -10
  50. package/dist/protocols/rest/index.js +3 -16
  51. package/dist/rest-BcS3SYjx.cjs +122 -0
  52. package/dist/rest-Dv9Xq9cV.js +117 -0
  53. package/dist/stacks/supabase/index.cjs +76 -1318
  54. package/dist/stacks/supabase/index.d.cts +29 -30
  55. package/dist/stacks/supabase/index.d.ts +29 -30
  56. package/dist/stacks/supabase/index.js +73 -89
  57. package/dist/stacks/supabase/vite.cjs +258 -287
  58. package/dist/stacks/supabase/vite.d.cts +24 -24
  59. package/dist/stacks/supabase/vite.d.ts +24 -24
  60. package/dist/stacks/supabase/vite.js +252 -252
  61. package/dist/stacks/tanstack/index.cjs +42 -1272
  62. package/dist/stacks/tanstack/index.d.cts +8 -9
  63. package/dist/stacks/tanstack/index.d.ts +8 -9
  64. package/dist/stacks/tanstack/index.js +36 -41
  65. package/dist/stacks/tanstack/vite.cjs +223 -312
  66. package/dist/stacks/tanstack/vite.d.cts +80 -81
  67. package/dist/stacks/tanstack/vite.d.ts +80 -81
  68. package/dist/stacks/tanstack/vite.js +216 -282
  69. package/dist/types-BYdYYTjk.d.cts +321 -0
  70. package/dist/types-BYdYYTjk.d.ts +321 -0
  71. package/package.json +69 -28
  72. package/dist/authorize-BMeXd_Sh.d.ts +0 -25
  73. package/dist/base-CM-KCpp6.d.ts +0 -28
  74. package/dist/chunk-4EHZUUS5.js +0 -141
  75. package/dist/chunk-6DXGZZA4.js +0 -6
  76. package/dist/chunk-6KNM7RGD.js +0 -79
  77. package/dist/chunk-6QFZYYUV.js +0 -11
  78. package/dist/chunk-EOFPMSND.js +0 -6
  79. package/dist/chunk-H37EB22A.js +0 -125
  80. package/dist/chunk-MA5H6PSF.js +0 -46
  81. package/dist/chunk-P43FIUMZ.js +0 -114
  82. package/dist/chunk-RK62EMPY.js +0 -741
  83. package/dist/chunk-RLE4UE63.js +0 -58
  84. package/dist/chunk-UQK5UO6C.js +0 -26
  85. package/dist/chunk-XQWJN6DC.js +0 -14
  86. package/dist/chunk-Y3ZFPEQH.js +0 -8
  87. package/dist/types-qqrmJ736.d.ts +0 -321
@@ -1,750 +1,3 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/protocols/mcp/index.ts
21
- var mcp_exports = {};
22
- __export(mcp_exports, {
23
- createMcpProtocolHandler: () => createMcpProtocolHandler
24
- });
25
- module.exports = __toCommonJS(mcp_exports);
26
-
27
- // src/protocols/mcp/protocol.ts
28
- var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
29
- var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
30
-
31
- // src/core/http.ts
32
- var JSON_HEADERS = { "Content-Type": "application/json" };
33
-
34
- // src/core/logger.ts
35
- var LEVEL_RANK = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
36
- function isLogLevel(value) {
37
- return typeof value === "string" && value in LEVEL_RANK;
38
- }
39
- var LOG_LEVEL_ENV_VAR = "LOVABLE_MCP_LOG_LEVEL";
40
- function readEnvLevel() {
41
- try {
42
- const raw = typeof process !== "undefined" ? process.env?.[LOG_LEVEL_ENV_VAR] : void 0;
43
- const normalized = raw?.trim().toLowerCase();
44
- return isLogLevel(normalized) ? normalized : void 0;
45
- } catch {
46
- return void 0;
47
- }
48
- }
49
- var currentLevel = readEnvLevel() ?? "debug";
50
- function enabled(level) {
51
- return LEVEL_RANK[level] <= LEVEL_RANK[currentLevel];
52
- }
53
- function emit(level, method, event, fields) {
54
- if (!enabled(level))
55
- return;
56
- const message = `[mcp-js] ${event}`;
57
- if (fields)
58
- console[method](message, fields);
59
- else
60
- console[method](message);
61
- }
62
- var log = {
63
- error: (event, fields) => emit("error", "error", event, fields),
64
- warn: (event, fields) => emit("warn", "warn", event, fields),
65
- info: (event, fields) => emit("info", "info", event, fields),
66
- debug: (event, fields) => emit("debug", "debug", event, fields)
67
- };
68
- function describeError(err) {
69
- if (err instanceof Error) {
70
- const code = err.code;
71
- return { name: err.name, message: err.message, ...typeof code === "string" ? { code } : {} };
72
- }
73
- return { value: String(err) };
74
- }
75
-
76
- // src/metrics/impl/base.ts
77
- function nowMs() {
78
- return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
79
- }
80
- var NOOP_RECORDER = { async emit() {
81
- } };
82
- function createNoopRecorder() {
83
- return NOOP_RECORDER;
84
- }
85
-
86
- // src/core/promise.ts
87
- function cachedPromise(load, label) {
88
- let settled = false;
89
- let value;
90
- return async () => {
91
- if (settled) {
92
- if (label)
93
- log.debug(`${label}.cache_hit`);
94
- return value;
95
- }
96
- if (label)
97
- log.debug(`${label}.load_start`);
98
- try {
99
- const loaded = await load();
100
- settled = true;
101
- value = loaded;
102
- if (label)
103
- log.debug(`${label}.settled`);
104
- return loaded;
105
- } catch (err) {
106
- if (label)
107
- log.debug(`${label}.load_failed`, describeError(err));
108
- throw err;
109
- }
110
- };
111
- }
112
-
113
- // src/core/url.ts
114
- function trimTrailingSlash(value) {
115
- return value.replace(/\/+$/, "");
116
- }
117
- function isLocalHTTPHost(hostname) {
118
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
119
- }
120
- function urlSafetyProblem(url) {
121
- const isAllowedHTTP = url.protocol === "http:" && isLocalHTTPHost(url.hostname);
122
- if (url.protocol !== "https:" && !isAllowedHTTP) {
123
- return "must use https://, except localhost development URLs";
124
- }
125
- if (url.username || url.password) {
126
- return "must not include credentials";
127
- }
128
- if (url.search || url.hash) {
129
- return "must not include query or fragment";
130
- }
131
- return void 0;
132
- }
133
-
134
- // src/core/validation.ts
135
- function parseSafeUrl(subject, raw, ErrorClass = Error) {
136
- let url;
137
- try {
138
- url = new URL(raw);
139
- } catch {
140
- throw new ErrorClass(`${subject} must be an absolute URL`);
141
- }
142
- const problem = urlSafetyProblem(url);
143
- if (problem) {
144
- throw new ErrorClass(`${subject} ${problem}`);
145
- }
146
- return url;
147
- }
148
-
149
- // src/auth/discovery.ts
150
- var OAuthConfigurationError = class extends Error {
151
- constructor(message) {
152
- super(message);
153
- this.name = "OAuthConfigurationError";
154
- }
155
- };
156
- var METADATA_FETCH_TIMEOUT_MS = 5e3;
157
- function issuerPath(url) {
158
- const path = trimTrailingSlash(url.pathname);
159
- return path === "" ? void 0 : path;
160
- }
161
- function pathInsertedOAuthMetadataUrls(url, path) {
162
- return [
163
- `${url.origin}/.well-known/oauth-authorization-server${path}`,
164
- `${url.origin}/.well-known/openid-configuration${path}`
165
- ];
166
- }
167
- function oauthMetadataUrlsForIssuer(issuer) {
168
- const normalizedIssuer = trimTrailingSlash(issuer);
169
- const url = new URL(normalizedIssuer);
170
- const path = issuerPath(url);
171
- if (!path) {
172
- return [
173
- `${normalizedIssuer}/.well-known/oauth-authorization-server`,
174
- `${normalizedIssuer}/.well-known/openid-configuration`
175
- ];
176
- }
177
- return [...pathInsertedOAuthMetadataUrls(url, path), `${normalizedIssuer}/.well-known/openid-configuration`];
178
- }
179
- async function fetchFirstValidOAuthServerMetadata(metadataUrls, expectedIssuer) {
180
- const errors = [];
181
- for (const url of metadataUrls) {
182
- try {
183
- return await fetchOAuthServerMetadata(url, expectedIssuer);
184
- } catch (err) {
185
- log.debug("oauth.discovery.attempt_failed", { url, ...describeError(err) });
186
- errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
187
- }
188
- }
189
- log.error("oauth.discovery.exhausted", { expectedIssuer, urlsTried: metadataUrls, errors });
190
- throw new Error(`failed to discover OAuth server metadata (${errors.join("; ")})`);
191
- }
192
- async function fetchOAuthServerMetadata(url, expectedIssuer) {
193
- log.debug("oauth.discovery.fetch", { url });
194
- const response = await fetch(url, { signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS), redirect: "manual" });
195
- if (!response.ok) {
196
- throw new Error(String(response.status));
197
- }
198
- const json = await response.json();
199
- if (typeof json.issuer !== "string") {
200
- throw new Error("missing issuer");
201
- }
202
- parseSafeUrl("discovered issuer", json.issuer);
203
- if (trimTrailingSlash(json.issuer) !== expectedIssuer) {
204
- log.warn("oauth.discovery.issuer_mismatch", { url, expectedIssuer, published: json.issuer });
205
- throw new Error("issuer mismatch");
206
- }
207
- if (typeof json.jwks_uri !== "string") {
208
- throw new Error("missing jwks_uri");
209
- }
210
- parseSafeUrl("discovered jwks_uri", json.jwks_uri);
211
- return { issuer: json.issuer, jwks_uri: json.jwks_uri };
212
- }
213
- async function fetchIssuerOAuthServerMetadata(issuer) {
214
- try {
215
- return await fetchFirstValidOAuthServerMetadata(oauthMetadataUrlsForIssuer(issuer), issuer);
216
- } catch (err) {
217
- log.error("oauth.discovery.config_error", {
218
- issuer,
219
- ...describeError(err),
220
- outcome: "500 oauth configuration error"
221
- });
222
- throw new OAuthConfigurationError(
223
- `OAuth issuer discovery failed: ${err instanceof Error ? err.message : String(err)}`
224
- );
225
- }
226
- }
227
- function createOAuthDiscoveryResolver(auth) {
228
- const configuredIssuer = trimTrailingSlash(auth.issuer);
229
- const oauthServerMetadata = cachedPromise(
230
- () => fetchIssuerOAuthServerMetadata(configuredIssuer),
231
- "oauth.discovery.metadata"
232
- );
233
- return {
234
- resolveIssuer: async () => configuredIssuer,
235
- resolveJwksUri: async () => {
236
- if (auth.jwksUri) {
237
- log.debug("oauth.jwks.resolved", { jwksUri: auth.jwksUri, source: "configured" });
238
- return auth.jwksUri;
239
- }
240
- const jwksUri = (await oauthServerMetadata()).jwks_uri;
241
- log.debug("oauth.jwks.resolved", { jwksUri, source: "discovered" });
242
- return jwksUri;
243
- }
244
- };
245
- }
246
-
247
- // src/auth/metadata-path.ts
248
- var OAUTH_PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
249
-
250
- // src/auth/resource.ts
251
- function resolveProtectedResource(auth, request, options) {
252
- if (auth.resource)
253
- return trimTrailingSlash(auth.resource);
254
- const path = resolveResourcePath(options.resourcePath, request);
255
- const resourceURL = new URL(path, request.url);
256
- resourceURL.search = "";
257
- resourceURL.hash = "";
258
- return trimTrailingSlash(resourceURL.toString());
259
- }
260
- function assertResourcePathShape(resourcePath, label = "resourcePath") {
261
- if (!resourcePath.startsWith("/") || resourcePath.startsWith("//") || resourcePath.includes("\\") || /(^|\/)\.\.(\/|$)/.test(resourcePath)) {
262
- throw new Error(
263
- `@lovable.dev/mcp-js: ${label} must be an absolute path beginning with "/" without ".." segments or backslashes (got ${JSON.stringify(resourcePath)})`
264
- );
265
- }
266
- }
267
- function resolveResourcePath(resourcePath, request) {
268
- if (resourcePath === void 0)
269
- return new URL(request.url).pathname;
270
- assertResourcePathShape(resourcePath);
271
- return resourcePath;
272
- }
273
-
274
- // src/auth/verifier.ts
275
- var import_jose = require("jose");
276
-
277
- // src/auth/claims.ts
278
- function readString(value) {
279
- return typeof value === "string" ? value : void 0;
280
- }
281
- function splitScopes(value) {
282
- if (typeof value === "string")
283
- return value.split(/\s+/).filter(Boolean);
284
- return stringClaimList(value);
285
- }
286
- function stringClaim(claims, name) {
287
- return readString(claims[name]);
288
- }
289
- function stringClaimList(value) {
290
- if (typeof value === "string")
291
- return value === "" ? [] : [value];
292
- if (Array.isArray(value))
293
- return value.filter((entry) => typeof entry === "string" && entry !== "");
294
- return [];
295
- }
296
-
297
- // src/auth/verifier.ts
298
- var DEFAULT_JWT_ALGORITHMS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "EdDSA"];
299
- var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
300
- var DEFAULT_ACCESS_TOKEN_TYPS = ["at+jwt", "JWT"];
301
- var JWKS_FETCH_TIMEOUT_MS = 5e3;
302
- var OAuthTokenError = class extends Error {
303
- constructor(status, oauthError, message) {
304
- super(message);
305
- this.status = status;
306
- this.oauthError = oauthError;
307
- this.name = "OAuthTokenError";
308
- }
309
- };
310
- function resolveAcceptedAudiences(auth, resource) {
311
- return auth.acceptedAudiences ?? [resource];
312
- }
313
- function tokenHeaderFields(token) {
314
- try {
315
- const header = (0, import_jose.decodeProtectedHeader)(token);
316
- return { jwtAlg: header.alg, jwtKid: header.kid, tokenLength: token.length };
317
- } catch {
318
- return { tokenLength: token.length };
319
- }
320
- }
321
- async function fetchVerificationKeySet(jwksUri) {
322
- try {
323
- const response = await fetch(jwksUri, { signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS), redirect: "manual" });
324
- if (!response.ok)
325
- throw new Error(`JWKS endpoint returned ${response.status}`);
326
- const json = await response.json();
327
- return (0, import_jose.createLocalJWKSet)(json);
328
- } catch (err) {
329
- log.error("oauth.jwks.fetch_failed", { ...describeError(err), outcome: "500 oauth configuration error" });
330
- throw new OAuthConfigurationError(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`);
331
- }
332
- }
333
- function assertAccessTokenTyp(token, allowed) {
334
- let header;
335
- try {
336
- header = (0, import_jose.decodeProtectedHeader)(token);
337
- } catch (err) {
338
- log.debug("oauth.verify.bad_header", { ...describeError(err), outcome: "401 invalid_token" });
339
- throw new OAuthTokenError(401, "invalid_token", "Malformed JWT header");
340
- }
341
- const typ = header.typ;
342
- if (typeof typ !== "string" || !allowed.includes(typ)) {
343
- log.debug("oauth.verify.bad_typ", { jwtTyp: typ, allowed, outcome: "401 invalid_token" });
344
- throw new OAuthTokenError(401, "invalid_token", "Access token typ header is not accepted");
345
- }
346
- }
347
- async function verifyJwtClaims(token, keySet, issuer, auth) {
348
- try {
349
- const { payload } = await (0, import_jose.jwtVerify)(token, keySet, {
350
- // `issuer` is trimmed of any trailing slash; accept both forms so a token whose
351
- // `iss` carries the slash the AS publishes still verifies.
352
- issuer: [issuer, `${issuer}/`],
353
- algorithms: auth.algorithms ? [...auth.algorithms] : DEFAULT_JWT_ALGORITHMS,
354
- requiredClaims: ["sub", "exp"],
355
- clockTolerance: auth.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
356
- });
357
- return payload;
358
- } catch (err) {
359
- log.debug("oauth.verify.rejected", { ...describeError(err), outcome: "401 invalid_token" });
360
- throw err;
361
- }
362
- }
363
- function checkAcceptedAudience(claims, accepted, auth) {
364
- const audPopulated = claims.aud !== void 0 && !(Array.isArray(claims.aud) && claims.aud.length === 0);
365
- if (audPopulated) {
366
- if (stringClaimList(claims.aud).some((audience) => accepted.includes(audience)))
367
- return "aud";
368
- log.debug("oauth.verify.bad_audience", { tokenAud: claims.aud, accepted, outcome: "401 invalid_token" });
369
- } else if (auth.acceptResourceClaim !== false) {
370
- const acceptedTrimmed = accepted.map(trimTrailingSlash);
371
- if (stringClaimList(claims.resource).some((resource) => acceptedTrimmed.includes(trimTrailingSlash(resource))))
372
- return "resource";
373
- log.debug("oauth.verify.bad_resource", { tokenResource: claims.resource, accepted, outcome: "401 invalid_token" });
374
- } else {
375
- log.debug("oauth.verify.empty_audience", { accepted, outcome: "401 invalid_token" });
376
- }
377
- throw new OAuthTokenError(401, "invalid_token", "token audience is not accepted");
378
- }
379
- function assertNonEmptySubject(claims) {
380
- const sub = claims["sub"];
381
- if (typeof sub !== "string" || sub.trim() === "") {
382
- log.debug("oauth.verify.bad_subject", { subType: typeof sub });
383
- throw new OAuthTokenError(401, "invalid_token", "token subject claim must be a non-empty string");
384
- }
385
- }
386
- function assertOAuthClientClaim(auth, clientId) {
387
- if (auth.requireOAuthClientClaim !== false && !clientId) {
388
- log.debug("oauth.verify.missing_client_claim", { outcome: "401 invalid_token" });
389
- throw new OAuthTokenError(401, "invalid_token", "OAuth client claim is required");
390
- }
391
- }
392
- function makeBearer(token) {
393
- return Object.defineProperty({}, "token", { value: token, enumerable: false });
394
- }
395
- function buildMcpAuthContext(args) {
396
- const { claims } = args;
397
- return {
398
- type: "oauth",
399
- principal: {
400
- claims,
401
- issuer: args.issuer,
402
- resource: args.resource,
403
- acceptedAudiences: args.acceptedAudiences,
404
- scopes: splitScopes(claims.scope),
405
- sub: stringClaim(claims, "sub"),
406
- email: stringClaim(claims, "email"),
407
- clientId: stringClaim(claims, "client_id") ?? stringClaim(claims, "azp")
408
- },
409
- bearer: makeBearer(args.token)
410
- };
411
- }
412
- function createOAuthTokenVerifier(auth, discovery) {
413
- const allowedTyps = auth.accessTokenTyp ?? DEFAULT_ACCESS_TOKEN_TYPS;
414
- return async (token, request, options) => {
415
- const resource = resolveProtectedResource(auth, request, options);
416
- const issuer = await discovery.resolveIssuer();
417
- const acceptedAudiences = resolveAcceptedAudiences(auth, resource);
418
- log.debug("oauth.verify.start", { issuer, acceptedAudiences, resource, ...tokenHeaderFields(token) });
419
- const jwksUri = await discovery.resolveJwksUri();
420
- log.debug("oauth.jwks.fetch", { jwksUri });
421
- const keySet = await fetchVerificationKeySet(jwksUri);
422
- assertAccessTokenTyp(token, allowedTyps);
423
- const claims = await verifyJwtClaims(token, keySet, issuer, auth);
424
- const audienceVia = checkAcceptedAudience(claims, acceptedAudiences, auth);
425
- assertNonEmptySubject(claims);
426
- const context = buildMcpAuthContext({ token, claims, issuer, resource, acceptedAudiences });
427
- assertOAuthClientClaim(auth, context.principal.clientId);
428
- log.info("oauth.verify.ok", {
429
- sub: context.principal.sub,
430
- clientId: context.principal.clientId,
431
- scopes: context.principal.scopes,
432
- audienceVia
433
- });
434
- return context;
435
- };
436
- }
437
-
438
- // src/auth/authorize.ts
439
- function quoteAuthenticateParam(value) {
440
- const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, "");
441
- return `"${sanitized.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
442
- }
443
- function resolveProtectedResourceMetadataUrl(auth, request, options) {
444
- if (auth.protectedResourceMetadataUrl !== void 0)
445
- return auth.protectedResourceMetadataUrl;
446
- const base = auth.resource ?? request.url;
447
- return new URL(options.metadataPath ?? OAUTH_PROTECTED_RESOURCE_METADATA_PATH, base).toString();
448
- }
449
- function wwwAuthenticateHeader(auth, request, options, params = {}) {
450
- const values = [
451
- `realm=${quoteAuthenticateParam("mcp")}`,
452
- `resource_metadata=${quoteAuthenticateParam(resolveProtectedResourceMetadataUrl(auth, request, options))}`
453
- ];
454
- if (auth.requiredScopes && auth.requiredScopes.length > 0) {
455
- values.push(`scope=${quoteAuthenticateParam(auth.requiredScopes.join(" "))}`);
456
- }
457
- if (params.error)
458
- values.push(`error=${quoteAuthenticateParam(params.error)}`);
459
- if (params.errorDescription)
460
- values.push(`error_description=${quoteAuthenticateParam(params.errorDescription)}`);
461
- return `Bearer ${values.join(", ")}`;
462
- }
463
- function challengeResponse(auth, request, options, status, oauthError, errorDescription) {
464
- const headers = new Headers(JSON_HEADERS);
465
- headers.set(
466
- "WWW-Authenticate",
467
- wwwAuthenticateHeader(auth, request, options, { error: oauthError, errorDescription })
468
- );
469
- headers.set("Cache-Control", "no-store");
470
- return new Response(JSON.stringify({ error: status === 403 ? "forbidden" : "unauthorized" }), {
471
- status,
472
- headers
473
- });
474
- }
475
- function oauthConfigurationErrorResponse() {
476
- return new Response(JSON.stringify({ error: "oauth configuration error" }), {
477
- status: 500,
478
- headers: { ...JSON_HEADERS, "Cache-Control": "no-store" }
479
- });
480
- }
481
- function parseBearerToken(request) {
482
- const header = request.headers.get("Authorization");
483
- if (!header)
484
- return void 0;
485
- const match = /^Bearer\s+(.+)$/i.exec(header.trim());
486
- if (!match)
487
- return void 0;
488
- const token = match[1].trim();
489
- if (token === "" || /\s/.test(token))
490
- return void 0;
491
- return token;
492
- }
493
- function getOAuthRuntime(mcp, options = {}) {
494
- if (options.resourcePath !== void 0)
495
- assertResourcePathShape(options.resourcePath);
496
- if (options.metadataPath !== void 0)
497
- assertResourcePathShape(options.metadataPath, "metadataPath");
498
- const stableOptions = { resourcePath: options.resourcePath, metadataPath: options.metadataPath };
499
- const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
500
- if (!auth)
501
- return { kind: "unconfigured", options: stableOptions };
502
- if (options.metadataPath !== void 0 && auth.protectedResourceMetadataUrl !== void 0) {
503
- throw new Error(
504
- `@lovable.dev/mcp-js: the Vite plugin generates protected-resource metadata (metadataPath set), so auth.protectedResourceMetadataUrl must not also be set. Drop protectedResourceMetadataUrl, or set protectedResourceMetadataRoute: false in mcpPlugin(...) to host the document yourself.`
505
- );
506
- }
507
- const discovery = createOAuthDiscoveryResolver(auth);
508
- return {
509
- kind: "configured",
510
- auth,
511
- discovery,
512
- verify: createOAuthTokenVerifier(auth, discovery),
513
- options: stableOptions
514
- };
515
- }
516
- function missingRequiredScopes(auth, scopes) {
517
- const requiredScopes = auth.requiredScopes ?? [];
518
- if (requiredScopes.length === 0)
519
- return [];
520
- const granted = new Set(scopes);
521
- return requiredScopes.filter((scope) => !granted.has(scope));
522
- }
523
- function assertRequiredScopes(auth, context) {
524
- if (missingRequiredScopes(auth, context.principal.scopes).length > 0) {
525
- throw new OAuthTokenError(403, "insufficient_scope", "Additional OAuth scope is required");
526
- }
527
- }
528
- function createRequestAuthorizer(mcp, options = {}) {
529
- const runtime = getOAuthRuntime(mcp, options);
530
- return {
531
- async authorize(request, recorder) {
532
- if (runtime.kind === "unconfigured")
533
- return { ok: true };
534
- const startedAt = nowMs();
535
- const token = parseBearerToken(request);
536
- if (!token) {
537
- log.info("auth.no_bearer_token", { outcome: "401" });
538
- return { ok: false, response: challengeResponse(runtime.auth, request, runtime.options, 401) };
539
- }
540
- try {
541
- const auth = await runtime.verify(token, request, runtime.options);
542
- assertRequiredScopes(runtime.auth, auth);
543
- return { ok: true, auth };
544
- } catch (err) {
545
- if (err instanceof OAuthConfigurationError) {
546
- log.error("auth.config_error", { ...describeError(err), outcome: "500" });
547
- await recorder?.emit({
548
- tool: null,
549
- method: "authorize",
550
- outcome: "auth_config_error",
551
- durationMs: nowMs() - startedAt
552
- });
553
- return { ok: false, response: oauthConfigurationErrorResponse() };
554
- }
555
- if (err instanceof OAuthTokenError) {
556
- log.info("auth.token_rejected", { status: err.status, oauthError: err.oauthError });
557
- return {
558
- ok: false,
559
- response: challengeResponse(
560
- runtime.auth,
561
- request,
562
- runtime.options,
563
- err.status,
564
- err.oauthError,
565
- err.message
566
- )
567
- };
568
- }
569
- log.error("auth.unexpected_error", { ...describeError(err), outcome: "401" });
570
- return {
571
- ok: false,
572
- response: challengeResponse(
573
- runtime.auth,
574
- request,
575
- runtime.options,
576
- 401,
577
- "invalid_token",
578
- "Invalid access token"
579
- )
580
- };
581
- }
582
- }
583
- };
584
- }
585
-
586
- // src/auth/context.ts
587
- var ToolContext = class {
588
- #auth;
589
- constructor(auth) {
590
- this.#auth = auth;
591
- }
592
- /** Whether the in-flight tool call carries a verified auth context. */
593
- isAuthenticated() {
594
- return this.#auth !== void 0;
595
- }
596
- /** The verified bearer token, or `undefined` when unauthenticated. Pass it to downstream APIs; never return or log it. */
597
- getToken() {
598
- return this.#auth?.bearer.token;
599
- }
600
- /** The verified user id (the token `sub`), or `undefined`. */
601
- getUserId() {
602
- return this.#auth?.principal.sub;
603
- }
604
- /** The verified user email, or `undefined` when absent. */
605
- getUserEmail() {
606
- return this.#auth?.principal.email;
607
- }
608
- /** The verified OAuth `client_id`, or `undefined`. */
609
- getClientId() {
610
- return this.#auth?.principal.clientId;
611
- }
612
- /** The verified OAuth scopes, or `undefined` when unauthenticated. */
613
- getScopes() {
614
- return this.#auth?.principal.scopes;
615
- }
616
- /** The verified token issuer, or `undefined`. */
617
- getIssuer() {
618
- return this.#auth?.principal.issuer;
619
- }
620
- /**
621
- * The full verified JWT claims, or `undefined`. Use this for app/business
622
- * authorization on issuer-specific claims that have no dedicated accessor.
623
- */
624
- getClaims() {
625
- return this.#auth?.principal.claims;
626
- }
627
- };
628
-
629
- // src/core/content.ts
630
- function extractTextContent(content) {
631
- if (!content)
632
- return void 0;
633
- const text = content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
634
- return text.length > 0 ? text : void 0;
635
- }
636
-
637
- // src/core/cors.ts
638
- var EXPOSE_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
639
- var ALLOW_HEADERS = "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID";
640
- function withCors(response) {
641
- response.headers.set("Access-Control-Allow-Origin", "*");
642
- response.headers.set("Access-Control-Expose-Headers", EXPOSE_HEADERS);
643
- return response;
644
- }
645
- function corsPreflightResponse(allowMethods) {
646
- return new Response(null, {
647
- status: 204,
648
- headers: {
649
- "Access-Control-Allow-Origin": "*",
650
- "Access-Control-Allow-Methods": allowMethods,
651
- "Access-Control-Allow-Headers": ALLOW_HEADERS,
652
- "Access-Control-Max-Age": "86400"
653
- }
654
- });
655
- }
656
-
657
- // src/protocols/mcp/protocol.ts
658
- function adaptToolToSdkCallback(tool, auth, recorder) {
659
- const endUserId = auth?.principal.sub;
660
- return async (first) => {
661
- const args = tool.inputSchema ? first ?? {} : {};
662
- const start = nowMs();
663
- let result;
664
- try {
665
- result = await tool.handler(args, new ToolContext(auth));
666
- } catch {
667
- await recorder.emit({
668
- tool: tool.name,
669
- method: "tools/call",
670
- outcome: "handler_error",
671
- durationMs: nowMs() - start,
672
- endUserId
673
- });
674
- return { content: [{ type: "text", text: "tool execution failed" }], isError: true };
675
- }
676
- if (result == null) {
677
- await recorder.emit({
678
- tool: tool.name,
679
- method: "tools/call",
680
- outcome: "handler_error",
681
- durationMs: nowMs() - start,
682
- endUserId
683
- });
684
- return { content: [{ type: "text", text: `tool "${tool.name}" returned no result` }], isError: true };
685
- }
686
- await recorder.emit({
687
- tool: tool.name,
688
- method: "tools/call",
689
- outcome: result.isError ? "tool_error" : "ok",
690
- durationMs: nowMs() - start,
691
- errorText: result.isError ? extractTextContent(result.content) : void 0,
692
- endUserId
693
- });
694
- return { content: result.content ?? [], structuredContent: result.structuredContent, isError: result.isError };
695
- };
696
- }
697
- function createMcpProtocolHandler(mcp, options = {}) {
698
- const authorizer = createRequestAuthorizer(mcp, options);
699
- const handle = async (request, recorder) => {
700
- const authResult = await authorizer.authorize(request, recorder);
701
- if (!authResult.ok)
702
- return authResult.response;
703
- try {
704
- const server = new import_mcp.McpServer(
705
- { name: mcp.name, version: mcp.version, title: mcp.title },
706
- { instructions: mcp.instructions }
707
- );
708
- for (const tool of mcp.tools) {
709
- server.registerTool(
710
- tool.name,
711
- {
712
- title: tool.title,
713
- description: tool.description,
714
- inputSchema: tool.inputSchema,
715
- outputSchema: tool.outputSchema,
716
- annotations: tool.annotations
717
- },
718
- adaptToolToSdkCallback(tool, authResult.auth, recorder)
719
- );
720
- }
721
- const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
722
- sessionIdGenerator: void 0
723
- });
724
- await server.connect(transport);
725
- return await transport.handleRequest(request);
726
- } catch (err) {
727
- await recorder.emit({
728
- tool: null,
729
- method: "transport",
730
- outcome: "transport_error",
731
- durationMs: 0,
732
- endUserId: authResult.auth?.principal.sub
733
- });
734
- log.error("mcp.transport_error", { ...describeError(err), outcome: "500 internal error" });
735
- return Response.json(
736
- { jsonrpc: "2.0", id: null, error: { code: -32603, message: "internal error" } },
737
- { status: 500 }
738
- );
739
- }
740
- };
741
- return async (request, recorder = createNoopRecorder()) => {
742
- if (request.method === "OPTIONS")
743
- return corsPreflightResponse("GET, POST, DELETE, OPTIONS");
744
- return withCors(await handle(request, recorder));
745
- };
746
- }
747
- // Annotate the CommonJS export names for ESM import in node:
748
- 0 && (module.exports = {
749
- createMcpProtocolHandler
750
- });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_mcp = require("../../mcp--iewDKrV.cjs");
3
+ exports.createMcpProtocolHandler = require_mcp.createMcpProtocolHandler;