@mfdaves/okf-mcp 0.3.2-rc.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.
@@ -0,0 +1,816 @@
1
+ "use strict";
2
+
3
+ const path = require("path");
4
+ const readline = require("readline");
5
+ const {
6
+ attachProject,
7
+ buildIndex,
8
+ conceptSummary,
9
+ loadProjectBundles,
10
+ validateIndex,
11
+ } = require("./indexer");
12
+ const { searchConcepts } = require("./search");
13
+ const { exportGraph, findPaths, getGraph, getNeighbors, getSubgraph, graphSummary } = require("./graph");
14
+ const { fetchGitHubBundle, fetchRemoteBundles } = require("./remote");
15
+ const { ConceptAuthoringService } = require("./authoring");
16
+ const { FileConceptStore } = require("./store");
17
+ const { loadProjectConfig } = require("./project");
18
+ const packageMetadata = require("../package.json");
19
+
20
+ const SUPPORTED_PROTOCOL_VERSIONS = [
21
+ "2025-06-18",
22
+ "2025-03-26",
23
+ "2024-11-05",
24
+ ];
25
+
26
+ const READ_ONLY = {
27
+ readOnlyHint: true,
28
+ destructiveHint: false,
29
+ idempotentHint: true,
30
+ openWorldHint: false,
31
+ };
32
+ const LOCAL_WRITE = {
33
+ readOnlyHint: false,
34
+ destructiveHint: false,
35
+ idempotentHint: false,
36
+ openWorldHint: false,
37
+ };
38
+ const DESTRUCTIVE_WRITE = {
39
+ readOnlyHint: false,
40
+ destructiveHint: true,
41
+ idempotentHint: false,
42
+ openWorldHint: false,
43
+ };
44
+ const REMOTE_LOAD = {
45
+ readOnlyHint: false,
46
+ destructiveHint: false,
47
+ idempotentHint: false,
48
+ openWorldHint: true,
49
+ };
50
+
51
+ function stringParameter(description, extra) {
52
+ return Object.assign({ type: "string", description }, extra || {});
53
+ }
54
+
55
+ function numberParameter(description, extra) {
56
+ return Object.assign({ type: "number", description }, extra || {});
57
+ }
58
+
59
+ function booleanParameter(description) {
60
+ return { type: "boolean", description };
61
+ }
62
+
63
+ function stringArrayParameter(description) {
64
+ return {
65
+ type: "array",
66
+ description,
67
+ items: { type: "string" },
68
+ };
69
+ }
70
+
71
+ function objectParameter(description) {
72
+ return {
73
+ type: "object",
74
+ description,
75
+ additionalProperties: true,
76
+ };
77
+ }
78
+
79
+ function defineTool(description, annotations, properties, required, schemaExtras) {
80
+ return {
81
+ description,
82
+ annotations,
83
+ inputSchema: {
84
+ type: "object",
85
+ additionalProperties: false,
86
+ properties: properties || {},
87
+ ...(required && required.length ? { required } : {}),
88
+ ...(schemaExtras || {}),
89
+ },
90
+ };
91
+ }
92
+
93
+ const TOOL_DEFINITIONS = {
94
+ list_bundles: defineTool(
95
+ "List the local and remote OKF bundles currently loaded by the server.",
96
+ READ_ONLY,
97
+ ),
98
+ list_concepts: defineTool(
99
+ "List compact OKF concept summaries with optional bundle, type, tag, and text filters.",
100
+ READ_ONLY,
101
+ {
102
+ query: stringParameter("Optional text matched against concept metadata and content."),
103
+ bundle: stringParameter("Limit results to this bundle id."),
104
+ type: stringParameter("Limit results to this exact concept type."),
105
+ tag: stringParameter("Limit results to concepts containing this tag."),
106
+ limit: numberParameter("Maximum number of concepts to return."),
107
+ offset: numberParameter("Number of matching concepts to skip before returning results."),
108
+ },
109
+ ),
110
+ get_concept: defineTool(
111
+ "Read one valid OKF concept, including its frontmatter, Markdown body, and links.",
112
+ READ_ONLY,
113
+ {
114
+ uri: stringParameter("Canonical or path based okf URI for the concept."),
115
+ bundle: stringParameter("Bundle id used with path when uri is not supplied."),
116
+ path: stringParameter("Bundle relative Markdown path used with bundle when uri is not supplied."),
117
+ },
118
+ [],
119
+ {
120
+ anyOf: [
121
+ { required: ["uri"] },
122
+ { required: ["bundle", "path"] },
123
+ ],
124
+ },
125
+ ),
126
+ search_concepts: defineTool(
127
+ "Search OKF concepts and return ranked summaries using text and structured filters.",
128
+ READ_ONLY,
129
+ {
130
+ query: stringParameter("Text query matched against concept metadata and content."),
131
+ bundle: stringParameter("Limit results to this bundle id."),
132
+ types: stringArrayParameter("Limit results to any of these concept types."),
133
+ tagsAny: stringArrayParameter("Require at least one of these tags."),
134
+ tagsAll: stringArrayParameter("Require all of these tags."),
135
+ pathPrefix: stringParameter("Limit results to bundle relative paths beginning with this prefix."),
136
+ relationType: stringParameter("Limit results to concepts participating in this relation type."),
137
+ limit: numberParameter("Maximum number of concepts to return."),
138
+ offset: numberParameter("Number of matching concepts to skip before returning results."),
139
+ },
140
+ ),
141
+ list_types: defineTool(
142
+ "Count the concept types present in the current OKF index.",
143
+ READ_ONLY,
144
+ ),
145
+ list_tags: defineTool(
146
+ "Count the tags present on concepts in the current OKF index.",
147
+ READ_ONLY,
148
+ ),
149
+ list_relation_types: defineTool(
150
+ "Count the typed relations present in the current OKF graph.",
151
+ READ_ONLY,
152
+ ),
153
+ load_remote_bundle: defineTool(
154
+ "Fetch a public GitHub Markdown tree and add it to the in memory index as a read only remote bundle.",
155
+ REMOTE_LOAD,
156
+ {
157
+ id: stringParameter("Unique bundle id to assign to the fetched remote tree."),
158
+ url: stringParameter("Public GitHub tree URL to fetch."),
159
+ provider: stringParameter("Remote provider name. Only github is supported.", { enum: ["github"] }),
160
+ include: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to include."),
161
+ exclude: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to exclude."),
162
+ },
163
+ ["id", "url"],
164
+ ),
165
+ list_remote_bundles: defineTool(
166
+ "List metadata for remote bundles currently loaded into the server.",
167
+ READ_ONLY,
168
+ ),
169
+ okf_validate_concept: defineTool(
170
+ "Validate a proposed new OKF concept without writing a proposal or concept file.",
171
+ READ_ONLY,
172
+ {
173
+ bundle: stringParameter("Writable bundle id that would contain the concept."),
174
+ path: stringParameter("Safe bundle relative Markdown path for the concept."),
175
+ frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
176
+ body: stringParameter("Markdown body for the concept."),
177
+ },
178
+ ["bundle", "path", "frontmatter"],
179
+ ),
180
+ okf_suggest_concept_path: defineTool(
181
+ "Suggest a safe bundle relative Markdown path from a concept type and title.",
182
+ READ_ONLY,
183
+ {
184
+ bundle: stringParameter("Writable bundle id that will contain the concept."),
185
+ type: stringParameter("Concept type used to build the path."),
186
+ title: stringParameter("Concept title used to build the file name."),
187
+ prefix: stringParameter("Optional bundle relative directory prefix."),
188
+ },
189
+ ["bundle", "type", "title"],
190
+ ),
191
+ okf_propose_concept: defineTool(
192
+ "Create a reviewable proposal for a new OKF concept without writing the concept file.",
193
+ LOCAL_WRITE,
194
+ {
195
+ bundle: stringParameter("Writable bundle id that will contain the concept."),
196
+ path: stringParameter("Safe bundle relative Markdown path for the new concept."),
197
+ frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
198
+ body: stringParameter("Markdown body for the new concept."),
199
+ message: stringParameter("Optional review note explaining why the concept should be created."),
200
+ },
201
+ ["bundle", "path", "frontmatter"],
202
+ ),
203
+ okf_propose_update: defineTool(
204
+ "Create a reviewable update proposal for an existing OKF concept while preserving unspecified content.",
205
+ LOCAL_WRITE,
206
+ {
207
+ uri: stringParameter("Canonical or path based okf URI of the existing concept."),
208
+ frontmatter: objectParameter("Frontmatter fields to add or replace; unspecified fields are preserved."),
209
+ removeFrontmatterKeys: stringArrayParameter("Frontmatter keys to remove; the id field cannot be removed."),
210
+ body: stringParameter("Replacement Markdown body; omit it to preserve the current body."),
211
+ message: stringParameter("Optional review note explaining why the concept should be updated."),
212
+ },
213
+ ["uri"],
214
+ {
215
+ anyOf: [
216
+ { required: ["frontmatter"] },
217
+ { required: ["removeFrontmatterKeys"] },
218
+ { required: ["body"] },
219
+ ],
220
+ },
221
+ ),
222
+ okf_list_proposals: defineTool(
223
+ "List compact metadata for stored authoring proposals.",
224
+ READ_ONLY,
225
+ {
226
+ bundle: stringParameter("Limit results to proposals for this bundle id."),
227
+ status: stringParameter("Limit results to this proposal status.", { enum: ["proposed", "accepted", "rejected"] }),
228
+ },
229
+ ),
230
+ okf_get_proposal: defineTool(
231
+ "Read one authoring proposal, including its candidate content and validation result.",
232
+ READ_ONLY,
233
+ {
234
+ proposalId: stringParameter("Identifier returned when the proposal was created."),
235
+ },
236
+ ["proposalId"],
237
+ ),
238
+ okf_accept_proposal: defineTool(
239
+ "Accept a reviewed proposal and write its new or updated concept file after revalidation.",
240
+ DESTRUCTIVE_WRITE,
241
+ {
242
+ proposalId: stringParameter("Identifier of the proposed change to accept."),
243
+ },
244
+ ["proposalId"],
245
+ ),
246
+ okf_reject_proposal: defineTool(
247
+ "Reject a reviewed proposal so it can no longer be accepted.",
248
+ DESTRUCTIVE_WRITE,
249
+ {
250
+ proposalId: stringParameter("Identifier of the proposed change to reject."),
251
+ reason: stringParameter("Optional explanation recorded with the rejection."),
252
+ },
253
+ ["proposalId"],
254
+ ),
255
+ get_graph: defineTool(
256
+ "Return a bounded set of OKF graph nodes and edges with optional concept filters.",
257
+ READ_ONLY,
258
+ {
259
+ bundle: stringParameter("Limit graph nodes to this bundle id."),
260
+ type: stringParameter("Limit graph nodes to this exact concept type."),
261
+ tag: stringParameter("Limit graph nodes to concepts containing this tag."),
262
+ pathPrefix: stringParameter("Limit graph nodes to bundle relative paths beginning with this prefix."),
263
+ includeExternal: booleanParameter("Include opaque external relation targets in the graph."),
264
+ maxNodes: numberParameter("Maximum number of graph nodes to return."),
265
+ maxEdges: numberParameter("Maximum number of graph edges to return."),
266
+ },
267
+ ),
268
+ get_neighbors: defineTool(
269
+ "Return the incoming and outgoing graph relationships for one OKF concept.",
270
+ READ_ONLY,
271
+ {
272
+ uri: stringParameter("Canonical or path based okf URI of the center concept."),
273
+ },
274
+ ["uri"],
275
+ ),
276
+ get_subgraph: defineTool(
277
+ "Traverse a bounded OKF subgraph outward from one or more seed concepts.",
278
+ READ_ONLY,
279
+ {
280
+ uri: stringParameter("Single canonical or path based okf URI to use as a seed."),
281
+ seeds: stringArrayParameter("One or more okf URIs to use as traversal seeds."),
282
+ depth: numberParameter("Maximum relationship depth to traverse from the seeds."),
283
+ maxNodes: numberParameter("Maximum number of graph nodes to return."),
284
+ },
285
+ [],
286
+ {
287
+ anyOf: [
288
+ { required: ["uri"] },
289
+ { required: ["seeds"] },
290
+ ],
291
+ },
292
+ ),
293
+ find_paths: defineTool(
294
+ "Find bounded relationship paths between two OKF concepts.",
295
+ READ_ONLY,
296
+ {
297
+ source: stringParameter("Canonical or path based okf URI where path search begins."),
298
+ target: stringParameter("Canonical or path based okf URI where path search ends."),
299
+ maxPaths: numberParameter("Maximum number of distinct paths to return."),
300
+ },
301
+ ["source", "target"],
302
+ ),
303
+ graph_summary: defineTool(
304
+ "Summarize bundle, concept, edge, type, tag, and graph health counts.",
305
+ READ_ONLY,
306
+ ),
307
+ validate_bundle: defineTool(
308
+ "Report OKF conformance separately from project validity for one bundle or the full current index.",
309
+ READ_ONLY,
310
+ {
311
+ bundle: stringParameter("Optional bundle id to validate in isolation."),
312
+ },
313
+ ),
314
+ validate_project: defineTool(
315
+ "Report OKF conformance, project validity, and structured diagnostics for the complete configured project.",
316
+ READ_ONLY,
317
+ ),
318
+ export_graph: defineTool(
319
+ "Render the current OKF graph as JSON, Graphviz DOT, or Mermaid text.",
320
+ READ_ONLY,
321
+ {
322
+ format: stringParameter("Output format for the graph.", { enum: ["json", "dot", "mermaid"] }),
323
+ includeExternal: booleanParameter("Include opaque external relation targets in the export."),
324
+ maxNodes: numberParameter("Maximum number of graph nodes to export."),
325
+ maxEdges: numberParameter("Maximum number of graph edges to export."),
326
+ },
327
+ ),
328
+ };
329
+
330
+ const TOOL_NAMES = Object.keys(TOOL_DEFINITIONS);
331
+ const PROJECT_HELPER_TOOL_NAMES = new Set([
332
+ "okf_validate_concept",
333
+ "okf_suggest_concept_path",
334
+ "okf_list_proposals",
335
+ "okf_get_proposal",
336
+ ]);
337
+ const AUTHORING_MUTATION_TOOL_NAMES = new Set([
338
+ "okf_propose_concept",
339
+ "okf_propose_update",
340
+ "okf_accept_proposal",
341
+ "okf_reject_proposal",
342
+ ]);
343
+ const RUNTIME_REMOTE_TOOL_NAMES = new Set([
344
+ "load_remote_bundle",
345
+ ]);
346
+
347
+ function jsonContent(value) {
348
+ return {
349
+ content: [
350
+ {
351
+ type: "text",
352
+ text: JSON.stringify(value, null, 2),
353
+ },
354
+ ],
355
+ };
356
+ }
357
+
358
+ function toolEnabled(state, name) {
359
+ if (PROJECT_HELPER_TOOL_NAMES.has(name)) {
360
+ return Boolean(state && state.authoringService);
361
+ }
362
+ if (AUTHORING_MUTATION_TOOL_NAMES.has(name)) {
363
+ return Boolean(state && state.authoringService && state.allowAuthoring);
364
+ }
365
+ if (RUNTIME_REMOTE_TOOL_NAMES.has(name)) {
366
+ return Boolean(state && state.allowRuntimeRemoteLoad);
367
+ }
368
+ return true;
369
+ }
370
+
371
+ function requireToolEnabled(state, name) {
372
+ if (!toolEnabled(state, name)) {
373
+ throw new Error(`MCP tool is disabled by server configuration: ${name}`);
374
+ }
375
+ }
376
+
377
+ function listTools(state) {
378
+ return {
379
+ tools: TOOL_NAMES
380
+ .filter((name) => toolEnabled(state, name))
381
+ .map((name) => Object.assign({ name }, TOOL_DEFINITIONS[name])),
382
+ };
383
+ }
384
+
385
+ function listResources(index) {
386
+ return {
387
+ resources: index.documents.map((doc) => ({
388
+ uri: doc.uri,
389
+ name: doc.title,
390
+ description: doc.description || `${doc.kind} ${doc.path}`,
391
+ mimeType: "text/markdown",
392
+ })),
393
+ };
394
+ }
395
+
396
+ function publicBundles(index) {
397
+ return index.bundles.map((bundle) => {
398
+ if (bundle.remote) {
399
+ return {
400
+ id: bundle.id,
401
+ remote: true,
402
+ provider: bundle.remoteSource && bundle.remoteSource.provider,
403
+ url: bundle.remoteSource && bundle.remoteSource.url,
404
+ ref: bundle.remoteSource && bundle.remoteSource.ref,
405
+ path: bundle.remoteSource && bundle.remoteSource.path,
406
+ fileCount: bundle.remoteSource && bundle.remoteSource.fileCount,
407
+ include: bundle.include || [],
408
+ exclude: bundle.exclude || [],
409
+ };
410
+ }
411
+ const root = index.project && index.project.root
412
+ ? path.relative(index.project.root, bundle.root).replace(/\\/g, "/") || "."
413
+ : "<configured>";
414
+ return {
415
+ id: bundle.id,
416
+ root,
417
+ include: bundle.include || [],
418
+ exclude: bundle.exclude || [],
419
+ };
420
+ });
421
+ }
422
+
423
+ function readResource(index, uri) {
424
+ const doc = index.byUri.get(uri);
425
+ if (!doc) {
426
+ throw new Error(`Unknown OKF resource URI: ${uri}`);
427
+ }
428
+ return {
429
+ contents: [
430
+ {
431
+ uri: doc.uri,
432
+ mimeType: "text/markdown",
433
+ text: doc.text,
434
+ },
435
+ ],
436
+ };
437
+ }
438
+
439
+ function listConcepts(index, args) {
440
+ const options = Object.assign({}, args || {});
441
+ if (options.type && !options.types) {
442
+ options.types = [options.type];
443
+ }
444
+ if (options.tag && !options.tagsAny) {
445
+ options.tagsAny = [options.tag];
446
+ }
447
+ return searchConcepts(index, Object.assign(options, { query: "" }));
448
+ }
449
+
450
+ function getConcept(index, args) {
451
+ const uri = args && args.uri ? args.uri : args && args.bundle && args.path ? `okf://${args.bundle}/${args.path}` : null;
452
+ if (!uri || !index.byUri.has(uri)) {
453
+ throw new Error(`Unknown OKF concept URI: ${uri || "<missing>"}`);
454
+ }
455
+ const doc = index.byUri.get(uri);
456
+ if (!doc.valid || doc.reserved) {
457
+ throw new Error(`URI is not a valid OKF concept: ${uri}`);
458
+ }
459
+ return Object.assign(conceptSummary(doc), {
460
+ frontmatter: doc.frontmatter,
461
+ body: doc.body,
462
+ links: doc.links,
463
+ });
464
+ }
465
+
466
+ function listTypes(index) {
467
+ const counts = {};
468
+ index.concepts.forEach((doc) => {
469
+ counts[doc.type] = (counts[doc.type] || 0) + 1;
470
+ });
471
+ return counts;
472
+ }
473
+
474
+ function listTags(index) {
475
+ const counts = {};
476
+ index.concepts.forEach((doc) => {
477
+ doc.tags.forEach((tag) => {
478
+ counts[tag] = (counts[tag] || 0) + 1;
479
+ });
480
+ });
481
+ return counts;
482
+ }
483
+
484
+ function listRelationTypes(index) {
485
+ const counts = {};
486
+ index.edges.filter((edge) => edge.kind === "relation").forEach((edge) => {
487
+ counts[edge.relationType] = (counts[edge.relationType] || 0) + 1;
488
+ });
489
+ return counts;
490
+ }
491
+
492
+ function requireAuthoring(state) {
493
+ if (!state.authoringService) {
494
+ throw new Error("OKF authoring is not configured. Start the server with --project to enable writable concept proposals.");
495
+ }
496
+ return state.authoringService;
497
+ }
498
+
499
+ function rebuildStateIndex(state) {
500
+ const index = buildIndex(
501
+ state.localBundleArgs.concat(state.remoteBundles),
502
+ { relationTypes: state.relationTypes },
503
+ );
504
+ state.index = state.project ? attachProject(index, state.project) : index;
505
+ return state.index;
506
+ }
507
+
508
+ async function callTool(state, name, args) {
509
+ if (!state || !state.index) {
510
+ state = {
511
+ index: state,
512
+ localBundleArgs: [],
513
+ remoteBundles: [],
514
+ relationTypes: state && state.relationTypes,
515
+ project: null,
516
+ authoringService: null,
517
+ allowAuthoring: false,
518
+ allowRuntimeRemoteLoad: false,
519
+ };
520
+ }
521
+ requireToolEnabled(state, name);
522
+ const index = state.index;
523
+ switch (name) {
524
+ case "list_bundles":
525
+ return jsonContent(publicBundles(index));
526
+ case "list_concepts":
527
+ return jsonContent(listConcepts(index, args));
528
+ case "get_concept":
529
+ return jsonContent(getConcept(index, args));
530
+ case "search_concepts":
531
+ return jsonContent(searchConcepts(index, args || {}));
532
+ case "list_types":
533
+ return jsonContent(listTypes(index));
534
+ case "list_tags":
535
+ return jsonContent(listTags(index));
536
+ case "list_relation_types":
537
+ return jsonContent(listRelationTypes(index));
538
+ case "list_remote_bundles":
539
+ return jsonContent(state.remoteBundles.map((bundle) => bundle.remoteSource));
540
+ case "load_remote_bundle": {
541
+ if (!args || !args.id || !args.url) {
542
+ throw new Error("load_remote_bundle requires id and url.");
543
+ }
544
+ const provider = String(args.provider || "github");
545
+ if (provider !== "github") {
546
+ throw new Error(`Unsupported remote bundle provider: ${provider}`);
547
+ }
548
+ if (state.index.bundles.some((bundle) => bundle.id === args.id)) {
549
+ throw new Error(`Bundle id already loaded: ${args.id}`);
550
+ }
551
+ const remoteBundle = await fetchGitHubBundle({
552
+ id: args.id,
553
+ url: args.url,
554
+ include: Array.isArray(args.include) ? args.include : [],
555
+ exclude: Array.isArray(args.exclude) ? args.exclude : [],
556
+ });
557
+ state.remoteBundles.push(remoteBundle);
558
+ rebuildStateIndex(state);
559
+ return jsonContent(remoteBundle.remoteSource);
560
+ }
561
+ case "okf_validate_concept":
562
+ return jsonContent(requireAuthoring(state).validateConcept(args || {}));
563
+ case "okf_suggest_concept_path":
564
+ return jsonContent(requireAuthoring(state).suggestConceptPath(args || {}));
565
+ case "okf_propose_concept":
566
+ return jsonContent(await requireAuthoring(state).proposeConcept(args || {}));
567
+ case "okf_propose_update":
568
+ return jsonContent(await requireAuthoring(state).proposeUpdate(args || {}));
569
+ case "okf_list_proposals":
570
+ return jsonContent(await requireAuthoring(state).listProposals(args || {}));
571
+ case "okf_get_proposal":
572
+ return jsonContent(await requireAuthoring(state).getProposal(args || {}));
573
+ case "okf_accept_proposal": {
574
+ const result = await requireAuthoring(state).acceptProposal(args || {});
575
+ if (result.accepted) {
576
+ rebuildStateIndex(state);
577
+ }
578
+ return jsonContent(result);
579
+ }
580
+ case "okf_reject_proposal":
581
+ return jsonContent(await requireAuthoring(state).rejectProposal(args || {}));
582
+ case "get_graph":
583
+ return jsonContent(getGraph(index, args || {}));
584
+ case "get_neighbors":
585
+ if (!args || !args.uri) {
586
+ throw new Error("get_neighbors requires uri.");
587
+ }
588
+ return jsonContent(getNeighbors(index, args && args.uri));
589
+ case "get_subgraph":
590
+ return jsonContent(getSubgraph(index, args || {}));
591
+ case "find_paths":
592
+ if (!args || !args.source || !args.target) {
593
+ throw new Error("find_paths requires source and target.");
594
+ }
595
+ return jsonContent(findPaths(index, args && args.source, args && args.target, args && args.maxPaths));
596
+ case "graph_summary":
597
+ return jsonContent(graphSummary(index));
598
+ case "validate_bundle":
599
+ return jsonContent(validateIndex(index, args && args.bundle));
600
+ case "validate_project":
601
+ return jsonContent(validateIndex(index));
602
+ case "export_graph":
603
+ return {
604
+ content: [
605
+ {
606
+ type: "text",
607
+ text: exportGraph(index, args || {}),
608
+ },
609
+ ],
610
+ };
611
+ default:
612
+ throw new Error(`Unknown OKF MCP tool: ${name}`);
613
+ }
614
+ }
615
+
616
+ function createServer(bundleArgs, options) {
617
+ const authoringService = options && options.authoringService;
618
+ let project = null;
619
+ if (authoringService && authoringService.store) {
620
+ project = authoringService.store.project;
621
+ } else if (options && options.projectPath) {
622
+ project = loadProjectConfig(options.projectPath);
623
+ }
624
+ const localBundleArgs = project
625
+ ? project.bundles.filter((bundle) => !bundle.remote)
626
+ : (bundleArgs || []).slice();
627
+ const relationTypes = (options && options.relationTypes)
628
+ || (project && project.relationTypes);
629
+ let initialIndex = options && options.initialIndex;
630
+ if (!initialIndex) {
631
+ initialIndex = buildIndex(localBundleArgs, { relationTypes });
632
+ if (project) {
633
+ initialIndex = attachProject(initialIndex, project);
634
+ }
635
+ }
636
+ const state = {
637
+ index: initialIndex,
638
+ localBundleArgs,
639
+ remoteBundles: (options && options.initialRemoteBundles) || [],
640
+ relationTypes,
641
+ project,
642
+ authoringService,
643
+ allowAuthoring: Boolean(options && options.allowAuthoring),
644
+ allowRuntimeRemoteLoad: Boolean(options && options.allowRuntimeRemoteLoad),
645
+ };
646
+ async function handle(request) {
647
+ const method = request.method;
648
+ const params = request.params || {};
649
+ if (method === "initialize") {
650
+ const requestedVersion = params.protocolVersion;
651
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)) {
652
+ throw new Error(
653
+ `Unsupported MCP protocol version: ${requestedVersion || "<missing>"}. `
654
+ + `Supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`,
655
+ );
656
+ }
657
+ return {
658
+ protocolVersion: requestedVersion,
659
+ serverInfo: { name: "okf-mcp", version: packageMetadata.version },
660
+ capabilities: { resources: {}, tools: {} },
661
+ };
662
+ }
663
+ if (method === "notifications/initialized") {
664
+ return null;
665
+ }
666
+ if (method === "resources/list") {
667
+ return listResources(state.index);
668
+ }
669
+ if (method === "resources/read") {
670
+ return readResource(state.index, params.uri);
671
+ }
672
+ if (method === "tools/list") {
673
+ return listTools(state);
674
+ }
675
+ if (method === "tools/call") {
676
+ return callTool(state, params.name, params.arguments || {});
677
+ }
678
+ throw new Error(`Unsupported MCP method: ${method}`);
679
+ }
680
+ return { get index() { return state.index; }, handle };
681
+ }
682
+
683
+ async function createServerAsync(bundleArgs, options) {
684
+ if (options && options.projectPath) {
685
+ const loaded = await loadProjectBundles(options.projectPath);
686
+ const extraRemoteBundles = await fetchRemoteBundles(options.remoteBundles || []);
687
+ const initialRemoteBundles = loaded.remoteBundles.concat(extraRemoteBundles);
688
+ const localBundleArgs = (loaded.bundles || []).filter((bundle) => !bundle.remote);
689
+ const store = options.authoringStore || FileConceptStore.fromProject(options.projectPath, { proposalRoot: options.proposalRoot });
690
+ const authoringService = options.authoringService || new ConceptAuthoringService(store);
691
+ const initialIndex = attachProject(
692
+ buildIndex(localBundleArgs.concat(initialRemoteBundles), { relationTypes: loaded.project.relationTypes }),
693
+ loaded.project,
694
+ );
695
+ return createServer(localBundleArgs, {
696
+ initialIndex,
697
+ initialRemoteBundles,
698
+ relationTypes: loaded.project.relationTypes,
699
+ authoringService,
700
+ allowAuthoring: options.allowAuthoring,
701
+ allowRuntimeRemoteLoad: options.allowRuntimeRemoteLoad,
702
+ });
703
+ }
704
+ const remoteBundles = await fetchRemoteBundles((options && options.remoteBundles) || []);
705
+ const localBundleArgs = (bundleArgs || []).slice();
706
+ return createServer(localBundleArgs, {
707
+ initialIndex: buildIndex(localBundleArgs.concat(remoteBundles)),
708
+ initialRemoteBundles: remoteBundles,
709
+ allowAuthoring: options && options.allowAuthoring,
710
+ allowRuntimeRemoteLoad: options && options.allowRuntimeRemoteLoad,
711
+ });
712
+ }
713
+
714
+ function responseFor(id, result, error) {
715
+ if (error) {
716
+ return {
717
+ jsonrpc: "2.0",
718
+ id,
719
+ error: {
720
+ code: -32000,
721
+ message: error.message || String(error),
722
+ },
723
+ };
724
+ }
725
+ return { jsonrpc: "2.0", id, result };
726
+ }
727
+
728
+ async function runStdioServer(bundleArgs, input, output, options) {
729
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
730
+ let serverPromise;
731
+ let pending = Promise.resolve();
732
+
733
+ function writeResponse(response) {
734
+ return new Promise((resolve, reject) => {
735
+ output.write(`${JSON.stringify(response)}\n`, (error) => {
736
+ if (error) {
737
+ reject(error);
738
+ return;
739
+ }
740
+ resolve();
741
+ });
742
+ });
743
+ }
744
+
745
+ async function handleLine(line) {
746
+ if (!line.trim()) {
747
+ return;
748
+ }
749
+ if (line.length > 1024 * 1024) {
750
+ await writeResponse(responseFor(null, null, new Error("MCP request line exceeds 1 MiB.")));
751
+ return;
752
+ }
753
+ let request;
754
+ try {
755
+ request = JSON.parse(line);
756
+ const server = await serverPromise;
757
+ const result = await server.handle(request);
758
+ if (request.id !== undefined) {
759
+ await writeResponse(responseFor(request.id, result, null));
760
+ }
761
+ } catch (error) {
762
+ const id = request && request.id !== undefined ? request.id : null;
763
+ await writeResponse(responseFor(id, null, error));
764
+ }
765
+ }
766
+
767
+ rl.on("line", (line) => {
768
+ pending = pending.then(() => handleLine(line));
769
+ });
770
+
771
+ const closed = new Promise((resolve, reject) => {
772
+ rl.once("close", () => {
773
+ // A pending Promise alone does not keep a CommonJS CLI alive after stdin reaches EOF.
774
+ const keepAlive = setInterval(() => {}, 1000);
775
+ pending.then(
776
+ () => {
777
+ clearInterval(keepAlive);
778
+ resolve();
779
+ },
780
+ (error) => {
781
+ clearInterval(keepAlive);
782
+ reject(error);
783
+ },
784
+ );
785
+ });
786
+ });
787
+
788
+ serverPromise = createServerAsync(bundleArgs, options);
789
+ let server;
790
+ try {
791
+ server = await serverPromise;
792
+ } catch (error) {
793
+ rl.close();
794
+ throw error;
795
+ }
796
+ Object.defineProperty(server, "closed", {
797
+ configurable: false,
798
+ enumerable: false,
799
+ value: closed,
800
+ writable: false,
801
+ });
802
+ return server;
803
+ }
804
+
805
+ module.exports = {
806
+ SUPPORTED_PROTOCOL_VERSIONS,
807
+ TOOL_NAMES,
808
+ callTool,
809
+ createServer,
810
+ createServerAsync,
811
+ listResources,
812
+ listTools,
813
+ readResource,
814
+ rebuildStateIndex,
815
+ runStdioServer,
816
+ };