@lovable.dev/mcp-js 3.0.5 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +61 -1
  2. package/dist/cli/check-server.cjs +61 -0
  3. package/dist/cli/check-server.d.cts +1 -0
  4. package/dist/cli/check-server.d.ts +1 -0
  5. package/dist/cli/check-server.js +62 -0
  6. package/dist/cli/extract-manifest.cjs +1 -1
  7. package/dist/cli/extract-manifest.js +1 -1
  8. package/dist/{cors-BGAtyAr_.js → cors-Df2tqbzV.js} +1 -1
  9. package/dist/{cors-COakIjqg.cjs → cors-YjwGFsid.cjs} +1 -1
  10. package/dist/diagnostic-ClI2_5MW.js +11 -0
  11. package/dist/diagnostic-DRKjgCsW.d.cts +12 -0
  12. package/dist/diagnostic-DRKjgCsW.d.ts +12 -0
  13. package/dist/diagnostic-ol9IE9Dl.cjs +16 -0
  14. package/dist/{io-NrWvjpmZ.js → io-BoS6dhC0.js} +13 -2
  15. package/dist/{io-dULHdKny.cjs → io-D_DKGquD.cjs} +16 -5
  16. package/dist/{mcp-ChLv-MV0.js → mcp-Bm89K_uU.js} +3 -69
  17. package/dist/{mcp-DTAMXcRF.cjs → mcp-aNWgpVIF.cjs} +5 -71
  18. package/dist/{package-D8nhrfTR.js → package-C6IcwY5Z.js} +1 -1
  19. package/dist/{package-KAnnqE79.cjs → package-Cl7NhnV4.cjs} +1 -1
  20. package/dist/protocols/mcp/index.cjs +1 -1
  21. package/dist/protocols/mcp/index.js +1 -1
  22. package/dist/protocols/oauth-metadata.cjs +1 -1
  23. package/dist/protocols/oauth-metadata.js +1 -1
  24. package/dist/stacks/supabase/index.cjs +2 -2
  25. package/dist/stacks/supabase/index.js +2 -2
  26. package/dist/stacks/supabase/vite.cjs +7 -8
  27. package/dist/stacks/supabase/vite.js +2 -3
  28. package/dist/stacks/tanstack/index.cjs +2 -2
  29. package/dist/stacks/tanstack/index.js +2 -2
  30. package/dist/stacks/tanstack/vite.cjs +7 -8
  31. package/dist/stacks/tanstack/vite.js +1 -2
  32. package/dist/{supabase-config-CakTU8YF.js → supabase-config-DITfH_bn.js} +6 -2
  33. package/dist/{supabase-config-Dz7dnUv0.cjs → supabase-config-Dz13d9ze.cjs} +12 -2
  34. package/dist/testing/index.cjs +46 -0
  35. package/dist/testing/index.d.cts +10 -0
  36. package/dist/testing/index.d.ts +10 -0
  37. package/dist/testing/index.js +44 -0
  38. package/dist/testing/server.cjs +197 -0
  39. package/dist/testing/server.d.cts +31 -0
  40. package/dist/testing/server.d.ts +31 -0
  41. package/dist/testing/server.js +195 -0
  42. package/dist/tool-result-DcNioyiI.js +70 -0
  43. package/dist/tool-result-rU-PpNNi.cjs +87 -0
  44. package/package.json +26 -2
  45. package/dist/fs-errors-CWNzOV75.cjs +0 -11
  46. package/dist/fs-errors-PA2t1TIp.js +0 -6
package/README.md CHANGED
@@ -323,6 +323,64 @@ The request-derived `resource` default trusts the incoming `Host` to name this s
323
323
 
324
324
  Use `auth.oauth.issuer(...)`, set `resource` or `acceptedAudiences` to anchor the accepted audience, and optionally set `jwksUri` and `requiredScopes`. For Supabase project auth, set `acceptedAudiences: "authenticated"`, keep app/business checks in app code, and forward `ctx.getToken()` to Supabase for RLS-backed data access.
325
325
 
326
+ ## Testing
327
+
328
+ Test an MCP server in three layers:
329
+
330
+ 1. **Business and persistence logic.** Keep it in ordinary functions and services and test it with your usual runner. No MCP is involved.
331
+ 2. **Tool results.** Assert a result directly with `assertToolResult` from `@lovable.dev/mcp-js/testing`.
332
+ 3. **The endpoint.** Connect a real MCP client to an in-process handler or a URL with `@lovable.dev/mcp-js/testing/server` or the `lovable-mcp-check` CLI.
333
+
334
+ Browser and UI testing are not covered.
335
+
336
+ ```ts
337
+ import { assertToolResult } from "@lovable.dev/mcp-js/testing";
338
+
339
+ await assertToolResult(result, { outputSchema }); // expects success by default
340
+ await assertToolResult(failed, { isError: true });
341
+ ```
342
+
343
+ A failed assertion throws `McpCheckError` with a fixed, value-free diagnostic. This assertion accepts package handler conveniences such as omitted content; it is not a raw-wire validator.
344
+
345
+ ```ts
346
+ import assert from "node:assert/strict";
347
+ import { checkMcpServer, withMcpClient } from "@lovable.dev/mcp-js/testing/server";
348
+
349
+ // In process: the callback receives the official MCP SDK Client.
350
+ await withMcpClient({ endpoint: "http://localhost/mcp", handler }, async (client) => {
351
+ const result = await client.callTool({ name: "echo", arguments: { text: "hi" } });
352
+ assert.deepEqual(result.content, [{ type: "text", text: "hi" }]);
353
+ });
354
+
355
+ // Discovery plus explicit calls; returns { checks, passed }.
356
+ const report = await checkMcpServer({
357
+ endpoint: "https://my-app.lovable.app/mcp",
358
+ headers: { authorization: `Bearer ${process.env.MCP_TOKEN}` },
359
+ calls: [{ name: "echo", arguments: { text: "hi" } }, { name: "echo", arguments: {}, isError: true }],
360
+ });
361
+ ```
362
+
363
+ ```bash
364
+ pnpm exec lovable-mcp-check --url https://my-app.lovable.app/mcp --bearer-env MCP_TOKEN --calls calls.json
365
+ ```
366
+
367
+ `calls.json` holds the same `calls` array. Both entry points accept `protocolVersion` (`--protocol`): `2026-07-28` (default) or `2025-11-25`. `timeoutMs` (`--timeout`) bounds HTTP requests and checker operations, not the whole run, and defaults to 10 seconds. Inside `withMcpClient`, use the SDK's request options to bound long-running streaming operations. A timed-out handler must honor `request.signal` to stop its own work.
368
+
369
+ What a check does and does not prove:
370
+
371
+ - Discovery never calls a tool. Only the listed `calls` run, in order. After a failed or incomplete call, or a tool whose schema can't be checked, the remaining calls are skipped.
372
+ - `passed` means no failure was observed. A successful connection does not prove that auth is enforced or that business behavior is correct; assert those separately.
373
+ - Reports contain only fixed, value-free diagnostics with indexed locations. Exceptions from `withMcpClient` and its callback are **not** redacted.
374
+ - Credential headers are never sent across a redirect or to a different endpoint, and require HTTPS to a non-loopback host unless an in-process `handler` is supplied. The kit does not mint tokens or run a deployed OAuth flow; supply your own bearer.
375
+
376
+ Notes:
377
+
378
+ - `/testing/server` depends on the official MCP client, which adds install weight. The root `@lovable.dev/mcp-js` import never loads it.
379
+ - Both testing subpaths support ESM and CommonJS on Node 20 or later.
380
+ - Keep these tests isolated from production data. Tool schemas are not sandboxed: run checks against servers you don't trust in a separate, externally time-bounded process.
381
+
382
+ See [`example/testing`](./example/testing) for a runnable setup; `pnpm test:package:testing` runs it against the packed package.
383
+
326
384
  ## Security posture
327
385
 
328
386
  For anyone evaluating an app that exposes an MCP server with this package:
@@ -444,5 +502,7 @@ Ownership: the emitted `index.ts` carries a `// AUTO-GENERATED by @lovable.dev/m
444
502
  | `@lovable.dev/mcp-js/stacks/tanstack/vite` | The Vite plugin |
445
503
  | `@lovable.dev/mcp-js/stacks/supabase` | `createSupabaseHandler` — Web-Standard Supabase Edge Function dispatcher |
446
504
  | `@lovable.dev/mcp-js/stacks/supabase/vite` | `mcpPlugin` — the Vite plugin (Supabase variant; same name as TanStack's, picked by import path) |
505
+ | `@lovable.dev/mcp-js/testing` | Direct handler result assertion and redacted diagnostics |
506
+ | `@lovable.dev/mcp-js/testing/server` | Official-client lifecycle helper and endpoint checker (Node only) |
447
507
 
448
- End users only need the root import (`@lovable.dev/mcp-js`). Generated route files import from `@lovable.dev/mcp-js/stacks/tanstack` (TanStack) or `@lovable.dev/mcp-js/stacks/supabase` (Supabase). The other subpaths are escape hatches for hand-wiring custom stacks against the protocol layer directly.
508
+ End users only need the root import (`@lovable.dev/mcp-js`). Generated route files import from `@lovable.dev/mcp-js/stacks/tanstack` (TanStack) or `@lovable.dev/mcp-js/stacks/supabase` (Supabase). Keep the testing subpaths in tests; the protocol subpaths are escape hatches for hand-wiring custom stacks.
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ const require_testing_server = require("../testing/server.cjs");
3
+ let node_fs_promises = require("node:fs/promises");
4
+ let node_util = require("node:util");
5
+ //#region src/cli/check-server.ts
6
+ async function main() {
7
+ let options;
8
+ try {
9
+ const { values } = (0, node_util.parseArgs)({ options: {
10
+ url: { type: "string" },
11
+ "bearer-env": { type: "string" },
12
+ protocol: {
13
+ type: "string",
14
+ default: "2026-07-28"
15
+ },
16
+ calls: { type: "string" },
17
+ timeout: { type: "string" },
18
+ help: { type: "boolean" }
19
+ } });
20
+ if (values.help) {
21
+ console.log("lovable-mcp-check --url <endpoint> [--bearer-env <NAME>] [--protocol 2025-11-25|2026-07-28] [--calls <json-file>] [--timeout <milliseconds>]\nDiscovery never calls tools. Only calls listed in the JSON array run. Supply credentials through a named environment variable, never command arguments. Timeout is per request (default 10000 ms), not the whole run. Exit 0 means no observed failures, not full coverage; 1 means a failed check, 2 invalid configuration.");
22
+ return;
23
+ }
24
+ if (!values.url) throw new Error();
25
+ const bearer = values["bearer-env"] ? process.env[values["bearer-env"]] : void 0;
26
+ if (values["bearer-env"] && !bearer) throw new Error();
27
+ const calls = values.calls ? JSON.parse(await (0, node_fs_promises.readFile)(values.calls, "utf8")) : [];
28
+ if (!Array.isArray(calls) || calls.some((call) => !call || typeof call.name !== "string" || call.arguments !== void 0 && (!call.arguments || typeof call.arguments !== "object" || Array.isArray(call.arguments)) || call.isError !== void 0 && typeof call.isError !== "boolean" || Object.keys(call).some((key) => ![
29
+ "name",
30
+ "arguments",
31
+ "isError"
32
+ ].includes(key)))) throw new Error();
33
+ options = {
34
+ endpoint: values.url,
35
+ protocolVersion: values.protocol,
36
+ headers: bearer ? { Authorization: `Bearer ${bearer}` } : void 0,
37
+ calls,
38
+ timeoutMs: values.timeout === void 0 ? void 0 : Number(values.timeout)
39
+ };
40
+ } catch {
41
+ console.error("Invalid check configuration. Use --help; check url, protocol, timeout, bearer-env and calls file. Values are omitted.");
42
+ process.exitCode = 2;
43
+ return;
44
+ }
45
+ const report = await require_testing_server.checkMcpServer(options);
46
+ console.log(JSON.stringify(report, null, 2));
47
+ process.exitCode = report.checks.some((check) => check.code === "connection.options") ? 2 : report.passed ? 0 : 1;
48
+ }
49
+ main().catch(() => {
50
+ console.log(JSON.stringify({
51
+ passed: false,
52
+ checks: [{
53
+ code: "check.execution",
54
+ status: "failed",
55
+ basis: "package-guarantee",
56
+ message: "The check could not complete. Error details are omitted."
57
+ }]
58
+ }));
59
+ process.exitCode = 1;
60
+ });
61
+ //#endregion
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import { checkMcpServer } from "../testing/server.js";
3
+ import { readFile } from "node:fs/promises";
4
+ import { parseArgs } from "node:util";
5
+ //#region src/cli/check-server.ts
6
+ async function main() {
7
+ let options;
8
+ try {
9
+ const { values } = parseArgs({ options: {
10
+ url: { type: "string" },
11
+ "bearer-env": { type: "string" },
12
+ protocol: {
13
+ type: "string",
14
+ default: "2026-07-28"
15
+ },
16
+ calls: { type: "string" },
17
+ timeout: { type: "string" },
18
+ help: { type: "boolean" }
19
+ } });
20
+ if (values.help) {
21
+ console.log("lovable-mcp-check --url <endpoint> [--bearer-env <NAME>] [--protocol 2025-11-25|2026-07-28] [--calls <json-file>] [--timeout <milliseconds>]\nDiscovery never calls tools. Only calls listed in the JSON array run. Supply credentials through a named environment variable, never command arguments. Timeout is per request (default 10000 ms), not the whole run. Exit 0 means no observed failures, not full coverage; 1 means a failed check, 2 invalid configuration.");
22
+ return;
23
+ }
24
+ if (!values.url) throw new Error();
25
+ const bearer = values["bearer-env"] ? process.env[values["bearer-env"]] : void 0;
26
+ if (values["bearer-env"] && !bearer) throw new Error();
27
+ const calls = values.calls ? JSON.parse(await readFile(values.calls, "utf8")) : [];
28
+ if (!Array.isArray(calls) || calls.some((call) => !call || typeof call.name !== "string" || call.arguments !== void 0 && (!call.arguments || typeof call.arguments !== "object" || Array.isArray(call.arguments)) || call.isError !== void 0 && typeof call.isError !== "boolean" || Object.keys(call).some((key) => ![
29
+ "name",
30
+ "arguments",
31
+ "isError"
32
+ ].includes(key)))) throw new Error();
33
+ options = {
34
+ endpoint: values.url,
35
+ protocolVersion: values.protocol,
36
+ headers: bearer ? { Authorization: `Bearer ${bearer}` } : void 0,
37
+ calls,
38
+ timeoutMs: values.timeout === void 0 ? void 0 : Number(values.timeout)
39
+ };
40
+ } catch {
41
+ console.error("Invalid check configuration. Use --help; check url, protocol, timeout, bearer-env and calls file. Values are omitted.");
42
+ process.exitCode = 2;
43
+ return;
44
+ }
45
+ const report = await checkMcpServer(options);
46
+ console.log(JSON.stringify(report, null, 2));
47
+ process.exitCode = report.checks.some((check) => check.code === "connection.options") ? 2 : report.passed ? 0 : 1;
48
+ }
49
+ main().catch(() => {
50
+ console.log(JSON.stringify({
51
+ passed: false,
52
+ checks: [{
53
+ code: "check.execution",
54
+ status: "failed",
55
+ basis: "package-guarantee",
56
+ message: "The check could not complete. Error details are omitted."
57
+ }]
58
+ }));
59
+ process.exitCode = 1;
60
+ });
61
+ //#endregion
62
+ export {};
@@ -4,7 +4,7 @@ const projectRoot = process.argv[2] ?? process.cwd();
4
4
  import("zod/v3").catch((err) => {
5
5
  const message = err instanceof Error ? err.message : String(err);
6
6
  throw new Error(`@lovable.dev/mcp-js requires zod ^3.25 or ^4.0 to extract MCP schemas. Verify the project's zod dependency and package resolution, then try again. Underlying error: ${message}`);
7
- }).then(() => Promise.resolve().then(() => require("../io-dULHdKny.cjs"))).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
7
+ }).then(() => Promise.resolve().then(() => require("../io-D_DKGquD.cjs"))).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
8
8
  console.error(err instanceof Error ? err.message : String(err));
9
9
  process.exit(1);
10
10
  });
@@ -4,7 +4,7 @@ const projectRoot = process.argv[2] ?? process.cwd();
4
4
  import("zod/v3").catch((err) => {
5
5
  const message = err instanceof Error ? err.message : String(err);
6
6
  throw new Error(`@lovable.dev/mcp-js requires zod ^3.25 or ^4.0 to extract MCP schemas. Verify the project's zod dependency and package resolution, then try again. Underlying error: ${message}`);
7
- }).then(() => import("../io-NrWvjpmZ.js")).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
7
+ }).then(() => import("../io-BoS6dhC0.js")).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
8
8
  console.error(err instanceof Error ? err.message : String(err));
9
9
  process.exit(1);
10
10
  });
@@ -1,5 +1,5 @@
1
1
  import { i as log, n as applyLogLevelFromEnv, o as parseSafeUrl, r as describeError, s as trimTrailingSlash, t as LOG_LEVEL_ENV_VAR, u as resolveMetricsConfig } from "./logger-CpLgYbCG.js";
2
- import { t as version } from "./package-D8nhrfTR.js";
2
+ import { t as version } from "./package-C6IcwY5Z.js";
3
3
  import "./metadata-path-CAkNcfyY.js";
4
4
  import { createLocalJWKSet, decodeProtectedHeader, errors, jwtVerify } from "jose";
5
5
  //#region src/core/http.ts
@@ -1,5 +1,5 @@
1
1
  const require_logger = require("./logger-C-Hdu57K.cjs");
2
- const require_package = require("./package-KAnnqE79.cjs");
2
+ const require_package = require("./package-Cl7NhnV4.cjs");
3
3
  require("./metadata-path-zd7NSNoa.cjs");
4
4
  let jose = require("jose");
5
5
  //#region src/core/http.ts
@@ -0,0 +1,11 @@
1
+ //#region src/testing/diagnostic.ts
2
+ var McpCheckError = class extends Error {
3
+ diagnostic;
4
+ constructor(diagnostic) {
5
+ super(`${diagnostic.code}: ${diagnostic.message}`);
6
+ this.diagnostic = diagnostic;
7
+ this.name = "McpCheckError";
8
+ }
9
+ };
10
+ //#endregion
11
+ export { McpCheckError as t };
@@ -0,0 +1,12 @@
1
+ //#region src/testing/diagnostic.d.ts
2
+ interface Diagnostic {
3
+ code: string;
4
+ basis: "protocol-requirement" | "package-guarantee" | "app-expectation";
5
+ message: string;
6
+ }
7
+ declare class McpCheckError extends Error {
8
+ readonly diagnostic: Diagnostic;
9
+ constructor(diagnostic: Diagnostic);
10
+ }
11
+ //#endregion
12
+ export { McpCheckError as n, Diagnostic as t };
@@ -0,0 +1,12 @@
1
+ //#region src/testing/diagnostic.d.ts
2
+ interface Diagnostic {
3
+ code: string;
4
+ basis: "protocol-requirement" | "package-guarantee" | "app-expectation";
5
+ message: string;
6
+ }
7
+ declare class McpCheckError extends Error {
8
+ readonly diagnostic: Diagnostic;
9
+ constructor(diagnostic: Diagnostic);
10
+ }
11
+ //#endregion
12
+ export { McpCheckError as n, Diagnostic as t };
@@ -0,0 +1,16 @@
1
+ //#region src/testing/diagnostic.ts
2
+ var McpCheckError = class extends Error {
3
+ diagnostic;
4
+ constructor(diagnostic) {
5
+ super(`${diagnostic.code}: ${diagnostic.message}`);
6
+ this.diagnostic = diagnostic;
7
+ this.name = "McpCheckError";
8
+ }
9
+ };
10
+ //#endregion
11
+ Object.defineProperty(exports, "McpCheckError", {
12
+ enumerable: true,
13
+ get: function() {
14
+ return McpCheckError;
15
+ }
16
+ });
@@ -1,6 +1,6 @@
1
1
  import { t as jsonSchemaFromDefinition } from "./schema-JK_1KkOa.js";
2
- import { t as version } from "./package-D8nhrfTR.js";
3
- import { t as isFileMissing } from "./fs-errors-PA2t1TIp.js";
2
+ import { t as version } from "./package-C6IcwY5Z.js";
3
+ import { n as isFileMissing, t as readSupabaseProjectRef } from "./supabase-config-DITfH_bn.js";
4
4
  import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { dirname, resolve } from "node:path";
6
6
  import { createServer, resolveConfig } from "vite";
@@ -59,9 +59,16 @@ function isAuthShape(auth) {
59
59
  const a = auth;
60
60
  return a.type === "oauth" && typeof a.issuer === "string" && a.issuer.length > 0;
61
61
  }
62
+ function hasBlankIssuerHost(issuer) {
63
+ if (!URL.canParse(issuer)) return false;
64
+ const { hostname } = new URL(issuer);
65
+ return hostname === "" || hostname.startsWith(".");
66
+ }
62
67
  function manifestFromDefinition(definition, urlPath, source = "the MCP entry") {
63
68
  const def = definition;
64
69
  if (!(!!def && typeof def === "object" && typeof def.name === "string" && typeof def.title === "string" && typeof def.version === "string" && Array.isArray(def.tools) && def.tools.every(isToolShape) && isAuthShape(def.auth))) throw new Error(`@lovable.dev/mcp-js: ${source} must \`export default defineMcp(...)\` (got ${definition == null ? "no default export" : typeof definition}).`);
70
+ const issuer = def.auth?.issuer;
71
+ if (issuer !== void 0 && hasBlankIssuerHost(issuer)) throw new Error(`@lovable.dev/mcp-js: ${source} resolves its OAuth issuer to "${issuer}", which has no project host. Set VITE_SUPABASE_PROJECT_ID or the top-level project_id in supabase/config.toml, then extract the manifest again.`);
65
72
  return {
66
73
  version: 1,
67
74
  sdk_version: version,
@@ -95,6 +102,7 @@ async function produceViaSsr(projectRoot, alias, ssr, entryAbs, urlPath) {
95
102
  //#endregion
96
103
  //#region src/manifest/io.ts
97
104
  const MAX_MANIFEST_TOOLS = 512;
105
+ const SUPABASE_PROJECT_REF_ENV = "VITE_SUPABASE_PROJECT_ID";
98
106
  const MCP_PLUGIN_NAME_PREFIX = "@lovable.dev/mcp-js";
99
107
  const DEFAULT_MCP_ENTRY = "src/lib/mcp/index.ts";
100
108
  const DEFAULT_MCP_PATH = "/mcp";
@@ -143,10 +151,13 @@ async function syncManifest(manifestFile, entryAbs, urlPath, produce) {
143
151
  if (manifest.mcp.tools.length > MAX_MANIFEST_TOOLS) throw new Error(`@lovable.dev/mcp-js: ${entryAbs} declares ${manifest.mcp.tools.length} tools, exceeding the App MCP manifest limit of ${MAX_MANIFEST_TOOLS}. Reduce defineMcp({ tools }) to ${MAX_MANIFEST_TOOLS} tools or fewer and extract the manifest again.`);
144
152
  }
145
153
  async function runExtract(projectRoot) {
154
+ if (process.env[SUPABASE_PROJECT_REF_ENV] === "") delete process.env[SUPABASE_PROJECT_REF_ENV];
146
155
  const resolved = await resolveConfig({
147
156
  root: projectRoot,
148
157
  logLevel: "silent"
149
158
  }, "serve");
159
+ const ref = resolved.env[SUPABASE_PROJECT_REF_ENV] || readSupabaseProjectRef(projectRoot);
160
+ if (ref) process.env[SUPABASE_PROJECT_REF_ENV] = ref;
150
161
  const alias = resolved.resolve?.alias ?? [];
151
162
  const ssr = {
152
163
  external: resolved.ssr.external,
@@ -1,6 +1,6 @@
1
1
  const require_schema = require("./schema-DNMsvJwE.cjs");
2
- const require_package = require("./package-KAnnqE79.cjs");
3
- const require_fs_errors = require("./fs-errors-CWNzOV75.cjs");
2
+ const require_package = require("./package-Cl7NhnV4.cjs");
3
+ const require_supabase_config = require("./supabase-config-Dz13d9ze.cjs");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  let vite = require("vite");
@@ -59,9 +59,16 @@ function isAuthShape(auth) {
59
59
  const a = auth;
60
60
  return a.type === "oauth" && typeof a.issuer === "string" && a.issuer.length > 0;
61
61
  }
62
+ function hasBlankIssuerHost(issuer) {
63
+ if (!URL.canParse(issuer)) return false;
64
+ const { hostname } = new URL(issuer);
65
+ return hostname === "" || hostname.startsWith(".");
66
+ }
62
67
  function manifestFromDefinition(definition, urlPath, source = "the MCP entry") {
63
68
  const def = definition;
64
69
  if (!(!!def && typeof def === "object" && typeof def.name === "string" && typeof def.title === "string" && typeof def.version === "string" && Array.isArray(def.tools) && def.tools.every(isToolShape) && isAuthShape(def.auth))) throw new Error(`@lovable.dev/mcp-js: ${source} must \`export default defineMcp(...)\` (got ${definition == null ? "no default export" : typeof definition}).`);
70
+ const issuer = def.auth?.issuer;
71
+ if (issuer !== void 0 && hasBlankIssuerHost(issuer)) throw new Error(`@lovable.dev/mcp-js: ${source} resolves its OAuth issuer to "${issuer}", which has no project host. Set VITE_SUPABASE_PROJECT_ID or the top-level project_id in supabase/config.toml, then extract the manifest again.`);
65
72
  return {
66
73
  version: 1,
67
74
  sdk_version: require_package.version,
@@ -95,6 +102,7 @@ async function produceViaSsr(projectRoot, alias, ssr, entryAbs, urlPath) {
95
102
  //#endregion
96
103
  //#region src/manifest/io.ts
97
104
  const MAX_MANIFEST_TOOLS = 512;
105
+ const SUPABASE_PROJECT_REF_ENV = "VITE_SUPABASE_PROJECT_ID";
98
106
  const MCP_PLUGIN_NAME_PREFIX = "@lovable.dev/mcp-js";
99
107
  const DEFAULT_MCP_ENTRY = "src/lib/mcp/index.ts";
100
108
  const DEFAULT_MCP_PATH = "/mcp";
@@ -104,7 +112,7 @@ function writeManifestIfChanged(file, manifest) {
104
112
  try {
105
113
  existing = (0, node_fs.readFileSync)(file, "utf8");
106
114
  } catch (err) {
107
- if (!require_fs_errors.isFileMissing(err)) throw err;
115
+ if (!require_supabase_config.isFileMissing(err)) throw err;
108
116
  }
109
117
  if (existing === content) return;
110
118
  (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
@@ -123,7 +131,7 @@ function removeManifest(file) {
123
131
  try {
124
132
  (0, node_fs.unlinkSync)(file);
125
133
  } catch (err) {
126
- if (!require_fs_errors.isFileMissing(err)) throw err;
134
+ if (!require_supabase_config.isFileMissing(err)) throw err;
127
135
  }
128
136
  }
129
137
  async function syncManifest(manifestFile, entryAbs, urlPath, produce) {
@@ -131,7 +139,7 @@ async function syncManifest(manifestFile, entryAbs, urlPath, produce) {
131
139
  try {
132
140
  (0, node_fs.lstatSync)(entryAbs);
133
141
  } catch (err) {
134
- if (!require_fs_errors.isFileMissing(err)) throw err;
142
+ if (!require_supabase_config.isFileMissing(err)) throw err;
135
143
  entryExists = false;
136
144
  }
137
145
  if (!entryExists) {
@@ -143,10 +151,13 @@ async function syncManifest(manifestFile, entryAbs, urlPath, produce) {
143
151
  if (manifest.mcp.tools.length > MAX_MANIFEST_TOOLS) throw new Error(`@lovable.dev/mcp-js: ${entryAbs} declares ${manifest.mcp.tools.length} tools, exceeding the App MCP manifest limit of ${MAX_MANIFEST_TOOLS}. Reduce defineMcp({ tools }) to ${MAX_MANIFEST_TOOLS} tools or fewer and extract the manifest again.`);
144
152
  }
145
153
  async function runExtract(projectRoot) {
154
+ if (process.env[SUPABASE_PROJECT_REF_ENV] === "") delete process.env[SUPABASE_PROJECT_REF_ENV];
146
155
  const resolved = await (0, vite.resolveConfig)({
147
156
  root: projectRoot,
148
157
  logLevel: "silent"
149
158
  }, "serve");
159
+ const ref = resolved.env[SUPABASE_PROJECT_REF_ENV] || require_supabase_config.readSupabaseProjectRef(projectRoot);
160
+ if (ref) process.env[SUPABASE_PROJECT_REF_ENV] = ref;
150
161
  const alias = resolved.resolve?.alias ?? [];
151
162
  const ssr = {
152
163
  external: resolved.ssr.external,
@@ -1,8 +1,9 @@
1
1
  import { i as log, r as describeError } from "./logger-CpLgYbCG.js";
2
2
  import { n as schemaFromDefinition, t as jsonSchemaFromDefinition } from "./schema-JK_1KkOa.js";
3
3
  import { a as ToolContext, c as toolRequiresAppContext, i as AuthContext, n as errorSummary, r as resolveToolErrorMessage } from "./errors-ZmYYVYKN.js";
4
- import { d as nowMs, i as normalizeHttpMethod, l as emitBeforeResponse, n as createRequestAuthorizer, p as finalizeWireResponse, t as evaluateCors, u as createNoopRecorder } from "./cors-BGAtyAr_.js";
5
- import { getParseErrorMessage, safeParseAsync } from "@modelcontextprotocol/sdk/server/zod-compat.js";
4
+ import { d as nowMs, i as normalizeHttpMethod, l as emitBeforeResponse, n as createRequestAuthorizer, p as finalizeWireResponse, t as evaluateCors, u as createNoopRecorder } from "./cors-Df2tqbzV.js";
5
+ import { t as finalizeToolResult } from "./tool-result-DcNioyiI.js";
6
+ import { safeParseAsync } from "@modelcontextprotocol/sdk/server/zod-compat.js";
6
7
  import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, McpServer, createMcpHandler } from "@modelcontextprotocol/server";
7
8
  //#region src/core/content.ts
8
9
  /** Join the text of a result's `type: "text"` blocks into one string, dropping
@@ -15,73 +16,6 @@ function extractTextContent(content) {
15
16
  return text.length > 0 ? text : void 0;
16
17
  }
17
18
  //#endregion
18
- //#region src/core/tool-result.ts
19
- function normalizeResourceLinkIcon(icon) {
20
- if (typeof icon.sizes !== "string") return icon;
21
- const { sizes, ...rest } = icon;
22
- const normalized = sizes.trim();
23
- return normalized === "" ? rest : {
24
- ...rest,
25
- sizes: normalized.split(/\s+/)
26
- };
27
- }
28
- function normalizeToolContent(content) {
29
- return (content ?? []).map((block) => {
30
- if (block.type !== "resource_link" || block.icons === void 0) return block;
31
- return {
32
- ...block,
33
- icons: block.icons.map(normalizeResourceLinkIcon)
34
- };
35
- });
36
- }
37
- function outputValidationError(text) {
38
- return {
39
- content: [{
40
- type: "text",
41
- text
42
- }],
43
- isError: true
44
- };
45
- }
46
- function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
47
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
48
- if (typeof value === "number") return Number.isFinite(value);
49
- if (typeof value !== "object" || ancestors.has(value)) return false;
50
- const prototype = Object.getPrototypeOf(value);
51
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;
52
- ancestors.add(value);
53
- const valid = (Array.isArray(value) ? value : Object.values(value).filter((entry) => entry !== void 0)).every((entry) => isJsonValue(entry, ancestors));
54
- ancestors.delete(value);
55
- return valid;
56
- }
57
- async function finalizeToolResult(tool, result) {
58
- const content = normalizeToolContent(result.content);
59
- let structuredContent = result.structuredContent;
60
- if (tool.outputSchema && !result.isError) {
61
- if (structuredContent === void 0) return outputValidationError(`Output validation error: Tool ${tool.name} has an output schema but no structured content was provided`);
62
- try {
63
- const parsed = await safeParseAsync(schemaFromDefinition(tool.outputSchema, false), structuredContent);
64
- if (!parsed.success) return outputValidationError(`Output validation error: Invalid structured content for tool ${tool.name}: ${getParseErrorMessage(parsed.error)}`);
65
- structuredContent = parsed.data;
66
- } catch {
67
- return outputValidationError(`Output validation error: Could not validate structured content for tool ${tool.name}`);
68
- }
69
- }
70
- if (structuredContent !== void 0 && !isJsonValue(structuredContent)) {
71
- if (!result.isError) return outputValidationError(`Output validation error: Tool ${tool.name} returned a non-JSON structured value`);
72
- structuredContent = void 0;
73
- }
74
- if (structuredContent !== void 0 && (structuredContent === null || typeof structuredContent !== "object" || Array.isArray(structuredContent)) && !content.some((block) => block.type === "text")) content.push({
75
- type: "text",
76
- text: JSON.stringify(structuredContent)
77
- });
78
- return {
79
- content,
80
- structuredContent,
81
- isError: result.isError
82
- };
83
- }
84
- //#endregion
85
19
  //#region src/protocols/gate.ts
86
20
  function createGatedHandler(gate) {
87
21
  const allow = [...gate.methods, "OPTIONS"].join(", ");
@@ -1,7 +1,8 @@
1
1
  const require_schema = require("./schema-DNMsvJwE.cjs");
2
2
  const require_logger = require("./logger-C-Hdu57K.cjs");
3
3
  const require_errors = require("./errors-CWxgUZH3.cjs");
4
- const require_cors = require("./cors-COakIjqg.cjs");
4
+ const require_cors = require("./cors-YjwGFsid.cjs");
5
+ const require_tool_result = require("./tool-result-rU-PpNNi.cjs");
5
6
  let _modelcontextprotocol_sdk_server_zod_compat_js = require("@modelcontextprotocol/sdk/server/zod-compat.js");
6
7
  let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
7
8
  //#region src/core/content.ts
@@ -15,73 +16,6 @@ function extractTextContent(content) {
15
16
  return text.length > 0 ? text : void 0;
16
17
  }
17
18
  //#endregion
18
- //#region src/core/tool-result.ts
19
- function normalizeResourceLinkIcon(icon) {
20
- if (typeof icon.sizes !== "string") return icon;
21
- const { sizes, ...rest } = icon;
22
- const normalized = sizes.trim();
23
- return normalized === "" ? rest : {
24
- ...rest,
25
- sizes: normalized.split(/\s+/)
26
- };
27
- }
28
- function normalizeToolContent(content) {
29
- return (content ?? []).map((block) => {
30
- if (block.type !== "resource_link" || block.icons === void 0) return block;
31
- return {
32
- ...block,
33
- icons: block.icons.map(normalizeResourceLinkIcon)
34
- };
35
- });
36
- }
37
- function outputValidationError(text) {
38
- return {
39
- content: [{
40
- type: "text",
41
- text
42
- }],
43
- isError: true
44
- };
45
- }
46
- function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
47
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
48
- if (typeof value === "number") return Number.isFinite(value);
49
- if (typeof value !== "object" || ancestors.has(value)) return false;
50
- const prototype = Object.getPrototypeOf(value);
51
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;
52
- ancestors.add(value);
53
- const valid = (Array.isArray(value) ? value : Object.values(value).filter((entry) => entry !== void 0)).every((entry) => isJsonValue(entry, ancestors));
54
- ancestors.delete(value);
55
- return valid;
56
- }
57
- async function finalizeToolResult(tool, result) {
58
- const content = normalizeToolContent(result.content);
59
- let structuredContent = result.structuredContent;
60
- if (tool.outputSchema && !result.isError) {
61
- if (structuredContent === void 0) return outputValidationError(`Output validation error: Tool ${tool.name} has an output schema but no structured content was provided`);
62
- try {
63
- const parsed = await (0, _modelcontextprotocol_sdk_server_zod_compat_js.safeParseAsync)(require_schema.schemaFromDefinition(tool.outputSchema, false), structuredContent);
64
- if (!parsed.success) return outputValidationError(`Output validation error: Invalid structured content for tool ${tool.name}: ${(0, _modelcontextprotocol_sdk_server_zod_compat_js.getParseErrorMessage)(parsed.error)}`);
65
- structuredContent = parsed.data;
66
- } catch {
67
- return outputValidationError(`Output validation error: Could not validate structured content for tool ${tool.name}`);
68
- }
69
- }
70
- if (structuredContent !== void 0 && !isJsonValue(structuredContent)) {
71
- if (!result.isError) return outputValidationError(`Output validation error: Tool ${tool.name} returned a non-JSON structured value`);
72
- structuredContent = void 0;
73
- }
74
- if (structuredContent !== void 0 && (structuredContent === null || typeof structuredContent !== "object" || Array.isArray(structuredContent)) && !content.some((block) => block.type === "text")) content.push({
75
- type: "text",
76
- text: JSON.stringify(structuredContent)
77
- });
78
- return {
79
- content,
80
- structuredContent,
81
- isError: result.isError
82
- };
83
- }
84
- //#endregion
85
19
  //#region src/protocols/gate.ts
86
20
  function createGatedHandler(gate) {
87
21
  const allow = [...gate.methods, "OPTIONS"].join(", ");
@@ -258,7 +192,7 @@ async function invokeTool(tool, auth, recorder, args, protocol, sdkCtx, appConte
258
192
  endUserId,
259
193
  protocol
260
194
  });
261
- return finalizeToolResult(tool, {
195
+ return require_tool_result.finalizeToolResult(tool, {
262
196
  content: [{
263
197
  type: "text",
264
198
  text: "tool execution failed"
@@ -284,7 +218,7 @@ async function invokeTool(tool, auth, recorder, args, protocol, sdkCtx, appConte
284
218
  endUserId,
285
219
  protocol
286
220
  });
287
- return finalizeToolResult(tool, {
221
+ return require_tool_result.finalizeToolResult(tool, {
288
222
  content: [{
289
223
  type: "text",
290
224
  text: `tool "${tool.name}" returned no result`
@@ -292,7 +226,7 @@ async function invokeTool(tool, auth, recorder, args, protocol, sdkCtx, appConte
292
226
  isError: true
293
227
  });
294
228
  }
295
- result = await finalizeToolResult(tool, result);
229
+ result = await require_tool_result.finalizeToolResult(tool, result);
296
230
  await recorder.emit({
297
231
  tool: tool.name,
298
232
  toolConditional,
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "3.0.5";
2
+ var version = "3.1.0";
3
3
  //#endregion
4
4
  export { version as t };
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "3.0.5";
2
+ var version = "3.1.0";
3
3
  //#endregion
4
4
  Object.defineProperty(exports, "version", {
5
5
  enumerable: true,
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_mcp = require("../../mcp-DTAMXcRF.cjs");
2
+ const require_mcp = require("../../mcp-aNWgpVIF.cjs");
3
3
  exports.createMcpProtocolHandler = require_mcp.createMcpProtocolHandler;
@@ -1,2 +1,2 @@
1
- import { t as createMcpProtocolHandler } from "../../mcp-ChLv-MV0.js";
1
+ import { t as createMcpProtocolHandler } from "../../mcp-Bm89K_uU.js";
2
2
  export { createMcpProtocolHandler };