@contractspec/bundle.library 3.8.4 → 3.8.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.
Files changed (90) hide show
  1. package/.turbo/turbo-build.log +126 -112
  2. package/CHANGELOG.md +56 -0
  3. package/dist/application/index.js +806 -131
  4. package/dist/application/mcp/cliMcp.js +21 -2
  5. package/dist/application/mcp/common.js +21 -2
  6. package/dist/application/mcp/common.test.d.ts +1 -0
  7. package/dist/application/mcp/contractsMcp.js +21 -2
  8. package/dist/application/mcp/docsMcp.catalog.d.ts +2 -0
  9. package/dist/application/mcp/docsMcp.catalog.js +382 -0
  10. package/dist/application/mcp/docsMcp.d.ts +5 -1
  11. package/dist/application/mcp/docsMcp.data.d.ts +85 -0
  12. package/dist/application/mcp/docsMcp.data.js +148 -0
  13. package/dist/application/mcp/docsMcp.js +776 -101
  14. package/dist/application/mcp/docsMcp.prompts.d.ts +3 -0
  15. package/dist/application/mcp/docsMcp.prompts.js +522 -0
  16. package/dist/application/mcp/docsMcp.reference.d.ts +24 -0
  17. package/dist/application/mcp/docsMcp.reference.js +236 -0
  18. package/dist/application/mcp/docsMcp.resources.d.ts +3 -0
  19. package/dist/application/mcp/docsMcp.resources.js +520 -0
  20. package/dist/application/mcp/docsMcp.test.d.ts +1 -0
  21. package/dist/application/mcp/docsMcp.tools.d.ts +3 -0
  22. package/dist/application/mcp/docsMcp.tools.js +519 -0
  23. package/dist/application/mcp/index.js +806 -131
  24. package/dist/application/mcp/internalMcp.js +21 -2
  25. package/dist/application/mcp/normalizeMcpRequest.d.ts +1 -0
  26. package/dist/application/mcp/normalizeMcpRequest.js +22 -0
  27. package/dist/application/mcp/providerRankingMcp.js +21 -2
  28. package/dist/features/index.js +15 -15
  29. package/dist/index.js +171 -171
  30. package/dist/node/application/index.js +806 -131
  31. package/dist/node/application/mcp/cliMcp.js +21 -2
  32. package/dist/node/application/mcp/common.js +21 -2
  33. package/dist/node/application/mcp/contractsMcp.js +21 -2
  34. package/dist/node/application/mcp/docsMcp.catalog.js +381 -0
  35. package/dist/node/application/mcp/docsMcp.data.js +147 -0
  36. package/dist/node/application/mcp/docsMcp.js +776 -101
  37. package/dist/node/application/mcp/docsMcp.prompts.js +521 -0
  38. package/dist/node/application/mcp/docsMcp.reference.js +235 -0
  39. package/dist/node/application/mcp/docsMcp.resources.js +519 -0
  40. package/dist/node/application/mcp/docsMcp.tools.js +518 -0
  41. package/dist/node/application/mcp/index.js +806 -131
  42. package/dist/node/application/mcp/internalMcp.js +21 -2
  43. package/dist/node/application/mcp/normalizeMcpRequest.js +21 -0
  44. package/dist/node/application/mcp/providerRankingMcp.js +21 -2
  45. package/dist/node/features/index.js +15 -15
  46. package/dist/node/index.js +171 -171
  47. package/dist/node/presentation/features/hooks/index.js +12 -12
  48. package/dist/node/presentation/features/hooks/useContractsRegistry.js +12 -12
  49. package/dist/node/presentation/features/index.js +12 -12
  50. package/dist/node/presentation/features/organisms/FeatureDataViewsList.js +12 -12
  51. package/dist/node/presentation/features/organisms/FeatureEventsList.js +12 -12
  52. package/dist/node/presentation/features/organisms/FeatureFormsList.js +12 -12
  53. package/dist/node/presentation/features/organisms/FeaturePresentationsList.js +12 -12
  54. package/dist/node/presentation/features/organisms/index.js +12 -12
  55. package/dist/node/presentation/features/templates/FeatureDataViewsTemplate/FeatureDataViewsTemplate.js +12 -12
  56. package/dist/node/presentation/features/templates/FeatureDataViewsTemplate/index.js +12 -12
  57. package/dist/node/presentation/features/templates/FeatureEventsTemplate/FeatureEventsTemplate.js +12 -12
  58. package/dist/node/presentation/features/templates/FeatureEventsTemplate/index.js +12 -12
  59. package/dist/node/presentation/features/templates/FeatureFormsTemplate/FeatureFormsTemplate.js +12 -12
  60. package/dist/node/presentation/features/templates/FeatureFormsTemplate/index.js +12 -12
  61. package/dist/node/presentation/features/templates/FeaturePresentationsTemplate/FeaturePresentationsTemplate.js +12 -12
  62. package/dist/node/presentation/features/templates/FeaturePresentationsTemplate/index.js +12 -12
  63. package/dist/presentation/features/hooks/index.js +12 -12
  64. package/dist/presentation/features/hooks/useContractsRegistry.js +12 -12
  65. package/dist/presentation/features/index.js +12 -12
  66. package/dist/presentation/features/organisms/FeatureDataViewsList.js +12 -12
  67. package/dist/presentation/features/organisms/FeatureEventsList.js +12 -12
  68. package/dist/presentation/features/organisms/FeatureFormsList.js +12 -12
  69. package/dist/presentation/features/organisms/FeaturePresentationsList.js +12 -12
  70. package/dist/presentation/features/organisms/index.js +12 -12
  71. package/dist/presentation/features/templates/FeatureDataViewsTemplate/FeatureDataViewsTemplate.js +12 -12
  72. package/dist/presentation/features/templates/FeatureDataViewsTemplate/index.js +12 -12
  73. package/dist/presentation/features/templates/FeatureEventsTemplate/FeatureEventsTemplate.js +12 -12
  74. package/dist/presentation/features/templates/FeatureEventsTemplate/index.js +12 -12
  75. package/dist/presentation/features/templates/FeatureFormsTemplate/FeatureFormsTemplate.js +12 -12
  76. package/dist/presentation/features/templates/FeatureFormsTemplate/index.js +12 -12
  77. package/dist/presentation/features/templates/FeaturePresentationsTemplate/FeaturePresentationsTemplate.js +12 -12
  78. package/dist/presentation/features/templates/FeaturePresentationsTemplate/index.js +12 -12
  79. package/package.json +108 -24
  80. package/src/application/mcp/common.test.ts +64 -0
  81. package/src/application/mcp/common.ts +5 -2
  82. package/src/application/mcp/docsMcp.catalog.ts +2 -0
  83. package/src/application/mcp/docsMcp.data.ts +196 -0
  84. package/src/application/mcp/docsMcp.prompts.ts +165 -0
  85. package/src/application/mcp/docsMcp.reference.ts +152 -0
  86. package/src/application/mcp/docsMcp.resources.ts +194 -0
  87. package/src/application/mcp/docsMcp.test.ts +148 -0
  88. package/src/application/mcp/docsMcp.tools.ts +183 -0
  89. package/src/application/mcp/docsMcp.ts +13 -177
  90. package/src/application/mcp/normalizeMcpRequest.ts +30 -0
@@ -26,6 +26,25 @@ var authLogger = new Logger({
26
26
  enableContext: true,
27
27
  enableColors: false
28
28
  });
29
+ // src/application/mcp/normalizeMcpRequest.ts
30
+ var REQUIRED_ACCEPT_TYPES = ["application/json", "text/event-stream"];
31
+ function canNormalizeAcceptHeader(acceptHeader) {
32
+ return !acceptHeader || acceptHeader.includes("*/*") || acceptHeader.includes("application/*") || REQUIRED_ACCEPT_TYPES.some((value) => acceptHeader.includes(value));
33
+ }
34
+ function normalizeMcpRequest(request) {
35
+ if (request.method !== "POST")
36
+ return request;
37
+ const acceptHeader = request.headers.get("accept");
38
+ if (!canNormalizeAcceptHeader(acceptHeader))
39
+ return request;
40
+ const missingTypes = REQUIRED_ACCEPT_TYPES.filter((value) => !acceptHeader?.includes(value));
41
+ if (missingTypes.length === 0)
42
+ return request;
43
+ const headers = new Headers(request.headers);
44
+ headers.set("accept", [acceptHeader, ...missingTypes].filter(Boolean).join(", "));
45
+ return new Request(request, { headers });
46
+ }
47
+
29
48
  // src/application/mcp/common.ts
30
49
  import { randomUUID } from "crypto";
31
50
  import { createMcpServer } from "@contractspec/lib.contracts-runtime-server-mcp/provider-mcp";
@@ -121,7 +140,7 @@ function createMcpElysiaHandler({
121
140
  stateful: false
122
141
  });
123
142
  try {
124
- return await state.transport.handleRequest(request);
143
+ return await state.transport.handleRequest(normalizeMcpRequest(request));
125
144
  } finally {
126
145
  await closeSessionState(state);
127
146
  }
@@ -157,7 +176,7 @@ function createMcpElysiaHandler({
157
176
  createdState = true;
158
177
  }
159
178
  try {
160
- const response = await state.transport.handleRequest(request);
179
+ const response = await state.transport.handleRequest(normalizeMcpRequest(request));
161
180
  const activeSessionId = state.transport.sessionId;
162
181
  if (activeSessionId && !sessions.has(activeSessionId)) {
163
182
  sessions.set(activeSessionId, state);
@@ -198,90 +217,393 @@ function createMcpElysiaHandler({
198
217
  });
199
218
  }
200
219
 
201
- // src/features/docs/docs.contracts.ts
220
+ // src/application/mcp/docsMcp.data.ts
221
+ import { defaultDocRegistry } from "@contractspec/lib.contracts-spec/docs";
222
+ var DEFAULT_LIMIT = 20;
223
+ var MAX_LIMIT = 100;
224
+ function normalizeText(value) {
225
+ return value?.trim().toLowerCase() ?? "";
226
+ }
227
+ function normalizeRoute(route) {
228
+ const decoded = decodeURIComponent(route).trim();
229
+ if (!decoded)
230
+ return "/";
231
+ return decoded.startsWith("/") ? decoded : `/${decoded}`;
232
+ }
233
+ function normalizeTags(value) {
234
+ const tags = Array.isArray(value) ? value : value ? [value] : [];
235
+ return tags.map((tag) => normalizeText(tag)).filter(Boolean);
236
+ }
237
+ function clampLimit(limit) {
238
+ if (!limit || Number.isNaN(limit))
239
+ return DEFAULT_LIMIT;
240
+ return Math.min(Math.max(limit, 1), MAX_LIMIT);
241
+ }
242
+ function clampOffset(offset) {
243
+ if (!offset || Number.isNaN(offset))
244
+ return 0;
245
+ return Math.max(offset, 0);
246
+ }
247
+ function toDocSummary({ block, route }) {
248
+ return {
249
+ id: block.id,
250
+ title: block.title,
251
+ summary: block.summary ?? "",
252
+ route,
253
+ visibility: block.visibility ?? "public",
254
+ kind: block.kind ?? "reference",
255
+ version: block.version ?? "1.0.0",
256
+ tags: block.tags ?? []
257
+ };
258
+ }
259
+ function scoreDoc(route, query) {
260
+ if (!query)
261
+ return 1;
262
+ const tokens = query.split(/\s+/).filter(Boolean);
263
+ const title = normalizeText(route.block.title);
264
+ const id = normalizeText(route.block.id);
265
+ const summary = normalizeText(route.block.summary);
266
+ const body = normalizeText(route.block.body);
267
+ const path = normalizeText(route.route);
268
+ const tags = (route.block.tags ?? []).map((tag) => normalizeText(tag));
269
+ const haystack = [title, id, summary, body, path, ...tags].join(" ");
270
+ if (tokens.some((token) => !haystack.includes(token)))
271
+ return 0;
272
+ let score = 0;
273
+ for (const token of tokens) {
274
+ if (id.includes(token))
275
+ score += 8;
276
+ if (title.includes(token))
277
+ score += 7;
278
+ if (tags.some((tag) => tag.includes(token)))
279
+ score += 5;
280
+ if (summary.includes(token))
281
+ score += 4;
282
+ if (path.includes(token))
283
+ score += 3;
284
+ if (body.includes(token))
285
+ score += 2;
286
+ }
287
+ return score;
288
+ }
289
+ function searchDocs(routes, args) {
290
+ const query = normalizeText(typeof args.query === "string" ? args.query : undefined);
291
+ const tags = normalizeTags(args.tag);
292
+ const visibility = normalizeText(typeof args.visibility === "string" ? args.visibility : undefined);
293
+ const kind = normalizeText(typeof args.kind === "string" ? args.kind : undefined);
294
+ const limit = clampLimit(typeof args.limit === "number" ? args.limit : undefined);
295
+ const offset = clampOffset(typeof args.offset === "number" ? args.offset : undefined);
296
+ const ranked = routes.map((route) => ({
297
+ doc: toDocSummary(route),
298
+ score: scoreDoc(route, query)
299
+ })).filter(({ doc, score }) => {
300
+ const matchesQuery = query ? score > 0 : true;
301
+ const matchesTags = tags.length ? tags.every((tag) => doc.tags.some((docTag) => normalizeText(docTag).includes(tag))) : true;
302
+ const matchesVisibility = visibility ? normalizeText(doc.visibility) === visibility : true;
303
+ const matchesKind = kind ? normalizeText(doc.kind) === kind : true;
304
+ return matchesQuery && matchesTags && matchesVisibility && matchesKind;
305
+ }).sort((left, right) => {
306
+ if (right.score !== left.score)
307
+ return right.score - left.score;
308
+ return left.doc.title.localeCompare(right.doc.title);
309
+ });
310
+ const docs = ranked.slice(offset, offset + limit).map(({ doc }) => doc);
311
+ const nextOffset = offset + docs.length < ranked.length ? offset + docs.length : undefined;
312
+ return {
313
+ docs,
314
+ items: docs,
315
+ total: ranked.length,
316
+ ...nextOffset != null ? { nextOffset } : {}
317
+ };
318
+ }
319
+ function getDocById(id) {
320
+ const normalizedId = decodeURIComponent(id);
321
+ const found = defaultDocRegistry.get(normalizedId);
322
+ if (!found)
323
+ return;
324
+ return {
325
+ doc: toDocSummary(found),
326
+ content: String(found.block.body ?? "")
327
+ };
328
+ }
329
+ function getDocByRoute(routes, routePath) {
330
+ const normalizedPath = normalizeRoute(routePath);
331
+ const found = routes.find((route) => normalizeRoute(route.route) === normalizedPath);
332
+ if (!found)
333
+ return;
334
+ return {
335
+ doc: toDocSummary(found),
336
+ content: String(found.block.body ?? "")
337
+ };
338
+ }
339
+ function listDocFacets(routes) {
340
+ const tags = new Map;
341
+ const kinds = new Map;
342
+ const visibilities = new Map;
343
+ for (const route of routes) {
344
+ const kind = route.block.kind ?? "reference";
345
+ const visibility = route.block.visibility ?? "public";
346
+ kinds.set(kind, (kinds.get(kind) ?? 0) + 1);
347
+ visibilities.set(visibility, (visibilities.get(visibility) ?? 0) + 1);
348
+ for (const tag of route.block.tags ?? []) {
349
+ tags.set(tag, (tags.get(tag) ?? 0) + 1);
350
+ }
351
+ }
352
+ const toEntries = (values, key) => [...values.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])).map(([value, count]) => ({ [key]: value, count }));
353
+ return {
354
+ totalDocs: routes.length,
355
+ tags: toEntries(tags, "tag"),
356
+ kinds: toEntries(kinds, "kind"),
357
+ visibilities: toEntries(visibilities, "visibility")
358
+ };
359
+ }
360
+
361
+ // src/features/contracts-registry.ts
362
+ import {
363
+ EventRegistry,
364
+ OperationSpecRegistry
365
+ } from "@contractspec/lib.contracts-spec";
202
366
  import {
367
+ DataViewRegistry
368
+ } from "@contractspec/lib.contracts-spec/data-views";
369
+ import {
370
+ ContractReferenceDataView,
203
371
  ContractReferenceQuery,
204
- DocSummaryModel,
205
- DocsIndexInput,
206
- DocsIndexOutput,
372
+ DocsGenerateCommand,
373
+ DocsGeneratedEvent,
374
+ DocsIndexDataView,
207
375
  DocsIndexQuery,
208
- DocsIndexQuery as DocsIndexQuery2
376
+ DocsLayoutPresentation,
377
+ DocsPublishCommand,
378
+ DocsPublishedEvent,
379
+ DocsReferencePagePresentation,
380
+ DocsSearchForm,
381
+ ExampleCatalogDataView
209
382
  } from "@contractspec/lib.contracts-spec/docs";
210
- // src/application/mcp/docsMcp.ts
383
+ import { FormRegistry } from "@contractspec/lib.contracts-spec/forms";
211
384
  import {
212
- definePrompt,
213
- defineResourceTemplate,
214
- installOp,
215
- OperationSpecRegistry,
216
- PromptRegistry,
217
- ResourceRegistry
218
- } from "@contractspec/lib.contracts-spec";
219
- import { defaultDocRegistry } from "@contractspec/lib.contracts-spec/docs";
220
- import z from "zod";
221
- var DOC_OWNERS = ["@contractspec"];
222
- var DOC_TAGS = ["docs", "mcp"];
223
- function buildDocResources(routes) {
224
- const resources = new ResourceRegistry;
225
- resources.register(defineResourceTemplate({
226
- meta: {
227
- uriTemplate: "docs://list",
228
- title: "DocBlocks index",
229
- description: "All registered DocBlocks with route, visibility, tags, and summary.",
230
- mimeType: "application/json",
231
- tags: DOC_TAGS
385
+ PresentationRegistry as PresentationRegistry2
386
+ } from "@contractspec/lib.contracts-spec/presentations";
387
+ import {
388
+ serializeDataViewSpec,
389
+ serializeEventSpec,
390
+ serializeFormSpec,
391
+ serializeOperationSpec,
392
+ serializePresentationSpec
393
+ } from "@contractspec/lib.contracts-spec/serialization";
394
+ var operationRegistry = null;
395
+ function createContractSpecOperationRegistry() {
396
+ const registry = new OperationSpecRegistry;
397
+ registry.register(DocsIndexQuery).register(ContractReferenceQuery).register(DocsGenerateCommand).register(DocsPublishCommand);
398
+ return registry;
399
+ }
400
+ function getContractSpecOperationRegistry() {
401
+ if (!operationRegistry) {
402
+ operationRegistry = createContractSpecOperationRegistry();
403
+ }
404
+ return operationRegistry;
405
+ }
406
+ function resolveOperationSpec(key, version) {
407
+ return getContractSpecOperationRegistry().get(key, version);
408
+ }
409
+ var eventRegistry = null;
410
+ function createContractSpecEventRegistry() {
411
+ const registry = new EventRegistry;
412
+ registry.register(DocsGeneratedEvent).register(DocsPublishedEvent);
413
+ return registry;
414
+ }
415
+ function getContractSpecEventRegistry() {
416
+ if (!eventRegistry) {
417
+ eventRegistry = createContractSpecEventRegistry();
418
+ }
419
+ return eventRegistry;
420
+ }
421
+ function resolveEventSpec(key, version) {
422
+ return getContractSpecEventRegistry().get(key, version);
423
+ }
424
+ var presentationRegistry = null;
425
+ function createContractSpecPresentationRegistry() {
426
+ const registry = new PresentationRegistry2;
427
+ registry.register(DocsLayoutPresentation).register(DocsReferencePagePresentation);
428
+ return registry;
429
+ }
430
+ function getContractSpecPresentationRegistry() {
431
+ if (!presentationRegistry) {
432
+ presentationRegistry = createContractSpecPresentationRegistry();
433
+ }
434
+ return presentationRegistry;
435
+ }
436
+ function resolvePresentationSpec(key, version) {
437
+ return getContractSpecPresentationRegistry().get(key, version);
438
+ }
439
+ var dataViewRegistry = null;
440
+ function createContractSpecDataViewRegistry() {
441
+ const registry = new DataViewRegistry;
442
+ registry.register(DocsIndexDataView).register(ContractReferenceDataView).register(ExampleCatalogDataView);
443
+ return registry;
444
+ }
445
+ function getContractSpecDataViewRegistry() {
446
+ if (!dataViewRegistry) {
447
+ dataViewRegistry = createContractSpecDataViewRegistry();
448
+ }
449
+ return dataViewRegistry;
450
+ }
451
+ function resolveDataViewSpec(key, version) {
452
+ return getContractSpecDataViewRegistry().get(key, version);
453
+ }
454
+ var formRegistry = null;
455
+ function createContractSpecFormRegistry() {
456
+ const registry = new FormRegistry;
457
+ registry.register(DocsSearchForm);
458
+ return registry;
459
+ }
460
+ function getContractSpecFormRegistry() {
461
+ if (!formRegistry) {
462
+ formRegistry = createContractSpecFormRegistry();
463
+ }
464
+ return formRegistry;
465
+ }
466
+ function resolveFormSpec(key, _version) {
467
+ return getContractSpecFormRegistry().get(key);
468
+ }
469
+ function resolveSerializedOperationSpec(key, version) {
470
+ const spec = resolveOperationSpec(key, version);
471
+ return serializeOperationSpec(spec) ?? undefined;
472
+ }
473
+ function resolveSerializedEventSpec(key, version) {
474
+ const spec = resolveEventSpec(key, version);
475
+ return serializeEventSpec(spec) ?? undefined;
476
+ }
477
+ function resolveSerializedPresentationSpec(key, version) {
478
+ const spec = resolvePresentationSpec(key, version);
479
+ return serializePresentationSpec(spec) ?? undefined;
480
+ }
481
+ function resolveSerializedDataViewSpec(key, version) {
482
+ const spec = resolveDataViewSpec(key, version);
483
+ return serializeDataViewSpec(spec) ?? undefined;
484
+ }
485
+ function resolveSerializedFormSpec(key, version) {
486
+ const spec = resolveFormSpec(key, version);
487
+ return serializeFormSpec(spec) ?? undefined;
488
+ }
489
+ function resetContractSpecOperationRegistry() {
490
+ operationRegistry = null;
491
+ }
492
+ function resetContractSpecEventRegistry() {
493
+ eventRegistry = null;
494
+ }
495
+ function resetContractSpecPresentationRegistry() {
496
+ presentationRegistry = null;
497
+ }
498
+ function resetContractSpecDataViewRegistry() {
499
+ dataViewRegistry = null;
500
+ }
501
+ function resetContractSpecFormRegistry() {
502
+ formRegistry = null;
503
+ }
504
+ function resetAllContractSpecRegistries() {
505
+ resetContractSpecOperationRegistry();
506
+ resetContractSpecEventRegistry();
507
+ resetContractSpecPresentationRegistry();
508
+ resetContractSpecDataViewRegistry();
509
+ resetContractSpecFormRegistry();
510
+ }
511
+
512
+ // src/application/mcp/docsMcp.reference.ts
513
+ import { defaultDocRegistry as defaultDocRegistry2 } from "@contractspec/lib.contracts-spec/docs";
514
+ function normalizeText2(value) {
515
+ return value?.trim().toLowerCase() ?? "";
516
+ }
517
+ function routeFromDocIds(docIds) {
518
+ for (const docId of docIds ?? []) {
519
+ const doc = defaultDocRegistry2.get(docId);
520
+ if (doc)
521
+ return doc.route;
522
+ }
523
+ return;
524
+ }
525
+ function toReference(spec, type, schema, policy) {
526
+ const title = spec.meta.title ?? spec.meta.key;
527
+ const route = routeFromDocIds(spec.meta.docId);
528
+ const description = spec.meta.description;
529
+ return {
530
+ key: spec.meta.key,
531
+ version: spec.meta.version,
532
+ type,
533
+ title,
534
+ description,
535
+ markdown: [
536
+ `# ${title}`,
537
+ `- Key: ${spec.meta.key}`,
538
+ `- Type: ${type}`,
539
+ `- Version: ${spec.meta.version}`,
540
+ route ? `- Docs route: ${route}` : "",
541
+ description ? `
542
+ ${description}` : ""
543
+ ].filter(Boolean).join(`
544
+ `),
545
+ ...route ? { route } : {},
546
+ ...schema ? { schema } : {},
547
+ ...policy ? { policy } : {},
548
+ tags: spec.meta.tags ?? [],
549
+ owners: spec.meta.owners ?? [],
550
+ stability: spec.meta.stability
551
+ };
552
+ }
553
+ function resolveContractReference(args) {
554
+ const includeSchema = args.includeSchema ?? false;
555
+ const requestedType = normalizeText2(args.type);
556
+ const operation = resolveOperationSpec(args.key, args.version);
557
+ if (operation && (!requestedType || requestedType === "operation" || requestedType === operation.meta.kind)) {
558
+ return {
559
+ reference: toReference(operation, operation.meta.kind, includeSchema ? resolveSerializedOperationSpec(args.key, args.version) : undefined, operation.policy)
560
+ };
561
+ }
562
+ const resolvers = [
563
+ {
564
+ type: "data-view",
565
+ spec: resolveDataViewSpec(args.key, args.version),
566
+ schema: includeSchema ? resolveSerializedDataViewSpec(args.key, args.version) : undefined
232
567
  },
233
- input: z.object({}),
234
- resolve: async () => {
235
- const docs = routes.map(({ block, route }) => ({
236
- id: block.id,
237
- title: block.title,
238
- summary: block.summary ?? "",
239
- tags: block.tags ?? [],
240
- visibility: block.visibility ?? "public",
241
- route
242
- }));
243
- return {
244
- uri: "docs://list",
245
- mimeType: "application/json",
246
- data: JSON.stringify(docs, null, 2)
247
- };
248
- }
249
- }));
250
- resources.register(defineResourceTemplate({
251
- meta: {
252
- uriTemplate: "docs://doc/{id}",
253
- title: "DocBlock markdown",
254
- description: "Fetch DocBlock body by id as markdown.",
255
- mimeType: "text/markdown",
256
- tags: DOC_TAGS
568
+ {
569
+ type: "form",
570
+ spec: resolveFormSpec(args.key, args.version),
571
+ schema: includeSchema ? resolveSerializedFormSpec(args.key, args.version) : undefined
257
572
  },
258
- input: z.object({ id: z.string() }),
259
- resolve: async ({ id }) => {
260
- const found = defaultDocRegistry.get(id);
261
- if (!found) {
262
- return {
263
- uri: `docs://doc/${encodeURIComponent(id)}`,
264
- mimeType: "text/plain",
265
- data: `DocBlock not found: ${id}`
266
- };
267
- }
573
+ {
574
+ type: "presentation",
575
+ spec: resolvePresentationSpec(args.key, args.version),
576
+ schema: includeSchema ? resolveSerializedPresentationSpec(args.key, args.version) : undefined
577
+ },
578
+ {
579
+ type: "event",
580
+ spec: resolveEventSpec(args.key, args.version),
581
+ schema: includeSchema ? resolveSerializedEventSpec(args.key, args.version) : undefined
582
+ }
583
+ ];
584
+ for (const candidate of resolvers) {
585
+ if (candidate.spec && (!requestedType || requestedType === candidate.type)) {
268
586
  return {
269
- uri: `docs://doc/${encodeURIComponent(id)}`,
270
- mimeType: "text/markdown",
271
- data: String(found.block.body ?? "")
587
+ reference: toReference(candidate.spec, candidate.type, candidate.schema)
272
588
  };
273
589
  }
274
- }));
275
- return resources;
590
+ }
591
+ throw new Error(`Contract reference not found: ${args.key}`);
276
592
  }
277
- function buildDocPrompts() {
593
+
594
+ // src/application/mcp/docsMcp.prompts.ts
595
+ import { definePrompt, PromptRegistry } from "@contractspec/lib.contracts-spec";
596
+ import z from "zod";
597
+ var DOC_OWNERS = ["@contractspec"];
598
+ var DOC_TAGS = ["docs", "mcp"];
599
+ function buildDocPrompts(routes) {
278
600
  const prompts = new PromptRegistry;
279
601
  prompts.register(definePrompt({
280
602
  meta: {
281
603
  key: "docs.navigator",
282
604
  version: "1.0.0",
283
605
  title: "Find relevant ContractSpec docs",
284
- description: "Guide agents to pick the right DocBlock by topic or tag.",
606
+ description: "Guide agents to search, filter, and open the right ContractSpec docs.",
285
607
  tags: DOC_TAGS,
286
608
  stability: "beta",
287
609
  owners: DOC_OWNERS
@@ -293,6 +615,12 @@ function buildDocPrompts() {
293
615
  required: false,
294
616
  schema: z.string().optional()
295
617
  },
618
+ {
619
+ name: "kind",
620
+ description: "Optional doc kind filter.",
621
+ required: false,
622
+ schema: z.string().optional()
623
+ },
296
624
  {
297
625
  name: "tag",
298
626
  description: "Optional tag filter.",
@@ -302,62 +630,409 @@ function buildDocPrompts() {
302
630
  ],
303
631
  input: z.object({
304
632
  topic: z.string().optional(),
633
+ kind: z.string().optional(),
305
634
  tag: z.string().optional()
306
635
  }),
307
- render: async ({ topic, tag }) => {
308
- const parts = [
636
+ render: async ({ topic, kind, tag }) => {
637
+ const matches = searchDocs(routes, {
638
+ query: topic,
639
+ kind,
640
+ tag,
641
+ limit: 3
642
+ });
643
+ const suggestedDocs = matches.docs.length ? matches.docs.map((doc) => `- ${doc.title} (${doc.id}) -> ${doc.route}`).join(`
644
+ `) : "- No direct pre-match. Use docs_list_facets-v1_0_0 to browse tags and kinds.";
645
+ return [
309
646
  {
310
647
  type: "text",
311
- text: `Use the docs index to choose DocBlocks. If a specific topic is provided, prefer docs whose id/title/summary match it.${topic ? ` Topic: ${topic}.` : ""}${tag ? ` Tag: ${tag}.` : ""}`
648
+ text: [
649
+ "Use docs_search-v1_0_0 first, then read docs://doc/{id} for the strongest matches.",
650
+ "Use docs_resolve_route-v1_0_0 when the user already gives you a docs URL or route.",
651
+ "Use docs_list_facets-v1_0_0 or docs://facets to browse the docs taxonomy before guessing.",
652
+ topic ? `Topic: ${topic}` : "",
653
+ kind ? `Kind: ${kind}` : "",
654
+ tag ? `Tag: ${tag}` : "",
655
+ "Suggested starting docs:",
656
+ suggestedDocs
657
+ ].filter(Boolean).join(`
658
+ `)
312
659
  },
313
660
  {
314
661
  type: "resource",
315
- uri: "docs://list",
662
+ uri: "docs://index",
316
663
  title: "DocBlocks index"
664
+ },
665
+ {
666
+ type: "resource",
667
+ uri: "docs://facets",
668
+ title: "Docs facets"
669
+ }
670
+ ];
671
+ }
672
+ }));
673
+ prompts.register(definePrompt({
674
+ meta: {
675
+ key: "docs.reference.guide",
676
+ version: "1.0.0",
677
+ title: "Resolve a ContractSpec reference",
678
+ description: "Guide agents to fetch the canonical reference payload for a ContractSpec surface.",
679
+ tags: DOC_TAGS,
680
+ stability: "beta",
681
+ owners: DOC_OWNERS
682
+ },
683
+ args: [
684
+ {
685
+ name: "key",
686
+ description: "ContractSpec key to resolve.",
687
+ required: true,
688
+ schema: z.string()
689
+ },
690
+ {
691
+ name: "version",
692
+ description: "Optional version override.",
693
+ required: false,
694
+ schema: z.string().optional()
695
+ },
696
+ {
697
+ name: "type",
698
+ description: "Optional surface type: command, query, form, data-view, presentation, event.",
699
+ required: false,
700
+ schema: z.string().optional()
701
+ }
702
+ ],
703
+ input: z.object({
704
+ key: z.string(),
705
+ version: z.string().optional(),
706
+ type: z.string().optional()
707
+ }),
708
+ render: async ({ key, version, type }) => {
709
+ const reference = resolveContractReference({
710
+ key,
711
+ version,
712
+ type,
713
+ includeSchema: true
714
+ }).reference;
715
+ return [
716
+ {
717
+ type: "text",
718
+ text: [
719
+ "Use docs_contract_reference-v1_0_0 when you need the canonical docs payload for a ContractSpec surface.",
720
+ "Use docs_get-v1_0_0 only when you already know the exact DocBlock id and need raw markdown.",
721
+ `Resolved key: ${reference.key}`,
722
+ `Resolved type: ${reference.type}`,
723
+ reference.route ? `Docs route: ${reference.route}` : "",
724
+ `Resource URI: docs://contract-reference/${encodeURIComponent(key)}`
725
+ ].filter(Boolean).join(`
726
+ `)
727
+ },
728
+ {
729
+ type: "resource",
730
+ uri: `docs://contract-reference/${encodeURIComponent(key)}`,
731
+ title: "Contract reference"
317
732
  }
318
733
  ];
319
- return parts;
320
734
  }
321
735
  }));
322
736
  return prompts;
323
737
  }
738
+
739
+ // src/application/mcp/docsMcp.resources.ts
740
+ import {
741
+ defineResourceTemplate,
742
+ ResourceRegistry
743
+ } from "@contractspec/lib.contracts-spec";
744
+ import z2 from "zod";
745
+ var DOC_TAGS2 = ["docs", "mcp"];
746
+ function buildDocResources(routes) {
747
+ const resources = new ResourceRegistry;
748
+ const readDocIndex = (input) => searchDocs(routes, input);
749
+ resources.register(defineResourceTemplate({
750
+ meta: {
751
+ uriTemplate: "docs://index",
752
+ title: "DocBlocks index",
753
+ description: "Default ContractSpec docs index resource.",
754
+ mimeType: "application/json",
755
+ tags: DOC_TAGS2
756
+ },
757
+ input: z2.object({}),
758
+ resolve: async () => ({
759
+ uri: "docs://index",
760
+ mimeType: "application/json",
761
+ data: JSON.stringify(readDocIndex({}), null, 2)
762
+ })
763
+ }));
764
+ resources.register(defineResourceTemplate({
765
+ meta: {
766
+ uriTemplate: "docs://index{?query,tag,kind,visibility,limit,offset}",
767
+ title: "DocBlocks index",
768
+ description: "Search and paginate ContractSpec docs by query, tag, kind, or visibility.",
769
+ mimeType: "application/json",
770
+ tags: DOC_TAGS2
771
+ },
772
+ input: z2.object({
773
+ query: z2.string().optional(),
774
+ tag: z2.string().optional(),
775
+ kind: z2.string().optional(),
776
+ visibility: z2.string().optional(),
777
+ limit: z2.coerce.number().optional(),
778
+ offset: z2.coerce.number().optional()
779
+ }),
780
+ resolve: async (input) => ({
781
+ uri: "docs://index",
782
+ mimeType: "application/json",
783
+ data: JSON.stringify(readDocIndex(input), null, 2)
784
+ })
785
+ }));
786
+ resources.register(defineResourceTemplate({
787
+ meta: {
788
+ uriTemplate: "docs://list",
789
+ title: "DocBlocks index (legacy alias)",
790
+ description: "Compatibility alias for the docs index resource.",
791
+ mimeType: "application/json",
792
+ tags: DOC_TAGS2
793
+ },
794
+ input: z2.object({}),
795
+ resolve: async () => ({
796
+ uri: "docs://list",
797
+ mimeType: "application/json",
798
+ data: JSON.stringify(readDocIndex({}), null, 2)
799
+ })
800
+ }));
801
+ resources.register(defineResourceTemplate({
802
+ meta: {
803
+ uriTemplate: "docs://doc/{id}",
804
+ title: "Doc markdown",
805
+ description: "Fetch a single DocBlock body by id as markdown.",
806
+ mimeType: "text/markdown",
807
+ tags: DOC_TAGS2
808
+ },
809
+ input: z2.object({ id: z2.string() }),
810
+ resolve: async ({ id }) => {
811
+ const found = getDocById(id);
812
+ if (!found) {
813
+ return {
814
+ uri: `docs://doc/${encodeURIComponent(id)}`,
815
+ mimeType: "text/plain",
816
+ data: `DocBlock not found: ${id}`
817
+ };
818
+ }
819
+ return {
820
+ uri: `docs://doc/${encodeURIComponent(id)}`,
821
+ mimeType: "text/markdown",
822
+ data: found.content
823
+ };
824
+ }
825
+ }));
826
+ resources.register(defineResourceTemplate({
827
+ meta: {
828
+ uriTemplate: "docs://route/{routePath}",
829
+ title: "Doc by route",
830
+ description: "Resolve a docs route to the matching DocBlock summary and body.",
831
+ mimeType: "application/json",
832
+ tags: DOC_TAGS2
833
+ },
834
+ input: z2.object({ routePath: z2.string() }),
835
+ resolve: async ({ routePath }) => ({
836
+ uri: `docs://route/${encodeURIComponent(routePath)}`,
837
+ mimeType: "application/json",
838
+ data: JSON.stringify(getDocByRoute(routes, routePath) ?? {
839
+ error: "not_found",
840
+ route: routePath
841
+ }, null, 2)
842
+ })
843
+ }));
844
+ resources.register(defineResourceTemplate({
845
+ meta: {
846
+ uriTemplate: "docs://facets",
847
+ title: "Docs facets",
848
+ description: "Counts of available tags, kinds, and visibilities across docs.",
849
+ mimeType: "application/json",
850
+ tags: DOC_TAGS2
851
+ },
852
+ input: z2.object({}),
853
+ resolve: async () => ({
854
+ uri: "docs://facets",
855
+ mimeType: "application/json",
856
+ data: JSON.stringify(listDocFacets(routes), null, 2)
857
+ })
858
+ }));
859
+ resources.register(defineResourceTemplate({
860
+ meta: {
861
+ uriTemplate: "docs://contract-reference/{key}{?version,type,includeSchema}",
862
+ title: "Contract reference",
863
+ description: "Resolve a ContractSpec surface into a docs-ready reference payload.",
864
+ mimeType: "application/json",
865
+ tags: DOC_TAGS2
866
+ },
867
+ input: z2.object({
868
+ key: z2.string(),
869
+ version: z2.string().optional(),
870
+ type: z2.string().optional(),
871
+ includeSchema: z2.coerce.boolean().optional()
872
+ }),
873
+ resolve: async ({ key, version, type, includeSchema }) => ({
874
+ uri: `docs://contract-reference/${encodeURIComponent(key)}`,
875
+ mimeType: "application/json",
876
+ data: JSON.stringify(resolveContractReference({ key, version, type, includeSchema }), null, 2)
877
+ })
878
+ }));
879
+ return resources;
880
+ }
881
+
882
+ // src/application/mcp/docsMcp.tools.ts
883
+ import {
884
+ defineCommand,
885
+ defineSchemaModel,
886
+ installOp,
887
+ OperationSpecRegistry as OperationSpecRegistry2
888
+ } from "@contractspec/lib.contracts-spec";
889
+ import {
890
+ ContractReferenceInput,
891
+ ContractReferenceOutput,
892
+ DocsIndexInput,
893
+ DocsIndexOutput
894
+ } from "@contractspec/lib.contracts-spec/docs";
895
+ import { ScalarTypeEnum } from "@contractspec/lib.schema";
896
+ var DOC_OWNERS2 = ["@contractspec"];
897
+ var DOC_TAGS3 = ["docs", "mcp"];
898
+ var DocsGetInput = defineSchemaModel({
899
+ name: "DocsGetInput",
900
+ fields: {
901
+ id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
902
+ }
903
+ });
904
+ var DocsGetOutput = defineSchemaModel({
905
+ name: "DocsGetOutput",
906
+ fields: {
907
+ doc: { type: ScalarTypeEnum.JSON(), isOptional: false },
908
+ content: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
909
+ }
910
+ });
911
+ var DocsResolveRouteInput = defineSchemaModel({
912
+ name: "DocsResolveRouteInput",
913
+ fields: {
914
+ route: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
915
+ }
916
+ });
917
+ var DocsResolveRouteOutput = defineSchemaModel({
918
+ name: "DocsResolveRouteOutput",
919
+ fields: {
920
+ doc: { type: ScalarTypeEnum.JSON(), isOptional: false },
921
+ content: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
922
+ }
923
+ });
924
+ var DocsFacetsInput = defineSchemaModel({
925
+ name: "DocsFacetsInput",
926
+ fields: {}
927
+ });
928
+ var DocsFacetsOutput = defineSchemaModel({
929
+ name: "DocsFacetsOutput",
930
+ fields: {
931
+ facets: { type: ScalarTypeEnum.JSON(), isOptional: false }
932
+ }
933
+ });
324
934
  function buildDocOps(routes) {
325
- const registry = new OperationSpecRegistry;
326
- installOp(registry, DocsIndexQuery, async (args) => {
327
- const query = args.query?.toLowerCase().trim();
328
- const tagsFilter = args.tag?.map((t) => t.toLowerCase().trim()) ?? [];
329
- const visibility = args.visibility?.toLowerCase().trim();
330
- const docs = routes.map(({ block, route }) => ({
331
- id: block.id,
332
- title: block.title,
333
- summary: block.summary ?? "",
334
- tags: block.tags ?? [],
335
- visibility: (block.visibility ?? "public").toLowerCase(),
336
- route
337
- })).filter((doc) => {
338
- const matchesQuery = query ? doc.id.toLowerCase().includes(query) || doc.title.toLowerCase().includes(query) || doc.summary.toLowerCase().includes(query) : true;
339
- const matchesTags = tagsFilter.length ? tagsFilter.every((t) => doc.tags.some((tag) => tag.toLowerCase().includes(t))) : true;
340
- const matchesVisibility = visibility ? doc.visibility === visibility : true;
341
- return matchesQuery && matchesTags && matchesVisibility;
342
- });
343
- return {
344
- docs,
345
- items: docs,
346
- total: docs.length
347
- };
935
+ const registry = new OperationSpecRegistry2;
936
+ installOp(registry, defineCommand({
937
+ meta: {
938
+ key: "docs.search",
939
+ version: "1.0.0",
940
+ stability: "beta",
941
+ owners: DOC_OWNERS2,
942
+ tags: DOC_TAGS3,
943
+ description: "Search ContractSpec docs by query, tag, kind, or visibility.",
944
+ goal: "Find the most relevant DocBlocks without browsing the full corpus.",
945
+ context: "Read-only docs MCP search surface."
946
+ },
947
+ io: { input: DocsIndexInput, output: DocsIndexOutput },
948
+ policy: { auth: "anonymous" },
949
+ transport: { mcp: { toolName: "docs_search-v1_0_0" } }
950
+ }), async (args) => searchDocs(routes, args));
951
+ installOp(registry, defineCommand({
952
+ meta: {
953
+ key: "docs.get",
954
+ version: "1.0.0",
955
+ stability: "beta",
956
+ owners: DOC_OWNERS2,
957
+ tags: DOC_TAGS3,
958
+ description: "Read a single DocBlock by id.",
959
+ goal: "Fetch the exact markdown content and metadata for a known doc id.",
960
+ context: "Read-only docs MCP surface."
961
+ },
962
+ io: { input: DocsGetInput, output: DocsGetOutput },
963
+ policy: { auth: "anonymous" },
964
+ transport: { mcp: { toolName: "docs_get-v1_0_0" } }
965
+ }), async ({ id }) => {
966
+ const found = getDocById(id);
967
+ if (!found)
968
+ throw new Error(`DocBlock not found: ${id}`);
969
+ return found;
970
+ });
971
+ installOp(registry, defineCommand({
972
+ meta: {
973
+ key: "docs.resolveRoute",
974
+ version: "1.0.0",
975
+ stability: "beta",
976
+ owners: DOC_OWNERS2,
977
+ tags: DOC_TAGS3,
978
+ description: "Resolve a docs route to the matching DocBlock.",
979
+ goal: "Turn a route or URL path into a canonical doc id and markdown body.",
980
+ context: "Read-only docs MCP surface."
981
+ },
982
+ io: { input: DocsResolveRouteInput, output: DocsResolveRouteOutput },
983
+ policy: { auth: "anonymous" },
984
+ transport: { mcp: { toolName: "docs_resolve_route-v1_0_0" } }
985
+ }), async ({ route }) => {
986
+ const found = getDocByRoute(routes, route);
987
+ if (!found)
988
+ throw new Error(`Doc route not found: ${route}`);
989
+ return found;
348
990
  });
991
+ installOp(registry, defineCommand({
992
+ meta: {
993
+ key: "docs.contract.lookup",
994
+ version: "1.0.0",
995
+ stability: "beta",
996
+ owners: DOC_OWNERS2,
997
+ tags: DOC_TAGS3,
998
+ description: "Resolve a ContractSpec surface into a docs-ready reference payload.",
999
+ goal: "Get canonical docs metadata, route, and optional schema for a spec key.",
1000
+ context: "Read-only docs MCP surface."
1001
+ },
1002
+ io: { input: ContractReferenceInput, output: ContractReferenceOutput },
1003
+ policy: { auth: "anonymous" },
1004
+ transport: { mcp: { toolName: "docs_contract_reference-v1_0_0" } }
1005
+ }), async (args) => resolveContractReference(args));
1006
+ installOp(registry, defineCommand({
1007
+ meta: {
1008
+ key: "docs.list.facets",
1009
+ version: "1.0.0",
1010
+ stability: "beta",
1011
+ owners: DOC_OWNERS2,
1012
+ tags: DOC_TAGS3,
1013
+ description: "List docs taxonomy facets such as tags, kinds, and visibilities.",
1014
+ goal: "Help agents browse the docs corpus before making targeted reads.",
1015
+ context: "Read-only docs MCP surface."
1016
+ },
1017
+ io: { input: DocsFacetsInput, output: DocsFacetsOutput },
1018
+ policy: { auth: "anonymous" },
1019
+ transport: { mcp: { toolName: "docs_list_facets-v1_0_0" } }
1020
+ }), async () => ({ facets: listDocFacets(routes) }));
349
1021
  return registry;
350
1022
  }
351
- function createDocsMcpHandler(path = "/api/mcp/docs") {
352
- const routes = defaultDocRegistry.list();
1023
+
1024
+ // src/application/mcp/docsMcp.ts
1025
+ import { defaultDocRegistry as defaultDocRegistry3 } from "@contractspec/lib.contracts-spec/docs";
1026
+ function createDocsMcpHandler(path = "/api/mcp/docs", options = {}) {
1027
+ const routes = defaultDocRegistry3.list();
353
1028
  return createMcpElysiaHandler({
354
1029
  logger: appLogger,
355
1030
  path,
356
1031
  serverName: "contractspec-docs-mcp",
357
1032
  ops: buildDocOps(routes),
358
1033
  resources: buildDocResources(routes),
359
- prompts: buildDocPrompts(),
360
- presentations: routes.map(({ descriptor }) => descriptor)
1034
+ prompts: buildDocPrompts(routes),
1035
+ presentations: options.includePresentations ? routes.map(({ descriptor }) => descriptor) : undefined
361
1036
  });
362
1037
  }
363
1038
  export {