@contractspec/bundle.library 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.turbo/turbo-build.log +178 -166
  2. package/AGENTS.md +19 -12
  3. package/CHANGELOG.md +46 -0
  4. package/dist/application/context-storage/index.d.ts +18 -0
  5. package/dist/application/context-storage/index.js +29 -0
  6. package/dist/application/index.d.ts +1 -0
  7. package/dist/application/index.js +662 -2
  8. package/dist/application/mcp/cliMcp.js +12 -2
  9. package/dist/application/mcp/common.d.ts +11 -1
  10. package/dist/application/mcp/common.js +12 -2
  11. package/dist/application/mcp/contractsMcp.d.ts +51 -0
  12. package/dist/application/mcp/contractsMcp.js +531 -0
  13. package/dist/application/mcp/contractsMcpResources.d.ts +7 -0
  14. package/dist/application/mcp/contractsMcpResources.js +124 -0
  15. package/dist/application/mcp/contractsMcpTools.d.ts +9 -0
  16. package/dist/application/mcp/contractsMcpTools.js +200 -0
  17. package/dist/application/mcp/contractsMcpTypes.d.ts +50 -0
  18. package/dist/application/mcp/contractsMcpTypes.js +1 -0
  19. package/dist/application/mcp/docsMcp.js +12 -2
  20. package/dist/application/mcp/index.d.ts +2 -0
  21. package/dist/application/mcp/index.js +635 -2
  22. package/dist/application/mcp/internalMcp.js +12 -2
  23. package/dist/application/mcp/providerRankingMcp.d.ts +46 -0
  24. package/dist/application/mcp/providerRankingMcp.js +494 -0
  25. package/dist/node/application/context-storage/index.js +28 -0
  26. package/dist/node/application/index.js +662 -2
  27. package/dist/node/application/mcp/cliMcp.js +12 -2
  28. package/dist/node/application/mcp/common.js +12 -2
  29. package/dist/node/application/mcp/contractsMcp.js +530 -0
  30. package/dist/node/application/mcp/contractsMcpResources.js +123 -0
  31. package/dist/node/application/mcp/contractsMcpTools.js +199 -0
  32. package/dist/node/application/mcp/contractsMcpTypes.js +0 -0
  33. package/dist/node/application/mcp/docsMcp.js +12 -2
  34. package/dist/node/application/mcp/index.js +635 -2
  35. package/dist/node/application/mcp/internalMcp.js +12 -2
  36. package/dist/node/application/mcp/providerRankingMcp.js +493 -0
  37. package/package.json +111 -25
  38. package/src/application/context-storage/index.ts +58 -0
  39. package/src/application/index.ts +1 -0
  40. package/src/application/mcp/common.ts +28 -1
  41. package/src/application/mcp/contractsMcp.ts +34 -0
  42. package/src/application/mcp/contractsMcpResources.ts +142 -0
  43. package/src/application/mcp/contractsMcpTools.ts +246 -0
  44. package/src/application/mcp/contractsMcpTypes.ts +47 -0
  45. package/src/application/mcp/index.ts +2 -0
  46. package/src/application/mcp/providerRankingMcp.ts +380 -0
  47. package/src/components/docs/generated/docs-index._common.json +879 -1
  48. package/src/components/docs/generated/docs-index.manifest.json +5 -5
  49. package/src/components/docs/generated/docs-index.metrics.json +8 -0
  50. package/src/components/docs/generated/docs-index.platform-integrations.json +8 -0
@@ -72,9 +72,13 @@ function createMcpElysiaHandler({
72
72
  ops,
73
73
  resources,
74
74
  prompts,
75
- presentations
75
+ presentations,
76
+ validateAuth,
77
+ requiredAuthMethods
76
78
  }) {
77
- logger.info("Setting up MCP handler...");
79
+ logger.info("Setting up MCP handler...", {
80
+ requiredAuthMethods: requiredAuthMethods ?? []
81
+ });
78
82
  const isStateful = process.env.CONTRACTSPEC_MCP_STATEFUL === "1";
79
83
  const sessions = new Map;
80
84
  async function handleStateless(request) {
@@ -145,6 +149,12 @@ function createMcpElysiaHandler({
145
149
  }
146
150
  return new Elysia({ name: `mcp-${serverName}` }).all(path, async ({ request }) => {
147
151
  try {
152
+ if (validateAuth) {
153
+ const authResult = await validateAuth(request);
154
+ if (!authResult.valid) {
155
+ return createJsonRpcErrorResponse(401, -32002, "Authentication failed", authResult.reason);
156
+ }
157
+ }
148
158
  if (isStateful) {
149
159
  return await handleStateful(request);
150
160
  }
@@ -72,9 +72,13 @@ function createMcpElysiaHandler({
72
72
  ops,
73
73
  resources,
74
74
  prompts,
75
- presentations
75
+ presentations,
76
+ validateAuth,
77
+ requiredAuthMethods
76
78
  }) {
77
- logger.info("Setting up MCP handler...");
79
+ logger.info("Setting up MCP handler...", {
80
+ requiredAuthMethods: requiredAuthMethods ?? []
81
+ });
78
82
  const isStateful = process.env.CONTRACTSPEC_MCP_STATEFUL === "1";
79
83
  const sessions = new Map;
80
84
  async function handleStateless(request) {
@@ -145,6 +149,12 @@ function createMcpElysiaHandler({
145
149
  }
146
150
  return new Elysia({ name: `mcp-${serverName}` }).all(path, async ({ request }) => {
147
151
  try {
152
+ if (validateAuth) {
153
+ const authResult = await validateAuth(request);
154
+ if (!authResult.valid) {
155
+ return createJsonRpcErrorResponse(401, -32002, "Authentication failed", authResult.reason);
156
+ }
157
+ }
148
158
  if (isStateful) {
149
159
  return await handleStateful(request);
150
160
  }
@@ -0,0 +1,530 @@
1
+ // src/application/mcp/common.ts
2
+ import { PresentationRegistry } from "@contractspec/lib.contracts-spec/presentations";
3
+ import { createMcpServer } from "@contractspec/lib.contracts-runtime-server-mcp/provider-mcp";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
6
+ import { Elysia } from "elysia";
7
+ import { randomUUID } from "node:crypto";
8
+ var baseCtx = {
9
+ actor: "anonymous",
10
+ decide: async () => ({ effect: "allow" })
11
+ };
12
+ function createJsonRpcErrorResponse(status, code, message, data) {
13
+ return new Response(JSON.stringify({
14
+ jsonrpc: "2.0",
15
+ error: {
16
+ code,
17
+ message,
18
+ ...data ? { data } : {}
19
+ },
20
+ id: null
21
+ }), {
22
+ status,
23
+ headers: {
24
+ "content-type": "application/json"
25
+ }
26
+ });
27
+ }
28
+ function createSessionState({
29
+ logger,
30
+ serverName,
31
+ ops,
32
+ resources,
33
+ prompts,
34
+ presentations,
35
+ stateful
36
+ }) {
37
+ const server = new McpServer({
38
+ name: serverName,
39
+ version: "1.0.0"
40
+ }, {
41
+ capabilities: {
42
+ tools: {},
43
+ resources: {},
44
+ prompts: {},
45
+ logging: {}
46
+ }
47
+ });
48
+ logger.info("Setting up MCP server...");
49
+ createMcpServer(server, ops, resources, prompts, {
50
+ logger,
51
+ toolCtx: () => baseCtx,
52
+ promptCtx: () => ({ locale: "en" }),
53
+ resourceCtx: () => ({ locale: "en" }),
54
+ presentations: new PresentationRegistry(presentations)
55
+ });
56
+ const transport = new WebStandardStreamableHTTPServerTransport({
57
+ sessionIdGenerator: stateful ? () => randomUUID() : undefined,
58
+ enableJsonResponse: true
59
+ });
60
+ return server.connect(transport).then(() => ({ server, transport }));
61
+ }
62
+ async function closeSessionState(state) {
63
+ await Promise.allSettled([state.transport.close(), state.server.close()]);
64
+ }
65
+ function toErrorMessage(error) {
66
+ return error instanceof Error ? error.stack ?? error.message : String(error);
67
+ }
68
+ function createMcpElysiaHandler({
69
+ logger,
70
+ path,
71
+ serverName,
72
+ ops,
73
+ resources,
74
+ prompts,
75
+ presentations,
76
+ validateAuth,
77
+ requiredAuthMethods
78
+ }) {
79
+ logger.info("Setting up MCP handler...", {
80
+ requiredAuthMethods: requiredAuthMethods ?? []
81
+ });
82
+ const isStateful = process.env.CONTRACTSPEC_MCP_STATEFUL === "1";
83
+ const sessions = new Map;
84
+ async function handleStateless(request) {
85
+ const state = await createSessionState({
86
+ logger,
87
+ path,
88
+ serverName,
89
+ ops,
90
+ resources,
91
+ prompts,
92
+ presentations,
93
+ stateful: false
94
+ });
95
+ try {
96
+ return await state.transport.handleRequest(request);
97
+ } finally {
98
+ await closeSessionState(state);
99
+ }
100
+ }
101
+ async function closeSession(sessionId) {
102
+ const state = sessions.get(sessionId);
103
+ if (!state)
104
+ return;
105
+ sessions.delete(sessionId);
106
+ await closeSessionState(state);
107
+ }
108
+ async function handleStateful(request) {
109
+ const requestedSessionId = request.headers.get("mcp-session-id");
110
+ let state;
111
+ let createdState = false;
112
+ if (requestedSessionId) {
113
+ const existing = sessions.get(requestedSessionId);
114
+ if (!existing) {
115
+ return createJsonRpcErrorResponse(404, -32001, "Session not found");
116
+ }
117
+ state = existing;
118
+ } else {
119
+ state = await createSessionState({
120
+ logger,
121
+ path,
122
+ serverName,
123
+ ops,
124
+ resources,
125
+ prompts,
126
+ presentations,
127
+ stateful: true
128
+ });
129
+ createdState = true;
130
+ }
131
+ try {
132
+ const response = await state.transport.handleRequest(request);
133
+ const activeSessionId = state.transport.sessionId;
134
+ if (activeSessionId && !sessions.has(activeSessionId)) {
135
+ sessions.set(activeSessionId, state);
136
+ }
137
+ if (request.method === "DELETE" && activeSessionId) {
138
+ await closeSession(activeSessionId);
139
+ } else if (!activeSessionId && createdState) {
140
+ await closeSessionState(state);
141
+ }
142
+ return response;
143
+ } catch (error) {
144
+ if (createdState) {
145
+ await closeSessionState(state);
146
+ }
147
+ throw error;
148
+ }
149
+ }
150
+ return new Elysia({ name: `mcp-${serverName}` }).all(path, async ({ request }) => {
151
+ try {
152
+ if (validateAuth) {
153
+ const authResult = await validateAuth(request);
154
+ if (!authResult.valid) {
155
+ return createJsonRpcErrorResponse(401, -32002, "Authentication failed", authResult.reason);
156
+ }
157
+ }
158
+ if (isStateful) {
159
+ return await handleStateful(request);
160
+ }
161
+ return await handleStateless(request);
162
+ } catch (error) {
163
+ logger.error("Error handling MCP request", {
164
+ path,
165
+ method: request.method,
166
+ error: toErrorMessage(error)
167
+ });
168
+ return createJsonRpcErrorResponse(500, -32000, "Internal error");
169
+ }
170
+ });
171
+ }
172
+
173
+ // src/infrastructure/elysia/logger.ts
174
+ import { Logger, LogLevel } from "@contractspec/lib.logger";
175
+ var createAppLogger = () => new Logger({
176
+ level: LogLevel.DEBUG,
177
+ environment: "development",
178
+ enableTracing: true,
179
+ enableTiming: true,
180
+ enableContext: true,
181
+ enableColors: true
182
+ });
183
+ var appLogger = createAppLogger();
184
+ var dbLogger = new Logger({
185
+ level: LogLevel.DEBUG,
186
+ environment: "development",
187
+ enableTracing: true,
188
+ enableTiming: true,
189
+ enableContext: true,
190
+ enableColors: true
191
+ });
192
+ var authLogger = new Logger({
193
+ level: LogLevel.INFO,
194
+ environment: "development",
195
+ enableTracing: true,
196
+ enableTiming: true,
197
+ enableContext: true,
198
+ enableColors: true
199
+ });
200
+ // src/application/mcp/contractsMcpTools.ts
201
+ import {
202
+ defineCommand,
203
+ installOp,
204
+ OperationSpecRegistry
205
+ } from "@contractspec/lib.contracts-spec";
206
+ import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
207
+ var OWNERS = ["@contractspec"];
208
+ var TAGS = ["contracts", "mcp"];
209
+ function buildContractsOps(services) {
210
+ const registry = new OperationSpecRegistry;
211
+ const ListInput = defineSchemaModel({
212
+ name: "ContractsListInput",
213
+ fields: {
214
+ pattern: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
215
+ type: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
216
+ }
217
+ });
218
+ const ListOutput = defineSchemaModel({
219
+ name: "ContractsListOutput",
220
+ fields: {
221
+ specs: { type: ScalarTypeEnum.JSON(), isOptional: false },
222
+ total: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false }
223
+ }
224
+ });
225
+ installOp(registry, defineCommand({
226
+ meta: {
227
+ key: "contracts.list",
228
+ version: "1.0.0",
229
+ stability: "beta",
230
+ owners: OWNERS,
231
+ tags: TAGS,
232
+ description: "List contract specs in the workspace.",
233
+ goal: "Discover available contracts by type, pattern, or owner.",
234
+ context: "Contracts MCP server."
235
+ },
236
+ io: { input: ListInput, output: ListOutput },
237
+ policy: { auth: "anonymous" }
238
+ }), async ({ pattern, type }) => {
239
+ const specs = await services.listSpecs({ pattern, type });
240
+ return { specs, total: specs.length };
241
+ });
242
+ const GetInput = defineSchemaModel({
243
+ name: "ContractsGetInput",
244
+ fields: {
245
+ path: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
246
+ }
247
+ });
248
+ const GetOutput = defineSchemaModel({
249
+ name: "ContractsGetOutput",
250
+ fields: {
251
+ content: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
252
+ info: { type: ScalarTypeEnum.JSON(), isOptional: false }
253
+ }
254
+ });
255
+ installOp(registry, defineCommand({
256
+ meta: {
257
+ key: "contracts.get",
258
+ version: "1.0.0",
259
+ stability: "beta",
260
+ owners: OWNERS,
261
+ tags: TAGS,
262
+ description: "Read a single contract spec file.",
263
+ goal: "Fetch spec content and parsed metadata.",
264
+ context: "Contracts MCP server."
265
+ },
266
+ io: { input: GetInput, output: GetOutput },
267
+ policy: { auth: "anonymous" }
268
+ }), async ({ path }) => {
269
+ const result = await services.getSpec(path);
270
+ if (!result)
271
+ throw new Error(`Spec not found: ${path}`);
272
+ return result;
273
+ });
274
+ const ValidateInput = defineSchemaModel({
275
+ name: "ContractsValidateInput",
276
+ fields: {
277
+ path: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
278
+ }
279
+ });
280
+ const ValidateOutput = defineSchemaModel({
281
+ name: "ContractsValidateOutput",
282
+ fields: {
283
+ valid: { type: ScalarTypeEnum.Boolean(), isOptional: false },
284
+ errors: { type: ScalarTypeEnum.JSON(), isOptional: false },
285
+ warnings: { type: ScalarTypeEnum.JSON(), isOptional: false }
286
+ }
287
+ });
288
+ installOp(registry, defineCommand({
289
+ meta: {
290
+ key: "contracts.validate",
291
+ version: "1.0.0",
292
+ stability: "beta",
293
+ owners: OWNERS,
294
+ tags: TAGS,
295
+ description: "Validate a contract spec structure.",
296
+ goal: "Check spec for structural or policy issues.",
297
+ context: "Contracts MCP server."
298
+ },
299
+ io: { input: ValidateInput, output: ValidateOutput },
300
+ policy: { auth: "anonymous" }
301
+ }), async ({ path }) => services.validateSpec(path));
302
+ const BuildInput = defineSchemaModel({
303
+ name: "ContractsBuildInput",
304
+ fields: {
305
+ path: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
306
+ dryRun: { type: ScalarTypeEnum.Boolean(), isOptional: true }
307
+ }
308
+ });
309
+ const BuildOutput = defineSchemaModel({
310
+ name: "ContractsBuildOutput",
311
+ fields: {
312
+ results: { type: ScalarTypeEnum.JSON(), isOptional: false }
313
+ }
314
+ });
315
+ installOp(registry, defineCommand({
316
+ meta: {
317
+ key: "contracts.build",
318
+ version: "1.0.0",
319
+ stability: "beta",
320
+ owners: OWNERS,
321
+ tags: TAGS,
322
+ description: "Generate implementation code from a contract spec.",
323
+ goal: "Produce handler, component, or test skeletons.",
324
+ context: "Contracts MCP server."
325
+ },
326
+ io: { input: BuildInput, output: BuildOutput },
327
+ policy: { auth: "user" }
328
+ }), async ({ path, dryRun }) => services.buildSpec(path, { dryRun }));
329
+ registerMutationTools(registry, services);
330
+ return registry;
331
+ }
332
+ function registerMutationTools(registry, services) {
333
+ const UpdateInput = defineSchemaModel({
334
+ name: "ContractsUpdateInput",
335
+ fields: {
336
+ path: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
337
+ content: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
338
+ fields: { type: ScalarTypeEnum.JSON(), isOptional: true }
339
+ }
340
+ });
341
+ const UpdateOutput = defineSchemaModel({
342
+ name: "ContractsUpdateOutput",
343
+ fields: {
344
+ updated: { type: ScalarTypeEnum.Boolean(), isOptional: false },
345
+ errors: { type: ScalarTypeEnum.JSON(), isOptional: false },
346
+ warnings: { type: ScalarTypeEnum.JSON(), isOptional: false }
347
+ }
348
+ });
349
+ installOp(registry, defineCommand({
350
+ meta: {
351
+ key: "contracts.update",
352
+ version: "1.0.0",
353
+ stability: "beta",
354
+ owners: OWNERS,
355
+ tags: TAGS,
356
+ description: "Update an existing contract spec.",
357
+ goal: "Modify spec content or individual fields with validation.",
358
+ context: "Contracts MCP server."
359
+ },
360
+ io: { input: UpdateInput, output: UpdateOutput },
361
+ policy: { auth: "user" }
362
+ }), async ({ path, content, fields }) => services.updateSpec(path, {
363
+ content,
364
+ fields: Array.isArray(fields) ? fields : undefined
365
+ }));
366
+ const DeleteInput = defineSchemaModel({
367
+ name: "ContractsDeleteInput",
368
+ fields: {
369
+ path: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
370
+ clean: { type: ScalarTypeEnum.Boolean(), isOptional: true }
371
+ }
372
+ });
373
+ const DeleteOutput = defineSchemaModel({
374
+ name: "ContractsDeleteOutput",
375
+ fields: {
376
+ deleted: { type: ScalarTypeEnum.Boolean(), isOptional: false },
377
+ cleanedFiles: { type: ScalarTypeEnum.JSON(), isOptional: false },
378
+ errors: { type: ScalarTypeEnum.JSON(), isOptional: false }
379
+ }
380
+ });
381
+ installOp(registry, defineCommand({
382
+ meta: {
383
+ key: "contracts.delete",
384
+ version: "1.0.0",
385
+ stability: "beta",
386
+ owners: OWNERS,
387
+ tags: TAGS,
388
+ description: "Delete a contract spec and optionally its artifacts.",
389
+ goal: "Remove a spec file and clean generated handlers/tests.",
390
+ context: "Contracts MCP server."
391
+ },
392
+ io: { input: DeleteInput, output: DeleteOutput },
393
+ policy: { auth: "user" }
394
+ }), async ({ path, clean }) => services.deleteSpec(path, { clean }));
395
+ }
396
+
397
+ // src/application/mcp/contractsMcpResources.ts
398
+ import {
399
+ definePrompt,
400
+ defineResourceTemplate,
401
+ PromptRegistry,
402
+ ResourceRegistry
403
+ } from "@contractspec/lib.contracts-spec";
404
+ import z from "zod";
405
+ var OWNERS2 = ["@contractspec"];
406
+ var TAGS2 = ["contracts", "mcp"];
407
+ function buildContractsResources(services) {
408
+ const resources = new ResourceRegistry;
409
+ resources.register(defineResourceTemplate({
410
+ meta: {
411
+ uriTemplate: "contracts://list",
412
+ title: "Contract specs list",
413
+ description: "JSON list of all contract specs in the workspace.",
414
+ mimeType: "application/json",
415
+ tags: TAGS2
416
+ },
417
+ input: z.object({}),
418
+ resolve: async () => {
419
+ const specs = await services.listSpecs();
420
+ return {
421
+ uri: "contracts://list",
422
+ mimeType: "application/json",
423
+ data: JSON.stringify(specs, null, 2)
424
+ };
425
+ }
426
+ }));
427
+ resources.register(defineResourceTemplate({
428
+ meta: {
429
+ uriTemplate: "contracts://spec/{path}",
430
+ title: "Contract spec content",
431
+ description: "Read a single contract spec file by path.",
432
+ mimeType: "text/plain",
433
+ tags: TAGS2
434
+ },
435
+ input: z.object({ path: z.string() }),
436
+ resolve: async ({ path }) => {
437
+ const result = await services.getSpec(path);
438
+ if (!result) {
439
+ return {
440
+ uri: `contracts://spec/${encodeURIComponent(path)}`,
441
+ mimeType: "text/plain",
442
+ data: `Spec not found: ${path}`
443
+ };
444
+ }
445
+ return {
446
+ uri: `contracts://spec/${encodeURIComponent(path)}`,
447
+ mimeType: "text/plain",
448
+ data: result.content
449
+ };
450
+ }
451
+ }));
452
+ resources.register(defineResourceTemplate({
453
+ meta: {
454
+ uriTemplate: "contracts://registry/manifest",
455
+ title: "Remote registry manifest",
456
+ description: "Contract registry manifest from the remote server.",
457
+ mimeType: "application/json",
458
+ tags: TAGS2
459
+ },
460
+ input: z.object({}),
461
+ resolve: async () => {
462
+ const manifest = await services.fetchRegistryManifest();
463
+ return {
464
+ uri: "contracts://registry/manifest",
465
+ mimeType: "application/json",
466
+ data: JSON.stringify(manifest, null, 2)
467
+ };
468
+ }
469
+ }));
470
+ return resources;
471
+ }
472
+ function buildContractsPrompts() {
473
+ const prompts = new PromptRegistry;
474
+ prompts.register(definePrompt({
475
+ meta: {
476
+ key: "contracts.editor",
477
+ version: "1.0.0",
478
+ title: "Contract editing guide",
479
+ description: "Guide AI agents through reading, editing, and validating contracts.",
480
+ tags: TAGS2,
481
+ stability: "beta",
482
+ owners: OWNERS2
483
+ },
484
+ args: [
485
+ {
486
+ name: "goal",
487
+ description: "What the agent wants to achieve with the contract.",
488
+ required: false,
489
+ schema: z.string().optional()
490
+ }
491
+ ],
492
+ input: z.object({ goal: z.string().optional() }),
493
+ render: async ({ goal }) => [
494
+ {
495
+ type: "text",
496
+ text: [
497
+ "Contract editing workflow:",
498
+ "1. Use contracts.list to discover specs",
499
+ "2. Use contracts.get to read a spec",
500
+ "3. Edit content and call contracts.update",
501
+ "4. Run contracts.validate to verify changes",
502
+ "5. Run contracts.build to regenerate artifacts",
503
+ goal ? `Agent goal: ${goal}` : ""
504
+ ].filter(Boolean).join(`
505
+ `)
506
+ },
507
+ {
508
+ type: "resource",
509
+ uri: "contracts://list",
510
+ title: "Available contracts"
511
+ }
512
+ ]
513
+ }));
514
+ return prompts;
515
+ }
516
+
517
+ // src/application/mcp/contractsMcp.ts
518
+ function createContractsMcpHandler(path = "/api/mcp/contracts", services) {
519
+ return createMcpElysiaHandler({
520
+ logger: appLogger,
521
+ path,
522
+ serverName: "contractspec-contracts-mcp",
523
+ ops: buildContractsOps(services),
524
+ resources: buildContractsResources(services),
525
+ prompts: buildContractsPrompts()
526
+ });
527
+ }
528
+ export {
529
+ createContractsMcpHandler
530
+ };
@@ -0,0 +1,123 @@
1
+ // src/application/mcp/contractsMcpResources.ts
2
+ import {
3
+ definePrompt,
4
+ defineResourceTemplate,
5
+ PromptRegistry,
6
+ ResourceRegistry
7
+ } from "@contractspec/lib.contracts-spec";
8
+ import z from "zod";
9
+ var OWNERS = ["@contractspec"];
10
+ var TAGS = ["contracts", "mcp"];
11
+ function buildContractsResources(services) {
12
+ const resources = new ResourceRegistry;
13
+ resources.register(defineResourceTemplate({
14
+ meta: {
15
+ uriTemplate: "contracts://list",
16
+ title: "Contract specs list",
17
+ description: "JSON list of all contract specs in the workspace.",
18
+ mimeType: "application/json",
19
+ tags: TAGS
20
+ },
21
+ input: z.object({}),
22
+ resolve: async () => {
23
+ const specs = await services.listSpecs();
24
+ return {
25
+ uri: "contracts://list",
26
+ mimeType: "application/json",
27
+ data: JSON.stringify(specs, null, 2)
28
+ };
29
+ }
30
+ }));
31
+ resources.register(defineResourceTemplate({
32
+ meta: {
33
+ uriTemplate: "contracts://spec/{path}",
34
+ title: "Contract spec content",
35
+ description: "Read a single contract spec file by path.",
36
+ mimeType: "text/plain",
37
+ tags: TAGS
38
+ },
39
+ input: z.object({ path: z.string() }),
40
+ resolve: async ({ path }) => {
41
+ const result = await services.getSpec(path);
42
+ if (!result) {
43
+ return {
44
+ uri: `contracts://spec/${encodeURIComponent(path)}`,
45
+ mimeType: "text/plain",
46
+ data: `Spec not found: ${path}`
47
+ };
48
+ }
49
+ return {
50
+ uri: `contracts://spec/${encodeURIComponent(path)}`,
51
+ mimeType: "text/plain",
52
+ data: result.content
53
+ };
54
+ }
55
+ }));
56
+ resources.register(defineResourceTemplate({
57
+ meta: {
58
+ uriTemplate: "contracts://registry/manifest",
59
+ title: "Remote registry manifest",
60
+ description: "Contract registry manifest from the remote server.",
61
+ mimeType: "application/json",
62
+ tags: TAGS
63
+ },
64
+ input: z.object({}),
65
+ resolve: async () => {
66
+ const manifest = await services.fetchRegistryManifest();
67
+ return {
68
+ uri: "contracts://registry/manifest",
69
+ mimeType: "application/json",
70
+ data: JSON.stringify(manifest, null, 2)
71
+ };
72
+ }
73
+ }));
74
+ return resources;
75
+ }
76
+ function buildContractsPrompts() {
77
+ const prompts = new PromptRegistry;
78
+ prompts.register(definePrompt({
79
+ meta: {
80
+ key: "contracts.editor",
81
+ version: "1.0.0",
82
+ title: "Contract editing guide",
83
+ description: "Guide AI agents through reading, editing, and validating contracts.",
84
+ tags: TAGS,
85
+ stability: "beta",
86
+ owners: OWNERS
87
+ },
88
+ args: [
89
+ {
90
+ name: "goal",
91
+ description: "What the agent wants to achieve with the contract.",
92
+ required: false,
93
+ schema: z.string().optional()
94
+ }
95
+ ],
96
+ input: z.object({ goal: z.string().optional() }),
97
+ render: async ({ goal }) => [
98
+ {
99
+ type: "text",
100
+ text: [
101
+ "Contract editing workflow:",
102
+ "1. Use contracts.list to discover specs",
103
+ "2. Use contracts.get to read a spec",
104
+ "3. Edit content and call contracts.update",
105
+ "4. Run contracts.validate to verify changes",
106
+ "5. Run contracts.build to regenerate artifacts",
107
+ goal ? `Agent goal: ${goal}` : ""
108
+ ].filter(Boolean).join(`
109
+ `)
110
+ },
111
+ {
112
+ type: "resource",
113
+ uri: "contracts://list",
114
+ title: "Available contracts"
115
+ }
116
+ ]
117
+ }));
118
+ return prompts;
119
+ }
120
+ export {
121
+ buildContractsResources,
122
+ buildContractsPrompts
123
+ };