@enhance-eng/enhance 0.1.5 → 0.1.7

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.
@@ -0,0 +1,492 @@
1
+ #!/usr/bin/env node
2
+ import { C as CliError, a as toPresentedCapabilities, i as toFailurePayload, l as createCapabilityCatalogAdapter, n as withCommandName, s as createMcpCapabilityDiscoveryAdapter, t as withCommandInFailure } from "./cli-output-identity.lib-BSUBcRJm.mjs";
3
+ import { z } from "zod";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { readFile, rm } from "node:fs/promises";
6
+ import { McpServer } from "@modelcontextprotocol/server";
7
+
8
+ //#region src/infrastructure/capability-catalogue-text.mapper.ts
9
+ const MAX_LINE_CHARACTERS = 180;
10
+ const MAX_CATALOGUE_BYTES = 24 * 1024;
11
+ const oneLine = (value) => value.replaceAll(/\s+/gu, " ").trim();
12
+ const lineFor = (capability) => {
13
+ const prefix = `${capability.id} [${capability.effect}] — `;
14
+ const summary = oneLine(capability.guide.summary);
15
+ const available = MAX_LINE_CHARACTERS - prefix.length;
16
+ return `${prefix}${summary.slice(0, available)}`;
17
+ };
18
+ const toCapabilityCatalogueText = (catalog, serverVersion) => {
19
+ const lines = catalog.toSorted((left, right) => left.id.localeCompare(right.id)).map((capability) => lineFor(capability));
20
+ const digest = createHash("sha256").update(lines.join("\n")).digest("hex");
21
+ const text = [`Enhance MCP ${serverVersion} — ${String(lines.length)} capabilities — sha256:${digest}`, ...lines].join("\n");
22
+ if (Buffer.byteLength(text) > MAX_CATALOGUE_BYTES) throw new RangeError("the complete capability catalogue exceeds 24 KiB");
23
+ return {
24
+ digest,
25
+ text
26
+ };
27
+ };
28
+
29
+ //#endregion
30
+ //#region src/infrastructure/mcp-catalogue-tool.adapter.ts
31
+ const createMcpCatalogueToolAdapter = (catalog, version, commandName = "enhance") => {
32
+ const catalogue = toCapabilityCatalogueText(catalog, version);
33
+ const presented = String(withCommandName(catalogue.text, commandName));
34
+ return { register: (server) => {
35
+ server.registerTool("capability_catalogue", {
36
+ title: "Scan every Enhance capability",
37
+ description: "Return the complete bounded capability inventory when the task is broad, uncertain, or capability_search does not find the right words. Call capability_describe with one exact id before invoking it.",
38
+ inputSchema: z.strictObject({}),
39
+ annotations: {
40
+ readOnlyHint: true,
41
+ destructiveHint: false,
42
+ idempotentHint: true,
43
+ openWorldHint: false
44
+ },
45
+ _meta: {
46
+ "ai.enhancelabs/disclosure": "progressive",
47
+ "ai.enhancelabs/catalogSize": catalog.length,
48
+ "enhance/disclosure": "progressive",
49
+ "enhance/catalogSize": catalog.length
50
+ }
51
+ }, () => ({ content: [{
52
+ type: "text",
53
+ text: presented
54
+ }] }));
55
+ } };
56
+ };
57
+
58
+ //#endregion
59
+ //#region src/infrastructure/mcp-progressive.schema.ts
60
+ const failureSchema = z.object({
61
+ ok: z.literal(false),
62
+ error: z.object({
63
+ code: z.string(),
64
+ message: z.string(),
65
+ remediation: z.string(),
66
+ fields: z.array(z.object({
67
+ path: z.string(),
68
+ message: z.string()
69
+ })).optional()
70
+ })
71
+ });
72
+ const artifactSchema = z.object({
73
+ ok: z.literal(true),
74
+ artifact: z.object({
75
+ uri: z.string(),
76
+ mimeType: z.string(),
77
+ bytes: z.number().int().nonnegative()
78
+ })
79
+ });
80
+ const capabilityContractSchema = z.object({
81
+ id: z.string(),
82
+ operation: z.enum(["query", "mutation"]),
83
+ effect: z.enum([
84
+ "read",
85
+ "write",
86
+ "delete",
87
+ "external"
88
+ ]),
89
+ idempotency: z.enum([
90
+ "none",
91
+ "single",
92
+ "composite"
93
+ ]),
94
+ summary: z.string(),
95
+ useWhen: z.string(),
96
+ preconditions: z.array(z.string()),
97
+ inputSchema: z.unknown(),
98
+ exampleInput: z.unknown(),
99
+ output: z.array(z.object({
100
+ name: z.string(),
101
+ required: z.boolean(),
102
+ meaning: z.string()
103
+ })),
104
+ result: z.string(),
105
+ recovery: z.array(z.string()),
106
+ next: z.array(z.string()),
107
+ schemaDigest: z.string(),
108
+ guidanceDigest: z.string(),
109
+ behaviorDigest: z.string()
110
+ });
111
+ const capabilityBriefSchema = capabilityContractSchema.pick({
112
+ id: true,
113
+ operation: true,
114
+ effect: true,
115
+ summary: true,
116
+ useWhen: true
117
+ });
118
+ const mcpDispatchedResultSchema = z.union([
119
+ z.object({
120
+ ok: z.literal(true),
121
+ result: z.unknown()
122
+ }),
123
+ artifactSchema,
124
+ failureSchema
125
+ ]);
126
+ const mcpSearchResultSchema = z.union([z.object({
127
+ ok: z.literal(true),
128
+ result: z.object({
129
+ matches: z.array(capabilityBriefSchema),
130
+ totalMatches: z.number().int().nonnegative(),
131
+ truncated: z.boolean()
132
+ })
133
+ }), failureSchema]);
134
+ const mcpDescribeResultSchema = z.union([z.object({
135
+ ok: z.literal(true),
136
+ result: capabilityContractSchema
137
+ }), failureSchema]);
138
+
139
+ //#endregion
140
+ //#region src/infrastructure/mcp-describe-tool.adapter.ts
141
+ const describeInputSchema = z.object({ capability: z.string().min(1).describe("Exact capability id returned by capability_search or capability_catalogue.") });
142
+ const createMcpDescribeToolAdapter = (discovery, mcpResults) => ({ register: (server) => {
143
+ server.registerTool("capability_describe", {
144
+ title: "Load one Enhance capability contract",
145
+ description: "Load the exact input schema, example, preconditions, result guidance, recovery, and next steps for one id returned by capability_search or capability_catalogue.",
146
+ inputSchema: describeInputSchema,
147
+ outputSchema: mcpDescribeResultSchema,
148
+ annotations: {
149
+ readOnlyHint: true,
150
+ destructiveHint: false,
151
+ idempotentHint: true,
152
+ openWorldHint: false
153
+ },
154
+ _meta: {
155
+ "ai.enhancelabs/disclosure": "progressive",
156
+ "enhance/disclosure": "progressive"
157
+ }
158
+ }, ({ capability }) => {
159
+ const contract = discovery.describe(capability);
160
+ if (contract !== null) return mcpResults.inline(contract);
161
+ return mcpResults.failure(new CliError("BAD_REQUEST", `Unknown shared capability: ${capability}.`, "Call capability_search or capability_catalogue and use an exact id from its results.", { capability: "No shared capability has this id." }));
162
+ });
163
+ } });
164
+
165
+ //#endregion
166
+ //#region src/infrastructure/mcp-result.adapter.ts
167
+ const PROTECTED_RESULT_BYTES = 2e4;
168
+ const SENSITIVE_FIELD = /(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu;
169
+ const SIGNED_URL = /[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu;
170
+ const textFor = (value) => JSON.stringify(value);
171
+ const hasProtectedMaterial = (value, key = "") => {
172
+ if (typeof value === "string") return SIGNED_URL.test(value) || SENSITIVE_FIELD.test(key) && !key.endsWith("Id");
173
+ if (Array.isArray(value)) return value.some((entry) => hasProtectedMaterial(entry, key));
174
+ if (typeof value !== "object" || value === null) return false;
175
+ if (Reflect.get(value, "sensitive") === true) return true;
176
+ return Object.entries(value).some(([childKey, child]) => hasProtectedMaterial(child, childKey));
177
+ };
178
+ const localArtifactResult = async (server, result, delivery) => {
179
+ if (typeof result !== "object" || result === null) return null;
180
+ const path = Reflect.get(result, "path");
181
+ if (typeof path !== "string") return null;
182
+ const mimeType = Reflect.get(result, "contentType");
183
+ if (typeof mimeType !== "string" || !mimeType.startsWith("image/")) return null;
184
+ if (Reflect.get(result, "sensitive") !== true) return null;
185
+ const body = await readFile(path);
186
+ const id = randomUUID();
187
+ const uri = `enhance://artifact/${id}`;
188
+ if (delivery === "embedded") {
189
+ await rm(path, { force: true });
190
+ const structuredContent = {
191
+ ok: true,
192
+ artifact: {
193
+ uri,
194
+ mimeType,
195
+ bytes: body.byteLength
196
+ }
197
+ };
198
+ return {
199
+ content: [{
200
+ type: "text",
201
+ text: textFor(structuredContent)
202
+ }, {
203
+ type: "image",
204
+ data: body.toString("base64"),
205
+ mimeType
206
+ }],
207
+ structuredContent
208
+ };
209
+ }
210
+ server.registerResource(`artifact-${id}`, uri, {
211
+ title: "Enhance artifact",
212
+ mimeType
213
+ }, (requested) => ({ contents: [{
214
+ uri: requested.href,
215
+ mimeType,
216
+ blob: body.toString("base64")
217
+ }] }));
218
+ const structuredContent = {
219
+ ok: true,
220
+ artifact: {
221
+ uri,
222
+ mimeType,
223
+ bytes: body.byteLength
224
+ }
225
+ };
226
+ return {
227
+ content: [{
228
+ type: "text",
229
+ text: textFor(structuredContent)
230
+ }, {
231
+ type: "resource_link",
232
+ name: "Enhance artifact",
233
+ uri,
234
+ mimeType
235
+ }],
236
+ structuredContent
237
+ };
238
+ };
239
+ const artifactResult = (server, serialized, delivery) => {
240
+ const id = randomUUID();
241
+ const uri = `enhance://result/${id}`;
242
+ const bytes = Buffer.byteLength(serialized);
243
+ if (delivery === "embedded") {
244
+ const structuredContent = {
245
+ ok: true,
246
+ artifact: {
247
+ uri,
248
+ mimeType: "application/json",
249
+ bytes
250
+ }
251
+ };
252
+ return {
253
+ content: [{
254
+ type: "text",
255
+ text: textFor(structuredContent)
256
+ }, {
257
+ type: "resource",
258
+ resource: {
259
+ uri,
260
+ mimeType: "application/json",
261
+ text: serialized
262
+ }
263
+ }],
264
+ structuredContent
265
+ };
266
+ }
267
+ server.registerResource(`result-${id}`, uri, {
268
+ title: "Protected Enhance result",
269
+ mimeType: "application/json"
270
+ }, (requested) => ({ contents: [{
271
+ uri: requested.href,
272
+ mimeType: "application/json",
273
+ text: serialized
274
+ }] }));
275
+ const structuredContent = {
276
+ ok: true,
277
+ artifact: {
278
+ uri,
279
+ mimeType: "application/json",
280
+ bytes
281
+ }
282
+ };
283
+ return {
284
+ content: [{
285
+ type: "text",
286
+ text: textFor(structuredContent)
287
+ }, {
288
+ type: "resource_link",
289
+ name: "Protected Enhance result",
290
+ uri,
291
+ mimeType: "application/json"
292
+ }],
293
+ structuredContent
294
+ };
295
+ };
296
+ const validationError = (error) => new CliError("BAD_REQUEST", "Input validation error.", "Call capability_search again and rewrite every rejected input field.", Object.fromEntries(error.issues.map((issue) => [issue.path.length === 0 ? "input" : issue.path.join("."), issue.message])));
297
+ const createMcpResultAdapter = (authenticationRemediation, commandName = "enhance") => ({
298
+ success: async (server, result, delivery) => {
299
+ const presented = withCommandName(result, commandName);
300
+ const localArtifact = await localArtifactResult(server, presented, delivery);
301
+ if (localArtifact !== null) return localArtifact;
302
+ const serialized = textFor(presented);
303
+ if (Buffer.byteLength(serialized) > PROTECTED_RESULT_BYTES || hasProtectedMaterial(presented)) return artifactResult(server, serialized, delivery);
304
+ const structuredContent = {
305
+ ok: true,
306
+ result: presented
307
+ };
308
+ return {
309
+ content: [{
310
+ type: "text",
311
+ text: textFor(structuredContent)
312
+ }],
313
+ structuredContent
314
+ };
315
+ },
316
+ inline: (result) => {
317
+ const structuredContent = {
318
+ ok: true,
319
+ result: withCommandName(result, commandName)
320
+ };
321
+ return {
322
+ content: [{
323
+ type: "text",
324
+ text: textFor(structuredContent)
325
+ }],
326
+ structuredContent
327
+ };
328
+ },
329
+ failure: (error) => {
330
+ const failure = withCommandInFailure(toFailurePayload(error instanceof z.ZodError ? validationError(error) : error, null), commandName);
331
+ const structuredContent = {
332
+ ok: false,
333
+ error: failure.code === "UNAUTHORIZED" ? {
334
+ ...failure,
335
+ remediation: authenticationRemediation
336
+ } : failure
337
+ };
338
+ return {
339
+ content: [{
340
+ type: "text",
341
+ text: textFor(structuredContent)
342
+ }],
343
+ structuredContent,
344
+ isError: true
345
+ };
346
+ }
347
+ });
348
+
349
+ //#endregion
350
+ //#region src/infrastructure/mcp-server.adapter.ts
351
+ const MAX_SEARCH_QUERY_CHARACTERS = 200;
352
+ const MAX_SEARCH_RESULTS = 10;
353
+ const DEFAULT_SEARCH_RESULTS = 5;
354
+ const AUTHENTICATION_INSTRUCTIONS = "Transport attachment is not Enhance sign-in, even when the host reports mcp_auth success. Use capability_query with capability auth.status to check the person. If authenticated is false or a read returns UNAUTHORIZED, use capability_mutate with capability auth.login and input {\"openBrowser\":true}, then let the person complete browser sign-in. Verify auth.status and a read such as canvas.list before reporting setup complete.";
355
+ const LOCAL_AUTHENTICATION_REMEDY = "Call capability_mutate with capability auth.login and input {\"openBrowser\":true}. Complete browser sign-in, then verify auth.status and a read such as canvas.list.";
356
+ const HOSTED_AUTHENTICATION_REMEDY = "Reconnect this hosted MCP server through your host’s browser OAuth sign-in. Then verify person.me and a read such as canvas.list.";
357
+ const searchInputSchema = z.object({
358
+ query: z.string().trim().min(1).max(MAX_SEARCH_QUERY_CHARACTERS).describe("Plain-language task, domain, or exact capability id to discover."),
359
+ operation: z.enum([
360
+ "any",
361
+ "query",
362
+ "mutation"
363
+ ]).default("any").describe("Limit matches to reads or mutations when the intended effect is known."),
364
+ limit: z.number().int().min(1).max(MAX_SEARCH_RESULTS).default(DEFAULT_SEARCH_RESULTS).describe("Maximum contracts to return.")
365
+ });
366
+ const queryInputSchema = z.object({
367
+ capability: z.string().min(1).describe("Exact query id returned by capability_describe."),
368
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema.")
369
+ });
370
+ const mutationInputSchema = z.object({
371
+ capability: z.string().min(1).describe("Exact mutation id returned by capability_describe."),
372
+ input: z.record(z.string(), z.unknown()).default({}).describe("Input matching the discovered capability inputSchema."),
373
+ clientToken: z.uuid().optional().describe("Stable UUID reused only when retrying this exact mutation input.")
374
+ });
375
+ const capabilityFor = (catalog, id, operation) => {
376
+ const capability = catalog.find((candidate) => candidate.id === id);
377
+ 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." });
378
+ if (capability.operation !== operation) {
379
+ const dispatcher = capability.operation === "query" ? "capability_query" : "capability_mutate";
380
+ throw new CliError("BAD_REQUEST", `${id} is a ${capability.operation}, not a ${operation}.`, `Call ${dispatcher} with the same capability and input.`, { capability: `Use ${dispatcher} for this capability.` });
381
+ }
382
+ return capability;
383
+ };
384
+ const registerSearch = (server, catalog, discovery, mcpResults) => {
385
+ server.registerTool("capability_search", {
386
+ title: "Discover Enhance capabilities",
387
+ description: "Search the Enhance capability catalogue for a specific likely action. Returns only the most relevant summaries; use capability_catalogue when the request is broad or the matches look wrong, then call capability_describe before invoking.",
388
+ inputSchema: searchInputSchema,
389
+ outputSchema: mcpSearchResultSchema,
390
+ annotations: {
391
+ readOnlyHint: true,
392
+ destructiveHint: false,
393
+ idempotentHint: true,
394
+ openWorldHint: false
395
+ },
396
+ _meta: {
397
+ "ai.enhancelabs/disclosure": "progressive",
398
+ "ai.enhancelabs/catalogSize": catalog.length,
399
+ "enhance/disclosure": "progressive",
400
+ "enhance/catalogSize": catalog.length
401
+ }
402
+ }, async ({ query, operation, limit }) => mcpResults.inline(discovery.search({
403
+ query,
404
+ operation,
405
+ limit
406
+ })));
407
+ };
408
+ const registerQuery = (server, catalog, invocation, execution) => {
409
+ server.registerTool("capability_query", {
410
+ title: "Run a discovered Enhance query",
411
+ description: "Run one read-only capability using the exact id and input loaded by capability_describe. Search and describe first whenever the contract is not already present in the conversation.",
412
+ inputSchema: queryInputSchema,
413
+ outputSchema: mcpDispatchedResultSchema,
414
+ annotations: {
415
+ readOnlyHint: true,
416
+ destructiveHint: false,
417
+ idempotentHint: true,
418
+ openWorldHint: false
419
+ },
420
+ _meta: {
421
+ "ai.enhancelabs/disclosure": "progressive",
422
+ "enhance/disclosure": "progressive"
423
+ }
424
+ }, async ({ capability: id, input }) => {
425
+ try {
426
+ return await execution.results.success(server, await invocation.invoke({
427
+ capability: capabilityFor(catalog, id, "query"),
428
+ arguments: input,
429
+ clientToken: null
430
+ }), execution.delivery);
431
+ } catch (error) {
432
+ return execution.results.failure(error);
433
+ }
434
+ });
435
+ };
436
+ const registerMutation = (server, catalog, invocation, execution) => {
437
+ server.registerTool("capability_mutate", {
438
+ title: "Run a discovered Enhance mutation",
439
+ description: "Run one state-changing capability using the exact id and input loaded by capability_describe. Search and describe first, respect its preconditions, and reuse clientToken only when retrying the identical mutation.",
440
+ inputSchema: mutationInputSchema,
441
+ outputSchema: mcpDispatchedResultSchema,
442
+ annotations: {
443
+ readOnlyHint: false,
444
+ destructiveHint: true,
445
+ idempotentHint: false,
446
+ openWorldHint: false
447
+ },
448
+ _meta: {
449
+ "ai.enhancelabs/disclosure": "progressive",
450
+ "enhance/disclosure": "progressive"
451
+ }
452
+ }, async ({ capability: id, input, clientToken }) => {
453
+ try {
454
+ return await execution.results.success(server, await invocation.invoke({
455
+ capability: capabilityFor(catalog, id, "mutation"),
456
+ arguments: input,
457
+ clientToken: clientToken ?? null
458
+ }), execution.delivery);
459
+ } catch (error) {
460
+ return execution.results.failure(error);
461
+ }
462
+ });
463
+ };
464
+ const createMcpServerAdapter = (input) => {
465
+ const server = new McpServer({
466
+ name: input.name ?? "enhance-mcp",
467
+ version: input.version
468
+ }, {
469
+ capabilities: {
470
+ tools: { listChanged: false },
471
+ resources: { listChanged: true }
472
+ },
473
+ ...input.exposures?.includes("mcp-transport") === true && { instructions: AUTHENTICATION_INSTRUCTIONS }
474
+ });
475
+ const catalog = toPresentedCapabilities(input.catalog ?? createCapabilityCatalogAdapter(), input.exposures ?? ["shared"]);
476
+ const discovery = createMcpCapabilityDiscoveryAdapter(catalog);
477
+ const delivery = input.delivery ?? "linked";
478
+ const mcpResults = createMcpResultAdapter(input.exposures?.includes("mcp-transport") === true ? LOCAL_AUTHENTICATION_REMEDY : HOSTED_AUTHENTICATION_REMEDY, input.commandName);
479
+ createMcpCatalogueToolAdapter(catalog, input.version, input.commandName).register(server);
480
+ registerSearch(server, catalog, discovery, mcpResults);
481
+ createMcpDescribeToolAdapter(discovery, mcpResults).register(server);
482
+ const execution = {
483
+ delivery,
484
+ results: mcpResults
485
+ };
486
+ registerQuery(server, catalog, input.invocation, execution);
487
+ registerMutation(server, catalog, input.invocation, execution);
488
+ return server;
489
+ };
490
+
491
+ //#endregion
492
+ export { createMcpServerAdapter as t };
package/dist/mcp.mjs ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { l as createCapabilityCatalogAdapter, o as toSharedCapabilities } from "./cli-output-identity.lib-BSUBcRJm.mjs";
3
+ import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
4
+ import { t as createMcpServerAdapter } from "./mcp-server.adapter-lxpsuDlU.mjs";
5
+
6
+ export { createCapabilityCatalogAdapter, createMcpServerAdapter as createEnhanceMcpServer, toCapabilityInventory, toSharedCapabilities };