@enhance-eng/enhance 0.1.4 → 0.1.6

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