@ontology-kit/mcp 0.0.0-stage → 0.3.0-alpha.135

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/dist/cli.js ADDED
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // Usage: node src/cli.ts <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source] [--skills none|bundled|all]
3
+ // [--snapshot-id <id> --snapshot-version <version>]
4
+ import path from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { OkbMcpError } from "./errors.js";
8
+ import { kbSkillNames, SKILL_SETS } from "./skills.js";
9
+ import { loadForServing } from "./serving.js";
10
+ import { createServer } from "./server.js";
11
+ import { EVIDENCE_MODES } from "./tools.js";
12
+ // `okb-mcp check <folder>` asks the competency questions through the tools instead of starting the server.
13
+ if (process.argv[2] === "check")
14
+ process.exit(await (await import("./check-cli.js")).main(process.argv.slice(3)));
15
+ // `okb-mcp skills [<folder>]`, `okb-mcp skills install` and `okb-mcp skills status` list, install and check the skills.
16
+ if (process.argv[2] === "skills")
17
+ process.exit(await (await import("./skills-cli.js")).main(process.argv.slice(3)));
18
+ const USAGE = `Usage: okb-mcp <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source] [--skills none|bundled|all]
19
+ [--snapshot-id <id> --snapshot-version <version>]
20
+
21
+ Serves an okb ontology (the folder with okb.json, nodes.jsonl and edges.jsonl) over MCP on stdio.
22
+
23
+ Other commands:
24
+ okb-mcp check <ontology-folder> ask the competency questions through the tools
25
+ okb-mcp skills [<ontology-folder>] list the skills the server can serve
26
+ okb-mcp skills install install the bundled skills into a skills folder
27
+ okb-mcp skills status check the installed skills against the bundled ones
28
+ Run one with --help for its options. A folder named check or skills has to be written ./check or ./skills,
29
+ or the word is taken as the command.
30
+
31
+ --quotes full show each rule's verbatim source quote and where it came from (default)
32
+ --quotes locator show only where it came from: document, heading, line, link
33
+ --quotes none show neither
34
+
35
+ --include-unverified also serve rules that haven't been verified against their quote.
36
+ By default they're held back, as \`okb export\` does, along with any
37
+ link whose \`rule\` property points at one.
38
+
39
+ --read-source also serve read_source: the text of a cited document, by heading or
40
+ line range, from the files the ontology's sources name. Off by default,
41
+ because it gives the agent the documents as well as the structure.
42
+ Works only with --quotes full, since the documents contain the quotes.
43
+
44
+ --skills none serve no skills
45
+ --skills bundled serve the skills this package ships, today query-kb, through the MCP
46
+ skills extension (default)
47
+ --skills all also serve the skills in the KB's skills/ folder. They're instructions
48
+ the KB's author wrote and the agent follows, so use \`all\` only for a KB
49
+ you trust.
50
+
51
+ --snapshot-id <id> --snapshot-version <version>
52
+ report which data this is as the eval-kit://snapshot resource, JSON
53
+ {"id", "version"}, so an eval harness can check it before a run. The
54
+ model never sees it. Give both or neither.
55
+ `;
56
+ function fail(message) {
57
+ console.error(message);
58
+ process.exit(2);
59
+ }
60
+ const { positionals, values } = (() => {
61
+ try {
62
+ return parseArgs({
63
+ allowPositionals: true,
64
+ options: {
65
+ quotes: { type: "string" },
66
+ "include-unverified": { type: "boolean" },
67
+ "read-source": { type: "boolean" },
68
+ skills: { type: "string" },
69
+ "snapshot-id": { type: "string" },
70
+ "snapshot-version": { type: "string" },
71
+ help: { type: "boolean", short: "h" },
72
+ },
73
+ });
74
+ }
75
+ catch (err) {
76
+ return fail(`${err.message}\n\n${USAGE}`);
77
+ }
78
+ })();
79
+ if (values.help) {
80
+ console.error(USAGE);
81
+ process.exit(0);
82
+ }
83
+ const dir = positionals[0];
84
+ if (!dir)
85
+ fail(USAGE);
86
+ const quotes = values.quotes ?? "full";
87
+ if (!EVIDENCE_MODES.includes(quotes)) {
88
+ fail(`--quotes must be one of ${EVIDENCE_MODES.join(", ")}, not "${quotes}".`);
89
+ }
90
+ if (values["read-source"] && quotes !== "full") {
91
+ fail(`--read-source can't be combined with --quotes ${quotes}: read_source returns the documents' own text, quotes included. Use --quotes full, or leave --read-source off.`);
92
+ }
93
+ const skillSet = values.skills ?? "bundled";
94
+ if (!SKILL_SETS.includes(skillSet)) {
95
+ fail(`--skills must be one of ${SKILL_SETS.join(", ")}, not "${skillSet}".`);
96
+ }
97
+ const snapshotId = values["snapshot-id"];
98
+ const snapshotVersion = values["snapshot-version"];
99
+ if ((snapshotId === undefined) !== (snapshotVersion === undefined) || snapshotId === "" || snapshotVersion === "") {
100
+ fail("--snapshot-id and --snapshot-version go together, and neither can be empty.");
101
+ }
102
+ const snapshot = snapshotId && snapshotVersion ? { id: snapshotId, version: snapshotVersion } : undefined;
103
+ let loaded;
104
+ try {
105
+ loaded = loadForServing(path.resolve(dir), { includeUnverified: values["include-unverified"] ?? false });
106
+ }
107
+ catch (err) {
108
+ fail(err instanceof OkbMcpError ? err.message : String(err));
109
+ }
110
+ const { ontology, held, root } = loaded;
111
+ if (held.rules > 0) {
112
+ // stderr, so an operator sees it in the MCP client's logs without it reaching the agent.
113
+ console.error(`okb-mcp: holding back ${held.rules} unverified rule${held.rules === 1 ? "" : "s"}` +
114
+ `${held.links ? ` and ${held.links} link${held.links === 1 ? "" : "s"} they justify` : ""}. Use --include-unverified to serve them.`);
115
+ }
116
+ let server;
117
+ try {
118
+ server = createServer(ontology, {
119
+ evidence: quotes,
120
+ readSource: values["read-source"] ? { root } : undefined,
121
+ snapshot,
122
+ skills: skillSet === "all" ? { kb: root } : skillSet,
123
+ });
124
+ }
125
+ catch (err) {
126
+ fail(err instanceof OkbMcpError ? err.message : String(err));
127
+ }
128
+ // Also stderr: which author-written instructions go out, or how many are held back.
129
+ const kbSkills = skillSet === "none" ? [] : kbSkillNames(root);
130
+ if (skillSet === "all" && kbSkills.length > 0) {
131
+ console.error(`okb-mcp: serving ${kbSkills.length} skill${kbSkills.length === 1 ? "" : "s"} from the KB's skills/ folder: ${kbSkills.join(", ")}.`);
132
+ }
133
+ else if (skillSet === "bundled" && kbSkills.length > 0) {
134
+ console.error(`okb-mcp: the KB has ${kbSkills.length} skill${kbSkills.length === 1 ? "" : "s"} in skills/ that aren't served. Use --skills all to serve ${kbSkills.length === 1 ? "it" : "them"}.`);
135
+ }
136
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,4 @@
1
+ /** A user-facing problem (bad folder, unknown name). Tool handlers return these to the model as tool errors. */
2
+ export declare class OkbMcpError extends Error {
3
+ name: string;
4
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,4 @@
1
+ /** A user-facing problem (bad folder, unknown name). Tool handlers return these to the model as tool errors. */
2
+ export class OkbMcpError extends Error {
3
+ name = "OkbMcpError";
4
+ }
@@ -0,0 +1,112 @@
1
+ import { type OkbNode, type Ontology, type SlotNode } from "@ontology-kit/reader";
2
+ type Bag = Record<string, unknown>;
3
+ /** A node's fields by name, for the optional fields the typed union doesn't share. */
4
+ export declare const bag: (n: OkbNode) => Bag;
5
+ /** What a node is called: its name, or for a source document its title. */
6
+ export declare function displayName(n: OkbNode): string;
7
+ export declare function byName(a: OkbNode, b: OkbNode): number;
8
+ /** "Segmented Control", "SegmentedControl" and "segmented-control" all squash to the same string. */
9
+ export declare function squash(s: string): string;
10
+ export declare function asStrings(v: unknown): string[];
11
+ export declare const parents: (ont: Ontology, id: string) => OkbNode[];
12
+ export declare const children: (ont: Ontology, id: string) => OkbNode[];
13
+ /** Nearest first. Excludes the class itself. */
14
+ export declare const ancestors: (ont: Ontology, id: string) => OkbNode[];
15
+ export declare const descendants: (ont: Ontology, id: string) => OkbNode[];
16
+ /** Instances of a class and its subclasses (or of the class alone), by name. */
17
+ export declare function instancesOf(ont: Ontology, classId: string, { direct }?: {
18
+ direct?: boolean | undefined;
19
+ }): OkbNode[];
20
+ /** A node's own classes first, then their ancestors. */
21
+ export declare function classesOf(ont: Ontology, node: OkbNode): OkbNode[];
22
+ /**
23
+ * Finds one node by id, `type:Name`, exact name, synonym, or (when it's unambiguous) a case-insensitive
24
+ * substring of a name. More forgiving than the reader's `find`, which matches a whole name only. Throws
25
+ * with the candidates when the reference is unknown or ambiguous.
26
+ */
27
+ export declare function resolve(ont: Ontology, ref: string, types?: string[]): OkbNode;
28
+ export interface PropertyValue {
29
+ slot: OkbNode;
30
+ value: unknown;
31
+ /** The class whose fixed value this is, when the node states none of its own. */
32
+ inheritedFrom: OkbNode | undefined;
33
+ }
34
+ /** Property slots (not relationships) and their values for a class or instance, with inheritance, by slot name. */
35
+ export declare function propertyValues(ont: Ontology, node: OkbNode): PropertyValue[];
36
+ /** Slots attached to the class or inherited from its ancestors. `from` is the class that declares each. */
37
+ export declare function slotsOf(ont: Ontology, classNode: OkbNode): {
38
+ slot: OkbNode;
39
+ from: OkbNode;
40
+ }[];
41
+ /** How each relationship edge type is named from either end, read once per call. */
42
+ export interface RelNames {
43
+ /** The relationship's own (forward) name. */
44
+ name(type: string): string;
45
+ /** True when the relationship has a declared inverse name. */
46
+ hasInverse(type: string): boolean;
47
+ /** The name from the other end: the declared inverse, else "name (incoming)". */
48
+ inverseLabel(type: string): string;
49
+ }
50
+ export declare function relNames(ont: Ontology): RelNames;
51
+ /** The slots that store a relationship, by name. An inverse is the same relationship, so it isn't listed. */
52
+ export declare function relationshipSlots(ont: Ontology): SlotNode[];
53
+ export interface RelationshipEnd {
54
+ /** The relationship as the reader sees it from this node (the inverse name when incoming). */
55
+ label: string;
56
+ /** The relationship's own (forward) name, whichever end the node is on. */
57
+ relName: string;
58
+ /** True when `label` is a declared inverse name rather than a generated one. */
59
+ hasInverse: boolean;
60
+ direction: "out" | "in";
61
+ other: OkbNode;
62
+ props: Record<string, unknown>;
63
+ }
64
+ /**
65
+ * Every relationship value on the node, both directions, from the edges `queryGet` returns. Class-level
66
+ * edges to instances are facts about every member, so a node also gets those of its classes.
67
+ */
68
+ export declare function relationshipsOf(ont: Ontology, node: OkbNode, { inherited }?: {
69
+ inherited?: boolean | undefined;
70
+ }): RelationshipEnd[];
71
+ /**
72
+ * Resolves `preferredOver`, `PREFERRED_OVER` or `preferred over` to a relationship slot. `backwards` says
73
+ * the slot named is the inverse of the one that stores the edges, so it reads them against their stored direction.
74
+ */
75
+ export declare function resolveRelationship(ont: Ontology, ref: string): {
76
+ slot: OkbNode;
77
+ backwards: boolean;
78
+ };
79
+ /** A property's value or values, comma-separated, for `get`. `splitValues` is its inverse. */
80
+ export declare function showValues(value: unknown): string;
81
+ /**
82
+ * Reads the values `showValues` wrote from the start of `text`: split on ", " outside quoted strings. An unquoted value
83
+ * also ends at any of `stops` (text that follows the values on the line, such as an annotation or a description), and
84
+ * a quoted one may be followed by one. Returns the values and what is left after them.
85
+ */
86
+ export declare function readValues(text: string, stops?: readonly string[]): {
87
+ values: string[];
88
+ rest: string;
89
+ };
90
+ /** The values in `text` as `showValues` wrote them: split on ", " outside quoted strings. */
91
+ export declare function splitValues(text: string): string[];
92
+ export interface Citation {
93
+ quote: string;
94
+ source: string;
95
+ locator: string;
96
+ lines: string | undefined;
97
+ link: string | undefined;
98
+ }
99
+ export interface Rule {
100
+ id: string;
101
+ modality: string;
102
+ statement: string;
103
+ /** SUPPORTED, or why a reader should be careful. */
104
+ caveat: string | undefined;
105
+ citations: Citation[];
106
+ }
107
+ /** Rules that govern the node itself. */
108
+ export declare const rulesGoverning: (ont: Ontology, nodeId: string) => OkbNode[];
109
+ export declare function describeRule(ont: Ontology, rule: OkbNode): Rule;
110
+ /** The passages a node cites, each with its source document and place in it. */
111
+ export declare function citationsFor(ont: Ontology, nodeId: string): Citation[];
112
+ export {};
package/dist/graph.js ADDED
@@ -0,0 +1,295 @@
1
+ // Reading the served ontology the way the tools need it: names, forgiving lookup, rules and their
2
+ // citations, relationships with their labels. Everything goes through the reader (`Ontology`, `ont.rel`,
3
+ // the query layer); nothing here knows how relationships are stored.
4
+ import { edgeProps, isStructuralEdgeType, queryGet, queryTraverse, querySlots, } from "@ontology-kit/reader";
5
+ import { OkbMcpError } from "./errors.js";
6
+ /** A node's fields by name, for the optional fields the typed union doesn't share. */
7
+ export const bag = (n) => n;
8
+ /** What a node is called: its name, or for a source document its title. */
9
+ export function displayName(n) {
10
+ const b = bag(n);
11
+ return String(b.name ?? b.title ?? n.id);
12
+ }
13
+ export function byName(a, b) {
14
+ return displayName(a).localeCompare(displayName(b));
15
+ }
16
+ /** "Segmented Control", "SegmentedControl" and "segmented-control" all squash to the same string. */
17
+ export function squash(s) {
18
+ return s.toLowerCase().replace(/[^a-z0-9]/g, "");
19
+ }
20
+ export function asStrings(v) {
21
+ return Array.isArray(v) ? v.map(String) : typeof v === "string" ? [v] : [];
22
+ }
23
+ function nodes(ont, ids) {
24
+ const out = [];
25
+ for (const id of ids) {
26
+ const n = ont.get(id);
27
+ if (n)
28
+ out.push(n);
29
+ }
30
+ return out;
31
+ }
32
+ // Classes ---------------------------------------------------------------
33
+ export const parents = (ont, id) => nodes(ont, ont.parents(id)).filter((n) => n.type === "Class");
34
+ export const children = (ont, id) => nodes(ont, ont.children(id)).filter((n) => n.type === "Class").sort(byName);
35
+ /** Nearest first. Excludes the class itself. */
36
+ export const ancestors = (ont, id) => nodes(ont, ont.ancestors(id));
37
+ export const descendants = (ont, id) => nodes(ont, ont.descendants(id));
38
+ /** Instances of a class and its subclasses (or of the class alone), by name. */
39
+ export function instancesOf(ont, classId, { direct = false } = {}) {
40
+ const ids = direct ? [classId] : [classId, ...ont.descendants(classId)];
41
+ const seen = new Set();
42
+ return ids
43
+ .flatMap((id) => nodes(ont, ont.sources(id, "INSTANCE_OF")))
44
+ .filter((n) => n.type === "Instance" && !seen.has(n.id) && seen.add(n.id))
45
+ .sort(byName);
46
+ }
47
+ /** A node's own classes first, then their ancestors. */
48
+ export function classesOf(ont, node) {
49
+ if (node.type === "Class")
50
+ return [node, ...ancestors(ont, node.id)];
51
+ const own = nodes(ont, ont.targets(node.id, "INSTANCE_OF")).filter((n) => n.type === "Class");
52
+ const seen = new Set(own.map((c) => c.id));
53
+ const out = [...own];
54
+ for (const c of own)
55
+ for (const a of ancestors(ont, c.id))
56
+ if (!seen.has(a.id))
57
+ (seen.add(a.id), out.push(a));
58
+ return out;
59
+ }
60
+ // Lookup ----------------------------------------------------------------
61
+ const NAMED_TYPES = new Set(["Class", "Slot", "Instance", "Rule", "Source"]);
62
+ function capitalize(s) {
63
+ return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
64
+ }
65
+ /**
66
+ * Finds one node by id, `type:Name`, exact name, synonym, or (when it's unambiguous) a case-insensitive
67
+ * substring of a name. More forgiving than the reader's `find`, which matches a whole name only. Throws
68
+ * with the candidates when the reference is unknown or ambiguous.
69
+ */
70
+ export function resolve(ont, ref, types) {
71
+ const allowed = (n) => !types || types.includes(n.type);
72
+ const raw = ref.trim();
73
+ const direct = ont.get(raw);
74
+ if (direct && allowed(direct))
75
+ return direct;
76
+ const prefixed = /^(class|slot|instance|rule|source):(.+)$/i.exec(raw);
77
+ const wantType = prefixed ? capitalize(prefixed[1]) : undefined;
78
+ const text = (prefixed ? prefixed[2] : raw).trim().toLowerCase();
79
+ const pool = ont.nodes.filter((n) => NAMED_TYPES.has(n.type) && allowed(n) && (!wantType || n.type === wantType));
80
+ const exact = pool.filter((n) => displayName(n).toLowerCase() === text || squash(displayName(n)) === squash(text));
81
+ const synonym = pool.filter((n) => asStrings(bag(n).synonyms).some((s) => s.toLowerCase() === text));
82
+ const partial = pool.filter((n) => displayName(n).toLowerCase().includes(text) || squash(displayName(n)).includes(squash(text)));
83
+ for (const tier of [exact, synonym, partial]) {
84
+ if (tier.length === 1)
85
+ return tier[0];
86
+ if (tier.length > 1) {
87
+ // A class and a slot sharing a name is the usual ambiguity; the class is almost always meant.
88
+ const classes = tier.filter((n) => n.type === "Class");
89
+ if (classes.length === 1 && tier !== partial)
90
+ return classes[0];
91
+ throw new OkbMcpError(`"${ref}" is ambiguous. Did you mean: ${tier.slice(0, 8).map((n) => `${n.type.toLowerCase()}:${displayName(n)}`).join(", ")}?`);
92
+ }
93
+ }
94
+ const near = pool.filter((n) => text.split(/\s+/).some((w) => w.length > 2 && displayName(n).toLowerCase().includes(w))).slice(0, 5);
95
+ throw new OkbMcpError(`Nothing named "${ref}"${types ? ` (looking for ${types.join(" or ").toLowerCase()})` : ""}.` +
96
+ (near.length ? ` Similar: ${near.map((n) => displayName(n)).join(", ")}.` : " Try `find` to search."));
97
+ }
98
+ /** Property slots (not relationships) and their values for a class or instance, with inheritance, by slot name. */
99
+ export function propertyValues(ont, node) {
100
+ if (node.type !== "Class" && node.type !== "Instance")
101
+ return [];
102
+ const out = [];
103
+ for (const slot of querySlots(ont, { of: node.id })) {
104
+ if (slot.relationship)
105
+ continue;
106
+ const hits = queryTraverse(ont, { from: node.id, slot: slot.id });
107
+ if (hits.length === 0)
108
+ continue;
109
+ const via = hits[0].inheritedFrom;
110
+ out.push({
111
+ slot: ont.require(slot.id),
112
+ value: hits.length === 1 ? hits[0].value : hits.map((h) => h.value),
113
+ inheritedFrom: via ? ont.get(via) : undefined,
114
+ });
115
+ }
116
+ return out.sort((a, b) => String(bag(a.slot).name).localeCompare(String(bag(b.slot).name)));
117
+ }
118
+ /** Slots attached to the class or inherited from its ancestors. `from` is the class that declares each. */
119
+ export function slotsOf(ont, classNode) {
120
+ const out = [];
121
+ const seen = new Set();
122
+ for (const c of [classNode, ...ancestors(ont, classNode.id)]) {
123
+ for (const s of nodes(ont, ont.ownSlots(c.id))) {
124
+ if (s.type === "Slot" && !seen.has(s.id))
125
+ (seen.add(s.id), out.push({ slot: s, from: c }));
126
+ }
127
+ }
128
+ return out;
129
+ }
130
+ export function relNames(ont) {
131
+ const slots = new Map();
132
+ const inverse = new Map();
133
+ for (const [type, slotId] of ont.rel.edgeTypes()) {
134
+ const slot = ont.get(slotId);
135
+ if (!slot)
136
+ continue;
137
+ slots.set(type, slot);
138
+ const other = ont.inverses(slotId).map((id) => ont.get(id)).find((s) => s?.type === "Slot");
139
+ if (other)
140
+ inverse.set(type, displayName(other));
141
+ }
142
+ const name = (type) => (slots.has(type) ? displayName(slots.get(type)) : type);
143
+ return {
144
+ name,
145
+ hasInverse: (type) => inverse.has(type),
146
+ inverseLabel: (type) => inverse.get(type) ?? `${name(type)} (incoming)`,
147
+ };
148
+ }
149
+ /** The slots that store a relationship, by name. An inverse is the same relationship, so it isn't listed. */
150
+ export function relationshipSlots(ont) {
151
+ return ont.ofType("Slot").filter((s) => s.valueType === "Instance" && ont.rel.isPrimary(s.id)).sort(byName);
152
+ }
153
+ /**
154
+ * Every relationship value on the node, both directions, from the edges `queryGet` returns. Class-level
155
+ * edges to instances are facts about every member, so a node also gets those of its classes.
156
+ */
157
+ export function relationshipsOf(ont, node, { inherited = true } = {}) {
158
+ const names = relNames(ont);
159
+ const out = [];
160
+ const add = (e, direction, inheritedFrom) => {
161
+ const other = ont.get(direction === "out" ? e.to : e.from);
162
+ if (!other || isStructuralEdgeType(e.type))
163
+ return;
164
+ const props = edgeProps(e);
165
+ out.push({
166
+ label: direction === "out" ? names.name(e.type) : names.inverseLabel(e.type),
167
+ relName: names.name(e.type),
168
+ hasInverse: names.hasInverse(e.type),
169
+ direction,
170
+ other,
171
+ props: inheritedFrom ? { ...props, inheritedFrom: displayName(inheritedFrom) } : props,
172
+ });
173
+ };
174
+ const own = queryGet(ont, node.id);
175
+ for (const e of own.out)
176
+ add(e, "out");
177
+ for (const e of own.in)
178
+ add(e, "in");
179
+ if (inherited) {
180
+ const have = new Set(out.map((r) => `${r.label}|${r.direction}|${r.other.id}`));
181
+ for (const c of classesOf(ont, node)) {
182
+ if (c.id === node.id)
183
+ continue;
184
+ for (const e of queryGet(ont, c.id).out) {
185
+ const target = ont.get(e.to);
186
+ if (target?.type !== "Instance" || isStructuralEdgeType(e.type))
187
+ continue; // only values that are facts about the members
188
+ const key = `${names.name(e.type)}|out|${target.id}`;
189
+ if (have.has(key))
190
+ continue;
191
+ have.add(key);
192
+ add(e, "out", c);
193
+ }
194
+ }
195
+ }
196
+ return out.sort((a, b) => a.label.localeCompare(b.label) || displayName(a.other).localeCompare(displayName(b.other)));
197
+ }
198
+ /**
199
+ * Resolves `preferredOver`, `PREFERRED_OVER` or `preferred over` to a relationship slot. `backwards` says
200
+ * the slot named is the inverse of the one that stores the edges, so it reads them against their stored direction.
201
+ */
202
+ export function resolveRelationship(ont, ref) {
203
+ const want = squash(ref);
204
+ const slots = ont.ofType("Slot").filter((s) => ont.rel.spec(s.id) !== null);
205
+ const hit = slots.find((s) => squash(String(s.relType ?? "")) === want || squash(s.name) === want);
206
+ if (hit)
207
+ return { slot: hit, backwards: ont.rel.spec(hit.id).reverse };
208
+ const known = relationshipSlots(ont).map((s) => s.name).join(", ");
209
+ throw new OkbMcpError(`No relationship called "${ref}". Relationships in this ontology: ${known || "none"}.`);
210
+ }
211
+ // Property values as text -----------------------------------------------
212
+ /** Text that `splitValues` or the `get` tool's own annotations (`(from X)`, `(inherited from X)`) would misread, so it is written as a JSON string. */
213
+ const NEEDS_QUOTES = /, |^"|[\r\n]| — | \(inherited from | \((?:from|inherited from) [^)]*\)$/;
214
+ /** One value of a property as the `get` tool prints it. Text that would read as a list, a quote, a second line or an annotation is written as a JSON string, so ordinary values keep their plain form. */
215
+ function valueText(v) {
216
+ if (typeof v === "string")
217
+ return NEEDS_QUOTES.test(v) ? JSON.stringify(v) : v;
218
+ if (v && typeof v === "object")
219
+ return JSON.stringify(v);
220
+ return String(v);
221
+ }
222
+ /** A property's value or values, comma-separated, for `get`. `splitValues` is its inverse. */
223
+ export function showValues(value) {
224
+ return (Array.isArray(value) ? value : [value]).map(valueText).join(", ");
225
+ }
226
+ /**
227
+ * Reads the values `showValues` wrote from the start of `text`: split on ", " outside quoted strings. An unquoted value
228
+ * also ends at any of `stops` (text that follows the values on the line, such as an annotation or a description), and
229
+ * a quoted one may be followed by one. Returns the values and what is left after them.
230
+ */
231
+ export function readValues(text, stops = []) {
232
+ const values = [];
233
+ const after = [", ", ...stops].map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
234
+ const quotedAt = new RegExp(`^"(?:[^"\\\\]|\\\\.)*"(?=${after}|$)`);
235
+ let i = 0;
236
+ while (i <= text.length) {
237
+ const quoted = quotedAt.exec(text.slice(i))?.[0];
238
+ let token;
239
+ if (quoted !== undefined) {
240
+ token = JSON.parse(quoted);
241
+ i += quoted.length;
242
+ }
243
+ else {
244
+ const ends = [", ", ...stops].map((x) => text.indexOf(x, i)).filter((x) => x !== -1);
245
+ const end = ends.length ? Math.min(...ends) : text.length;
246
+ token = text.slice(i, end);
247
+ i = end;
248
+ }
249
+ values.push(token);
250
+ if (!text.startsWith(", ", i))
251
+ break;
252
+ i += 2; // the ", "
253
+ }
254
+ return { values, rest: text.slice(i) };
255
+ }
256
+ /** The values in `text` as `showValues` wrote them: split on ", " outside quoted strings. */
257
+ export function splitValues(text) {
258
+ return readValues(text).values;
259
+ }
260
+ /** Rules that govern the node itself. */
261
+ export const rulesGoverning = (ont, nodeId) => nodes(ont, ont.sources(nodeId, "GOVERNS")).filter((n) => n.type === "Rule");
262
+ export function describeRule(ont, rule) {
263
+ const b = bag(rule);
264
+ const status = b.verification?.status;
265
+ let caveat;
266
+ if (b.extractionConfidence === "corrected")
267
+ caveat = "corrected from the first draft";
268
+ else if (status && status !== "SUPPORTED")
269
+ caveat = `verification: ${status.toLowerCase()}`;
270
+ else if (b.extracted && !b.verification)
271
+ caveat = "not verified against its quote";
272
+ return {
273
+ id: rule.id,
274
+ modality: String(b.modality ?? ""),
275
+ statement: String(b.statement ?? b.name ?? rule.id),
276
+ caveat,
277
+ citations: citationsFor(ont, rule.id),
278
+ };
279
+ }
280
+ /** The passages a node cites, each with its source document and place in it. */
281
+ export function citationsFor(ont, nodeId) {
282
+ return nodes(ont, ont.targets(nodeId, "CITES"))
283
+ .filter((n) => n.type === "SourceLocation")
284
+ .map((loc) => {
285
+ const l = bag(loc);
286
+ const source = nodes(ont, ont.targets(loc.id, "PART_OF")).find((s) => s.type === "Source");
287
+ return {
288
+ quote: String(l.quote ?? ""),
289
+ source: source ? displayName(source) : "unknown source",
290
+ locator: String(l.locator ?? ""),
291
+ lines: typeof l.lines === "string" || typeof l.lines === "number" ? String(l.lines) : undefined,
292
+ link: typeof l.sourceLink === "string" ? l.sourceLink : typeof l.pageLink === "string" ? l.pageLink : undefined,
293
+ };
294
+ });
295
+ }
@@ -0,0 +1,4 @@
1
+ export { OkbMcpError } from "./errors.js";
2
+ export { loadForServing, type HeldBack, type ServingOptions } from "./serving.js";
3
+ export { createServer, SNAPSHOT_URI, type ServerOptions, type Snapshot } from "./server.js";
4
+ export { EVIDENCE_MODES, type Evidence } from "./tools.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // The public API, for embedding the server in another program. Anything not exported here is internal.
2
+ export { OkbMcpError } from "./errors.js";
3
+ export { loadForServing } from "./serving.js";
4
+ export { createServer, SNAPSHOT_URI } from "./server.js";
5
+ export { EVIDENCE_MODES } from "./tools.js";
@@ -0,0 +1,42 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Ontology } from "@ontology-kit/reader";
3
+ import { type Evidence } from "./tools.js";
4
+ export interface ServerOptions {
5
+ /** What tool results show of the evidence behind a rule. Default: the full quote. */
6
+ evidence?: Evidence;
7
+ /**
8
+ * Also serve `read_source`, which returns the text of a cited source document by heading or line range, and
9
+ * show each source's `localPath` in results. `root` is the ontology folder that each `localPath` is relative
10
+ * to: `loadForServing` returns it. Needs `evidence: "full"`. Default: off.
11
+ */
12
+ readSource?: {
13
+ root: string;
14
+ };
15
+ /**
16
+ * Report which data this server loaded, as Eval Kit's snapshot resource: `eval-kit://snapshot`, served as
17
+ * JSON `{"id", "version"}`. It's a resource, not a tool, so the model never sees it. Default: not served.
18
+ */
19
+ snapshot?: Snapshot;
20
+ /**
21
+ * Which skills to serve through the MCP skills extension. `"bundled"` serves the skills this package ships
22
+ * (`query-kb`). `{ kb }` serves those plus the skill folders in `<kb>/skills/`, where `kb` is the ontology
23
+ * folder (`loadForServing` returns it as `root`); those are instructions the KB's author wrote, so pass it only
24
+ * for a KB you trust. `"none"` serves no skills and the server advertises no skills capability. Default: `"bundled"`.
25
+ */
26
+ skills?: "none" | "bundled" | {
27
+ kb: string;
28
+ };
29
+ }
30
+ export interface Snapshot {
31
+ id: string;
32
+ version: string;
33
+ }
34
+ /** The resource URI Eval Kit reads a server's snapshot report from. */
35
+ export declare const SNAPSHOT_URI = "eval-kit://snapshot";
36
+ /** This package's version, read from its package.json (one level above both src/ and dist/). */
37
+ export declare const VERSION: string;
38
+ /**
39
+ * Builds the server for an ontology. The ontology is served as given: to hold back rules that aren't
40
+ * verified, load it with `loadForServing`.
41
+ */
42
+ export declare function createServer(ont: Ontology, { evidence, readSource: readSourceOptions, snapshot, skills }?: ServerOptions): McpServer;