@lovable.dev/mcp-js 3.1.1 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +43 -0
  2. package/dist/{authorize-Dt7ll7Ur.d.ts → authorize-DUEaDXjU.d.ts} +1 -1
  3. package/dist/{authorize-BS_In2AW.d.cts → authorize-bDiUiJco.d.cts} +1 -1
  4. package/dist/{base-B7D0KqaY.d.ts → base-CLO7XsxC.d.ts} +1 -1
  5. package/dist/{base-D3TT1Wup.d.cts → base-D2d7lJY5.d.cts} +1 -1
  6. package/dist/cli/extract-manifest.cjs +1 -1
  7. package/dist/cli/extract-manifest.js +1 -1
  8. package/dist/{cors-CEF2VQQ4.cjs → cors-CAjdoGLn.cjs} +1 -1
  9. package/dist/{cors-DbJgGIwT.js → cors-DqGRvw0A.js} +1 -1
  10. package/dist/{errors-CWxgUZH3.cjs → errors-CLfxIB-l.cjs} +3 -2
  11. package/dist/{errors-ZmYYVYKN.js → errors-CljrUVby.js} +3 -2
  12. package/dist/format-DDzvc92Z.cjs +41 -0
  13. package/dist/format-DKEuO8Tn.js +30 -0
  14. package/dist/hooks-BOdDe251.js +353 -0
  15. package/dist/hooks-xQl3EkDa.cjs +382 -0
  16. package/dist/index.cjs +1 -1
  17. package/dist/index.d.cts +2 -2
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +1 -1
  20. package/dist/{io-DvrElu4G.cjs → io-C-KJpQde.cjs} +7 -6
  21. package/dist/{io-BvogiiQ1.d.ts → io-CFyHLyvs.d.ts} +1 -1
  22. package/dist/{io-Cuzga3zO.js → io-DewJxgO4.js} +3 -2
  23. package/dist/{io-Bn0ErYbG.d.cts → io-DfUvQ-SV.d.cts} +1 -1
  24. package/dist/{mcp-cPwyvSCx.js → mcp-ClL3tmtt.js} +161 -9
  25. package/dist/{mcp-BClUdQ3O.cjs → mcp-FRaH2mQW.cjs} +160 -8
  26. package/dist/{package-CaoFQDOo.cjs → package-B0CFKfHW.cjs} +1 -1
  27. package/dist/{package-Dvpf79Jm.js → package-tjBEL0hN.js} +1 -1
  28. package/dist/protocols/mcp/index.cjs +1 -1
  29. package/dist/protocols/mcp/index.d.cts +3 -3
  30. package/dist/protocols/mcp/index.d.ts +3 -3
  31. package/dist/protocols/mcp/index.js +1 -1
  32. package/dist/protocols/oauth-metadata.cjs +1 -1
  33. package/dist/protocols/oauth-metadata.d.cts +3 -3
  34. package/dist/protocols/oauth-metadata.d.ts +3 -3
  35. package/dist/protocols/oauth-metadata.js +1 -1
  36. package/dist/stacks/supabase/index.cjs +2 -2
  37. package/dist/stacks/supabase/index.d.cts +1 -1
  38. package/dist/stacks/supabase/index.d.ts +1 -1
  39. package/dist/stacks/supabase/index.js +2 -2
  40. package/dist/stacks/supabase/vite.cjs +40 -18
  41. package/dist/stacks/supabase/vite.d.cts +1 -1
  42. package/dist/stacks/supabase/vite.d.ts +1 -1
  43. package/dist/stacks/supabase/vite.js +34 -12
  44. package/dist/stacks/tanstack/index.cjs +2 -2
  45. package/dist/stacks/tanstack/index.d.cts +2 -2
  46. package/dist/stacks/tanstack/index.d.ts +2 -2
  47. package/dist/stacks/tanstack/index.js +2 -2
  48. package/dist/stacks/tanstack/vite.cjs +22 -22
  49. package/dist/stacks/tanstack/vite.d.cts +1 -1
  50. package/dist/stacks/tanstack/vite.d.ts +1 -1
  51. package/dist/stacks/tanstack/vite.js +14 -14
  52. package/dist/testing/index.d.cts +1 -1
  53. package/dist/testing/index.d.ts +1 -1
  54. package/dist/{types-BX8RawmT.d.ts → types-CAFCH0yK.d.cts} +7 -1
  55. package/dist/{types-BX8RawmT.d.cts → types-CAFCH0yK.d.ts} +7 -1
  56. package/package.json +16 -4
  57. package/skill-imports.d.cts +1 -0
  58. package/skill-imports.d.ts +11 -0
  59. package/dist/supabase-config-DITfH_bn.js +0 -30
  60. package/dist/supabase-config-Dz13d9ze.cjs +0 -41
package/README.md CHANGED
@@ -44,6 +44,48 @@ Manifest extraction allows **512 tools** in the evaluated `defineMcp({ tools })`
44
44
 
45
45
  `inputSchema` is closed: a `tools/call` carrying an argument key the schema does not declare fails in-band (`isError: true`, naming the key) instead of silently dropping it, and `tools/list` advertises `additionalProperties: false`. Set `strict: false` on a tool to accept and drop unknown keys instead.
46
46
 
47
+ ## Task workflows as skills
48
+
49
+ **Experimental:** Skills support follows the developing [MCP Skills extension](https://modelcontextprotocol.io/extensions/skills). Client support varies, and the integration may change as the specification evolves.
50
+
51
+ Keep shared terminology and server-wide rules in `instructions`, individual tool contracts in tool descriptions, and task procedures in [Agent Skills](https://agentskills.io/specification). Import a dedicated skill directory and pass it in `defineMcp({ skills: [refunds] })`:
52
+
53
+ ```ts
54
+ import refunds from "./skills/refunds?skill";
55
+ ```
56
+
57
+ Add `/// <reference types="@lovable.dev/mcp-js/skill-imports" />` to an included `.d.ts` file. Imports use relative or absolute directory paths, not aliases. Both stack plugins and the manifest extractor compile these imports; the deployed server needs no source directory or filesystem access. Imported values have the opaque `Skill` type: pass them to `defineMcp`, rather than constructing or inspecting compiled manifests. Each directory needs `SKILL.md` with valid YAML `name` and `description`; `name` must match its directory. All JSON-compatible frontmatter fields are preserved. Supporting files must be UTF-8 text. Binary content, ASCII controls other than tab/CR/LF (including DEL), symlinks, cycles and metadata that cannot survive JSON serialization fail the build. Text scripts can be included, but the SDK neither installs nor executes them.
58
+
59
+ **Every ordinary file beneath an imported directory is published recursively.** Hidden entries (a dot-prefixed path segment) fail the build unless each file is explicitly allowlisted on that import:
60
+
61
+ ```ts
62
+ import refunds from "./skills/refunds?allowHidden=templates/.prettierrc&allowHidden=.config/example.json&skill";
63
+ ```
64
+
65
+ Repeat `allowHidden` for each exact, case-sensitive file path relative to the skill directory. Directory-wide grants, globs, traversal paths, duplicate entries and entries that do not name an existing file are rejected. A hidden directory is traversed only for listed descendants; every file beneath it needs its own entry. An empty hidden directory fails too. Allowed files still pass the text-only and symlink checks. Combine `allowHidden` with `path` in either order, keeping `skill` last; percent-encode reserved characters in values (for example `%26` for `&` and `%25` for `%`).
66
+
67
+ Use dedicated publication directories without credentials or private documents. The allowlist prevents accidental hidden-file publication, not secrets in ordinary or explicitly approved files. Files use the same server-level OAuth and origin policy as tools; conditional tool permissions do not hide skills or their contents.
68
+
69
+ By default, `./skills/refunds?skill` publishes `skill://refunds/SKILL.md` and its supporting files. Use root-relative file references such as `references/rules.md` inside a skill. Reference a different skill with its complete URI; the host resolves it through `skills/get` and its skill-loading path. Reading `SKILL.md` as an ordinary resource does not activate it.
70
+
71
+ An explicit path supports namespacing and nested skills:
72
+
73
+ ```ts
74
+ import refunds from "./skills/refunds?path=acme/refunds&skill";
75
+ import escalation from "./skills/refunds/escalation?path=acme/refunds/escalation&skill";
76
+ ```
77
+
78
+ Register both imports to list both skills. Keep a nested import's path consistent with its enclosing skill so shared files have one URI. Nested directories remain supporting content unless separately registered. The last path segment must match the skill's name; duplicate names at distinct URIs are allowed. URI collisions with different content fail. Paths are encoded per segment, so Unicode supporting filenames are preserved.
79
+
80
+ The server advertises the [Skills extension](https://modelcontextprotocol.io/extensions/skills), implements `skills/list` and `skills/get`, and serves complete manifests and byte-exact files through MCP resources. Client support is evolving; consult the official page for current implementations.
81
+
82
+ | Client declaration | Server instructions |
83
+ | --- | --- |
84
+ | Declares `io.modelcontextprotocol/skills` | Authored instructions plus names, descriptions and URIs; the host loads skills on demand. |
85
+ | No declaration | Authored instructions plus a deterministic, URI-labelled copy of every included text file. |
86
+
87
+ Fallback is reference text, not installation, execution or a permission grant. It preserves source text rather than summarizing it or rewriting links. A capable client that omits the declaration can receive both representations, even if its native skill loader is disabled. Host context limits still apply: the SDK does not truncate instructions or guarantee that a host will retain them. Build output lists published file sizes; the standard recommends at most 512 files and 16 MiB per skill, and fallback instructions should be substantially smaller for practical model context. Omit `skills` to retain existing tools-only behavior.
88
+
47
89
  ## What the plugin emits
48
90
 
49
91
  | URL | File | Purpose |
@@ -496,6 +538,7 @@ Ownership: the emitted `index.ts` carries a `// AUTO-GENERATED by @lovable.dev/m
496
538
  | Subpath | Contents |
497
539
  | --------------------------------------- | ----------------------------------------------------------------------- |
498
540
  | `@lovable.dev/mcp-js` | `defineTool`, `defineMcp`, public types |
541
+ | `@lovable.dev/mcp-js/skill-imports` | Type-only declarations for skill directory imports |
499
542
  | `@lovable.dev/mcp-js/protocols/mcp` | `createMcpProtocolHandler` — Web-Standard MCP-over-HTTP |
500
543
  | `@lovable.dev/mcp-js/protocols/oauth-metadata` | `createOAuthProtectedResourceMetadataHandler` (the `auth` namespace lives at the root) |
501
544
  | `@lovable.dev/mcp-js/stacks/tanstack` | TanStack-route-ctx adapters (`createTanStack*Handler`) |
@@ -1,4 +1,4 @@
1
- import "./types-BX8RawmT.js";
1
+ import "./types-CAFCH0yK.js";
2
2
  //#region src/metrics/recorder.d.ts
3
3
  type ScheduleBackground = (task: Promise<unknown>) => void;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import "./types-BX8RawmT.cjs";
1
+ import "./types-CAFCH0yK.cjs";
2
2
  //#region src/metrics/recorder.d.ts
3
3
  type ScheduleBackground = (task: Promise<unknown>) => void;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { j as McpProtocolEra } from "./types-BX8RawmT.js";
1
+ import { M as McpProtocolEra } from "./types-CAFCH0yK.js";
2
2
  //#region src/metrics/impl/base.d.ts
3
3
  type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "app_context_error" | "auth_challenge" | "auth_token_expired" | "auth_token_invalid" | "auth_insufficient_scope" | "auth_unexpected_error" | "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
@@ -1,4 +1,4 @@
1
- import { j as McpProtocolEra } from "./types-BX8RawmT.cjs";
1
+ import { M as McpProtocolEra } from "./types-CAFCH0yK.cjs";
2
2
  //#region src/metrics/impl/base.d.ts
3
3
  type InvocationOutcome = "ok" | "tool_error" | "handler_error" | "transport_error" | "app_context_error" | "auth_challenge" | "auth_token_expired" | "auth_token_invalid" | "auth_insufficient_scope" | "auth_unexpected_error" | "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
@@ -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-DvrElu4G.cjs"))).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
7
+ }).then(() => Promise.resolve().then(() => require("../io-C-KJpQde.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-Cuzga3zO.js")).then(({ runExtract }) => runExtract(projectRoot)).catch((err) => {
7
+ }).then(() => import("../io-DewJxgO4.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-C-Hdu57K.cjs");
2
- const require_package = require("./package-CaoFQDOo.cjs");
2
+ const require_package = require("./package-B0CFKfHW.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-CpLgYbCG.js";
2
- import { t as version } from "./package-Dvpf79Jm.js";
2
+ import { t as version } from "./package-tjBEL0hN.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,6 @@
1
1
  const require_schema = require("./schema-DNMsvJwE.cjs");
2
2
  const require_logger = require("./logger-C-Hdu57K.cjs");
3
+ const require_format = require("./format-DDzvc92Z.cjs");
3
4
  //#region src/core/define.ts
4
5
  function toolRequiresAppContext(tool) {
5
6
  return "requiresAppContext" in tool && tool.requiresAppContext === true;
@@ -146,11 +147,11 @@ function defineMcp(def) {
146
147
  if (Array.isArray(def.allowedOrigins)) Object.freeze(def.allowedOrigins);
147
148
  Object.freeze(def.tools);
148
149
  for (const tool of def.tools) Object.freeze(tool);
150
+ if (def.skills !== void 0) require_format.validateSkills(def.skills);
149
151
  return def;
150
152
  }
151
153
  //#endregion
152
154
  //#region src/auth/context.ts
153
- const NEVER_ABORTED = new AbortController().signal;
154
155
  /** Verified caller identity exposed to the app-context factory.
155
156
  * `getToken()` is the sole bearer escape hatch. */
156
157
  var AuthContext = class {
@@ -203,7 +204,7 @@ var ToolContext = class extends AuthContext {
203
204
  constructor(auth, request = {}, appContext) {
204
205
  super(auth);
205
206
  this.#appContext = appContext;
206
- this.#signal = request.signal ?? NEVER_ABORTED;
207
+ this.#signal = request.signal ?? new AbortController().signal;
207
208
  this.#client = request.client ?? { protocol: "legacy" };
208
209
  this.#sendProgress = request.sendProgress;
209
210
  }
@@ -1,4 +1,5 @@
1
1
  import { o as parseSafeUrl, s as trimTrailingSlash, u as resolveMetricsConfig } from "./logger-CpLgYbCG.js";
2
+ import { n as validateSkills } from "./format-DKEuO8Tn.js";
2
3
  import { t as jsonSchemaFromDefinition } from "./schema-JK_1KkOa.js";
3
4
  //#region src/core/define.ts
4
5
  function toolRequiresAppContext(tool) {
@@ -146,11 +147,11 @@ function defineMcp(def) {
146
147
  if (Array.isArray(def.allowedOrigins)) Object.freeze(def.allowedOrigins);
147
148
  Object.freeze(def.tools);
148
149
  for (const tool of def.tools) Object.freeze(tool);
150
+ if (def.skills !== void 0) validateSkills(def.skills);
149
151
  return def;
150
152
  }
151
153
  //#endregion
152
154
  //#region src/auth/context.ts
153
- const NEVER_ABORTED = new AbortController().signal;
154
155
  /** Verified caller identity exposed to the app-context factory.
155
156
  * `getToken()` is the sole bearer escape hatch. */
156
157
  var AuthContext = class {
@@ -203,7 +204,7 @@ var ToolContext = class extends AuthContext {
203
204
  constructor(auth, request = {}, appContext) {
204
205
  super(auth);
205
206
  this.#appContext = appContext;
206
- this.#signal = request.signal ?? NEVER_ABORTED;
207
+ this.#signal = request.signal ?? new AbortController().signal;
207
208
  this.#client = request.client ?? { protocol: "legacy" };
208
209
  this.#sendProgress = request.sendProgress;
209
210
  }
@@ -0,0 +1,41 @@
1
+ //#region src/skills/format.ts
2
+ const COMPILED_SKILL_KIND = "lovable-mcp-compiled-skill";
3
+ function freezeTree(value) {
4
+ if (typeof value !== "object" || value === null) return;
5
+ Object.freeze(value);
6
+ for (const child of Object.values(value)) freezeTree(child);
7
+ }
8
+ function validateSkills(skills) {
9
+ if (!Array.isArray(skills)) throw new TypeError("@lovable.dev/mcp-js: skills must be an array of ?skill imports");
10
+ const uris = /* @__PURE__ */ new Set();
11
+ const files = /* @__PURE__ */ new Map();
12
+ for (const skill of skills) {
13
+ if (!skill || skill.kind !== "lovable-mcp-compiled-skill" || !Array.isArray(skill.files) || !skill.frontmatter || typeof skill.frontmatter.name !== "string" || typeof skill.frontmatter.description !== "string" || typeof skill.rootUri !== "string" || skill.uri !== `${skill.rootUri}/SKILL.md` || !skill.rootUri.startsWith("skill://") || decodeURIComponent(skill.rootUri.split("/").at(-1) ?? "") !== skill.frontmatter.name) throw new TypeError("@lovable.dev/mcp-js: skills entries must come from a ?skill import");
14
+ if (uris.has(skill.uri)) throw new Error(`@lovable.dev/mcp-js: duplicate skill URI ${skill.uri}`);
15
+ uris.add(skill.uri);
16
+ const paths = /* @__PURE__ */ new Set();
17
+ for (const file of skill.files) {
18
+ if (!file || typeof file.path !== "string" || file.path.split("/").some((part) => !part || part === "." || part === "..") || file.uri !== `${skill.rootUri}/${file.path.split("/").map(encodeURIComponent).join("/")}` || typeof file.text !== "string" || typeof file.mimeType !== "string" || !/^sha256:[a-f0-9]{64}$/.test(file.digest) || file.size !== new TextEncoder().encode(file.text).length || paths.has(file.path)) throw new TypeError(`@lovable.dev/mcp-js: invalid compiled skill file in ${skill.uri}`);
19
+ paths.add(file.path);
20
+ const existing = files.get(file.uri);
21
+ if (existing && (existing.text !== file.text || existing.digest !== file.digest || existing.mimeType !== file.mimeType)) throw new Error(`@lovable.dev/mcp-js: skill file URI collision with different content: ${file.uri}`);
22
+ files.set(file.uri, file);
23
+ }
24
+ if (!paths.has("SKILL.md")) throw new Error(`@lovable.dev/mcp-js: missing SKILL.md in ${skill.uri}`);
25
+ freezeTree(skill);
26
+ }
27
+ Object.freeze(skills);
28
+ }
29
+ //#endregion
30
+ Object.defineProperty(exports, "COMPILED_SKILL_KIND", {
31
+ enumerable: true,
32
+ get: function() {
33
+ return COMPILED_SKILL_KIND;
34
+ }
35
+ });
36
+ Object.defineProperty(exports, "validateSkills", {
37
+ enumerable: true,
38
+ get: function() {
39
+ return validateSkills;
40
+ }
41
+ });
@@ -0,0 +1,30 @@
1
+ //#region src/skills/format.ts
2
+ const COMPILED_SKILL_KIND = "lovable-mcp-compiled-skill";
3
+ function freezeTree(value) {
4
+ if (typeof value !== "object" || value === null) return;
5
+ Object.freeze(value);
6
+ for (const child of Object.values(value)) freezeTree(child);
7
+ }
8
+ function validateSkills(skills) {
9
+ if (!Array.isArray(skills)) throw new TypeError("@lovable.dev/mcp-js: skills must be an array of ?skill imports");
10
+ const uris = /* @__PURE__ */ new Set();
11
+ const files = /* @__PURE__ */ new Map();
12
+ for (const skill of skills) {
13
+ if (!skill || skill.kind !== "lovable-mcp-compiled-skill" || !Array.isArray(skill.files) || !skill.frontmatter || typeof skill.frontmatter.name !== "string" || typeof skill.frontmatter.description !== "string" || typeof skill.rootUri !== "string" || skill.uri !== `${skill.rootUri}/SKILL.md` || !skill.rootUri.startsWith("skill://") || decodeURIComponent(skill.rootUri.split("/").at(-1) ?? "") !== skill.frontmatter.name) throw new TypeError("@lovable.dev/mcp-js: skills entries must come from a ?skill import");
14
+ if (uris.has(skill.uri)) throw new Error(`@lovable.dev/mcp-js: duplicate skill URI ${skill.uri}`);
15
+ uris.add(skill.uri);
16
+ const paths = /* @__PURE__ */ new Set();
17
+ for (const file of skill.files) {
18
+ if (!file || typeof file.path !== "string" || file.path.split("/").some((part) => !part || part === "." || part === "..") || file.uri !== `${skill.rootUri}/${file.path.split("/").map(encodeURIComponent).join("/")}` || typeof file.text !== "string" || typeof file.mimeType !== "string" || !/^sha256:[a-f0-9]{64}$/.test(file.digest) || file.size !== new TextEncoder().encode(file.text).length || paths.has(file.path)) throw new TypeError(`@lovable.dev/mcp-js: invalid compiled skill file in ${skill.uri}`);
19
+ paths.add(file.path);
20
+ const existing = files.get(file.uri);
21
+ if (existing && (existing.text !== file.text || existing.digest !== file.digest || existing.mimeType !== file.mimeType)) throw new Error(`@lovable.dev/mcp-js: skill file URI collision with different content: ${file.uri}`);
22
+ files.set(file.uri, file);
23
+ }
24
+ if (!paths.has("SKILL.md")) throw new Error(`@lovable.dev/mcp-js: missing SKILL.md in ${skill.uri}`);
25
+ freezeTree(skill);
26
+ }
27
+ Object.freeze(skills);
28
+ }
29
+ //#endregion
30
+ export { validateSkills as n, COMPILED_SKILL_KIND as t };
@@ -0,0 +1,353 @@
1
+ import { t as COMPILED_SKILL_KIND } from "./format-DKEuO8Tn.js";
2
+ import { lstatSync, readFileSync, readdirSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { JSON_SCHEMA, load } from "js-yaml";
6
+ //#region src/core/fs-errors.ts
7
+ function isFileMissing(err) {
8
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
9
+ }
10
+ //#endregion
11
+ //#region src/core/supabase-config.ts
12
+ const SUPABASE_CONFIG_RELATIVE_PATH = "supabase/config.toml";
13
+ function readSupabaseProjectRef(projectRoot) {
14
+ let content;
15
+ try {
16
+ content = readFileSync(join(projectRoot, SUPABASE_CONFIG_RELATIVE_PATH), "utf8");
17
+ } catch (err) {
18
+ if (isFileMissing(err)) return void 0;
19
+ throw err;
20
+ }
21
+ for (const raw of content.split(/\r?\n/)) {
22
+ const line = raw.trim();
23
+ if (line.length === 0 || line.startsWith("#")) continue;
24
+ if (line.startsWith("[")) break;
25
+ const match = /^project_id\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);
26
+ if (match) {
27
+ const value = match[1] ?? match[2] ?? "";
28
+ return value.length > 0 ? value : void 0;
29
+ }
30
+ }
31
+ }
32
+ //#endregion
33
+ //#region src/skills/frontmatter.ts
34
+ const NAME_RE = /^[\p{Ll}\p{Lo}\p{N}]+(?:-[\p{Ll}\p{Lo}\p{N}]+)*$/u;
35
+ function assertJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
36
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
37
+ if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0)) {
38
+ if (!Number.isInteger(value) || Number.isSafeInteger(value)) return;
39
+ }
40
+ if (typeof value !== "object" || value === null || ancestors.has(value)) throw new Error("frontmatter must contain finite JSON values without cycles or unsafe integers");
41
+ ancestors.add(value);
42
+ for (const child of Object.values(value)) assertJsonValue(child, ancestors);
43
+ ancestors.delete(value);
44
+ }
45
+ function parseFrontmatter(text, fileAbs) {
46
+ const body = text.startsWith("") ? text.slice(1) : text;
47
+ const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(body);
48
+ if (!match) throw new Error(`@lovable.dev/mcp-js: ${fileAbs} must start with YAML frontmatter delimited by ---`);
49
+ let parsed;
50
+ try {
51
+ parsed = load(match[1], {
52
+ schema: JSON_SCHEMA,
53
+ filename: fileAbs
54
+ });
55
+ } catch (err) {
56
+ throw new Error(`@lovable.dev/mcp-js: invalid SKILL.md frontmatter in ${fileAbs}: ${err.message}`);
57
+ }
58
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`@lovable.dev/mcp-js: SKILL.md frontmatter must be a mapping in ${fileAbs}`);
59
+ try {
60
+ assertJsonValue(parsed);
61
+ } catch (error) {
62
+ throw new Error(`@lovable.dev/mcp-js: invalid frontmatter in ${fileAbs}: ${error.message}`);
63
+ }
64
+ return parsed;
65
+ }
66
+ function validateIdentity(frontmatter, rootAbs, skillPath) {
67
+ const { name, description } = frontmatter;
68
+ if (typeof name !== "string" || Array.from(name).length > 64 || !NAME_RE.test(name)) throw new Error(`@lovable.dev/mcp-js: invalid skill name ${JSON.stringify(name)} in ${rootAbs}/SKILL.md`);
69
+ if (name !== basename(rootAbs)) throw new Error(`@lovable.dev/mcp-js: skill name "${name}" must equal its directory name "${basename(rootAbs)}"`);
70
+ if (typeof description !== "string" || description.trim().length === 0 || Array.from(description).length > 1024) throw new Error(`@lovable.dev/mcp-js: skill description must be a 1-1024 character string in ${rootAbs}/SKILL.md`);
71
+ if (skillPath.split("/").some((part) => !part || part === "." || part === ".." || /[\\\s]/u.test(part) || Array.from(part).some((char) => char < " ")) || skillPath.split("/").at(-1) !== name) throw new Error(`@lovable.dev/mcp-js: skill path must end in ${name} and contain nonempty directory segments: ${skillPath}`);
72
+ }
73
+ function validateOptionalFields(frontmatter, rootAbs) {
74
+ for (const field of [
75
+ "license",
76
+ "compatibility",
77
+ "allowed-tools"
78
+ ]) if (frontmatter[field] !== void 0 && typeof frontmatter[field] !== "string") throw new Error(`@lovable.dev/mcp-js: ${field} must be a string in ${rootAbs}/SKILL.md`);
79
+ if (typeof frontmatter.compatibility === "string" && (!frontmatter.compatibility.trim() || Array.from(frontmatter.compatibility).length > 500)) throw new Error(`@lovable.dev/mcp-js: compatibility must be 1-500 characters in ${rootAbs}/SKILL.md`);
80
+ const metadata = frontmatter.metadata;
81
+ if (metadata !== void 0 && (metadata === null || typeof metadata !== "object" || Array.isArray(metadata) || Object.values(metadata).some((value) => typeof value !== "string"))) throw new Error(`@lovable.dev/mcp-js: metadata must map strings to strings in ${rootAbs}/SKILL.md`);
82
+ }
83
+ function readSkillFrontmatter(text, rootAbs, skillPath) {
84
+ const frontmatter = parseFrontmatter(text, join(rootAbs, "SKILL.md"));
85
+ validateIdentity(frontmatter, rootAbs, skillPath);
86
+ validateOptionalFields(frontmatter, rootAbs);
87
+ return frontmatter;
88
+ }
89
+ //#endregion
90
+ //#region src/skills/compile.ts
91
+ function mimeTypeFor(path) {
92
+ const lower = path.toLowerCase();
93
+ if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "text/markdown";
94
+ if (lower.endsWith(".json")) return "application/json";
95
+ if (lower.endsWith(".yaml") || lower.endsWith(".yml")) return "application/yaml";
96
+ if (lower.endsWith(".csv")) return "text/csv";
97
+ return "text/plain";
98
+ }
99
+ function compareBytes(a, b) {
100
+ return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
101
+ }
102
+ function approvedHiddenFiles(allowHidden) {
103
+ const allowed = new Set(allowHidden);
104
+ for (const path of allowed) {
105
+ const segments = path.split("/");
106
+ if (segments.some((part) => !part || part === "." || part === "..") || !segments.some((part) => part.startsWith(".")) || Array.from(path).some((char) => "\\:*?[]".includes(char) || char < " " || char === "")) throw new Error(`@lovable.dev/mcp-js: allowHidden requires exact relative hidden-file paths, not directories or globs: ${path}`);
107
+ }
108
+ return allowed;
109
+ }
110
+ function walk(rootAbs, allowHidden) {
111
+ const files = [];
112
+ const dirs = [rootAbs];
113
+ const allowed = approvedHiddenFiles(allowHidden);
114
+ const visit = (dirAbs, relPrefix) => {
115
+ for (const entry of readdirSync(dirAbs)) {
116
+ const abs = join(dirAbs, entry);
117
+ const rel = relPrefix ? `${relPrefix}/${entry}` : entry;
118
+ const stat = lstatSync(abs);
119
+ if (stat.isSymbolicLink()) throw new Error(`@lovable.dev/mcp-js: skill files must not be symlinks: ${abs}`);
120
+ if (rel.split("/").some((part) => part.startsWith(".")) && !(stat.isDirectory() ? allowHidden.some((path) => path.startsWith(`${rel}/`)) : allowed.has(rel))) throw new Error(`@lovable.dev/mcp-js: hidden skill entry ${rel} is not approved for publication; remove it or add an exact allowHidden=<relative-file-path> to the ?skill import`);
121
+ if (stat.isDirectory()) {
122
+ dirs.push(abs);
123
+ visit(abs, rel);
124
+ } else if (stat.isFile()) files.push(rel);
125
+ else throw new Error(`@lovable.dev/mcp-js: unsupported skill file type: ${abs}`);
126
+ }
127
+ };
128
+ visit(rootAbs, "");
129
+ for (const path of allowed) if (!files.includes(path)) throw new Error(`@lovable.dev/mcp-js: allowHidden entry does not name a skill file: ${path}`);
130
+ return {
131
+ files,
132
+ dirs
133
+ };
134
+ }
135
+ function encodeUri(skillPath, relPath) {
136
+ const segments = [...skillPath.split("/"), ...relPath.split("/")].map((segment) => encodeURIComponent(segment));
137
+ return new URL(`skill://${segments.join("/")}`).href;
138
+ }
139
+ function decodeSkillFile(bytes, abs) {
140
+ let text;
141
+ try {
142
+ text = new TextDecoder("utf-8", {
143
+ fatal: true,
144
+ ignoreBOM: true
145
+ }).decode(bytes);
146
+ } catch {
147
+ throw new Error(`@lovable.dev/mcp-js: skill file is not UTF-8 text (unsupported in this release): ${abs}`);
148
+ }
149
+ for (const char of text) if (char < " " && char !== " " && char !== "\n" && char !== "\r" || char === "") throw new Error(`@lovable.dev/mcp-js: skill file contains binary control characters: ${abs}`);
150
+ return text;
151
+ }
152
+ function compileSkillDirectory(dirInput, skillPath = basename(resolve(dirInput)), allowHidden = []) {
153
+ const rootAbs = resolve(dirInput);
154
+ for (let path = rootAbs;; path = dirname(path)) {
155
+ if (lstatSync(path).isSymbolicLink()) throw new Error(`@lovable.dev/mcp-js: skill paths must not be symlinks: ${path}`);
156
+ if (dirname(path) === path) break;
157
+ }
158
+ const rootStat = lstatSync(rootAbs);
159
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error(`@lovable.dev/mcp-js: ?skill import must name a real directory: ${rootAbs}`);
160
+ const { files: relPaths, dirs } = walk(rootAbs, allowHidden);
161
+ if (!relPaths.includes("SKILL.md")) throw new Error(`@lovable.dev/mcp-js: ${rootAbs} has no SKILL.md`);
162
+ relPaths.sort((a, b) => a === "SKILL.md" ? -1 : b === "SKILL.md" ? 1 : compareBytes(a, b));
163
+ const decoder = new TextDecoder("utf-8", {
164
+ fatal: true,
165
+ ignoreBOM: true
166
+ });
167
+ const skillBytes = readFileSync(join(rootAbs, "SKILL.md"));
168
+ const frontmatter = readSkillFrontmatter((() => {
169
+ try {
170
+ return decoder.decode(skillBytes);
171
+ } catch {
172
+ throw new Error(`@lovable.dev/mcp-js: ${join(rootAbs, "SKILL.md")} is not valid UTF-8`);
173
+ }
174
+ })(), rootAbs, skillPath);
175
+ let totalBytes = 0;
176
+ const files = relPaths.map((path) => {
177
+ const abs = join(rootAbs, path);
178
+ const bytes = path === "SKILL.md" ? skillBytes : readFileSync(abs);
179
+ totalBytes += bytes.byteLength;
180
+ const text = decodeSkillFile(bytes, abs);
181
+ return {
182
+ path,
183
+ uri: encodeUri(skillPath, path),
184
+ mimeType: mimeTypeFor(path),
185
+ text,
186
+ size: bytes.byteLength,
187
+ digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`
188
+ };
189
+ });
190
+ const uri = encodeUri(skillPath, "SKILL.md");
191
+ const skill = {
192
+ kind: COMPILED_SKILL_KIND,
193
+ uri,
194
+ rootUri: uri.slice(0, -9),
195
+ frontmatter,
196
+ files
197
+ };
198
+ const report = [`[@lovable.dev/mcp-js] skill ${uri} (${files.length} files, ${totalBytes} bytes) — every file below is published to authorized MCP clients:`, ...files.map((file) => ` ${file.uri} ${file.size} B ${file.digest}`)].join("\n");
199
+ return {
200
+ skill,
201
+ watchFiles: relPaths.map((path) => join(rootAbs, path)),
202
+ watchDirs: dirs,
203
+ report
204
+ };
205
+ }
206
+ function skillModuleSource(compilation) {
207
+ return `export default JSON.parse(${JSON.stringify(JSON.stringify(compilation.skill))});\n`;
208
+ }
209
+ //#endregion
210
+ //#region src/skills/imports.ts
211
+ const SKILL_IMPORT_FILTER = /[?&]skill$/;
212
+ function skillImportId(directory, spec) {
213
+ const options = spec.skillPath === void 0 ? [] : [`path=${encodeURIComponent(spec.skillPath)}`];
214
+ for (const path of [...spec.allowHidden].sort()) options.push(`allowHidden=${encodeURIComponent(path)}`);
215
+ return `${directory}?${[...options, "skill"].join("&")}`;
216
+ }
217
+ function parseOption(option, id) {
218
+ const equals = option.indexOf("=");
219
+ const key = option.slice(0, equals);
220
+ if (equals < 0 || key !== "path" && key !== "allowHidden") throw new Error(`@lovable.dev/mcp-js: unknown ?skill import option: ${option}`);
221
+ try {
222
+ return [key, decodeURIComponent(option.slice(equals + 1))];
223
+ } catch {
224
+ throw new Error(`@lovable.dev/mcp-js: invalid percent encoding in ?skill import: ${id}`);
225
+ }
226
+ }
227
+ function parseSkillImport(id) {
228
+ const queryStart = id.lastIndexOf("?");
229
+ if (queryStart < 0 || /[\r\n\u2028\u2029]/.test(id)) return void 0;
230
+ const query = id.slice(queryStart + 1);
231
+ if (query !== "skill" && !query.endsWith("&skill")) return void 0;
232
+ const options = query === "skill" ? [] : query.slice(0, -6).split("&");
233
+ let skillPath;
234
+ const allowHidden = [];
235
+ for (const option of options) {
236
+ const [key, value] = parseOption(option, id);
237
+ if (key === "path") {
238
+ if (skillPath !== void 0) throw new Error("@lovable.dev/mcp-js: duplicate path in ?skill import");
239
+ skillPath = value;
240
+ } else {
241
+ if (allowHidden.includes(value)) throw new Error(`@lovable.dev/mcp-js: duplicate allowHidden entry: ${value}`);
242
+ allowHidden.push(value);
243
+ }
244
+ }
245
+ return {
246
+ directory: id.slice(0, queryStart),
247
+ skillPath,
248
+ allowHidden
249
+ };
250
+ }
251
+ //#endregion
252
+ //#region src/skills/hooks.ts
253
+ const VIRTUAL_PREFIX = "\0lovable-mcp-skill:";
254
+ const ESBUILD_NAMESPACE = "lovable-mcp-skill";
255
+ function resolveSkillDir(spec, baseDir) {
256
+ if (!spec.startsWith(".") && !isAbsolute(spec)) return void 0;
257
+ return resolve(baseDir, spec);
258
+ }
259
+ function isUnder(dir, file) {
260
+ return file === dir || file.startsWith(dir + sep);
261
+ }
262
+ function invalidateModule(server, id) {
263
+ for (const environment of Object.values(server.environments ?? {})) {
264
+ const mod = environment.moduleGraph.getModuleById(id);
265
+ if (mod) environment.moduleGraph.invalidateModule(mod);
266
+ }
267
+ const legacy = server.moduleGraph.getModuleById(id);
268
+ if (legacy) server.moduleGraph.invalidateModule(legacy);
269
+ }
270
+ function skillImportVitePlugin(options = {}) {
271
+ const report = options.report ?? ((text) => console.info(text));
272
+ const dirsById = /* @__PURE__ */ new Map();
273
+ let devServer;
274
+ const invalidateFor = (file) => {
275
+ if (!devServer) return;
276
+ const abs = resolve(file);
277
+ for (const [id, dir] of dirsById) {
278
+ if (!isUnder(dir, abs)) continue;
279
+ invalidateModule(devServer, id);
280
+ }
281
+ };
282
+ return {
283
+ name: "@lovable.dev/mcp-js/skill-import",
284
+ resolveId: {
285
+ order: "pre",
286
+ handler(source, importer) {
287
+ const spec = parseSkillImport(source);
288
+ if (spec === void 0) return null;
289
+ const baseDir = importer ? dirname(importer.replace(/[?#].*$/, "")) : process.cwd();
290
+ const dir = resolveSkillDir(spec.directory, baseDir);
291
+ if (dir === void 0) throw new Error(`@lovable.dev/mcp-js: ?skill imports must be relative or absolute paths, got ${source}`);
292
+ return VIRTUAL_PREFIX + skillImportId(dir, spec);
293
+ }
294
+ },
295
+ load: { handler(id) {
296
+ if (!id.startsWith(VIRTUAL_PREFIX)) return null;
297
+ const spec = parseSkillImport(id.slice(19));
298
+ const dir = spec.directory;
299
+ dirsById.set(id, dir);
300
+ devServer?.watcher.add(dir);
301
+ const compilation = compileSkillDirectory(dir, spec.skillPath, spec.allowHidden);
302
+ for (const file of compilation.watchFiles) this.addWatchFile(file);
303
+ report(compilation.report);
304
+ return skillModuleSource(compilation);
305
+ } },
306
+ configureServer(server) {
307
+ devServer = server;
308
+ server.watcher.on("add", invalidateFor);
309
+ server.watcher.on("change", invalidateFor);
310
+ server.watcher.on("unlink", invalidateFor);
311
+ server.watcher.on("unlinkDir", invalidateFor);
312
+ options.onServer?.(server);
313
+ }
314
+ };
315
+ }
316
+ function skillImportEsbuildPlugin(onCompile, onDirectory) {
317
+ return {
318
+ name: "lovable-mcp-skill-import",
319
+ setup(pluginBuild) {
320
+ const workingDir = pluginBuild.initialOptions.absWorkingDir ?? process.cwd();
321
+ pluginBuild.onResolve({ filter: SKILL_IMPORT_FILTER }, (args) => {
322
+ const spec = parseSkillImport(args.path);
323
+ if (spec === void 0) return void 0;
324
+ const dir = resolveSkillDir(spec.directory, args.resolveDir);
325
+ if (dir === void 0) return { errors: [{ text: `?skill imports must be relative or absolute paths, got ${args.path}` }] };
326
+ onDirectory?.(dir);
327
+ return {
328
+ path: skillImportId(relative(workingDir, dir).split(sep).join("/"), spec),
329
+ namespace: ESBUILD_NAMESPACE
330
+ };
331
+ });
332
+ pluginBuild.onLoad({
333
+ filter: /.*/,
334
+ namespace: ESBUILD_NAMESPACE
335
+ }, (args) => {
336
+ const spec = parseSkillImport(args.path);
337
+ const compilation = compileSkillDirectory(resolve(workingDir, spec.directory), spec.skillPath, spec.allowHidden);
338
+ onCompile(compilation);
339
+ return {
340
+ contents: skillModuleSource(compilation),
341
+ loader: "js",
342
+ watchFiles: [...compilation.watchFiles],
343
+ watchDirs: [...compilation.watchDirs]
344
+ };
345
+ });
346
+ }
347
+ };
348
+ }
349
+ function isSkillImportInput(input) {
350
+ return input.startsWith(`${ESBUILD_NAMESPACE}:`);
351
+ }
352
+ //#endregion
353
+ export { isFileMissing as a, readSupabaseProjectRef as i, skillImportEsbuildPlugin as n, skillImportVitePlugin as r, isSkillImportInput as t };