@mfdaves/okf-mcp 0.3.2 → 0.3.3

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.
package/src/mcp-server.js CHANGED
@@ -15,9 +15,21 @@ const { fetchGitHubBundle, fetchRemoteBundles } = require("./remote");
15
15
  const { ConceptAuthoringService } = require("./authoring");
16
16
  const { FileConceptStore } = require("./store");
17
17
  const { loadProjectConfig } = require("./project");
18
+ const {
19
+ ERROR_CODES,
20
+ ProtocolError,
21
+ ToolExecutionError,
22
+ assertSupportedSchema,
23
+ isPlainObject,
24
+ isValidRequestId,
25
+ responseFor,
26
+ validateJsonRpcEnvelope,
27
+ validateToolArguments,
28
+ } = require("./mcp-protocol");
18
29
  const packageMetadata = require("../package.json");
19
30
 
20
31
  const SUPPORTED_PROTOCOL_VERSIONS = [
32
+ "2025-11-25",
21
33
  "2025-06-18",
22
34
  "2025-03-26",
23
35
  "2024-11-05",
@@ -52,28 +64,43 @@ function stringParameter(description, extra) {
52
64
  return Object.assign({ type: "string", description }, extra || {});
53
65
  }
54
66
 
55
- function numberParameter(description, extra) {
56
- return Object.assign({ type: "number", description }, extra || {});
67
+ function nonEmptyStringParameter(description, extra) {
68
+ return stringParameter(description, Object.assign({ minLength: 1 }, extra || {}));
69
+ }
70
+
71
+ function integerParameter(description, minimum, maximum, defaultValue) {
72
+ return {
73
+ type: "integer",
74
+ description,
75
+ minimum,
76
+ ...(maximum === undefined ? {} : { maximum }),
77
+ default: defaultValue,
78
+ };
57
79
  }
58
80
 
59
81
  function booleanParameter(description) {
60
- return { type: "boolean", description };
82
+ return { type: "boolean", description, default: false };
61
83
  }
62
84
 
63
- function stringArrayParameter(description) {
85
+ function stringArrayParameter(description, options) {
86
+ const config = options || {};
64
87
  return {
65
88
  type: "array",
66
89
  description,
67
- items: { type: "string" },
90
+ items: Object.assign(
91
+ { type: "string" },
92
+ config.nonEmptyItems ? { minLength: 1 } : {},
93
+ ),
94
+ ...(config.minItems === undefined ? {} : { minItems: config.minItems }),
68
95
  };
69
96
  }
70
97
 
71
- function objectParameter(description) {
72
- return {
98
+ function objectParameter(description, extra) {
99
+ return Object.assign({
73
100
  type: "object",
74
101
  description,
75
102
  additionalProperties: true,
76
- };
103
+ }, extra || {});
77
104
  }
78
105
 
79
106
  function defineTool(description, annotations, properties, required, schemaExtras) {
@@ -100,20 +127,20 @@ const TOOL_DEFINITIONS = {
100
127
  READ_ONLY,
101
128
  {
102
129
  query: stringParameter("Optional text matched against concept metadata and content."),
103
- bundle: stringParameter("Limit results to this bundle id."),
104
- type: stringParameter("Limit results to this exact concept type."),
105
- tag: stringParameter("Limit results to concepts containing this tag."),
106
- limit: numberParameter("Maximum number of concepts to return."),
107
- offset: numberParameter("Number of matching concepts to skip before returning results."),
130
+ bundle: nonEmptyStringParameter("Limit results to this bundle id."),
131
+ type: nonEmptyStringParameter("Limit results to this exact concept type."),
132
+ tag: nonEmptyStringParameter("Limit results to concepts containing this tag."),
133
+ limit: integerParameter("Maximum number of concepts to return.", 1, 250, 25),
134
+ offset: integerParameter("Number of matching concepts to skip before returning results.", 0, undefined, 0),
108
135
  },
109
136
  ),
110
137
  get_concept: defineTool(
111
138
  "Read one valid OKF concept, including its frontmatter, Markdown body, and links.",
112
139
  READ_ONLY,
113
140
  {
114
- uri: stringParameter("Canonical or path based okf URI for the concept."),
115
- bundle: stringParameter("Bundle id used with path when uri is not supplied."),
116
- path: stringParameter("Bundle relative Markdown path used with bundle when uri is not supplied."),
141
+ uri: nonEmptyStringParameter("Canonical or path based okf URI for the concept."),
142
+ bundle: nonEmptyStringParameter("Bundle id used with path when uri is not supplied."),
143
+ path: nonEmptyStringParameter("Bundle relative Markdown path used with bundle when uri is not supplied."),
117
144
  },
118
145
  [],
119
146
  {
@@ -128,14 +155,14 @@ const TOOL_DEFINITIONS = {
128
155
  READ_ONLY,
129
156
  {
130
157
  query: stringParameter("Text query matched against concept metadata and content."),
131
- bundle: stringParameter("Limit results to this bundle id."),
132
- types: stringArrayParameter("Limit results to any of these concept types."),
133
- tagsAny: stringArrayParameter("Require at least one of these tags."),
134
- tagsAll: stringArrayParameter("Require all of these tags."),
158
+ bundle: nonEmptyStringParameter("Limit results to this bundle id."),
159
+ types: stringArrayParameter("Limit results to any of these concept types.", { nonEmptyItems: true }),
160
+ tagsAny: stringArrayParameter("Require at least one of these tags.", { nonEmptyItems: true }),
161
+ tagsAll: stringArrayParameter("Require all of these tags.", { nonEmptyItems: true }),
135
162
  pathPrefix: stringParameter("Limit results to bundle relative paths beginning with this prefix."),
136
- relationType: stringParameter("Limit results to concepts participating in this relation type."),
137
- limit: numberParameter("Maximum number of concepts to return."),
138
- offset: numberParameter("Number of matching concepts to skip before returning results."),
163
+ relationType: nonEmptyStringParameter("Limit results to concepts with an outgoing relation of this type."),
164
+ limit: integerParameter("Maximum number of concepts to return.", 1, 250, 25),
165
+ offset: integerParameter("Number of matching concepts to skip before returning results.", 0, undefined, 0),
139
166
  },
140
167
  ),
141
168
  list_types: defineTool(
@@ -154,11 +181,11 @@ const TOOL_DEFINITIONS = {
154
181
  "Fetch a public GitHub Markdown tree and add it to the in memory index as a read only remote bundle.",
155
182
  REMOTE_LOAD,
156
183
  {
157
- id: stringParameter("Unique bundle id to assign to the fetched remote tree."),
158
- url: stringParameter("Public GitHub tree URL to fetch."),
159
- provider: stringParameter("Remote provider name. Only github is supported.", { enum: ["github"] }),
160
- include: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to include."),
161
- exclude: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to exclude."),
184
+ id: nonEmptyStringParameter("Unique bundle id to assign to the fetched remote tree."),
185
+ url: nonEmptyStringParameter("Public GitHub tree URL to fetch."),
186
+ provider: stringParameter("Remote provider name. Only github is supported.", { enum: ["github"], default: "github" }),
187
+ include: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to include.", { nonEmptyItems: true }),
188
+ exclude: stringArrayParameter("Optional glob patterns selecting remote Markdown paths to exclude.", { nonEmptyItems: true }),
162
189
  },
163
190
  ["id", "url"],
164
191
  ),
@@ -170,8 +197,8 @@ const TOOL_DEFINITIONS = {
170
197
  "Validate a proposed new OKF concept without writing a proposal or concept file.",
171
198
  READ_ONLY,
172
199
  {
173
- bundle: stringParameter("Writable bundle id that would contain the concept."),
174
- path: stringParameter("Safe bundle relative Markdown path for the concept."),
200
+ bundle: nonEmptyStringParameter("Writable bundle id that would contain the concept."),
201
+ path: nonEmptyStringParameter("Safe bundle relative Markdown path for the concept."),
175
202
  frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
176
203
  body: stringParameter("Markdown body for the concept."),
177
204
  },
@@ -181,9 +208,9 @@ const TOOL_DEFINITIONS = {
181
208
  "Suggest a safe bundle relative Markdown path from a concept type and title.",
182
209
  READ_ONLY,
183
210
  {
184
- bundle: stringParameter("Writable bundle id that will contain the concept."),
185
- type: stringParameter("Concept type used to build the path."),
186
- title: stringParameter("Concept title used to build the file name."),
211
+ bundle: nonEmptyStringParameter("Writable bundle id that will contain the concept."),
212
+ type: nonEmptyStringParameter("Concept type used to build the path."),
213
+ title: nonEmptyStringParameter("Concept title used to build the file name."),
187
214
  prefix: stringParameter("Optional bundle relative directory prefix."),
188
215
  },
189
216
  ["bundle", "type", "title"],
@@ -192,8 +219,8 @@ const TOOL_DEFINITIONS = {
192
219
  "Create a reviewable proposal for a new OKF concept without writing the concept file.",
193
220
  LOCAL_WRITE,
194
221
  {
195
- bundle: stringParameter("Writable bundle id that will contain the concept."),
196
- path: stringParameter("Safe bundle relative Markdown path for the new concept."),
222
+ bundle: nonEmptyStringParameter("Writable bundle id that will contain the concept."),
223
+ path: nonEmptyStringParameter("Safe bundle relative Markdown path for the new concept."),
197
224
  frontmatter: objectParameter("Complete YAML frontmatter represented as a JSON object."),
198
225
  body: stringParameter("Markdown body for the new concept."),
199
226
  message: stringParameter("Optional review note explaining why the concept should be created."),
@@ -204,9 +231,12 @@ const TOOL_DEFINITIONS = {
204
231
  "Create a reviewable update proposal for an existing OKF concept while preserving unspecified content.",
205
232
  LOCAL_WRITE,
206
233
  {
207
- uri: stringParameter("Canonical or path based okf URI of the existing concept."),
208
- frontmatter: objectParameter("Frontmatter fields to add or replace; unspecified fields are preserved."),
209
- removeFrontmatterKeys: stringArrayParameter("Frontmatter keys to remove; the id field cannot be removed."),
234
+ uri: nonEmptyStringParameter("Canonical or path based okf URI of the existing concept."),
235
+ frontmatter: objectParameter(
236
+ "Frontmatter fields to add or replace; unspecified fields are preserved.",
237
+ { minProperties: 1 },
238
+ ),
239
+ removeFrontmatterKeys: stringArrayParameter("Frontmatter keys to remove; the id field cannot be removed.", { minItems: 1, nonEmptyItems: true }),
210
240
  body: stringParameter("Replacement Markdown body; omit it to preserve the current body."),
211
241
  message: stringParameter("Optional review note explaining why the concept should be updated."),
212
242
  },
@@ -223,7 +253,7 @@ const TOOL_DEFINITIONS = {
223
253
  "List compact metadata for stored authoring proposals.",
224
254
  READ_ONLY,
225
255
  {
226
- bundle: stringParameter("Limit results to proposals for this bundle id."),
256
+ bundle: nonEmptyStringParameter("Limit results to proposals for this bundle id."),
227
257
  status: stringParameter("Limit results to this proposal status.", { enum: ["proposed", "accepted", "rejected"] }),
228
258
  },
229
259
  ),
@@ -231,7 +261,7 @@ const TOOL_DEFINITIONS = {
231
261
  "Read one authoring proposal, including its candidate content and validation result.",
232
262
  READ_ONLY,
233
263
  {
234
- proposalId: stringParameter("Identifier returned when the proposal was created."),
264
+ proposalId: nonEmptyStringParameter("Identifier returned when the proposal was created."),
235
265
  },
236
266
  ["proposalId"],
237
267
  ),
@@ -239,7 +269,7 @@ const TOOL_DEFINITIONS = {
239
269
  "Accept a reviewed proposal and write its new or updated concept file after revalidation.",
240
270
  DESTRUCTIVE_WRITE,
241
271
  {
242
- proposalId: stringParameter("Identifier of the proposed change to accept."),
272
+ proposalId: nonEmptyStringParameter("Identifier of the proposed change to accept."),
243
273
  },
244
274
  ["proposalId"],
245
275
  ),
@@ -247,7 +277,7 @@ const TOOL_DEFINITIONS = {
247
277
  "Reject a reviewed proposal so it can no longer be accepted.",
248
278
  DESTRUCTIVE_WRITE,
249
279
  {
250
- proposalId: stringParameter("Identifier of the proposed change to reject."),
280
+ proposalId: nonEmptyStringParameter("Identifier of the proposed change to reject."),
251
281
  reason: stringParameter("Optional explanation recorded with the rejection."),
252
282
  },
253
283
  ["proposalId"],
@@ -256,20 +286,20 @@ const TOOL_DEFINITIONS = {
256
286
  "Return a bounded set of OKF graph nodes and edges with optional concept filters.",
257
287
  READ_ONLY,
258
288
  {
259
- bundle: stringParameter("Limit graph nodes to this bundle id."),
260
- type: stringParameter("Limit graph nodes to this exact concept type."),
261
- tag: stringParameter("Limit graph nodes to concepts containing this tag."),
289
+ bundle: nonEmptyStringParameter("Limit graph nodes to this bundle id."),
290
+ type: nonEmptyStringParameter("Limit graph nodes to this exact concept type."),
291
+ tag: nonEmptyStringParameter("Limit graph nodes to concepts containing this tag."),
262
292
  pathPrefix: stringParameter("Limit graph nodes to bundle relative paths beginning with this prefix."),
263
293
  includeExternal: booleanParameter("Include opaque external relation targets in the graph."),
264
- maxNodes: numberParameter("Maximum number of graph nodes to return."),
265
- maxEdges: numberParameter("Maximum number of graph edges to return."),
294
+ maxNodes: integerParameter("Maximum number of graph nodes to return.", 1, 1000, 100),
295
+ maxEdges: integerParameter("Maximum number of graph edges to return.", 1, 5000, 300),
266
296
  },
267
297
  ),
268
298
  get_neighbors: defineTool(
269
299
  "Return the incoming and outgoing graph relationships for one OKF concept.",
270
300
  READ_ONLY,
271
301
  {
272
- uri: stringParameter("Canonical or path based okf URI of the center concept."),
302
+ uri: nonEmptyStringParameter("Canonical or path based okf URI of the center concept."),
273
303
  },
274
304
  ["uri"],
275
305
  ),
@@ -277,10 +307,10 @@ const TOOL_DEFINITIONS = {
277
307
  "Traverse a bounded OKF subgraph outward from one or more seed concepts.",
278
308
  READ_ONLY,
279
309
  {
280
- uri: stringParameter("Single canonical or path based okf URI to use as a seed."),
281
- seeds: stringArrayParameter("One or more okf URIs to use as traversal seeds."),
282
- depth: numberParameter("Maximum relationship depth to traverse from the seeds."),
283
- maxNodes: numberParameter("Maximum number of graph nodes to return."),
310
+ uri: nonEmptyStringParameter("Single canonical or path based okf URI to use as a seed."),
311
+ seeds: stringArrayParameter("One or more okf URIs to use as traversal seeds.", { minItems: 1, nonEmptyItems: true }),
312
+ depth: integerParameter("Maximum relationship depth to traverse from the seeds.", 0, 10, 1),
313
+ maxNodes: integerParameter("Maximum number of graph nodes to return.", 1, 1000, 50),
284
314
  },
285
315
  [],
286
316
  {
@@ -294,9 +324,9 @@ const TOOL_DEFINITIONS = {
294
324
  "Find bounded relationship paths between two OKF concepts.",
295
325
  READ_ONLY,
296
326
  {
297
- source: stringParameter("Canonical or path based okf URI where path search begins."),
298
- target: stringParameter("Canonical or path based okf URI where path search ends."),
299
- maxPaths: numberParameter("Maximum number of distinct paths to return."),
327
+ source: nonEmptyStringParameter("Canonical or path based okf URI where path search begins."),
328
+ target: nonEmptyStringParameter("Canonical or path based okf URI where path search ends."),
329
+ maxPaths: integerParameter("Maximum number of distinct paths to return.", 1, 50, 3),
300
330
  },
301
331
  ["source", "target"],
302
332
  ),
@@ -308,7 +338,7 @@ const TOOL_DEFINITIONS = {
308
338
  "Report OKF conformance separately from project validity for one bundle or the full current index.",
309
339
  READ_ONLY,
310
340
  {
311
- bundle: stringParameter("Optional bundle id to validate in isolation."),
341
+ bundle: nonEmptyStringParameter("Optional bundle id to validate in isolation."),
312
342
  },
313
343
  ),
314
344
  validate_project: defineTool(
@@ -319,15 +349,18 @@ const TOOL_DEFINITIONS = {
319
349
  "Render the current OKF graph as JSON, Graphviz DOT, or Mermaid text.",
320
350
  READ_ONLY,
321
351
  {
322
- format: stringParameter("Output format for the graph.", { enum: ["json", "dot", "mermaid"] }),
352
+ format: stringParameter("Output format for the graph.", { enum: ["json", "dot", "mermaid"], default: "json" }),
323
353
  includeExternal: booleanParameter("Include opaque external relation targets in the export."),
324
- maxNodes: numberParameter("Maximum number of graph nodes to export."),
325
- maxEdges: numberParameter("Maximum number of graph edges to export."),
354
+ maxNodes: integerParameter("Maximum number of graph nodes to export.", 1, 1000, 100),
355
+ maxEdges: integerParameter("Maximum number of graph edges to export.", 1, 5000, 300),
326
356
  },
327
357
  ),
328
358
  };
329
359
 
330
360
  const TOOL_NAMES = Object.keys(TOOL_DEFINITIONS);
361
+ TOOL_NAMES.forEach((name) => {
362
+ assertSupportedSchema(TOOL_DEFINITIONS[name].inputSchema, `#/tools/${name}/inputSchema`);
363
+ });
331
364
  const PROJECT_HELPER_TOOL_NAMES = new Set([
332
365
  "okf_validate_concept",
333
366
  "okf_suggest_concept_path",
@@ -344,8 +377,8 @@ const RUNTIME_REMOTE_TOOL_NAMES = new Set([
344
377
  "load_remote_bundle",
345
378
  ]);
346
379
 
347
- function jsonContent(value) {
348
- return {
380
+ function jsonContent(value, options) {
381
+ const result = {
349
382
  content: [
350
383
  {
351
384
  type: "text",
@@ -353,6 +386,10 @@ function jsonContent(value) {
353
386
  },
354
387
  ],
355
388
  };
389
+ if (options && options.isError) {
390
+ result.isError = true;
391
+ }
392
+ return result;
356
393
  }
357
394
 
358
395
  function toolEnabled(state, name) {
@@ -369,8 +406,15 @@ function toolEnabled(state, name) {
369
406
  }
370
407
 
371
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
+ }
372
414
  if (!toolEnabled(state, name)) {
373
- throw new Error(`MCP tool is disabled by server configuration: ${name}`);
415
+ throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
416
+ detail: "Unknown or unavailable tool",
417
+ });
374
418
  }
375
419
  }
376
420
 
@@ -423,7 +467,9 @@ function publicBundles(index) {
423
467
  function readResource(index, uri) {
424
468
  const doc = index.byUri.get(uri);
425
469
  if (!doc) {
426
- throw new Error(`Unknown OKF resource URI: ${uri}`);
470
+ throw new ProtocolError(ERROR_CODES.RESOURCE_NOT_FOUND, "Resource not found", {
471
+ uri,
472
+ });
427
473
  }
428
474
  return {
429
475
  contents: [
@@ -444,17 +490,17 @@ function listConcepts(index, args) {
444
490
  if (options.tag && !options.tagsAny) {
445
491
  options.tagsAny = [options.tag];
446
492
  }
447
- return searchConcepts(index, Object.assign(options, { query: "" }));
493
+ return searchConcepts(index, options);
448
494
  }
449
495
 
450
496
  function getConcept(index, args) {
451
497
  const uri = args && args.uri ? args.uri : args && args.bundle && args.path ? `okf://${args.bundle}/${args.path}` : null;
452
498
  if (!uri || !index.byUri.has(uri)) {
453
- throw new Error(`Unknown OKF concept URI: ${uri || "<missing>"}`);
499
+ throw new ToolExecutionError(`Unknown OKF concept URI: ${uri || "<missing>"}`);
454
500
  }
455
501
  const doc = index.byUri.get(uri);
456
502
  if (!doc.valid || doc.reserved) {
457
- throw new Error(`URI is not a valid OKF concept: ${uri}`);
503
+ throw new ToolExecutionError(`URI is not a valid OKF concept: ${uri}`);
458
504
  }
459
505
  return Object.assign(conceptSummary(doc), {
460
506
  frontmatter: doc.frontmatter,
@@ -505,6 +551,46 @@ function rebuildStateIndex(state) {
505
551
  return state.index;
506
552
  }
507
553
 
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
+ async function expectedToolOperation(operation, options) {
569
+ try {
570
+ return await operation();
571
+ } catch (error) {
572
+ if (error instanceof ProtocolError || error instanceof ToolExecutionError) {
573
+ throw error;
574
+ }
575
+ const programmingError = error instanceof ReferenceError
576
+ || error instanceof SyntaxError
577
+ || error instanceof RangeError
578
+ || (error instanceof TypeError && !(options && options.translateTypeError));
579
+ if (programmingError) {
580
+ throw error;
581
+ }
582
+ throw new ToolExecutionError(error && error.message ? error.message : String(error));
583
+ }
584
+ }
585
+
586
+ function requireGraphConcept(index, uri) {
587
+ const doc = uri && index.byUri.get(uri);
588
+ if (!doc || !doc.valid || doc.reserved) {
589
+ throw new ToolExecutionError(`Unknown valid OKF concept: ${uri || "<missing>"}`);
590
+ }
591
+ return doc;
592
+ }
593
+
508
594
  async function callTool(state, name, args) {
509
595
  if (!state || !state.index) {
510
596
  state = {
@@ -519,97 +605,146 @@ async function callTool(state, name, args) {
519
605
  };
520
606
  }
521
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
+ }
522
621
  const index = state.index;
523
- switch (name) {
524
- case "list_bundles":
525
- return jsonContent(publicBundles(index));
526
- case "list_concepts":
527
- return jsonContent(listConcepts(index, args));
528
- case "get_concept":
529
- return jsonContent(getConcept(index, args));
530
- case "search_concepts":
531
- return jsonContent(searchConcepts(index, args || {}));
532
- case "list_types":
533
- return jsonContent(listTypes(index));
534
- case "list_tags":
535
- return jsonContent(listTags(index));
536
- case "list_relation_types":
537
- return jsonContent(listRelationTypes(index));
538
- case "list_remote_bundles":
539
- return jsonContent(state.remoteBundles.map((bundle) => bundle.remoteSource));
540
- case "load_remote_bundle": {
541
- if (!args || !args.id || !args.url) {
542
- throw new Error("load_remote_bundle requires id and url.");
543
- }
544
- const provider = String(args.provider || "github");
545
- if (provider !== "github") {
546
- throw new Error(`Unsupported remote bundle provider: ${provider}`);
622
+ try {
623
+ switch (name) {
624
+ case "list_bundles":
625
+ return jsonContent(publicBundles(index));
626
+ case "list_concepts":
627
+ return jsonContent(listConcepts(index, args));
628
+ case "get_concept":
629
+ return jsonContent(getConcept(index, args));
630
+ case "search_concepts":
631
+ return jsonContent(searchConcepts(index, args));
632
+ case "list_types":
633
+ return jsonContent(listTypes(index));
634
+ case "list_tags":
635
+ return jsonContent(listTags(index));
636
+ case "list_relation_types":
637
+ return jsonContent(listRelationTypes(index));
638
+ case "list_remote_bundles":
639
+ return jsonContent(state.remoteBundles.map((bundle) => bundle.remoteSource));
640
+ case "load_remote_bundle": {
641
+ const provider = String(args.provider || "github");
642
+ if (provider !== "github") {
643
+ throw new ToolExecutionError(`Unsupported remote bundle provider: ${provider}`);
644
+ }
645
+ if (state.index.bundles.some((bundle) => bundle.id === args.id)) {
646
+ throw new ToolExecutionError(`Bundle id already loaded: ${args.id}`);
647
+ }
648
+ const remoteBundle = await expectedToolOperation(
649
+ () => fetchGitHubBundle({
650
+ id: args.id,
651
+ url: args.url,
652
+ include: args.include || [],
653
+ exclude: args.exclude || [],
654
+ }),
655
+ { translateTypeError: true },
656
+ );
657
+ state.remoteBundles.push(remoteBundle);
658
+ rebuildStateIndex(state);
659
+ return jsonContent(remoteBundle.remoteSource);
547
660
  }
548
- if (state.index.bundles.some((bundle) => bundle.id === args.id)) {
549
- throw new Error(`Bundle id already loaded: ${args.id}`);
661
+ case "okf_validate_concept":
662
+ return jsonContent(await expectedToolOperation(
663
+ () => requireAuthoring(state).validateConcept(args),
664
+ ));
665
+ case "okf_suggest_concept_path":
666
+ return jsonContent(await expectedToolOperation(
667
+ () => requireAuthoring(state).suggestConceptPath(args),
668
+ ));
669
+ case "okf_propose_concept": {
670
+ const result = await expectedToolOperation(
671
+ () => requireAuthoring(state).proposeConcept(args),
672
+ );
673
+ return jsonContent(result, { isError: result.created === false });
550
674
  }
551
- const remoteBundle = await fetchGitHubBundle({
552
- id: args.id,
553
- url: args.url,
554
- include: Array.isArray(args.include) ? args.include : [],
555
- exclude: Array.isArray(args.exclude) ? args.exclude : [],
556
- });
557
- state.remoteBundles.push(remoteBundle);
558
- rebuildStateIndex(state);
559
- return jsonContent(remoteBundle.remoteSource);
560
- }
561
- case "okf_validate_concept":
562
- return jsonContent(requireAuthoring(state).validateConcept(args || {}));
563
- case "okf_suggest_concept_path":
564
- return jsonContent(requireAuthoring(state).suggestConceptPath(args || {}));
565
- case "okf_propose_concept":
566
- return jsonContent(await requireAuthoring(state).proposeConcept(args || {}));
567
- case "okf_propose_update":
568
- return jsonContent(await requireAuthoring(state).proposeUpdate(args || {}));
569
- case "okf_list_proposals":
570
- return jsonContent(await requireAuthoring(state).listProposals(args || {}));
571
- case "okf_get_proposal":
572
- return jsonContent(await requireAuthoring(state).getProposal(args || {}));
573
- case "okf_accept_proposal": {
574
- const result = await requireAuthoring(state).acceptProposal(args || {});
575
- if (result.accepted) {
576
- rebuildStateIndex(state);
675
+ case "okf_propose_update": {
676
+ const result = await expectedToolOperation(
677
+ () => requireAuthoring(state).proposeUpdate(args),
678
+ );
679
+ return jsonContent(result, { isError: result.created === false });
577
680
  }
578
- return jsonContent(result);
579
- }
580
- case "okf_reject_proposal":
581
- return jsonContent(await requireAuthoring(state).rejectProposal(args || {}));
582
- case "get_graph":
583
- return jsonContent(getGraph(index, args || {}));
584
- case "get_neighbors":
585
- if (!args || !args.uri) {
586
- throw new Error("get_neighbors requires uri.");
681
+ case "okf_list_proposals":
682
+ return jsonContent(await expectedToolOperation(
683
+ () => requireAuthoring(state).listProposals(args),
684
+ ));
685
+ case "okf_get_proposal":
686
+ return jsonContent(await expectedToolOperation(
687
+ () => requireAuthoring(state).getProposal(args),
688
+ ));
689
+ case "okf_accept_proposal": {
690
+ const result = await expectedToolOperation(
691
+ () => requireAuthoring(state).acceptProposal(args),
692
+ );
693
+ if (result.accepted) {
694
+ rebuildStateIndex(state);
695
+ }
696
+ return jsonContent(result, { isError: result.accepted === false });
587
697
  }
588
- return jsonContent(getNeighbors(index, args && args.uri));
589
- case "get_subgraph":
590
- return jsonContent(getSubgraph(index, args || {}));
591
- case "find_paths":
592
- if (!args || !args.source || !args.target) {
593
- throw new Error("find_paths requires source and target.");
698
+ case "okf_reject_proposal":
699
+ return jsonContent(await expectedToolOperation(
700
+ () => requireAuthoring(state).rejectProposal(args),
701
+ ));
702
+ case "get_graph":
703
+ return jsonContent(getGraph(index, args));
704
+ case "get_neighbors":
705
+ requireGraphConcept(index, args.uri);
706
+ return jsonContent(getNeighbors(index, args.uri));
707
+ case "get_subgraph": {
708
+ const seeds = args.seeds || [args.uri];
709
+ seeds.forEach((uri) => requireGraphConcept(index, uri));
710
+ return jsonContent(getSubgraph(index, args));
594
711
  }
595
- return jsonContent(findPaths(index, args && args.source, args && args.target, args && args.maxPaths));
596
- case "graph_summary":
597
- return jsonContent(graphSummary(index));
598
- case "validate_bundle":
599
- return jsonContent(validateIndex(index, args && args.bundle));
600
- case "validate_project":
601
- return jsonContent(validateIndex(index));
602
- case "export_graph":
603
- return {
604
- content: [
605
- {
606
- type: "text",
607
- text: exportGraph(index, args || {}),
608
- },
609
- ],
610
- };
611
- default:
612
- throw new Error(`Unknown OKF MCP tool: ${name}`);
712
+ case "find_paths":
713
+ requireGraphConcept(index, args.source);
714
+ requireGraphConcept(index, args.target);
715
+ return jsonContent(findPaths(index, args.source, args.target, args.maxPaths));
716
+ case "graph_summary":
717
+ return jsonContent(graphSummary(index));
718
+ case "validate_bundle":
719
+ if (args.bundle && !index.bundles.some((bundle) => bundle.id === args.bundle)) {
720
+ throw new ToolExecutionError(`Unknown OKF bundle: ${args.bundle}`);
721
+ }
722
+ return jsonContent(validateIndex(index, args.bundle));
723
+ case "validate_project":
724
+ return jsonContent(validateIndex(index));
725
+ case "export_graph":
726
+ return {
727
+ content: [
728
+ {
729
+ type: "text",
730
+ text: exportGraph(index, args),
731
+ },
732
+ ],
733
+ };
734
+ default:
735
+ throw new ProtocolError(ERROR_CODES.INVALID_PARAMS, "Invalid params", {
736
+ detail: "Unknown or unavailable tool",
737
+ });
738
+ }
739
+ } catch (error) {
740
+ if (!(error instanceof ToolExecutionError)) {
741
+ throw error;
742
+ }
743
+ return jsonContent({
744
+ error: "Tool execution failed",
745
+ tool: name,
746
+ message: error.message,
747
+ }, { isError: true });
613
748
  }
614
749
  }
615
750
 
@@ -644,38 +779,84 @@ function createServer(bundleArgs, options) {
644
779
  allowRuntimeRemoteLoad: Boolean(options && options.allowRuntimeRemoteLoad),
645
780
  };
646
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
+ }
647
787
  const method = request.method;
648
- const params = request.params || {};
649
788
  if (method === "initialize") {
789
+ const params = objectParams(request, method);
650
790
  const requestedVersion = params.protocolVersion;
651
- if (!SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)) {
652
- throw new Error(
653
- `Unsupported MCP protocol version: ${requestedVersion || "<missing>"}. `
654
- + `Supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`,
655
- );
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.");
656
805
  }
657
806
  return {
658
- protocolVersion: requestedVersion,
807
+ protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)
808
+ ? requestedVersion
809
+ : SUPPORTED_PROTOCOL_VERSIONS[0],
659
810
  serverInfo: { name: "okf-mcp", version: packageMetadata.version },
660
811
  capabilities: { resources: {}, tools: {} },
661
812
  };
662
813
  }
663
814
  if (method === "notifications/initialized") {
815
+ objectParams(request, method);
664
816
  return null;
665
817
  }
818
+ if (method === "ping") {
819
+ objectParams(request, method);
820
+ return {};
821
+ }
666
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
+ }
667
827
  return listResources(state.index);
668
828
  }
669
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
+ }
670
834
  return readResource(state.index, params.uri);
671
835
  }
672
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
+ }
673
841
  return listTools(state);
674
842
  }
675
843
  if (method === "tools/call") {
676
- return callTool(state, params.name, params.arguments || {});
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);
677
856
  }
678
- throw new Error(`Unsupported MCP method: ${method}`);
857
+ throw new ProtocolError(ERROR_CODES.METHOD_NOT_FOUND, "Method not found", {
858
+ method,
859
+ });
679
860
  }
680
861
  return { get index() { return state.index; }, handle };
681
862
  }
@@ -711,20 +892,6 @@ async function createServerAsync(bundleArgs, options) {
711
892
  });
712
893
  }
713
894
 
714
- function responseFor(id, result, error) {
715
- if (error) {
716
- return {
717
- jsonrpc: "2.0",
718
- id,
719
- error: {
720
- code: -32000,
721
- message: error.message || String(error),
722
- },
723
- };
724
- }
725
- return { jsonrpc: "2.0", id, result };
726
- }
727
-
728
895
  async function runStdioServer(bundleArgs, input, output, options) {
729
896
  const rl = readline.createInterface({ input, crlfDelay: Infinity });
730
897
  let serverPromise;
@@ -746,21 +913,50 @@ async function runStdioServer(bundleArgs, input, output, options) {
746
913
  if (!line.trim()) {
747
914
  return;
748
915
  }
749
- if (line.length > 1024 * 1024) {
750
- await writeResponse(responseFor(null, null, new Error("MCP request line exceeds 1 MiB.")));
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
+ )));
751
922
  return;
752
923
  }
753
924
  let request;
754
925
  try {
755
926
  request = JSON.parse(line);
756
- const server = await serverPromise;
757
- const result = await server.handle(request);
758
- if (request.id !== undefined) {
759
- await writeResponse(responseFor(request.id, result, null));
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.
760
952
  }
953
+ return;
954
+ }
955
+ try {
956
+ const result = await server.handle(request);
957
+ await writeResponse(responseFor(envelope.id, result, null));
761
958
  } catch (error) {
762
- const id = request && request.id !== undefined ? request.id : null;
763
- await writeResponse(responseFor(id, null, error));
959
+ await writeResponse(responseFor(envelope.id, null, error));
764
960
  }
765
961
  }
766
962