@lovable.dev/mcp-js 2.0.4-rc.0 → 2.1.0-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/README.md +82 -1
- package/dist/{authorize-oCEahmRv.d.cts → authorize-BC4TM__8.d.cts} +1 -1
- package/dist/{authorize-B5VMSzcN.d.ts → authorize-DEsM-zTN.d.ts} +1 -1
- package/dist/{base-DnCoJOZN.d.ts → base-4G2k3bMl.d.cts} +2 -2
- package/dist/{base-DAkOPRay.d.cts → base-BnlJz6TE.d.ts} +2 -2
- package/dist/cli/extract-manifest.cjs +1 -1
- package/dist/cli/extract-manifest.js +1 -1
- package/dist/{cors-DheH0sX2.cjs → cors-0ZCwmwyK.cjs} +1 -1
- package/dist/{cors-K-QaLAV0.js → cors-D4BjUpgU.js} +1 -1
- package/dist/errors-CdrGi5aP.cjs +309 -0
- package/dist/errors-DTvfh8lb.js +262 -0
- package/dist/index.cjs +4 -147
- package/dist/index.d.cts +12 -4
- package/dist/index.d.ts +12 -4
- package/dist/index.js +3 -147
- package/dist/{io-D2PGAhYM.d.cts → io-9jGNgPfl.d.cts} +1 -1
- package/dist/{io-CanMDPsW.js → io-BEoJ_gb5.js} +3 -2
- package/dist/{io-BD2TuqtG.d.ts → io-BLZ8jYW6.d.ts} +1 -1
- package/dist/{io-B5Mit9aD.cjs → io-Cz81GsrM.cjs} +3 -2
- package/dist/{mcp-TJZHxHwb.js → mcp-CuHyVOZK.js} +92 -15
- package/dist/{mcp-CY55D6Km.cjs → mcp-Q_rjpR99.cjs} +92 -15
- package/dist/{package-ZzwBAUf7.js → package-BAYb-3dX.js} +1 -1
- package/dist/{package-ClsLrfmB.cjs → package-DlouusYQ.cjs} +1 -1
- package/dist/protocols/mcp/index.cjs +1 -1
- package/dist/protocols/mcp/index.d.cts +3 -3
- package/dist/protocols/mcp/index.d.ts +3 -3
- package/dist/protocols/mcp/index.js +1 -1
- package/dist/protocols/oauth-metadata.cjs +1 -1
- package/dist/protocols/oauth-metadata.d.cts +3 -3
- package/dist/protocols/oauth-metadata.d.ts +3 -3
- package/dist/protocols/oauth-metadata.js +1 -1
- package/dist/stacks/supabase/index.cjs +2 -2
- package/dist/stacks/supabase/index.d.cts +1 -1
- package/dist/stacks/supabase/index.d.ts +1 -1
- package/dist/stacks/supabase/index.js +2 -2
- package/dist/stacks/supabase/vite.cjs +1 -1
- package/dist/stacks/supabase/vite.d.cts +1 -1
- package/dist/stacks/supabase/vite.d.ts +1 -1
- package/dist/stacks/supabase/vite.js +1 -1
- package/dist/stacks/tanstack/index.cjs +2 -2
- package/dist/stacks/tanstack/index.d.cts +2 -2
- package/dist/stacks/tanstack/index.d.ts +2 -2
- package/dist/stacks/tanstack/index.js +2 -2
- package/dist/stacks/tanstack/vite.d.cts +1 -1
- package/dist/stacks/tanstack/vite.d.ts +1 -1
- package/dist/{types-C6O4ciic.d.ts → types-S6J_QTXw.d.cts} +60 -20
- package/dist/{types-C6O4ciic.d.cts → types-S6J_QTXw.d.ts} +60 -20
- package/package.json +1 -1
- package/dist/errors-Bwd1L0Rf.js +0 -100
- package/dist/errors-Cr95rSkB.cjs +0 -123
package/README.md
CHANGED
|
@@ -53,6 +53,87 @@ MCP (`POST <path>`, `/mcp` by default) is the wire format clients speak directly
|
|
|
53
53
|
|
|
54
54
|
The MCP endpoint supports both protocol eras on one URL. Finalized `2026-07-28` clients send the version, client capabilities, and mirrored HTTP headers on every request; the server returns typed results plus cache metadata on discovery and list responses without initialization or protocol sessions. Initialization-era clients continue through a stateless compatibility path: `initialize`, `tools/list`, and `tools/call` work as independent requests, and the endpoint never mints `Mcp-Session-Id`. `GET` and `DELETE` return `405` because there is no standalone stream or session to manage.
|
|
55
55
|
|
|
56
|
+
## Caller-dependent tool catalogs
|
|
57
|
+
|
|
58
|
+
Use a request context only when authenticated callers must see different tool
|
|
59
|
+
names. Bind its type once and export the resulting helper for tool files:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// src/lib/mcp/context.ts
|
|
63
|
+
import { defineTool } from "@lovable.dev/mcp-js";
|
|
64
|
+
|
|
65
|
+
export interface AppContext {
|
|
66
|
+
readonly plan: "free" | "pro";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const defineAppTool = defineTool.withAppContext<AppContext>();
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Create the app context from verified auth when an operation needs it, then
|
|
73
|
+
register every tool in the build-time union:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { auth, defineMcp } from "@lovable.dev/mcp-js";
|
|
77
|
+
import type { AppContext } from "./context";
|
|
78
|
+
import exportDataTool from "./tools/export-data";
|
|
79
|
+
|
|
80
|
+
export default defineMcp<AppContext>({
|
|
81
|
+
name: "my-app-mcp",
|
|
82
|
+
title: "My App MCP",
|
|
83
|
+
version: "0.1.0",
|
|
84
|
+
instructions: "Tools for interacting with My App.",
|
|
85
|
+
auth: auth.oauth.issuer({
|
|
86
|
+
issuer: "https://auth.example.com",
|
|
87
|
+
resource: "https://my-app.example.com/mcp",
|
|
88
|
+
}),
|
|
89
|
+
createAppContext: async ({ auth, signal }) => ({
|
|
90
|
+
// Unknown callers get the least-privilege catalog; only a failed lookup throws.
|
|
91
|
+
plan: (await loadPlan(auth.getUserId(), signal)) ?? "free",
|
|
92
|
+
}),
|
|
93
|
+
tools: [exportDataTool],
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Define conditional tools with the bound helper. The predicate is synchronous
|
|
98
|
+
and intentionally receives only `appContext`; handlers receive the same value
|
|
99
|
+
on `ctx.appContext`. Keep predicates pure: do not mutate `appContext` or depend
|
|
100
|
+
on tool evaluation order.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { defineAppTool } from "../context";
|
|
104
|
+
|
|
105
|
+
export default defineAppTool({
|
|
106
|
+
name: "export_data",
|
|
107
|
+
title: "Export data",
|
|
108
|
+
description: "Export the caller's data.",
|
|
109
|
+
enabled: ({ appContext }) => appContext.plan === "pro",
|
|
110
|
+
handler: async (_args, ctx) => {
|
|
111
|
+
const token = ctx.getToken();
|
|
112
|
+
if (!token) throw new Error("Authenticated caller required");
|
|
113
|
+
await exportDataForCaller(token, ctx.signal);
|
|
114
|
+
return { content: [{ type: "text", text: "Export ready." }] };
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The SDK runs `createAppContext` once per request: for `tools/list` when any tool
|
|
120
|
+
has `enabled`, and for a call to a conditional or app-context tool. Plain static
|
|
121
|
+
tool calls, discovery, and ping skip it. A throw from the factory or a predicate
|
|
122
|
+
fails the whole request with a redacted 500, including `tools/list`, so return a
|
|
123
|
+
least-privilege context for callers who lack access and throw only when the
|
|
124
|
+
lookup itself fails. Disabled tools are omitted from
|
|
125
|
+
`tools/list`; direct calls receive the standard unknown-tool error. `enabled`
|
|
126
|
+
gates discovery and dispatch, but the operation must still authorize current
|
|
127
|
+
permissions in its app service or database. Repeating the predicate against the
|
|
128
|
+
same `ctx.appContext` is not a fresh authorization check.
|
|
129
|
+
|
|
130
|
+
Modern responses advertise caching policy to clients: static catalogs are
|
|
131
|
+
`public` for 24 hours; catalogs containing any `enabled` predicate are `private`
|
|
132
|
+
for 12 hours. `private` means a client must not reuse the result across auth
|
|
133
|
+
contexts; it does not itself enforce endpoint access. The publish manifest
|
|
134
|
+
always contains the complete tool union and marks predicate-bearing entries as
|
|
135
|
+
`conditional`, so Lovable can review and display the full API surface.
|
|
136
|
+
|
|
56
137
|
`outputSchema` accepts either the existing object-shape shorthand (`{ value: z.string() }`) or a JSON-Schema-representable Zod schema such as `z.array(z.string())`; `structuredContent` may be any JSON value. The server returns the schema's parsed output, so coercions are reflected in the result; transforms with no truthful JSON Schema are rejected when `defineMcp` runs. Modern clients receive the natural schema and value. The compatibility path wraps non-object schemas and values under `result` for initialization-era clients whose wire format requires an object root.
|
|
57
138
|
|
|
58
139
|
Browser-origin checks apply to the MCP and OAuth metadata routes before authentication. Omit `allowedOrigins` to allow requests with no `Origin` header (Go, desktop, CLI, and server clients) plus same-origin browser requests. Set `allowedOrigins: ["https://client.example.com"]` for exact additional origins, or `allowedOrigins: "any"` to intentionally restore wildcard CORS. Exact and same origins are reflected with `Vary: Origin`; other browser origins receive `403` without an OAuth challenge. Reverse-proxy adapters compare against the effective public origin after applying only their configured trusted forwarded headers.
|
|
@@ -63,7 +144,7 @@ To serve the metadata from a different path — e.g. a workspace-private project
|
|
|
63
144
|
|
|
64
145
|
### `.lovable/mcp/manifest.json`
|
|
65
146
|
|
|
66
|
-
`.lovable/mcp/manifest.json` is a snapshot the Lovable platform reads to register the MCP server. Envelope fields: `version` (manifest schema version), `sdk_version` (the `@lovable.dev/mcp-js` release that wrote the snapshot), `path`, and `auth`. `auth` is the server's auth configuration, lifted into the envelope (not into `mcp`): `{ "type": "none" }`, or `{ "type": "oauth", ... }` mirroring the `defineMcp({ auth })` config (snake_case — `issuer`, `accepted_audiences`, `required_scopes`, `resource`, …). The `mcp` field is the server listing — `server` plus the tool catalog (`name`/`title`/`description`/`annotations
|
|
147
|
+
`.lovable/mcp/manifest.json` is a snapshot the Lovable platform reads to register the MCP server. Envelope fields: `version` (manifest schema version), `sdk_version` (the `@lovable.dev/mcp-js` release that wrote the snapshot), `path`, and `auth`. `auth` is the server's auth configuration, lifted into the envelope (not into `mcp`): `{ "type": "none" }`, or `{ "type": "oauth", ... }` mirroring the `defineMcp({ auth })` config (snake_case — `issuer`, `accepted_audiences`, `required_scopes`, `resource`, …). The `mcp` field is the server listing — `server` plus the complete build-time tool catalog (`name`/`title`/`description`/`annotations`, JSON-Schema `inputSchema`/`outputSchema`, and `conditional: true` for tools with an `enabled` predicate). It's produced by loading the entry and reading the catalog off the `defineMcp` result, so it includes tools built programmatically (spreads, computed names, tools from npm) even when a live caller's `tools/list` narrows the catalog. **The `lovable-mcp-extract-manifest` CLI writes it** (loading the entry through Vite's SSR module loader, so it works under Node/Bun), and removes it when the entry is deleted. The Lovable platform runs the CLI in its commit pipeline; the Vite plugin only generates routes. Commit it: the platform reads the committed file.
|
|
67
148
|
|
|
68
149
|
Three caveats:
|
|
69
150
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as McpProtocolEra } from "./types-S6J_QTXw.cjs";
|
|
2
2
|
//#region src/metrics/impl/base.d.ts
|
|
3
|
-
type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "auth_challenge" | "origin_rejected" | "auth_discovery_config_error" | "auth_discovery_unreachable" | "auth_jwks_config_error" | "auth_jwks_unreachable";
|
|
3
|
+
type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "app_context_error" | "auth_challenge" | "origin_rejected" | "auth_discovery_config_error" | "auth_discovery_unreachable" | "auth_jwks_config_error" | "auth_jwks_unreachable";
|
|
4
4
|
/** One recorded MCP call. Carries no arguments or response payloads — only the
|
|
5
5
|
* tool name, the JSON-RPC method, the result class, timing, and byte sizes.
|
|
6
6
|
* `errorText` is the sole exception: it is logged locally for debugging and
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as McpProtocolEra } from "./types-S6J_QTXw.js";
|
|
2
2
|
//#region src/metrics/impl/base.d.ts
|
|
3
|
-
type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "auth_challenge" | "origin_rejected" | "auth_discovery_config_error" | "auth_discovery_unreachable" | "auth_jwks_config_error" | "auth_jwks_unreachable";
|
|
3
|
+
type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "app_context_error" | "auth_challenge" | "origin_rejected" | "auth_discovery_config_error" | "auth_discovery_unreachable" | "auth_jwks_config_error" | "auth_jwks_unreachable";
|
|
4
4
|
/** One recorded MCP call. Carries no arguments or response payloads — only the
|
|
5
5
|
* tool name, the JSON-RPC method, the result class, timing, and byte sizes.
|
|
6
6
|
* `errorText` is the sole exception: it is logged locally for debugging and
|
|
@@ -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-
|
|
7
|
+
}).then(() => Promise.resolve().then(() => require("../io-Cz81GsrM.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-
|
|
7
|
+
}).then(() => import("../io-BEoJ_gb5.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
|
const require_logger = require("./logger-CN1q-KNn.cjs");
|
|
2
|
-
const require_package = require("./package-
|
|
2
|
+
const require_package = require("./package-DlouusYQ.cjs");
|
|
3
3
|
require("./metadata-path-zd7NSNoa.cjs");
|
|
4
4
|
let jose = require("jose");
|
|
5
5
|
//#region src/core/http.ts
|
|
@@ -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-Ctv5xUSD.js";
|
|
2
|
-
import { t as version } from "./package-
|
|
2
|
+
import { t as version } from "./package-BAYb-3dX.js";
|
|
3
3
|
import "./metadata-path-CAkNcfyY.js";
|
|
4
4
|
import { createLocalJWKSet, decodeProtectedHeader, errors, jwtVerify } from "jose";
|
|
5
5
|
//#region src/core/http.ts
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
const require_logger = require("./logger-CN1q-KNn.cjs");
|
|
2
|
+
const require_schema = require("./schema-D3vClxb7.cjs");
|
|
3
|
+
//#region src/core/define.ts
|
|
4
|
+
function toolRequiresAppContext(tool) {
|
|
5
|
+
return "requiresAppContext" in tool && tool.requiresAppContext === true;
|
|
6
|
+
}
|
|
7
|
+
function assertUniqueNames(mcp) {
|
|
8
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9
|
+
for (const tool of mcp.tools) {
|
|
10
|
+
if (seen.has(tool.name)) throw new Error(`@lovable.dev/mcp-js: duplicate tool name "${tool.name}"`);
|
|
11
|
+
seen.add(tool.name);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function assertAppContextConfiguration(mcp) {
|
|
15
|
+
if (mcp.createAppContext && !mcp.auth) throw new Error(`@lovable.dev/mcp-js: createAppContext requires auth`);
|
|
16
|
+
if (!mcp.createAppContext && mcp.tools.some((tool) => tool.enabled || toolRequiresAppContext(tool))) throw new Error(`@lovable.dev/mcp-js: app-context or conditional tools require createAppContext`);
|
|
17
|
+
}
|
|
18
|
+
function assertNonEmptyString(label, value) {
|
|
19
|
+
if (value.trim() === "") throw new Error(`@lovable.dev/mcp-js: ${label} must not be empty`);
|
|
20
|
+
if (value !== value.trim()) throw new Error(`@lovable.dev/mcp-js: ${label} must not have leading or trailing whitespace`);
|
|
21
|
+
}
|
|
22
|
+
function assertHttpsUrlField(name, value) {
|
|
23
|
+
assertNonEmptyString(`auth.${name}`, value);
|
|
24
|
+
require_logger.parseSafeUrl(`@lovable.dev/mcp-js: auth.${name}`, value);
|
|
25
|
+
}
|
|
26
|
+
function assertScope(scope) {
|
|
27
|
+
if (scope.trim() === "" || /\s/.test(scope)) throw new Error(`@lovable.dev/mcp-js: OAuth scopes must be non-empty space-free tokens`);
|
|
28
|
+
}
|
|
29
|
+
function assertJwtAlgorithm(algorithm) {
|
|
30
|
+
if (algorithm.trim() === "" || /\s/.test(algorithm)) throw new Error(`@lovable.dev/mcp-js: auth.algorithms must contain non-empty space-free tokens`);
|
|
31
|
+
if (/^HS\d+$/i.test(algorithm) || algorithm.toLowerCase() === "none") throw new Error(`@lovable.dev/mcp-js: auth.algorithms cannot include "${algorithm}"; this verifier is JWKS-only`);
|
|
32
|
+
}
|
|
33
|
+
const MAX_CLOCK_TOLERANCE_SECONDS = 300;
|
|
34
|
+
function assertClockToleranceSeconds(value) {
|
|
35
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > MAX_CLOCK_TOLERANCE_SECONDS) throw new Error(`@lovable.dev/mcp-js: auth.clockToleranceSeconds must be a non-negative number of seconds no greater than ${MAX_CLOCK_TOLERANCE_SECONDS}`);
|
|
36
|
+
}
|
|
37
|
+
function assertOAuthConfig(auth) {
|
|
38
|
+
if (auth.type !== "oauth") {
|
|
39
|
+
const authType = String(auth.type);
|
|
40
|
+
throw new Error(`@lovable.dev/mcp-js: unsupported auth type "${authType}"`);
|
|
41
|
+
}
|
|
42
|
+
if (auth.issuer === void 0) throw new Error(`@lovable.dev/mcp-js: auth.issuer is required`);
|
|
43
|
+
assertHttpsUrlField("issuer", auth.issuer);
|
|
44
|
+
if (auth.jwksUri !== void 0) assertHttpsUrlField("jwksUri", auth.jwksUri);
|
|
45
|
+
if (auth.resource !== void 0) assertHttpsUrlField("resource", auth.resource);
|
|
46
|
+
if (auth.resourceName !== void 0) assertNonEmptyString("auth.resourceName", auth.resourceName);
|
|
47
|
+
if (auth.resourceDocumentation !== void 0) assertHttpsUrlField("resourceDocumentation", auth.resourceDocumentation);
|
|
48
|
+
if (auth.protectedResourceMetadataUrl !== void 0) assertHttpsUrlField("protectedResourceMetadataUrl", auth.protectedResourceMetadataUrl);
|
|
49
|
+
if (auth.acceptedAudiences !== void 0) {
|
|
50
|
+
if (!Array.isArray(auth.acceptedAudiences)) throw new Error(`@lovable.dev/mcp-js: auth.acceptedAudiences must be an array`);
|
|
51
|
+
if (auth.acceptedAudiences.length === 0) throw new Error(`@lovable.dev/mcp-js: auth.acceptedAudiences must not be empty`);
|
|
52
|
+
for (const audience of auth.acceptedAudiences) {
|
|
53
|
+
if (typeof audience !== "string") throw new Error(`@lovable.dev/mcp-js: auth.acceptedAudiences must contain strings`);
|
|
54
|
+
assertNonEmptyString("auth.acceptedAudiences", audience);
|
|
55
|
+
if (require_logger.trimTrailingSlash(audience) === "") throw new Error(`@lovable.dev/mcp-js: auth.acceptedAudiences entries must not be only slashes`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (auth.requireOAuthClientClaim !== void 0 && typeof auth.requireOAuthClientClaim !== "boolean") throw new Error(`@lovable.dev/mcp-js: auth.requireOAuthClientClaim must be a boolean`);
|
|
59
|
+
if (auth.acceptResourceClaim !== void 0 && typeof auth.acceptResourceClaim !== "boolean") throw new Error(`@lovable.dev/mcp-js: auth.acceptResourceClaim must be a boolean`);
|
|
60
|
+
if (auth.requiredScopes !== void 0) {
|
|
61
|
+
if (!Array.isArray(auth.requiredScopes)) throw new Error(`@lovable.dev/mcp-js: auth.requiredScopes must be an array`);
|
|
62
|
+
for (const scope of auth.requiredScopes) assertScope(scope);
|
|
63
|
+
}
|
|
64
|
+
if (auth.algorithms !== void 0) {
|
|
65
|
+
if (!Array.isArray(auth.algorithms)) throw new Error(`@lovable.dev/mcp-js: auth.algorithms must be an array`);
|
|
66
|
+
if (auth.algorithms.length === 0) throw new Error(`@lovable.dev/mcp-js: auth.algorithms must not be empty`);
|
|
67
|
+
for (const algorithm of auth.algorithms) assertJwtAlgorithm(algorithm);
|
|
68
|
+
}
|
|
69
|
+
if (auth.accessTokenTyp !== void 0) {
|
|
70
|
+
if (!Array.isArray(auth.accessTokenTyp)) throw new Error(`@lovable.dev/mcp-js: auth.accessTokenTyp must be an array`);
|
|
71
|
+
if (auth.accessTokenTyp.length === 0) throw new Error(`@lovable.dev/mcp-js: auth.accessTokenTyp must not be empty`);
|
|
72
|
+
for (const typ of auth.accessTokenTyp) {
|
|
73
|
+
if (typeof typ !== "string") throw new Error(`@lovable.dev/mcp-js: auth.accessTokenTyp must contain strings`);
|
|
74
|
+
assertNonEmptyString("auth.accessTokenTyp", typ);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (auth.clockToleranceSeconds !== void 0) assertClockToleranceSeconds(auth.clockToleranceSeconds);
|
|
78
|
+
if (auth.resource === void 0 && auth.acceptedAudiences === void 0) throw new Error(`@lovable.dev/mcp-js: auth.resource or auth.acceptedAudiences is required`);
|
|
79
|
+
}
|
|
80
|
+
function freezeAuth(auth) {
|
|
81
|
+
if (!auth) return;
|
|
82
|
+
if (auth.acceptedAudiences) Object.freeze(auth.acceptedAudiences);
|
|
83
|
+
if (auth.requiredScopes) Object.freeze(auth.requiredScopes);
|
|
84
|
+
if (auth.algorithms) Object.freeze(auth.algorithms);
|
|
85
|
+
if (auth.accessTokenTyp) Object.freeze(auth.accessTokenTyp);
|
|
86
|
+
Object.freeze(auth);
|
|
87
|
+
}
|
|
88
|
+
function assertAllowedOrigins(allowedOrigins) {
|
|
89
|
+
if (allowedOrigins === void 0 || allowedOrigins === "any") return;
|
|
90
|
+
if (!Array.isArray(allowedOrigins)) throw new Error(`@lovable.dev/mcp-js: allowedOrigins must be "any" or an array of exact origins`);
|
|
91
|
+
for (const origin of allowedOrigins) {
|
|
92
|
+
if (typeof origin !== "string") throw new Error(`@lovable.dev/mcp-js: allowedOrigins must contain strings`);
|
|
93
|
+
let parsed;
|
|
94
|
+
try {
|
|
95
|
+
parsed = new URL(origin);
|
|
96
|
+
} catch {
|
|
97
|
+
throw new Error(`@lovable.dev/mcp-js: allowedOrigins must contain valid exact origins`);
|
|
98
|
+
}
|
|
99
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.origin !== origin) throw new Error(`@lovable.dev/mcp-js: allowedOrigins entry "${origin}" must be an exact http(s) origin without a path, query, fragment, or trailing slash`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function assertToolSchemas(mcp) {
|
|
103
|
+
for (const tool of mcp.tools) for (const [name, definition, strategy] of [[
|
|
104
|
+
"inputSchema",
|
|
105
|
+
tool.inputSchema,
|
|
106
|
+
"input"
|
|
107
|
+
], [
|
|
108
|
+
"outputSchema",
|
|
109
|
+
tool.outputSchema,
|
|
110
|
+
"output"
|
|
111
|
+
]]) {
|
|
112
|
+
if (!definition) continue;
|
|
113
|
+
try {
|
|
114
|
+
require_schema.jsonSchemaFromDefinition(definition, strategy);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const detail = error instanceof Error ? `: ${error.message}` : "";
|
|
117
|
+
throw new Error(`@lovable.dev/mcp-js: tool "${tool.name}" ${name} cannot be represented as JSON Schema${detail}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** Bind app context once while retaining input/output inference for every tool. */
|
|
122
|
+
const defineStaticTool = (def) => def;
|
|
123
|
+
const defineTool = Object.assign(defineStaticTool, { withAppContext: () => (def) => {
|
|
124
|
+
return {
|
|
125
|
+
...def,
|
|
126
|
+
requiresAppContext: true
|
|
127
|
+
};
|
|
128
|
+
} });
|
|
129
|
+
/**
|
|
130
|
+
* Declare the MCP server. `export default` the result from your MCP
|
|
131
|
+
* entrypoint (default `lib/mcp/index.ts`); the Vite plugin reads it to
|
|
132
|
+
* emit the framework-specific route(s) at build time.
|
|
133
|
+
*/
|
|
134
|
+
function defineMcp(def) {
|
|
135
|
+
assertNonEmptyString("name", def.name);
|
|
136
|
+
assertNonEmptyString("title", def.title);
|
|
137
|
+
assertNonEmptyString("version", def.version);
|
|
138
|
+
assertUniqueNames(def);
|
|
139
|
+
assertAppContextConfiguration(def);
|
|
140
|
+
if (def.auth) assertOAuthConfig(def.auth);
|
|
141
|
+
assertAllowedOrigins(def.allowedOrigins);
|
|
142
|
+
assertToolSchemas(def);
|
|
143
|
+
require_logger.resolveMetricsConfig(def.metrics);
|
|
144
|
+
freezeAuth(def.auth);
|
|
145
|
+
if (Array.isArray(def.allowedOrigins)) Object.freeze(def.allowedOrigins);
|
|
146
|
+
Object.freeze(def.tools);
|
|
147
|
+
for (const tool of def.tools) Object.freeze(tool);
|
|
148
|
+
return def;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
//#region src/auth/context.ts
|
|
152
|
+
const NEVER_ABORTED = new AbortController().signal;
|
|
153
|
+
/** Verified caller identity exposed to the app-context factory.
|
|
154
|
+
* `getToken()` is the sole bearer escape hatch. */
|
|
155
|
+
var AuthContext = class {
|
|
156
|
+
#auth;
|
|
157
|
+
constructor(auth) {
|
|
158
|
+
this.#auth = auth;
|
|
159
|
+
}
|
|
160
|
+
/** Whether the in-flight tool call carries a verified auth context. */
|
|
161
|
+
isAuthenticated() {
|
|
162
|
+
return this.#auth !== void 0;
|
|
163
|
+
}
|
|
164
|
+
/** The verified bearer token, or `undefined` when unauthenticated. Pass it to downstream APIs; never return or log it. */
|
|
165
|
+
getToken() {
|
|
166
|
+
return this.#auth?.bearer.token;
|
|
167
|
+
}
|
|
168
|
+
/** The verified user id (the token `sub`), or `undefined`. */
|
|
169
|
+
getUserId() {
|
|
170
|
+
return this.#auth?.principal.sub;
|
|
171
|
+
}
|
|
172
|
+
/** The verified user email, or `undefined` when absent. */
|
|
173
|
+
getUserEmail() {
|
|
174
|
+
return this.#auth?.principal.email;
|
|
175
|
+
}
|
|
176
|
+
/** The verified OAuth `client_id`, or `undefined`. */
|
|
177
|
+
getClientId() {
|
|
178
|
+
return this.#auth?.principal.clientId;
|
|
179
|
+
}
|
|
180
|
+
/** The verified OAuth scopes, or `undefined` when unauthenticated. */
|
|
181
|
+
getScopes() {
|
|
182
|
+
return this.#auth?.principal.scopes;
|
|
183
|
+
}
|
|
184
|
+
/** The verified token issuer, or `undefined`. */
|
|
185
|
+
getIssuer() {
|
|
186
|
+
return this.#auth?.principal.issuer;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The full verified JWT claims, or `undefined`. Use this for app/business
|
|
190
|
+
* authorization on issuer-specific claims that have no dedicated accessor.
|
|
191
|
+
*/
|
|
192
|
+
getClaims() {
|
|
193
|
+
return this.#auth?.principal.claims;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
/** The per-request context passed to every tool handler as its second argument. */
|
|
197
|
+
var ToolContext = class extends AuthContext {
|
|
198
|
+
#appContext;
|
|
199
|
+
#signal;
|
|
200
|
+
#client;
|
|
201
|
+
#sendProgress;
|
|
202
|
+
constructor(auth, request = {}, appContext) {
|
|
203
|
+
super(auth);
|
|
204
|
+
this.#appContext = appContext;
|
|
205
|
+
this.#signal = request.signal ?? NEVER_ABORTED;
|
|
206
|
+
this.#client = request.client ?? { protocol: "legacy" };
|
|
207
|
+
this.#sendProgress = request.sendProgress;
|
|
208
|
+
}
|
|
209
|
+
/** App-defined context created for this tool call. */
|
|
210
|
+
get appContext() {
|
|
211
|
+
return this.#appContext;
|
|
212
|
+
}
|
|
213
|
+
/** Aborts when the client cancels the request or disconnects. */
|
|
214
|
+
get signal() {
|
|
215
|
+
return this.#signal;
|
|
216
|
+
}
|
|
217
|
+
/** What the client declared about itself on this request. Unverified input. */
|
|
218
|
+
get client() {
|
|
219
|
+
return this.#client;
|
|
220
|
+
}
|
|
221
|
+
/** Send a progress notification for this call. A no-op when the client
|
|
222
|
+
* didn't request progress (no `progressToken` on the request). */
|
|
223
|
+
async progress(update) {
|
|
224
|
+
await this.#sendProgress?.(update);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region src/core/errors.ts
|
|
229
|
+
const TOOL_ERROR_BRAND = Symbol.for("@lovable.dev/mcp-js/tool-error");
|
|
230
|
+
/** Error whose message is meant for the remote MCP caller; thrown from a handler
|
|
231
|
+
* it becomes an `isError` result carrying exactly `message`. */
|
|
232
|
+
var ToolError = class extends Error {
|
|
233
|
+
constructor(message, options) {
|
|
234
|
+
super(message, options);
|
|
235
|
+
this.name = "ToolError";
|
|
236
|
+
Object.defineProperty(this, TOOL_ERROR_BRAND, { value: true });
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
function isToolError(err) {
|
|
240
|
+
return err instanceof Error && Object.getOwnPropertyDescriptor(err, TOOL_ERROR_BRAND)?.value === true;
|
|
241
|
+
}
|
|
242
|
+
/** The caller-visible message of a thrown ToolError, or undefined for anything
|
|
243
|
+
* else — including when inspecting the value itself throws (fail closed). */
|
|
244
|
+
function resolveToolErrorMessage(err) {
|
|
245
|
+
try {
|
|
246
|
+
return isToolError(err) ? String(err.message) : void 0;
|
|
247
|
+
} catch {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const MAX_ERROR_SUMMARY = 500;
|
|
252
|
+
/** Bounded name+message line for local logs; never for wire responses. */
|
|
253
|
+
function errorSummary(err) {
|
|
254
|
+
try {
|
|
255
|
+
const text = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
|
|
256
|
+
return text.length > MAX_ERROR_SUMMARY ? `${text.slice(0, MAX_ERROR_SUMMARY)}…` : text;
|
|
257
|
+
} catch {
|
|
258
|
+
return "unprintable error";
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
//#endregion
|
|
262
|
+
Object.defineProperty(exports, "AuthContext", {
|
|
263
|
+
enumerable: true,
|
|
264
|
+
get: function() {
|
|
265
|
+
return AuthContext;
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
Object.defineProperty(exports, "ToolContext", {
|
|
269
|
+
enumerable: true,
|
|
270
|
+
get: function() {
|
|
271
|
+
return ToolContext;
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
Object.defineProperty(exports, "ToolError", {
|
|
275
|
+
enumerable: true,
|
|
276
|
+
get: function() {
|
|
277
|
+
return ToolError;
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
Object.defineProperty(exports, "defineMcp", {
|
|
281
|
+
enumerable: true,
|
|
282
|
+
get: function() {
|
|
283
|
+
return defineMcp;
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
Object.defineProperty(exports, "defineTool", {
|
|
287
|
+
enumerable: true,
|
|
288
|
+
get: function() {
|
|
289
|
+
return defineTool;
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
Object.defineProperty(exports, "errorSummary", {
|
|
293
|
+
enumerable: true,
|
|
294
|
+
get: function() {
|
|
295
|
+
return errorSummary;
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
Object.defineProperty(exports, "resolveToolErrorMessage", {
|
|
299
|
+
enumerable: true,
|
|
300
|
+
get: function() {
|
|
301
|
+
return resolveToolErrorMessage;
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
Object.defineProperty(exports, "toolRequiresAppContext", {
|
|
305
|
+
enumerable: true,
|
|
306
|
+
get: function() {
|
|
307
|
+
return toolRequiresAppContext;
|
|
308
|
+
}
|
|
309
|
+
});
|