@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/source.js ADDED
@@ -0,0 +1,197 @@
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, statSync } 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
+ // The fence that is open: its character and length. Only a fence of the same character, at least as long and
15
+ // followed by nothing but spaces, closes it, so a three-backtick example inside a four-backtick block stays inside.
16
+ let fence = null;
17
+ lines.forEach((raw, i) => {
18
+ if (fence === null) {
19
+ const open = /^\s*(`{3,}|~{3,})/.exec(raw)?.[1];
20
+ if (open)
21
+ fence = { char: open[0], length: open.length };
22
+ if (open)
23
+ return;
24
+ }
25
+ else {
26
+ const close = /^\s*(`{3,}|~{3,})\s*$/.exec(raw)?.[1];
27
+ if (close && close[0] === fence.char && close.length >= fence.length)
28
+ fence = null;
29
+ return;
30
+ }
31
+ const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(raw);
32
+ if (!m)
33
+ return;
34
+ const level = m[1].length;
35
+ while (stack.length && stack[stack.length - 1].level >= level)
36
+ stack.pop();
37
+ stack.push({ level, text: m[2] });
38
+ out.push({ level, text: m[2], path: stack.map((s) => s.text), line: i + 1 });
39
+ });
40
+ return out;
41
+ }
42
+ function parseLines(spec, total) {
43
+ const m = /^\s*(\d+)\s*(?:[-–—:]\s*(\d+))?\s*$/.exec(spec);
44
+ if (!m)
45
+ throw new OkbMcpError(`lines must look like "40-72" or "40", not "${spec}".`);
46
+ const start = Number(m[1]);
47
+ const end = m[2] ? Number(m[2]) : start;
48
+ if (start < 1 || end < start)
49
+ throw new OkbMcpError(`lines "${spec}" is not a valid range.`);
50
+ if (start > total)
51
+ throw new OkbMcpError(`The document has ${total} lines; ${start} is past the end.`);
52
+ return [start, Math.min(end, total)];
53
+ }
54
+ /** The KB's data files. Compared case-insensitively, as a case-insensitive file system would resolve them. */
55
+ const OWN_FILES = ["okb.json", "nodes.jsonl", "edges.jsonl", "nodes.json", "edges.json"];
56
+ /**
57
+ * Whether a path inside the folder is not one of the KB's documents: a name starting with `.` in any segment (`.env`, `.okb.lock`, `.git/`),
58
+ * a name ending in `.tmp` (the save leftovers `nodes.jsonl.tmp`, `edges.jsonl.tmp` and `okb.json.tmp` hold the whole KB, unverified rules included),
59
+ * or one of the data files by name. A hard link to a data file has another name, so `isDataFile` compares identity instead.
60
+ */
61
+ function isOwnFile(relative) {
62
+ const parts = relative.split(/[\\/]+/).map((p) => p.toLowerCase());
63
+ const name = parts[parts.length - 1] ?? "";
64
+ return parts.some((p) => p.startsWith(".")) || name.endsWith(".tmp") || (parts.length === 1 && OWN_FILES.includes(name));
65
+ }
66
+ /** Whether `file` is the same file (device and inode) as one of the KB's data files in `realRoot`, under whatever name. */
67
+ function isDataFile(realRoot, file) {
68
+ const here = statSync(file, { bigint: true });
69
+ return OWN_FILES.some((name) => {
70
+ try {
71
+ const own = statSync(path.join(realRoot, name), { bigint: true });
72
+ return own.dev === here.dev && own.ino === here.ino;
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ });
78
+ }
79
+ /** `root` is the ontology folder: a source's `localPath` is relative to it. */
80
+ /** The most headings an "ambiguous heading" error lists, so a document with many repeats can't flood the reply. */
81
+ const MAX_LISTED_HEADINGS = 20;
82
+ export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
83
+ const src = resolve(ont, args.source, ["Source"]);
84
+ const title = displayName(src);
85
+ const localPath = typeof bag(src).localPath === "string" ? String(bag(src).localPath) : "";
86
+ if (!localPath)
87
+ throw new OkbMcpError(`${title} has no local file to read.`);
88
+ // A source's path is relative to the ontology folder and stays inside it, symbolic links included.
89
+ const unavailable = new OkbMcpError(`The file for ${title} isn't available (${localPath}).`);
90
+ const file = path.resolve(root, localPath);
91
+ if (!existsSync(file))
92
+ throw unavailable;
93
+ const realRoot = realpathSync(root);
94
+ const realFile = realpathSync(file);
95
+ const inside = path.relative(realRoot, realFile);
96
+ if (isOwnFile(inside) || isOwnFile(path.relative(realRoot, path.resolve(realRoot, localPath))))
97
+ throw unavailable;
98
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside))
99
+ throw unavailable;
100
+ if (isDataFile(realRoot, realFile))
101
+ throw unavailable;
102
+ let all;
103
+ try {
104
+ if (!statSync(realFile).isFile())
105
+ throw unavailable;
106
+ all = readFileSync(realFile, "utf8").split("\n");
107
+ }
108
+ catch (err) {
109
+ if (err instanceof OkbMcpError)
110
+ throw err;
111
+ throw unavailable; // a system error would carry the absolute path
112
+ }
113
+ const total = all.length;
114
+ const heads = headingsOf(all);
115
+ // An outline stays within the same character budget as a passage, so a document with thousands of headings can't flood the reply.
116
+ const outline = () => {
117
+ const rows = heads.map((h) => `${" ".repeat(Math.max(0, h.level - 1))}${h.text} (line ${h.line})`);
118
+ let used = 0;
119
+ let keep = 0;
120
+ for (const row of rows) {
121
+ if (used + row.length + 1 > maxChars && keep > 0)
122
+ break;
123
+ used += row.length + 1;
124
+ keep++;
125
+ }
126
+ const cut = rows.slice(0, keep).map((r) => (r.length > maxChars ? `${r.slice(0, maxChars)}…` : r));
127
+ return [...cut, ...(keep < rows.length ? [`… ${rows.length - keep} more headings; read by lines to see the rest.`] : [])].join("\n");
128
+ };
129
+ let start;
130
+ let end;
131
+ if (args.lines) {
132
+ [start, end] = parseLines(args.lines, total);
133
+ }
134
+ else if (args.heading) {
135
+ const want = args.heading.split(/\s*[›>]\s*/).map(norm).filter(Boolean);
136
+ const hits = heads.filter((h) => {
137
+ const p = h.path.map(norm);
138
+ return want.every((w, i) => p[p.length - want.length + i] === w);
139
+ });
140
+ if (hits.length === 0) {
141
+ throw new OkbMcpError(`No heading "${args.heading}" in ${title}. Headings:\n${outline()}`);
142
+ }
143
+ if (hits.length > 1) {
144
+ // At most MAX_LISTED_HEADINGS entries and maxChars characters in all, each entry clipped, so long headings can't flood the reply either.
145
+ const rows = hits.slice(0, MAX_LISTED_HEADINGS).map((h) => {
146
+ const row = ` ${h.path.join(" › ")} (line ${h.line})`;
147
+ return row.length > 300 ? `${row.slice(0, 300)}… (line ${h.line})` : row;
148
+ });
149
+ let used = 0;
150
+ let keep = 0;
151
+ for (const row of rows) {
152
+ if (used + row.length + 1 > maxChars && keep > 0)
153
+ break;
154
+ used += row.length + 1;
155
+ keep++;
156
+ }
157
+ const list = [...rows.slice(0, keep), ...(hits.length > keep ? [` … ${hits.length - keep} more`] : [])].join("\n");
158
+ throw new OkbMcpError(`"${args.heading}" matches ${hits.length} headings in ${title}; give a longer path or use lines:\n${list}`);
159
+ }
160
+ const h = hits[0];
161
+ const next = heads.find((x) => x.line > h.line && x.level <= h.level);
162
+ start = h.line;
163
+ end = next ? next.line - 1 : total;
164
+ }
165
+ else {
166
+ return `${title}: ${total} lines. Headings:\n${outline()}\n\nCall again with heading or lines to read part of it.`;
167
+ }
168
+ let body = all.slice(start - 1, end);
169
+ while (body.length && body[body.length - 1].trim() === "")
170
+ body.pop();
171
+ let shownEnd = start + body.length - 1;
172
+ let text = body.join("\n");
173
+ let note = "";
174
+ if (body.length > 0 && body[0].length > maxChars) {
175
+ // The first line alone is over the budget: show a fragment of it, and continue after it (the rest of the line can't be reached).
176
+ const first = start;
177
+ body = [body[0].slice(0, maxChars)];
178
+ text = body[0];
179
+ shownEnd = first;
180
+ note = `\n\n[Line ${first} has ${all[first - 1].length} characters; showed the first ${maxChars}.${end > first ? ` Call again with lines="${first + 1}-${end}" to continue after it.` : ""}]`;
181
+ }
182
+ else if (text.length > maxChars) {
183
+ let used = 0;
184
+ let keep = 0;
185
+ for (const line of body) {
186
+ if (used + line.length + 1 > maxChars && keep > 0)
187
+ break;
188
+ used += line.length + 1;
189
+ keep++;
190
+ }
191
+ body = body.slice(0, keep);
192
+ text = body.join("\n");
193
+ shownEnd = start + keep - 1;
194
+ note = `\n\n[Stopped at line ${shownEnd} of ${end}. Call again with lines="${shownEnd + 1}-${end}" to continue.]`;
195
+ }
196
+ return `${title}, lines ${start}-${shownEnd}${args.heading && !args.lines ? ` (${args.heading})` : ""}:\n\n${text}${note}`;
197
+ }
@@ -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;