@lovable.dev/mcp-js 0.9.4 → 0.10.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.
- package/README.internal.md +15 -8
- package/README.md +50 -1
- package/dist/chunk-D6KB4Q7R.js +6 -0
- package/dist/{chunk-OXSSMKQE.js → chunk-DF3DD3KD.js} +1 -1
- package/dist/{chunk-YQBOGY7D.js → chunk-LAFJDJRY.js} +1 -0
- package/dist/{chunk-2RGXCDBU.js → chunk-PJXKJNSZ.js} +1 -1
- package/dist/{chunk-6N7B7NZY.js → chunk-SZLSAGDF.js} +1 -1
- package/dist/{chunk-4JO3BZQG.js → chunk-X7V2CL7C.js} +1 -1
- package/dist/chunk-XQWJN6DC.js +14 -0
- package/dist/cli/extract-manifest.cjs +1 -1
- package/dist/cli/extract-manifest.js +6 -6
- package/dist/io-D4srzRKc.d.ts +13 -0
- package/dist/protocols/mcp/index.js +2 -2
- package/dist/protocols/oauth-metadata.js +2 -2
- package/dist/protocols/rest/index.js +4 -4
- package/dist/stacks/supabase/index.cjs +950 -0
- package/dist/stacks/supabase/index.d.cts +39 -0
- package/dist/stacks/supabase/index.d.ts +39 -0
- package/dist/stacks/supabase/index.js +95 -0
- package/dist/stacks/supabase/vite.cjs +263 -0
- package/dist/stacks/supabase/vite.d.cts +47 -0
- package/dist/stacks/supabase/vite.d.ts +47 -0
- package/dist/stacks/supabase/vite.js +229 -0
- package/dist/stacks/tanstack/index.js +6 -6
- package/dist/stacks/tanstack/vite.d.cts +2 -13
- package/dist/stacks/tanstack/vite.d.ts +2 -13
- package/dist/stacks/tanstack/vite.js +3 -3
- package/package.json +26 -11
|
@@ -0,0 +1,950 @@
|
|
|
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/stacks/supabase/index.ts
|
|
21
|
+
var supabase_exports = {};
|
|
22
|
+
__export(supabase_exports, {
|
|
23
|
+
createSupabaseHandler: () => createSupabaseHandler
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(supabase_exports);
|
|
26
|
+
|
|
27
|
+
// src/auth/metadata-path.ts
|
|
28
|
+
var OAUTH_PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
29
|
+
|
|
30
|
+
// src/core/url.ts
|
|
31
|
+
function trimTrailingSlash(value) {
|
|
32
|
+
return value.replace(/\/+$/, "");
|
|
33
|
+
}
|
|
34
|
+
function isLocalHTTPHost(hostname) {
|
|
35
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
36
|
+
}
|
|
37
|
+
function urlSafetyProblem(url) {
|
|
38
|
+
const isAllowedHTTP = url.protocol === "http:" && isLocalHTTPHost(url.hostname);
|
|
39
|
+
if (url.protocol !== "https:" && !isAllowedHTTP) {
|
|
40
|
+
return "must use https://, except localhost development URLs";
|
|
41
|
+
}
|
|
42
|
+
if (url.username || url.password) {
|
|
43
|
+
return "must not include credentials";
|
|
44
|
+
}
|
|
45
|
+
if (url.search || url.hash) {
|
|
46
|
+
return "must not include query or fragment";
|
|
47
|
+
}
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/auth/resource.ts
|
|
52
|
+
function resolveProtectedResource(auth, request, options) {
|
|
53
|
+
if (auth.resource)
|
|
54
|
+
return trimTrailingSlash(auth.resource);
|
|
55
|
+
const path = resolveResourcePath(options.resourcePath, request);
|
|
56
|
+
const resourceURL = new URL(path, request.url);
|
|
57
|
+
resourceURL.search = "";
|
|
58
|
+
resourceURL.hash = "";
|
|
59
|
+
return trimTrailingSlash(resourceURL.toString());
|
|
60
|
+
}
|
|
61
|
+
function assertResourcePathShape(resourcePath, label = "resourcePath") {
|
|
62
|
+
if (!resourcePath.startsWith("/") || resourcePath.startsWith("//") || resourcePath.includes("\\") || /(^|\/)\.\.(\/|$)/.test(resourcePath)) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`@lovable.dev/mcp-js: ${label} must be an absolute path beginning with "/" without ".." segments or backslashes (got ${JSON.stringify(resourcePath)})`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function resolveResourcePath(resourcePath, request) {
|
|
69
|
+
if (resourcePath === void 0)
|
|
70
|
+
return new URL(request.url).pathname;
|
|
71
|
+
assertResourcePathShape(resourcePath);
|
|
72
|
+
return resourcePath;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/protocols/mcp/protocol.ts
|
|
76
|
+
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
77
|
+
var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
|
|
78
|
+
|
|
79
|
+
// src/core/http.ts
|
|
80
|
+
var JSON_HEADERS = { "Content-Type": "application/json" };
|
|
81
|
+
function headResponse(response) {
|
|
82
|
+
return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
83
|
+
}
|
|
84
|
+
function methodNotAllowed(allow) {
|
|
85
|
+
return new Response(JSON.stringify({ error: "method not allowed" }), {
|
|
86
|
+
status: 405,
|
|
87
|
+
headers: { ...JSON_HEADERS, Allow: allow }
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/core/logger.ts
|
|
92
|
+
var LEVEL_RANK = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
|
|
93
|
+
function isLogLevel(value) {
|
|
94
|
+
return typeof value === "string" && value in LEVEL_RANK;
|
|
95
|
+
}
|
|
96
|
+
function readEnvLevel() {
|
|
97
|
+
try {
|
|
98
|
+
const raw = typeof process !== "undefined" ? process.env?.["LOVABLE_MCP_LOG_LEVEL"] : void 0;
|
|
99
|
+
const normalized = raw?.trim().toLowerCase();
|
|
100
|
+
return isLogLevel(normalized) ? normalized : void 0;
|
|
101
|
+
} catch {
|
|
102
|
+
return void 0;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
var currentLevel = readEnvLevel() ?? "silent";
|
|
106
|
+
function enabled(level) {
|
|
107
|
+
return LEVEL_RANK[level] <= LEVEL_RANK[currentLevel];
|
|
108
|
+
}
|
|
109
|
+
function emit(level, method, event, fields) {
|
|
110
|
+
if (!enabled(level))
|
|
111
|
+
return;
|
|
112
|
+
const message = `[mcp-js] ${event}`;
|
|
113
|
+
if (fields)
|
|
114
|
+
console[method](message, fields);
|
|
115
|
+
else
|
|
116
|
+
console[method](message);
|
|
117
|
+
}
|
|
118
|
+
var log = {
|
|
119
|
+
error: (event, fields) => emit("error", "error", event, fields),
|
|
120
|
+
warn: (event, fields) => emit("warn", "warn", event, fields),
|
|
121
|
+
info: (event, fields) => emit("info", "info", event, fields),
|
|
122
|
+
debug: (event, fields) => emit("debug", "debug", event, fields)
|
|
123
|
+
};
|
|
124
|
+
function describeError(err) {
|
|
125
|
+
if (err instanceof Error) {
|
|
126
|
+
const code = err.code;
|
|
127
|
+
return { name: err.name, message: err.message, ...typeof code === "string" ? { code } : {} };
|
|
128
|
+
}
|
|
129
|
+
return { value: String(err) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/core/promise.ts
|
|
133
|
+
function cachedPromise(load, label) {
|
|
134
|
+
let settled = false;
|
|
135
|
+
let value;
|
|
136
|
+
return async () => {
|
|
137
|
+
if (settled) {
|
|
138
|
+
if (label)
|
|
139
|
+
log.debug(`${label}.cache_hit`);
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
if (label)
|
|
143
|
+
log.debug(`${label}.load_start`);
|
|
144
|
+
try {
|
|
145
|
+
const loaded = await load();
|
|
146
|
+
settled = true;
|
|
147
|
+
value = loaded;
|
|
148
|
+
if (label)
|
|
149
|
+
log.debug(`${label}.settled`);
|
|
150
|
+
return loaded;
|
|
151
|
+
} catch (err) {
|
|
152
|
+
if (label)
|
|
153
|
+
log.debug(`${label}.load_failed`, describeError(err));
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/core/validation.ts
|
|
160
|
+
function parseSafeUrl(subject, raw, ErrorClass = Error) {
|
|
161
|
+
let url;
|
|
162
|
+
try {
|
|
163
|
+
url = new URL(raw);
|
|
164
|
+
} catch {
|
|
165
|
+
throw new ErrorClass(`${subject} must be an absolute URL`);
|
|
166
|
+
}
|
|
167
|
+
const problem = urlSafetyProblem(url);
|
|
168
|
+
if (problem) {
|
|
169
|
+
throw new ErrorClass(`${subject} ${problem}`);
|
|
170
|
+
}
|
|
171
|
+
return url;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/auth/discovery.ts
|
|
175
|
+
var OAuthConfigurationError = class extends Error {
|
|
176
|
+
constructor(message) {
|
|
177
|
+
super(message);
|
|
178
|
+
this.name = "OAuthConfigurationError";
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
var METADATA_FETCH_TIMEOUT_MS = 5e3;
|
|
182
|
+
function issuerPath(url) {
|
|
183
|
+
const path = trimTrailingSlash(url.pathname);
|
|
184
|
+
return path === "" ? void 0 : path;
|
|
185
|
+
}
|
|
186
|
+
function pathInsertedOAuthMetadataUrls(url, path) {
|
|
187
|
+
return [
|
|
188
|
+
`${url.origin}/.well-known/oauth-authorization-server${path}`,
|
|
189
|
+
`${url.origin}/.well-known/openid-configuration${path}`
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
function oauthMetadataUrlsForIssuer(issuer) {
|
|
193
|
+
const normalizedIssuer = trimTrailingSlash(issuer);
|
|
194
|
+
const url = new URL(normalizedIssuer);
|
|
195
|
+
const path = issuerPath(url);
|
|
196
|
+
if (!path) {
|
|
197
|
+
return [
|
|
198
|
+
`${normalizedIssuer}/.well-known/oauth-authorization-server`,
|
|
199
|
+
`${normalizedIssuer}/.well-known/openid-configuration`
|
|
200
|
+
];
|
|
201
|
+
}
|
|
202
|
+
return [...pathInsertedOAuthMetadataUrls(url, path), `${normalizedIssuer}/.well-known/openid-configuration`];
|
|
203
|
+
}
|
|
204
|
+
async function fetchFirstValidOAuthServerMetadata(metadataUrls, expectedIssuer) {
|
|
205
|
+
const errors = [];
|
|
206
|
+
for (const url of metadataUrls) {
|
|
207
|
+
try {
|
|
208
|
+
return await fetchOAuthServerMetadata(url, expectedIssuer);
|
|
209
|
+
} catch (err) {
|
|
210
|
+
log.debug("oauth.discovery.attempt_failed", { url, ...describeError(err) });
|
|
211
|
+
errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
log.error("oauth.discovery.exhausted", { expectedIssuer, urlsTried: metadataUrls, errors });
|
|
215
|
+
throw new Error(`failed to discover OAuth server metadata (${errors.join("; ")})`);
|
|
216
|
+
}
|
|
217
|
+
async function fetchOAuthServerMetadata(url, expectedIssuer) {
|
|
218
|
+
log.debug("oauth.discovery.fetch", { url });
|
|
219
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS), redirect: "manual" });
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
throw new Error(String(response.status));
|
|
222
|
+
}
|
|
223
|
+
const json = await response.json();
|
|
224
|
+
if (typeof json.issuer !== "string") {
|
|
225
|
+
throw new Error("missing issuer");
|
|
226
|
+
}
|
|
227
|
+
parseSafeUrl("discovered issuer", json.issuer);
|
|
228
|
+
if (trimTrailingSlash(json.issuer) !== expectedIssuer) {
|
|
229
|
+
log.warn("oauth.discovery.issuer_mismatch", { url, expectedIssuer, published: json.issuer });
|
|
230
|
+
throw new Error("issuer mismatch");
|
|
231
|
+
}
|
|
232
|
+
if (typeof json.jwks_uri !== "string") {
|
|
233
|
+
throw new Error("missing jwks_uri");
|
|
234
|
+
}
|
|
235
|
+
parseSafeUrl("discovered jwks_uri", json.jwks_uri);
|
|
236
|
+
return { issuer: json.issuer, jwks_uri: json.jwks_uri };
|
|
237
|
+
}
|
|
238
|
+
async function fetchIssuerOAuthServerMetadata(issuer) {
|
|
239
|
+
try {
|
|
240
|
+
return await fetchFirstValidOAuthServerMetadata(oauthMetadataUrlsForIssuer(issuer), issuer);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
log.error("oauth.discovery.config_error", {
|
|
243
|
+
issuer,
|
|
244
|
+
...describeError(err),
|
|
245
|
+
outcome: "500 oauth configuration error"
|
|
246
|
+
});
|
|
247
|
+
throw new OAuthConfigurationError(
|
|
248
|
+
`OAuth issuer discovery failed: ${err instanceof Error ? err.message : String(err)}`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
function createOAuthDiscoveryResolver(auth) {
|
|
253
|
+
const configuredIssuer = trimTrailingSlash(auth.issuer);
|
|
254
|
+
const oauthServerMetadata = cachedPromise(
|
|
255
|
+
() => fetchIssuerOAuthServerMetadata(configuredIssuer),
|
|
256
|
+
"oauth.discovery.metadata"
|
|
257
|
+
);
|
|
258
|
+
return {
|
|
259
|
+
resolveIssuer: async () => configuredIssuer,
|
|
260
|
+
resolveJwksUri: async () => {
|
|
261
|
+
if (auth.jwksUri) {
|
|
262
|
+
log.debug("oauth.jwks.resolved", { jwksUri: auth.jwksUri, source: "configured" });
|
|
263
|
+
return auth.jwksUri;
|
|
264
|
+
}
|
|
265
|
+
const jwksUri = (await oauthServerMetadata()).jwks_uri;
|
|
266
|
+
log.debug("oauth.jwks.resolved", { jwksUri, source: "discovered" });
|
|
267
|
+
return jwksUri;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/auth/verifier.ts
|
|
273
|
+
var import_jose = require("jose");
|
|
274
|
+
|
|
275
|
+
// src/auth/claims.ts
|
|
276
|
+
function readString(value) {
|
|
277
|
+
return typeof value === "string" ? value : void 0;
|
|
278
|
+
}
|
|
279
|
+
function splitScopes(value) {
|
|
280
|
+
if (typeof value === "string")
|
|
281
|
+
return value.split(/\s+/).filter(Boolean);
|
|
282
|
+
if (Array.isArray(value))
|
|
283
|
+
return value.filter((entry) => typeof entry === "string" && entry.length > 0);
|
|
284
|
+
return [];
|
|
285
|
+
}
|
|
286
|
+
function stringClaim(claims, name) {
|
|
287
|
+
return readString(claims[name]);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/auth/verifier.ts
|
|
291
|
+
var DEFAULT_JWT_ALGORITHMS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "EdDSA"];
|
|
292
|
+
var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
|
|
293
|
+
var JWKS_FETCH_TIMEOUT_MS = 5e3;
|
|
294
|
+
var OAuthTokenError = class extends Error {
|
|
295
|
+
constructor(status, oauthError, message) {
|
|
296
|
+
super(message);
|
|
297
|
+
this.status = status;
|
|
298
|
+
this.oauthError = oauthError;
|
|
299
|
+
this.name = "OAuthTokenError";
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
function resolveAcceptedAudiences(auth, resource) {
|
|
303
|
+
return auth.acceptedAudiences ?? [resource];
|
|
304
|
+
}
|
|
305
|
+
function tokenHeaderFields(token) {
|
|
306
|
+
try {
|
|
307
|
+
const header = (0, import_jose.decodeProtectedHeader)(token);
|
|
308
|
+
return { jwtAlg: header.alg, jwtKid: header.kid, tokenLength: token.length };
|
|
309
|
+
} catch {
|
|
310
|
+
return { tokenLength: token.length };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
async function fetchVerificationKeySet(jwksUri) {
|
|
314
|
+
try {
|
|
315
|
+
const response = await fetch(jwksUri, { signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS), redirect: "manual" });
|
|
316
|
+
if (!response.ok)
|
|
317
|
+
throw new Error(`JWKS endpoint returned ${response.status}`);
|
|
318
|
+
const json = await response.json();
|
|
319
|
+
return (0, import_jose.createLocalJWKSet)(json);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
log.error("oauth.jwks.fetch_failed", { ...describeError(err), outcome: "500 oauth configuration error" });
|
|
322
|
+
throw new OAuthConfigurationError(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
async function verifyJwtClaims(token, keySet, issuer, audience, auth) {
|
|
326
|
+
try {
|
|
327
|
+
const { payload } = await (0, import_jose.jwtVerify)(token, keySet, {
|
|
328
|
+
typ: "at+jwt",
|
|
329
|
+
// `issuer` is trimmed of any trailing slash; accept both forms so a token whose
|
|
330
|
+
// `iss` carries the slash the AS publishes still verifies.
|
|
331
|
+
issuer: [issuer, `${issuer}/`],
|
|
332
|
+
audience: [...audience],
|
|
333
|
+
algorithms: auth.algorithms ? [...auth.algorithms] : DEFAULT_JWT_ALGORITHMS,
|
|
334
|
+
requiredClaims: ["sub", "exp"],
|
|
335
|
+
clockTolerance: auth.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
|
|
336
|
+
});
|
|
337
|
+
return payload;
|
|
338
|
+
} catch (err) {
|
|
339
|
+
log.debug("oauth.verify.rejected", { ...describeError(err), outcome: "401 invalid_token" });
|
|
340
|
+
throw err;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
function assertNonEmptySubject(claims) {
|
|
344
|
+
const sub = claims["sub"];
|
|
345
|
+
if (typeof sub !== "string" || sub.trim() === "") {
|
|
346
|
+
log.debug("oauth.verify.bad_subject", { subType: typeof sub });
|
|
347
|
+
throw new OAuthTokenError(401, "invalid_token", "token subject claim must be a non-empty string");
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function assertOAuthClientClaim(auth, clientId) {
|
|
351
|
+
if (auth.requireOAuthClientClaim !== false && !clientId) {
|
|
352
|
+
log.debug("oauth.verify.missing_client_claim", { outcome: "401 invalid_token" });
|
|
353
|
+
throw new OAuthTokenError(401, "invalid_token", "OAuth client claim is required");
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function makeBearer(token) {
|
|
357
|
+
return Object.defineProperty({}, "token", { value: token, enumerable: false });
|
|
358
|
+
}
|
|
359
|
+
function buildMcpAuthContext(args) {
|
|
360
|
+
const { claims } = args;
|
|
361
|
+
return {
|
|
362
|
+
type: "oauth",
|
|
363
|
+
principal: {
|
|
364
|
+
claims,
|
|
365
|
+
issuer: args.issuer,
|
|
366
|
+
resource: args.resource,
|
|
367
|
+
acceptedAudiences: args.acceptedAudiences,
|
|
368
|
+
scopes: splitScopes(claims.scope),
|
|
369
|
+
sub: stringClaim(claims, "sub"),
|
|
370
|
+
email: stringClaim(claims, "email"),
|
|
371
|
+
clientId: stringClaim(claims, "client_id") ?? stringClaim(claims, "azp")
|
|
372
|
+
},
|
|
373
|
+
bearer: makeBearer(args.token)
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function createOAuthTokenVerifier(auth, discovery) {
|
|
377
|
+
return async (token, request, options) => {
|
|
378
|
+
const resource = resolveProtectedResource(auth, request, options);
|
|
379
|
+
const issuer = await discovery.resolveIssuer();
|
|
380
|
+
const acceptedAudiences = resolveAcceptedAudiences(auth, resource);
|
|
381
|
+
log.debug("oauth.verify.start", { issuer, acceptedAudiences, resource, ...tokenHeaderFields(token) });
|
|
382
|
+
const jwksUri = await discovery.resolveJwksUri();
|
|
383
|
+
log.debug("oauth.jwks.fetch", { jwksUri });
|
|
384
|
+
const keySet = await fetchVerificationKeySet(jwksUri);
|
|
385
|
+
const claims = await verifyJwtClaims(token, keySet, issuer, acceptedAudiences, auth);
|
|
386
|
+
assertNonEmptySubject(claims);
|
|
387
|
+
const context = buildMcpAuthContext({ token, claims, issuer, resource, acceptedAudiences });
|
|
388
|
+
assertOAuthClientClaim(auth, context.principal.clientId);
|
|
389
|
+
log.info("oauth.verify.ok", {
|
|
390
|
+
sub: context.principal.sub,
|
|
391
|
+
clientId: context.principal.clientId,
|
|
392
|
+
scopes: context.principal.scopes
|
|
393
|
+
});
|
|
394
|
+
return context;
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// src/auth/authorize.ts
|
|
399
|
+
function quoteAuthenticateParam(value) {
|
|
400
|
+
const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, "");
|
|
401
|
+
return `"${sanitized.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
402
|
+
}
|
|
403
|
+
function resolveProtectedResourceMetadataUrl(auth, request, options) {
|
|
404
|
+
if (auth.protectedResourceMetadataUrl !== void 0)
|
|
405
|
+
return auth.protectedResourceMetadataUrl;
|
|
406
|
+
const base = auth.resource ?? request.url;
|
|
407
|
+
return new URL(options.metadataPath ?? OAUTH_PROTECTED_RESOURCE_METADATA_PATH, base).toString();
|
|
408
|
+
}
|
|
409
|
+
function wwwAuthenticateHeader(auth, request, options, params = {}) {
|
|
410
|
+
const values = [
|
|
411
|
+
`realm=${quoteAuthenticateParam("mcp")}`,
|
|
412
|
+
`resource_metadata=${quoteAuthenticateParam(resolveProtectedResourceMetadataUrl(auth, request, options))}`
|
|
413
|
+
];
|
|
414
|
+
if (auth.requiredScopes && auth.requiredScopes.length > 0) {
|
|
415
|
+
values.push(`scope=${quoteAuthenticateParam(auth.requiredScopes.join(" "))}`);
|
|
416
|
+
}
|
|
417
|
+
if (params.error)
|
|
418
|
+
values.push(`error=${quoteAuthenticateParam(params.error)}`);
|
|
419
|
+
if (params.errorDescription)
|
|
420
|
+
values.push(`error_description=${quoteAuthenticateParam(params.errorDescription)}`);
|
|
421
|
+
return `Bearer ${values.join(", ")}`;
|
|
422
|
+
}
|
|
423
|
+
function challengeResponse(auth, request, options, status, oauthError, errorDescription) {
|
|
424
|
+
const headers = new Headers(JSON_HEADERS);
|
|
425
|
+
headers.set(
|
|
426
|
+
"WWW-Authenticate",
|
|
427
|
+
wwwAuthenticateHeader(auth, request, options, { error: oauthError, errorDescription })
|
|
428
|
+
);
|
|
429
|
+
headers.set("Cache-Control", "no-store");
|
|
430
|
+
return new Response(JSON.stringify({ error: status === 403 ? "forbidden" : "unauthorized" }), {
|
|
431
|
+
status,
|
|
432
|
+
headers
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
function oauthConfigurationErrorResponse() {
|
|
436
|
+
return new Response(JSON.stringify({ error: "oauth configuration error" }), {
|
|
437
|
+
status: 500,
|
|
438
|
+
headers: { ...JSON_HEADERS, "Cache-Control": "no-store" }
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
function parseBearerToken(request) {
|
|
442
|
+
const header = request.headers.get("Authorization");
|
|
443
|
+
if (!header)
|
|
444
|
+
return void 0;
|
|
445
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
446
|
+
if (!match)
|
|
447
|
+
return void 0;
|
|
448
|
+
const token = match[1].trim();
|
|
449
|
+
if (token === "" || /\s/.test(token))
|
|
450
|
+
return void 0;
|
|
451
|
+
return token;
|
|
452
|
+
}
|
|
453
|
+
function getOAuthRuntime(mcp, options = {}) {
|
|
454
|
+
if (options.resourcePath !== void 0)
|
|
455
|
+
assertResourcePathShape(options.resourcePath);
|
|
456
|
+
if (options.metadataPath !== void 0)
|
|
457
|
+
assertResourcePathShape(options.metadataPath, "metadataPath");
|
|
458
|
+
const stableOptions = { resourcePath: options.resourcePath, metadataPath: options.metadataPath };
|
|
459
|
+
const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
|
|
460
|
+
if (!auth)
|
|
461
|
+
return { kind: "unconfigured", options: stableOptions };
|
|
462
|
+
if (options.metadataPath !== void 0 && auth.protectedResourceMetadataUrl !== void 0) {
|
|
463
|
+
throw new Error(
|
|
464
|
+
`@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.`
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
const discovery = createOAuthDiscoveryResolver(auth);
|
|
468
|
+
return {
|
|
469
|
+
kind: "configured",
|
|
470
|
+
auth,
|
|
471
|
+
discovery,
|
|
472
|
+
verify: createOAuthTokenVerifier(auth, discovery),
|
|
473
|
+
options: stableOptions
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function assertRestResourceBinding(mcp, options = {}) {
|
|
477
|
+
const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
|
|
478
|
+
if (auth && auth.resource === void 0 && options.resourcePath === void 0) {
|
|
479
|
+
throw new Error(
|
|
480
|
+
`@lovable.dev/mcp-js: REST companion handlers require auth.resource or a resourcePath so principal.resource binds to the public MCP route, not the internal /.mcp/* request path`
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function missingRequiredScopes(auth, scopes) {
|
|
485
|
+
const requiredScopes = auth.requiredScopes ?? [];
|
|
486
|
+
if (requiredScopes.length === 0)
|
|
487
|
+
return [];
|
|
488
|
+
const granted = new Set(scopes);
|
|
489
|
+
return requiredScopes.filter((scope) => !granted.has(scope));
|
|
490
|
+
}
|
|
491
|
+
function assertRequiredScopes(auth, context) {
|
|
492
|
+
if (missingRequiredScopes(auth, context.principal.scopes).length > 0) {
|
|
493
|
+
throw new OAuthTokenError(403, "insufficient_scope", "Additional OAuth scope is required");
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
function createRequestAuthorizer(mcp, options = {}) {
|
|
497
|
+
const runtime = getOAuthRuntime(mcp, options);
|
|
498
|
+
return {
|
|
499
|
+
async authorize(request) {
|
|
500
|
+
if (runtime.kind === "unconfigured")
|
|
501
|
+
return { ok: true };
|
|
502
|
+
const token = parseBearerToken(request);
|
|
503
|
+
if (!token) {
|
|
504
|
+
log.info("auth.no_bearer_token", { outcome: "401" });
|
|
505
|
+
return { ok: false, response: challengeResponse(runtime.auth, request, runtime.options, 401) };
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
const auth = await runtime.verify(token, request, runtime.options);
|
|
509
|
+
assertRequiredScopes(runtime.auth, auth);
|
|
510
|
+
return { ok: true, auth };
|
|
511
|
+
} catch (err) {
|
|
512
|
+
if (err instanceof OAuthConfigurationError) {
|
|
513
|
+
log.error("auth.config_error", { ...describeError(err), outcome: "500" });
|
|
514
|
+
return { ok: false, response: oauthConfigurationErrorResponse() };
|
|
515
|
+
}
|
|
516
|
+
if (err instanceof OAuthTokenError) {
|
|
517
|
+
log.info("auth.token_rejected", { status: err.status, oauthError: err.oauthError });
|
|
518
|
+
return {
|
|
519
|
+
ok: false,
|
|
520
|
+
response: challengeResponse(
|
|
521
|
+
runtime.auth,
|
|
522
|
+
request,
|
|
523
|
+
runtime.options,
|
|
524
|
+
err.status,
|
|
525
|
+
err.oauthError,
|
|
526
|
+
err.message
|
|
527
|
+
)
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
log.error("auth.unexpected_error", { ...describeError(err), outcome: "401" });
|
|
531
|
+
return {
|
|
532
|
+
ok: false,
|
|
533
|
+
response: challengeResponse(
|
|
534
|
+
runtime.auth,
|
|
535
|
+
request,
|
|
536
|
+
runtime.options,
|
|
537
|
+
401,
|
|
538
|
+
"invalid_token",
|
|
539
|
+
"Invalid access token"
|
|
540
|
+
)
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// src/auth/context.ts
|
|
548
|
+
var ToolContext = class {
|
|
549
|
+
#auth;
|
|
550
|
+
constructor(auth) {
|
|
551
|
+
this.#auth = auth;
|
|
552
|
+
}
|
|
553
|
+
/** Whether the in-flight tool call carries a verified auth context. */
|
|
554
|
+
isAuthenticated() {
|
|
555
|
+
return this.#auth !== void 0;
|
|
556
|
+
}
|
|
557
|
+
/** The verified bearer token, or `undefined` when unauthenticated. Pass it to downstream APIs; never return or log it. */
|
|
558
|
+
getToken() {
|
|
559
|
+
return this.#auth?.bearer.token;
|
|
560
|
+
}
|
|
561
|
+
/** The verified user id (the token `sub`), or `undefined`. */
|
|
562
|
+
getUserId() {
|
|
563
|
+
return this.#auth?.principal.sub;
|
|
564
|
+
}
|
|
565
|
+
/** The verified user email, or `undefined` when absent. */
|
|
566
|
+
getUserEmail() {
|
|
567
|
+
return this.#auth?.principal.email;
|
|
568
|
+
}
|
|
569
|
+
/** The verified OAuth `client_id`, or `undefined`. */
|
|
570
|
+
getClientId() {
|
|
571
|
+
return this.#auth?.principal.clientId;
|
|
572
|
+
}
|
|
573
|
+
/** The verified OAuth scopes, or `undefined` when unauthenticated. */
|
|
574
|
+
getScopes() {
|
|
575
|
+
return this.#auth?.principal.scopes;
|
|
576
|
+
}
|
|
577
|
+
/** The verified token issuer, or `undefined`. */
|
|
578
|
+
getIssuer() {
|
|
579
|
+
return this.#auth?.principal.issuer;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* The full verified JWT claims, or `undefined`. Use this for app/business
|
|
583
|
+
* authorization on issuer-specific claims that have no dedicated accessor.
|
|
584
|
+
*/
|
|
585
|
+
getClaims() {
|
|
586
|
+
return this.#auth?.principal.claims;
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// src/core/cors.ts
|
|
591
|
+
var EXPOSE_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
|
|
592
|
+
var ALLOW_HEADERS = "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID";
|
|
593
|
+
function withCors(response) {
|
|
594
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
595
|
+
response.headers.set("Access-Control-Expose-Headers", EXPOSE_HEADERS);
|
|
596
|
+
return response;
|
|
597
|
+
}
|
|
598
|
+
function corsPreflightResponse(allowMethods) {
|
|
599
|
+
return new Response(null, {
|
|
600
|
+
status: 204,
|
|
601
|
+
headers: {
|
|
602
|
+
"Access-Control-Allow-Origin": "*",
|
|
603
|
+
"Access-Control-Allow-Methods": allowMethods,
|
|
604
|
+
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
|
605
|
+
"Access-Control-Max-Age": "86400"
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// src/protocols/mcp/protocol.ts
|
|
611
|
+
function adaptToolToSdkCallback(tool, auth) {
|
|
612
|
+
return async (first) => {
|
|
613
|
+
const args = tool.inputSchema ? first ?? {} : {};
|
|
614
|
+
let result;
|
|
615
|
+
try {
|
|
616
|
+
result = await tool.handler(args, new ToolContext(auth));
|
|
617
|
+
} catch {
|
|
618
|
+
return { content: [{ type: "text", text: "tool execution failed" }], isError: true };
|
|
619
|
+
}
|
|
620
|
+
if (result == null) {
|
|
621
|
+
return { content: [{ type: "text", text: `tool "${tool.name}" returned no result` }], isError: true };
|
|
622
|
+
}
|
|
623
|
+
return { content: result.content ?? [], structuredContent: result.structuredContent, isError: result.isError };
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function createMcpProtocolHandler(mcp, options = {}) {
|
|
627
|
+
const authorizer = createRequestAuthorizer(mcp, options);
|
|
628
|
+
const handle = async (request) => {
|
|
629
|
+
const authResult = await authorizer.authorize(request);
|
|
630
|
+
if (!authResult.ok)
|
|
631
|
+
return authResult.response;
|
|
632
|
+
try {
|
|
633
|
+
const server = new import_mcp.McpServer(
|
|
634
|
+
{ name: mcp.name, version: mcp.version, title: mcp.title },
|
|
635
|
+
{ instructions: mcp.instructions }
|
|
636
|
+
);
|
|
637
|
+
for (const tool of mcp.tools) {
|
|
638
|
+
server.registerTool(
|
|
639
|
+
tool.name,
|
|
640
|
+
{
|
|
641
|
+
title: tool.title,
|
|
642
|
+
description: tool.description,
|
|
643
|
+
inputSchema: tool.inputSchema,
|
|
644
|
+
outputSchema: tool.outputSchema,
|
|
645
|
+
annotations: tool.annotations
|
|
646
|
+
},
|
|
647
|
+
adaptToolToSdkCallback(tool, authResult.auth)
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
|
|
651
|
+
sessionIdGenerator: void 0
|
|
652
|
+
});
|
|
653
|
+
await server.connect(transport);
|
|
654
|
+
return await transport.handleRequest(request);
|
|
655
|
+
} catch (err) {
|
|
656
|
+
log.error("mcp.transport_error", { ...describeError(err), outcome: "500 internal error" });
|
|
657
|
+
return Response.json(
|
|
658
|
+
{ jsonrpc: "2.0", id: null, error: { code: -32603, message: "internal error" } },
|
|
659
|
+
{ status: 500 }
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
return async (request) => {
|
|
664
|
+
if (request.method === "OPTIONS")
|
|
665
|
+
return corsPreflightResponse("GET, POST, DELETE, OPTIONS");
|
|
666
|
+
return withCors(await handle(request));
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/protocols/oauth-metadata.ts
|
|
671
|
+
function notFound() {
|
|
672
|
+
return withCors(
|
|
673
|
+
new Response(JSON.stringify({ error: "not found" }), {
|
|
674
|
+
status: 404,
|
|
675
|
+
// `no-store` so a 404 (OAuth unconfigured) isn't heuristically cached and
|
|
676
|
+
// then served past a later deploy that enables OAuth and starts returning 200.
|
|
677
|
+
headers: { ...JSON_HEADERS, "Cache-Control": "no-store" }
|
|
678
|
+
})
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
async function buildProtectedResourceMetadata(mcp, auth, request, options, discovery) {
|
|
682
|
+
const issuer = await discovery.resolveIssuer();
|
|
683
|
+
const body = {
|
|
684
|
+
resource: resolveProtectedResource(auth, request, options),
|
|
685
|
+
authorization_servers: [issuer],
|
|
686
|
+
bearer_methods_supported: ["header"],
|
|
687
|
+
resource_name: auth.resourceName ?? mcp.title,
|
|
688
|
+
resource_documentation: auth.resourceDocumentation
|
|
689
|
+
};
|
|
690
|
+
if (auth.requiredScopes && auth.requiredScopes.length > 0)
|
|
691
|
+
body.scopes_supported = auth.requiredScopes;
|
|
692
|
+
return body;
|
|
693
|
+
}
|
|
694
|
+
function createOAuthProtectedResourceMetadataHandler(mcp, options = {}) {
|
|
695
|
+
const runtime = getOAuthRuntime(mcp, options);
|
|
696
|
+
if (runtime.kind === "configured" && runtime.auth.protectedResourceMetadataUrl === void 0 && runtime.auth.resource === void 0 && runtime.options.resourcePath === void 0) {
|
|
697
|
+
throw new Error(
|
|
698
|
+
`@lovable.dev/mcp-js: auth.resource or a resourcePath is required so the protected-resource metadata doesn't advertise the well-known URL as the resource`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
return async (request) => {
|
|
702
|
+
if (runtime.kind !== "configured" || runtime.auth.protectedResourceMetadataUrl !== void 0)
|
|
703
|
+
return notFound();
|
|
704
|
+
if (request.method === "OPTIONS")
|
|
705
|
+
return corsPreflightResponse("GET, HEAD, OPTIONS");
|
|
706
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
707
|
+
return withCors(methodNotAllowed("GET, HEAD, OPTIONS"));
|
|
708
|
+
const headers = {
|
|
709
|
+
...JSON_HEADERS,
|
|
710
|
+
"Cache-Control": "public, max-age=300",
|
|
711
|
+
Vary: "Host"
|
|
712
|
+
};
|
|
713
|
+
try {
|
|
714
|
+
const metadata = await buildProtectedResourceMetadata(
|
|
715
|
+
mcp,
|
|
716
|
+
runtime.auth,
|
|
717
|
+
request,
|
|
718
|
+
runtime.options,
|
|
719
|
+
runtime.discovery
|
|
720
|
+
);
|
|
721
|
+
const response = withCors(Response.json(metadata, { headers }));
|
|
722
|
+
return request.method === "HEAD" ? headResponse(response) : response;
|
|
723
|
+
} catch (err) {
|
|
724
|
+
log.error("oauth.metadata.config_error", { ...describeError(err), outcome: "500 oauth configuration error" });
|
|
725
|
+
const response = withCors(oauthConfigurationErrorResponse());
|
|
726
|
+
return request.method === "HEAD" ? headResponse(response) : response;
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// src/protocols/rest/list-tools.ts
|
|
732
|
+
var import_zod_compat = require("@modelcontextprotocol/sdk/server/zod-compat.js");
|
|
733
|
+
var import_zod_json_schema_compat = require("@modelcontextprotocol/sdk/server/zod-json-schema-compat.js");
|
|
734
|
+
function shapeToJsonSchema(shape) {
|
|
735
|
+
if (!shape)
|
|
736
|
+
return null;
|
|
737
|
+
try {
|
|
738
|
+
return (0, import_zod_json_schema_compat.toJsonSchemaCompat)((0, import_zod_compat.objectFromShape)(shape));
|
|
739
|
+
} catch {
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
function buildMcpListing(mcp) {
|
|
744
|
+
return {
|
|
745
|
+
server: { name: mcp.name, version: mcp.version, title: mcp.title },
|
|
746
|
+
tools: mcp.tools.map((tool) => ({
|
|
747
|
+
name: tool.name,
|
|
748
|
+
title: tool.title,
|
|
749
|
+
description: tool.description,
|
|
750
|
+
annotations: tool.annotations,
|
|
751
|
+
inputSchema: shapeToJsonSchema(tool.inputSchema),
|
|
752
|
+
outputSchema: shapeToJsonSchema(tool.outputSchema)
|
|
753
|
+
}))
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
function createListToolsHandler(mcp, options = {}) {
|
|
757
|
+
assertRestResourceBinding(mcp, options);
|
|
758
|
+
const authorizer = createRequestAuthorizer(mcp, options);
|
|
759
|
+
const handle = async (request) => {
|
|
760
|
+
const authResult = await authorizer.authorize(request);
|
|
761
|
+
if (!authResult.ok)
|
|
762
|
+
return authResult.response;
|
|
763
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
764
|
+
return methodNotAllowed("GET, HEAD, OPTIONS");
|
|
765
|
+
const response = Response.json(buildMcpListing(mcp));
|
|
766
|
+
return request.method === "HEAD" ? headResponse(response) : response;
|
|
767
|
+
};
|
|
768
|
+
return async (request) => {
|
|
769
|
+
if (request.method === "OPTIONS")
|
|
770
|
+
return corsPreflightResponse("GET, HEAD, OPTIONS");
|
|
771
|
+
return withCors(await handle(request));
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/protocols/rest/invoke-tool.ts
|
|
776
|
+
var import_zod_compat2 = require("@modelcontextprotocol/sdk/server/zod-compat.js");
|
|
777
|
+
var MAX_REFLECTED_TOOL_NAME = 256;
|
|
778
|
+
function safeReflectName(name) {
|
|
779
|
+
const text = String(name);
|
|
780
|
+
return text.length > MAX_REFLECTED_TOOL_NAME ? `${text.slice(0, MAX_REFLECTED_TOOL_NAME)}\u2026` : text;
|
|
781
|
+
}
|
|
782
|
+
function isEmptyArgs(value) {
|
|
783
|
+
if (value == null)
|
|
784
|
+
return true;
|
|
785
|
+
if (typeof value !== "object" || Array.isArray(value))
|
|
786
|
+
return false;
|
|
787
|
+
return Object.keys(value).length === 0;
|
|
788
|
+
}
|
|
789
|
+
function createInvokeToolHandler(mcp, options = {}) {
|
|
790
|
+
assertRestResourceBinding(mcp, options);
|
|
791
|
+
const authorizer = createRequestAuthorizer(mcp, options);
|
|
792
|
+
const handle = async (request, toolName) => {
|
|
793
|
+
const authResult = await authorizer.authorize(request);
|
|
794
|
+
if (!authResult.ok)
|
|
795
|
+
return authResult.response;
|
|
796
|
+
if (request.method !== "POST")
|
|
797
|
+
return methodNotAllowed("POST, OPTIONS");
|
|
798
|
+
const tool = mcp.tools.find((t) => t.name === toolName);
|
|
799
|
+
if (!tool) {
|
|
800
|
+
return new Response(JSON.stringify({ error: `unknown tool: ${safeReflectName(toolName)}` }), {
|
|
801
|
+
status: 404,
|
|
802
|
+
headers: JSON_HEADERS
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
let rawArgs = {};
|
|
806
|
+
const text = await request.text();
|
|
807
|
+
if (text) {
|
|
808
|
+
try {
|
|
809
|
+
rawArgs = JSON.parse(text);
|
|
810
|
+
} catch {
|
|
811
|
+
return new Response(JSON.stringify({ error: "invalid JSON body" }), {
|
|
812
|
+
status: 400,
|
|
813
|
+
headers: JSON_HEADERS
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
let args = rawArgs;
|
|
818
|
+
if (tool.inputSchema) {
|
|
819
|
+
try {
|
|
820
|
+
const schema = (0, import_zod_compat2.objectFromShape)(tool.inputSchema);
|
|
821
|
+
const parsed = await (0, import_zod_compat2.safeParseAsync)(schema, rawArgs);
|
|
822
|
+
if (!parsed.success) {
|
|
823
|
+
return new Response(
|
|
824
|
+
JSON.stringify({
|
|
825
|
+
error: "validation failed",
|
|
826
|
+
details: (0, import_zod_compat2.getParseErrorMessage)(parsed.error)
|
|
827
|
+
}),
|
|
828
|
+
{ status: 400, headers: JSON_HEADERS }
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
args = parsed.data;
|
|
832
|
+
} catch {
|
|
833
|
+
return new Response(JSON.stringify({ error: "schema error", tool: toolName }), {
|
|
834
|
+
status: 500,
|
|
835
|
+
headers: JSON_HEADERS
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
} else if (!isEmptyArgs(rawArgs)) {
|
|
839
|
+
return new Response(JSON.stringify({ error: "tool has no inputSchema; expected empty body" }), {
|
|
840
|
+
status: 400,
|
|
841
|
+
headers: JSON_HEADERS
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
let result;
|
|
845
|
+
try {
|
|
846
|
+
result = await tool.handler(args, new ToolContext(authResult.auth));
|
|
847
|
+
} catch {
|
|
848
|
+
return new Response(JSON.stringify({ error: "handler threw", tool: toolName }), {
|
|
849
|
+
status: 500,
|
|
850
|
+
headers: JSON_HEADERS
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
if (result == null) {
|
|
854
|
+
return new Response(JSON.stringify({ error: `tool "${toolName}" returned no result` }), {
|
|
855
|
+
status: 500,
|
|
856
|
+
headers: JSON_HEADERS
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
return Response.json({
|
|
860
|
+
content: result.content ?? [],
|
|
861
|
+
structuredContent: result.structuredContent,
|
|
862
|
+
isError: result.isError
|
|
863
|
+
});
|
|
864
|
+
};
|
|
865
|
+
return async (request, toolName) => {
|
|
866
|
+
if (request.method === "OPTIONS")
|
|
867
|
+
return corsPreflightResponse("POST, OPTIONS");
|
|
868
|
+
return withCors(await handle(request, toolName));
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/stacks/supabase/paths.ts
|
|
873
|
+
var FUNCTIONS_MOUNT_PREFIX = "/functions/v1/";
|
|
874
|
+
function assertFunctionName(value, label = "functionName") {
|
|
875
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
|
|
876
|
+
throw new Error(
|
|
877
|
+
`@lovable.dev/mcp-js: ${label} must be a single path segment matching [A-Za-z0-9_-], got ${JSON.stringify(value)}`
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// src/stacks/supabase/handler.ts
|
|
883
|
+
function deriveResourcePath(options) {
|
|
884
|
+
if (options.resourcePath !== void 0)
|
|
885
|
+
return options.resourcePath;
|
|
886
|
+
if (options.functionName === void 0)
|
|
887
|
+
return void 0;
|
|
888
|
+
assertFunctionName(options.functionName);
|
|
889
|
+
return `${FUNCTIONS_MOUNT_PREFIX}${options.functionName}`;
|
|
890
|
+
}
|
|
891
|
+
function dispatchFor(pathname) {
|
|
892
|
+
const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
|
|
893
|
+
if (path.endsWith(OAUTH_PROTECTED_RESOURCE_METADATA_PATH)) {
|
|
894
|
+
return { kind: "metadata" };
|
|
895
|
+
}
|
|
896
|
+
if (path.endsWith("/.mcp/list-tools")) {
|
|
897
|
+
return { kind: "list-tools" };
|
|
898
|
+
}
|
|
899
|
+
const invokeMatch = /\/\.mcp\/invoke-tool\/([^/]+)$/.exec(path);
|
|
900
|
+
if (invokeMatch) {
|
|
901
|
+
let toolName;
|
|
902
|
+
try {
|
|
903
|
+
toolName = decodeURIComponent(invokeMatch[1]);
|
|
904
|
+
} catch {
|
|
905
|
+
return { kind: "mcp" };
|
|
906
|
+
}
|
|
907
|
+
return { kind: "invoke-tool", toolName };
|
|
908
|
+
}
|
|
909
|
+
return { kind: "mcp" };
|
|
910
|
+
}
|
|
911
|
+
function applyForwardedProto(request) {
|
|
912
|
+
const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
913
|
+
if (!proto)
|
|
914
|
+
return request;
|
|
915
|
+
const url = new URL(request.url);
|
|
916
|
+
if (`${proto}:` === url.protocol)
|
|
917
|
+
return request;
|
|
918
|
+
url.protocol = `${proto}:`;
|
|
919
|
+
return new Request(url.href, request);
|
|
920
|
+
}
|
|
921
|
+
function createSupabaseHandler(mcp, options = {}) {
|
|
922
|
+
const resourcePath = deriveResourcePath(options);
|
|
923
|
+
if (resourcePath !== void 0)
|
|
924
|
+
assertResourcePathShape(resourcePath);
|
|
925
|
+
const servesOwnPrm = !(mcp.auth?.type === "oauth" && mcp.auth.protectedResourceMetadataUrl !== void 0);
|
|
926
|
+
const metadataPath = resourcePath === void 0 || !servesOwnPrm ? void 0 : `${trimTrailingSlash(resourcePath)}${OAUTH_PROTECTED_RESOURCE_METADATA_PATH}`;
|
|
927
|
+
const runtimeOptions = resourcePath === void 0 ? {} : { resourcePath, ...metadataPath ? { metadataPath } : {} };
|
|
928
|
+
const mcpHandler = createMcpProtocolHandler(mcp, runtimeOptions);
|
|
929
|
+
const listToolsHandler = createListToolsHandler(mcp, runtimeOptions);
|
|
930
|
+
const invokeToolHandler = createInvokeToolHandler(mcp, runtimeOptions);
|
|
931
|
+
const metadataHandler = createOAuthProtectedResourceMetadataHandler(mcp, runtimeOptions);
|
|
932
|
+
return async (request) => {
|
|
933
|
+
const req = applyForwardedProto(request);
|
|
934
|
+
const target = dispatchFor(new URL(req.url).pathname);
|
|
935
|
+
switch (target.kind) {
|
|
936
|
+
case "metadata":
|
|
937
|
+
return metadataHandler(req);
|
|
938
|
+
case "list-tools":
|
|
939
|
+
return listToolsHandler(req);
|
|
940
|
+
case "invoke-tool":
|
|
941
|
+
return invokeToolHandler(req, target.toolName);
|
|
942
|
+
case "mcp":
|
|
943
|
+
return mcpHandler(req);
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
948
|
+
0 && (module.exports = {
|
|
949
|
+
createSupabaseHandler
|
|
950
|
+
});
|