@mfdaves/okf-mcp 0.9.1 → 0.13.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +452 -26
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/distribution/reference-bundle.md +10 -3
  5. package/okf/okf-mcp/index.md +2 -1
  6. package/okf/okf-mcp/interfaces/http-authoring-api.md +11 -2
  7. package/okf/okf-mcp/interfaces/mcp-http.md +64 -0
  8. package/okf/okf-mcp/interfaces/mcp-tools.md +25 -6
  9. package/okf/okf-mcp/overview/okf-mcp.md +16 -6
  10. package/okf/okf-mcp/policies/authoring-safety.md +28 -5
  11. package/okf/okf-mcp/runtime/indexer.md +14 -1
  12. package/okf/okf-mcp/runtime/mcp-server.md +16 -8
  13. package/okf/okf-mcp/specs/producer-api.md +16 -2
  14. package/package.json +17 -5
  15. package/server.json +38 -2
  16. package/src/assets.js +165 -73
  17. package/src/authoring/candidates.js +434 -0
  18. package/src/authoring/git-preflight.js +225 -0
  19. package/src/authoring/git-publish.js +783 -0
  20. package/src/authoring/live.js +757 -0
  21. package/src/authoring/paths.js +112 -0
  22. package/src/authoring/policy-hook.js +221 -0
  23. package/src/authoring/proposal-policy.js +159 -0
  24. package/src/authoring/receipts.js +373 -0
  25. package/src/authoring/render.js +38 -0
  26. package/src/authoring/shared.js +75 -0
  27. package/src/authoring/staging.js +216 -0
  28. package/src/authoring.js +386 -287
  29. package/src/cache/files.js +147 -0
  30. package/src/cache/lock.js +201 -0
  31. package/src/cache/paths.js +197 -0
  32. package/src/cache/store.js +703 -0
  33. package/src/catalog-text.js +19 -0
  34. package/src/cli/commands.js +448 -0
  35. package/src/cli/http-options.js +193 -0
  36. package/src/cli/options.js +554 -0
  37. package/src/cli/usage.js +96 -0
  38. package/src/cli.js +18 -932
  39. package/src/computation.js +99 -61
  40. package/src/context/assemble.js +567 -0
  41. package/src/context/cli-options.js +88 -0
  42. package/src/context/score.js +234 -0
  43. package/src/context/sections.js +274 -0
  44. package/src/embed/interface.js +160 -0
  45. package/src/embed/openai.js +715 -0
  46. package/src/embed/prepare.js +182 -0
  47. package/src/embed/units.js +96 -0
  48. package/src/error-details.js +53 -0
  49. package/src/git-source.js +112 -52
  50. package/src/graph.js +95 -37
  51. package/src/http-server.js +36 -17
  52. package/src/index.js +15 -0
  53. package/src/indexer/assemble.js +566 -0
  54. package/src/indexer/build.js +290 -0
  55. package/src/indexer/cache.js +81 -0
  56. package/src/indexer/edges.js +430 -0
  57. package/src/indexer/index.js +44 -0
  58. package/src/indexer/paths.js +178 -0
  59. package/src/indexer/resolve.js +282 -0
  60. package/src/indexer/update.js +720 -0
  61. package/src/indexer.js +3 -1068
  62. package/src/live-authoring.js +4 -2329
  63. package/src/markdown.js +21 -16
  64. package/src/mcp/auth.js +409 -0
  65. package/src/mcp/http.js +317 -0
  66. package/src/mcp/principal.js +59 -0
  67. package/src/mcp/registry.js +356 -0
  68. package/src/mcp/resources.js +45 -0
  69. package/src/mcp/server.js +567 -0
  70. package/src/mcp/tools/catalog.js +247 -0
  71. package/src/mcp/tools/computation.js +83 -0
  72. package/src/mcp/tools/context.js +133 -0
  73. package/src/mcp/tools/graph.js +167 -0
  74. package/src/mcp/tools/live-authoring.js +316 -0
  75. package/src/mcp/tools/migration.js +86 -0
  76. package/src/mcp/tools/producers.js +79 -0
  77. package/src/mcp/tools/proposals.js +225 -0
  78. package/src/mcp/tools/provenance.js +87 -0
  79. package/src/mcp/tools/remote.js +79 -0
  80. package/src/mcp/tools/search.js +242 -0
  81. package/src/mcp-server.js +3 -1611
  82. package/src/migration.js +431 -253
  83. package/src/parser.js +245 -130
  84. package/src/plugins.js +71 -48
  85. package/src/policy/write-policy.js +713 -0
  86. package/src/producer-publisher.js +202 -78
  87. package/src/producers.js +311 -103
  88. package/src/project.js +346 -93
  89. package/src/remote.js +96 -61
  90. package/src/search/cli-options.js +107 -0
  91. package/src/search/confidence.js +61 -0
  92. package/src/search/dense.js +304 -0
  93. package/src/search/embedding-cli.js +57 -0
  94. package/src/search/embedding-config.js +217 -0
  95. package/src/search/fusion.js +249 -0
  96. package/src/search/hybrid.js +526 -0
  97. package/src/search/languages.js +200 -0
  98. package/src/search/lexical.js +695 -0
  99. package/src/search/query.js +620 -0
  100. package/src/search/stem/among.js +43 -0
  101. package/src/search/stem/base-stemmer.js +311 -0
  102. package/src/search/stem/en-regions.js +456 -0
  103. package/src/search/stem/en-suffixes.js +664 -0
  104. package/src/search/stem/en-tables.js +176 -0
  105. package/src/search/stem/en.js +238 -0
  106. package/src/search/stem/it-regions.js +459 -0
  107. package/src/search/stem/it-suffixes.js +471 -0
  108. package/src/search/stem/it-tables.js +257 -0
  109. package/src/search/stem/it.js +155 -0
  110. package/src/search-index.js +2 -81
  111. package/src/search.js +2 -252
  112. package/src/store.js +134 -81
  113. package/src/tool-packs.js +346 -0
  114. package/src/v02.js +301 -105
  115. package/src/validation.js +24 -20
@@ -0,0 +1,567 @@
1
+ "use strict";
2
+
3
+ const { McpServer, ResourceTemplate, fromJsonSchema } = require("@modelcontextprotocol/server");
4
+ const { StdioServerTransport, serveStdio } = require("@modelcontextprotocol/server/stdio");
5
+ const path = require("node:path");
6
+ const { isDeepStrictEqual } = require("node:util");
7
+ const {
8
+ attachProject,
9
+ buildIndex,
10
+ indexInputs,
11
+ indexUpdateStats,
12
+ loadProjectBundles,
13
+ parseBundleArg,
14
+ refreshIndex,
15
+ updateIndex,
16
+ } = require("../indexer");
17
+ const { fetchRemoteBundles } = require("../remote");
18
+ const { ConceptAuthoringService } = require("../authoring");
19
+ const { LiveAuthoringService } = require("../live-authoring");
20
+ const { FileConceptStore } = require("../store");
21
+ const { DEFAULT_RELATION_TYPES, loadProjectConfig } = require("../project");
22
+ const { ProducerService } = require("../producers");
23
+ const { loadEmbeddingConfigFile } = require("../search/embedding-config");
24
+ const { openEmbeddingRuntime } = require("../search/hybrid");
25
+ const { callPackTool, loadToolPacks, toolPackScopes } = require("../tool-packs");
26
+ const packageMetadata = require("../../package.json");
27
+ const { READ_SCOPE, flagsPrincipal } = require("./principal");
28
+ const { ToolExecutionError, composeRegistry, jsonContent, toolEnabled } = require("./registry");
29
+ const { listResources, readResource } = require("./resources");
30
+
31
+ const MAX_MCP_MESSAGE_BYTES = 1024 * 1024;
32
+
33
+ // Each area module exports its tools with schema, annotations, gate, and
34
+ // handler together; the registry fixes the advertised order and rejects
35
+ // duplicates or tools missing from that order.
36
+ const registry = composeRegistry([
37
+ require("./tools/catalog"),
38
+ require("./tools/search"),
39
+ require("./tools/context"),
40
+ require("./tools/graph"),
41
+ require("./tools/provenance"),
42
+ require("./tools/computation"),
43
+ require("./tools/migration"),
44
+ require("./tools/remote"),
45
+ require("./tools/proposals"),
46
+ require("./tools/live-authoring"),
47
+ require("./tools/producers"),
48
+ ]);
49
+
50
+ // Whether the server's index was built from exactly what the live authoring
51
+ // service would build its own from (the service's bundles with their include
52
+ // and exclude patterns plus the server's remote snapshots, its relation
53
+ // types and flags, a floating date, the server's languages), so the two can
54
+ // share one index object instead of each keeping a copy. The check reads the
55
+ // index's own build record, so an index a host built from other arguments
56
+ // is never shared.
57
+ function liveIndexCompatible(state) {
58
+ const service = state.liveAuthoringService;
59
+ const store = service?.store;
60
+ if (!store || typeof service.adoptIndex !== "function" || store.project !== state.project) {
61
+ return false;
62
+ }
63
+ const built = indexInputs(state.index);
64
+ if (!built) {
65
+ return false;
66
+ }
67
+ const expected = {
68
+ bundles: store
69
+ .getBundles()
70
+ .concat(state.remoteBundles || [])
71
+ .map(parseBundleArg)
72
+ .map((bundle) => ({
73
+ id: bundle.id,
74
+ root: bundle.root,
75
+ remote: Boolean(bundle.remote),
76
+ include: (bundle.include || []).map(String),
77
+ exclude: (bundle.exclude || []).map(String),
78
+ })),
79
+ relationTypes: Array.from(
80
+ new Set((store.getRelationTypes() || DEFAULT_RELATION_TYPES).map(String)),
81
+ ),
82
+ allowCustomRelationTypes: Boolean(store.allowCustomRelationTypes),
83
+ strictLinks: Boolean(store.strictLinks),
84
+ asOf: null,
85
+ // The server stamps its --languages on the index; the service reads none.
86
+ languages: state.languages === undefined ? null : state.languages,
87
+ };
88
+ return isDeepStrictEqual(built, expected);
89
+ }
90
+
91
+ function shareIndexWithLiveAuthoring(state) {
92
+ if (state.shareLiveIndex) {
93
+ state.liveAuthoringService.adoptIndex(state.index, state.remoteBundles);
94
+ }
95
+ }
96
+
97
+ // After a live batch the service hands over what it published: the server
98
+ // adopts the service's index when the two share one, applies the batch to its
99
+ // own index otherwise (brought up to date with the files first, as the
100
+ // service's own index was), and only rebuilds from scratch when there is no
101
+ // batch to apply (producer runs, proposals, remote loads, a stale concept
102
+ // file).
103
+ function rebuildStateIndex(state) {
104
+ const service = state.liveAuthoringService;
105
+ const publication =
106
+ service && typeof service.takePublication === "function" ? service.takePublication() : null;
107
+ if (publication) {
108
+ if (publication.hostOwned && publication.index) {
109
+ state.index = publication.index;
110
+ return state.index;
111
+ }
112
+ if (indexUpdateStats(state.index)) {
113
+ state.index = updateIndex(refreshIndex(state.index), publication.changes);
114
+ return state.index;
115
+ }
116
+ }
117
+ const index = buildIndex(state.localBundleArgs.concat(state.remoteBundles), {
118
+ relationTypes: state.relationTypes,
119
+ strictLinks: state.strictLinks,
120
+ allowCustomRelationTypes: state.allowCustomRelationTypes,
121
+ });
122
+ state.index = state.project ? attachProject(index, state.project) : index;
123
+ if (state.languages) {
124
+ state.index.languages = state.languages;
125
+ }
126
+ shareIndexWithLiveAuthoring(state);
127
+ return state.index;
128
+ }
129
+
130
+ // Runs one tool for a principal (the flags' principal when none is given, as
131
+ // over stdio). A tool whose gate the principal does not pass is unknown to it.
132
+ // Plan I-2c: brings the server's index up to date with files edited outside
133
+ // okf-mcp (size and mtime, refreshIndex) and hands a changed index to live
134
+ // authoring as a write would. Indexes that did not come out of buildIndex
135
+ // are left as they are. Callers run it inside the call queue.
136
+ function refreshStateIndex(state) {
137
+ if (!indexUpdateStats(state.index)) {
138
+ return state.index;
139
+ }
140
+ const refreshed = refreshIndex(state.index);
141
+ if (refreshed !== state.index) {
142
+ state.index = refreshed;
143
+ shareIndexWithLiveAuthoring(state);
144
+ }
145
+ return state.index;
146
+ }
147
+
148
+ async function callTool(state, name, args, principal) {
149
+ const tool = registry.tools[name];
150
+ const caller = principal || flagsPrincipal(state);
151
+ try {
152
+ if (!tool || !toolEnabled(tool, state, caller)) {
153
+ throw new Error(`Unknown registered MCP tool: ${name}`);
154
+ }
155
+ return await tool.handler(state, args, caller);
156
+ } catch (error) {
157
+ if (!(error instanceof ToolExecutionError)) {
158
+ throw error;
159
+ }
160
+ const failure = {
161
+ error: "Tool execution failed",
162
+ tool: name,
163
+ message: error.message,
164
+ ...(error.code ? { code: error.code } : {}),
165
+ ...(error.details !== undefined ? { details: error.details } : {}),
166
+ };
167
+ return jsonContent(failure, { isError: true, structured: true });
168
+ }
169
+ }
170
+
171
+ function createState(bundleArgs, options) {
172
+ const authoringService = options?.authoringService;
173
+ let project = null;
174
+ if (authoringService?.store) {
175
+ project = authoringService.store.project;
176
+ } else if (options?.projectPath) {
177
+ project = loadProjectConfig(options.projectPath);
178
+ }
179
+ const localBundleArgs = project
180
+ ? project.bundles.filter((bundle) => !bundle.remote)
181
+ : (bundleArgs || []).slice();
182
+ const relationTypes = options?.relationTypes || project?.relationTypes;
183
+ const allowCustomRelationTypes = Boolean(options?.allowCustomRelationTypes || project?.rootMode);
184
+ let initialIndex = options?.initialIndex;
185
+ if (!initialIndex) {
186
+ initialIndex = buildIndex(localBundleArgs, {
187
+ relationTypes,
188
+ strictLinks: Boolean(options?.strictLinks || project?.strictLinks),
189
+ allowCustomRelationTypes,
190
+ });
191
+ if (project) {
192
+ initialIndex = attachProject(initialIndex, project);
193
+ }
194
+ }
195
+ const state = {
196
+ index: initialIndex,
197
+ localBundleArgs,
198
+ remoteBundles: options?.initialRemoteBundles || [],
199
+ relationTypes,
200
+ project,
201
+ authoringService,
202
+ liveAuthoringService: options?.liveAuthoringService,
203
+ producerService: options?.producerService,
204
+ allowWrite: Boolean(options?.allowWrite),
205
+ actor: options?.actor,
206
+ allowAuthoring: Boolean(options?.allowAuthoring),
207
+ allowRuntimeRemoteLoad: Boolean(options?.allowRuntimeRemoteLoad),
208
+ allowComputationAuthoring: Boolean(options?.allowComputationAuthoring),
209
+ strictLinks: Boolean(options?.strictLinks || project?.strictLinks),
210
+ allowCustomRelationTypes,
211
+ repositoryMappings: options?.repositoryMappings || new Map(),
212
+ // Search stemming languages from --languages; the project config's value
213
+ // travels on index.project (attachProject) and detection covers the rest.
214
+ languages: options?.languages || undefined,
215
+ // "http" once an HTTP handler serves the state to many principals.
216
+ transport: "stdio",
217
+ // Set by an HTTP handler: run before a call or resource read (plan I-2c).
218
+ refreshBeforeRead: null,
219
+ // Tool packs (plan D1) and the scopes their tools declare beyond okf.*.
220
+ toolPacks: [],
221
+ toolPackScopes: [],
222
+ // One tool-call queue per process: every McpServer built on this state
223
+ // (one per stdio connection, one per HTTP request) runs its tool calls
224
+ // through it, so calls from different sessions never interleave.
225
+ callQueue: Promise.resolve(),
226
+ };
227
+ if (state.languages) {
228
+ state.index.languages = state.languages;
229
+ }
230
+ // Tool handlers refresh the index through the state so index construction
231
+ // stays in this module; handlers never see bundle arguments or build options.
232
+ state.rebuildIndex = () => rebuildStateIndex(state);
233
+ state.refreshIndex = () => refreshStateIndex(state);
234
+ state.shareLiveIndex = liveIndexCompatible(state);
235
+ shareIndexWithLiveAuthoring(state);
236
+ if (
237
+ !state.producerService &&
238
+ project &&
239
+ (project.producers || []).length &&
240
+ authoringService?.store
241
+ ) {
242
+ state.producerService = new ProducerService({
243
+ project,
244
+ store: authoringService.store,
245
+ bundles: localBundleArgs,
246
+ loader: options?.producerLoader,
247
+ env: options?.producerEnv,
248
+ now: options?.producerNow,
249
+ });
250
+ }
251
+ return state;
252
+ }
253
+
254
+ // Hybrid search settings (WP3c): a library caller's settings object, the
255
+ // --embedder-config file of --root mode, or the project's own; --cache-dir
256
+ // (relative to the working directory) overrides the cache location.
257
+ function embeddingSettings(projectSettings, options) {
258
+ const given = options?.embedding || {};
259
+ const base = given.embedder
260
+ ? given
261
+ : given.configPath
262
+ ? loadEmbeddingConfigFile(given.configPath)
263
+ : projectSettings;
264
+ if (!base) return null;
265
+ return given.cacheDir
266
+ ? Object.assign({}, base, { cacheDir: path.resolve(given.cacheDir) })
267
+ : base;
268
+ }
269
+
270
+ // Opens the embedding runtime (never throws: failures leave it degraded) and
271
+ // prepares the missing vectors in the background, so a large first embed
272
+ // never delays the server's start; searches stay lexical until rows exist.
273
+ async function attachEmbeddings(state, settings, context) {
274
+ if (!settings) return state;
275
+ state.embeddings = await openEmbeddingRuntime(settings, context);
276
+ state.embeddings.scheduleSync(state.index);
277
+ return state;
278
+ }
279
+
280
+ async function createStateAsync(bundleArgs, options) {
281
+ if (options?.projectPath) {
282
+ const loaded = await loadProjectBundles(options.projectPath);
283
+ // Tool packs load first: a pack that fails stops the server at startup.
284
+ const toolPacks = await loadToolPacks(loaded.project, {
285
+ loader: options.toolPackLoader,
286
+ env: options.toolPackEnv,
287
+ coreNames: registry.names,
288
+ });
289
+ const extraRemoteBundles = await fetchRemoteBundles(options.remoteBundles || []);
290
+ const initialRemoteBundles = loaded.remoteBundles.concat(extraRemoteBundles);
291
+ const localBundleArgs = (loaded.bundles || []).filter((bundle) => !bundle.remote);
292
+ const store =
293
+ options.authoringStore ||
294
+ FileConceptStore.fromProject(options.projectPath, { proposalRoot: options.proposalRoot });
295
+ const authoringService =
296
+ options.authoringService ||
297
+ new ConceptAuthoringService(store, {
298
+ actor: options.actor,
299
+ writePolicy: options.writePolicy,
300
+ });
301
+ const liveAuthoringService =
302
+ options.liveAuthoringService ||
303
+ (options.allowWrite
304
+ ? new LiveAuthoringService(store, {
305
+ actor: options.actor,
306
+ gitCommit: options.gitCommit,
307
+ writePolicy: options.writePolicy,
308
+ })
309
+ : null);
310
+ const initialIndex = attachProject(
311
+ buildIndex(localBundleArgs.concat(initialRemoteBundles), {
312
+ relationTypes: loaded.project.relationTypes,
313
+ strictLinks: options.strictLinks || loaded.project.strictLinks,
314
+ }),
315
+ loaded.project,
316
+ );
317
+ const projectState = createState(localBundleArgs, {
318
+ initialIndex,
319
+ initialRemoteBundles,
320
+ relationTypes: loaded.project.relationTypes,
321
+ authoringService,
322
+ liveAuthoringService,
323
+ producerService: options.producerService,
324
+ producerLoader: options.producerLoader,
325
+ producerEnv: options.producerEnv,
326
+ producerNow: options.producerNow,
327
+ allowWrite: options.allowWrite,
328
+ actor: options.actor,
329
+ allowAuthoring: options.allowAuthoring,
330
+ allowRuntimeRemoteLoad: options.allowRuntimeRemoteLoad,
331
+ allowComputationAuthoring: options.allowComputationAuthoring,
332
+ strictLinks: options.strictLinks || loaded.project.strictLinks,
333
+ repositoryMappings: options.repositoryMappings,
334
+ languages: options.languages,
335
+ });
336
+ projectState.toolPacks = toolPacks;
337
+ projectState.toolPackScopes = toolPackScopes(toolPacks);
338
+ return attachEmbeddings(projectState, embeddingSettings(loaded.project.embedding, options), {
339
+ root: loaded.project.root,
340
+ write: Boolean(options.allowWrite),
341
+ });
342
+ }
343
+ if (options?.rootPath) {
344
+ const store =
345
+ options.authoringStore ||
346
+ FileConceptStore.fromRoot(options.rootPath, {
347
+ proposalRoot: options.proposalRoot,
348
+ strictLinks: options.strictLinks,
349
+ });
350
+ const authoringService =
351
+ options.authoringService ||
352
+ new ConceptAuthoringService(store, {
353
+ actor: options.actor,
354
+ writePolicy: options.writePolicy,
355
+ });
356
+ const liveAuthoringService =
357
+ options.liveAuthoringService ||
358
+ (options.allowWrite
359
+ ? new LiveAuthoringService(store, {
360
+ actor: options.actor,
361
+ gitCommit: options.gitCommit,
362
+ writePolicy: options.writePolicy,
363
+ })
364
+ : null);
365
+ const localBundleArgs = store.getBundles();
366
+ const remoteBundles = await fetchRemoteBundles(options.remoteBundles || []);
367
+ const initialIndex = attachProject(
368
+ buildIndex(localBundleArgs.concat(remoteBundles), {
369
+ relationTypes: store.getRelationTypes(),
370
+ strictLinks: options.strictLinks,
371
+ allowCustomRelationTypes: true,
372
+ }),
373
+ store.project,
374
+ );
375
+ const rootState = createState(localBundleArgs, {
376
+ initialIndex,
377
+ initialRemoteBundles: remoteBundles,
378
+ relationTypes: store.getRelationTypes(),
379
+ authoringService,
380
+ liveAuthoringService,
381
+ producerService: options.producerService,
382
+ allowWrite: options.allowWrite,
383
+ actor: options.actor,
384
+ allowAuthoring: options.allowAuthoring,
385
+ allowRuntimeRemoteLoad: options.allowRuntimeRemoteLoad,
386
+ allowComputationAuthoring: options.allowComputationAuthoring,
387
+ strictLinks: options.strictLinks,
388
+ allowCustomRelationTypes: true,
389
+ repositoryMappings: options.repositoryMappings,
390
+ languages: options.languages,
391
+ });
392
+ return attachEmbeddings(rootState, embeddingSettings(null, options), {
393
+ root: options.rootPath,
394
+ write: Boolean(options.allowWrite),
395
+ });
396
+ }
397
+ const remoteBundles = await fetchRemoteBundles(options?.remoteBundles || []);
398
+ const localBundleArgs = (bundleArgs || []).slice();
399
+ const liveAuthoringService = options?.liveAuthoringService
400
+ ? options.liveAuthoringService
401
+ : options?.allowWrite && options.authoringService?.store
402
+ ? new LiveAuthoringService(options.authoringService.store, {
403
+ actor: options.actor,
404
+ gitCommit: options.gitCommit,
405
+ writePolicy: options.writePolicy,
406
+ })
407
+ : null;
408
+ if (options?.allowWrite && !liveAuthoringService) {
409
+ throw new Error("Live OKF authoring requires --root or --project and a configured actor.");
410
+ }
411
+ return createState(localBundleArgs, {
412
+ initialIndex: buildIndex(localBundleArgs.concat(remoteBundles), {
413
+ strictLinks: options?.strictLinks,
414
+ allowCustomRelationTypes: true,
415
+ }),
416
+ initialRemoteBundles: remoteBundles,
417
+ authoringService: options?.authoringService,
418
+ liveAuthoringService,
419
+ producerService: options?.producerService,
420
+ allowWrite: options?.allowWrite,
421
+ actor: options?.actor,
422
+ allowAuthoring: options?.allowAuthoring,
423
+ allowRuntimeRemoteLoad: options?.allowRuntimeRemoteLoad,
424
+ allowComputationAuthoring: options?.allowComputationAuthoring,
425
+ strictLinks: options?.strictLinks,
426
+ allowCustomRelationTypes: true,
427
+ repositoryMappings: options?.repositoryMappings,
428
+ languages: options?.languages,
429
+ });
430
+ }
431
+
432
+ // Runs a read of the index. With a refresher set (MCP over HTTP, plan I-2c)
433
+ // the read goes through the call queue and the refresher runs first in the
434
+ // same job, so the check is taken in arrival order with the calls; without
435
+ // one (stdio) the read runs as before.
436
+ function readIndex(state, read) {
437
+ if (!state.refreshBeforeRead) return read();
438
+ const current = state.callQueue.then(() => {
439
+ state.refreshBeforeRead();
440
+ return read();
441
+ });
442
+ state.callQueue = current.catch(() => {});
443
+ return current;
444
+ }
445
+
446
+ // The configured tool packs' tools the principal may use, after the core
447
+ // tools: it needs okf.read and the tool's scope. A pack call runs outside the
448
+ // call queue unless its pack sets serialize: true; `subjectToken` is the
449
+ // caller's bearer token over HTTP and absent over stdio.
450
+ function registerToolPackTools(server, state, caller, subjectToken) {
451
+ if (!caller.scopes.has(READ_SCOPE)) return;
452
+ for (const pack of state.toolPacks) {
453
+ for (const tool of pack.tools) {
454
+ if (!caller.scopes.has(tool.scope)) continue;
455
+ // A tool that acts for the caller elsewhere needs the caller's token.
456
+ if (tool.requiresSubjectToken && !subjectToken) continue;
457
+ server.registerTool(
458
+ tool.name,
459
+ {
460
+ description: tool.description,
461
+ annotations: tool.annotations,
462
+ inputSchema: fromJsonSchema(tool.inputSchema),
463
+ ...(tool.outputSchema ? { outputSchema: fromJsonSchema(tool.outputSchema) } : {}),
464
+ },
465
+ async (args, ctx) => {
466
+ const run = () =>
467
+ callPackTool(pack, tool, args, caller, { subjectToken, signal: ctx?.mcpReq?.signal });
468
+ if (!pack.serialize) return run();
469
+ const current = state.callQueue.then(run);
470
+ state.callQueue = current.catch(() => {});
471
+ return current;
472
+ },
473
+ );
474
+ }
475
+ }
476
+ }
477
+
478
+ // One McpServer over shared state, advertising and serving the tools the
479
+ // principal may use (the flags' principal when none is given, as over stdio).
480
+ // `options.subjectToken` is the HTTP caller's bearer token, for tool packs.
481
+ function registerMcpInterface(state, principal, options) {
482
+ const caller = principal || flagsPrincipal(state);
483
+ const server = new McpServer(
484
+ {
485
+ name: "okf-mcp",
486
+ version: packageMetadata.version,
487
+ },
488
+ {
489
+ capabilities: {
490
+ resources: { listChanged: false },
491
+ tools: { listChanged: false },
492
+ },
493
+ },
494
+ );
495
+ const resources = new ResourceTemplate("okf://{+locator}", {
496
+ list: async () => readIndex(state, () => listResources(state.index)),
497
+ });
498
+ server.registerResource(
499
+ "okf-documents",
500
+ resources,
501
+ {
502
+ description: "Markdown documents in the loaded Open Knowledge Format catalog.",
503
+ mimeType: "text/markdown",
504
+ },
505
+ async (uri) => readIndex(state, () => readResource(state.index, uri.href)),
506
+ );
507
+ registry.names
508
+ .filter((name) => toolEnabled(registry.tools[name], state, caller))
509
+ .forEach((name) => {
510
+ const definition = registry.tools[name];
511
+ server.registerTool(
512
+ name,
513
+ {
514
+ description: definition.description,
515
+ annotations: definition.annotations,
516
+ inputSchema: fromJsonSchema(definition.inputSchema),
517
+ ...(definition.outputSchema
518
+ ? { outputSchema: fromJsonSchema(definition.outputSchema) }
519
+ : {}),
520
+ },
521
+ async (args) => {
522
+ const current = state.callQueue.then(async () => {
523
+ try {
524
+ state.refreshBeforeRead?.();
525
+ return await callTool(state, name, args, caller);
526
+ } catch {
527
+ return jsonContent(
528
+ {
529
+ error: "Internal tool error",
530
+ tool: name,
531
+ },
532
+ { isError: true },
533
+ );
534
+ }
535
+ });
536
+ state.callQueue = current.catch(() => {});
537
+ return current;
538
+ },
539
+ );
540
+ });
541
+ registerToolPackTools(server, state, caller, options?.subjectToken);
542
+ return server;
543
+ }
544
+
545
+ async function createMcpServer(bundleArgs, options) {
546
+ return registerMcpInterface(await createStateAsync(bundleArgs, options));
547
+ }
548
+
549
+ async function runStdioServer(bundleArgs, input, output, options) {
550
+ const state = await createStateAsync(bundleArgs, options);
551
+ const transport = new StdioServerTransport(input, output, {
552
+ maxBufferSize: MAX_MCP_MESSAGE_BYTES,
553
+ });
554
+ return serveStdio(() => registerMcpInterface(state), { legacy: "serve", transport });
555
+ }
556
+
557
+ module.exports = {
558
+ MAX_MCP_MESSAGE_BYTES,
559
+ createMcpServer,
560
+ runStdioServer,
561
+ /** @internal Exposed for tests that need the server state behind a tool call. */
562
+ callTool,
563
+ /** @internal */
564
+ createStateAsync,
565
+ /** @internal Builds one McpServer over an existing state (tests share one state). */
566
+ registerMcpInterface,
567
+ };