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