@openfairygui/mcp 0.6.3 → 0.7.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.
@@ -24,106 +24,12 @@ let _modelcontextprotocol_sdk_server_mcp_js = require("@modelcontextprotocol/sdk
24
24
  let _openfairygui_backend_node = require("@openfairygui/backend/node");
25
25
  let node_module = require("node:module");
26
26
  let zod = require("zod");
27
- let _openfairygui_backend = require("@openfairygui/backend");
28
27
  let _openfairygui_backend_docs = require("@openfairygui/backend/docs");
28
+ let _openfairygui_backend = require("@openfairygui/backend");
29
29
  let _modelcontextprotocol_sdk_server_stdio_js = require("@modelcontextprotocol/sdk/server/stdio.js");
30
30
  let node_path = require("node:path");
31
31
  node_path = __toESM(node_path);
32
32
  let node_url = require("node:url");
33
- //#region src/prompt-definitions.ts
34
- const OPENFAIRYGUI_BACKEND_PROMPT_NAMES = [
35
- "openfairygui_inspect_capabilities",
36
- "openfairygui_open_and_inspect_session",
37
- "openfairygui_inspect_project_outline",
38
- "openfairygui_plan_revision_checked_transaction",
39
- "openfairygui_save_session",
40
- "openfairygui_poll_runtime_state"
41
- ];
42
- const OPENFAIRYGUI_BACKEND_PROMPT_DEFINITIONS = [
43
- {
44
- name: "openfairygui_inspect_capabilities",
45
- title: "Inspect OpenFairyGUI Backend Capabilities",
46
- description: "Guide a client through the capability and version discovery tool.",
47
- text: [
48
- "Use openfairygui_backend_get_capabilities first.",
49
- "Read contractVersion, capabilitySchemaVersion, capability planes, methods, and runtime non-goals from the backend envelope.",
50
- "Do not infer artifact publish/restore, subscriptions, or cache source-of-truth support when the backend marks them unsupported."
51
- ].join("\n")
52
- },
53
- {
54
- name: "openfairygui_open_and_inspect_session",
55
- title: "Open and Inspect an OpenFairyGUI Session",
56
- description: "Guide a client through opening and reading a backend session.",
57
- text: [
58
- "Use openfairygui_backend_open_session with a projectPath, then use openfairygui_backend_get_session with the returned sessionId.",
59
- "Backend path policy remains authoritative for project paths and save targets; MCP roots are only client context in this package.",
60
- "Close the session with openfairygui_backend_close_session when finished."
61
- ].join("\n")
62
- },
63
- {
64
- name: "openfairygui_inspect_project_outline",
65
- title: "Inspect an OpenFairyGUI Project Outline",
66
- description: "Guide a client through selector discovery before a revision-checked transaction.",
67
- text: [
68
- "Use openfairygui_backend_get_project_outline with the active sessionId before planning mutations.",
69
- "Use package, resource, folder, display node, controller page, and transition identities from the returned outline.",
70
- "Pass the returned revision as expectedRevision when calling openfairygui_backend_apply_transaction.",
71
- "Read a new outline if the backend reports a stale revision; the outline intentionally excludes source bytes and full property payloads."
72
- ].join("\n")
73
- },
74
- {
75
- name: "openfairygui_plan_revision_checked_transaction",
76
- title: "Plan a Revision-Checked OpenFairyGUI Transaction",
77
- description: "Guide a client through backend-owned revision checks without inventing operation grammar.",
78
- text: [
79
- "Use openfairygui_backend_get_session to read the current revision before mutation.",
80
- "Use openfairygui_backend_get_project_outline for identities, then openfairygui_backend_query_entity for current properties at the returned revision.",
81
- "For settings edits, query target {kind:\"project\"} or {kind:\"package\",selector:{packageId}}; copy entity.properties.settings, change the requested fields, and submit the complete settings to updateProjectSettings or updatePackageSettings.",
82
- "Read openfairygui://contracts/operations and openfairygui://contracts/operations/{kind} for the current operation names and exact JSON parameters.",
83
- "Call openfairygui_backend_preflight_transaction with the queried revision and planned operations to execute and discard an isolated preview; inspect the backend diagnostics.",
84
- "A successful preview does not reserve a revision or guarantee save. Apply the same batch with expectedRevision set to the preview baseRevision; refresh properties and re-plan on stale revision.",
85
- "Call openfairygui_backend_apply_transaction with sessionId, expectedRevision, and backend/UAM-owned operations.",
86
- "If the backend returns a stale revision error, refresh the session snapshot and re-plan against the new revision.",
87
- "Do not invent selector grammar, transaction grammar, or operation payload semantics at the MCP layer."
88
- ].join("\n")
89
- },
90
- {
91
- name: "openfairygui_save_session",
92
- title: "Save an OpenFairyGUI Backend Session",
93
- description: "Guide a client through coordinated backend save semantics.",
94
- text: [
95
- "Use openfairygui_backend_save_session with sessionId and expectedRevision when available.",
96
- "Backend path policy remains authoritative for targetPath; MCP does not canonicalize or authorize paths.",
97
- "Handle stale revision and partial save failure envelopes from the backend without rewriting their error semantics."
98
- ].join("\n")
99
- },
100
- {
101
- name: "openfairygui_poll_runtime_state",
102
- title: "Poll OpenFairyGUI Runtime State",
103
- description: "Guide a client through event polling and synchronous cache snapshots.",
104
- text: [
105
- "Use openfairygui_backend_get_events for polling events with the backend cursor contract.",
106
- "Use openfairygui_backend_get_cache_snapshot for derived read-only cache state; openfairygui_backend_refresh_cache returns the refreshed snapshot synchronously.",
107
- "Subscriptions and cache-as-source-of-truth behavior are not supported by the backend."
108
- ].join("\n")
109
- }
110
- ];
111
- function promptResult(text) {
112
- return { messages: [{
113
- role: "user",
114
- content: {
115
- type: "text",
116
- text
117
- }
118
- }] };
119
- }
120
- function registerOpenFairyGuiBackendPrompts(server) {
121
- for (const definition of OPENFAIRYGUI_BACKEND_PROMPT_DEFINITIONS) server.registerPrompt(definition.name, {
122
- title: definition.title,
123
- description: definition.description
124
- }, () => promptResult(definition.text));
125
- }
126
- //#endregion
127
33
  //#region src/contract-schema.ts
128
34
  const CONTRACT_SNAPSHOT = (0, _openfairygui_backend_docs.getInstalledContractSnapshot)();
129
35
  function contractObjectSchema(schema) {
@@ -134,129 +40,67 @@ function contractObjectSchema(schema) {
134
40
  if (!(result instanceof zod.z.ZodObject)) throw new TypeError("Tool contract must be an object");
135
41
  return result;
136
42
  }
43
+ function valueAt(value, path) {
44
+ return path.reduce((node, key) => node !== null && typeof node === "object" ? node[key] : void 0, value);
45
+ }
46
+ /**
47
+ * A union of `kind`-tagged objects fails with one nested issue list per branch.
48
+ * Report only the branch selected by the input's kind, or the valid kinds when none matches;
49
+ * other unions keep Zod's issue. Paths stay relative to `input`.
50
+ */
51
+ function focusContractIssues(issues, input) {
52
+ return issues.flatMap((issue) => {
53
+ if (issue.code !== "invalid_union" || issue.errors.length < 2) return [issue];
54
+ const tags = issue.errors.map((branch) => branch.find((entry) => entry.code === "invalid_value" && entry.path.length === 1 && entry.path[0] === "kind"));
55
+ const untagged = issue.errors.filter((_branch, index) => !tags[index]);
56
+ if (untagged.length > 1 || untagged.some((branch) => branch.some((entry) => entry.code === "invalid_type" && entry.path.length === 0))) return [issue];
57
+ const target = valueAt(input, issue.path);
58
+ const kind = valueAt(target, ["kind"]);
59
+ const kinds = tags.flatMap((tag) => tag?.code === "invalid_value" ? tag.values : []);
60
+ const operation = issue.errors.length === Object.keys(CONTRACT_SNAPSHOT.operations).length && kinds.every((value) => typeof value === "string" && Object.hasOwn(CONTRACT_SNAPSHOT.operations, value));
61
+ if (untagged.length === 1) {
62
+ const note = operation && typeof kind === "string" ? ` (schema: ${_openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_CATALOG_URI}/${kind})` : "";
63
+ return focusContractIssues(untagged[0], target).map((entry) => ({
64
+ ...entry,
65
+ path: [...issue.path, ...entry.path],
66
+ message: entry.message + note
67
+ }));
68
+ }
69
+ const subject = operation ? "operation kind" : "kind";
70
+ const found = kind === void 0 ? `Missing ${subject}` : typeof kind === "string" ? `Unknown ${subject} ${JSON.stringify(kind)}` : `Invalid ${subject} of type ${typeof kind}`;
71
+ const help = operation ? `. Read ${_openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE} for one operation's fields` : "";
72
+ return [{
73
+ code: "invalid_value",
74
+ values: kinds,
75
+ path: [...issue.path, "kind"],
76
+ message: `${found}; expected one of: ${kinds.join(", ")}${help}`
77
+ }];
78
+ });
79
+ }
137
80
  /** Keep SDK discovery dynamic without expanding shared contract definitions. */
138
- function compactToolSchema(schema, io) {
139
- return zod.z.looseObject({}).superRefine((value, context) => {
140
- const parsed = schema.safeParse(value);
141
- if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue });
142
- }).meta(zod.z.toJSONSchema(schema, {
81
+ function compactToolSchema(getSchema, io, withinBudget) {
82
+ let metadata;
83
+ const getMetadata = () => metadata ??= { ...zod.z.toJSONSchema(getSchema(), {
143
84
  target: "draft-07",
144
85
  io,
145
86
  reused: "ref"
146
- }));
147
- }
148
- /** Decode only generated Uint8Array locations; arbitrary JSON metadata is not rewritten. */
149
- function decodeToolBytes(input, paths) {
150
- if (!paths.length) return input;
151
- const result = structuredClone(input);
152
- function visit(value, parts) {
153
- if (!parts.length) return value === null ? value : Uint8Array.from(value);
154
- if (!value || typeof value !== "object") return value;
155
- const [key, ...rest] = parts;
156
- const record = value;
157
- for (const name of key === "*" ? Object.keys(record) : [key]) if (Object.hasOwn(record, name)) record[name] = visit(record[name], rest);
158
- return value;
159
- }
160
- for (const parts of paths) visit(result, parts);
161
- return result;
162
- }
163
- //#endregion
164
- //#region src/resource-definitions.ts
165
- const JSON_MIME_TYPE = "application/json";
166
- function firstVariable(value) {
167
- return Array.isArray(value) ? value[0] ?? "" : value ?? "";
168
- }
169
- function jsonResource(uri, backendResult) {
170
- return { contents: [{
171
- uri: uri.toString(),
172
- mimeType: JSON_MIME_TYPE,
173
- text: JSON.stringify(backendResult, null, 2)
174
- }] };
175
- }
176
- const OPENFAIRYGUI_BACKEND_CAPABILITIES_RESOURCE_URI = "openfairygui://backend/capabilities";
177
- const OPENFAIRYGUI_BACKEND_RESOURCE_TEMPLATES = [
178
- "openfairygui://docs/methods/{method}",
179
- "openfairygui://docs/cli/{command}",
180
- _openfairygui_backend.BACKEND_DIAGNOSTIC_TEMPLATE,
181
- _openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE,
182
- "openfairygui://backend/session/{sessionId}",
183
- "openfairygui://backend/session/{sessionId}/outline",
184
- "openfairygui://backend/cache/{sessionId}"
185
- ];
186
- function registerOpenFairyGuiBackendResources(server, runtime) {
187
- server.registerResource("openfairygui_docs_index", _openfairygui_backend_docs.OPENFAIRYGUI_DOCS_INDEX_URI, {
188
- title: "Installed Documentation",
189
- description: "Offline documentation IDs, URIs, installed package version and contract digest shared with the CLI.",
190
- mimeType: JSON_MIME_TYPE
191
- }, (uri) => jsonResource(uri, (0, _openfairygui_backend_docs.getInstalledDocumentationIndex)()));
192
- function installedDocument(uri, id) {
193
- const document = (0, _openfairygui_backend_docs.readInstalledDocumentation)(id);
194
- return { contents: [{
195
- uri: uri.toString(),
196
- mimeType: document.mimeType,
197
- text: document.text
198
- }] };
199
- }
200
- for (const id of [
201
- "workflow",
202
- "restore-limits",
203
- "skill",
204
- "contracts"
205
- ]) server.registerResource(`openfairygui_docs_${id}`, `openfairygui://docs/${id}`, {
206
- title: `Installed ${id}`,
207
- description: "Read the installed-version corpus without repository or network access.",
208
- mimeType: id === "contracts" ? JSON_MIME_TYPE : "text/markdown"
209
- }, (uri) => installedDocument(uri, id));
210
- server.registerResource("openfairygui_docs_method", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://docs/methods/{method}", { list: void 0 }), {
211
- title: "Installed Method Contract",
212
- description: "Read self-contained Backend/MCP wire input/output schemas and metadata.",
213
- mimeType: JSON_MIME_TYPE
214
- }, (uri, variables) => installedDocument(uri, `methods/${firstVariable(variables.method)}`));
215
- server.registerResource("openfairygui_diagnostic_catalog", _openfairygui_backend.BACKEND_DIAGNOSTICS_URI, {
216
- title: "Diagnostic Recovery Catalog",
217
- description: "Complete formal diagnostic ownership and recovery guidance; never automatic repair.",
218
- mimeType: JSON_MIME_TYPE
219
- }, (uri) => jsonResource(uri, (0, _openfairygui_backend.getBackendDiagnosticCatalog)()));
220
- server.registerResource("openfairygui_docs_cli", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://docs/cli/{command}", { list: void 0 }), {
221
- title: "Installed CLI Output Contract",
222
- description: "Read a generated, self-contained CLI JSON envelope schema.",
223
- mimeType: JSON_MIME_TYPE
224
- }, (uri, variables) => installedDocument(uri, `cli/${decodeURIComponent(firstVariable(variables.command))}`));
225
- server.registerResource("openfairygui_diagnostic_guide", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate(_openfairygui_backend.BACKEND_DIAGNOSTIC_TEMPLATE, { list: void 0 }), {
226
- title: "Diagnostic Recovery Guide",
227
- description: "Read the recovery boundary for one stable diagnostic code.",
228
- mimeType: JSON_MIME_TYPE
229
- }, (uri, variables) => jsonResource(uri, (0, _openfairygui_backend.getBackendDiagnosticGuide)(firstVariable(variables.code))));
230
- server.registerResource("openfairygui_operation_catalog", _openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_CATALOG_URI, {
231
- title: "UAM Operation Catalog",
232
- description: "Discover current operations and their generated JSON schemas.",
233
- mimeType: JSON_MIME_TYPE
234
- }, (uri) => jsonResource(uri, (0, _openfairygui_backend_docs.getOpenFairyGuiOperationCatalog)()));
235
- server.registerResource("openfairygui_operation_schema", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate(_openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE, { list: void 0 }), {
236
- title: "UAM Operation Schema",
237
- description: "Read the precise Core-derived JSON wire schema for one operation. Structure is not semantic preflight.",
238
- mimeType: JSON_MIME_TYPE
239
- }, (uri, variables) => jsonResource(uri, (0, _openfairygui_backend_docs.getOpenFairyGuiOperationSchema)(firstVariable(variables.kind))));
240
- server.registerResource("openfairygui_backend_capabilities", OPENFAIRYGUI_BACKEND_CAPABILITIES_RESOURCE_URI, {
241
- title: "OpenFairyGUI Backend Capabilities",
242
- description: "Read the backend capability and version envelope as JSON.",
243
- mimeType: JSON_MIME_TYPE
244
- }, (uri) => jsonResource(uri, runtime.getCapabilities()));
245
- server.registerResource("openfairygui_backend_session", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/session/{sessionId}", { list: void 0 }), {
246
- title: "OpenFairyGUI Backend Session Snapshot",
247
- description: "Read a backend session envelope by backend-local session id.",
248
- mimeType: JSON_MIME_TYPE
249
- }, (uri, variables) => jsonResource(uri, runtime.getSession({ sessionId: firstVariable(variables.sessionId) })));
250
- server.registerResource("openfairygui_backend_project_outline", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/session/{sessionId}/outline", { list: void 0 }), {
251
- title: "OpenFairyGUI Project Outline",
252
- description: "Read a revision-bound project identity outline without source bytes or full property payloads.",
253
- mimeType: JSON_MIME_TYPE
254
- }, (uri, variables) => jsonResource(uri, runtime.getProjectOutline({ sessionId: firstVariable(variables.sessionId) })));
255
- server.registerResource("openfairygui_backend_cache", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/cache/{sessionId}", { list: void 0 }), {
256
- title: "OpenFairyGUI Backend Cache Snapshot",
257
- description: "Read a derived backend cache envelope by backend-local session id.",
258
- mimeType: JSON_MIME_TYPE
259
- }, (uri, variables) => jsonResource(uri, runtime.getCacheSnapshot({ sessionId: firstVariable(variables.sessionId) })));
87
+ }) };
88
+ const lazyMetadata = new Proxy({}, {
89
+ get: (_target, key) => Reflect.get(getMetadata(), key),
90
+ ownKeys: () => Reflect.ownKeys(getMetadata()),
91
+ getOwnPropertyDescriptor: (_target, key) => Object.getOwnPropertyDescriptor(getMetadata(), key)
92
+ });
93
+ return zod.z.looseObject({}).superRefine((value, context) => {
94
+ if (withinBudget && !withinBudget(value)) {
95
+ context.addIssue({
96
+ code: "custom",
97
+ message: "MCP input exceeds the payload budget."
98
+ });
99
+ return;
100
+ }
101
+ const parsed = getSchema().safeParse(value);
102
+ if (!parsed.success) for (const issue of focusContractIssues(parsed.error.issues, value)) context.addIssue({ ...issue });
103
+ }).meta(lazyMetadata);
260
104
  }
261
105
  //#endregion
262
106
  //#region src/tool-metadata.ts
@@ -276,7 +120,7 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
276
120
  name: "openfairygui_backend_open_session",
277
121
  backendMethod: "openSession",
278
122
  title: "Open Backend Session",
279
- description: "Open a FairyGUI project through BackendRuntime and acquire its backend-local session lock.",
123
+ description: "Open a project directory or .fairy file within allowed roots (stdio: OPENFAIRYGUI_ALLOWED_PROJECT_ROOTS). Acquire a session lock; close the session when finished.",
280
124
  annotations: {
281
125
  readOnlyHint: false,
282
126
  idempotentHint: false,
@@ -309,7 +153,8 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
309
153
  name: "openfairygui_backend_get_project_outline",
310
154
  backendMethod: "getProjectOutline",
311
155
  title: "Get Project Outline",
312
- description: "Return a revision-bound project/package/resource/component identity outline without source bytes or full property payloads.",
156
+ description: "Return a revision-bound project/package/resource/component identity outline without source bytes or full property payloads. Complete tool response is limited to 16 MiB.",
157
+ maxResponseBytes: 16777216,
313
158
  annotations: {
314
159
  readOnlyHint: true,
315
160
  idempotentHint: true,
@@ -355,7 +200,8 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
355
200
  name: "openfairygui_backend_validate_session",
356
201
  backendMethod: "validateSession",
357
202
  title: "Validate Project Session",
358
- description: "Validate the current session project structure, references, paths, and available source bytes without writing files.",
203
+ description: "Validate the current session project structure, references, paths, and available source bytes without writing files. Complete tool response is limited to 16 MiB.",
204
+ maxResponseBytes: 16777216,
359
205
  annotations: {
360
206
  readOnlyHint: true,
361
207
  idempotentHint: true,
@@ -366,7 +212,7 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
366
212
  name: "openfairygui_backend_preflight_transaction",
367
213
  backendMethod: "preflightTransaction",
368
214
  title: "Preview UAM Transaction",
369
- description: "Execute a revision-checked operation batch on an isolated project snapshot and discard the result. Returns the base revision and Core diagnostics; does not write, reserve a revision, or guarantee a later apply/save.",
215
+ description: "Execute a revision-checked operation batch on an isolated project snapshot and discard the result. Each operations[] item is one object whose \"kind\" field selects its fields, e.g. {\"kind\":\"renameResource\",\"selector\":{\"packageId\":\"<packageId>\",\"resourceId\":\"<resourceId>\"},\"newName\":\"Panel\"} with IDs from openfairygui_backend_get_project_outline. Read openfairygui://contracts/operations for every kind and openfairygui://contracts/operations/{kind} for the exact fields of one kind before composing operations. Returns the base revision and Core diagnostics; does not write, reserve a revision, or guarantee a later apply/save.",
370
216
  annotations: {
371
217
  readOnlyHint: true,
372
218
  idempotentHint: true,
@@ -377,7 +223,7 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
377
223
  name: "openfairygui_backend_apply_transaction",
378
224
  backendMethod: "applyTransaction",
379
225
  title: "Apply UAM Transaction",
380
- description: "Apply a bounded, revision-checked UAM operation batch using the Core transaction discriminants.",
226
+ description: "Apply a bounded, revision-checked UAM operation batch. Each operations[] item is one object whose \"kind\" field selects its fields, e.g. {\"kind\":\"renameResource\",\"selector\":{\"packageId\":\"<packageId>\",\"resourceId\":\"<resourceId>\"},\"newName\":\"Panel\"} with IDs from openfairygui_backend_get_project_outline. Read openfairygui://contracts/operations for every kind and openfairygui://contracts/operations/{kind} for the exact fields of one kind before composing operations. Check a batch first with openfairygui_backend_preflight_transaction. On stale_write, re-query and reconsider the batch; do not retry blindly. Validate and save afterward.",
381
227
  annotations: {
382
228
  readOnlyHint: false,
383
229
  destructiveHint: true,
@@ -389,7 +235,7 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
389
235
  name: "openfairygui_backend_save_session",
390
236
  backendMethod: "saveSession",
391
237
  title: "Save Backend Session",
392
- description: "Write the current backend session through its coordinated save path; Node uses an atomic staged directory swap.",
238
+ description: "Write the current backend session through its coordinated save path; Node stages project-owned files and reports rollback or retained-backup diagnostics.",
393
239
  annotations: {
394
240
  readOnlyHint: false,
395
241
  destructiveHint: true,
@@ -424,7 +270,8 @@ const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
424
270
  name: "openfairygui_backend_get_events",
425
271
  backendMethod: "getEvents",
426
272
  title: "Get Runtime Events",
427
- description: "Poll backend runtime events for a session using the backend P2 event cursor contract.",
273
+ description: "Poll backend runtime events for a session using the backend event cursor contract. Complete tool response is limited to 16 MiB.",
274
+ maxResponseBytes: 16777216,
428
275
  annotations: {
429
276
  readOnlyHint: true,
430
277
  idempotentHint: true,
@@ -507,21 +354,265 @@ function isOpenFairyGuiMcpPayloadWithinBudget(root, bytePaths = []) {
507
354
  }
508
355
  const OPENFAIRYGUI_BACKEND_TOOL_DEFINITIONS = OPENFAIRYGUI_BACKEND_TOOL_METADATA.map((metadata) => {
509
356
  const contract = CONTRACT_SNAPSHOT.tools[metadata.backendMethod];
357
+ let inputSchema;
358
+ let outputSchema;
510
359
  return {
511
360
  ...metadata,
512
- inputSchema: contractObjectSchema(contract.input),
513
- outputSchema: contractObjectSchema(contract.output)
361
+ get inputSchema() {
362
+ return inputSchema ??= contractObjectSchema(contract.input);
363
+ },
364
+ get outputSchema() {
365
+ return outputSchema ??= contractObjectSchema(contract.output);
366
+ }
514
367
  };
515
368
  });
516
369
  //#endregion
370
+ //#region src/prompt-definitions.ts
371
+ const OPENFAIRYGUI_BACKEND_PROMPT_NAMES = [
372
+ "openfairygui_inspect_capabilities",
373
+ "openfairygui_open_and_inspect_session",
374
+ "openfairygui_inspect_project_outline",
375
+ "openfairygui_plan_revision_checked_transaction",
376
+ "openfairygui_save_session",
377
+ "openfairygui_poll_runtime_state"
378
+ ];
379
+ const OPENFAIRYGUI_BACKEND_PROMPT_DEFINITIONS = [
380
+ {
381
+ name: "openfairygui_inspect_capabilities",
382
+ title: "Inspect OpenFairyGUI Backend Capabilities",
383
+ description: "Guide a client through the capability and version discovery tool.",
384
+ text: [
385
+ "Use openfairygui_backend_get_capabilities first.",
386
+ "Read contractVersion, capabilitySchemaVersion, capability planes, methods, and runtime non-goals from the backend envelope.",
387
+ "Do not infer artifact publish/restore, subscriptions, or cache source-of-truth support when the backend marks them unsupported."
388
+ ].join("\n")
389
+ },
390
+ {
391
+ name: "openfairygui_open_and_inspect_session",
392
+ title: "Open and Inspect an OpenFairyGUI Session",
393
+ description: "Guide a client through opening and reading a backend session.",
394
+ text: [
395
+ "Use openfairygui_backend_open_session with a projectPath, then use openfairygui_backend_get_session with the returned sessionId.",
396
+ "Backend path policy remains authoritative for project paths and save targets; MCP roots are only client context in this package.",
397
+ "Close the session with openfairygui_backend_close_session when finished."
398
+ ].join("\n")
399
+ },
400
+ {
401
+ name: "openfairygui_inspect_project_outline",
402
+ title: "Inspect an OpenFairyGUI Project Outline",
403
+ description: "Guide a client through selector discovery before a revision-checked transaction.",
404
+ text: [
405
+ "Use openfairygui_backend_get_project_outline with the active sessionId before planning mutations.",
406
+ "Use package, resource, folder, display node, controller page, and transition identities from the returned outline.",
407
+ "Pass the returned revision as expectedRevision when calling openfairygui_backend_apply_transaction.",
408
+ "Read a new outline if the backend reports a stale revision; the outline intentionally excludes source bytes and full property payloads."
409
+ ].join("\n")
410
+ },
411
+ {
412
+ name: "openfairygui_plan_revision_checked_transaction",
413
+ title: "Plan a Revision-Checked OpenFairyGUI Transaction",
414
+ description: "Guide a client through backend-owned revision checks without inventing operation grammar.",
415
+ text: [
416
+ "Use openfairygui_backend_get_session to read the current revision before mutation.",
417
+ "Use openfairygui_backend_get_project_outline for identities, then openfairygui_backend_query_entity for current properties at the returned revision.",
418
+ "For settings edits, query target {kind:\"project\"} or {kind:\"package\",selector:{packageId}}; copy entity.properties.settings, change the requested fields, and submit the complete settings to updateProjectSettings or updatePackageSettings.",
419
+ "Read openfairygui://contracts/operations and openfairygui://contracts/operations/{kind} for the current operation names and exact JSON parameters.",
420
+ "Call openfairygui_backend_preflight_transaction with the queried revision and planned operations to execute and discard an isolated preview; inspect the backend diagnostics.",
421
+ "A successful preview does not reserve a revision or guarantee save. Apply the same batch with expectedRevision set to the preview baseRevision; refresh properties and re-plan on stale revision.",
422
+ "Call openfairygui_backend_apply_transaction with sessionId, expectedRevision, and backend/UAM-owned operations.",
423
+ "If the backend returns a stale revision error, refresh the session snapshot and re-plan against the new revision.",
424
+ "Do not invent selector grammar, transaction grammar, or operation payload semantics at the MCP layer."
425
+ ].join("\n")
426
+ },
427
+ {
428
+ name: "openfairygui_save_session",
429
+ title: "Save an OpenFairyGUI Backend Session",
430
+ description: "Guide a client through coordinated backend save semantics.",
431
+ text: [
432
+ "Use openfairygui_backend_save_session with sessionId and expectedRevision when available.",
433
+ "Backend path policy remains authoritative for targetPath; MCP does not canonicalize or authorize paths.",
434
+ "Handle stale revision and partial save failure envelopes from the backend without rewriting their error semantics."
435
+ ].join("\n")
436
+ },
437
+ {
438
+ name: "openfairygui_poll_runtime_state",
439
+ title: "Poll OpenFairyGUI Runtime State",
440
+ description: "Guide a client through event polling and synchronous cache snapshots.",
441
+ text: [
442
+ "Use openfairygui_backend_get_events for polling events with the backend cursor contract.",
443
+ "Use openfairygui_backend_get_cache_snapshot for derived read-only cache state; openfairygui_backend_refresh_cache returns the refreshed snapshot synchronously.",
444
+ "Subscriptions and cache-as-source-of-truth behavior are not supported by the backend."
445
+ ].join("\n")
446
+ }
447
+ ];
448
+ function promptResult(text) {
449
+ return { messages: [{
450
+ role: "user",
451
+ content: {
452
+ type: "text",
453
+ text
454
+ }
455
+ }] };
456
+ }
457
+ function registerOpenFairyGuiBackendPrompts(server) {
458
+ for (const definition of OPENFAIRYGUI_BACKEND_PROMPT_DEFINITIONS) server.registerPrompt(definition.name, {
459
+ title: definition.title,
460
+ description: definition.description
461
+ }, () => promptResult(definition.text));
462
+ }
463
+ //#endregion
464
+ //#region src/resource-definitions.ts
465
+ const JSON_MIME_TYPE = "application/json";
466
+ function firstVariable(value) {
467
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
468
+ }
469
+ function jsonResource(uri, backendResult) {
470
+ return { contents: [{
471
+ uri: uri.toString(),
472
+ mimeType: JSON_MIME_TYPE,
473
+ text: JSON.stringify(backendResult, null, 2)
474
+ }] };
475
+ }
476
+ const OPENFAIRYGUI_BACKEND_CAPABILITIES_RESOURCE_URI = "openfairygui://backend/capabilities";
477
+ const OPENFAIRYGUI_BACKEND_RESOURCE_TEMPLATES = [
478
+ "openfairygui://docs/methods/{method}",
479
+ "openfairygui://docs/cli/{command}",
480
+ _openfairygui_backend.BACKEND_DIAGNOSTIC_TEMPLATE,
481
+ _openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE,
482
+ "openfairygui://backend/session/{sessionId}",
483
+ "openfairygui://backend/session/{sessionId}/outline",
484
+ "openfairygui://backend/cache/{sessionId}"
485
+ ];
486
+ function registerOpenFairyGuiBackendResources(server, runtime) {
487
+ server.registerResource("openfairygui_docs_index", _openfairygui_backend_docs.OPENFAIRYGUI_DOCS_INDEX_URI, {
488
+ title: "Installed Documentation",
489
+ description: "Offline documentation IDs, URIs, installed package version and contract digest shared with the CLI.",
490
+ mimeType: JSON_MIME_TYPE
491
+ }, (uri) => jsonResource(uri, (0, _openfairygui_backend_docs.getInstalledDocumentationIndex)()));
492
+ function installedDocument(uri, id) {
493
+ const document = (0, _openfairygui_backend_docs.readInstalledDocumentation)(id);
494
+ return { contents: [{
495
+ uri: uri.toString(),
496
+ mimeType: document.mimeType,
497
+ text: document.text
498
+ }] };
499
+ }
500
+ for (const id of [
501
+ "workflow",
502
+ "restore-limits",
503
+ "skill",
504
+ "contracts"
505
+ ]) server.registerResource(`openfairygui_docs_${id}`, `openfairygui://docs/${id}`, {
506
+ title: `Installed ${id}`,
507
+ description: "Read the installed-version corpus without repository or network access.",
508
+ mimeType: id === "contracts" ? JSON_MIME_TYPE : "text/markdown"
509
+ }, (uri) => installedDocument(uri, id));
510
+ server.registerResource("openfairygui_docs_method", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://docs/methods/{method}", { list: void 0 }), {
511
+ title: "Installed Method Contract",
512
+ description: "Read self-contained Backend/MCP wire input/output schemas and metadata.",
513
+ mimeType: JSON_MIME_TYPE
514
+ }, (uri, variables) => installedDocument(uri, `methods/${firstVariable(variables.method)}`));
515
+ server.registerResource("openfairygui_diagnostic_catalog", _openfairygui_backend.BACKEND_DIAGNOSTICS_URI, {
516
+ title: "Diagnostic Recovery Catalog",
517
+ description: "Complete formal diagnostic ownership and recovery guidance; never automatic repair.",
518
+ mimeType: JSON_MIME_TYPE
519
+ }, (uri) => jsonResource(uri, (0, _openfairygui_backend.getBackendDiagnosticCatalog)()));
520
+ server.registerResource("openfairygui_docs_cli", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://docs/cli/{command}", { list: void 0 }), {
521
+ title: "Installed CLI Output Contract",
522
+ description: "Read a generated, self-contained CLI JSON envelope schema.",
523
+ mimeType: JSON_MIME_TYPE
524
+ }, (uri, variables) => installedDocument(uri, `cli/${decodeURIComponent(firstVariable(variables.command))}`));
525
+ server.registerResource("openfairygui_diagnostic_guide", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate(_openfairygui_backend.BACKEND_DIAGNOSTIC_TEMPLATE, { list: void 0 }), {
526
+ title: "Diagnostic Recovery Guide",
527
+ description: "Read the recovery boundary for one stable diagnostic code.",
528
+ mimeType: JSON_MIME_TYPE
529
+ }, (uri, variables) => jsonResource(uri, (0, _openfairygui_backend.getBackendDiagnosticGuide)(firstVariable(variables.code))));
530
+ server.registerResource("openfairygui_operation_catalog", _openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_CATALOG_URI, {
531
+ title: "UAM Operation Catalog",
532
+ description: "Discover current operations and their generated JSON schemas.",
533
+ mimeType: JSON_MIME_TYPE
534
+ }, (uri) => jsonResource(uri, (0, _openfairygui_backend_docs.getOpenFairyGuiOperationCatalog)()));
535
+ server.registerResource("openfairygui_operation_schema", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate(_openfairygui_backend_docs.OPENFAIRYGUI_OPERATION_SCHEMA_TEMPLATE, { list: void 0 }), {
536
+ title: "UAM Operation Schema",
537
+ description: "Read the precise Core-derived JSON wire schema for one operation. Structure is not semantic preflight.",
538
+ mimeType: JSON_MIME_TYPE
539
+ }, (uri, variables) => jsonResource(uri, (0, _openfairygui_backend_docs.getOpenFairyGuiOperationSchema)(firstVariable(variables.kind))));
540
+ server.registerResource("openfairygui_backend_capabilities", OPENFAIRYGUI_BACKEND_CAPABILITIES_RESOURCE_URI, {
541
+ title: "OpenFairyGUI Backend Capabilities",
542
+ description: "Read the backend capability and version envelope as JSON.",
543
+ mimeType: JSON_MIME_TYPE
544
+ }, (uri) => jsonResource(uri, runtime.getCapabilities()));
545
+ server.registerResource("openfairygui_backend_session", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/session/{sessionId}", { list: void 0 }), {
546
+ title: "OpenFairyGUI Backend Session Snapshot",
547
+ description: "Read a backend session envelope by backend-local session id.",
548
+ mimeType: JSON_MIME_TYPE
549
+ }, (uri, variables) => jsonResource(uri, runtime.getSession({ sessionId: firstVariable(variables.sessionId) })));
550
+ server.registerResource("openfairygui_backend_project_outline", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/session/{sessionId}/outline", { list: void 0 }), {
551
+ title: "OpenFairyGUI Project Outline",
552
+ description: "Read a revision-bound project identity outline without source bytes or full property payloads.",
553
+ mimeType: JSON_MIME_TYPE
554
+ }, (uri, variables) => jsonResource(uri, runtime.getProjectOutline({ sessionId: firstVariable(variables.sessionId) })));
555
+ server.registerResource("openfairygui_backend_cache", new _modelcontextprotocol_sdk_server_mcp_js.ResourceTemplate("openfairygui://backend/cache/{sessionId}", { list: void 0 }), {
556
+ title: "OpenFairyGUI Backend Cache Snapshot",
557
+ description: "Read a derived backend cache envelope by backend-local session id.",
558
+ mimeType: JSON_MIME_TYPE
559
+ }, (uri, variables) => jsonResource(uri, runtime.getCacheSnapshot({ sessionId: firstVariable(variables.sessionId) })));
560
+ }
561
+ //#endregion
517
562
  //#region src/tool-handler.ts
518
- function jsonResult(payload, isError = false, compact = false) {
519
- const text = JSON.stringify(payload, (_key, value) => value instanceof Uint8Array ? [...value] : value, compact ? void 0 : 2);
563
+ function failureText(payload) {
564
+ const record = (value) => value !== null && typeof value === "object" ? value : {};
565
+ const root = record(payload), error = record(root.error), meta = record(root.meta);
566
+ const bounded = (value, limit) => typeof value === "string" ? value.slice(0, limit) : void 0;
567
+ const codes = /* @__PURE__ */ new Set();
568
+ let truncated = false;
569
+ for (const entries of [
570
+ error.issues,
571
+ error.diagnostics,
572
+ meta.diagnostics
573
+ ]) {
574
+ if (!Array.isArray(entries)) continue;
575
+ for (const entry of entries) {
576
+ const code = bounded(record(entry).code, 128);
577
+ if (!code || codes.has(code)) continue;
578
+ if (codes.size === 32) {
579
+ truncated = true;
580
+ break;
581
+ }
582
+ codes.add(code);
583
+ }
584
+ }
585
+ return JSON.stringify({
586
+ ok: false,
587
+ error: {
588
+ code: bounded(error.code, 128),
589
+ message: bounded(error.message, 1024)
590
+ },
591
+ diagnosticCodes: [...codes],
592
+ ...truncated ? { diagnosticCodesTruncated: true } : {},
593
+ requestId: bounded(meta.requestId, 128),
594
+ fullResult: "structuredContent.backendResult"
595
+ });
596
+ }
597
+ function jsonResult(payload, isError = false, paths = []) {
598
+ const envelope = { backendResult: structuredClone(payload) };
599
+ function encode(value, parts) {
600
+ if (!value || typeof value !== "object") return;
601
+ const [key, ...rest] = parts;
602
+ const record = value;
603
+ for (const name of key === "*" ? Object.keys(record) : [key]) {
604
+ if (!Object.hasOwn(record, name)) continue;
605
+ if (rest.length) encode(record[name], rest);
606
+ else if (record[name] instanceof Uint8Array) record[name] = Buffer.from(record[name]).toString("base64");
607
+ }
608
+ }
609
+ for (const path of paths) encode(envelope, path);
610
+ const text = JSON.stringify(envelope.backendResult);
520
611
  const wirePayload = JSON.parse(text);
521
612
  return {
522
613
  content: [{
523
614
  type: "text",
524
- text
615
+ text: isError ? failureText(wirePayload) : "Result available in structuredContent.backendResult."
525
616
  }],
526
617
  structuredContent: { backendResult: wirePayload },
527
618
  isError
@@ -553,8 +644,10 @@ async function callOpenFairyGuiBackendTool(runtime, name, input, policy) {
553
644
  if (!definition) throw new RangeError(`Unknown OpenFairyGUI backend MCP tool: ${name}`);
554
645
  const bytePaths = CONTRACT_SNAPSHOT.tools[definition.backendMethod].bytePaths;
555
646
  if (!isOpenFairyGuiMcpPayloadWithinBudget(input, bytePaths)) throw new RangeError("MCP input exceeds the depth, node, key, string, or byte budget.");
556
- const parsed = definition.inputSchema.parse(input);
557
- const decoded = decodeToolBytes(parsed, bytePaths);
647
+ const checked = definition.inputSchema.safeParse(input);
648
+ if (!checked.success) throw new zod.z.ZodRealError(focusContractIssues(checked.error.issues, input));
649
+ const parsed = checked.data;
650
+ const decoded = (0, _openfairygui_backend_docs.decodeContractBytes)(parsed, bytePaths);
558
651
  const startedAt = Date.now();
559
652
  try {
560
653
  let hostFailure = await policy?.beforeCall(structuredClone(parsed));
@@ -563,7 +656,7 @@ async function callOpenFairyGuiBackendTool(runtime, name, input, policy) {
563
656
  if (!isBackendFailure(hostFailure)) throw new TypeError("Host policy must return a failure or undefined.");
564
657
  }
565
658
  const result = hostFailure ?? await Reflect.apply(runtime[definition.backendMethod], runtime, definition.backendMethod === "getCapabilities" ? [] : [decoded]);
566
- let response = jsonResult(result, isBackendFailure(result), definition.maxResponseBytes !== void 0);
659
+ let response = jsonResult(result, isBackendFailure(result), CONTRACT_SNAPSHOT.tools[definition.backendMethod].outputBytePaths);
567
660
  if (definition.maxResponseBytes !== void 0 && new TextEncoder().encode(JSON.stringify(response)).byteLength > definition.maxResponseBytes) {
568
661
  response = jsonResult({
569
662
  ...unhandledBackendFailure(startedAt),
@@ -578,15 +671,17 @@ async function callOpenFairyGuiBackendTool(runtime, name, input, policy) {
578
671
  if (hostFailure === void 0) definition.outputSchema.parse(response.structuredContent);
579
672
  else policy.failureSchema.parse(response.structuredContent?.backendResult);
580
673
  return response;
581
- } catch {
582
- return jsonResult(unhandledBackendFailure(startedAt), true);
674
+ } catch (error) {
675
+ const failure = unhandledBackendFailure(startedAt);
676
+ console.error(`[openfairygui-mcp] ${name} failed (requestId ${failure.meta.requestId}):`, error);
677
+ return jsonResult(failure, true);
583
678
  }
584
679
  }
585
680
  //#endregion
586
681
  //#region src/server.ts
587
682
  const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
588
683
  function getInjectedPackageVersion() {
589
- const version = "0.6.3";
684
+ const version = "0.7.1";
590
685
  return typeof version === "string" && true ? version : null;
591
686
  }
592
687
  function readPackageVersion() {
@@ -599,16 +694,25 @@ function readPackageVersion() {
599
694
  return "0.0.0-dev";
600
695
  }
601
696
  const PACKAGE_VERSION = readPackageVersion();
697
+ const DEFAULT_INSTRUCTIONS = [
698
+ "Read openfairygui_docs_read with id index, then workflow and the needed operation/method documents.",
699
+ "Open a project directory or .fairy file within the configured allowed roots.",
700
+ "Read the project outline, then query exact entity IDs and their current revision.",
701
+ "Preflight the operation batch with expectedRevision before applying it.",
702
+ "Apply at that same revision; on stale_write re-query and reconsider, never retry blindly.",
703
+ "Validate the edited session, save with its current revision, and close the session when finished."
704
+ ].join("\n");
602
705
  function createOpenFairyGuiMcpServer(options = {}) {
603
706
  for (const name of Object.keys(options.toolPolicies ?? {})) if (!OPENFAIRYGUI_BACKEND_TOOL_DEFINITIONS.some((definition) => definition.name === name)) throw new RangeError(`Unknown OpenFairyGUI backend MCP tool policy: ${name}`);
604
707
  const runtime = options.runtime ?? (0, _openfairygui_backend_node.createNodeBackendRuntime)({ allowedProjectRoots: options.allowedProjectRoots ?? [process.cwd()] });
605
708
  const server = new _modelcontextprotocol_sdk_server_mcp_js.McpServer({
606
709
  name: options.name ?? "openfairygui-mcp",
607
710
  version: options.version ?? PACKAGE_VERSION
608
- }, { instructions: options.instructions });
711
+ }, { instructions: options.instructions ?? DEFAULT_INSTRUCTIONS });
609
712
  for (const definition of OPENFAIRYGUI_BACKEND_TOOL_DEFINITIONS) {
610
713
  const policy = options.toolPolicies?.[definition.name];
611
- const outputSchema = policy ? definition.outputSchema.extend({ backendResult: zod.z.union([definition.outputSchema.shape.backendResult, policy.failureSchema]) }) : definition.outputSchema;
714
+ let outputSchema;
715
+ const getOutputSchema = () => outputSchema ??= policy ? definition.outputSchema.extend({ backendResult: zod.z.union([definition.outputSchema.shape.backendResult, policy.failureSchema]) }) : definition.outputSchema;
612
716
  const metadata = {
613
717
  name: definition.name,
614
718
  title: definition.title,
@@ -616,26 +720,72 @@ function createOpenFairyGuiMcpServer(options = {}) {
616
720
  annotations: definition.annotations,
617
721
  _meta: {
618
722
  "openfairygui/backendMethod": definition.backendMethod,
619
- "openfairygui/adapter": "thin-backend-p2",
723
+ "openfairygui/adapter": "backend",
620
724
  "openfairygui/contractDigest": CONTRACT_SNAPSHOT.digest,
621
725
  ...policy ? { "openfairygui/hostPolicy": true } : {}
622
726
  }
623
727
  };
624
728
  server.registerTool(definition.name, {
625
729
  ...metadata,
626
- inputSchema: compactToolSchema(definition.inputSchema, "input"),
627
- outputSchema: compactToolSchema(outputSchema, "output")
730
+ inputSchema: compactToolSchema(() => definition.inputSchema, "input", (value) => isOpenFairyGuiMcpPayloadWithinBudget(value, CONTRACT_SNAPSHOT.tools[definition.backendMethod].bytePaths)),
731
+ outputSchema: compactToolSchema(getOutputSchema, "output")
628
732
  }, async (args) => callOpenFairyGuiBackendTool(runtime, definition.name, args, policy));
629
733
  }
734
+ server.registerTool("openfairygui_docs_read", {
735
+ title: "Read installed documentation",
736
+ description: "Read index first, then an exact document ID from that index. Offline, read-only and bound to the installed version.",
737
+ inputSchema: zod.z.object({ id: zod.z.string().min(1).max(256).default("index") }),
738
+ _meta: { "openfairygui/contractDigest": CONTRACT_SNAPSHOT.digest },
739
+ annotations: {
740
+ readOnlyHint: true,
741
+ idempotentHint: true,
742
+ openWorldHint: false
743
+ }
744
+ }, async ({ id }) => {
745
+ try {
746
+ return { content: [{
747
+ type: "text",
748
+ text: id === "index" ? JSON.stringify((0, _openfairygui_backend_docs.getInstalledDocumentationIndex)()) : (0, _openfairygui_backend_docs.readInstalledDocumentation)(id).text
749
+ }] };
750
+ } catch {
751
+ return {
752
+ isError: true,
753
+ content: [{
754
+ type: "text",
755
+ text: "Unknown document ID; read index for available IDs."
756
+ }]
757
+ };
758
+ }
759
+ });
630
760
  registerOpenFairyGuiBackendResources(server, runtime);
761
+ if (options.publish) server.registerTool("openfairygui_host_publish", {
762
+ title: "Publish project through host",
763
+ description: "Publish saved project files through an explicitly enabled host. Host owns path authorization, output policy and plugin execution; unsaved session edits are not included.",
764
+ inputSchema: zod.z.object({
765
+ projectPath: zod.z.string().min(1).max(4096),
766
+ outputDirectory: zod.z.string().min(1).max(4096),
767
+ packageNames: zod.z.array(zod.z.string().min(1).max(256)).max(1e3).optional()
768
+ }),
769
+ annotations: {
770
+ readOnlyHint: false,
771
+ destructiveHint: true,
772
+ idempotentHint: false,
773
+ openWorldHint: false
774
+ }
775
+ }, options.publish);
631
776
  registerOpenFairyGuiBackendPrompts(server);
632
777
  return server;
633
778
  }
634
779
  //#endregion
635
780
  //#region src/stdio.ts
781
+ function parseAllowedProjectRoots(value) {
782
+ if (value === void 0) return void 0;
783
+ const roots = value.split(node_path.default.delimiter).map((entry) => entry.trim()).filter(Boolean);
784
+ if (roots.length === 0) throw new Error("OPENFAIRYGUI_ALLOWED_PROJECT_ROOTS is set but lists no project roots. Set absolute roots separated by the platform path delimiter, or unset it to allow only the working directory.");
785
+ return roots;
786
+ }
636
787
  async function connectOpenFairyGuiMcpStdio() {
637
- const configuredRoots = process.env.OPENFAIRYGUI_ALLOWED_PROJECT_ROOTS?.split(node_path.default.delimiter).map((value) => value.trim()).filter(Boolean);
638
- await createOpenFairyGuiMcpServer({ allowedProjectRoots: configuredRoots }).connect(new _modelcontextprotocol_sdk_server_stdio_js.StdioServerTransport());
788
+ await createOpenFairyGuiMcpServer({ allowedProjectRoots: parseAllowedProjectRoots(process.env.OPENFAIRYGUI_ALLOWED_PROJECT_ROOTS) }).connect(new _modelcontextprotocol_sdk_server_stdio_js.StdioServerTransport());
639
789
  }
640
790
  if (process.argv[1] && require("url").pathToFileURL(__filename).href === (0, node_url.pathToFileURL)(process.argv[1]).href) connectOpenFairyGuiMcpStdio().catch((error) => {
641
791
  console.error(error instanceof Error ? error.stack ?? error.message : String(error));