@mfdaves/okf-mcp 0.3.3 → 0.5.1

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