@enhance-eng/enhance 0.1.22 → 0.1.33

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,382 @@
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 { $n as canvasRenderTargetSchema, Et as canvasReferenceRenderTarget, Fn as agentClientMetadata, Gn as getCanvasDocumentOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Ot as hasCanvasReferenceScope, Q as canvasRenderBatchResultSchema, St as canvasEditCapabilityInputSchema, Zn as canvasRenderSourceStateSchema, ar as canvasReadableSceneDocumentSchema, c as toPresentedCapabilities, f as createCapabilityCatalogAdapter, jt as CliError, kt as parseCanvasReference, n as withCommandName, o as toMcpFailurePayload, r as toCanvasAuthoringResult, rt as canvasRenderFileSchema, t as withCommandInFailure, u as createMcpCapabilityDiscoveryAdapter } from "./cli-output-identity.lib-CWNAXho4.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
- import { McpServer } from "@modelcontextprotocol/server";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
9
+ import { CLIENT_INFO_META_KEY, McpServer } from "@modelcontextprotocol/server";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
7
11
 
12
+ //#region src/infrastructure/mcp-client-context.adapter.ts
13
+ const requests = new AsyncLocalStorage();
14
+ const initializeSchema = z.object({
15
+ method: z.literal("initialize"),
16
+ params: z.object({ clientInfo: z.object({
17
+ name: z.string(),
18
+ version: z.string()
19
+ }) })
20
+ });
21
+ const envelopeSchema = z.object({ [CLIENT_INFO_META_KEY]: z.object({
22
+ name: z.string(),
23
+ version: z.string()
24
+ }).optional() });
25
+ const currentMcpClientMetadata = () => requests.getStore();
26
+ const withMcpClientContext = (context, action) => {
27
+ const envelope = envelopeSchema.safeParse(context.mcpReq.envelope);
28
+ const client = envelope.success ? envelope.data[CLIENT_INFO_META_KEY] : void 0;
29
+ const metadata = context.mcpReq.envelope === void 0 ? void 0 : agentClientMetadata({
30
+ path: "local_mcp",
31
+ ...client !== void 0 && {
32
+ name: client.name,
33
+ version: client.version
34
+ }
35
+ });
36
+ return requests.run(metadata, action);
37
+ };
38
+ const createMcpStdioClientAdapter = (offered) => {
39
+ const native = offered ?? new StdioServerTransport();
40
+ const state = {
41
+ metadata: agentClientMetadata({ path: "local_mcp" }),
42
+ isInitialized: false
43
+ };
44
+ const onmessage = (message, extra) => {
45
+ const initialized = initializeSchema.safeParse(message);
46
+ if (!state.isInitialized && initialized.success) {
47
+ state.metadata = agentClientMetadata({
48
+ path: "local_mcp",
49
+ ...initialized.data.params.clientInfo
50
+ });
51
+ state.isInitialized = true;
52
+ }
53
+ transport.onmessage?.(message, extra);
54
+ };
55
+ const transport = {
56
+ start: async () => {
57
+ Object.assign(native, {
58
+ onmessage,
59
+ onclose: () => transport.onclose?.(),
60
+ onerror: (error) => transport.onerror?.(error)
61
+ });
62
+ await native.start();
63
+ },
64
+ send: async (message, options) => native.send(message, options),
65
+ close: async () => native.close()
66
+ };
67
+ return {
68
+ transport,
69
+ metadata: () => state.metadata
70
+ };
71
+ };
72
+ const createMcpClientContextAdapter = () => ({
73
+ current: currentMcpClientMetadata,
74
+ run: withMcpClientContext,
75
+ createStdio: createMcpStdioClientAdapter
76
+ });
77
+
78
+ //#endregion
79
+ //#region src/infrastructure/mcp-render-attachment.adapter.ts
80
+ const createMcpRenderAttachmentAdapter = async (server, result, delivery) => {
81
+ const body = await readFile(result.path);
82
+ const id = randomUUID();
83
+ const uri = `enhance://artifact/${id}`;
84
+ if (delivery === "embedded" && result.cleanup === "unlink-after-use") try {
85
+ await rm(result.path, { force: true });
86
+ } catch {}
87
+ if (delivery === "linked") server.registerResource(`artifact-${id}`, uri, {
88
+ title: "Enhance artifact",
89
+ mimeType: result.contentType
90
+ }, (requested) => ({ contents: [{
91
+ uri: requested.href,
92
+ mimeType: result.contentType,
93
+ blob: body.toString("base64")
94
+ }] }));
95
+ return {
96
+ metadata: canvasRenderFileSchema.omit({
97
+ path: true,
98
+ sensitive: true,
99
+ cleanup: true,
100
+ deleteAfter: true
101
+ }).parse(result),
102
+ artifact: {
103
+ uri,
104
+ mimeType: result.contentType,
105
+ bytes: body.byteLength
106
+ },
107
+ image: {
108
+ type: "image",
109
+ data: body.toString("base64"),
110
+ mimeType: result.contentType
111
+ }
112
+ };
113
+ };
114
+
115
+ //#endregion
116
+ //#region src/infrastructure/mcp-render-batch-result.adapter.ts
117
+ const createMcpRenderBatchResultAdapter = async (server, presented, delivery) => {
118
+ const parsed = canvasRenderBatchResultSchema.safeParse(presented);
119
+ if (!parsed.success) return null;
120
+ const attachments = [];
121
+ let isComplete = parsed.data.complete;
122
+ const results = [];
123
+ for (const target of parsed.data.results) {
124
+ const render = canvasRenderFileSchema.safeParse(target.outcome);
125
+ if (!render.success) {
126
+ results.push({
127
+ ...target,
128
+ pixelsDelivered: false
129
+ });
130
+ continue;
131
+ }
132
+ try {
133
+ const attachment = await createMcpRenderAttachmentAdapter(server, render.data, delivery);
134
+ attachments.push(attachment);
135
+ results.push({
136
+ ...target,
137
+ outcome: attachment.metadata,
138
+ pixelsDelivered: true,
139
+ contentIndex: attachments.length,
140
+ artifact: attachment.artifact
141
+ });
142
+ } catch {
143
+ isComplete = false;
144
+ results.push({
145
+ id: target.id,
146
+ target: target.target,
147
+ maxOutputPixels: target.maxOutputPixels,
148
+ pixelsDelivered: false,
149
+ outcome: {
150
+ state: "delivery_unavailable",
151
+ operation: {
152
+ kind: "canvas-render",
153
+ canvasId: render.data.canvasId,
154
+ jobId: render.data.jobId
155
+ },
156
+ requestedVersion: render.data.requestedVersion,
157
+ loadedVersion: render.data.loadedVersion,
158
+ next: ["Read operation_status with includeImage true to collect the existing render."]
159
+ }
160
+ });
161
+ }
162
+ }
163
+ return {
164
+ value: {
165
+ ...parsed.data,
166
+ complete: isComplete,
167
+ results
168
+ },
169
+ detail: null,
170
+ attachments
171
+ };
172
+ };
173
+
174
+ //#endregion
175
+ //#region src/infrastructure/mcp-result.adapter.ts
176
+ const PROTECTED_RESULT_BYTES = 2e4;
177
+ const SENSITIVE_FIELD = /(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu;
178
+ const SIGNED_URL = /[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu;
179
+ const textFor = (value) => JSON.stringify(value);
180
+ const hasProtectedMaterial = (value, key = "") => {
181
+ if (typeof value === "string") return SIGNED_URL.test(value) || SENSITIVE_FIELD.test(key) && !key.endsWith("Id");
182
+ if (Array.isArray(value)) return value.some((entry) => hasProtectedMaterial(entry, key));
183
+ if (typeof value !== "object" || value === null) return false;
184
+ if (Reflect.get(value, "sensitive") === true) return true;
185
+ return Object.entries(value).some(([childKey, child]) => hasProtectedMaterial(child, childKey));
186
+ };
187
+ const artifactResult = (server, serialized, delivery) => {
188
+ const id = randomUUID();
189
+ const uri = `enhance://result/${id}`;
190
+ const bytes = Buffer.byteLength(serialized);
191
+ if (delivery === "embedded") {
192
+ const structuredContent = {
193
+ ok: true,
194
+ artifact: {
195
+ uri,
196
+ mimeType: "application/json",
197
+ bytes
198
+ }
199
+ };
200
+ return {
201
+ content: [{
202
+ type: "text",
203
+ text: textFor(structuredContent)
204
+ }, {
205
+ type: "resource",
206
+ resource: {
207
+ uri,
208
+ mimeType: "application/json",
209
+ text: serialized
210
+ }
211
+ }],
212
+ structuredContent
213
+ };
214
+ }
215
+ server.registerResource(`result-${id}`, uri, {
216
+ title: "Protected Enhance result",
217
+ mimeType: "application/json"
218
+ }, (requested) => ({ contents: [{
219
+ uri: requested.href,
220
+ mimeType: "application/json",
221
+ text: serialized
222
+ }] }));
223
+ const structuredContent = {
224
+ ok: true,
225
+ artifact: {
226
+ uri,
227
+ mimeType: "application/json",
228
+ bytes
229
+ }
230
+ };
231
+ return {
232
+ content: [{
233
+ type: "text",
234
+ text: textFor(structuredContent)
235
+ }, {
236
+ type: "resource_link",
237
+ name: "Protected Enhance result",
238
+ uri,
239
+ mimeType: "application/json"
240
+ }],
241
+ structuredContent
242
+ };
243
+ };
244
+ 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])));
245
+ const prepareCanvasResult = async (server, presented, delivery) => {
246
+ const batch = await createMcpRenderBatchResultAdapter(server, presented, delivery);
247
+ if (batch !== null) return batch;
248
+ const render = canvasRenderFileSchema.safeParse(presented);
249
+ if (render.success) {
250
+ const attachment = await createMcpRenderAttachmentAdapter(server, render.data, delivery);
251
+ return {
252
+ value: attachment.metadata,
253
+ detail: null,
254
+ attachments: [attachment]
255
+ };
256
+ }
257
+ const originalAuthoring = toCanvasAuthoringResult(presented);
258
+ if (originalAuthoring === null) return {
259
+ value: presented,
260
+ detail: null,
261
+ attachments: []
262
+ };
263
+ const original = originalAuthoring.detail ?? originalAuthoring.value;
264
+ const review = canvasRenderFileSchema.safeParse(original["review"]);
265
+ if (!review.success) return {
266
+ ...originalAuthoring,
267
+ attachments: []
268
+ };
269
+ try {
270
+ const attachment = await createMcpRenderAttachmentAdapter(server, review.data, delivery);
271
+ const safeResult = {
272
+ ...original,
273
+ review: {
274
+ ...attachment.metadata,
275
+ artifact: attachment.artifact
276
+ }
277
+ };
278
+ const authoring = toCanvasAuthoringResult(safeResult);
279
+ return {
280
+ value: authoring?.value ?? safeResult,
281
+ detail: authoring?.detail ?? null,
282
+ attachments: [attachment]
283
+ };
284
+ } catch {
285
+ const safeResult = {
286
+ ...original,
287
+ review: {
288
+ state: "unavailable",
289
+ mutationCommitted: true,
290
+ requestedVersion: original["version"],
291
+ retry: {
292
+ tool: "canvas_render",
293
+ arguments: {
294
+ canvas: original["canvasId"],
295
+ expectedVersion: original["version"],
296
+ target: review.data.target
297
+ }
298
+ }
299
+ },
300
+ next: ["Retry the render of the committed version; do not replay the write."]
301
+ };
302
+ const authoring = toCanvasAuthoringResult(safeResult);
303
+ return {
304
+ value: authoring?.value ?? safeResult,
305
+ detail: authoring?.detail ?? null,
306
+ attachments: []
307
+ };
308
+ }
309
+ };
310
+ const inlineResult = (result, commandName) => {
311
+ const structuredContent = {
312
+ ok: true,
313
+ result: withCommandName(result, commandName)
314
+ };
315
+ return {
316
+ content: [{
317
+ type: "text",
318
+ text: textFor(structuredContent)
319
+ }],
320
+ structuredContent
321
+ };
322
+ };
323
+ const createMcpResultAdapter = (authenticationRemediation, commandName = "enhance") => ({
324
+ success: async (server, result, delivery) => {
325
+ const presented = withCommandName(result, commandName);
326
+ const prepared = await prepareCanvasResult(server, presented, delivery);
327
+ const attachments = prepared.attachments;
328
+ const attachment = attachments.length === 1 ? attachments[0] : void 0;
329
+ const serialized = textFor(prepared.value);
330
+ if (hasProtectedMaterial(prepared.value)) return artifactResult(server, serialized, delivery);
331
+ if (attachments.length === 0 && prepared.detail === null && Buffer.byteLength(serialized) > PROTECTED_RESULT_BYTES) return artifactResult(server, serialized, delivery);
332
+ const detail = prepared.detail === null ? null : artifactResult(server, textFor(prepared.detail), delivery);
333
+ const structuredContent = {
334
+ ok: true,
335
+ result: prepared.value,
336
+ ...attachment !== void 0 && { artifact: attachment.artifact },
337
+ ...detail !== null && { detail: detail.structuredContent.artifact }
338
+ };
339
+ return {
340
+ content: [
341
+ {
342
+ type: "text",
343
+ text: textFor(structuredContent)
344
+ },
345
+ ...attachments.map((entry) => entry.image),
346
+ ...detail?.content.filter((entry) => entry.type !== "text") ?? []
347
+ ],
348
+ structuredContent
349
+ };
350
+ },
351
+ inline: (result) => inlineResult(result, commandName),
352
+ structured: (result) => ({
353
+ structuredContent: result,
354
+ content: [{
355
+ type: "text",
356
+ text: textFor(result)
357
+ }]
358
+ }),
359
+ failure: (error) => {
360
+ const failure = withCommandInFailure(toMcpFailurePayload(error instanceof z.ZodError ? validationError(error) : error), commandName);
361
+ const structuredContent = {
362
+ ok: false,
363
+ error: failure.code === "UNAUTHORIZED" ? {
364
+ ...failure,
365
+ remediation: authenticationRemediation
366
+ } : failure
367
+ };
368
+ return {
369
+ content: [{
370
+ type: "text",
371
+ text: textFor(structuredContent)
372
+ }],
373
+ structuredContent,
374
+ isError: true
375
+ };
376
+ }
377
+ });
378
+
379
+ //#endregion
8
380
  //#region src/infrastructure/mcp-progressive.schema.ts
9
381
  const failureSchema = z.object({
10
382
  ok: z.literal(false),
@@ -89,11 +461,83 @@ const mcpDescribeResultSchema = z.union([z.object({
89
461
  ok: z.literal(true),
90
462
  result: capabilityContractSchema
91
463
  }), failureSchema]);
464
+ const mcpQueryInputSchema = z.object({
465
+ capability: z.string().min(1).describe("Exact query id from an available complete contract."),
466
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema.")
467
+ });
468
+ const mcpMutationInputSchema = z.object({
469
+ capability: z.string().min(1).describe("Exact mutation id from an available complete contract."),
470
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema."),
471
+ clientToken: z.uuid().optional().describe("Stable UUID reused only when retrying this exact mutation input.")
472
+ });
473
+
474
+ //#endregion
475
+ //#region src/infrastructure/mcp-client-invocation.adapter.ts
476
+ const clientContext$2 = createMcpClientContextAdapter();
477
+ const createMcpClientInvocationAdapter = (invocation, legacyClient) => ({ invoke: async (request) => {
478
+ return invocation.invoke({
479
+ ...request,
480
+ clientMetadata: clientContext$2.current() ?? legacyClient?.() ?? agentClientMetadata({ path: "local_mcp" })
481
+ });
482
+ } });
483
+
484
+ //#endregion
485
+ //#region src/infrastructure/mcp-workflows.adapter.ts
486
+ const workflowNameSchema = z.enum([
487
+ "apply-canvas-design",
488
+ "design-on-canvas",
489
+ "publish-prototype",
490
+ "respond-to-feedback"
491
+ ]);
492
+ const workflowSchema = z.object({
493
+ name: workflowNameSchema,
494
+ description: z.string().min(1),
495
+ body: z.string().min(1)
496
+ });
497
+ 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.";
498
+ const createMcpWorkflowsAdapter = (directory, authenticationInstructions) => {
499
+ const workflows = workflowNameSchema.options.map((name) => {
500
+ const source = readFileSync(path.join(directory, name, "SKILL.md"), "utf8");
501
+ const match = /^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n---\r?\n([\s\S]+)$/u.exec(source);
502
+ const workflow = workflowSchema.parse({
503
+ name: match?.[1],
504
+ description: match?.[2],
505
+ body: match?.[3]
506
+ });
507
+ if (workflow.name !== name) throw new Error(`Workflow name does not match its folder: ${name}`);
508
+ return workflow;
509
+ });
510
+ return {
511
+ instructions: [instructions, authenticationInstructions].filter(Boolean).join(" "),
512
+ register: (server) => {
513
+ for (const workflow of workflows) server.registerPrompt(workflow.name, { description: workflow.description }, () => ({ messages: [{
514
+ role: "user",
515
+ content: {
516
+ type: "text",
517
+ text: workflow.body
518
+ }
519
+ }] }));
520
+ server.registerTool("workflow_guide", {
521
+ title: "Load an Enhance workflow",
522
+ description: instructions,
523
+ inputSchema: z.strictObject({ workflow: workflowNameSchema }),
524
+ annotations: {
525
+ readOnlyHint: true,
526
+ destructiveHint: false,
527
+ idempotentHint: true,
528
+ openWorldHint: false
529
+ }
530
+ }, ({ workflow: name }) => ({ content: workflows.filter((workflow) => workflow.name === name).map((workflow) => ({
531
+ type: "text",
532
+ text: workflow.body
533
+ })) }));
534
+ }
535
+ };
536
+ };
92
537
 
93
538
  //#endregion
94
539
  //#region src/infrastructure/mcp-canvas-tools.adapter.ts
95
- const MIN_RENDER_SCALE = .1;
96
- const MAX_RENDER_SCALE = 4;
540
+ const clientContext$1 = createMcpClientContextAdapter();
97
541
  const clientToken = z.uuid().optional().describe("Reuse only when retrying this exact mutation.");
98
542
  const writeSchema = canvasWriteHtmlCapabilityInputSchema.pick({
99
543
  baseVersion: true,
@@ -101,17 +545,18 @@ const writeSchema = canvasWriteHtmlCapabilityInputSchema.pick({
101
545
  html: true,
102
546
  idPrefix: true
103
547
  }).extend({
104
- canvas: z.string().min(1).describe("Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL."),
548
+ canvas: z.string().min(1).describe("Canvas UUID or complete canvas/page/selection URL. Preserve every supplied page and selection."),
105
549
  mode: z.enum(["insert-children", "replace"]).default("insert-children"),
106
550
  clientToken
107
551
  });
108
552
  const editSchema = canvasEditCapabilityInputSchema.extend({ clientToken });
109
553
  const renderSchema = z.object({
554
+ clientToken,
110
555
  canvas: z.string().min(1),
111
556
  expectedVersion: z.number().int().positive().describe("Version returned by the latest successful read or write."),
112
557
  target: canvasRenderTargetSchema.default({ kind: "content" }),
113
558
  sourceState: canvasRenderSourceStateSchema.nullable().default(null),
114
- scale: z.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE).default(1)
559
+ scale: z.number().positive().default(1)
115
560
  });
116
561
  const invoke = async (input, id, args, token = null) => {
117
562
  const capability = input.catalog.find((candidate) => candidate.id === id);
@@ -123,22 +568,18 @@ const invoke = async (input, id, args, token = null) => {
123
568
  });
124
569
  };
125
570
  const renderTarget = async (input, args) => {
126
- const reference = parseCanvasReference(args.canvas);
127
- if (reference.nodeIds.length === 0) return {
571
+ const requested = parseCanvasReference(args.canvas);
572
+ const reference = input.scope ?? requested;
573
+ if (reference.canvasId !== requested.canvasId) throw new CliError("FORBIDDEN", "This turn cannot render another canvas.", "Render the submitted canvas and selection.");
574
+ if (!hasCanvasReferenceScope(reference)) return {
128
575
  canvasId: reference.canvasId,
129
576
  target: args.target
130
577
  };
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
578
  const held = getCanvasDocumentOutputSchema.parse(await invoke(input, "canvas.document.get", { canvasId: reference.canvasId }));
134
579
  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
580
  return {
137
581
  canvasId: reference.canvasId,
138
- target: {
139
- kind: "node",
140
- nodeId
141
- }
582
+ target: canvasReferenceRenderTarget(reference, canvasReadableSceneDocumentSchema.parse(held.document), args.target)
142
583
  };
143
584
  };
144
585
  const deliver = async (server, input, action) => {
@@ -151,7 +592,7 @@ const deliver = async (server, input, action) => {
151
592
  const registerWrite = (server, input) => {
152
593
  if (input.catalog.some((capability) => capability.id === "canvas.writeHtml")) server.registerTool("canvas_write_html", {
153
594
  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.",
595
+ 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
596
  inputSchema: writeSchema,
156
597
  outputSchema: mcpDispatchedResultSchema,
157
598
  annotations: {
@@ -160,11 +601,12 @@ const registerWrite = (server, input) => {
160
601
  idempotentHint: false,
161
602
  openWorldHint: false
162
603
  }
163
- }, async ({ canvas, clientToken: token, ...args }) => deliver(server, input, async () => {
604
+ }, async ({ canvas, clientToken: token, ...args }, context) => clientContext$1.run(context, async () => deliver(server, input, async () => {
164
605
  const reference = parseCanvasReference(canvas);
165
606
  return invoke(input, "canvas.writeHtml", {
166
607
  ...args,
167
608
  canvasId: reference.canvasId,
609
+ ...reference.pageId !== void 0 && { pageId: reference.pageId },
168
610
  ...reference.nodeIds.length > 0 && { selectionNodeIds: reference.nodeIds },
169
611
  review: "none",
170
612
  renderOutputPath: null,
@@ -172,7 +614,7 @@ const registerWrite = (server, input) => {
172
614
  renderScale: 1,
173
615
  renderTimeoutMs: 12e4
174
616
  }, token ?? null);
175
- }));
617
+ })));
176
618
  };
177
619
  const registerEdit = (server, input) => {
178
620
  if (input.catalog.some((capability) => capability.id === "canvas.edit")) server.registerTool("canvas_edit", {
@@ -186,7 +628,7 @@ const registerEdit = (server, input) => {
186
628
  idempotentHint: false,
187
629
  openWorldHint: false
188
630
  }
189
- }, async ({ clientToken: token, ...args }) => deliver(server, input, async () => invoke(input, "canvas.edit", args, token ?? null)));
631
+ }, async ({ clientToken: token, ...args }, context) => clientContext$1.run(context, async () => deliver(server, input, async () => invoke(input, "canvas.edit", args, token ?? null))));
190
632
  };
191
633
  const registerRender = (server, input) => {
192
634
  if (input.catalog.some((capability) => capability.id === "canvas.render")) server.registerTool("canvas_render", {
@@ -195,12 +637,12 @@ const registerRender = (server, input) => {
195
637
  inputSchema: renderSchema,
196
638
  outputSchema: mcpDispatchedResultSchema,
197
639
  annotations: {
198
- readOnlyHint: true,
640
+ readOnlyHint: false,
199
641
  destructiveHint: false,
200
- idempotentHint: true,
642
+ idempotentHint: false,
201
643
  openWorldHint: false
202
644
  }
203
- }, async (args) => deliver(server, input, async () => invoke(input, "canvas.render", {
645
+ }, async (args, context) => clientContext$1.run(context, async () => deliver(server, input, async () => invoke(input, "canvas.render", {
204
646
  ...await renderTarget(input, args),
205
647
  expectedVersion: args.expectedVersion,
206
648
  sourceState: args.sourceState,
@@ -208,12 +650,17 @@ const registerRender = (server, input) => {
208
650
  outputPath: null,
209
651
  overwrite: false,
210
652
  timeoutMs: 12e4
211
- })));
653
+ }, args.clientToken ?? null))));
212
654
  };
213
655
  const createMcpCanvasToolsAdapter = (input) => ({ register: (server) => {
214
- registerWrite(server, input);
215
- registerEdit(server, input);
216
- registerRender(server, input);
656
+ const selected = input.tools ?? [
657
+ "write",
658
+ "edit",
659
+ "render"
660
+ ];
661
+ if (selected.includes("write")) registerWrite(server, input);
662
+ if (selected.includes("edit")) registerEdit(server, input);
663
+ if (selected.includes("render")) registerRender(server, input);
217
664
  } });
218
665
 
219
666
  //#endregion
@@ -293,237 +740,15 @@ const createMcpDescribeToolAdapter = (discovery, mcpResults) => ({ register: (se
293
740
  });
294
741
  } });
295
742
 
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
743
  //#endregion
526
744
  //#region src/infrastructure/mcp-server.adapter.ts
745
+ const clientContext = createMcpClientContextAdapter();
746
+ const QUERY_ANNOTATIONS = {
747
+ readOnlyHint: true,
748
+ destructiveHint: false,
749
+ idempotentHint: true,
750
+ openWorldHint: false
751
+ };
527
752
  const MAX_SEARCH_QUERY_CHARACTERS = 200;
528
753
  const MAX_SEARCH_RESULTS = 10;
529
754
  const DEFAULT_SEARCH_RESULTS = 5;
@@ -539,15 +764,6 @@ const searchInputSchema = z.object({
539
764
  ]).default("any").describe("Filter dispatch, not effect. Omit if unknown; render uses mutation."),
540
765
  limit: z.number().int().min(1).max(MAX_SEARCH_RESULTS).default(DEFAULT_SEARCH_RESULTS).describe("Maximum contracts to return.")
541
766
  });
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
767
  const capabilityFor = (catalog, id, operation) => {
552
768
  const capability = catalog.find((candidate) => candidate.id === id);
553
769
  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." });
@@ -563,41 +779,31 @@ const registerSearch = (server, catalog, discovery, mcpResults) => {
563
779
  description: "Search the Enhance capability catalogue for a specific likely action. Returns relevant summaries and a complete bestContract when it fits. Invoke from that contract directly; call capability_describe only when detailRequired is returned or a different match is needed.",
564
780
  inputSchema: searchInputSchema,
565
781
  outputSchema: mcpSearchResultSchema,
566
- annotations: {
567
- readOnlyHint: true,
568
- destructiveHint: false,
569
- idempotentHint: true,
570
- openWorldHint: false
571
- },
782
+ annotations: QUERY_ANNOTATIONS,
572
783
  _meta: {
573
784
  "ai.enhancelabs/disclosure": "progressive",
574
785
  "ai.enhancelabs/catalogSize": catalog.length,
575
786
  "enhance/disclosure": "progressive",
576
787
  "enhance/catalogSize": catalog.length
577
788
  }
578
- }, async ({ query, operation, limit }) => mcpResults.inline(discovery.search({
789
+ }, async ({ query, operation, limit }, context) => clientContext.run(context, async () => mcpResults.inline(discovery.search({
579
790
  query,
580
791
  operation,
581
792
  limit
582
- })));
793
+ }))));
583
794
  };
584
795
  const registerQuery = (server, catalog, invocation, execution) => {
585
796
  server.registerTool("capability_query", {
586
797
  title: "Run a discovered Enhance query",
587
798
  description: "Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.",
588
- inputSchema: queryInputSchema,
799
+ inputSchema: mcpQueryInputSchema,
589
800
  outputSchema: mcpDispatchedResultSchema,
590
- annotations: {
591
- readOnlyHint: true,
592
- destructiveHint: false,
593
- idempotentHint: true,
594
- openWorldHint: false
595
- },
801
+ annotations: QUERY_ANNOTATIONS,
596
802
  _meta: {
597
803
  "ai.enhancelabs/disclosure": "progressive",
598
804
  "enhance/disclosure": "progressive"
599
805
  }
600
- }, async ({ capability: id, input }) => {
806
+ }, async ({ capability: id, input }, context) => clientContext.run(context, async () => {
601
807
  try {
602
808
  return await execution.results.success(server, await invocation.invoke({
603
809
  capability: capabilityFor(catalog, id, "query"),
@@ -607,13 +813,13 @@ const registerQuery = (server, catalog, invocation, execution) => {
607
813
  } catch (error) {
608
814
  return execution.results.failure(error);
609
815
  }
610
- });
816
+ }));
611
817
  };
612
818
  const registerMutation = (server, catalog, invocation, execution) => {
613
819
  server.registerTool("capability_mutate", {
614
820
  title: "Run a discovered Enhance mutation",
615
821
  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,
822
+ inputSchema: mcpMutationInputSchema,
617
823
  outputSchema: mcpDispatchedResultSchema,
618
824
  annotations: {
619
825
  readOnlyHint: false,
@@ -625,7 +831,7 @@ const registerMutation = (server, catalog, invocation, execution) => {
625
831
  "ai.enhancelabs/disclosure": "progressive",
626
832
  "enhance/disclosure": "progressive"
627
833
  }
628
- }, async ({ capability: id, input, clientToken }) => {
834
+ }, async ({ capability: id, input, clientToken }, context) => clientContext.run(context, async () => {
629
835
  try {
630
836
  return await execution.results.success(server, await invocation.invoke({
631
837
  capability: capabilityFor(catalog, id, "mutation"),
@@ -635,9 +841,12 @@ const registerMutation = (server, catalog, invocation, execution) => {
635
841
  } catch (error) {
636
842
  return execution.results.failure(error);
637
843
  }
638
- });
844
+ }));
639
845
  };
640
846
  const createMcpServerAdapter = (input) => {
847
+ const authenticationInstructions = input.exposures?.includes("mcp-transport") === true ? AUTHENTICATION_INSTRUCTIONS : void 0;
848
+ const workflows = input.workflowsDirectory === void 0 ? void 0 : createMcpWorkflowsAdapter(input.workflowsDirectory, authenticationInstructions);
849
+ const instructions = workflows?.instructions ?? authenticationInstructions;
641
850
  const server = new McpServer({
642
851
  name: input.name ?? "enhance-mcp",
643
852
  version: input.version
@@ -646,28 +855,28 @@ const createMcpServerAdapter = (input) => {
646
855
  tools: { listChanged: false },
647
856
  resources: { listChanged: true }
648
857
  },
649
- ...input.exposures?.includes("mcp-transport") === true && { instructions: AUTHENTICATION_INSTRUCTIONS }
858
+ ...instructions !== void 0 && { instructions }
650
859
  });
651
860
  const catalog = toPresentedCapabilities(input.catalog ?? createCapabilityCatalogAdapter(), input.exposures ?? ["shared"]);
652
861
  const discovery = createMcpCapabilityDiscoveryAdapter(catalog);
653
- const delivery = input.delivery ?? "linked";
654
862
  const mcpResults = createMcpResultAdapter(input.exposures?.includes("mcp-transport") === true ? LOCAL_AUTHENTICATION_REMEDY : HOSTED_AUTHENTICATION_REMEDY, input.commandName);
655
863
  createMcpCatalogueToolAdapter(catalog, input.version, input.commandName).register(server);
656
864
  registerSearch(server, catalog, discovery, mcpResults);
657
865
  createMcpDescribeToolAdapter(discovery, mcpResults).register(server);
658
866
  const execution = {
659
- delivery,
660
- results: mcpResults
867
+ delivery: input.delivery ?? "linked",
868
+ results: mcpResults,
869
+ invocation: createMcpClientInvocationAdapter(input.invocation, input.clientMetadata)
661
870
  };
662
- registerQuery(server, catalog, input.invocation, execution);
663
- registerMutation(server, catalog, input.invocation, execution);
871
+ registerQuery(server, catalog, execution.invocation, execution);
872
+ registerMutation(server, catalog, execution.invocation, execution);
664
873
  createMcpCanvasToolsAdapter({
665
874
  catalog,
666
- invocation: input.invocation,
667
875
  ...execution
668
876
  }).register(server);
877
+ workflows?.register(server);
669
878
  return server;
670
879
  };
671
880
 
672
881
  //#endregion
673
- export { createMcpServerAdapter as t };
882
+ export { createMcpResultAdapter as a, mcpDispatchedResultSchema as i, createMcpWorkflowsAdapter as n, createMcpClientContextAdapter as o, createMcpClientInvocationAdapter as r, createMcpServerAdapter as t };