@atolis-hq/corum 0.1.38 → 0.1.40

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,60 @@
1
+ /**
2
+ * Shared helper for resolving a template's flattened property-schema map.
3
+ *
4
+ * Templates express inheritance via nested `allOf` (see ADR-008): a
5
+ * template's `properties` block is either a plain JSON-schema-like object
6
+ * with a `properties` map, or an `allOf` array of such objects (accumulated
7
+ * from `extends` resolution at pack-load time). This walks that structure
8
+ * and merges all declared properties into a single flat map, keyed by
9
+ * property name.
10
+ *
11
+ * Used by both the cluster loader (to find node-ref targets) and the linter
12
+ * (to validate node properties against their owning template's schema).
13
+ */
14
+ export function getPropertySchemasFromTemplate(props) {
15
+ if (Array.isArray(props.allOf)) {
16
+ const merged = {};
17
+ for (const schema of props.allOf) {
18
+ Object.assign(merged, getPropertySchemasFromTemplate(schema));
19
+ }
20
+ return merged;
21
+ }
22
+ if (typeof props.properties === 'object' && props.properties !== null) {
23
+ return props.properties;
24
+ }
25
+ return {};
26
+ }
27
+ /**
28
+ * Merge a template's `properties` block (including its `allOf` inheritance
29
+ * chain) into a flat schema view: the combined property map, the union of
30
+ * all `required` lists, and whether unknown properties are disallowed
31
+ * anywhere in the chain. Used by the linter for shallow property validation.
32
+ */
33
+ export function getTemplateSchema(templateProperties) {
34
+ const properties = {};
35
+ const required = new Set();
36
+ let additionalProperties = true;
37
+ const walk = (props) => {
38
+ if (typeof props !== 'object' || props === null)
39
+ return;
40
+ const record = props;
41
+ if (Array.isArray(record.allOf)) {
42
+ for (const schema of record.allOf)
43
+ walk(schema);
44
+ return;
45
+ }
46
+ if (typeof record.properties === 'object' && record.properties !== null) {
47
+ Object.assign(properties, record.properties);
48
+ }
49
+ if (Array.isArray(record.required)) {
50
+ for (const name of record.required) {
51
+ if (typeof name === 'string')
52
+ required.add(name);
53
+ }
54
+ }
55
+ if (record.additionalProperties === false)
56
+ additionalProperties = false;
57
+ };
58
+ walk(templateProperties);
59
+ return { properties, required, additionalProperties };
60
+ }
@@ -3,27 +3,14 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
4
  import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { pathToFileURL } from 'node:url';
6
- import { computeClusterOverlay, getClusterView, getGraphSummary, getLineage, getLinkedFields, listNodes, SEMANTIC_EDGE_TYPES, searchNodes, STRUCTURAL_NODE_TEMPLATES, } from '../graph/index.js';
6
+ import { computeClusterOverlay, expandExternalNodes, getClusterView, getGraphSummary, getLineage, getLinkedFields, getStructuralNodeTemplates, getVisibleEdgeTypes, isVisibleEdgeType, listNodes, searchNodes, } from '../graph/index.js';
7
7
  import { loadGraph, loadMultiGraph } from '../loader/index.js';
8
8
  import { QueryError } from '../schema/index.js';
9
9
  import { createGraphRuntimeConfig } from '../source/config.js';
10
- import { startGraphFileWatcher, startWebServer } from '../web/server.js';
10
+ import { createMultiGraphCache, replaceGraph, startGraphFileWatcher, startWebServer } from '../web/server.js';
11
11
  import { USAGE_GUIDE_PROMPT } from './prompts/usage-guide.js';
12
12
  import { collapseClusterSchemas } from '../graph/schema-collapse.js';
13
13
  import { compactKeys, getSerializer } from './serializers.js';
14
- const EDGE_TYPES = [
15
- 'triggers',
16
- 'produces',
17
- 'reads',
18
- 'calls',
19
- 'implements',
20
- 'maps-to',
21
- 'derived-from',
22
- 'renamed-from',
23
- 'has-field',
24
- 'has-value',
25
- ];
26
- const EDGE_TYPE_SET = new Set(EDGE_TYPES);
27
14
  const STATE_VALUES = ['draft', 'proposed', 'agreed', 'future', 'removed', 'implemented'];
28
15
  const STABILITY_VALUES = ['unstable', 'stable', 'deprecated'];
29
16
  const LINEAGE_DIRECTIONS = ['downstream', 'upstream', 'both'];
@@ -31,11 +18,14 @@ const OUTPUT_FORMATS = ['yaml', 'json', 'toon'];
31
18
  function toStringArray(value) {
32
19
  return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : undefined;
33
20
  }
34
- function parseEdgeTypes(value) {
21
+ function parseEdgeTypes(value, graph) {
35
22
  const requested = toStringArray(value);
36
23
  if (!requested)
37
24
  return undefined;
38
- const invalid = requested.filter(type => !EDGE_TYPE_SET.has(type));
25
+ const known = graph.edgeTypes;
26
+ const invalid = known
27
+ ? requested.filter(type => !known.has(type))
28
+ : [];
39
29
  if (invalid.length > 0) {
40
30
  throw new QueryError(`Unknown edge type: ${invalid.join(', ')}`);
41
31
  }
@@ -89,18 +79,16 @@ function fullNode(node, includeProvenance) {
89
79
  ...(includeProvenance ? withProvenance(node) : {}),
90
80
  };
91
81
  }
92
- function mapEdge(edge, includeProvenance) {
93
- const out = {
94
- id: edge.id,
95
- from: edge.from,
96
- to: edge.to,
97
- type: edge.type,
98
- state: edge.state,
99
- stability: edge.stability,
100
- };
82
+ function mapEdge(edge, options = {}) {
83
+ const out = {};
84
+ if (options.includeId)
85
+ out.id = edge.id;
86
+ out.from = edge.from;
87
+ out.to = edge.to;
88
+ out.type = edge.type;
101
89
  if (edge.notes !== undefined)
102
90
  out.notes = edge.notes;
103
- if (includeProvenance) {
91
+ if (options.includeProvenance) {
104
92
  if (edge.derivation !== undefined)
105
93
  out.derivation = edge.derivation;
106
94
  if (edge.derivedBy !== undefined)
@@ -108,6 +96,12 @@ function mapEdge(edge, includeProvenance) {
108
96
  }
109
97
  return out;
110
98
  }
99
+ function getEdgeOutputOptions(args) {
100
+ return {
101
+ includeProvenance: includesProvenance(args),
102
+ includeId: args.include_edge_ids === true,
103
+ };
104
+ }
111
105
  function mapLineageNode(node, includeProvenance, lean) {
112
106
  const base = {
113
107
  id: String(node.id),
@@ -146,7 +140,7 @@ export function createMcpHandlers(graph, source, cache) {
146
140
  return formatResult(summaries, args.format, getCompactKeys(args));
147
141
  };
148
142
  if (hasBranch(args)) {
149
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
143
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
150
144
  }
151
145
  try {
152
146
  return run(graph);
@@ -158,7 +152,7 @@ export function createMcpHandlers(graph, source, cache) {
158
152
  get_graph_summary(args) {
159
153
  const run = (targetGraph) => formatResult(getGraphSummary(targetGraph), args.format, getCompactKeys(args));
160
154
  if (hasBranch(args) && source) {
161
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
155
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
162
156
  }
163
157
  try {
164
158
  return run(graph);
@@ -192,7 +186,7 @@ export function createMcpHandlers(graph, source, cache) {
192
186
  return formatResult(results, args.format, getCompactKeys(args));
193
187
  };
194
188
  if (hasBranch(args) && source) {
195
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
189
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
196
190
  }
197
191
  try {
198
192
  return run(graph);
@@ -216,7 +210,7 @@ export function createMcpHandlers(graph, source, cache) {
216
210
  return formatResult(summaries, args.format, getCompactKeys(args));
217
211
  };
218
212
  if (hasBranch(args) && source) {
219
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
213
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
220
214
  }
221
215
  try {
222
216
  return run(graph);
@@ -243,31 +237,71 @@ export function createMcpHandlers(graph, source, cache) {
243
237
  ? args.overlay_refs.filter((ref) => typeof ref === 'string')
244
238
  : [];
245
239
  const run = async (targetGraph, branchRef) => {
246
- const edgeTypes = parseEdgeTypes(args.edge_types)
247
- ?? [...SEMANTIC_EDGE_TYPES];
248
- const cluster = getClusterView(targetGraph, String(args.node_id), edgeTypes);
240
+ const edgeTypes = parseEdgeTypes(args.edge_types, targetGraph)
241
+ ?? getVisibleEdgeTypes(targetGraph);
242
+ const rawCluster = getClusterView(targetGraph, String(args.node_id), edgeTypes);
243
+ const clusterIds = new Set([rawCluster.root.id, ...rawCluster.descendants.map(n => n.id)]);
244
+ const externalIds = new Set();
245
+ for (const edge of rawCluster.edges) {
246
+ if (!clusterIds.has(edge.from))
247
+ externalIds.add(edge.from);
248
+ if (!clusterIds.has(edge.to))
249
+ externalIds.add(edge.to);
250
+ }
251
+ const cluster = { ...rawCluster, includedNodes: expandExternalNodes(targetGraph, externalIds) };
249
252
  const includeProvenance = includesProvenance(args);
250
253
  const collapseSchemas = args.collapse_schemas !== false;
254
+ const includeEdges = args.include_edges === true;
255
+ const includeDescendants = args.include_descendants !== false;
256
+ const nodeTypes = toStringArray(args.node_types);
257
+ const edgeOptions = getEdgeOutputOptions(args);
251
258
  let clusterPayload;
252
259
  if (collapseSchemas) {
253
260
  const collapsed = collapseClusterSchemas(targetGraph, cluster);
261
+ let filteredDescendants = collapsed.descendants;
262
+ let filteredIncludedNodes = collapsed.includedNodes;
263
+ if (!includeDescendants) {
264
+ filteredDescendants = [];
265
+ filteredIncludedNodes = [];
266
+ }
267
+ else if (nodeTypes) {
268
+ const typeSet = new Set(nodeTypes);
269
+ filteredDescendants = filteredDescendants.filter(n => typeSet.has(n.template));
270
+ filteredIncludedNodes = filteredIncludedNodes.filter(n => typeSet.has(n.template));
271
+ }
272
+ const mergedSchemas = { ...collapsed.schemas, ...collapsed.schemaEnums };
254
273
  clusterPayload = {
255
274
  root: {
256
275
  ...fullNode(collapsed.root, includeProvenance),
257
- ...(Object.keys(collapsed.schemas).length > 0 ? { schemas: collapsed.schemas } : {}),
276
+ ...(Object.keys(mergedSchemas).length > 0 ? { schemas: mergedSchemas } : {}),
258
277
  ...(Object.keys(collapsed.enums).length > 0 ? { enums: collapsed.enums } : {}),
259
278
  },
260
- descendants: collapsed.descendants.map(node => fullNode(node, includeProvenance)),
261
- includedNodes: collapsed.includedNodes.map(node => fullNode(node, includeProvenance)),
262
- edges: collapsed.edges.map(e => mapEdge(e, includeProvenance)),
279
+ ...(includeDescendants ? {
280
+ descendants: filteredDescendants.map(node => fullNode(node, includeProvenance)),
281
+ includedNodes: filteredIncludedNodes.map(node => fullNode(node, includeProvenance)),
282
+ } : {}),
283
+ ...(includeEdges ? { edges: collapsed.edges.map(e => mapEdge(e, edgeOptions)) } : {}),
263
284
  };
264
285
  }
265
286
  else {
287
+ let filteredDescendants = cluster.descendants;
288
+ let filteredIncludedNodes = cluster.includedNodes;
289
+ if (!includeDescendants) {
290
+ filteredDescendants = [];
291
+ filteredIncludedNodes = [];
292
+ }
293
+ else if (nodeTypes) {
294
+ const typeSet = new Set(nodeTypes);
295
+ filteredDescendants = filteredDescendants.filter(n => typeSet.has(n.template));
296
+ filteredIncludedNodes = filteredIncludedNodes.filter(n => typeSet.has(n.template));
297
+ }
266
298
  clusterPayload = {
267
299
  root: fullNode(cluster.root, includeProvenance),
268
- descendants: cluster.descendants.map(node => fullNode(node, includeProvenance)),
269
- includedNodes: cluster.includedNodes.map(node => fullNode(node, includeProvenance)),
270
- edges: cluster.edges.map(e => mapEdge(e, includeProvenance)),
300
+ ...(includeDescendants ? {
301
+ descendants: filteredDescendants.map(node => fullNode(node, includeProvenance)),
302
+ includedNodes: filteredIncludedNodes.map(node => fullNode(node, includeProvenance)),
303
+ } : {}),
304
+ ...(includeEdges ? { edges: cluster.edges.map(e => mapEdge(e, edgeOptions)) } : {}),
271
305
  };
272
306
  }
273
307
  if (overlayRefs.length === 0 || !source || !branchRef) {
@@ -287,7 +321,7 @@ export function createMcpHandlers(graph, source, cache) {
287
321
  const run = (targetGraph) => {
288
322
  const filter = parseListNodesFilter(args.filter);
289
323
  const effectiveFilter = (!filter.templates?.length && !filter.excludeTemplates?.length)
290
- ? { ...filter, excludeTemplates: [...STRUCTURAL_NODE_TEMPLATES] }
324
+ ? { ...filter, excludeTemplates: [...getStructuralNodeTemplates(targetGraph)] }
291
325
  : filter;
292
326
  const nodes = listNodes(targetGraph, effectiveFilter)
293
327
  .map(node => summarizeNode(node, includesProvenance(args)));
@@ -297,7 +331,7 @@ export function createMcpHandlers(graph, source, cache) {
297
331
  const edges = [];
298
332
  for (const edgeList of targetGraph.edgesByFrom.values()) {
299
333
  for (const edge of edgeList) {
300
- if (!SEMANTIC_EDGE_TYPES.has(edge.type) || !nodeIds.has(edge.from) || !nodeIds.has(edge.to))
334
+ if (!isVisibleEdgeType(targetGraph, edge.type) || !nodeIds.has(edge.from) || !nodeIds.has(edge.to))
301
335
  continue;
302
336
  edges.push({ id: edge.id, from: edge.from, to: edge.to, type: edge.type });
303
337
  }
@@ -307,7 +341,7 @@ export function createMcpHandlers(graph, source, cache) {
307
341
  return formatResult(payload, args.format, getCompactKeys(args));
308
342
  };
309
343
  if (hasBranch(args) && source) {
310
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
344
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
311
345
  }
312
346
  try {
313
347
  return run(graph);
@@ -332,7 +366,7 @@ export function createMcpHandlers(graph, source, cache) {
332
366
  node_templates_in_use: [...nodeTemplatesInUse].sort(),
333
367
  edge_types_in_use: [...edgeTypesInUse].sort(),
334
368
  ...(includeStatic ? {
335
- valid_edge_types: [...EDGE_TYPES],
369
+ valid_edge_types: [...(targetGraph.edgeTypes?.keys() ?? [])],
336
370
  states: [...STATE_VALUES],
337
371
  stabilities: [...STABILITY_VALUES],
338
372
  lineage_directions: [...LINEAGE_DIRECTIONS],
@@ -341,7 +375,7 @@ export function createMcpHandlers(graph, source, cache) {
341
375
  }, args.format, getCompactKeys(args));
342
376
  };
343
377
  if (hasBranch(args) && source) {
344
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
378
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
345
379
  }
346
380
  try {
347
381
  return run(graph);
@@ -363,7 +397,7 @@ export function createMcpHandlers(graph, source, cache) {
363
397
  const options = {
364
398
  depth: typeof args.depth === 'number' ? args.depth : 2,
365
399
  direction,
366
- edgeTypes: parseEdgeTypes(args.edge_types),
400
+ edgeTypes: parseEdgeTypes(args.edge_types, targetGraph),
367
401
  nodeTypes: toStringArray(args.node_types),
368
402
  excludeNodeTypes: toStringArray(args.exclude_node_types),
369
403
  includeDanglingEdges: args.include_dangling_edges === true,
@@ -373,17 +407,18 @@ export function createMcpHandlers(graph, source, cache) {
373
407
  const lean = args.lean !== false;
374
408
  const includeEdges = args.include_edges === true;
375
409
  const includeProvenance = includesProvenance(args);
410
+ const edgeOptions = getEdgeOutputOptions(args);
376
411
  const payload = {
377
412
  nodes: lineage.nodes.map(node => mapLineageNode(node, includeProvenance, lean)),
378
413
  };
379
414
  if (includeEdges)
380
- payload.edges = lineage.edges.map(e => mapEdge(e, includeProvenance));
415
+ payload.edges = lineage.edges.map(e => mapEdge(e, edgeOptions));
381
416
  if (args.include_dangling_edges === true && lineage.dangling_edges)
382
417
  payload.dangling_edges = lineage.dangling_edges;
383
418
  return formatResult(payload, args.format, getCompactKeys(args));
384
419
  };
385
420
  if (hasBranch(args) && source) {
386
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
421
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
387
422
  }
388
423
  try {
389
424
  return run(graph);
@@ -396,13 +431,14 @@ export function createMcpHandlers(graph, source, cache) {
396
431
  const run = (targetGraph) => {
397
432
  const linked = getLinkedFields(targetGraph, String(args.node_id));
398
433
  const incProv = includesProvenance(args);
434
+ const edgeOptions = getEdgeOutputOptions(args);
399
435
  return formatResult({
400
- edges: linked.edges.map(e => mapEdge(e, incProv)),
436
+ edges: linked.edges.map(e => mapEdge(e, edgeOptions)),
401
437
  nodes: linked.nodes.map(node => fullNode(node, incProv)),
402
438
  }, args.format, getCompactKeys(args));
403
439
  };
404
440
  if (hasBranch(args)) {
405
- return withBranchGraph(source, String(args.branch), branch => run(branch.graph));
441
+ return withBranchGraph(source, String(args.branch), branch => run(branch.graph), cache);
406
442
  }
407
443
  try {
408
444
  return run(graph);
@@ -461,6 +497,26 @@ async function withBranchGraph(source, branchRef, fn, cache) {
461
497
  function hasBranch(args) {
462
498
  return typeof args.branch === 'string' && args.branch.length > 0;
463
499
  }
500
+ /**
501
+ * Retries a previously-failed graph load. Only attempts the load when `loadError` is set —
502
+ * a healthy graph is never re-loaded on the hot call path. On success, `graph` is mutated in
503
+ * place (via `replaceGraph`) so existing closures over it observe the fresh data, and
504
+ * `onReload` fires so callers can invalidate any dependent caches (e.g. a MultiGraphCache).
505
+ * Returns the resulting error, if any (undefined once recovered).
506
+ */
507
+ export async function ensureGraphLoaded(graph, loadError, loader, onReload) {
508
+ if (!loadError)
509
+ return undefined;
510
+ try {
511
+ const fresh = await loader();
512
+ replaceGraph(graph, fresh);
513
+ onReload?.();
514
+ return undefined;
515
+ }
516
+ catch (err) {
517
+ return String(err);
518
+ }
519
+ }
464
520
  function formatResult(value, format, compact = false) {
465
521
  const payload = compact === true ? compactKeys(value) : value;
466
522
  return { content: [{ type: 'text', text: getSerializer(format).serialize(payload) }] };
@@ -539,7 +595,7 @@ export function getMcpToolDefinitions() {
539
595
  },
540
596
  {
541
597
  name: 'get_cluster',
542
- description: 'Use when you need the full structural contents of a single node - its schema, fields, and owned children. Not suited for following relationships across the graph; use get_lineage for that. Note: large aggregates may exceed response size limits.',
598
+ description: 'Use when you need the full structural contents of a single node - its schema, fields, and owned children. Not suited for following relationships across the graph; use get_lineage for that.\n\nBy default returns only the root node with its collapsed schema and enums blocks (descendants and edges excluded). Pass include_descendants: true to include owned operations/commands/events. Pass include_edges: true to include the edge list.',
543
599
  inputSchema: {
544
600
  type: 'object',
545
601
  required: ['node_id'],
@@ -550,9 +606,15 @@ export function getMcpToolDefinitions() {
550
606
  items: { type: 'string' },
551
607
  description: 'Edge types to follow for external node inclusion. Defaults to all semantic types.',
552
608
  },
553
- include_dangling_edges: { type: 'boolean', description: 'Include edges to nodes outside the cluster. Default false.' },
554
- reads_outbound_only: { type: 'boolean', description: 'Restrict reads edges to outbound only. Default true.' },
555
609
  collapse_schemas: { type: 'boolean', description: 'Collapse schema/enum child nodes into compact schemas and enums blocks on the root. Structural edges and schema child nodes are removed from descendants. Default true.' },
610
+ include_descendants: { type: 'boolean', description: 'Include descendant nodes (operations, commands, events, and cross-component nodes). Default true.' },
611
+ node_types: {
612
+ type: 'array',
613
+ items: { type: 'string' },
614
+ description: 'Allowlist of node templates to include in the descendant set. Useful for limiting to specific types (e.g. ["DomainOperation", "DomainEvent"]).',
615
+ },
616
+ include_edges: { type: 'boolean', description: 'Include the edge list in the response. Default false.' },
617
+ include_edge_ids: { type: 'boolean', description: 'Include edge id field in edge output. Default false.' },
556
618
  include_provenance: { type: 'boolean', description: 'Include provenance fields on returned nodes. Default false.' },
557
619
  branch: { type: 'string', description: 'Branch ref to load the cluster from' },
558
620
  overlay_refs: {
@@ -620,9 +682,10 @@ export function getMcpToolDefinitions() {
620
682
  node_types: { type: 'array', items: { type: 'string' }, description: 'Allowlist of node templates.' },
621
683
  exclude_node_types: { type: 'array', items: { type: 'string' }, description: 'Denylist of node templates.' },
622
684
  include_dangling_edges: { type: 'boolean', description: 'Include dangling edges in the response when present. Default false.' },
623
- reads_outbound_only: { type: 'boolean', description: 'Do not follow inbound reads edges in upstream traversal. Default true.' },
685
+ reads_outbound_only: { type: 'boolean', description: 'Do not follow inbound reads/uses-type edges in upstream traversal. Default true.' },
624
686
  lean: { type: 'boolean', description: 'Return minimal lineage node shape. Default true.' },
625
687
  include_edges: { type: 'boolean', description: 'Include the edges list in the response. Default false.' },
688
+ include_edge_ids: { type: 'boolean', description: 'Include edge id field in edge output. Default false.' },
626
689
  include_provenance: { type: 'boolean', description: 'Include provenance fields on returned nodes. Default false.' },
627
690
  branch: { type: 'string', description: 'Branch ref to load the lineage from' },
628
691
  format: { type: 'string', enum: ['yaml', 'json', 'toon'], description: 'Output format. Defaults to yaml.' },
@@ -638,6 +701,7 @@ export function getMcpToolDefinitions() {
638
701
  required: ['node_id'],
639
702
  properties: {
640
703
  node_id: { type: 'string', description: 'Fully qualified root node ID' },
704
+ include_edge_ids: { type: 'boolean', description: 'Include edge id field in edge output. Default false.' },
641
705
  include_provenance: { type: 'boolean', description: 'Include provenance fields on returned nodes. Default false.' },
642
706
  branch: { type: 'string', description: 'Branch ref to load linked fields from' },
643
707
  format: { type: 'string', enum: ['yaml', 'json', 'toon'], description: 'Output format. Defaults to yaml.' },
@@ -726,16 +790,26 @@ export async function startMcpServer(options = {}) {
726
790
  diagnostics: [],
727
791
  };
728
792
  }
729
- const handlers = createMcpHandlers(graph, config.source);
793
+ const mcpCache = config.source ? createMultiGraphCache(config.source) : undefined;
794
+ const handlers = createMcpHandlers(graph, config.source, mcpCache);
730
795
  if (!noWeb) {
731
- await startWebServer(graph, {
732
- graphPath: config.graphPath,
733
- fileWatcher: config.fileWatcherGraphPath && watch ? true : undefined,
734
- source: config.source,
735
- });
796
+ try {
797
+ await startWebServer(graph, {
798
+ graphPath: config.graphPath,
799
+ fileWatcher: config.fileWatcherGraphPath && watch ? true : undefined,
800
+ source: config.source,
801
+ onReload: () => mcpCache?.invalidate(),
802
+ });
803
+ }
804
+ catch (err) {
805
+ process.stderr.write(`[corum] web server failed to start, continuing MCP-only: ${err}\n`);
806
+ }
736
807
  }
737
808
  else if (watch && config.fileWatcherGraphPath) {
738
- startGraphFileWatcher(graph, { graphPath: config.fileWatcherGraphPath });
809
+ startGraphFileWatcher(graph, {
810
+ graphPath: config.fileWatcherGraphPath,
811
+ onReload: () => mcpCache?.invalidate(),
812
+ });
739
813
  }
740
814
  const server = new Server({ name: 'corum', version: '0.1.0' }, { capabilities: { tools: {}, prompts: {} } });
741
815
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({
@@ -761,6 +835,7 @@ export async function startMcpServer(options = {}) {
761
835
  tools: getMcpToolDefinitions(),
762
836
  }));
763
837
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
838
+ loadError = await ensureGraphLoaded(graph, loadError, () => loadGraph({ source: config.source, strict: true }), () => mcpCache?.invalidate());
764
839
  if (loadError) {
765
840
  return { content: [{ type: 'text', text: `Graph load error: ${loadError}` }], isError: true };
766
841
  }
@@ -69,6 +69,7 @@ export function compactKeys(value) {
69
69
  }
70
70
  return Object.fromEntries(Object.entries(value).map(([key, child]) => [
71
71
  COMPACT_KEY_MAP[key] ?? key,
72
- compactKeys(child),
72
+ // `properties` values are user-authored data; compact envelope keys only.
73
+ key === 'properties' ? child : compactKeys(child),
73
74
  ]));
74
75
  }
@@ -1,6 +1,12 @@
1
1
  import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { parse } from 'yaml';
4
+ import { resolveContentPath } from '../source/safe-path.js';
5
+ function validateTemplateName(name) {
6
+ if (!/^[^/\\]+$/.test(name) || name === '.' || name === '..') {
7
+ throw new Error(`invalid template name in pack.yaml: ${name}`);
8
+ }
9
+ }
4
10
  export async function installPackFiles(baseUrl, destDir, fetchFn = fetch) {
5
11
  const packYamlUrl = `${baseUrl}/pack.yaml`;
6
12
  const packRes = await fetchFn(packYamlUrl);
@@ -8,6 +14,14 @@ export async function installPackFiles(baseUrl, destDir, fetchFn = fetch) {
8
14
  throw new Error(`Failed to fetch pack.yaml: ${packRes.status} ${packRes.statusText}`);
9
15
  const packText = await packRes.text();
10
16
  const meta = parse(packText);
17
+ // Remote pack.yaml content is untrusted: validate every declared name/path
18
+ // before any file is written so a malicious pack cannot escape destDir.
19
+ for (const templateName of meta.templates)
20
+ validateTemplateName(templateName);
21
+ const fileDests = new Map();
22
+ for (const filePath of meta.files ?? []) {
23
+ fileDests.set(filePath, resolveContentPath(destDir, filePath));
24
+ }
11
25
  await mkdir(path.join(destDir, 'templates'), { recursive: true });
12
26
  await writeFile(path.join(destDir, 'pack.yaml'), packText);
13
27
  for (const templateName of meta.templates) {
@@ -17,12 +31,11 @@ export async function installPackFiles(baseUrl, destDir, fetchFn = fetch) {
17
31
  throw new Error(`Failed to fetch template ${templateName}: ${res.status} ${res.statusText}`);
18
32
  await writeFile(path.join(destDir, 'templates', `${templateName}.yaml`), await res.text());
19
33
  }
20
- for (const filePath of meta.files ?? []) {
34
+ for (const [filePath, dest] of fileDests) {
21
35
  const fileUrl = `${baseUrl}/${filePath}`;
22
36
  const res = await fetchFn(fileUrl);
23
37
  if (!res.ok)
24
38
  throw new Error(`Failed to fetch file ${filePath}: ${res.status} ${res.statusText}`);
25
- const dest = path.join(destDir, filePath);
26
39
  await mkdir(path.dirname(dest), { recursive: true });
27
40
  await writeFile(dest, await res.text());
28
41
  }