@enhance-eng/enhance 0.1.21 → 0.1.25

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.
@@ -1,10 +1,313 @@
1
1
  #!/usr/bin/env node
2
- import { A as parseCanvasReference, E as assertCanvasReferenceNodes, M as CliError, Tt as canvasReadableSceneDocumentSchema, ct as getCanvasDocumentOutputSchema, d as createCapabilityCatalogAdapter, i as toCanvasAuthoringResult, l as createMcpCapabilityDiscoveryAdapter, n as withCommandName, o as toFailurePayload, r as canvasRenderResultSchema, s as toPresentedCapabilities, t as withCommandInFailure, vt as canvasRenderSourceStateSchema, w as canvasEditCapabilityInputSchema, y as canvasWriteHtmlCapabilityInputSchema, yt as canvasRenderTargetSchema } from "./cli-output-identity.lib-a1wTreJ6.mjs";
2
+ import { Gn as getCanvasDocumentOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Mt as parseCanvasReference, Pt as CliError, Q as canvasRenderBatchResultSchema, Qn as canvasRenderSourceStateSchema, Tt as canvasEditCapabilityInputSchema, c as toPresentedCapabilities, er as canvasRenderTargetSchema, f as createCapabilityCatalogAdapter, jt as hasCanvasReferenceScope, kt as canvasReferenceRenderTarget, lr as canvasReadableSceneDocumentSchema, n as withCommandName, o as toMcpFailurePayload, r as toCanvasAuthoringResult, rt as canvasRenderFileSchema, t as withCommandInFailure, u as createMcpCapabilityDiscoveryAdapter } from "./cli-output-identity.lib-DpON8As5.mjs";
3
3
  import { z } from "zod";
4
+ import { readFileSync } from "node:fs";
5
+ import path from "node:path";
4
6
  import { createHash, randomUUID } from "node:crypto";
5
7
  import { readFile, rm } from "node:fs/promises";
6
8
  import { McpServer } from "@modelcontextprotocol/server";
7
9
 
10
+ //#region src/infrastructure/mcp-render-attachment.adapter.ts
11
+ const createMcpRenderAttachmentAdapter = async (server, result, delivery) => {
12
+ const body = await readFile(result.path);
13
+ const id = randomUUID();
14
+ const uri = `enhance://artifact/${id}`;
15
+ if (delivery === "embedded" && result.cleanup === "unlink-after-use") try {
16
+ await rm(result.path, { force: true });
17
+ } catch {}
18
+ if (delivery === "linked") server.registerResource(`artifact-${id}`, uri, {
19
+ title: "Enhance artifact",
20
+ mimeType: result.contentType
21
+ }, (requested) => ({ contents: [{
22
+ uri: requested.href,
23
+ mimeType: result.contentType,
24
+ blob: body.toString("base64")
25
+ }] }));
26
+ return {
27
+ metadata: canvasRenderFileSchema.omit({
28
+ path: true,
29
+ sensitive: true,
30
+ cleanup: true,
31
+ deleteAfter: true
32
+ }).parse(result),
33
+ artifact: {
34
+ uri,
35
+ mimeType: result.contentType,
36
+ bytes: body.byteLength
37
+ },
38
+ image: {
39
+ type: "image",
40
+ data: body.toString("base64"),
41
+ mimeType: result.contentType
42
+ }
43
+ };
44
+ };
45
+
46
+ //#endregion
47
+ //#region src/infrastructure/mcp-render-batch-result.adapter.ts
48
+ const createMcpRenderBatchResultAdapter = async (server, presented, delivery) => {
49
+ const parsed = canvasRenderBatchResultSchema.safeParse(presented);
50
+ if (!parsed.success) return null;
51
+ const attachments = [];
52
+ let isComplete = parsed.data.complete;
53
+ const results = [];
54
+ for (const target of parsed.data.results) {
55
+ const render = canvasRenderFileSchema.safeParse(target.outcome);
56
+ if (!render.success) {
57
+ results.push({
58
+ ...target,
59
+ pixelsDelivered: false
60
+ });
61
+ continue;
62
+ }
63
+ try {
64
+ const attachment = await createMcpRenderAttachmentAdapter(server, render.data, delivery);
65
+ attachments.push(attachment);
66
+ results.push({
67
+ ...target,
68
+ outcome: attachment.metadata,
69
+ pixelsDelivered: true,
70
+ contentIndex: attachments.length,
71
+ artifact: attachment.artifact
72
+ });
73
+ } catch {
74
+ isComplete = false;
75
+ results.push({
76
+ id: target.id,
77
+ target: target.target,
78
+ maxOutputPixels: target.maxOutputPixels,
79
+ pixelsDelivered: false,
80
+ outcome: {
81
+ state: "delivery_unavailable",
82
+ operation: {
83
+ kind: "canvas-render",
84
+ canvasId: render.data.canvasId,
85
+ jobId: render.data.jobId
86
+ },
87
+ requestedVersion: render.data.requestedVersion,
88
+ loadedVersion: render.data.loadedVersion,
89
+ next: ["Read operation_status with includeImage true to collect the existing render."]
90
+ }
91
+ });
92
+ }
93
+ }
94
+ return {
95
+ value: {
96
+ ...parsed.data,
97
+ complete: isComplete,
98
+ results
99
+ },
100
+ detail: null,
101
+ attachments
102
+ };
103
+ };
104
+
105
+ //#endregion
106
+ //#region src/infrastructure/mcp-result.adapter.ts
107
+ const PROTECTED_RESULT_BYTES = 2e4;
108
+ const SENSITIVE_FIELD = /(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu;
109
+ const SIGNED_URL = /[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu;
110
+ const textFor = (value) => JSON.stringify(value);
111
+ const hasProtectedMaterial = (value, key = "") => {
112
+ if (typeof value === "string") return SIGNED_URL.test(value) || SENSITIVE_FIELD.test(key) && !key.endsWith("Id");
113
+ if (Array.isArray(value)) return value.some((entry) => hasProtectedMaterial(entry, key));
114
+ if (typeof value !== "object" || value === null) return false;
115
+ if (Reflect.get(value, "sensitive") === true) return true;
116
+ return Object.entries(value).some(([childKey, child]) => hasProtectedMaterial(child, childKey));
117
+ };
118
+ const artifactResult = (server, serialized, delivery) => {
119
+ const id = randomUUID();
120
+ const uri = `enhance://result/${id}`;
121
+ const bytes = Buffer.byteLength(serialized);
122
+ if (delivery === "embedded") {
123
+ const structuredContent = {
124
+ ok: true,
125
+ artifact: {
126
+ uri,
127
+ mimeType: "application/json",
128
+ bytes
129
+ }
130
+ };
131
+ return {
132
+ content: [{
133
+ type: "text",
134
+ text: textFor(structuredContent)
135
+ }, {
136
+ type: "resource",
137
+ resource: {
138
+ uri,
139
+ mimeType: "application/json",
140
+ text: serialized
141
+ }
142
+ }],
143
+ structuredContent
144
+ };
145
+ }
146
+ server.registerResource(`result-${id}`, uri, {
147
+ title: "Protected Enhance result",
148
+ mimeType: "application/json"
149
+ }, (requested) => ({ contents: [{
150
+ uri: requested.href,
151
+ mimeType: "application/json",
152
+ text: serialized
153
+ }] }));
154
+ const structuredContent = {
155
+ ok: true,
156
+ artifact: {
157
+ uri,
158
+ mimeType: "application/json",
159
+ bytes
160
+ }
161
+ };
162
+ return {
163
+ content: [{
164
+ type: "text",
165
+ text: textFor(structuredContent)
166
+ }, {
167
+ type: "resource_link",
168
+ name: "Protected Enhance result",
169
+ uri,
170
+ mimeType: "application/json"
171
+ }],
172
+ structuredContent
173
+ };
174
+ };
175
+ const validationError = (error) => new CliError("BAD_REQUEST", "Input validation error.", "Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.", Object.fromEntries(error.issues.map((issue) => [issue.path.length === 0 ? "input" : issue.path.join("."), issue.message])));
176
+ const prepareCanvasResult = async (server, presented, delivery) => {
177
+ const batch = await createMcpRenderBatchResultAdapter(server, presented, delivery);
178
+ if (batch !== null) return batch;
179
+ const render = canvasRenderFileSchema.safeParse(presented);
180
+ if (render.success) {
181
+ const attachment = await createMcpRenderAttachmentAdapter(server, render.data, delivery);
182
+ return {
183
+ value: attachment.metadata,
184
+ detail: null,
185
+ attachments: [attachment]
186
+ };
187
+ }
188
+ const originalAuthoring = toCanvasAuthoringResult(presented);
189
+ if (originalAuthoring === null) return {
190
+ value: presented,
191
+ detail: null,
192
+ attachments: []
193
+ };
194
+ const original = originalAuthoring.detail ?? originalAuthoring.value;
195
+ const review = canvasRenderFileSchema.safeParse(original["review"]);
196
+ if (!review.success) return {
197
+ ...originalAuthoring,
198
+ attachments: []
199
+ };
200
+ try {
201
+ const attachment = await createMcpRenderAttachmentAdapter(server, review.data, delivery);
202
+ const safeResult = {
203
+ ...original,
204
+ review: {
205
+ ...attachment.metadata,
206
+ artifact: attachment.artifact
207
+ }
208
+ };
209
+ const authoring = toCanvasAuthoringResult(safeResult);
210
+ return {
211
+ value: authoring?.value ?? safeResult,
212
+ detail: authoring?.detail ?? null,
213
+ attachments: [attachment]
214
+ };
215
+ } catch {
216
+ const safeResult = {
217
+ ...original,
218
+ review: {
219
+ state: "unavailable",
220
+ mutationCommitted: true,
221
+ requestedVersion: original["version"],
222
+ retry: {
223
+ tool: "canvas_render",
224
+ arguments: {
225
+ canvas: original["canvasId"],
226
+ expectedVersion: original["version"],
227
+ target: review.data.target
228
+ }
229
+ }
230
+ },
231
+ next: ["Retry the render of the committed version; do not replay the write."]
232
+ };
233
+ const authoring = toCanvasAuthoringResult(safeResult);
234
+ return {
235
+ value: authoring?.value ?? safeResult,
236
+ detail: authoring?.detail ?? null,
237
+ attachments: []
238
+ };
239
+ }
240
+ };
241
+ const inlineResult = (result, commandName) => {
242
+ const structuredContent = {
243
+ ok: true,
244
+ result: withCommandName(result, commandName)
245
+ };
246
+ return {
247
+ content: [{
248
+ type: "text",
249
+ text: textFor(structuredContent)
250
+ }],
251
+ structuredContent
252
+ };
253
+ };
254
+ const createMcpResultAdapter = (authenticationRemediation, commandName = "enhance") => ({
255
+ success: async (server, result, delivery) => {
256
+ const presented = withCommandName(result, commandName);
257
+ const prepared = await prepareCanvasResult(server, presented, delivery);
258
+ const attachments = prepared.attachments;
259
+ const attachment = attachments.length === 1 ? attachments[0] : void 0;
260
+ const serialized = textFor(prepared.value);
261
+ if (hasProtectedMaterial(prepared.value)) return artifactResult(server, serialized, delivery);
262
+ if (attachments.length === 0 && prepared.detail === null && Buffer.byteLength(serialized) > PROTECTED_RESULT_BYTES) return artifactResult(server, serialized, delivery);
263
+ const detail = prepared.detail === null ? null : artifactResult(server, textFor(prepared.detail), delivery);
264
+ const structuredContent = {
265
+ ok: true,
266
+ result: prepared.value,
267
+ ...attachment !== void 0 && { artifact: attachment.artifact },
268
+ ...detail !== null && { detail: detail.structuredContent.artifact }
269
+ };
270
+ return {
271
+ content: [
272
+ {
273
+ type: "text",
274
+ text: textFor(structuredContent)
275
+ },
276
+ ...attachments.map((entry) => entry.image),
277
+ ...detail?.content.filter((entry) => entry.type !== "text") ?? []
278
+ ],
279
+ structuredContent
280
+ };
281
+ },
282
+ inline: (result) => inlineResult(result, commandName),
283
+ structured: (result) => ({
284
+ structuredContent: result,
285
+ content: [{
286
+ type: "text",
287
+ text: textFor(result)
288
+ }]
289
+ }),
290
+ failure: (error) => {
291
+ const failure = withCommandInFailure(toMcpFailurePayload(error instanceof z.ZodError ? validationError(error) : error), commandName);
292
+ const structuredContent = {
293
+ ok: false,
294
+ error: failure.code === "UNAUTHORIZED" ? {
295
+ ...failure,
296
+ remediation: authenticationRemediation
297
+ } : failure
298
+ };
299
+ return {
300
+ content: [{
301
+ type: "text",
302
+ text: textFor(structuredContent)
303
+ }],
304
+ structuredContent,
305
+ isError: true
306
+ };
307
+ }
308
+ });
309
+
310
+ //#endregion
8
311
  //#region src/infrastructure/mcp-progressive.schema.ts
9
312
  const failureSchema = z.object({
10
313
  ok: z.literal(false),
@@ -89,6 +392,69 @@ const mcpDescribeResultSchema = z.union([z.object({
89
392
  ok: z.literal(true),
90
393
  result: capabilityContractSchema
91
394
  }), failureSchema]);
395
+ const mcpQueryInputSchema = z.object({
396
+ capability: z.string().min(1).describe("Exact query id from an available complete contract."),
397
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema.")
398
+ });
399
+ const mcpMutationInputSchema = z.object({
400
+ capability: z.string().min(1).describe("Exact mutation id from an available complete contract."),
401
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema."),
402
+ clientToken: z.uuid().optional().describe("Stable UUID reused only when retrying this exact mutation input.")
403
+ });
404
+
405
+ //#endregion
406
+ //#region src/infrastructure/mcp-workflows.adapter.ts
407
+ const workflowNameSchema = z.enum([
408
+ "apply-canvas-design",
409
+ "design-on-canvas",
410
+ "publish-prototype",
411
+ "respond-to-feedback"
412
+ ]);
413
+ const workflowSchema = z.object({
414
+ name: workflowNameSchema,
415
+ description: z.string().min(1),
416
+ body: z.string().min(1)
417
+ });
418
+ const instructions = "Before designing on a canvas, responding to feedback, publishing a prototype or applying a canvas design, call workflow_guide with the matching workflow and follow its guidance.";
419
+ const createMcpWorkflowsAdapter = (directory, authenticationInstructions) => {
420
+ const workflows = workflowNameSchema.options.map((name) => {
421
+ const source = readFileSync(path.join(directory, name, "SKILL.md"), "utf8");
422
+ const match = /^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n---\r?\n([\s\S]+)$/u.exec(source);
423
+ const workflow = workflowSchema.parse({
424
+ name: match?.[1],
425
+ description: match?.[2],
426
+ body: match?.[3]
427
+ });
428
+ if (workflow.name !== name) throw new Error(`Workflow name does not match its folder: ${name}`);
429
+ return workflow;
430
+ });
431
+ return {
432
+ instructions: [instructions, authenticationInstructions].filter(Boolean).join(" "),
433
+ register: (server) => {
434
+ for (const workflow of workflows) server.registerPrompt(workflow.name, { description: workflow.description }, () => ({ messages: [{
435
+ role: "user",
436
+ content: {
437
+ type: "text",
438
+ text: workflow.body
439
+ }
440
+ }] }));
441
+ server.registerTool("workflow_guide", {
442
+ title: "Load an Enhance workflow",
443
+ description: instructions,
444
+ inputSchema: z.strictObject({ workflow: workflowNameSchema }),
445
+ annotations: {
446
+ readOnlyHint: true,
447
+ destructiveHint: false,
448
+ idempotentHint: true,
449
+ openWorldHint: false
450
+ }
451
+ }, ({ workflow: name }) => ({ content: workflows.filter((workflow) => workflow.name === name).map((workflow) => ({
452
+ type: "text",
453
+ text: workflow.body
454
+ })) }));
455
+ }
456
+ };
457
+ };
92
458
 
93
459
  //#endregion
94
460
  //#region src/infrastructure/mcp-canvas-tools.adapter.ts
@@ -101,12 +467,13 @@ const writeSchema = canvasWriteHtmlCapabilityInputSchema.pick({
101
467
  html: true,
102
468
  idPrefix: true
103
469
  }).extend({
104
- canvas: z.string().min(1).describe("Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL."),
470
+ canvas: z.string().min(1).describe("Canvas UUID or complete canvas/page/selection URL. Preserve every supplied page and selection."),
105
471
  mode: z.enum(["insert-children", "replace"]).default("insert-children"),
106
472
  clientToken
107
473
  });
108
474
  const editSchema = canvasEditCapabilityInputSchema.extend({ clientToken });
109
475
  const renderSchema = z.object({
476
+ clientToken,
110
477
  canvas: z.string().min(1),
111
478
  expectedVersion: z.number().int().positive().describe("Version returned by the latest successful read or write."),
112
479
  target: canvasRenderTargetSchema.default({ kind: "content" }),
@@ -123,22 +490,18 @@ const invoke = async (input, id, args, token = null) => {
123
490
  });
124
491
  };
125
492
  const renderTarget = async (input, args) => {
126
- const reference = parseCanvasReference(args.canvas);
127
- if (reference.nodeIds.length === 0) return {
493
+ const requested = parseCanvasReference(args.canvas);
494
+ const reference = input.scope ?? requested;
495
+ if (reference.canvasId !== requested.canvasId) throw new CliError("FORBIDDEN", "This turn cannot render another canvas.", "Render the submitted canvas and selection.");
496
+ if (!hasCanvasReferenceScope(reference)) return {
128
497
  canvasId: reference.canvasId,
129
498
  target: args.target
130
499
  };
131
- const nodeId = args.target.kind === "node" ? args.target.nodeId : args.target.kind === "content" && reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0;
132
- if (nodeId === void 0) throw new CliError("BAD_REQUEST", "A selection link requires one selected node to render.", "Choose a node target inside the selection; bounds or whole-canvas renders can include unrelated content.");
133
500
  const held = getCanvasDocumentOutputSchema.parse(await invoke(input, "canvas.document.get", { canvasId: reference.canvasId }));
134
501
  if (held.version !== args.expectedVersion) throw new CliError("CONFLICT", "The canvas changed before rendering.", "Read the selected subtree and render its current version.");
135
- assertCanvasReferenceNodes(reference, canvasReadableSceneDocumentSchema.parse(held.document), [nodeId]);
136
502
  return {
137
503
  canvasId: reference.canvasId,
138
- target: {
139
- kind: "node",
140
- nodeId
141
- }
504
+ target: canvasReferenceRenderTarget(reference, canvasReadableSceneDocumentSchema.parse(held.document), args.target)
142
505
  };
143
506
  };
144
507
  const deliver = async (server, input, action) => {
@@ -151,7 +514,7 @@ const deliver = async (server, input, action) => {
151
514
  const registerWrite = (server, input) => {
152
515
  if (input.catalog.some((capability) => capability.id === "canvas.writeHtml")) server.registerTool("canvas_write_html", {
153
516
  title: "Design editable canvas content",
154
- description: "Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. If starting state is unknown, call capability_query with {\"capability\":\"canvas.inspect\",\"input\":{\"canvasId\":\"<UUID from canvas URL>\"}}. When nodeCount is 0, use targetNodeId \"root\" and the returned version. Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.",
517
+ description: `Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. ${input.readTool === "canvas_read" ? "Read canonical IDs and the current version with canvas_read. Keep all writes inside the frozen selection." : "If starting state is unknown, call capability_query with {\"capability\":\"canvas.read\",\"input\":{\"canvasId\":\"<UUID from canvas URL>\"}}. When nodeCount is 0, use targetNodeId \"root\" and the returned version."} Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.`,
155
518
  inputSchema: writeSchema,
156
519
  outputSchema: mcpDispatchedResultSchema,
157
520
  annotations: {
@@ -165,6 +528,7 @@ const registerWrite = (server, input) => {
165
528
  return invoke(input, "canvas.writeHtml", {
166
529
  ...args,
167
530
  canvasId: reference.canvasId,
531
+ ...reference.pageId !== void 0 && { pageId: reference.pageId },
168
532
  ...reference.nodeIds.length > 0 && { selectionNodeIds: reference.nodeIds },
169
533
  review: "none",
170
534
  renderOutputPath: null,
@@ -195,9 +559,9 @@ const registerRender = (server, input) => {
195
559
  inputSchema: renderSchema,
196
560
  outputSchema: mcpDispatchedResultSchema,
197
561
  annotations: {
198
- readOnlyHint: true,
562
+ readOnlyHint: false,
199
563
  destructiveHint: false,
200
- idempotentHint: true,
564
+ idempotentHint: false,
201
565
  openWorldHint: false
202
566
  }
203
567
  }, async (args) => deliver(server, input, async () => invoke(input, "canvas.render", {
@@ -208,12 +572,17 @@ const registerRender = (server, input) => {
208
572
  outputPath: null,
209
573
  overwrite: false,
210
574
  timeoutMs: 12e4
211
- })));
575
+ }, args.clientToken ?? null)));
212
576
  };
213
577
  const createMcpCanvasToolsAdapter = (input) => ({ register: (server) => {
214
- registerWrite(server, input);
215
- registerEdit(server, input);
216
- registerRender(server, input);
578
+ const selected = input.tools ?? [
579
+ "write",
580
+ "edit",
581
+ "render"
582
+ ];
583
+ if (selected.includes("write")) registerWrite(server, input);
584
+ if (selected.includes("edit")) registerEdit(server, input);
585
+ if (selected.includes("render")) registerRender(server, input);
217
586
  } });
218
587
 
219
588
  //#endregion
@@ -293,235 +662,6 @@ const createMcpDescribeToolAdapter = (discovery, mcpResults) => ({ register: (se
293
662
  });
294
663
  } });
295
664
 
296
- //#endregion
297
- //#region src/infrastructure/mcp-result.adapter.ts
298
- const PROTECTED_RESULT_BYTES = 2e4;
299
- const SENSITIVE_FIELD = /(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu;
300
- const SIGNED_URL = /[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu;
301
- const textFor = (value) => JSON.stringify(value);
302
- const hasProtectedMaterial = (value, key = "") => {
303
- if (typeof value === "string") return SIGNED_URL.test(value) || SENSITIVE_FIELD.test(key) && !key.endsWith("Id");
304
- if (Array.isArray(value)) return value.some((entry) => hasProtectedMaterial(entry, key));
305
- if (typeof value !== "object" || value === null) return false;
306
- if (Reflect.get(value, "sensitive") === true) return true;
307
- return Object.entries(value).some(([childKey, child]) => hasProtectedMaterial(child, childKey));
308
- };
309
- const renderAttachment = async (server, result, delivery) => {
310
- const body = await readFile(result.path);
311
- const id = randomUUID();
312
- const uri = `enhance://artifact/${id}`;
313
- if (delivery === "embedded" && result.cleanup === "unlink-after-use") try {
314
- await rm(result.path, { force: true });
315
- } catch {}
316
- if (delivery === "linked") server.registerResource(`artifact-${id}`, uri, {
317
- title: "Enhance artifact",
318
- mimeType: result.contentType
319
- }, (requested) => ({ contents: [{
320
- uri: requested.href,
321
- mimeType: result.contentType,
322
- blob: body.toString("base64")
323
- }] }));
324
- return {
325
- metadata: canvasRenderResultSchema.omit({
326
- path: true,
327
- sensitive: true,
328
- cleanup: true,
329
- deleteAfter: true
330
- }).parse(result),
331
- artifact: {
332
- uri,
333
- mimeType: result.contentType,
334
- bytes: body.byteLength
335
- },
336
- image: {
337
- type: "image",
338
- data: body.toString("base64"),
339
- mimeType: result.contentType
340
- }
341
- };
342
- };
343
- const artifactResult = (server, serialized, delivery) => {
344
- const id = randomUUID();
345
- const uri = `enhance://result/${id}`;
346
- const bytes = Buffer.byteLength(serialized);
347
- if (delivery === "embedded") {
348
- const structuredContent = {
349
- ok: true,
350
- artifact: {
351
- uri,
352
- mimeType: "application/json",
353
- bytes
354
- }
355
- };
356
- return {
357
- content: [{
358
- type: "text",
359
- text: textFor(structuredContent)
360
- }, {
361
- type: "resource",
362
- resource: {
363
- uri,
364
- mimeType: "application/json",
365
- text: serialized
366
- }
367
- }],
368
- structuredContent
369
- };
370
- }
371
- server.registerResource(`result-${id}`, uri, {
372
- title: "Protected Enhance result",
373
- mimeType: "application/json"
374
- }, (requested) => ({ contents: [{
375
- uri: requested.href,
376
- mimeType: "application/json",
377
- text: serialized
378
- }] }));
379
- const structuredContent = {
380
- ok: true,
381
- artifact: {
382
- uri,
383
- mimeType: "application/json",
384
- bytes
385
- }
386
- };
387
- return {
388
- content: [{
389
- type: "text",
390
- text: textFor(structuredContent)
391
- }, {
392
- type: "resource_link",
393
- name: "Protected Enhance result",
394
- uri,
395
- mimeType: "application/json"
396
- }],
397
- structuredContent
398
- };
399
- };
400
- const validationError = (error) => new CliError("BAD_REQUEST", "Input validation error.", "Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.", Object.fromEntries(error.issues.map((issue) => [issue.path.length === 0 ? "input" : issue.path.join("."), issue.message])));
401
- const prepareCanvasResult = async (server, presented, delivery) => {
402
- const render = canvasRenderResultSchema.safeParse(presented);
403
- if (render.success) {
404
- const attachment = await renderAttachment(server, render.data, delivery);
405
- return {
406
- value: attachment.metadata,
407
- detail: null,
408
- attachment
409
- };
410
- }
411
- const originalAuthoring = toCanvasAuthoringResult(presented);
412
- if (originalAuthoring === null) return {
413
- value: presented,
414
- detail: null,
415
- attachment: null
416
- };
417
- const original = originalAuthoring.detail ?? originalAuthoring.value;
418
- const review = canvasRenderResultSchema.safeParse(original["review"]);
419
- if (!review.success) return {
420
- ...originalAuthoring,
421
- attachment: null
422
- };
423
- try {
424
- const attachment = await renderAttachment(server, review.data, delivery);
425
- const safeResult = {
426
- ...original,
427
- review: {
428
- ...attachment.metadata,
429
- artifact: attachment.artifact
430
- }
431
- };
432
- const authoring = toCanvasAuthoringResult(safeResult);
433
- return {
434
- value: authoring?.value ?? safeResult,
435
- detail: authoring?.detail ?? null,
436
- attachment
437
- };
438
- } catch {
439
- const safeResult = {
440
- ...original,
441
- review: {
442
- state: "unavailable",
443
- mutationCommitted: true,
444
- requestedVersion: original["version"],
445
- retry: {
446
- tool: "canvas_render",
447
- arguments: {
448
- canvas: original["canvasId"],
449
- expectedVersion: original["version"],
450
- target: review.data.target
451
- }
452
- }
453
- },
454
- next: ["Retry the render of the committed version; do not replay the write."]
455
- };
456
- const authoring = toCanvasAuthoringResult(safeResult);
457
- return {
458
- value: authoring?.value ?? safeResult,
459
- detail: authoring?.detail ?? null,
460
- attachment: null
461
- };
462
- }
463
- };
464
- const inlineResult = (result, commandName) => {
465
- const structuredContent = {
466
- ok: true,
467
- result: withCommandName(result, commandName)
468
- };
469
- return {
470
- content: [{
471
- type: "text",
472
- text: textFor(structuredContent)
473
- }],
474
- structuredContent
475
- };
476
- };
477
- const createMcpResultAdapter = (authenticationRemediation, commandName = "enhance") => ({
478
- success: async (server, result, delivery) => {
479
- const presented = withCommandName(result, commandName);
480
- const prepared = await prepareCanvasResult(server, presented, delivery);
481
- const attachment = prepared.attachment;
482
- const serialized = textFor(prepared.value);
483
- if (hasProtectedMaterial(prepared.value)) return artifactResult(server, serialized, delivery);
484
- if (attachment === null && prepared.detail === null && Buffer.byteLength(serialized) > PROTECTED_RESULT_BYTES) return artifactResult(server, serialized, delivery);
485
- const detail = prepared.detail === null ? null : artifactResult(server, textFor(prepared.detail), delivery);
486
- const structuredContent = {
487
- ok: true,
488
- result: prepared.value,
489
- ...attachment !== null && { artifact: attachment.artifact },
490
- ...detail !== null && { detail: detail.structuredContent.artifact }
491
- };
492
- return {
493
- content: [
494
- {
495
- type: "text",
496
- text: textFor(structuredContent)
497
- },
498
- ...attachment === null ? [] : [attachment.image],
499
- ...detail?.content.filter((entry) => entry.type !== "text") ?? []
500
- ],
501
- structuredContent
502
- };
503
- },
504
- inline: (result) => inlineResult(result, commandName),
505
- failure: (error) => {
506
- const failure = withCommandInFailure(toFailurePayload(error instanceof z.ZodError ? validationError(error) : error, null), commandName);
507
- const structuredContent = {
508
- ok: false,
509
- error: failure.code === "UNAUTHORIZED" ? {
510
- ...failure,
511
- remediation: authenticationRemediation
512
- } : failure
513
- };
514
- return {
515
- content: [{
516
- type: "text",
517
- text: textFor(structuredContent)
518
- }],
519
- structuredContent,
520
- isError: true
521
- };
522
- }
523
- });
524
-
525
665
  //#endregion
526
666
  //#region src/infrastructure/mcp-server.adapter.ts
527
667
  const MAX_SEARCH_QUERY_CHARACTERS = 200;
@@ -539,15 +679,6 @@ const searchInputSchema = z.object({
539
679
  ]).default("any").describe("Filter dispatch, not effect. Omit if unknown; render uses mutation."),
540
680
  limit: z.number().int().min(1).max(MAX_SEARCH_RESULTS).default(DEFAULT_SEARCH_RESULTS).describe("Maximum contracts to return.")
541
681
  });
542
- const queryInputSchema = z.object({
543
- capability: z.string().min(1).describe("Exact query id from an available complete contract."),
544
- input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema.")
545
- });
546
- const mutationInputSchema = z.object({
547
- capability: z.string().min(1).describe("Exact mutation id from an available complete contract."),
548
- input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema."),
549
- clientToken: z.uuid().optional().describe("Stable UUID reused only when retrying this exact mutation input.")
550
- });
551
682
  const capabilityFor = (catalog, id, operation) => {
552
683
  const capability = catalog.find((candidate) => candidate.id === id);
553
684
  if (capability === void 0) throw new CliError("BAD_REQUEST", `Unknown shared capability: ${id}.`, "Call capability_search or capability_catalogue and use an exact id from its results.", { capability: "No shared capability has this id." });
@@ -585,7 +716,7 @@ const registerQuery = (server, catalog, invocation, execution) => {
585
716
  server.registerTool("capability_query", {
586
717
  title: "Run a discovered Enhance query",
587
718
  description: "Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.",
588
- inputSchema: queryInputSchema,
719
+ inputSchema: mcpQueryInputSchema,
589
720
  outputSchema: mcpDispatchedResultSchema,
590
721
  annotations: {
591
722
  readOnlyHint: true,
@@ -613,7 +744,7 @@ const registerMutation = (server, catalog, invocation, execution) => {
613
744
  server.registerTool("capability_mutate", {
614
745
  title: "Run a discovered Enhance mutation",
615
746
  description: "Run one state-changing capability using an available complete contract. Respect its preconditions and reuse clientToken only when retrying the identical mutation.",
616
- inputSchema: mutationInputSchema,
747
+ inputSchema: mcpMutationInputSchema,
617
748
  outputSchema: mcpDispatchedResultSchema,
618
749
  annotations: {
619
750
  readOnlyHint: false,
@@ -638,6 +769,9 @@ const registerMutation = (server, catalog, invocation, execution) => {
638
769
  });
639
770
  };
640
771
  const createMcpServerAdapter = (input) => {
772
+ const authenticationInstructions = input.exposures?.includes("mcp-transport") === true ? AUTHENTICATION_INSTRUCTIONS : void 0;
773
+ const workflows = input.workflowsDirectory === void 0 ? void 0 : createMcpWorkflowsAdapter(input.workflowsDirectory, authenticationInstructions);
774
+ const instructions = workflows?.instructions ?? authenticationInstructions;
641
775
  const server = new McpServer({
642
776
  name: input.name ?? "enhance-mcp",
643
777
  version: input.version
@@ -646,7 +780,7 @@ const createMcpServerAdapter = (input) => {
646
780
  tools: { listChanged: false },
647
781
  resources: { listChanged: true }
648
782
  },
649
- ...input.exposures?.includes("mcp-transport") === true && { instructions: AUTHENTICATION_INSTRUCTIONS }
783
+ ...instructions !== void 0 && { instructions }
650
784
  });
651
785
  const catalog = toPresentedCapabilities(input.catalog ?? createCapabilityCatalogAdapter(), input.exposures ?? ["shared"]);
652
786
  const discovery = createMcpCapabilityDiscoveryAdapter(catalog);
@@ -666,8 +800,9 @@ const createMcpServerAdapter = (input) => {
666
800
  invocation: input.invocation,
667
801
  ...execution
668
802
  }).register(server);
803
+ workflows?.register(server);
669
804
  return server;
670
805
  };
671
806
 
672
807
  //#endregion
673
- export { createMcpServerAdapter as t };
808
+ export { createMcpResultAdapter as i, createMcpWorkflowsAdapter as n, mcpDispatchedResultSchema as r, createMcpServerAdapter as t };