@mfdaves/okf-mcp 0.3.3 → 0.5.0

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 (40) hide show
  1. package/.agents/skills/okf-v02-migration/SKILL.md +37 -0
  2. package/.agents/skills/okf-v02-migration/agents/openai.yaml +6 -0
  3. package/.agents/skills/okf-v02-migration/references/field-mapping.md +26 -0
  4. package/README.md +192 -78
  5. package/okf/bundles/okf-mcp/distribution/reference-bundle.md +2 -2
  6. package/okf/bundles/okf-mcp/index.md +7 -0
  7. package/okf/bundles/okf-mcp/interfaces/http-authoring-api.md +2 -2
  8. package/okf/bundles/okf-mcp/interfaces/mcp-tools.md +8 -4
  9. package/okf/bundles/okf-mcp/overview/okf-mcp.md +2 -2
  10. package/okf/bundles/okf-mcp/policies/authoring-safety.md +5 -3
  11. package/okf/bundles/okf-mcp/runtime/file-concept-store.md +7 -5
  12. package/okf/bundles/okf-mcp/runtime/indexer.md +6 -4
  13. package/okf/bundles/okf-mcp/runtime/mcp-server.md +6 -6
  14. package/okf/bundles/okf-mcp/specs/attested-computation.md +24 -0
  15. package/okf/bundles/okf-mcp/specs/concept-format.md +5 -3
  16. package/okf/bundles/okf-mcp/specs/git-sources.md +23 -0
  17. package/okf/bundles/okf-mcp/workflows/v02-migration.md +24 -0
  18. package/package.json +9 -3
  19. package/server.json +5 -5
  20. package/src/assets.js +469 -0
  21. package/src/authoring.js +492 -20
  22. package/src/cli.js +467 -37
  23. package/src/computation.js +366 -0
  24. package/src/git-source.js +551 -0
  25. package/src/graph.js +71 -18
  26. package/src/http-server.js +8 -1
  27. package/src/index.js +5 -0
  28. package/src/indexer.js +428 -24
  29. package/src/markdown.js +129 -0
  30. package/src/mcp-server.js +447 -313
  31. package/src/migration.js +687 -0
  32. package/src/parser.js +135 -54
  33. package/src/plugins.js +30 -50
  34. package/src/project.js +74 -17
  35. package/src/remote.js +232 -17
  36. package/src/search.js +69 -6
  37. package/src/store.js +421 -25
  38. package/src/v02.js +545 -0
  39. package/src/validation.js +13 -2
  40. package/src/mcp-protocol.js +0 -283
package/src/mcp-server.js CHANGED
@@ -1,39 +1,47 @@
1
1
  "use strict";
2
2
 
3
3
  const path = require("path");
4
- const readline = require("readline");
4
+ const {
5
+ McpServer,
6
+ ResourceNotFoundError,
7
+ ResourceTemplate,
8
+ fromJsonSchema,
9
+ } = require("@modelcontextprotocol/server");
10
+ const { StdioServerTransport, serveStdio } = require("@modelcontextprotocol/server/stdio");
5
11
  const {
6
12
  attachProject,
7
13
  buildIndex,
14
+ conceptSignals,
8
15
  conceptSummary,
9
16
  loadProjectBundles,
17
+ resolveConcept,
10
18
  validateIndex,
11
19
  } = require("./indexer");
12
20
  const { searchConcepts } = require("./search");
13
21
  const { exportGraph, findPaths, getGraph, getNeighbors, getSubgraph, graphSummary } = require("./graph");
14
- const { fetchGitHubBundle, fetchRemoteBundles } = require("./remote");
22
+ const { fetchGitHubBundle, fetchRemoteBundles, sanitizeRemoteId } = require("./remote");
15
23
  const { ConceptAuthoringService } = require("./authoring");
16
24
  const { FileConceptStore } = require("./store");
17
25
  const { loadProjectConfig } = require("./project");
18
26
  const {
19
- ERROR_CODES,
20
- ProtocolError,
21
- ToolExecutionError,
22
- assertSupportedSchema,
23
- isPlainObject,
24
- isValidRequestId,
25
- responseFor,
26
- validateJsonRpcEnvelope,
27
- validateToolArguments,
28
- } = require("./mcp-protocol");
27
+ checkComputationReceipt,
28
+ getProvenance,
29
+ inspectAttestedComputation,
30
+ prepareAttestedComputation,
31
+ readBundleAsset,
32
+ } = require("./computation");
33
+ const { checkV02Migration } = require("./migration");
34
+ const { describeConceptGitSources, readConceptGitSource } = require("./git-source");
29
35
  const packageMetadata = require("../package.json");
30
36
 
31
- const SUPPORTED_PROTOCOL_VERSIONS = [
32
- "2025-11-25",
33
- "2025-06-18",
34
- "2025-03-26",
35
- "2024-11-05",
36
- ];
37
+ const MAX_MCP_MESSAGE_BYTES = 1024 * 1024;
38
+
39
+ class ToolExecutionError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = "ToolExecutionError";
43
+ }
44
+ }
37
45
 
38
46
  const READ_ONLY = {
39
47
  readOnlyHint: true,
@@ -82,6 +90,10 @@ function booleanParameter(description) {
82
90
  return { type: "boolean", description, default: false };
83
91
  }
84
92
 
93
+ function optionalBooleanParameter(description) {
94
+ return { type: "boolean", description };
95
+ }
96
+
85
97
  function stringArrayParameter(description, options) {
86
98
  const config = options || {};
87
99
  return {
@@ -138,6 +150,7 @@ const TOOL_DEFINITIONS = {
138
150
  "Read one valid OKF concept, including its frontmatter, Markdown body, and links.",
139
151
  READ_ONLY,
140
152
  {
153
+ id: nonEmptyStringParameter("Portable extensionless Concept ID or bundle-relative Markdown path."),
141
154
  uri: nonEmptyStringParameter("Canonical or path based okf URI for the concept."),
142
155
  bundle: nonEmptyStringParameter("Bundle id used with path when uri is not supplied."),
143
156
  path: nonEmptyStringParameter("Bundle relative Markdown path used with bundle when uri is not supplied."),
@@ -145,6 +158,7 @@ const TOOL_DEFINITIONS = {
145
158
  [],
146
159
  {
147
160
  anyOf: [
161
+ { required: ["id"] },
148
162
  { required: ["uri"] },
149
163
  { required: ["bundle", "path"] },
150
164
  ],
@@ -161,6 +175,19 @@ const TOOL_DEFINITIONS = {
161
175
  tagsAll: stringArrayParameter("Require all of these tags.", { nonEmptyItems: true }),
162
176
  pathPrefix: stringParameter("Limit results to bundle relative paths beginning with this prefix."),
163
177
  relationType: nonEmptyStringParameter("Limit results to concepts with an outgoing relation of this type."),
178
+ frontmatter: objectParameter("Exact frontmatter filters; array fields use contains matching."),
179
+ linkedTo: nonEmptyStringParameter("Require an outgoing edge to this concept URI."),
180
+ linkedFrom: nonEmptyStringParameter("Require an incoming edge from this concept URI."),
181
+ orphanOnly: booleanParameter("Return only concepts without incoming or outgoing resolved edges."),
182
+ statuses: stringArrayParameter("Limit results to lifecycle statuses.", { nonEmptyItems: true }),
183
+ trustTiers: stringArrayParameter("Limit results to unverified, machine-confirmed, or human-reviewed trust tiers.", { nonEmptyItems: true }),
184
+ freshness: stringArrayParameter("Limit results to unspecified, fresh, stale, or invalid freshness states.", { nonEmptyItems: true }),
185
+ asOf: nonEmptyStringParameter("UTC ISO date or datetime used for deterministic freshness evaluation."),
186
+ hasSources: optionalBooleanParameter("Require concepts to have or not have normalized sources."),
187
+ runtime: nonEmptyStringParameter("Limit results to this Attested Computation runtime."),
188
+ attestationReady: optionalBooleanParameter("Require static Attested Computation readiness."),
189
+ generatedBy: nonEmptyStringParameter("Limit results to this generator actor."),
190
+ verifiedBy: nonEmptyStringParameter("Limit results to concepts verified by this actor."),
164
191
  limit: integerParameter("Maximum number of concepts to return.", 1, 250, 25),
165
192
  offset: integerParameter("Number of matching concepts to skip before returning results.", 0, undefined, 0),
166
193
  },
@@ -177,6 +204,83 @@ const TOOL_DEFINITIONS = {
177
204
  "Count the typed relations present in the current OKF graph.",
178
205
  READ_ONLY,
179
206
  ),
207
+ list_edge_kinds: defineTool(
208
+ "Count standard semantic and extension edge kinds in the current graph.",
209
+ READ_ONLY,
210
+ ),
211
+ get_provenance: defineTool(
212
+ "Trace normalized source provenance through internal concepts without fetching external resources.",
213
+ READ_ONLY,
214
+ {
215
+ uri: nonEmptyStringParameter("Canonical or compatibility OKF URI of the root concept."),
216
+ maxDepth: integerParameter("Maximum internal source depth.", 0, 10, 3),
217
+ maxNodes: integerParameter("Maximum provenance nodes.", 1, 1000, 100),
218
+ includeExternal: booleanParameter("Include URL and opaque provenance leaves without fetching them."),
219
+ },
220
+ ["uri"],
221
+ ),
222
+ inspect_attested_computation: defineTool(
223
+ "Statically inspect an Attested Computation contract and indexed inert artifacts; never execute it.",
224
+ READ_ONLY,
225
+ {
226
+ uri: nonEmptyStringParameter("Canonical or compatibility URI of the Attested Computation."),
227
+ asOf: nonEmptyStringParameter("UTC ISO date or datetime for freshness evaluation."),
228
+ includeComputation: booleanParameter("Include bounded inline or text computation content."),
229
+ maxContentBytes: integerParameter("Maximum computation bytes to include.", 1, 1048576, 65536),
230
+ },
231
+ ["uri"],
232
+ ),
233
+ read_bundle_asset: defineTool(
234
+ "Read one explicitly referenced, already indexed bundle asset with digest verification and byte bounds.",
235
+ READ_ONLY,
236
+ {
237
+ uri: nonEmptyStringParameter("Indexed okf-asset URI."),
238
+ bundle: nonEmptyStringParameter("Bundle id used with path when uri is omitted."),
239
+ path: nonEmptyStringParameter("Bundle-relative indexed asset path used with bundle."),
240
+ maxContentBytes: integerParameter("Maximum asset bytes to return.", 1, 1048576, 65536),
241
+ },
242
+ [],
243
+ { anyOf: [{ required: ["uri"] }, { required: ["bundle", "path"] }] },
244
+ ),
245
+ read_git_source: defineTool(
246
+ "Read one pinned sources[].git entry from an explicitly mapped checkout or bare repository without fetching.",
247
+ READ_ONLY,
248
+ {
249
+ concept: nonEmptyStringParameter("Concept ID, Markdown path, custom ID, or compatibility URI declaring the source."),
250
+ sourceId: nonEmptyStringParameter("Exact sources[].id value to read."),
251
+ maxContentBytes: integerParameter("Maximum Git blob bytes to read.", 1, 1048576, 65536),
252
+ },
253
+ ["concept", "sourceId"],
254
+ ),
255
+ prepare_attested_computation: defineTool(
256
+ "Check declared parameters and produce non-executing digests without echoing parameter values.",
257
+ READ_ONLY,
258
+ {
259
+ uri: nonEmptyStringParameter("Canonical or compatibility URI of the Attested Computation."),
260
+ parameters: objectParameter("Parameter values keyed only by declared names."),
261
+ asOf: nonEmptyStringParameter("UTC ISO date or datetime for freshness evaluation."),
262
+ },
263
+ ["uri", "parameters"],
264
+ ),
265
+ check_computation_receipt: defineTool(
266
+ "Check receipt field presence only; never attest, echo values, or persist the receipt.",
267
+ READ_ONLY,
268
+ {
269
+ uri: nonEmptyStringParameter("Canonical or compatibility URI of the Attested Computation."),
270
+ receipt: objectParameter("Ephemeral receipt object; only its field names are returned."),
271
+ },
272
+ ["uri", "receipt"],
273
+ ),
274
+ check_v02_migration: defineTool(
275
+ "Analyze a local or remote bundle for safe staged OKF v0.2 migration without creating proposals or writes.",
276
+ READ_ONLY,
277
+ {
278
+ bundle: nonEmptyStringParameter("Bundle id to analyze; optional when exactly one root is loaded."),
279
+ actorMappings: objectParameter("Mappings keyed by URI, path, or $default; each value requires by plus confirmed: true."),
280
+ generatedPaths: stringArrayParameter("Paths generated elsewhere and therefore skipped from direct proposals.", { nonEmptyItems: true }),
281
+ },
282
+ [],
283
+ ),
180
284
  load_remote_bundle: defineTool(
181
285
  "Fetch a public GitHub Markdown tree and add it to the in memory index as a read only remote bundle.",
182
286
  REMOTE_LOAD,
@@ -197,35 +301,35 @@ const TOOL_DEFINITIONS = {
197
301
  "Validate a proposed new OKF concept without writing a proposal or concept file.",
198
302
  READ_ONLY,
199
303
  {
200
- bundle: nonEmptyStringParameter("Writable bundle id that would contain the concept."),
304
+ bundle: nonEmptyStringParameter("Writable root id; optional when exactly one local root is configured."),
201
305
  path: nonEmptyStringParameter("Safe bundle relative Markdown path for the concept."),
202
306
  frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
203
307
  body: stringParameter("Markdown body for the concept."),
204
308
  },
205
- ["bundle", "path", "frontmatter"],
309
+ ["path", "frontmatter"],
206
310
  ),
207
311
  okf_suggest_concept_path: defineTool(
208
312
  "Suggest a safe bundle relative Markdown path from a concept type and title.",
209
313
  READ_ONLY,
210
314
  {
211
- bundle: nonEmptyStringParameter("Writable bundle id that will contain the concept."),
315
+ bundle: nonEmptyStringParameter("Writable root id; optional when exactly one local root is configured."),
212
316
  type: nonEmptyStringParameter("Concept type used to build the path."),
213
317
  title: nonEmptyStringParameter("Concept title used to build the file name."),
214
318
  prefix: stringParameter("Optional bundle relative directory prefix."),
215
319
  },
216
- ["bundle", "type", "title"],
320
+ ["type", "title"],
217
321
  ),
218
322
  okf_propose_concept: defineTool(
219
323
  "Create a reviewable proposal for a new OKF concept without writing the concept file.",
220
324
  LOCAL_WRITE,
221
325
  {
222
- bundle: nonEmptyStringParameter("Writable bundle id that will contain the concept."),
326
+ bundle: nonEmptyStringParameter("Writable root id; optional when exactly one local root is configured."),
223
327
  path: nonEmptyStringParameter("Safe bundle relative Markdown path for the new concept."),
224
328
  frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
225
329
  body: stringParameter("Markdown body for the new concept."),
226
330
  message: stringParameter("Optional review note explaining why the concept should be created."),
227
331
  },
228
- ["bundle", "path", "frontmatter"],
332
+ ["path", "frontmatter"],
229
333
  ),
230
334
  okf_propose_update: defineTool(
231
335
  "Create a reviewable update proposal for an existing OKF concept while preserving unspecified content.",
@@ -249,6 +353,31 @@ const TOOL_DEFINITIONS = {
249
353
  ],
250
354
  },
251
355
  ),
356
+ okf_propose_attested_computation: defineTool(
357
+ "Create one coordinated review proposal for an Attested Computation concept and optional external computation file; never execute it.",
358
+ LOCAL_WRITE,
359
+ {
360
+ bundle: nonEmptyStringParameter("Writable root id; optional when exactly one local root is configured."),
361
+ path: nonEmptyStringParameter("Safe bundle-relative Markdown path for the computation concept."),
362
+ frontmatter: objectParameter("Complete strict OKF v0.2 Attested Computation frontmatter."),
363
+ body: stringParameter("Markdown body, including inline computation when no computation file is declared."),
364
+ computationPath: nonEmptyStringParameter("Bundle-relative path of the optional external computation file."),
365
+ computationContent: stringParameter("Text content for the optional external computation file."),
366
+ message: stringParameter("Optional review note."),
367
+ },
368
+ ["path", "frontmatter"],
369
+ ),
370
+ okf_propose_v02_migration: defineTool(
371
+ "Create a review-only Stage-A migration manifest plus individual child proposals; never accept them automatically.",
372
+ LOCAL_WRITE,
373
+ {
374
+ bundle: nonEmptyStringParameter("Writable root id; optional when exactly one local root is configured."),
375
+ actorMappings: objectParameter("Mappings keyed by URI, path, or $default; each value requires by plus confirmed: true."),
376
+ generatedPaths: stringArrayParameter("Generated concept paths that must be migrated through their generator.", { nonEmptyItems: true }),
377
+ message: stringParameter("Optional migration review note."),
378
+ },
379
+ [],
380
+ ),
252
381
  okf_list_proposals: defineTool(
253
382
  "List compact metadata for stored authoring proposals.",
254
383
  READ_ONLY,
@@ -291,6 +420,8 @@ const TOOL_DEFINITIONS = {
291
420
  tag: nonEmptyStringParameter("Limit graph nodes to concepts containing this tag."),
292
421
  pathPrefix: stringParameter("Limit graph nodes to bundle relative paths beginning with this prefix."),
293
422
  includeExternal: booleanParameter("Include opaque external relation targets in the graph."),
423
+ includeAssets: booleanParameter("Include explicitly referenced bundle assets as graph nodes."),
424
+ edgeKinds: stringArrayParameter("Limit returned edges to these edge kinds.", { nonEmptyItems: true }),
294
425
  maxNodes: integerParameter("Maximum number of graph nodes to return.", 1, 1000, 100),
295
426
  maxEdges: integerParameter("Maximum number of graph edges to return.", 1, 5000, 300),
296
427
  },
@@ -300,6 +431,9 @@ const TOOL_DEFINITIONS = {
300
431
  READ_ONLY,
301
432
  {
302
433
  uri: nonEmptyStringParameter("Canonical or path based okf URI of the center concept."),
434
+ includeExternal: booleanParameter("Include opaque external neighbors without fetching them."),
435
+ includeAssets: booleanParameter("Include referenced asset neighbors."),
436
+ edgeKinds: stringArrayParameter("Limit neighbors to these edge kinds.", { nonEmptyItems: true }),
303
437
  },
304
438
  ["uri"],
305
439
  ),
@@ -311,6 +445,7 @@ const TOOL_DEFINITIONS = {
311
445
  seeds: stringArrayParameter("One or more okf URIs to use as traversal seeds.", { minItems: 1, nonEmptyItems: true }),
312
446
  depth: integerParameter("Maximum relationship depth to traverse from the seeds.", 0, 10, 1),
313
447
  maxNodes: integerParameter("Maximum number of graph nodes to return.", 1, 1000, 50),
448
+ edgeKinds: stringArrayParameter("Limit traversal to these edge kinds.", { nonEmptyItems: true }),
314
449
  },
315
450
  [],
316
451
  {
@@ -327,6 +462,7 @@ const TOOL_DEFINITIONS = {
327
462
  source: nonEmptyStringParameter("Canonical or path based okf URI where path search begins."),
328
463
  target: nonEmptyStringParameter("Canonical or path based okf URI where path search ends."),
329
464
  maxPaths: integerParameter("Maximum number of distinct paths to return.", 1, 50, 3),
465
+ edgeKinds: stringArrayParameter("Limit path traversal to these edge kinds.", { nonEmptyItems: true }),
330
466
  },
331
467
  ["source", "target"],
332
468
  ),
@@ -351,6 +487,8 @@ const TOOL_DEFINITIONS = {
351
487
  {
352
488
  format: stringParameter("Output format for the graph.", { enum: ["json", "dot", "mermaid"], default: "json" }),
353
489
  includeExternal: booleanParameter("Include opaque external relation targets in the export."),
490
+ includeAssets: booleanParameter("Include explicitly referenced bundle assets in the export."),
491
+ edgeKinds: stringArrayParameter("Limit exported edges to these edge kinds.", { nonEmptyItems: true }),
354
492
  maxNodes: integerParameter("Maximum number of graph nodes to export.", 1, 1000, 100),
355
493
  maxEdges: integerParameter("Maximum number of graph edges to export.", 1, 5000, 300),
356
494
  },
@@ -358,9 +496,6 @@ const TOOL_DEFINITIONS = {
358
496
  };
359
497
 
360
498
  const TOOL_NAMES = Object.keys(TOOL_DEFINITIONS);
361
- TOOL_NAMES.forEach((name) => {
362
- assertSupportedSchema(TOOL_DEFINITIONS[name].inputSchema, `#/tools/${name}/inputSchema`);
363
- });
364
499
  const PROJECT_HELPER_TOOL_NAMES = new Set([
365
500
  "okf_validate_concept",
366
501
  "okf_suggest_concept_path",
@@ -372,6 +507,10 @@ const AUTHORING_MUTATION_TOOL_NAMES = new Set([
372
507
  "okf_propose_update",
373
508
  "okf_accept_proposal",
374
509
  "okf_reject_proposal",
510
+ "okf_propose_v02_migration",
511
+ ]);
512
+ const COMPUTATION_AUTHORING_TOOL_NAMES = new Set([
513
+ "okf_propose_attested_computation",
375
514
  ]);
376
515
  const RUNTIME_REMOTE_TOOL_NAMES = new Set([
377
516
  "load_remote_bundle",
@@ -399,37 +538,24 @@ function toolEnabled(state, name) {
399
538
  if (AUTHORING_MUTATION_TOOL_NAMES.has(name)) {
400
539
  return Boolean(state && state.authoringService && state.allowAuthoring);
401
540
  }
541
+ if (COMPUTATION_AUTHORING_TOOL_NAMES.has(name)) {
542
+ return Boolean(
543
+ state
544
+ && state.authoringService
545
+ && state.allowAuthoring
546
+ && state.allowComputationAuthoring,
547
+ );
548
+ }
402
549
  if (RUNTIME_REMOTE_TOOL_NAMES.has(name)) {
403
550
  return Boolean(state && state.allowRuntimeRemoteLoad);
404
551
  }
405
552
  return true;
406
553
  }
407
554
 
408
- function requireToolEnabled(state, name) {
409
- if (!Object.prototype.hasOwnProperty.call(TOOL_DEFINITIONS, name)) {
410
- throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
411
- detail: "Unknown or unavailable tool",
412
- });
413
- }
414
- if (!toolEnabled(state, name)) {
415
- throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
416
- detail: "Unknown or unavailable tool",
417
- });
418
- }
419
- }
420
-
421
- function listTools(state) {
422
- return {
423
- tools: TOOL_NAMES
424
- .filter((name) => toolEnabled(state, name))
425
- .map((name) => Object.assign({ name }, TOOL_DEFINITIONS[name])),
426
- };
427
- }
428
-
429
555
  function listResources(index) {
430
556
  return {
431
557
  resources: index.documents.map((doc) => ({
432
- uri: doc.uri,
558
+ uri: canonicalResourceUri(doc.uri),
433
559
  name: doc.title,
434
560
  description: doc.description || `${doc.kind} ${doc.path}`,
435
561
  mimeType: "text/markdown",
@@ -437,8 +563,19 @@ function listResources(index) {
437
563
  };
438
564
  }
439
565
 
566
+ function canonicalResourceUri(uri) {
567
+ try {
568
+ return new URL(uri).href;
569
+ } catch {
570
+ return uri;
571
+ }
572
+ }
573
+
440
574
  function publicBundles(index) {
441
575
  return index.bundles.map((bundle) => {
576
+ const documentCount = index.documents.filter((doc) => doc.bundle === bundle.id).length;
577
+ const conceptCount = index.concepts.filter((doc) => doc.bundle === bundle.id).length;
578
+ const assetCount = (index.assets || []).filter((asset) => asset.bundle === bundle.id).length;
442
579
  if (bundle.remote) {
443
580
  return {
444
581
  id: bundle.id,
@@ -448,6 +585,12 @@ function publicBundles(index) {
448
585
  ref: bundle.remoteSource && bundle.remoteSource.ref,
449
586
  path: bundle.remoteSource && bundle.remoteSource.path,
450
587
  fileCount: bundle.remoteSource && bundle.remoteSource.fileCount,
588
+ documentCount,
589
+ conceptCount,
590
+ assetCount,
591
+ okfVersion: bundle.okfVersion || null,
592
+ versionStatus: bundle.versionStatus,
593
+ revision: bundle.remoteSource && (bundle.remoteSource.commitSha || bundle.remoteSource.ref),
451
594
  include: bundle.include || [],
452
595
  exclude: bundle.exclude || [],
453
596
  };
@@ -458,6 +601,11 @@ function publicBundles(index) {
458
601
  return {
459
602
  id: bundle.id,
460
603
  root,
604
+ documentCount,
605
+ conceptCount,
606
+ assetCount,
607
+ okfVersion: bundle.okfVersion || null,
608
+ versionStatus: bundle.versionStatus,
461
609
  include: bundle.include || [],
462
610
  exclude: bundle.exclude || [],
463
611
  };
@@ -465,16 +613,15 @@ function publicBundles(index) {
465
613
  }
466
614
 
467
615
  function readResource(index, uri) {
468
- const doc = index.byUri.get(uri);
616
+ const doc = index.byUri.get(uri)
617
+ || index.documents.find((candidate) => canonicalResourceUri(candidate.uri) === uri);
469
618
  if (!doc) {
470
- throw new ProtocolError(ERROR_CODES.RESOURCE_NOT_FOUND, "Resource not found", {
471
- uri,
472
- });
619
+ throw new ResourceNotFoundError(uri);
473
620
  }
474
621
  return {
475
622
  contents: [
476
623
  {
477
- uri: doc.uri,
624
+ uri: canonicalResourceUri(doc.uri),
478
625
  mimeType: "text/markdown",
479
626
  text: doc.text,
480
627
  },
@@ -493,19 +640,36 @@ function listConcepts(index, args) {
493
640
  return searchConcepts(index, options);
494
641
  }
495
642
 
496
- function getConcept(index, args) {
497
- const uri = args && args.uri ? args.uri : args && args.bundle && args.path ? `okf://${args.bundle}/${args.path}` : null;
498
- if (!uri || !index.byUri.has(uri)) {
499
- throw new ToolExecutionError(`Unknown OKF concept URI: ${uri || "<missing>"}`);
643
+ function getConcept(index, args, repositoryMappings) {
644
+ const locator = args && (args.id || args.uri)
645
+ ? (args.id || args.uri)
646
+ : args && args.bundle && args.path
647
+ ? `okf://${args.bundle}/${args.path}`
648
+ : null;
649
+ const doc = resolveConcept(index, locator);
650
+ if (!doc) {
651
+ throw new ToolExecutionError(`Unknown OKF concept URI or ID: ${locator || "<missing>"}`);
500
652
  }
501
- const doc = index.byUri.get(uri);
502
653
  if (!doc.valid || doc.reserved) {
503
- throw new ToolExecutionError(`URI is not a valid OKF concept: ${uri}`);
654
+ throw new ToolExecutionError(`Locator is not a valid OKF concept: ${locator}`);
504
655
  }
505
656
  return Object.assign(conceptSummary(doc), {
506
657
  frontmatter: doc.frontmatter,
507
658
  body: doc.body,
508
659
  links: doc.links,
660
+ signals: conceptSignals(doc, true),
661
+ referencedAssets: (index.assets || []).filter((asset) => (
662
+ (asset.referencedBy || []).some((reference) => reference.uri === doc.uri)
663
+ )).map((asset) => ({
664
+ uri: asset.uri,
665
+ bundle: asset.bundle,
666
+ path: asset.path,
667
+ mimeType: asset.mimeType,
668
+ size: asset.size,
669
+ sha256: asset.sha256,
670
+ roles: asset.roles,
671
+ })),
672
+ gitSources: describeConceptGitSources(index, doc, repositoryMappings),
509
673
  });
510
674
  }
511
675
 
@@ -535,9 +699,21 @@ function listRelationTypes(index) {
535
699
  return counts;
536
700
  }
537
701
 
702
+ function listEdgeKinds(index) {
703
+ const counts = {};
704
+ index.edges.forEach((edge) => {
705
+ if (!counts[edge.kind]) {
706
+ counts[edge.kind] = { total: 0, resolved: 0, broken: 0 };
707
+ }
708
+ counts[edge.kind].total += 1;
709
+ counts[edge.kind][edge.broken ? "broken" : "resolved"] += 1;
710
+ });
711
+ return counts;
712
+ }
713
+
538
714
  function requireAuthoring(state) {
539
715
  if (!state.authoringService) {
540
- throw new Error("OKF authoring is not configured. Start the server with --project to enable writable concept proposals.");
716
+ throw new Error("OKF authoring is not configured. Start the server with --root or --project to enable writable concept proposals.");
541
717
  }
542
718
  return state.authoringService;
543
719
  }
@@ -545,31 +721,21 @@ function requireAuthoring(state) {
545
721
  function rebuildStateIndex(state) {
546
722
  const index = buildIndex(
547
723
  state.localBundleArgs.concat(state.remoteBundles),
548
- { relationTypes: state.relationTypes },
724
+ {
725
+ relationTypes: state.relationTypes,
726
+ strictLinks: state.strictLinks,
727
+ allowCustomRelationTypes: state.allowCustomRelationTypes,
728
+ },
549
729
  );
550
730
  state.index = state.project ? attachProject(index, state.project) : index;
551
731
  return state.index;
552
732
  }
553
733
 
554
- function invalidParams(detail) {
555
- throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", { detail });
556
- }
557
-
558
- function objectParams(request, method) {
559
- if (!request || !Object.prototype.hasOwnProperty.call(request, "params")) {
560
- return {};
561
- }
562
- if (!isPlainObject(request.params)) {
563
- invalidParams(`${method} params must be an object.`);
564
- }
565
- return request.params;
566
- }
567
-
568
734
  async function expectedToolOperation(operation, options) {
569
735
  try {
570
736
  return await operation();
571
737
  } catch (error) {
572
- if (error instanceof ProtocolError || error instanceof ToolExecutionError) {
738
+ if (error instanceof ToolExecutionError) {
573
739
  throw error;
574
740
  }
575
741
  const programmingError = error instanceof ReferenceError
@@ -584,7 +750,7 @@ async function expectedToolOperation(operation, options) {
584
750
  }
585
751
 
586
752
  function requireGraphConcept(index, uri) {
587
- const doc = uri && index.byUri.get(uri);
753
+ const doc = resolveConcept(index, uri);
588
754
  if (!doc || !doc.valid || doc.reserved) {
589
755
  throw new ToolExecutionError(`Unknown valid OKF concept: ${uri || "<missing>"}`);
590
756
  }
@@ -592,32 +758,6 @@ function requireGraphConcept(index, uri) {
592
758
  }
593
759
 
594
760
  async function callTool(state, name, args) {
595
- if (!state || !state.index) {
596
- state = {
597
- index: state,
598
- localBundleArgs: [],
599
- remoteBundles: [],
600
- relationTypes: state && state.relationTypes,
601
- project: null,
602
- authoringService: null,
603
- allowAuthoring: false,
604
- allowRuntimeRemoteLoad: false,
605
- };
606
- }
607
- requireToolEnabled(state, name);
608
- if (!isPlainObject(args)) {
609
- throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
610
- detail: "tools/call arguments must be an object.",
611
- });
612
- }
613
- const issues = validateToolArguments(TOOL_DEFINITIONS[name].inputSchema, args);
614
- if (issues.length) {
615
- return jsonContent({
616
- error: "Invalid tool arguments",
617
- tool: name,
618
- issues,
619
- }, { isError: true });
620
- }
621
761
  const index = state.index;
622
762
  try {
623
763
  switch (name) {
@@ -626,28 +766,86 @@ async function callTool(state, name, args) {
626
766
  case "list_concepts":
627
767
  return jsonContent(listConcepts(index, args));
628
768
  case "get_concept":
629
- return jsonContent(getConcept(index, args));
769
+ return jsonContent(getConcept(index, args, state.repositoryMappings));
630
770
  case "search_concepts":
631
- return jsonContent(searchConcepts(index, args));
771
+ return jsonContent(await expectedToolOperation(
772
+ () => searchConcepts(index, args),
773
+ { translateTypeError: true },
774
+ ));
632
775
  case "list_types":
633
776
  return jsonContent(listTypes(index));
634
777
  case "list_tags":
635
778
  return jsonContent(listTags(index));
636
779
  case "list_relation_types":
637
780
  return jsonContent(listRelationTypes(index));
781
+ case "list_edge_kinds":
782
+ return jsonContent(listEdgeKinds(index));
783
+ case "get_provenance":
784
+ return jsonContent(await expectedToolOperation(
785
+ () => getProvenance(index, args.uri, args),
786
+ { translateTypeError: true },
787
+ ));
788
+ case "inspect_attested_computation":
789
+ return jsonContent(await expectedToolOperation(
790
+ () => inspectAttestedComputation(index, args.uri, args),
791
+ { translateTypeError: true },
792
+ ));
793
+ case "read_bundle_asset":
794
+ return jsonContent(await expectedToolOperation(
795
+ () => readBundleAsset(index, args),
796
+ { translateTypeError: true },
797
+ ));
798
+ case "read_git_source":
799
+ return jsonContent(await expectedToolOperation(
800
+ () => readConceptGitSource(
801
+ index,
802
+ args.concept,
803
+ args.sourceId,
804
+ state.repositoryMappings,
805
+ { maxBytes: args.maxContentBytes || 65536 },
806
+ ),
807
+ { translateTypeError: true },
808
+ ));
809
+ case "prepare_attested_computation":
810
+ return jsonContent(await expectedToolOperation(
811
+ () => prepareAttestedComputation(index, args.uri, args.parameters, args),
812
+ { translateTypeError: true },
813
+ ));
814
+ case "check_computation_receipt":
815
+ return jsonContent(await expectedToolOperation(
816
+ () => checkComputationReceipt(index, args.uri, args.receipt),
817
+ { translateTypeError: true },
818
+ ));
819
+ case "check_v02_migration": {
820
+ const bundleId = args.bundle || (index.bundles.length === 1 ? index.bundles[0].id : "");
821
+ if (!bundleId) {
822
+ throw new ToolExecutionError("A bundle id is required when more than one OKF root is loaded.");
823
+ }
824
+ if (!index.bundles.some((bundle) => bundle.id === bundleId)) {
825
+ throw new ToolExecutionError(`Unknown OKF bundle: ${bundleId}`);
826
+ }
827
+ return jsonContent(await expectedToolOperation(
828
+ () => checkV02Migration(index, Object.assign({}, args, { bundle: bundleId })),
829
+ { translateTypeError: true },
830
+ ));
831
+ }
638
832
  case "list_remote_bundles":
639
- return jsonContent(state.remoteBundles.map((bundle) => bundle.remoteSource));
833
+ return jsonContent(state.remoteBundles.map((bundle) => Object.assign({ id: bundle.id }, bundle.remoteSource)));
640
834
  case "load_remote_bundle": {
641
835
  const provider = String(args.provider || "github");
642
836
  if (provider !== "github") {
643
837
  throw new ToolExecutionError(`Unsupported remote bundle provider: ${provider}`);
644
838
  }
645
- if (state.index.bundles.some((bundle) => bundle.id === args.id)) {
646
- throw new ToolExecutionError(`Bundle id already loaded: ${args.id}`);
839
+ const normalizedId = sanitizeRemoteId(args.id);
840
+ if (normalizedId !== args.id) {
841
+ throw new ToolExecutionError("Remote bundle id may contain only letters, numbers, underscores, dots, and hyphens.");
842
+ }
843
+ if (state.index.bundles.some((bundle) => bundle.id === normalizedId)) {
844
+ throw new ToolExecutionError(`Bundle id already loaded: ${normalizedId}`);
647
845
  }
648
846
  const remoteBundle = await expectedToolOperation(
649
847
  () => fetchGitHubBundle({
650
- id: args.id,
848
+ id: normalizedId,
651
849
  url: args.url,
652
850
  include: args.include || [],
653
851
  exclude: args.exclude || [],
@@ -678,6 +876,18 @@ async function callTool(state, name, args) {
678
876
  );
679
877
  return jsonContent(result, { isError: result.created === false });
680
878
  }
879
+ case "okf_propose_attested_computation": {
880
+ const result = await expectedToolOperation(
881
+ () => requireAuthoring(state).proposeAttestedComputation(args),
882
+ );
883
+ return jsonContent(result, { isError: result.created === false });
884
+ }
885
+ case "okf_propose_v02_migration": {
886
+ const result = await expectedToolOperation(
887
+ () => requireAuthoring(state).proposeV02Migration(args),
888
+ );
889
+ return jsonContent(result, { isError: result.created === false });
890
+ }
681
891
  case "okf_list_proposals":
682
892
  return jsonContent(await expectedToolOperation(
683
893
  () => requireAuthoring(state).listProposals(args),
@@ -688,7 +898,9 @@ async function callTool(state, name, args) {
688
898
  ));
689
899
  case "okf_accept_proposal": {
690
900
  const result = await expectedToolOperation(
691
- () => requireAuthoring(state).acceptProposal(args),
901
+ () => requireAuthoring(state).acceptProposal(Object.assign({}, args, {
902
+ allowComputation: state.allowComputationAuthoring,
903
+ })),
692
904
  );
693
905
  if (result.accepted) {
694
906
  rebuildStateIndex(state);
@@ -703,7 +915,7 @@ async function callTool(state, name, args) {
703
915
  return jsonContent(getGraph(index, args));
704
916
  case "get_neighbors":
705
917
  requireGraphConcept(index, args.uri);
706
- return jsonContent(getNeighbors(index, args.uri));
918
+ return jsonContent(getNeighbors(index, args.uri, args));
707
919
  case "get_subgraph": {
708
920
  const seeds = args.seeds || [args.uri];
709
921
  seeds.forEach((uri) => requireGraphConcept(index, uri));
@@ -712,7 +924,7 @@ async function callTool(state, name, args) {
712
924
  case "find_paths":
713
925
  requireGraphConcept(index, args.source);
714
926
  requireGraphConcept(index, args.target);
715
- return jsonContent(findPaths(index, args.source, args.target, args.maxPaths));
927
+ return jsonContent(findPaths(index, args.source, args.target, args.maxPaths, args));
716
928
  case "graph_summary":
717
929
  return jsonContent(graphSummary(index));
718
930
  case "validate_bundle":
@@ -732,9 +944,7 @@ async function callTool(state, name, args) {
732
944
  ],
733
945
  };
734
946
  default:
735
- throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
736
- detail: "Unknown or unavailable tool",
737
- });
947
+ throw new Error(`Unknown registered MCP tool: ${name}`);
738
948
  }
739
949
  } catch (error) {
740
950
  if (!(error instanceof ToolExecutionError)) {
@@ -748,7 +958,7 @@ async function callTool(state, name, args) {
748
958
  }
749
959
  }
750
960
 
751
- function createServer(bundleArgs, options) {
961
+ function createState(bundleArgs, options) {
752
962
  const authoringService = options && options.authoringService;
753
963
  let project = null;
754
964
  if (authoringService && authoringService.store) {
@@ -761,9 +971,17 @@ function createServer(bundleArgs, options) {
761
971
  : (bundleArgs || []).slice();
762
972
  const relationTypes = (options && options.relationTypes)
763
973
  || (project && project.relationTypes);
974
+ const allowCustomRelationTypes = Boolean(
975
+ (options && options.allowCustomRelationTypes)
976
+ || (project && project.rootMode),
977
+ );
764
978
  let initialIndex = options && options.initialIndex;
765
979
  if (!initialIndex) {
766
- initialIndex = buildIndex(localBundleArgs, { relationTypes });
980
+ initialIndex = buildIndex(localBundleArgs, {
981
+ relationTypes,
982
+ strictLinks: Boolean((options && options.strictLinks) || (project && project.strictLinks)),
983
+ allowCustomRelationTypes,
984
+ });
767
985
  if (project) {
768
986
  initialIndex = attachProject(initialIndex, project);
769
987
  }
@@ -777,91 +995,15 @@ function createServer(bundleArgs, options) {
777
995
  authoringService,
778
996
  allowAuthoring: Boolean(options && options.allowAuthoring),
779
997
  allowRuntimeRemoteLoad: Boolean(options && options.allowRuntimeRemoteLoad),
998
+ allowComputationAuthoring: Boolean(options && options.allowComputationAuthoring),
999
+ strictLinks: Boolean((options && options.strictLinks) || (project && project.strictLinks)),
1000
+ allowCustomRelationTypes,
1001
+ repositoryMappings: (options && options.repositoryMappings) || new Map(),
780
1002
  };
781
- async function handle(request) {
782
- if (!isPlainObject(request) || typeof request.method !== "string" || !request.method.trim()) {
783
- throw new ProtocolError(ERROR_CODES.INVALID_REQUEST, "Invalid Request", {
784
- detail: "The request method must be a non-empty string.",
785
- });
786
- }
787
- const method = request.method;
788
- if (method === "initialize") {
789
- const params = objectParams(request, method);
790
- const requestedVersion = params.protocolVersion;
791
- if (typeof requestedVersion !== "string" || !requestedVersion.trim()) {
792
- invalidParams("initialize.protocolVersion must be a non-empty string.");
793
- }
794
- if (!isPlainObject(params.capabilities)) {
795
- invalidParams("initialize.capabilities must be an object.");
796
- }
797
- if (!isPlainObject(params.clientInfo)) {
798
- invalidParams("initialize.clientInfo must be an object.");
799
- }
800
- if (typeof params.clientInfo.name !== "string" || !params.clientInfo.name.trim()) {
801
- invalidParams("initialize.clientInfo.name must be a non-empty string.");
802
- }
803
- if (typeof params.clientInfo.version !== "string" || !params.clientInfo.version.trim()) {
804
- invalidParams("initialize.clientInfo.version must be a non-empty string.");
805
- }
806
- return {
807
- protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)
808
- ? requestedVersion
809
- : SUPPORTED_PROTOCOL_VERSIONS[0],
810
- serverInfo: { name: "okf-mcp", version: packageMetadata.version },
811
- capabilities: { resources: {}, tools: {} },
812
- };
813
- }
814
- if (method === "notifications/initialized") {
815
- objectParams(request, method);
816
- return null;
817
- }
818
- if (method === "ping") {
819
- objectParams(request, method);
820
- return {};
821
- }
822
- if (method === "resources/list") {
823
- const params = objectParams(request, method);
824
- if (params.cursor !== undefined && typeof params.cursor !== "string") {
825
- invalidParams("resources/list cursor must be a string when supplied.");
826
- }
827
- return listResources(state.index);
828
- }
829
- if (method === "resources/read") {
830
- const params = objectParams(request, method);
831
- if (typeof params.uri !== "string" || !params.uri) {
832
- invalidParams("resources/read uri must be a non-empty string.");
833
- }
834
- return readResource(state.index, params.uri);
835
- }
836
- if (method === "tools/list") {
837
- const params = objectParams(request, method);
838
- if (params.cursor !== undefined && typeof params.cursor !== "string") {
839
- invalidParams("tools/list cursor must be a string when supplied.");
840
- }
841
- return listTools(state);
842
- }
843
- if (method === "tools/call") {
844
- const params = objectParams(request, method);
845
- if (typeof params.name !== "string" || !params.name.trim()) {
846
- invalidParams("tools/call name must be a non-empty string.");
847
- }
848
- let args = {};
849
- if (Object.prototype.hasOwnProperty.call(params, "arguments")) {
850
- if (!isPlainObject(params.arguments)) {
851
- invalidParams("tools/call arguments must be an object.");
852
- }
853
- args = params.arguments;
854
- }
855
- return callTool(state, params.name, args);
856
- }
857
- throw new ProtocolError(ERROR_CODES.METHOD_NOT_FOUND, "Method not found", {
858
- method,
859
- });
860
- }
861
- return { get index() { return state.index; }, handle };
1003
+ return state;
862
1004
  }
863
1005
 
864
- async function createServerAsync(bundleArgs, options) {
1006
+ async function createStateAsync(bundleArgs, options) {
865
1007
  if (options && options.projectPath) {
866
1008
  const loaded = await loadProjectBundles(options.projectPath);
867
1009
  const extraRemoteBundles = await fetchRemoteBundles(options.remoteBundles || []);
@@ -870,143 +1012,135 @@ async function createServerAsync(bundleArgs, options) {
870
1012
  const store = options.authoringStore || FileConceptStore.fromProject(options.projectPath, { proposalRoot: options.proposalRoot });
871
1013
  const authoringService = options.authoringService || new ConceptAuthoringService(store);
872
1014
  const initialIndex = attachProject(
873
- buildIndex(localBundleArgs.concat(initialRemoteBundles), { relationTypes: loaded.project.relationTypes }),
1015
+ buildIndex(localBundleArgs.concat(initialRemoteBundles), {
1016
+ relationTypes: loaded.project.relationTypes,
1017
+ strictLinks: options.strictLinks || loaded.project.strictLinks,
1018
+ }),
874
1019
  loaded.project,
875
1020
  );
876
- return createServer(localBundleArgs, {
1021
+ return createState(localBundleArgs, {
877
1022
  initialIndex,
878
1023
  initialRemoteBundles,
879
1024
  relationTypes: loaded.project.relationTypes,
880
1025
  authoringService,
881
1026
  allowAuthoring: options.allowAuthoring,
882
1027
  allowRuntimeRemoteLoad: options.allowRuntimeRemoteLoad,
1028
+ allowComputationAuthoring: options.allowComputationAuthoring,
1029
+ strictLinks: options.strictLinks || loaded.project.strictLinks,
1030
+ repositoryMappings: options.repositoryMappings,
1031
+ });
1032
+ }
1033
+ if (options && options.rootPath) {
1034
+ const store = options.authoringStore || FileConceptStore.fromRoot(options.rootPath, {
1035
+ proposalRoot: options.proposalRoot,
1036
+ strictLinks: options.strictLinks,
1037
+ });
1038
+ const authoringService = options.authoringService || new ConceptAuthoringService(store);
1039
+ const localBundleArgs = store.getBundles();
1040
+ const remoteBundles = await fetchRemoteBundles(options.remoteBundles || []);
1041
+ const initialIndex = attachProject(buildIndex(localBundleArgs.concat(remoteBundles), {
1042
+ relationTypes: store.getRelationTypes(),
1043
+ strictLinks: options.strictLinks,
1044
+ allowCustomRelationTypes: true,
1045
+ }), store.project);
1046
+ return createState(localBundleArgs, {
1047
+ initialIndex,
1048
+ initialRemoteBundles: remoteBundles,
1049
+ relationTypes: store.getRelationTypes(),
1050
+ authoringService,
1051
+ allowAuthoring: options.allowAuthoring,
1052
+ allowRuntimeRemoteLoad: options.allowRuntimeRemoteLoad,
1053
+ allowComputationAuthoring: options.allowComputationAuthoring,
1054
+ strictLinks: options.strictLinks,
1055
+ allowCustomRelationTypes: true,
1056
+ repositoryMappings: options.repositoryMappings,
883
1057
  });
884
1058
  }
885
1059
  const remoteBundles = await fetchRemoteBundles((options && options.remoteBundles) || []);
886
1060
  const localBundleArgs = (bundleArgs || []).slice();
887
- return createServer(localBundleArgs, {
888
- initialIndex: buildIndex(localBundleArgs.concat(remoteBundles)),
1061
+ return createState(localBundleArgs, {
1062
+ initialIndex: buildIndex(localBundleArgs.concat(remoteBundles), {
1063
+ strictLinks: options && options.strictLinks,
1064
+ allowCustomRelationTypes: true,
1065
+ }),
889
1066
  initialRemoteBundles: remoteBundles,
1067
+ authoringService: options && options.authoringService,
890
1068
  allowAuthoring: options && options.allowAuthoring,
891
1069
  allowRuntimeRemoteLoad: options && options.allowRuntimeRemoteLoad,
1070
+ allowComputationAuthoring: options && options.allowComputationAuthoring,
1071
+ strictLinks: options && options.strictLinks,
1072
+ allowCustomRelationTypes: true,
1073
+ repositoryMappings: options && options.repositoryMappings,
892
1074
  });
893
1075
  }
894
1076
 
895
- async function runStdioServer(bundleArgs, input, output, options) {
896
- const rl = readline.createInterface({ input, crlfDelay: Infinity });
897
- let serverPromise;
898
- let pending = Promise.resolve();
899
-
900
- function writeResponse(response) {
901
- return new Promise((resolve, reject) => {
902
- output.write(`${JSON.stringify(response)}\n`, (error) => {
903
- if (error) {
904
- reject(error);
905
- return;
906
- }
907
- resolve();
908
- });
909
- });
910
- }
911
-
912
- async function handleLine(line) {
913
- if (!line.trim()) {
914
- return;
915
- }
916
- if (Buffer.byteLength(line, "utf8") > 1024 * 1024) {
917
- await writeResponse(responseFor(null, null, new ProtocolError(
918
- ERROR_CODES.INVALID_REQUEST,
919
- "Invalid Request",
920
- { detail: "MCP request line exceeds 1 MiB." },
921
- )));
922
- return;
923
- }
924
- let request;
925
- try {
926
- request = JSON.parse(line);
927
- } catch (error) {
928
- await writeResponse(responseFor(null, null, new ProtocolError(
929
- ERROR_CODES.PARSE_ERROR,
930
- "Parse error",
931
- )));
932
- return;
933
- }
934
- let envelope;
935
- try {
936
- envelope = validateJsonRpcEnvelope(request);
937
- } catch (error) {
938
- const errorId = isPlainObject(request)
939
- && Object.prototype.hasOwnProperty.call(request, "id")
940
- && isValidRequestId(request.id)
941
- ? request.id
942
- : null;
943
- await writeResponse(responseFor(errorId, null, error));
944
- return;
945
- }
946
- const server = await serverPromise;
947
- if (envelope.notification) {
948
- try {
949
- await server.handle(request);
950
- } catch {
951
- // JSON-RPC notifications are one-way, including when their handling fails.
952
- }
953
- return;
954
- }
955
- try {
956
- const result = await server.handle(request);
957
- await writeResponse(responseFor(envelope.id, result, null));
958
- } catch (error) {
959
- await writeResponse(responseFor(envelope.id, null, error));
960
- }
961
- }
962
-
963
- rl.on("line", (line) => {
964
- pending = pending.then(() => handleLine(line));
1077
+ function registerMcpInterface(state) {
1078
+ const server = new McpServer({
1079
+ name: "okf-mcp",
1080
+ version: packageMetadata.version,
1081
+ }, {
1082
+ capabilities: {
1083
+ resources: { listChanged: false },
1084
+ tools: { listChanged: false },
1085
+ },
965
1086
  });
966
-
967
- const closed = new Promise((resolve, reject) => {
968
- rl.once("close", () => {
969
- // A pending Promise alone does not keep a CommonJS CLI alive after stdin reaches EOF.
970
- const keepAlive = setInterval(() => {}, 1000);
971
- pending.then(
972
- () => {
973
- clearInterval(keepAlive);
974
- resolve();
975
- },
976
- (error) => {
977
- clearInterval(keepAlive);
978
- reject(error);
979
- },
980
- );
981
- });
1087
+ let pendingToolCall = Promise.resolve();
1088
+ const resources = new ResourceTemplate("okf://{+locator}", {
1089
+ list: async () => listResources(state.index),
982
1090
  });
983
-
984
- serverPromise = createServerAsync(bundleArgs, options);
985
- let server;
986
- try {
987
- server = await serverPromise;
988
- } catch (error) {
989
- rl.close();
990
- throw error;
991
- }
992
- Object.defineProperty(server, "closed", {
993
- configurable: false,
994
- enumerable: false,
995
- value: closed,
996
- writable: false,
1091
+ server.registerResource(
1092
+ "okf-documents",
1093
+ resources,
1094
+ {
1095
+ description: "Markdown documents in the loaded Open Knowledge Format catalog.",
1096
+ mimeType: "text/markdown",
1097
+ },
1098
+ async (uri) => readResource(state.index, uri.href),
1099
+ );
1100
+ TOOL_NAMES.filter((name) => toolEnabled(state, name)).forEach((name) => {
1101
+ const definition = TOOL_DEFINITIONS[name];
1102
+ server.registerTool(
1103
+ name,
1104
+ {
1105
+ description: definition.description,
1106
+ annotations: definition.annotations,
1107
+ inputSchema: fromJsonSchema(definition.inputSchema),
1108
+ },
1109
+ async (args) => {
1110
+ const current = pendingToolCall.then(async () => {
1111
+ try {
1112
+ return await callTool(state, name, args);
1113
+ } catch {
1114
+ return jsonContent({
1115
+ error: "Internal tool error",
1116
+ tool: name,
1117
+ }, { isError: true });
1118
+ }
1119
+ });
1120
+ pendingToolCall = current.catch(() => {});
1121
+ return current;
1122
+ },
1123
+ );
997
1124
  });
998
1125
  return server;
999
1126
  }
1000
1127
 
1128
+ async function createMcpServer(bundleArgs, options) {
1129
+ return registerMcpInterface(await createStateAsync(bundleArgs, options));
1130
+ }
1131
+
1132
+ async function runStdioServer(bundleArgs, input, output, options) {
1133
+ const state = await createStateAsync(bundleArgs, options);
1134
+ const transport = new StdioServerTransport(input, output, {
1135
+ maxBufferSize: MAX_MCP_MESSAGE_BYTES,
1136
+ });
1137
+ return serveStdio(
1138
+ () => registerMcpInterface(state),
1139
+ { legacy: "serve", transport },
1140
+ );
1141
+ }
1142
+
1001
1143
  module.exports = {
1002
- SUPPORTED_PROTOCOL_VERSIONS,
1003
- TOOL_NAMES,
1004
- callTool,
1005
- createServer,
1006
- createServerAsync,
1007
- listResources,
1008
- listTools,
1009
- readResource,
1010
- rebuildStateIndex,
1144
+ createMcpServer,
1011
1145
  runStdioServer,
1012
1146
  };