@ontology-kit/mcp 0.3.0-bootstrap.0 → 0.3.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/README.md +58 -3
- package/dist/check-cli.d.ts +2 -0
- package/dist/check-cli.js +63 -0
- package/dist/check.d.ts +38 -0
- package/dist/check.js +295 -0
- package/dist/cli.js +50 -3
- package/dist/graph.d.ts +13 -0
- package/dist/graph.js +49 -0
- package/dist/server.d.ts +10 -1
- package/dist/server.js +4 -1
- package/dist/serving.d.ts +1 -1
- package/dist/serving.js +4 -3
- package/dist/skills-cli.d.ts +65 -0
- package/dist/skills-cli.js +395 -0
- package/dist/skills.d.ts +49 -0
- package/dist/skills.js +210 -0
- package/dist/source.d.ts +0 -1
- package/dist/source.js +88 -16
- package/dist/tools.js +27 -8
- package/package.json +4 -2
- package/skills/query-kb/SKILL.md +48 -0
package/dist/skills.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Serves skills through the MCP skills extension (SEP-2640, `io.modelcontextprotocol/skills`): the bundled `query-kb`
|
|
2
|
+
// skill and any skill folders in the KB's own `skills/` folder. Used by server.ts.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
8
|
+
import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
9
|
+
import { parse as parseYaml } from "yaml";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { OkbMcpError } from "./errors.js";
|
|
12
|
+
/** The capability name a host looks for. */
|
|
13
|
+
export const SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
|
|
14
|
+
/** The folder in a KB folder that holds the KB's own skills, one folder per skill. */
|
|
15
|
+
export const KB_SKILLS_FOLDER = "skills";
|
|
16
|
+
/** Limits. The file count and total size are the extension's own; the rest are ours. */
|
|
17
|
+
export const SKILL_LIMITS = {
|
|
18
|
+
/** Files in one skill, `SKILL.md` included. */
|
|
19
|
+
files: 512,
|
|
20
|
+
/** Total bytes of one skill's files (16 MiB). */
|
|
21
|
+
bytes: 16 * 1024 * 1024,
|
|
22
|
+
/** Bytes in `SKILL.md`, because a host puts the whole file in the agent's context. */
|
|
23
|
+
skillMd: 100_000,
|
|
24
|
+
nameLength: 64,
|
|
25
|
+
descriptionLength: 1024,
|
|
26
|
+
};
|
|
27
|
+
/** How long a host may reuse a listing. Digests only change when the server restarts on changed files. */
|
|
28
|
+
const TTL_MS = 300_000;
|
|
29
|
+
/** The folder of the skills this package bundles. Both `src/` and `dist/` sit one level below the package root. */
|
|
30
|
+
const BUNDLED = new URL("../skills", import.meta.url);
|
|
31
|
+
/** The same folder as a path. */
|
|
32
|
+
export const BUNDLED_SKILLS_DIR = fileURLToPath(BUNDLED);
|
|
33
|
+
/** Every file under a folder, as paths relative to it with `/` separators, sorted by code point so the order never varies. */
|
|
34
|
+
function walk(dir, rel = "") {
|
|
35
|
+
const out = [];
|
|
36
|
+
for (const entry of readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
|
37
|
+
if (entry.name.startsWith("."))
|
|
38
|
+
continue; // .DS_Store, editor files
|
|
39
|
+
const r = rel ? `${rel}/${entry.name}` : entry.name;
|
|
40
|
+
if (entry.isSymbolicLink())
|
|
41
|
+
throw new OkbMcpError(`Skill file ${path.join(dir, r)} is a symbolic link. Skills can't contain links; copy the file in.`);
|
|
42
|
+
if (entry.isDirectory())
|
|
43
|
+
out.push(...walk(dir, r));
|
|
44
|
+
else
|
|
45
|
+
out.push(r);
|
|
46
|
+
}
|
|
47
|
+
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
48
|
+
}
|
|
49
|
+
function parseFrontmatter(text, where) {
|
|
50
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
|
|
51
|
+
if (!m)
|
|
52
|
+
throw new OkbMcpError(`${where} must start with a frontmatter block (--- lines) holding \`name\` and \`description\`.`);
|
|
53
|
+
let data;
|
|
54
|
+
try {
|
|
55
|
+
data = parseYaml(m[1]);
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
throw new OkbMcpError(`The frontmatter of ${where} isn't valid YAML: ${err.message.split("\n")[0]}`);
|
|
59
|
+
}
|
|
60
|
+
if (data === null || typeof data !== "object" || Array.isArray(data))
|
|
61
|
+
throw new OkbMcpError(`The frontmatter of ${where} must be a list of \`key: value\` lines.`);
|
|
62
|
+
return JSON.parse(JSON.stringify(data));
|
|
63
|
+
}
|
|
64
|
+
/** Reads and checks one skill folder. Throws `OkbMcpError` naming the folder and what's wrong. */
|
|
65
|
+
export function loadSkill(dir) {
|
|
66
|
+
const folder = path.basename(dir);
|
|
67
|
+
const skillMd = path.join(dir, "SKILL.md");
|
|
68
|
+
if (!existsSync(skillMd))
|
|
69
|
+
throw new OkbMcpError(`Skill folder ${dir} has no SKILL.md.`);
|
|
70
|
+
if (!statSync(skillMd).isFile())
|
|
71
|
+
throw new OkbMcpError(`${skillMd} isn't a file. A skill folder needs a SKILL.md file.`);
|
|
72
|
+
const rels = walk(dir);
|
|
73
|
+
if (rels.length > SKILL_LIMITS.files)
|
|
74
|
+
throw new OkbMcpError(`Skill ${folder} has ${rels.length} files; the limit is ${SKILL_LIMITS.files}.`);
|
|
75
|
+
const files = rels.map((rel) => {
|
|
76
|
+
const bytes = readFileSync(path.join(dir, rel));
|
|
77
|
+
return { rel, bytes };
|
|
78
|
+
});
|
|
79
|
+
const total = files.reduce((n, f) => n + f.bytes.length, 0);
|
|
80
|
+
if (total > SKILL_LIMITS.bytes)
|
|
81
|
+
throw new OkbMcpError(`Skill ${folder} is ${total} bytes; the limit is ${SKILL_LIMITS.bytes}.`);
|
|
82
|
+
const main = files.find((f) => f.rel === "SKILL.md");
|
|
83
|
+
if (main.bytes.length > SKILL_LIMITS.skillMd) {
|
|
84
|
+
throw new OkbMcpError(`${skillMd} is ${main.bytes.length} bytes; the limit is ${SKILL_LIMITS.skillMd}. Move detail into other files in the folder.`);
|
|
85
|
+
}
|
|
86
|
+
const frontmatter = parseFrontmatter(main.bytes.toString("utf8"), skillMd);
|
|
87
|
+
const { name, description } = frontmatter;
|
|
88
|
+
if (typeof name !== "string" || typeof description !== "string" || !name || !description.trim()) {
|
|
89
|
+
throw new OkbMcpError(`The frontmatter of ${skillMd} needs a \`name\` and a \`description\`, both text.`);
|
|
90
|
+
}
|
|
91
|
+
if (name !== folder)
|
|
92
|
+
throw new OkbMcpError(`The frontmatter \`name\` of ${skillMd} is "${name}", but its folder is "${folder}". They must match.`);
|
|
93
|
+
if (name.length > SKILL_LIMITS.nameLength || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) {
|
|
94
|
+
throw new OkbMcpError(`Skill name "${name}" must be lowercase letters, digits and single hyphens, at most ${SKILL_LIMITS.nameLength} characters.`);
|
|
95
|
+
}
|
|
96
|
+
if (description.length > SKILL_LIMITS.descriptionLength) {
|
|
97
|
+
throw new OkbMcpError(`The \`description\` of ${skillMd} is ${description.length} characters; the limit is ${SKILL_LIMITS.descriptionLength}.`);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
name,
|
|
101
|
+
uri: `skill://${name}/SKILL.md`,
|
|
102
|
+
frontmatter,
|
|
103
|
+
files: files.map(({ rel, bytes }) => ({
|
|
104
|
+
uri: `skill://${name}/${rel.split("/").map(encodeURIComponent).join("/")}`,
|
|
105
|
+
bytes,
|
|
106
|
+
digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
|
|
107
|
+
size: bytes.length,
|
|
108
|
+
})),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** The KB's `skills/` folder as a link: it could lead anywhere, so it is refused as a skill link inside it is. */
|
|
112
|
+
export function isLinkedSkillsRoot(skillsDir) {
|
|
113
|
+
try {
|
|
114
|
+
return lstatSync(skillsDir).isSymbolicLink();
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function loadFolder(skillsDir) {
|
|
121
|
+
if (isLinkedSkillsRoot(skillsDir))
|
|
122
|
+
throw new OkbMcpError(`${skillsDir} is a symbolic link. The ${KB_SKILLS_FOLDER}/ folder has to be a real folder inside the KB, with the skill folders in it.`);
|
|
123
|
+
if (!existsSync(skillsDir))
|
|
124
|
+
return [];
|
|
125
|
+
const names = readdirSync(skillsDir, { withFileTypes: true })
|
|
126
|
+
.filter((e) => !e.name.startsWith("."))
|
|
127
|
+
.map((e) => {
|
|
128
|
+
if (!e.isDirectory() || lstatSync(path.join(skillsDir, e.name)).isSymbolicLink()) {
|
|
129
|
+
throw new OkbMcpError(`${path.join(skillsDir, e.name)} isn't a skill folder. ${KB_SKILLS_FOLDER}/ holds only folders, one per skill.`);
|
|
130
|
+
}
|
|
131
|
+
return e.name;
|
|
132
|
+
})
|
|
133
|
+
.sort();
|
|
134
|
+
return names.map((n) => loadSkill(path.join(skillsDir, n)));
|
|
135
|
+
}
|
|
136
|
+
/** The skill sets the CLI offers, as `--skills` values. */
|
|
137
|
+
export const SKILL_SETS = ["none", "bundled", "all"];
|
|
138
|
+
/** The names of the skill folders in `<kbRoot>/skills/`, sorted, without reading or checking them. */
|
|
139
|
+
export function kbSkillNames(kbRoot) {
|
|
140
|
+
const dir = path.join(kbRoot, KB_SKILLS_FOLDER);
|
|
141
|
+
if (!existsSync(dir) || isLinkedSkillsRoot(dir))
|
|
142
|
+
return [];
|
|
143
|
+
return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort();
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The skills to serve: the ones this package bundles, plus, for `{ kb }`, those in `<kb>/skills/`. Only the sets
|
|
147
|
+
* asked for are read, so a broken KB skill can't stop a server that doesn't serve them. Throws `OkbMcpError` if
|
|
148
|
+
* a skill that is read is invalid or two share a name.
|
|
149
|
+
*/
|
|
150
|
+
export function loadSkills(set = "bundled") {
|
|
151
|
+
const bundled = loadFolder(BUNDLED_SKILLS_DIR);
|
|
152
|
+
const own = typeof set === "object" ? loadFolder(path.join(set.kb, KB_SKILLS_FOLDER)) : [];
|
|
153
|
+
const seen = new Set(bundled.map((s) => s.name));
|
|
154
|
+
for (const s of own) {
|
|
155
|
+
if (seen.has(s.name))
|
|
156
|
+
throw new OkbMcpError(`The KB's skill "${s.name}" has the name of a skill the server bundles. Rename its folder and \`name\`.`);
|
|
157
|
+
seen.add(s.name);
|
|
158
|
+
}
|
|
159
|
+
return [...bundled, ...own].sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
160
|
+
}
|
|
161
|
+
function mimeType(file, bytes) {
|
|
162
|
+
const ext = path.extname(file).toLowerCase();
|
|
163
|
+
const known = { ".md": "text/markdown", ".json": "application/json", ".yaml": "application/yaml", ".yml": "application/yaml", ".txt": "text/plain" };
|
|
164
|
+
if (known[ext])
|
|
165
|
+
return known[ext];
|
|
166
|
+
return isText(bytes) ? "text/plain" : "application/octet-stream";
|
|
167
|
+
}
|
|
168
|
+
function isText(bytes) {
|
|
169
|
+
try {
|
|
170
|
+
new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const entry = (s) => ({
|
|
178
|
+
uri: s.uri,
|
|
179
|
+
frontmatter: s.frontmatter,
|
|
180
|
+
resources: s.files.map(({ uri, digest, size }) => ({ uri, digest, size })),
|
|
181
|
+
});
|
|
182
|
+
/** Declares the extension on a server, answers `skills/list` and `skills/get`, and serves each file with `resources/read`. */
|
|
183
|
+
export function serveSkills(server, skills) {
|
|
184
|
+
server.server.registerCapabilities({ extensions: { [SKILLS_EXTENSION]: {} } });
|
|
185
|
+
const list = z.object({ method: z.literal("skills/list"), params: z.looseObject({}).optional() });
|
|
186
|
+
const get = z.object({ method: z.literal("skills/get"), params: z.looseObject({ uri: z.string().optional() }).optional() });
|
|
187
|
+
server.server.setRequestHandler(list, () => ({ resultType: "complete", skills: skills.map(entry), ttlMs: TTL_MS, cacheScope: "public" }));
|
|
188
|
+
server.server.setRequestHandler(get, (request) => {
|
|
189
|
+
const uri = request.params?.uri;
|
|
190
|
+
const skill = skills.find((s) => s.uri === uri);
|
|
191
|
+
if (!skill)
|
|
192
|
+
throw new McpError(ErrorCode.InvalidParams, `No skill has the SKILL.md URI ${String(uri)}.`);
|
|
193
|
+
return { resultType: "complete", skill: entry(skill), ttlMs: TTL_MS, cacheScope: "public" };
|
|
194
|
+
});
|
|
195
|
+
// One template for every file, with no list callback, so the files are read by URI but don't crowd `resources/list`.
|
|
196
|
+
const files = new Map(skills.flatMap((s) => s.files.map((f) => [f.uri, f])));
|
|
197
|
+
server.registerResource("skill-files", new ResourceTemplate("skill://{+path}", { list: undefined }), { description: "Files of the skills this server serves." }, (uri) => {
|
|
198
|
+
const file = files.get(uri.href);
|
|
199
|
+
if (!file)
|
|
200
|
+
throw new McpError(ErrorCode.InvalidParams, `No skill file at ${uri.href}.`);
|
|
201
|
+
const mime = mimeType(file.uri, file.bytes);
|
|
202
|
+
return {
|
|
203
|
+
contents: [
|
|
204
|
+
isText(file.bytes)
|
|
205
|
+
? { uri: uri.href, mimeType: mime, text: file.bytes.toString("utf8") }
|
|
206
|
+
: { uri: uri.href, mimeType: mime, blob: file.bytes.toString("base64") },
|
|
207
|
+
],
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
}
|
package/dist/source.d.ts
CHANGED
|
@@ -9,5 +9,4 @@ export interface ReadSourceArgs {
|
|
|
9
9
|
}
|
|
10
10
|
/** Most characters one call returns, so a huge example can't flood the agent's context. */
|
|
11
11
|
export declare const DEFAULT_MAX_CHARS = 12000;
|
|
12
|
-
/** `root` is the ontology folder: a source's `localPath` is relative to it. */
|
|
13
12
|
export declare function readSource(ont: Ontology, root: string, args: ReadSourceArgs, maxChars?: number): string;
|
package/dist/source.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// read_source: the text of a cited source document, by heading or by line range.
|
|
2
2
|
// The ontology cites where things came from (document, heading, line); this lets an agent
|
|
3
3
|
// open that place without the ontology holding the text itself.
|
|
4
|
-
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { OkbMcpError } from "./errors.js";
|
|
7
7
|
import { bag, displayName, resolve } from "./graph.js";
|
|
@@ -11,18 +11,23 @@ const norm = (s) => s.replace(/[`*_]/g, "").replace(/\s+/g, " ").trim().toLowerC
|
|
|
11
11
|
function headingsOf(lines) {
|
|
12
12
|
const out = [];
|
|
13
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.
|
|
14
16
|
let fence = null;
|
|
15
17
|
lines.forEach((raw, i) => {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
if (
|
|
19
|
-
fence =
|
|
20
|
-
|
|
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)
|
|
21
28
|
fence = null;
|
|
22
29
|
return;
|
|
23
30
|
}
|
|
24
|
-
if (fence !== null)
|
|
25
|
-
return;
|
|
26
31
|
const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(raw);
|
|
27
32
|
if (!m)
|
|
28
33
|
return;
|
|
@@ -46,13 +51,34 @@ function parseLines(spec, total) {
|
|
|
46
51
|
throw new OkbMcpError(`The document has ${total} lines; ${start} is past the end.`);
|
|
47
52
|
return [start, Math.min(end, total)];
|
|
48
53
|
}
|
|
49
|
-
/** The KB's
|
|
50
|
-
const OWN_FILES =
|
|
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
|
+
*/
|
|
51
61
|
function isOwnFile(relative) {
|
|
52
|
-
const
|
|
53
|
-
|
|
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
|
+
});
|
|
54
78
|
}
|
|
55
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;
|
|
56
82
|
export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
|
|
57
83
|
const src = resolve(ont, args.source, ["Source"]);
|
|
58
84
|
const title = displayName(src);
|
|
@@ -71,10 +97,35 @@ export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
|
|
|
71
97
|
throw unavailable;
|
|
72
98
|
if (inside === "" || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside))
|
|
73
99
|
throw unavailable;
|
|
74
|
-
|
|
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
|
+
}
|
|
75
113
|
const total = all.length;
|
|
76
114
|
const heads = headingsOf(all);
|
|
77
|
-
|
|
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
|
+
};
|
|
78
129
|
let start;
|
|
79
130
|
let end;
|
|
80
131
|
if (args.lines) {
|
|
@@ -90,7 +141,20 @@ export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
|
|
|
90
141
|
throw new OkbMcpError(`No heading "${args.heading}" in ${title}. Headings:\n${outline()}`);
|
|
91
142
|
}
|
|
92
143
|
if (hits.length > 1) {
|
|
93
|
-
|
|
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");
|
|
94
158
|
throw new OkbMcpError(`"${args.heading}" matches ${hits.length} headings in ${title}; give a longer path or use lines:\n${list}`);
|
|
95
159
|
}
|
|
96
160
|
const h = hits[0];
|
|
@@ -107,7 +171,15 @@ export function readSource(ont, root, args, maxChars = DEFAULT_MAX_CHARS) {
|
|
|
107
171
|
let shownEnd = start + body.length - 1;
|
|
108
172
|
let text = body.join("\n");
|
|
109
173
|
let note = "";
|
|
110
|
-
if (
|
|
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) {
|
|
111
183
|
let used = 0;
|
|
112
184
|
let keep = 0;
|
|
113
185
|
for (const line of body) {
|
package/dist/tools.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { queryFind, queryTraverse, } from "@ontology-kit/reader";
|
|
2
2
|
import { OkbMcpError } from "./errors.js";
|
|
3
|
-
import {
|
|
3
|
+
import { isVerified } from "./serving.js";
|
|
4
|
+
import { ancestors, asStrings, bag, byName, children, citationsFor, classesOf, descendants, describeRule, displayName, instancesOf, parents, propertyValues, relationshipSlots, showValues, relationshipsOf, relNames, resolve, resolveRelationship, rulesGoverning, slotsOf, squash, } from "./graph.js";
|
|
4
5
|
export const EVIDENCE_MODES = ["full", "locator", "none"];
|
|
5
6
|
const DEFAULT_LIMIT = 25;
|
|
6
7
|
const STOPWORDS = new Set([
|
|
@@ -149,10 +150,14 @@ export function describeOntology(ont, evidence = "full", maxLines = 150) {
|
|
|
149
150
|
const byModality = new Map();
|
|
150
151
|
for (const r of rules)
|
|
151
152
|
byModality.set(String(r.modality), (byModality.get(String(r.modality)) ?? 0) + 1);
|
|
153
|
+
// What the rules served are, not what a default would make them: with --include-unverified some haven't been verified.
|
|
154
|
+
const verified = rules.filter(isVerified).length;
|
|
152
155
|
const provenance = {
|
|
153
156
|
full: "Each cites a verbatim quote from a source document.",
|
|
154
157
|
locator: "Each cites its location in a source document.",
|
|
155
|
-
none:
|
|
158
|
+
none: verified === rules.length
|
|
159
|
+
? "Each was verified against its source document."
|
|
160
|
+
: `${verified} of ${rules.length} rules were verified against their source document; the other ${rules.length - verified} haven't been.`,
|
|
156
161
|
}[evidence];
|
|
157
162
|
if (byModality.size)
|
|
158
163
|
out.push(`Rules: ${[...byModality].map(([m, n]) => `${m} ${n}`).join(", ")}. ${provenance}`);
|
|
@@ -185,8 +190,22 @@ function hasValue(ont, node, slot, wanted) {
|
|
|
185
190
|
const have = queryTraverse(ont, { from: node.id, slot: slot.id });
|
|
186
191
|
if (wanted === "*")
|
|
187
192
|
return have.length > 0;
|
|
188
|
-
|
|
189
|
-
|
|
193
|
+
return have.some((h) => sameValue(slot, bag(slot).valueType === "Instance" ? h.name : h.value, wanted));
|
|
194
|
+
}
|
|
195
|
+
const NUMERIC_TYPES = new Set(["Integer", "Float", "Number"]);
|
|
196
|
+
/** Equal values: numbers by value for a numeric slot (so -1 isn't 1 and 1.5 isn't 15), anything else ignoring case and punctuation. */
|
|
197
|
+
function sameValue(slot, have, wanted) {
|
|
198
|
+
if (NUMERIC_TYPES.has(String(bag(slot).valueType)) && String(have).trim() !== "" && String(wanted).trim() !== "") {
|
|
199
|
+
const a = Number(have);
|
|
200
|
+
const b = Number(wanted);
|
|
201
|
+
if (Number.isFinite(a) && Number.isFinite(b))
|
|
202
|
+
return a === b;
|
|
203
|
+
}
|
|
204
|
+
return squash(String(have)) === squash(String(wanted));
|
|
205
|
+
}
|
|
206
|
+
/** The values a slot allows on this class: the slot's own, narrowed by the class's and its ancestors' `facetOverrides`. */
|
|
207
|
+
function allowedFor(ont, classNode, slotId) {
|
|
208
|
+
return (ont.effectiveFacets(slotId, [classNode.id, ...ont.ancestors(classNode.id)]).allowedValues ?? []).map(String);
|
|
190
209
|
}
|
|
191
210
|
/** Does the class permit `key` = `wanted`: one of the slot's allowed values, or (with "*") simply have the slot? Only classes have slots. */
|
|
192
211
|
function permits(ont, node, slot, wanted) {
|
|
@@ -196,7 +215,7 @@ function permits(ont, node, slot, wanted) {
|
|
|
196
215
|
return false;
|
|
197
216
|
if (wanted === "*")
|
|
198
217
|
return true;
|
|
199
|
-
return
|
|
218
|
+
return allowedFor(ont, node, slot.id).some((v) => sameValue(slot, v, wanted));
|
|
200
219
|
}
|
|
201
220
|
/**
|
|
202
221
|
* `showPaths` says whether a source's `localPath` appears in results, and in what a search matches. It is on
|
|
@@ -340,11 +359,11 @@ function getClass(ont, c, evidence) {
|
|
|
340
359
|
out.push("", "Properties:");
|
|
341
360
|
for (const { slot, from } of own) {
|
|
342
361
|
const s = bag(slot);
|
|
343
|
-
const values =
|
|
362
|
+
const values = allowedFor(ont, c, slot.id);
|
|
344
363
|
const fixed = props.find((p) => p.slot.id === slot.id);
|
|
345
364
|
out.push(` ${s.name}${values.length ? `: ${values.join(" | ")}` : s.valueType ? ` (${s.valueType})` : ""}` +
|
|
346
365
|
`${s.default !== undefined ? `, default ${show(s.default)}` : ""}` +
|
|
347
|
-
`${fixed ? `, always ${
|
|
366
|
+
`${fixed ? `, always ${showValues(fixed.value)}` : ""}` +
|
|
348
367
|
`${from.id !== c.id ? ` (inherited from ${displayName(from)})` : ""}` +
|
|
349
368
|
`${s.description ? ` — ${clip(String(s.description), 90)}` : ""}`);
|
|
350
369
|
}
|
|
@@ -389,7 +408,7 @@ function getInstance(ont, n, evidence) {
|
|
|
389
408
|
if (props.length) {
|
|
390
409
|
out.push("", "Properties:");
|
|
391
410
|
for (const p of props)
|
|
392
|
-
out.push(` ${bag(p.slot).name}: ${
|
|
411
|
+
out.push(` ${bag(p.slot).name}: ${showValues(p.value)}${p.inheritedFrom ? ` (from ${displayName(p.inheritedFrom)})` : ""}`);
|
|
393
412
|
}
|
|
394
413
|
const rels = relationshipsOf(ont, n);
|
|
395
414
|
if (rels.length) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ontology-kit/mcp",
|
|
3
|
-
"version": "0.3.0
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"license": "MIT",
|
|
5
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
6
|
"homepage": "https://ontology-kit.dev",
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"files": [
|
|
38
38
|
"bin",
|
|
39
39
|
"dist",
|
|
40
|
+
"skills",
|
|
40
41
|
"README.md",
|
|
41
42
|
"LICENSE"
|
|
42
43
|
],
|
|
@@ -45,7 +46,8 @@
|
|
|
45
46
|
},
|
|
46
47
|
"dependencies": {
|
|
47
48
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
48
|
-
"@ontology-kit/reader": "0.
|
|
49
|
+
"@ontology-kit/reader": "0.3.0",
|
|
50
|
+
"yaml": "^2.8.0",
|
|
49
51
|
"zod": "^4.6.5"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: query-kb
|
|
3
|
+
description: Answer questions from an okb knowledge base that an okb-mcp server serves, using its describe_ontology, find, get, traverse and list_rules tools, and quote the rule and source behind each answer. Use it whenever the okb-mcp tools are connected and someone asks what a KB says, which things match, how things relate, or what must hold. Not for building or changing a KB.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Query a KB
|
|
7
|
+
|
|
8
|
+
**Version 0.3.0.** It matches the `@ontology-kit/mcp` version it ships with.
|
|
9
|
+
|
|
10
|
+
Answer questions from a knowledge base served by `okb-mcp`. The KB is the only source. Say what it says, show where it says it, and say plainly when it says nothing. The server only reads: nothing here changes the KB. To build or fix one, use the ontology skills that ship with okb.
|
|
11
|
+
|
|
12
|
+
## 1. Pick the tool
|
|
13
|
+
|
|
14
|
+
1. **`describe_ontology` first, once.** It lists what the KB covers, the class tree, the properties and relationships (with the exact names you will pass to other tools) and how many rules it holds. Keep it in mind; don't call it again.
|
|
15
|
+
2. **`find`, then `get`.** `find` finds candidates: `query` for words, `class` for the members of a class (subclasses included), `where` for values a thing has (`"*"` for any value), `allows` for values a class permits, `type` to narrow to classes, instances, properties, rules or sources. Use it for "which" and "list every" questions. Then `get` the one or two best matches for the full picture. A query is not an answer.
|
|
16
|
+
3. **`traverse` for links.** To follow one relationship from a starting point ("what is preferred over X", "what is built on Y"), name the relationship exactly as `describe_ontology` shows it. Add `direction: "in"` to read it backwards and `depth` (up to 3) to go further.
|
|
17
|
+
4. **`list_rules` for what must hold.** Filter by `about` (a class or instance), `modality` or `query`. A class includes the rules of its parent classes.
|
|
18
|
+
|
|
19
|
+
Names are forgiving (`Segmented Control`, `segmentedcontrol` and an id all work), and a name that matches nothing comes back with similar names.
|
|
20
|
+
|
|
21
|
+
## 2. Read what you get
|
|
22
|
+
|
|
23
|
+
- **Inverse relationships are one set of edges.** If `wrote` and `writtenBy` are inverses, "Ann wrote Tides" and "Tides is writtenBy Ann" are the same fact. Ask from whichever end you have, by either name, or with `direction: "in"`. Never conclude "no link" from one end alone.
|
|
24
|
+
- **Members inherit.** A class's fixed values and the rules that govern it apply to its subclasses and instances. A rule on `Overlay` covers `Modal`. When you answer for a member, check its parent classes with `get` or `list_rules`.
|
|
25
|
+
- **Filters mean different things.** `where` finds things that have a value. `allows` finds classes that permit one. A class that permits `size: large` has no `size` value until an instance sets one.
|
|
26
|
+
- **Read the modality.** MUST and MUST_NOT are requirements. SHOULD is a recommendation with exceptions. MAY is permission. Don't turn a SHOULD into "must", or the reverse.
|
|
27
|
+
- **Read the caveat.** A rule marked unverified, corrected, unsupported or overreach is weaker than one with no mark. Say so in your answer. Relationship links can carry a condition (`{condition: ...}`) and the rule behind them. Include the condition, because without it the answer overstates.
|
|
28
|
+
|
|
29
|
+
## 3. Answer with evidence
|
|
30
|
+
|
|
31
|
+
For each claim, give the rule's statement, its modality, and where it came from. What you can show depends on how the server was started (`--quotes`), so look at what the results contain and don't assume:
|
|
32
|
+
|
|
33
|
+
| You see | Say |
|
|
34
|
+
| ----------------------------- | --------------------------------------------------------------------------------------------- |
|
|
35
|
+
| A quote and a location | Quote it, with the document, heading and line, such as “…” (Button › Accessibility, line 18). |
|
|
36
|
+
| Only `source: …` under a rule | The quote is the rule's own statement. Quote the statement and give that location. |
|
|
37
|
+
| A location and no quote | Give the rule's statement, and point to the document, heading and line. |
|
|
38
|
+
| Neither | Give the rule's statement and its modality, and say the source isn't shown to you. |
|
|
39
|
+
|
|
40
|
+
Quote only text the tools returned, and never write a quote from memory. If `read_source` is among the tools (the server was started with `--read-source`), use it to read the cited section when the quote or the context matters: give it the document and heading or lines from a result. If it isn't there, don't look for it.
|
|
41
|
+
|
|
42
|
+
## 4. When the KB can't answer
|
|
43
|
+
|
|
44
|
+
- **Ambiguous name.** If a name matches several things (a class and a rule, say), `get` the likeliest, say which you chose, and mention the other.
|
|
45
|
+
- **Unknown name.** Read the suggestions the error gives, try one, and tell the person what you used. If nothing close exists, search with `find` and different words once or twice, not more.
|
|
46
|
+
- **No result.** Say "the KB doesn't cover this", name what you searched (tool, words, class) and, if useful, what it does cover nearby. Don't fill the gap from general knowledge. If you do add outside knowledge, label it as not from the KB.
|
|
47
|
+
- **No rule found** means the KB holds none, not that none exists. Say it that way. The server may also hold back unverified rules, so a missing rule is not proof that a source is silent.
|
|
48
|
+
- **Partial answer.** Give what the KB supports, and mark what it doesn't.
|