@ontology-kit/mcp 0.0.0-stage → 0.3.0-bootstrap.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +98 -2
- package/bin/okb-mcp.js +8 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +89 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/graph.d.ts +99 -0
- package/dist/graph.js +246 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/server.d.ts +33 -0
- package/dist/server.js +127 -0
- package/dist/serving.d.ts +41 -0
- package/dist/serving.js +66 -0
- package/dist/source.d.ts +13 -0
- package/dist/source.js +125 -0
- package/dist/tools.d.ts +55 -0
- package/dist/tools.js +547 -0
- package/package.json +58 -3
package/dist/tools.js
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { queryFind, queryTraverse, } from "@ontology-kit/reader";
|
|
2
|
+
import { OkbMcpError } from "./errors.js";
|
|
3
|
+
import { ancestors, asStrings, bag, byName, children, citationsFor, classesOf, descendants, describeRule, displayName, instancesOf, parents, propertyValues, relationshipSlots, relationshipsOf, relNames, resolve, resolveRelationship, rulesGoverning, slotsOf, squash, } from "./graph.js";
|
|
4
|
+
export const EVIDENCE_MODES = ["full", "locator", "none"];
|
|
5
|
+
const DEFAULT_LIMIT = 25;
|
|
6
|
+
const STOPWORDS = new Set([
|
|
7
|
+
"the", "a", "an", "of", "to", "in", "on", "for", "and", "or", "is", "are", "be", "should", "can", "do", "does",
|
|
8
|
+
"how", "what", "when", "which", "with", "use", "used", "i", "my", "it", "that", "this", "as", "at", "by", "from",
|
|
9
|
+
]);
|
|
10
|
+
// Shared rendering ------------------------------------------------------
|
|
11
|
+
function clip(text, max) {
|
|
12
|
+
const t = text.replace(/\s+/g, " ").trim();
|
|
13
|
+
return t.length > max ? `${t.slice(0, max - 1).trimEnd()}…` : t;
|
|
14
|
+
}
|
|
15
|
+
function show(value) {
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return value.map(show).join(", ");
|
|
18
|
+
if (value && typeof value === "object")
|
|
19
|
+
return JSON.stringify(value);
|
|
20
|
+
return String(value);
|
|
21
|
+
}
|
|
22
|
+
/** "Button › Accessibility, line 16, https://…": a place in a source document. */
|
|
23
|
+
function whereIs(c) {
|
|
24
|
+
const place = [c.source, c.locator.replace(/^.*?\s>\s/, "") || undefined].filter(Boolean).join(" › ");
|
|
25
|
+
return `${place}${c.lines ? `, line ${c.lines}` : ""}${c.link ? `, ${c.link}` : ""}`;
|
|
26
|
+
}
|
|
27
|
+
/** The place without its link, for lists where a URL on every line would dwarf the content. */
|
|
28
|
+
function whereCompact(c) {
|
|
29
|
+
const place = [c.source, c.locator.replace(/^.*?\s>\s/, "") || undefined].filter(Boolean).join(" › ");
|
|
30
|
+
return `${place}${c.lines ? `, line ${c.lines}` : ""}`;
|
|
31
|
+
}
|
|
32
|
+
/** Lowercase words with a trailing plural s folded away, so "Action Bars" and "Action Bar" match. */
|
|
33
|
+
function wordSet(text) {
|
|
34
|
+
const words = text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
|
|
35
|
+
return new Set(words.map((w) => (w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w)));
|
|
36
|
+
}
|
|
37
|
+
/** True when the quote says (almost) nothing the rule's statement doesn't already say. */
|
|
38
|
+
function addsNothing(statement, quote) {
|
|
39
|
+
const a = wordSet(statement);
|
|
40
|
+
const b = wordSet(quote);
|
|
41
|
+
if (a.size === 0 || b.size === 0)
|
|
42
|
+
return false;
|
|
43
|
+
const shared = [...a].filter((w) => b.has(w)).length;
|
|
44
|
+
return shared / (a.size + b.size - shared) >= 0.8;
|
|
45
|
+
}
|
|
46
|
+
/** One citation as the reader should see it, or undefined when this mode shows none. */
|
|
47
|
+
function evidenceLine(c, evidence, { compact = false, statement } = {}) {
|
|
48
|
+
if (evidence === "none")
|
|
49
|
+
return undefined;
|
|
50
|
+
const place = compact ? whereCompact(c) : whereIs(c);
|
|
51
|
+
const quoteHelps = evidence === "full" && !(compact && statement !== undefined && addsNothing(statement, c.quote));
|
|
52
|
+
return quoteHelps ? `“${c.quote}” (${place})` : `source: ${place}`;
|
|
53
|
+
}
|
|
54
|
+
function ruleLines(ont, rule, evidence, indent = "", { governs = false, compact = false } = {}) {
|
|
55
|
+
const r = describeRule(ont, rule);
|
|
56
|
+
const head = `${indent}[${r.modality}] ${r.statement}${r.caveat ? ` (${r.caveat})` : ""}`;
|
|
57
|
+
const lines = [head];
|
|
58
|
+
if (governs) {
|
|
59
|
+
const names = ont.targets(rule.id, "GOVERNS").map((id) => ont.get(id)).flatMap((n) => (n && bag(n).name ? [String(bag(n).name)] : []));
|
|
60
|
+
if (names.length)
|
|
61
|
+
lines.push(`${indent} governs: ${names.join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
for (const c of r.citations) {
|
|
64
|
+
const line = evidenceLine(c, evidence, { compact, statement: r.statement });
|
|
65
|
+
if (line)
|
|
66
|
+
lines.push(`${indent} ${line}`);
|
|
67
|
+
}
|
|
68
|
+
// A rule's id is only for looking it up; the compact form is for lists, where it would be noise.
|
|
69
|
+
if (!compact)
|
|
70
|
+
lines.push(`${indent} id: ${r.id}`);
|
|
71
|
+
return lines;
|
|
72
|
+
}
|
|
73
|
+
/** A relationship as a short statement: "RadioGroup preferredOver SegmentedControl {condition: ...}". */
|
|
74
|
+
function relationshipLine(self, r) {
|
|
75
|
+
const props = Object.entries(r.props).filter(([k]) => k !== "rule" && k !== "inheritedFrom");
|
|
76
|
+
const rule = typeof r.props.rule === "string" ? r.props.rule : undefined;
|
|
77
|
+
const extra = props.length ? ` {${props.map(([k, v]) => `${k}: ${show(v)}`).join("; ")}}` : "";
|
|
78
|
+
const tail = `${extra}${rule ? ` [rule: ${rule}]` : ""}${r.props.inheritedFrom ? ` (inherited from ${r.props.inheritedFrom})` : ""}`;
|
|
79
|
+
const me = displayName(self);
|
|
80
|
+
const other = displayName(r.other);
|
|
81
|
+
if (r.direction === "out")
|
|
82
|
+
return `${me} ${r.relName} ${other}${tail}`;
|
|
83
|
+
if (r.hasInverse)
|
|
84
|
+
return `${me} ${r.label} ${other}${tail}`;
|
|
85
|
+
return `${other} ${r.relName} ${me}${tail}`;
|
|
86
|
+
}
|
|
87
|
+
function kindOf(n) {
|
|
88
|
+
return n.type === "SourceLocation" ? "passage" : n.type.toLowerCase();
|
|
89
|
+
}
|
|
90
|
+
const names = (nodes) => nodes.map(displayName);
|
|
91
|
+
const sourcesOfSlot = (ont, slotId) => ont.domain(slotId).flatMap((id) => (ont.get(id) ? [displayName(ont.get(id))] : []));
|
|
92
|
+
const rangeOfSlot = (ont, slotId) => ont.range(slotId).flatMap((id) => (ont.get(id) ? [displayName(ont.get(id))] : []));
|
|
93
|
+
// describe_ontology ------------------------------------------------------
|
|
94
|
+
export function describeOntology(ont, evidence = "full", maxLines = 150) {
|
|
95
|
+
const meta = ont.meta;
|
|
96
|
+
const classes = ont.ofType("Class");
|
|
97
|
+
const rules = ont.ofType("Rule");
|
|
98
|
+
const out = [];
|
|
99
|
+
out.push(`${meta.name || "Ontology"}${meta.domain ? ` — ${meta.domain}` : ""}`);
|
|
100
|
+
if (meta.purpose)
|
|
101
|
+
out.push(`Purpose: ${meta.purpose}`);
|
|
102
|
+
const outOfScope = asStrings(meta.outOfScope);
|
|
103
|
+
if (outOfScope.length)
|
|
104
|
+
out.push(`Out of scope: ${outOfScope.join("; ")}`);
|
|
105
|
+
out.push(`${classes.length} classes, ${ont.ofType("Instance").length} instances, ${rules.length} rules, ${ont.ofType("Source").length} source documents.`, "");
|
|
106
|
+
const roots = classes.filter((c) => ont.parents(c.id).length === 0).sort(byName);
|
|
107
|
+
const tree = [];
|
|
108
|
+
const walk = (c, depth, seen) => {
|
|
109
|
+
const direct = instancesOf(ont, c.id, { direct: true }).length;
|
|
110
|
+
const b = bag(c);
|
|
111
|
+
const tags = [b.abstract ? "abstract" : "", direct ? `${direct} instance${direct === 1 ? "" : "s"}` : ""].filter(Boolean);
|
|
112
|
+
tree.push(`${" ".repeat(depth)}${b.name}${tags.length ? ` (${tags.join(", ")})` : ""}${b.description ? ` — ${clip(String(b.description), 80)}` : ""}`);
|
|
113
|
+
if (seen.has(c.id))
|
|
114
|
+
return;
|
|
115
|
+
seen.add(c.id);
|
|
116
|
+
for (const child of children(ont, c.id))
|
|
117
|
+
walk(child, depth + 1, seen);
|
|
118
|
+
};
|
|
119
|
+
for (const r of roots)
|
|
120
|
+
walk(r, 0, new Set());
|
|
121
|
+
out.push("Classes:");
|
|
122
|
+
out.push(...(tree.length > maxLines ? [...tree.slice(0, maxLines), `… ${tree.length - maxLines} more; use find to explore.`] : tree), "");
|
|
123
|
+
const slots = ont.ofType("Slot").sort(byName);
|
|
124
|
+
const props = slots.filter((s) => s.valueType !== "Instance");
|
|
125
|
+
if (props.length) {
|
|
126
|
+
out.push("Properties:");
|
|
127
|
+
for (const s of props) {
|
|
128
|
+
const on = sourcesOfSlot(ont, s.id).join(", ");
|
|
129
|
+
const values = asStrings(s.allowedValues);
|
|
130
|
+
out.push(` ${s.name}${values.length ? ` (${values.join(" | ")})` : s.valueType ? ` (${s.valueType})` : ""}${on ? ` on ${on}` : ""}`);
|
|
131
|
+
}
|
|
132
|
+
out.push("");
|
|
133
|
+
}
|
|
134
|
+
const rels = relationshipSlots(ont);
|
|
135
|
+
if (rels.length) {
|
|
136
|
+
const rn = relNames(ont);
|
|
137
|
+
out.push("Relationships:");
|
|
138
|
+
for (const s of rels) {
|
|
139
|
+
const from = sourcesOfSlot(ont, s.id).join(", ");
|
|
140
|
+
const to = rangeOfSlot(ont, s.id).join(", ");
|
|
141
|
+
const edgeProps = ont.rel.edgeProperties(s.id).map((p) => p.name).filter(Boolean);
|
|
142
|
+
const inverse = rn.inverseLabel(String(s.relType));
|
|
143
|
+
out.push(` ${s.name}: ${from || "?"} → ${to || "?"}` +
|
|
144
|
+
`${edgeProps.length ? `; edge properties: ${edgeProps.join(", ")}` : ""}` +
|
|
145
|
+
`${inverse.endsWith("(incoming)") ? "" : `; read backwards as ${inverse}`}`);
|
|
146
|
+
}
|
|
147
|
+
out.push("");
|
|
148
|
+
}
|
|
149
|
+
const byModality = new Map();
|
|
150
|
+
for (const r of rules)
|
|
151
|
+
byModality.set(String(r.modality), (byModality.get(String(r.modality)) ?? 0) + 1);
|
|
152
|
+
const provenance = {
|
|
153
|
+
full: "Each cites a verbatim quote from a source document.",
|
|
154
|
+
locator: "Each cites its location in a source document.",
|
|
155
|
+
none: "Each was verified against its source document.",
|
|
156
|
+
}[evidence];
|
|
157
|
+
if (byModality.size)
|
|
158
|
+
out.push(`Rules: ${[...byModality].map(([m, n]) => `${m} ${n}`).join(", ")}. ${provenance}`);
|
|
159
|
+
out.push("Tools: find (search/filter), get (everything about one thing), traverse (follow relationships), list_rules.");
|
|
160
|
+
return out.join("\n");
|
|
161
|
+
}
|
|
162
|
+
function tokens(query) {
|
|
163
|
+
return query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1 && !STOPWORDS.has(t));
|
|
164
|
+
}
|
|
165
|
+
function searchText(ont, n, evidence, showPaths) {
|
|
166
|
+
const b = bag(n);
|
|
167
|
+
// A rule's name is a clipped sentence, so it counts as its own text, not as a name worth ranking on.
|
|
168
|
+
const name = n.type === "Rule" ? "" : [displayName(n), ...asStrings(b.synonyms)].filter(Boolean).join(" ").toLowerCase();
|
|
169
|
+
const own = [String(b.description ?? ""), String(b.statement ?? ""), n.type === "Rule" ? String(b.name ?? "") : "", showPaths && n.type === "Source" ? String(b.localPath ?? "") : ""]
|
|
170
|
+
.join(" ").toLowerCase();
|
|
171
|
+
// Quote text is only searchable when the reader can see quotes.
|
|
172
|
+
const cited = evidence === "full" ? citationsFor(ont, n.id).map((c) => c.quote).join(" ").toLowerCase() : "";
|
|
173
|
+
return { name, own, cited };
|
|
174
|
+
}
|
|
175
|
+
/** The slot a filter key names, matched like a name on the command line but also ignoring punctuation. */
|
|
176
|
+
function slotFor(ont, key) {
|
|
177
|
+
return ont.ofType("Slot").find((s) => squash(s.name) === squash(key));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Does the node have `key` = `wanted`? The values come from the query layer: the node's own, what a class
|
|
181
|
+
* fixes for it, or a relationship's targets. `"*"` means "has any value". The comparison ignores case and
|
|
182
|
+
* punctuation, which the layer's exact matching doesn't.
|
|
183
|
+
*/
|
|
184
|
+
function hasValue(ont, node, slot, wanted) {
|
|
185
|
+
const have = queryTraverse(ont, { from: node.id, slot: slot.id });
|
|
186
|
+
if (wanted === "*")
|
|
187
|
+
return have.length > 0;
|
|
188
|
+
const w = squash(String(wanted));
|
|
189
|
+
return have.some((h) => squash(h.name) === w);
|
|
190
|
+
}
|
|
191
|
+
/** Does the class permit `key` = `wanted`: one of the slot's allowed values, or (with "*") simply have the slot? Only classes have slots. */
|
|
192
|
+
function permits(ont, node, slot, wanted) {
|
|
193
|
+
if (node.type !== "Class")
|
|
194
|
+
return false;
|
|
195
|
+
if (!ont.applicableSlots(node.id).includes(slot.id))
|
|
196
|
+
return false;
|
|
197
|
+
if (wanted === "*")
|
|
198
|
+
return true;
|
|
199
|
+
return asStrings(bag(slot).allowedValues).some((v) => squash(v) === squash(String(wanted)));
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* `showPaths` says whether a source's `localPath` appears in results, and in what a search matches. It is on
|
|
203
|
+
* only when `read_source` is served; otherwise the agent has no use for a file path.
|
|
204
|
+
*/
|
|
205
|
+
export function find(ont, args, evidence = "full", showPaths = false) {
|
|
206
|
+
const limit = Math.max(1, Math.min(args.limit ?? DEFAULT_LIMIT, 200));
|
|
207
|
+
const typeNames = args.type ? [args.type.charAt(0).toUpperCase() + args.type.slice(1)] : ["Class", "Instance", "Slot", "Rule"];
|
|
208
|
+
let pool = ont.nodes.filter((n) => typeNames.includes(n.type));
|
|
209
|
+
if (args.class) {
|
|
210
|
+
const cls = resolve(ont, args.class, ["Class"]);
|
|
211
|
+
const family = new Set([cls.id, ...ont.descendants(cls.id)]);
|
|
212
|
+
// The members are what the query layer says they are: instances of the class and its subclasses.
|
|
213
|
+
const members = new Set(queryFind(ont, { class: cls.id }).map((h) => h.id));
|
|
214
|
+
pool = pool.filter((n) => {
|
|
215
|
+
if (n.type === "Class")
|
|
216
|
+
return family.has(n.id) && n.id !== cls.id;
|
|
217
|
+
if (n.type === "Instance")
|
|
218
|
+
return members.has(n.id);
|
|
219
|
+
if (n.type === "Rule")
|
|
220
|
+
return ont.targets(n.id, "GOVERNS").some((g) => family.has(g));
|
|
221
|
+
return false;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const filters = [
|
|
225
|
+
[args.where, (n, s, w) => hasValue(ont, n, s, w)],
|
|
226
|
+
[args.allows, (n, s, w) => permits(ont, n, s, w)],
|
|
227
|
+
];
|
|
228
|
+
let filtered = false;
|
|
229
|
+
for (const [filter, test] of filters) {
|
|
230
|
+
if (!filter || Object.keys(filter).length === 0)
|
|
231
|
+
continue;
|
|
232
|
+
filtered = true;
|
|
233
|
+
const checks = Object.entries(filter).map(([key, wanted]) => {
|
|
234
|
+
const slot = slotFor(ont, key);
|
|
235
|
+
if (!slot) {
|
|
236
|
+
throw new OkbMcpError(`"${key}" isn't a property or relationship here. Known: ${ont.ofType("Slot").sort(byName).map((s) => s.name).join(", ")}.`);
|
|
237
|
+
}
|
|
238
|
+
return { slot, wanted };
|
|
239
|
+
});
|
|
240
|
+
pool = pool.filter((n) => (n.type === "Class" || n.type === "Instance") && checks.every((c) => test(n, c.slot, c.wanted)));
|
|
241
|
+
}
|
|
242
|
+
// An abstract class is a category (Button, as opposed to PrimaryButton). It can carry values its
|
|
243
|
+
// members inherit, but "which components are X" is asking for the members, not the category.
|
|
244
|
+
if (filtered)
|
|
245
|
+
pool = pool.filter((n) => !(n.type === "Class" && bag(n).abstract === true));
|
|
246
|
+
let ranked;
|
|
247
|
+
const words = args.query ? tokens(args.query) : [];
|
|
248
|
+
if (words.length) {
|
|
249
|
+
const wholeQuery = squash(args.query ?? "");
|
|
250
|
+
const typeOrder = ["Class", "Instance", "Slot", "Rule", "Source"];
|
|
251
|
+
const scored = pool
|
|
252
|
+
.map((n) => {
|
|
253
|
+
const t = searchText(ont, n, evidence, showPaths);
|
|
254
|
+
// A word in the name counts most, then the node's own text; a quote it merely cites counts least.
|
|
255
|
+
let score = words.reduce((s, w) => s + (t.name.includes(w) ? 3 : 0) + (t.own.includes(w) ? 2 : 0) + (!t.own.includes(w) && t.cited.includes(w) ? 1 : 0), 0);
|
|
256
|
+
// The thing the query names outranks things that merely mention it.
|
|
257
|
+
if (wholeQuery && [displayName(n), ...asStrings(bag(n).synonyms)].some((x) => x && squash(String(x)) === wholeQuery))
|
|
258
|
+
score += 20;
|
|
259
|
+
return { n, score };
|
|
260
|
+
})
|
|
261
|
+
.filter((x) => x.score > 0)
|
|
262
|
+
.sort((a, b) => b.score - a.score || typeOrder.indexOf(a.n.type) - typeOrder.indexOf(b.n.type) || byName(a.n, b.n));
|
|
263
|
+
ranked = scored.map((x) => x.n);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
ranked = [...pool].sort((a, b) => a.type.localeCompare(b.type) || byName(a, b));
|
|
267
|
+
}
|
|
268
|
+
if (ranked.length === 0) {
|
|
269
|
+
return `No matches${args.query ? ` for "${args.query}"` : ""}. Try fewer words, or describe_ontology to see what exists.`;
|
|
270
|
+
}
|
|
271
|
+
const lines = ranked.slice(0, limit).map((n) => findLine(ont, n, showPaths));
|
|
272
|
+
const more = ranked.length > limit ? [`… ${ranked.length - limit} more (raise limit, or narrow with type/class/where).`] : [];
|
|
273
|
+
return [`${ranked.length} match${ranked.length === 1 ? "" : "es"}:`, ...lines, ...more].join("\n");
|
|
274
|
+
}
|
|
275
|
+
function findLine(ont, n, showPaths) {
|
|
276
|
+
const b = bag(n);
|
|
277
|
+
switch (n.type) {
|
|
278
|
+
case "Class": {
|
|
279
|
+
const parentNames = names(parents(ont, n.id)).join(", ");
|
|
280
|
+
const tag = [b.abstract === true ? "abstract category" : "", parentNames ? `kind of ${parentNames}` : ""].filter(Boolean).join("; ");
|
|
281
|
+
return `- class ${b.name}${tag ? ` (${tag})` : ""}${b.description ? `: ${clip(String(b.description), 110)}` : ""}`;
|
|
282
|
+
}
|
|
283
|
+
case "Instance": {
|
|
284
|
+
const of = ont.targets(n.id, "INSTANCE_OF").flatMap((id) => (ont.get(id) ? [displayName(ont.get(id))] : [])).join(", ");
|
|
285
|
+
// A few properties, each clipped: long descriptions on hundreds of instances would swamp a list.
|
|
286
|
+
const vals = propertyValues(ont, n).slice(0, 3).map((p) => `${bag(p.slot).name}=${clip(show(p.value), 70)}`).join(", ");
|
|
287
|
+
return `- instance ${b.name}${of ? ` (${of})` : ""}${vals ? `: ${vals}` : ""}`;
|
|
288
|
+
}
|
|
289
|
+
case "Slot": {
|
|
290
|
+
const on = sourcesOfSlot(ont, n.id).join(", ");
|
|
291
|
+
const relationship = b.valueType === "Instance";
|
|
292
|
+
const allowed = asStrings(b.allowedValues);
|
|
293
|
+
const kind = relationship ? `relationship → ${rangeOfSlot(ont, n.id).join(", ")}` : `property${allowed.length ? ` (${allowed.join(" | ")})` : ""}`;
|
|
294
|
+
return `- ${relationship ? "relationship" : "property"} ${b.name}${on ? ` on ${on}` : ""}: ${kind}`;
|
|
295
|
+
}
|
|
296
|
+
case "Rule": {
|
|
297
|
+
const governs = ont.targets(n.id, "GOVERNS").flatMap((id) => (ont.get(id) ? [displayName(ont.get(id))] : [])).join(", ");
|
|
298
|
+
return `- rule [${b.modality}] ${clip(String(b.statement ?? b.name), 140)}${governs ? ` (governs ${governs})` : ""} (${n.id})`;
|
|
299
|
+
}
|
|
300
|
+
default:
|
|
301
|
+
return `- ${kindOf(n)} ${displayName(n)}${showPaths && b.localPath ? ` (${b.localPath})` : ""}`;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// get -------------------------------------------------------------------
|
|
305
|
+
export function get(ont, ref, evidence = "full", showPaths = false) {
|
|
306
|
+
const node = resolve(ont, ref);
|
|
307
|
+
switch (node.type) {
|
|
308
|
+
case "Class": return getClass(ont, node, evidence);
|
|
309
|
+
case "Instance": return getInstance(ont, node, evidence);
|
|
310
|
+
case "Slot": return getSlot(ont, node);
|
|
311
|
+
case "Rule": return ruleLines(ont, node, evidence, "", { governs: true }).join("\n");
|
|
312
|
+
default: return getSource(ont, node, evidence, showPaths);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/** Passages the node cites that aren't already shown under one of its rules. */
|
|
316
|
+
function sourcePassages(ont, node, shown, evidence) {
|
|
317
|
+
if (evidence === "none")
|
|
318
|
+
return [];
|
|
319
|
+
const cites = citationsFor(ont, node.id).filter((c) => !shown.has(c.quote));
|
|
320
|
+
if (cites.length === 0)
|
|
321
|
+
return [];
|
|
322
|
+
return [evidence === "full" ? "Source passages:" : "Also cited from:", ...cites.map((c) => ` ${evidenceLine(c, evidence, { compact: true })}`)];
|
|
323
|
+
}
|
|
324
|
+
function quotesOf(ont, rules) {
|
|
325
|
+
return new Set(rules.flatMap((r) => citationsFor(ont, r.id).map((c) => c.quote)));
|
|
326
|
+
}
|
|
327
|
+
function getClass(ont, c, evidence) {
|
|
328
|
+
const b = bag(c);
|
|
329
|
+
const out = [];
|
|
330
|
+
const up = ancestors(ont, c.id);
|
|
331
|
+
out.push(`Class: ${b.name}${b.abstract ? " (abstract)" : ""}${up.length ? ` — kind of ${names(up).join(" > ")}` : ""}`);
|
|
332
|
+
if (b.description)
|
|
333
|
+
out.push(String(b.description));
|
|
334
|
+
const syn = asStrings(b.synonyms);
|
|
335
|
+
if (syn.length)
|
|
336
|
+
out.push(`Also called: ${syn.join(", ")}`);
|
|
337
|
+
const props = propertyValues(ont, c);
|
|
338
|
+
const own = slotsOf(ont, c).filter((s) => bag(s.slot).valueType !== "Instance");
|
|
339
|
+
if (own.length) {
|
|
340
|
+
out.push("", "Properties:");
|
|
341
|
+
for (const { slot, from } of own) {
|
|
342
|
+
const s = bag(slot);
|
|
343
|
+
const values = asStrings(s.allowedValues);
|
|
344
|
+
const fixed = props.find((p) => p.slot.id === slot.id);
|
|
345
|
+
out.push(` ${s.name}${values.length ? `: ${values.join(" | ")}` : s.valueType ? ` (${s.valueType})` : ""}` +
|
|
346
|
+
`${s.default !== undefined ? `, default ${show(s.default)}` : ""}` +
|
|
347
|
+
`${fixed ? `, always ${show(fixed.value)}` : ""}` +
|
|
348
|
+
`${from.id !== c.id ? ` (inherited from ${displayName(from)})` : ""}` +
|
|
349
|
+
`${s.description ? ` — ${clip(String(s.description), 90)}` : ""}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const rels = relationshipsOf(ont, c);
|
|
353
|
+
if (rels.length) {
|
|
354
|
+
out.push("", "Relationships:");
|
|
355
|
+
for (const r of rels)
|
|
356
|
+
out.push(` ${relationshipLine(c, r)}`);
|
|
357
|
+
}
|
|
358
|
+
const kids = children(ont, c.id);
|
|
359
|
+
if (kids.length)
|
|
360
|
+
out.push("", `Subclasses: ${names(kids).join(", ")}`);
|
|
361
|
+
const instances = instancesOf(ont, c.id, { direct: true });
|
|
362
|
+
if (instances.length)
|
|
363
|
+
out.push("", `Instances: ${names(instances).join(", ")}`);
|
|
364
|
+
const ownRules = rulesGoverning(ont, c.id);
|
|
365
|
+
if (ownRules.length) {
|
|
366
|
+
out.push("", "Rules:");
|
|
367
|
+
for (const r of ownRules)
|
|
368
|
+
out.push(...ruleLines(ont, r, evidence, " ", { compact: true }));
|
|
369
|
+
}
|
|
370
|
+
const inherited = up.flatMap((a) => rulesGoverning(ont, a.id).map((r) => ({ r, a })));
|
|
371
|
+
if (inherited.length) {
|
|
372
|
+
out.push("", "Rules inherited from parent classes:");
|
|
373
|
+
for (const { r, a } of inherited)
|
|
374
|
+
out.push(` (from ${displayName(a)})`, ...ruleLines(ont, r, evidence, " ", { compact: true }));
|
|
375
|
+
}
|
|
376
|
+
const passages = sourcePassages(ont, c, quotesOf(ont, [...ownRules, ...inherited.map((i) => i.r)]), evidence);
|
|
377
|
+
if (passages.length)
|
|
378
|
+
out.push("", ...passages);
|
|
379
|
+
return out.join("\n");
|
|
380
|
+
}
|
|
381
|
+
function getInstance(ont, n, evidence) {
|
|
382
|
+
const b = bag(n);
|
|
383
|
+
const out = [];
|
|
384
|
+
const classes = classesOf(ont, n);
|
|
385
|
+
out.push(`Instance: ${b.name}${classes.length ? ` — a ${names(classes).join(" > ")}` : ""}`);
|
|
386
|
+
if (b.description)
|
|
387
|
+
out.push(String(b.description));
|
|
388
|
+
const props = propertyValues(ont, n);
|
|
389
|
+
if (props.length) {
|
|
390
|
+
out.push("", "Properties:");
|
|
391
|
+
for (const p of props)
|
|
392
|
+
out.push(` ${bag(p.slot).name}: ${show(p.value)}${p.inheritedFrom ? ` (from ${displayName(p.inheritedFrom)})` : ""}`);
|
|
393
|
+
}
|
|
394
|
+
const rels = relationshipsOf(ont, n);
|
|
395
|
+
if (rels.length) {
|
|
396
|
+
out.push("", "Relationships:");
|
|
397
|
+
for (const r of rels)
|
|
398
|
+
out.push(` ${relationshipLine(n, r)}`);
|
|
399
|
+
}
|
|
400
|
+
const rules = [n, ...classes].flatMap((x) => rulesGoverning(ont, x.id).map((r) => ({ r, x })));
|
|
401
|
+
if (rules.length) {
|
|
402
|
+
out.push("", "Rules:");
|
|
403
|
+
for (const { r, x } of rules)
|
|
404
|
+
out.push(...ruleLines(ont, r, evidence, " ", { compact: true }).map((l, i) => (i === 0 && x.id !== n.id ? `${l} (via ${displayName(x)})` : l)));
|
|
405
|
+
}
|
|
406
|
+
const passages = sourcePassages(ont, n, quotesOf(ont, rules.map((x) => x.r)), evidence);
|
|
407
|
+
if (passages.length)
|
|
408
|
+
out.push("", ...passages);
|
|
409
|
+
return out.join("\n");
|
|
410
|
+
}
|
|
411
|
+
function getSlot(ont, slot) {
|
|
412
|
+
const s = bag(slot);
|
|
413
|
+
const out = [];
|
|
414
|
+
const rel = s.valueType === "Instance";
|
|
415
|
+
out.push(`${rel ? "Relationship" : "Property"}: ${s.name}`);
|
|
416
|
+
if (s.description)
|
|
417
|
+
out.push(String(s.description));
|
|
418
|
+
const on = sourcesOfSlot(ont, slot.id).join(", ");
|
|
419
|
+
if (on)
|
|
420
|
+
out.push(`On: ${on}`);
|
|
421
|
+
if (rel) {
|
|
422
|
+
out.push(`Points to: ${rangeOfSlot(ont, slot.id).join(", ") || "any"}`);
|
|
423
|
+
const props = ont.rel.edgeProperties(slot.id);
|
|
424
|
+
if (props.length)
|
|
425
|
+
out.push(`Edge properties: ${props.map((p) => `${p.name} (${p.valueType})`).join(", ")}`);
|
|
426
|
+
if (!ont.rel.isPrimary(slot.id)) {
|
|
427
|
+
out.push(`The same relationship as ${displayName(ont.require(ont.rel.primary(slot.id)))}, read from the other end.`);
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
const inv = relNames(ont).inverseLabel(String(s.relType));
|
|
431
|
+
if (!inv.endsWith("(incoming)"))
|
|
432
|
+
out.push(`Read from the other end as: ${inv}`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
out.push(`Value type: ${s.valueType}`);
|
|
437
|
+
const values = asStrings(s.allowedValues);
|
|
438
|
+
if (values.length)
|
|
439
|
+
out.push(`Allowed values: ${values.join(" | ")}`);
|
|
440
|
+
if (s.default !== undefined)
|
|
441
|
+
out.push(`Default: ${show(s.default)}`);
|
|
442
|
+
}
|
|
443
|
+
return out.join("\n");
|
|
444
|
+
}
|
|
445
|
+
function getSource(ont, src, evidence, showPaths) {
|
|
446
|
+
const s = bag(src);
|
|
447
|
+
const out = [`Source: ${s.title ?? s.name ?? src.id}${showPaths && s.localPath ? ` (${s.localPath})` : ""}`];
|
|
448
|
+
const url = s.url ?? s.repoUrl;
|
|
449
|
+
if (typeof url === "string")
|
|
450
|
+
out.push(url);
|
|
451
|
+
if (evidence === "none")
|
|
452
|
+
return out.join("\n");
|
|
453
|
+
const passages = ont.sources(src.id, "PART_OF").map((id) => ont.get(id)).filter((n) => n?.type === "SourceLocation");
|
|
454
|
+
if (passages.length) {
|
|
455
|
+
const place = (p) => `${String(bag(p).locator ?? "").replace(/^.*?\s>\s/, "")}${bag(p).lines ? `, line ${bag(p).lines}` : ""}`;
|
|
456
|
+
out.push("", `${passages.length} ${evidence === "full" ? "quoted passage" : "cited location"}${passages.length === 1 ? "" : "s"}:`);
|
|
457
|
+
for (const p of passages.slice(0, 40))
|
|
458
|
+
out.push(evidence === "full" ? ` “${bag(p).quote}” (${place(p)})` : ` ${place(p)}`);
|
|
459
|
+
}
|
|
460
|
+
return out.join("\n");
|
|
461
|
+
}
|
|
462
|
+
const MAX_TRAVERSE_LINES = 100;
|
|
463
|
+
/**
|
|
464
|
+
* Follows one relationship. `direction` is relative to how the relationship is stored, so naming an
|
|
465
|
+
* inverse (`produces`) reads the stored edges backwards by default, and an explicit direction means
|
|
466
|
+
* what it says whichever name is used. The query layer reads a slot in its own direction, so the
|
|
467
|
+
* direction is translated before the call.
|
|
468
|
+
*/
|
|
469
|
+
export function traverse(ont, args) {
|
|
470
|
+
const { slot, backwards } = resolveRelationship(ont, args.relationship);
|
|
471
|
+
const direction = args.direction ?? (backwards ? "in" : "out");
|
|
472
|
+
const depth = Math.max(1, Math.min(args.depth ?? 1, 3));
|
|
473
|
+
const starts = args.from.map((ref) => resolve(ont, ref, ["Class", "Instance"]));
|
|
474
|
+
const type = ont.rel.spec(slot.id).type;
|
|
475
|
+
const rn = relNames(ont);
|
|
476
|
+
// The slot as named reads one way; asking for the other way is the layer's `direction: "in"`.
|
|
477
|
+
const hits = queryTraverse(ont, {
|
|
478
|
+
from: starts.map((s) => s.id),
|
|
479
|
+
slot: slot.id,
|
|
480
|
+
depth,
|
|
481
|
+
...(direction === (backwards ? "in" : "out") ? {} : { direction: "in" }),
|
|
482
|
+
});
|
|
483
|
+
if (hits.length === 0) {
|
|
484
|
+
return `No "${rn.name(type)}" relationships ${direction === "out" ? "from" : "into"} ${starts.map(displayName).join(", ")}.`;
|
|
485
|
+
}
|
|
486
|
+
const inverse = direction === "in" && rn.hasInverse(type);
|
|
487
|
+
const lines = hits.slice(0, MAX_TRAVERSE_LINES).map((h) => {
|
|
488
|
+
const node = ont.require(h.from);
|
|
489
|
+
const other = h.id ? ont.get(h.id) : undefined;
|
|
490
|
+
const otherName = other ? displayName(other) : h.name;
|
|
491
|
+
// Reading backwards through a declared inverse says it that way: "Winery produces Wine".
|
|
492
|
+
const [a, verb, b] = inverse
|
|
493
|
+
? [displayName(node), rn.inverseLabel(type), otherName]
|
|
494
|
+
: direction === "out" ? [displayName(node), rn.name(type), otherName] : [otherName, rn.name(type), displayName(node)];
|
|
495
|
+
const edge = h.edge ?? {};
|
|
496
|
+
const shown = Object.entries(edge).filter(([k]) => k !== "rule").map(([k, v]) => `${k}: ${show(v)}`).join("; ");
|
|
497
|
+
return (`${" ".repeat(h.depth - 1)}${a} —${verb}→ ${b}${shown ? ` {${shown}}` : ""}` +
|
|
498
|
+
`${typeof edge.rule === "string" ? ` [rule: ${edge.rule}]` : ""}${h.inheritedFrom ? ` (inherited from ${displayName(ont.require(h.inheritedFrom))})` : ""}`);
|
|
499
|
+
});
|
|
500
|
+
const verbName = inverse ? rn.inverseLabel(type) : rn.name(type);
|
|
501
|
+
return [`${lines.length} ${verbName} link${lines.length === 1 ? "" : "s"} (${direction === "out" ? "following" : "reading backwards"}):`, ...lines].join("\n");
|
|
502
|
+
}
|
|
503
|
+
export function listRules(ont, args, evidence = "full") {
|
|
504
|
+
const limit = Math.max(1, Math.min(args.limit ?? DEFAULT_LIMIT, 100));
|
|
505
|
+
let rules = ont.ofType("Rule");
|
|
506
|
+
const notes = [];
|
|
507
|
+
if (args.about) {
|
|
508
|
+
const subject = resolve(ont, args.about, ["Class", "Instance", "Slot"]);
|
|
509
|
+
const family = new Map([[subject.id, undefined]]);
|
|
510
|
+
if (subject.type === "Class") {
|
|
511
|
+
for (const d of descendants(ont, subject.id))
|
|
512
|
+
family.set(d.id, undefined);
|
|
513
|
+
for (const a of ancestors(ont, subject.id))
|
|
514
|
+
family.set(a.id, displayName(a));
|
|
515
|
+
}
|
|
516
|
+
else if (subject.type === "Instance") {
|
|
517
|
+
for (const c of classesOf(ont, subject))
|
|
518
|
+
family.set(c.id, displayName(c));
|
|
519
|
+
}
|
|
520
|
+
rules = rules.filter((r) => ont.targets(r.id, "GOVERNS").some((g) => family.has(g)));
|
|
521
|
+
const inheritedOnly = rules.filter((r) => !ont.targets(r.id, "GOVERNS").some((g) => family.has(g) && family.get(g) === undefined));
|
|
522
|
+
if (inheritedOnly.length)
|
|
523
|
+
notes.push(`${inheritedOnly.length} of these come from parent classes and apply to ${displayName(subject)} too.`);
|
|
524
|
+
}
|
|
525
|
+
if (args.modality) {
|
|
526
|
+
const want = args.modality.toUpperCase().replace(/[\s-]+/g, "_");
|
|
527
|
+
rules = rules.filter((r) => String(bag(r).modality).toUpperCase() === want);
|
|
528
|
+
}
|
|
529
|
+
const words = args.query ? tokens(args.query) : [];
|
|
530
|
+
if (words.length) {
|
|
531
|
+
rules = rules.filter((r) => {
|
|
532
|
+
const quotes = evidence === "full" ? citationsFor(ont, r.id).map((c) => c.quote).join(" ") : "";
|
|
533
|
+
const text = `${bag(r).statement} ${quotes}`.toLowerCase();
|
|
534
|
+
return words.some((w) => text.includes(w));
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
if (rules.length === 0)
|
|
538
|
+
return "No rules match.";
|
|
539
|
+
const order = ["MUST", "MUST_NOT", "SHOULD", "SHOULD_NOT", "MAY"];
|
|
540
|
+
rules = [...rules].sort((a, b) => order.indexOf(String(bag(a).modality)) - order.indexOf(String(bag(b).modality)) || byName(a, b));
|
|
541
|
+
const out = [`${rules.length} rule${rules.length === 1 ? "" : "s"}:`, ...notes];
|
|
542
|
+
for (const r of rules.slice(0, limit))
|
|
543
|
+
out.push(...ruleLines(ont, r, evidence, "", { governs: true, compact: true }));
|
|
544
|
+
if (rules.length > limit)
|
|
545
|
+
out.push(`… ${rules.length - limit} more (raise limit, or narrow with about/modality/query).`);
|
|
546
|
+
return out.join("\n");
|
|
547
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ontology-kit/mcp",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.3.0-bootstrap.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "An MCP server that serves an okb ontology to an agent as a queryable knowledge graph, with the rules and the source quotes behind them.",
|
|
6
|
+
"homepage": "https://ontology-kit.dev",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/alanbsmith/ontology-kit.git",
|
|
10
|
+
"directory": "packages/mcp"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/alanbsmith/ontology-kit/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"ontology",
|
|
17
|
+
"knowledge-graph",
|
|
18
|
+
"mcp",
|
|
19
|
+
"model-context-protocol",
|
|
20
|
+
"okb"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"development": "./src/index.ts",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./package.json": "./package.json"
|
|
33
|
+
},
|
|
34
|
+
"bin": {
|
|
35
|
+
"okb-mcp": "bin/okb-mcp.js"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"bin",
|
|
39
|
+
"dist",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=24"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
48
|
+
"@ontology-kit/reader": "0.2.0",
|
|
49
|
+
"zod": "^4.6.5"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^26.6.6",
|
|
53
|
+
"typescript": "^7.0.2"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"start": "node src/cli.ts",
|
|
57
|
+
"typecheck": "tsc",
|
|
58
|
+
"test": "node --conditions=development --test --test-concurrency=1 \"tests/*.test.ts\"",
|
|
59
|
+
"build": "pnpm --filter @ontology-kit/reader run build && rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/rewrite-dts.ts"
|
|
60
|
+
}
|
|
6
61
|
}
|