@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/dist/server.js ADDED
@@ -0,0 +1,127 @@
1
+ // The MCP server: five tools over an okb ontology, and read_source when asked. Started by cli.ts.
2
+ import { readFileSync } from "node:fs";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { z } from "zod";
5
+ import { OkbMcpError } from "./errors.js";
6
+ import { readSource } from "./source.js";
7
+ import { describeOntology, find, get, listRules, traverse } from "./tools.js";
8
+ /** The resource URI Eval Kit reads a server's snapshot report from. */
9
+ export const SNAPSHOT_URI = "eval-kit://snapshot";
10
+ /** This package's version, read from its package.json (one level above both src/ and dist/). */
11
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
12
+ /** Wording for the tool descriptions, which the model reads: they must match what the results actually contain. */
13
+ function evidenceWording(evidence) {
14
+ switch (evidence) {
15
+ case "full":
16
+ return {
17
+ search: "names, descriptions, rule statements and quoted source text",
18
+ get: "the rules that govern it, and the verbatim source passages behind them",
19
+ rules: "the verbatim quote it came from",
20
+ ruleQuery: "Words to look for in the rule or its quote",
21
+ };
22
+ case "locator":
23
+ return {
24
+ search: "names, descriptions and rule statements",
25
+ get: "the rules that govern it, and where in the source documents each came from",
26
+ rules: "where in the source documents it came from",
27
+ ruleQuery: "Words to look for in the rule",
28
+ };
29
+ case "none":
30
+ return {
31
+ search: "names, descriptions and rule statements",
32
+ get: "and the rules that govern it",
33
+ rules: "its statement",
34
+ ruleQuery: "Words to look for in the rule",
35
+ };
36
+ }
37
+ }
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 function createServer(ont, { evidence = "full", readSource: readSourceOptions, snapshot } = {}) {
43
+ const withReadSource = readSourceOptions !== undefined;
44
+ if (withReadSource && !readSourceOptions.root)
45
+ throw new OkbMcpError("read_source needs the ontology folder: pass `readSource: { root }`, where root is what loadForServing returns.");
46
+ if (withReadSource && evidence !== "full") {
47
+ throw new OkbMcpError(`read_source returns the documents' own text, quotes included, so it can't be served with evidence "${evidence}". Use "full", or leave read_source off.`);
48
+ }
49
+ const name = String(ont.meta.name || "ontology");
50
+ const words = evidenceWording(evidence);
51
+ const server = new McpServer({ name: `okb-${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`, version: VERSION });
52
+ /** Runs a tool, returning ordinary mistakes (unknown names) to the model as tool errors it can act on. */
53
+ const run = (fn) => {
54
+ try {
55
+ return { content: [{ type: "text", text: fn() }] };
56
+ }
57
+ catch (err) {
58
+ if (err instanceof OkbMcpError)
59
+ return { content: [{ type: "text", text: err.message }], isError: true };
60
+ throw err;
61
+ }
62
+ };
63
+ server.registerTool("describe_ontology", {
64
+ description: `Overview of the ${name} knowledge base: what it covers, the class hierarchy, properties, relationships and how many rules it holds. Call this first to learn what exists and what to search for.`,
65
+ }, async () => run(() => describeOntology(ont, evidence)));
66
+ server.registerTool("find", {
67
+ description: `Search or filter the knowledge base. Free-text \`query\` matches ${words.search}. ` +
68
+ "`class` lists the members of a class (including subclasses). `where` filters on values the thing has: " +
69
+ "where={shippedIn: \"lumen-web\"}, or \"*\" for any value. `allows` filters classes by the values their properties permit: " +
70
+ "allows={size: \"large\"} finds components that support a large size. Abstract categories are left out of filtered results, so you get the " +
71
+ "members. Use this for 'which ...' and 'list every ...' questions.",
72
+ inputSchema: {
73
+ query: z.string().optional().describe("Words to search for"),
74
+ type: z.enum(["class", "instance", "slot", "rule", "source"]).optional().describe("Only return this kind of thing"),
75
+ class: z.string().optional().describe("Only members (and subclasses) of this class"),
76
+ where: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional()
77
+ .describe("Property or relationship name → the value it has (\"*\" for any value)"),
78
+ allows: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional()
79
+ .describe("Property name → a value the class permits (\"*\" for classes that have the property)"),
80
+ limit: z.number().int().min(1).max(200).optional().describe("Maximum results (default 25)"),
81
+ },
82
+ }, async (args) => run(() => find(ont, args, evidence, withReadSource)));
83
+ server.registerTool("get", {
84
+ description: "Everything the knowledge base says about one class, instance, property, relationship, rule or source: description, properties, " +
85
+ `relationships (with conditions), ${words.get}. Accepts a name or id.`,
86
+ inputSchema: { name: z.string().describe("Name or id, such as Button, lumen-web, or rule.modals-must-trap-focus-while-open") },
87
+ }, async ({ name }) => run(() => get(ont, name, evidence, withReadSource)));
88
+ server.registerTool("traverse", {
89
+ description: "Follow one relationship from one or more starting points. Use for questions that connect things " +
90
+ "('what is preferred over X', 'what is built on Y'). `depth` follows the relationship further (up to 3).",
91
+ inputSchema: {
92
+ from: z.array(z.string()).min(1).describe("Names of the starting classes or instances"),
93
+ relationship: z.string().describe("Relationship name, such as preferredOver (see describe_ontology)"),
94
+ direction: z.enum(["out", "in"]).optional().describe("out follows links away from the start; in reads them backwards"),
95
+ depth: z.number().int().min(1).max(3).optional().describe("How many hops (default 1)"),
96
+ },
97
+ }, async (args) => run(() => traverse(ont, args)));
98
+ server.registerTool("list_rules", {
99
+ description: `List documented rules and recommendations, each with its modality (MUST, SHOULD, MUST_NOT...) and ${words.rules}. ` +
100
+ "Filter by what it governs, by modality, or by text. Rules from parent classes are included for a class.",
101
+ inputSchema: {
102
+ about: z.string().optional().describe("Class or instance the rules should govern"),
103
+ modality: z.string().optional().describe("MUST, MUST_NOT, SHOULD or MAY"),
104
+ query: z.string().optional().describe(words.ruleQuery),
105
+ limit: z.number().int().min(1).max(100).optional().describe("Maximum rules (default 25)"),
106
+ },
107
+ }, async (args) => run(() => listRules(ont, args, evidence)));
108
+ if (withReadSource) {
109
+ server.registerTool("read_source", {
110
+ description: "Read the original text of a source document: one section by heading, or a range of lines. Use the document, heading and " +
111
+ "line numbers that other results cite. With neither heading nor lines it returns the document's outline. Long sections " +
112
+ "are cut off with a note saying which lines to ask for next.",
113
+ inputSchema: {
114
+ source: z.string().describe("Name of the source document, such as Button"),
115
+ heading: z.string().optional().describe("Heading to read, or a path such as \"Examples › Grow Prop\""),
116
+ lines: z.string().optional().describe("Line range such as \"40-72\", or one line"),
117
+ },
118
+ }, async (args) => run(() => readSource(ont, readSourceOptions.root, args)));
119
+ }
120
+ if (snapshot) {
121
+ if (!snapshot.id || !snapshot.version)
122
+ throw new OkbMcpError("A snapshot needs a non-empty id and version.");
123
+ const report = JSON.stringify({ id: snapshot.id, version: snapshot.version });
124
+ server.registerResource("snapshot", SNAPSHOT_URI, { title: "Snapshot", description: "The data snapshot this server serves, for an eval harness to verify.", mimeType: "application/json" }, (uri) => ({ contents: [{ uri: uri.href, mimeType: "application/json", text: report }] }));
125
+ }
126
+ return server;
127
+ }
@@ -0,0 +1,41 @@
1
+ import { Ontology, type GraphEdge, type OkbNode } from "@ontology-kit/reader";
2
+ /** What was left out of the served ontology because it isn't verified. */
3
+ export interface HeldBack {
4
+ rules: number;
5
+ /** Relationship links justified only by a held-back rule. */
6
+ links: number;
7
+ }
8
+ export interface ServingOptions {
9
+ /**
10
+ * Serve rules that haven't been verified against their quote. By default they're held back, as
11
+ * `okb export` does: a rule nobody has checked shouldn't reach an agent as if it were fact.
12
+ */
13
+ includeUnverified?: boolean;
14
+ }
15
+ /** The test `okb export` uses: only a rule whose verification is SUPPORTED counts (an approved correction is recorded as SUPPORTED too). */
16
+ export declare function isVerified(rule: OkbNode): boolean;
17
+ /**
18
+ * Removes every trace of the rules that aren't verified: the rule and its edges (GOVERNS, CITES,
19
+ * REFINES, FULFILLS), relationship links whose `rule` edge property points at it, and quotes that only
20
+ * held-back rules cite (otherwise a source listing would still show the text).
21
+ *
22
+ * A relationship is stored as one edge per link, an inverse pair included, so dropping the edge drops
23
+ * the link from both ends.
24
+ */
25
+ export declare function holdBack(nodes: readonly OkbNode[], edges: readonly GraphEdge[]): {
26
+ nodes: OkbNode[];
27
+ edges: GraphEdge[];
28
+ held: HeldBack;
29
+ };
30
+ /**
31
+ * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
32
+ * view of the folder without the rules that aren't verified (see `holdBack`), so the tools never need to
33
+ * filter and nothing can leak. `held` says how much was left out. `root` is the resolved folder, which
34
+ * `createServer` needs to read the documents that sources point to. Any okb format version the reader
35
+ * loads works, including folders still on `nodes.json` and `edges.json`.
36
+ */
37
+ export declare function loadForServing(folder: string, { includeUnverified }?: ServingOptions): {
38
+ ontology: Ontology;
39
+ held: HeldBack;
40
+ root: string;
41
+ };
@@ -0,0 +1,66 @@
1
+ // Loading a KB to serve it: the reader's `Ontology`, with everything that isn't verified held back.
2
+ import path from "node:path";
3
+ import { Ontology, edgeProps, OkbError } from "@ontology-kit/reader";
4
+ import { OkbMcpError } from "./errors.js";
5
+ /** The test `okb export` uses: only a rule whose verification is SUPPORTED counts (an approved correction is recorded as SUPPORTED too). */
6
+ export function isVerified(rule) {
7
+ return rule.type === "Rule" && rule.verification?.status === "SUPPORTED";
8
+ }
9
+ /**
10
+ * Removes every trace of the rules that aren't verified: the rule and its edges (GOVERNS, CITES,
11
+ * REFINES, FULFILLS), relationship links whose `rule` edge property points at it, and quotes that only
12
+ * held-back rules cite (otherwise a source listing would still show the text).
13
+ *
14
+ * A relationship is stored as one edge per link, an inverse pair included, so dropping the edge drops
15
+ * the link from both ends.
16
+ */
17
+ export function holdBack(nodes, edges) {
18
+ const hidden = new Set(nodes.filter((n) => n.type === "Rule" && !isVerified(n)).map((n) => n.id));
19
+ if (hidden.size === 0)
20
+ return { nodes: [...nodes], edges: [...edges], held: { rules: 0, links: 0 } };
21
+ const citers = new Map();
22
+ for (const e of edges)
23
+ if (e.type === "CITES")
24
+ (citers.get(e.to) ?? citers.set(e.to, []).get(e.to)).push(e.from);
25
+ const orphanQuotes = new Set(nodes
26
+ .filter((n) => n.type === "SourceLocation" && (citers.get(n.id) ?? []).length > 0 && citers.get(n.id).every((c) => hidden.has(c)))
27
+ .map((n) => n.id));
28
+ const gone = (id) => hidden.has(id) || orphanQuotes.has(id);
29
+ let links = 0;
30
+ const kept = edges.filter((e) => {
31
+ if (gone(e.from) || gone(e.to))
32
+ return false;
33
+ const rule = edgeProps(e).rule;
34
+ if (typeof rule === "string" && hidden.has(rule)) {
35
+ links++;
36
+ return false;
37
+ }
38
+ return true;
39
+ });
40
+ return { nodes: nodes.filter((n) => !gone(n.id)), edges: kept, held: { rules: hidden.size, links } };
41
+ }
42
+ /**
43
+ * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
44
+ * view of the folder without the rules that aren't verified (see `holdBack`), so the tools never need to
45
+ * filter and nothing can leak. `held` says how much was left out. `root` is the resolved folder, which
46
+ * `createServer` needs to read the documents that sources point to. Any okb format version the reader
47
+ * loads works, including folders still on `nodes.json` and `edges.json`.
48
+ */
49
+ export function loadForServing(folder, { includeUnverified = false } = {}) {
50
+ let full;
51
+ try {
52
+ full = Ontology.load(folder);
53
+ }
54
+ catch (err) {
55
+ if (err instanceof OkbError)
56
+ throw new OkbMcpError(err.message);
57
+ throw err;
58
+ }
59
+ const root = path.resolve(folder);
60
+ if (includeUnverified)
61
+ return { ontology: full, held: { rules: 0, links: 0 }, root };
62
+ const { nodes, edges, held } = holdBack(full.nodes, full.edges);
63
+ if (held.rules === 0)
64
+ return { ontology: full, held, root };
65
+ return { ontology: Ontology.fromData(nodes, edges, full.manifest), held, root };
66
+ }
@@ -0,0 +1,13 @@
1
+ import type { Ontology } from "@ontology-kit/reader";
2
+ export interface ReadSourceArgs {
3
+ /** Name or id of a source document, such as "Button" or "src.button". */
4
+ source: string;
5
+ /** A heading to read, or a path of headings ("Examples › Grow Prop"). Reads to the next heading of the same or a higher level. */
6
+ heading?: string | undefined;
7
+ /** A line range such as "40-72", or one line. 1-based, inclusive. */
8
+ lines?: string | undefined;
9
+ }
10
+ /** Most characters one call returns, so a huge example can't flood the agent's context. */
11
+ export declare const DEFAULT_MAX_CHARS = 12000;
12
+ /** `root` is the ontology folder: a source's `localPath` is relative to it. */
13
+ export declare function readSource(ont: Ontology, root: string, args: ReadSourceArgs, maxChars?: number): string;
package/dist/source.js ADDED
@@ -0,0 +1,125 @@
1
+ // read_source: the text of a cited source document, by heading or by line range.
2
+ // The ontology cites where things came from (document, heading, line); this lets an agent
3
+ // open that place without the ontology holding the text itself.
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { OkbMcpError } from "./errors.js";
7
+ import { bag, displayName, resolve } from "./graph.js";
8
+ /** Most characters one call returns, so a huge example can't flood the agent's context. */
9
+ export const DEFAULT_MAX_CHARS = 12_000;
10
+ const norm = (s) => s.replace(/[`*_]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
11
+ function headingsOf(lines) {
12
+ const out = [];
13
+ const stack = [];
14
+ let fence = null;
15
+ lines.forEach((raw, i) => {
16
+ const fenceMark = /^\s*(```+|~~~+)/.exec(raw)?.[1];
17
+ if (fenceMark) {
18
+ if (fence === null)
19
+ fence = fenceMark[0];
20
+ else if (fenceMark[0] === fence)
21
+ fence = null;
22
+ return;
23
+ }
24
+ if (fence !== null)
25
+ return;
26
+ const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(raw);
27
+ if (!m)
28
+ return;
29
+ const level = m[1].length;
30
+ while (stack.length && stack[stack.length - 1].level >= level)
31
+ stack.pop();
32
+ stack.push({ level, text: m[2] });
33
+ out.push({ level, text: m[2], path: stack.map((s) => s.text), line: i + 1 });
34
+ });
35
+ return out;
36
+ }
37
+ function parseLines(spec, total) {
38
+ const m = /^\s*(\d+)\s*(?:[-–—:]\s*(\d+))?\s*$/.exec(spec);
39
+ if (!m)
40
+ throw new OkbMcpError(`lines must look like "40-72" or "40", not "${spec}".`);
41
+ const start = Number(m[1]);
42
+ const end = m[2] ? Number(m[2]) : start;
43
+ if (start < 1 || end < start)
44
+ throw new OkbMcpError(`lines "${spec}" is not a valid range.`);
45
+ if (start > total)
46
+ throw new OkbMcpError(`The document has ${total} lines; ${start} is past the end.`);
47
+ return [start, Math.min(end, total)];
48
+ }
49
+ /** The KB's own files: its manifest, data, legacy data and the lock and save files. Compared case-insensitively, as a case-insensitive file system would resolve them. */
50
+ const OWN_FILES = new Set(["okb.json", "nodes.jsonl", "edges.jsonl", "nodes.json", "edges.json"]);
51
+ function isOwnFile(relative) {
52
+ const name = relative.toLowerCase();
53
+ return OWN_FILES.has(name) || (name.startsWith(".okb") && !name.includes(path.sep));
54
+ }
55
+ /** `root` is the ontology folder: a source's `localPath` is relative to it. */
56
+ export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
57
+ const src = resolve(ont, args.source, ["Source"]);
58
+ const title = displayName(src);
59
+ const localPath = typeof bag(src).localPath === "string" ? String(bag(src).localPath) : "";
60
+ if (!localPath)
61
+ throw new OkbMcpError(`${title} has no local file to read.`);
62
+ // A source's path is relative to the ontology folder and stays inside it, symbolic links included.
63
+ const unavailable = new OkbMcpError(`The file for ${title} isn't available (${localPath}).`);
64
+ const file = path.resolve(root, localPath);
65
+ if (!existsSync(file))
66
+ throw unavailable;
67
+ const realRoot = realpathSync(root);
68
+ const realFile = realpathSync(file);
69
+ const inside = path.relative(realRoot, realFile);
70
+ if (isOwnFile(inside) || isOwnFile(path.relative(realRoot, path.resolve(realRoot, localPath))))
71
+ throw unavailable;
72
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside))
73
+ throw unavailable;
74
+ const all = readFileSync(realFile, "utf8").split("\n");
75
+ const total = all.length;
76
+ const heads = headingsOf(all);
77
+ const outline = () => heads.map((h) => `${" ".repeat(Math.max(0, h.level - 1))}${h.text} (line ${h.line})`).join("\n");
78
+ let start;
79
+ let end;
80
+ if (args.lines) {
81
+ [start, end] = parseLines(args.lines, total);
82
+ }
83
+ else if (args.heading) {
84
+ const want = args.heading.split(/\s*[›>]\s*/).map(norm).filter(Boolean);
85
+ const hits = heads.filter((h) => {
86
+ const p = h.path.map(norm);
87
+ return want.every((w, i) => p[p.length - want.length + i] === w);
88
+ });
89
+ if (hits.length === 0) {
90
+ throw new OkbMcpError(`No heading "${args.heading}" in ${title}. Headings:\n${outline()}`);
91
+ }
92
+ if (hits.length > 1) {
93
+ const list = hits.map((h) => ` ${h.path.join(" › ")} (line ${h.line})`).join("\n");
94
+ throw new OkbMcpError(`"${args.heading}" matches ${hits.length} headings in ${title}; give a longer path or use lines:\n${list}`);
95
+ }
96
+ const h = hits[0];
97
+ const next = heads.find((x) => x.line > h.line && x.level <= h.level);
98
+ start = h.line;
99
+ end = next ? next.line - 1 : total;
100
+ }
101
+ else {
102
+ return `${title}: ${total} lines. Headings:\n${outline()}\n\nCall again with heading or lines to read part of it.`;
103
+ }
104
+ let body = all.slice(start - 1, end);
105
+ while (body.length && body[body.length - 1].trim() === "")
106
+ body.pop();
107
+ let shownEnd = start + body.length - 1;
108
+ let text = body.join("\n");
109
+ let note = "";
110
+ if (text.length > maxChars) {
111
+ let used = 0;
112
+ let keep = 0;
113
+ for (const line of body) {
114
+ if (used + line.length + 1 > maxChars && keep > 0)
115
+ break;
116
+ used += line.length + 1;
117
+ keep++;
118
+ }
119
+ body = body.slice(0, keep);
120
+ text = body.join("\n");
121
+ shownEnd = start + keep - 1;
122
+ note = `\n\n[Stopped at line ${shownEnd} of ${end}. Call again with lines="${shownEnd + 1}-${end}" to continue.]`;
123
+ }
124
+ return `${title}, lines ${start}-${shownEnd}${args.heading && !args.lines ? ` (${args.heading})` : ""}:\n\n${text}${note}`;
125
+ }
@@ -0,0 +1,55 @@
1
+ import { type Ontology } from "@ontology-kit/reader";
2
+ /**
3
+ * The tools, as plain functions from (ontology, arguments) to text. Output is written for a model
4
+ * reader: names rather than ids, one fact per line, and every rule followed by the evidence behind it.
5
+ *
6
+ * `find`, `get` and `traverse` read through the reader's query layer (`queryFind`, `queryGet`,
7
+ * `queryTraverse`, `querySlots`) and format what it returns. What stays here is the part the layer
8
+ * leaves out on purpose: forgiving name lookup, free-text search and ranking, the `allows` filter,
9
+ * evidence modes and the text itself.
10
+ *
11
+ * `Evidence` controls what the reader sees of the evidence behind a rule. The ontology always stores
12
+ * the quote and its location; this only decides what's shown:
13
+ * full the verbatim quote and where it came from
14
+ * locator where it came from (document, heading, line, link), without the text
15
+ * none neither
16
+ * In the quote-free modes quote text is also left out of search, so a query can't find a rule through
17
+ * a sentence the reader never sees.
18
+ */
19
+ export type Evidence = "full" | "locator" | "none";
20
+ export declare const EVIDENCE_MODES: readonly Evidence[];
21
+ export declare function describeOntology(ont: Ontology, evidence?: Evidence, maxLines?: number): string;
22
+ export interface FindArgs {
23
+ query?: string | undefined;
24
+ type?: "class" | "instance" | "slot" | "rule" | "source" | undefined;
25
+ class?: string | undefined;
26
+ where?: Record<string, string | number | boolean> | undefined;
27
+ allows?: Record<string, string | number | boolean> | undefined;
28
+ limit?: number | undefined;
29
+ }
30
+ /**
31
+ * `showPaths` says whether a source's `localPath` appears in results, and in what a search matches. It is on
32
+ * only when `read_source` is served; otherwise the agent has no use for a file path.
33
+ */
34
+ export declare function find(ont: Ontology, args: FindArgs, evidence?: Evidence, showPaths?: boolean): string;
35
+ export declare function get(ont: Ontology, ref: string, evidence?: Evidence, showPaths?: boolean): string;
36
+ export interface TraverseArgs {
37
+ from: string[];
38
+ relationship: string;
39
+ direction?: "out" | "in" | undefined;
40
+ depth?: number | undefined;
41
+ }
42
+ /**
43
+ * Follows one relationship. `direction` is relative to how the relationship is stored, so naming an
44
+ * inverse (`produces`) reads the stored edges backwards by default, and an explicit direction means
45
+ * what it says whichever name is used. The query layer reads a slot in its own direction, so the
46
+ * direction is translated before the call.
47
+ */
48
+ export declare function traverse(ont: Ontology, args: TraverseArgs): string;
49
+ export interface ListRulesArgs {
50
+ about?: string | undefined;
51
+ modality?: string | undefined;
52
+ query?: string | undefined;
53
+ limit?: number | undefined;
54
+ }
55
+ export declare function listRules(ont: Ontology, args: ListRulesArgs, evidence?: Evidence): string;