@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 CHANGED
@@ -18,13 +18,14 @@ The server speaks MCP over stdio, so you start it from an MCP client, for exampl
18
18
  { "mcpServers": { "wine": { "command": "okb-mcp", "args": ["path/to/ontology-folder"] } } }
19
19
  ```
20
20
 
21
- The folder is the one that holds `okb.json`, `nodes.jsonl` and `edges.jsonl`. The server reads it with [`@ontology-kit/reader`](../reader/README.md), so any okb format version the reader loads works, including folders still on `nodes.json` and `edges.json` (`okb-lpg/1` and `okb-lpg/2`) and the current `okb-lpg/3`.
21
+ `okb-mcp check` and `okb-mcp skills` are commands, so a KB folder with one of those names has to be written `./check` or `./skills`. The folder is the one that holds `okb.json`, `nodes.jsonl` and `edges.jsonl`. The server reads it with [`@ontology-kit/reader`](../reader/README.md), so any okb format version the reader loads works, including folders still on `nodes.json` and `edges.json` (`okb-lpg/1` and `okb-lpg/2`) and the current `okb-lpg/3`.
22
22
 
23
23
  | Option | What it does |
24
24
  | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
25
25
  | `--quotes full\|locator\|none` | How much of each rule's evidence the agent sees (see below). Default `full`. |
26
26
  | `--include-unverified` | Also serve rules that haven't been verified (see below). |
27
27
  | `--read-source` | Also serve `read_source`, which returns the text of a cited document. Needs `--quotes full`. |
28
+ | `--skills none\|bundled\|all` | Which skills to serve (see below). Default `bundled`. |
28
29
  | `--snapshot-id <id>` and `--snapshot-version <version>` | Report which data this server serves, as a resource the agent never sees. Give both or neither. |
29
30
 
30
31
  ## Tools
@@ -54,13 +55,66 @@ An okb rule cites a verbatim quote from a source document. `--quotes` decides wh
54
55
 
55
56
  In `locator` and `none` the quote text doesn't reach the agent through the tools above. It isn't searchable, `get` on a source lists locations or nothing, and the tool descriptions don't promise evidence the mode withholds. Use them to test whether an agent does well with the structure alone. `read_source` is the exception: it returns the cited document's own text, quotes included, so the server refuses `--read-source` with `--quotes locator` or `none`.
56
57
 
57
- `read_source` only opens files inside the ontology folder. It follows a symbolic link only when the file it points to is also inside the folder. It refuses the folder's own files: `okb.json`, `nodes.jsonl`, `edges.jsonl`, the older `nodes.json` and `edges.json`, and anything whose name starts with `.okb` (the lock and save files).
58
+ `read_source` only opens files inside the ontology folder. It follows a symbolic link only when the file it points to is also inside the folder. It refuses the folder's own files: `okb.json`, `nodes.jsonl`, `edges.jsonl`, the older `nodes.json` and `edges.json`, and a hard link to any of them; any file or folder whose name starts with a dot (such as `.env`, `.git` and the `.okb.lock` file); and any name ending in `.tmp` (the files an interrupted save leaves, which hold the whole KB).
58
59
 
59
60
  A source's `localPath` shows in `find` and `get`, and `find` searches it, only when `--read-source` is on. Without `read_source` the agent has no use for a file path.
60
61
 
61
62
  ## Unverified rules
62
63
 
63
- By default the server serves only verified rules, the same test `okb export` uses: `verification.status` is `SUPPORTED`. It holds back every other rule, each relationship link whose `rule` property points at one, and each quote that only held-back rules cite. Nothing of them is in the data the tools read, so nothing can leak. The server prints how much it held back to standard error when it starts. `--include-unverified` serves them, each marked with its status.
64
+ By default the server serves only verified rules, the same test `okb export` uses: `verification.status` is `SUPPORTED`. It holds back every other rule, each relationship link whose `rule` property points at one, and each quote that only held-back rules cite. Nothing of them is in the data the tools read, so `find`, `get`, `traverse` and `list_rules` can't show them. `read_source` is the exception: it reads the cited documents themselves from disk, so a passage that only a held-back rule cites can still be read through it, if the document is one a source names. The server prints how much it held back to standard error when it starts. `--include-unverified` serves them, each marked with its status.
65
+
66
+ ## Skills
67
+
68
+ The server serves skills through the [MCP skills extension](https://modelcontextprotocol.io/extensions/skills/overview) (SEP-2640): it declares `io.modelcontextprotocol/skills` in its capabilities, answers `skills/list` and `skills/get`, and serves each file with `resources/read` at `skill://<name>/<path>`. Each skill's manifest lists every file with its SHA-256 digest and size, computed from the file's bytes, so they're the same on every start until a file changes.
69
+
70
+ `--skills` picks the set:
71
+
72
+ | Set | Serves |
73
+ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
74
+ | `none` | No skills. The server declares no skills capability. For comparing an agent with and without them. |
75
+ | `bundled` | The skills this package ships, today `query-kb`. The default. |
76
+ | `all` | The bundled skills and every skill folder in `<ontology-folder>/skills/` (the layout is in [the file format](../../docs/FORMAT.md#skills-the-kb-ships)). |
77
+
78
+ A KB's own skills are instructions its author wrote and the agent follows, so serving them is a choice you make: use `--skills all` only for a KB you trust. With `all` the server prints one line to standard error naming the KB's skills; with the default it prints one line saying how many the KB has that aren't served, and nothing if it has none. At startup the server checks each skill it serves: `SKILL.md` needs frontmatter whose `name` matches the folder and a `description`, `SKILL.md` is at most 100,000 bytes, and a skill has at most 512 files and 16 MiB. A skill that breaks a rule stops the server with a message naming it. A KB skill that isn't served isn't read, so it can't stop a `none` or `bundled` server. An unknown set fails with the list of valid ones.
79
+
80
+ From code, `createServer(ontology, { skills })` takes `"none"`, `"bundled"` (the default) or `{ kb }`, which serves the bundled skills and the KB's own from `<kb>/skills/`, where `kb` is the `root` that `loadForServing` returns.
81
+
82
+ The extension is new and the SDK this package builds on (`@modelcontextprotocol/sdk` 1.x) doesn't implement it yet. The server adds the methods itself on the protocol the SDK speaks, in the result shapes the extension defines, so a host that has the extension finds them after the usual `initialize`. Hosts that follow the extension's newer, stateless protocol revision (`server/discover`) need an SDK that speaks it.
83
+
84
+ ## See and install the skills
85
+
86
+ The commands below write `okb-mcp`, which is on your path after `npm install -g @ontology-kit/mcp`. Without a global install, write `npx @ontology-kit/mcp` in its place. A link made by `skills install` points into the package's folder, and `npx` keeps that folder in a cache it may clear, so with `npx` use `--copy`.
87
+
88
+ `okb-mcp skills` lists the skills the server can serve, so you can see them before you turn anything on:
89
+
90
+ ```bash
91
+ okb-mcp skills # the bundled skills
92
+ okb-mcp skills path/to/ontology-folder # also the KB's own, labeled "from the KB"
93
+ okb-mcp skills path/to/ontology-folder --json
94
+ ```
95
+
96
+ For each skill it prints the name, where it comes from, the file count, the size, the SHA-256 digest of `SKILL.md` and the description. The numbers come from the loader the server uses, so the digests match what `skills/list` returns (`--json` also lists every file's digest and size). The KB's own skills are instructions its author wrote, and the server serves them only with `--skills all`. A skill that fails the server's checks is listed with the reason, and the command exits with code 1.
97
+
98
+ For a host that doesn't support the skills extension, `okb-mcp skills install` puts the bundled skills (today `query-kb`) where Claude Code and Cursor load them from. It never installs a KB's own skills.
99
+
100
+ ```bash
101
+ okb-mcp skills install # link into ~/.claude/skills
102
+ okb-mcp skills install --copy # copy instead of linking
103
+ okb-mcp skills install --dir ~/.cursor/skills
104
+ okb-mcp skills status # installed, and does the version match?
105
+ ```
106
+
107
+ The folder is `--dir`, else `$OKB_SKILLS_DIR`, else `~/.claude/skills`, as for `okb skills install`. A link keeps the skill current when you update the package; `--copy` needs a second run after an update. Installing again does nothing when the skill is already in place (a link to this package, or a copy identical to the packaged files), and replaces a link that points nowhere any more. For anything else that is there (an older or edited copy, a folder that isn't this skill, a link to somewhere else such as your own checkout), it prints what it found, which files differ from the packaged skill, and what would change, then asks `Replace it? (y/N)`. Only `y` or `yes` continues; anything else, an empty answer or end of input changes nothing and exits with code 2. A copy is replaced only after you confirm, and the old folder is kept: it is moved to `<skills folder>.backup/<skill>-<UTC time>/`, a sibling of the skills folder, because a host loads every folder with a `SKILL.md` and a backup inside it would load twice. A replaced link needs no backup. It asks only when its input and output are both terminals. In a script, CI or an agent it refuses and changes nothing unless you add `--force`, which replaces without asking (and still keeps the backup). With several skills, every check runs first, it asks once per skill, and a "no" for any of them stops the whole run before anything changes. It also refuses a `--dir` that is this package's own `skills` folder or holds it. `status` compares the `**Version X.Y.Z.**` line and exits with code 1 when a skill is missing or out of date. `okb skills install` doesn't install `query-kb`, because okb doesn't depend on this package.
108
+
109
+ ## Check competency questions through the tools
110
+
111
+ `okb cq answer` stores the answer a competency question should get. `okb cq check` tests those answers against the files. `okb-mcp check` tests them through the server:
112
+
113
+ ```bash
114
+ npx @ontology-kit/mcp check path/to/your-kb
115
+ ```
116
+
117
+ It starts the server in the same process, asks each stored query as the tool call an agent would make (`find`, `traverse`, or `get` for a property's value), and compares the names the tool lists with the expected names. It prints the same lines as `okb cq check` and exits 0 when every answered question passes and 1 when one fails. `--json` prints the results as data, and `--include-unverified` serves unverified rules, as the server does. Without it, `check` holds back unverified rules and the links that point at them, as the server does by default, so a question answered through one of those links fails in `okb-mcp check` and can still pass in `okb cq check`, which reads every file. Add `--include-unverified` to see what the question gets when they're served. A stored query the tools can't ask is reported as "can't be asked through the tools", with the reason, and counts as a failure.
64
118
 
65
119
  ## Use it from code
66
120
 
@@ -75,6 +129,7 @@ console.error(`holding back ${held.rules} rules and ${held.links} links`);
75
129
 
76
130
  const server = createServer(ontology, {
77
131
  evidence: "locator", // "full" (default), "locator" or "none"
132
+ // skills: { kb: root }, // also serve the KB's own skills from <root>/skills/ (trusted KBs only); "none" serves none; default "bundled"
78
133
  // readSource: { root }, // also serve read_source, reading documents from the ontology folder (needs evidence "full")
79
134
  snapshot: { id: "lumen-demo", version: "2026-01-01" }, // served at SNAPSHOT_URI, never as a tool
80
135
  });
@@ -0,0 +1,2 @@
1
+ /** Runs the check and returns the exit code: 0 when every answered question passes, 1 on a failure, 2 on a usage error. */
2
+ export declare function main(argv: string[]): Promise<number>;
@@ -0,0 +1,63 @@
1
+ // The `okb-mcp check` subcommand: argument handling and output. The checking is in check.ts.
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { describeResult, checkQuestionsThroughServer } from "./check.js";
5
+ import { OkbMcpError } from "./errors.js";
6
+ import { loadForServing } from "./serving.js";
7
+ const USAGE = `Usage: okb-mcp check <ontology-folder> [--include-unverified] [--json]
8
+
9
+ Asks each competency question's stored query (okb cq answer) through the server's tools, as an agent
10
+ would, and compares the names the tools list with the expected answer. Prints pass, fail or "can't be
11
+ asked through the tools" for each question, and exits 1 when any fails, as \`okb cq check\` does.
12
+
13
+ Like the server, it holds back unverified rules, and any link whose \`rule\` property points at one. A
14
+ question whose answer comes through such a link fails here and can still pass in \`okb cq check\`, which
15
+ reads every file. Add --include-unverified to see what the question gets when they're served.
16
+
17
+ --include-unverified also serve rules that haven't been verified, as the server's flag does (by default they and the links to them are held back)
18
+ --json print the results as JSON
19
+ `;
20
+ /** Runs the check and returns the exit code: 0 when every answered question passes, 1 on a failure, 2 on a usage error. */
21
+ export async function main(argv) {
22
+ let parsed;
23
+ try {
24
+ parsed = parseArgs({
25
+ args: argv,
26
+ allowPositionals: true,
27
+ options: { "include-unverified": { type: "boolean" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
28
+ });
29
+ }
30
+ catch (err) {
31
+ console.error(`${err.message}\n\n${USAGE}`);
32
+ return 2;
33
+ }
34
+ if (parsed.values.help) {
35
+ console.error(USAGE);
36
+ return 0;
37
+ }
38
+ const dir = parsed.positionals[0];
39
+ if (!dir || parsed.positionals.length > 1) {
40
+ console.error(USAGE);
41
+ return 2;
42
+ }
43
+ try {
44
+ const { ontology, held } = loadForServing(path.resolve(dir), { includeUnverified: parsed.values["include-unverified"] ?? false });
45
+ if (held.rules > 0) {
46
+ console.error(`okb-mcp: holding back ${held.rules} unverified rule${held.rules === 1 ? "" : "s"}. Use --include-unverified to serve them.`);
47
+ }
48
+ const results = await checkQuestionsThroughServer(ontology);
49
+ if (parsed.values.json)
50
+ console.log(JSON.stringify(results, null, 2));
51
+ else
52
+ for (const line of results.length ? results.map(describeResult) : ["No competency questions yet."])
53
+ console.log(line);
54
+ return results.some((r) => r.status === "fail" || r.status === "unsupported") ? 1 : 0;
55
+ }
56
+ catch (err) {
57
+ if (err instanceof OkbMcpError) {
58
+ console.error(err.message);
59
+ return 2;
60
+ }
61
+ throw err;
62
+ }
63
+ }
@@ -0,0 +1,38 @@
1
+ import { type Ontology } from "@ontology-kit/reader";
2
+ export type MatchMode = "exact" | "includes";
3
+ export type CheckStatus = "pass" | "fail" | "unsupported" | "none";
4
+ export interface CheckResult {
5
+ number: number;
6
+ id: string;
7
+ text: string;
8
+ /** `unsupported`: the tools can't ask this query. It counts as a failure. */
9
+ status: CheckStatus;
10
+ /** The tool the query was asked through. */
11
+ tool?: string;
12
+ /** Expected names the tools didn't list. */
13
+ missing: string[];
14
+ /** Names the tools listed that weren't expected (a failure only for `exact`). */
15
+ extra: string[];
16
+ /** The names the tools listed. */
17
+ actual: string[];
18
+ /** Why the tool call failed, for example a name the server can't resolve. */
19
+ error?: string;
20
+ /** Why the tools can't ask the query (status `unsupported`). */
21
+ unsupported?: string;
22
+ /** Set when the query has a `*` in `where`, which means "has any value". */
23
+ note?: string;
24
+ match?: MatchMode;
25
+ }
26
+ /** What a tool call gave back. */
27
+ interface ToolReply {
28
+ text: string;
29
+ isError: boolean;
30
+ }
31
+ type CallTool = (name: string, args: Record<string, unknown>) => Promise<ToolReply>;
32
+ /** Asks every question that has a stored answer through the server's tools, in number order. */
33
+ export declare function checkQuestionsThroughServer(ont: Ontology, options?: {
34
+ call?: CallTool;
35
+ }): Promise<CheckResult[]>;
36
+ /** One line per result, worded like `okb cq check`. */
37
+ export declare function describeResult(r: CheckResult): string;
38
+ export {};
package/dist/check.js ADDED
@@ -0,0 +1,295 @@
1
+ // `okb-mcp check <folder>`: the competency questions' stored queries, asked through the server's tools.
2
+ //
3
+ // `okb cq check` evaluates each question's stored query against the files. This asks the same
4
+ // questions the way an agent would: it starts the server in-process, connects the SDK client over an
5
+ // in-memory transport, turns each stored query into the tool call that asks it, reads the names out of
6
+ // the tool's text, and compares them with the expected answer. A filter the tools can't express, a name
7
+ // the server can't resolve or an inverse read the wrong way shows up here and not in `okb cq check`.
8
+ //
9
+ // The three stored shapes (the reader's `checkQuery`) map to tools like this:
10
+ // find -> `find` with class, where and type "instance"
11
+ // traverse -> `traverse` for a relationship; `get` for a property, which the traverse tool doesn't follow
12
+ // slots -> `find` with type "slot": each slot lists the classes it's on
13
+ // Anything else is reported as "can't be asked through the tools", with the reason, and counts as a failure.
14
+ //
15
+ // The comparison (names trimmed and lowercased, `exact` or `includes`) is the one `okb cq check` uses
16
+ // (packages/okb/src/cqanswer.ts); this package doesn't depend on okb, so the few lines are repeated here.
17
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
18
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
19
+ import { checkQuery, OkbError } from "@ontology-kit/reader";
20
+ import { OkbMcpError } from "./errors.js";
21
+ import { classesOf, displayName, relNames, resolve, readValues, splitValues, resolveRelationship, squash } from "./graph.js";
22
+ import { createServer } from "./server.js";
23
+ const STAR_NOTE = `"*" in where means "has any value", not the text "*". If this question meant the literal text, it no longer matches it.`;
24
+ const norm = (s) => s.trim().toLowerCase();
25
+ /** The most results `find` returns in one call. */
26
+ const FIND_LIMIT = 200;
27
+ /** The query can't be asked through the tools. Never a crash and never a pass. */
28
+ class Unsupported extends Error {
29
+ }
30
+ /** The tool answered, but not with names this check can read. Also reported as unsupported. */
31
+ const unreadable = (tool, line) => new Unsupported(`the ${tool} tool's result has a line this check can't read: "${line}"`);
32
+ /** The tool returned an error message (an unknown name, say). A failure with the message, not unsupported. */
33
+ class ToolFailed extends Error {
34
+ }
35
+ function compare(actual, expect, match) {
36
+ const have = new Set(actual.map(norm));
37
+ const want = new Set(expect.map(norm));
38
+ const missing = expect.filter((n) => !have.has(norm(n)));
39
+ const extra = actual.filter((n) => !want.has(norm(n)));
40
+ const ok = !missing.length && (match === "includes" || !extra.length);
41
+ return { status: (ok ? "pass" : "fail"), missing, extra, actual, match };
42
+ }
43
+ /** Longest known name that `text` starts with, where the name ends the text or is followed by one of `stops`. */
44
+ function leadingName(text, known, stops) {
45
+ let best;
46
+ for (const k of known) {
47
+ if (!text.startsWith(k) || (best !== undefined && k.length <= best.length))
48
+ continue;
49
+ const rest = text.slice(k.length);
50
+ if (rest === "" || stops.some((s) => rest.startsWith(s)))
51
+ best = k;
52
+ }
53
+ return best;
54
+ }
55
+ async function ask(call, name, args) {
56
+ let reply;
57
+ try {
58
+ reply = await call(name, args);
59
+ }
60
+ catch (err) {
61
+ // The server refused the arguments before running the tool (its input schema): the tools can't take this.
62
+ throw new Unsupported(`the ${name} tool refused the arguments ${JSON.stringify(args)}: ${err.message}`);
63
+ }
64
+ if (reply.isError)
65
+ throw new ToolFailed(reply.text);
66
+ return reply.text;
67
+ }
68
+ /** A relationship slot? The `traverse` tool follows these; properties are read with `get`. */
69
+ function slotKind(ont, name) {
70
+ const slot = ont.ofType("Slot").find((s) => squash(s.name) === squash(name) || squash(String(s.relType ?? "")) === squash(name));
71
+ if (!slot)
72
+ return undefined;
73
+ return ont.rel.spec(slot.id) !== null ? "relationship" : "property";
74
+ }
75
+ // find -----------------------------------------------------------------
76
+ async function viaFind(ont, call, q) {
77
+ const where = {};
78
+ for (const [slot, v] of Object.entries(q.where ?? {})) {
79
+ if (Array.isArray(v)) {
80
+ if (v.length !== 1)
81
+ throw new Unsupported(`"where.${slot}" lists several values, which means "all of them", and the find tool filters on one value per property.`);
82
+ where[slot] = v[0];
83
+ }
84
+ else
85
+ where[slot] = v;
86
+ }
87
+ const text = await ask(call, "find", { class: q.class, type: "instance", limit: FIND_LIMIT, ...(Object.keys(where).length ? { where } : {}) });
88
+ const lines = text.split("\n");
89
+ if (lines[0]?.startsWith("No matches"))
90
+ return { tool: "find", names: [] };
91
+ const more = lines.find((l) => l.startsWith("… "));
92
+ if (more)
93
+ throw new Unsupported(`the find tool lists at most ${FIND_LIMIT} results and this query has more (${lines[0]}).`);
94
+ const known = ont.ofType("Instance").map(displayName);
95
+ const names = [];
96
+ for (const line of lines.slice(1)) {
97
+ if (!line.trim())
98
+ continue;
99
+ const rest = /^- instance (.*)$/.exec(line)?.[1];
100
+ const name = rest === undefined ? undefined : leadingName(rest, known, [" (", ": "]);
101
+ if (name === undefined)
102
+ throw unreadable("find", line);
103
+ names.push(name);
104
+ }
105
+ return { tool: "find", names };
106
+ }
107
+ // traverse -------------------------------------------------------------
108
+ const TRAVERSE_LINE = /^( *)(.+?) —(.+?)→ (.+)$/;
109
+ async function viaTraverse(ont, call, q) {
110
+ const from = Array.isArray(q.from) ? q.from : [q.from];
111
+ // A stored `direction` is relative to the slot named, as in the reader's query layer; the tool's is relative to how the
112
+ // edges are stored. They differ for the inverse half of a pair, so an explicit direction is flipped there.
113
+ const named = resolveRelationship(ont, q.slot);
114
+ const direction = q.direction && named.backwards ? (q.direction === "out" ? "in" : "out") : q.direction;
115
+ const text = await ask(call, "traverse", {
116
+ from,
117
+ relationship: q.slot,
118
+ ...(direction ? { direction } : {}),
119
+ ...(q.depth ? { depth: q.depth } : {}),
120
+ });
121
+ const lines = text.split("\n");
122
+ const header = /^\d+ .* links? \((following|reading backwards)\):$/.exec(lines[0] ?? "");
123
+ if (!header) {
124
+ if (/^No ".*" relationships /.test(lines[0] ?? ""))
125
+ return { tool: "traverse", names: [] };
126
+ throw unreadable("traverse", lines[0] ?? "");
127
+ }
128
+ const known = [...ont.ofType("Class"), ...ont.ofType("Instance")].map(displayName);
129
+ // The tool writes the start on the left and the far end on the right, except when it reads backwards without a
130
+ // declared inverse: then it writes the statement as stored, "far —verb→ start". The direction says which, however many ends are starts.
131
+ const inverse = relNames(ont).hasInverse(ont.rel.spec(named.slot.id).type);
132
+ const farIsRight = header[1] === "following" || inverse;
133
+ const names = [];
134
+ for (const line of lines.slice(1)) {
135
+ const m = TRAVERSE_LINE.exec(line);
136
+ if (!m)
137
+ throw unreadable("traverse", line);
138
+ const left = m[2];
139
+ const right = leadingName(m[4], known, [" {", " [rule:", " (inherited from"]);
140
+ if (right === undefined)
141
+ throw unreadable("traverse", line);
142
+ names.push(farIsRight ? right : left);
143
+ }
144
+ return { tool: "traverse", names };
145
+ }
146
+ // get (a property's values) ---------------------------------------------
147
+ /** The values the `get` tool shows for a property: an instance's `slot: value`, or a class's `always value`. */
148
+ async function viaGetProperty(ont, call, q) {
149
+ if (q.direction === "in")
150
+ throw new Unsupported(`"${q.slot}" is a property, and the tools read a property's values from the thing that has it, not backwards.`);
151
+ if (q.depth !== undefined && q.depth > 1)
152
+ throw new Unsupported(`"${q.slot}" is a property, so there is nothing to follow past depth 1.`);
153
+ const slot = ont.ofType("Slot").find((s) => squash(s.name) === squash(q.slot) || squash(String(s.relType ?? "")) === squash(q.slot));
154
+ const names = [];
155
+ for (const from of Array.isArray(q.from) ? q.from : [q.from]) {
156
+ const lines = (await ask(call, "get", { name: from })).split("\n");
157
+ const isClass = lines[0]?.startsWith("Class: ");
158
+ if (!isClass && !lines[0]?.startsWith("Instance: "))
159
+ throw new Unsupported(`"${from}" isn't a class or an instance, and the tools show property values only for those.`);
160
+ const start = lines.indexOf("Properties:");
161
+ const section = [];
162
+ for (let i = start + 1; start >= 0 && i < lines.length && lines[i]; i++)
163
+ section.push(lines[i].trim());
164
+ const line = section.find((l) => l === slot.name || l.startsWith(`${slot.name}:`) || l.startsWith(`${slot.name} (`) || l.startsWith(`${slot.name},`));
165
+ if (line === undefined)
166
+ continue;
167
+ let value;
168
+ if (isClass) {
169
+ // After ", always" come the values, then an optional "(inherited from X)" and a " — description", neither inside a quoted value.
170
+ const at = line.indexOf(", always ");
171
+ if (at !== -1)
172
+ names.push(...readValues(line.slice(at + ", always ".length), [" (inherited from ", " — "]).values);
173
+ }
174
+ else {
175
+ value = /^[^:]*: (.*?)(?: \(from [^)]*\))?$/.exec(line)?.[1];
176
+ }
177
+ if (value !== undefined)
178
+ names.push(...splitValues(value));
179
+ }
180
+ return { tool: "get", names: [...new Set(names)] };
181
+ }
182
+ // slots ----------------------------------------------------------------
183
+ /** The slots a class or instance has: the `find` tool lists every slot with the classes it's on. */
184
+ async function viaSlots(ont, call, q) {
185
+ const node = resolve(ont, q.of, ["Class", "Instance"]);
186
+ const context = new Set(classesOf(ont, node).map(displayName));
187
+ const text = await ask(call, "find", { type: "slot", limit: FIND_LIMIT });
188
+ const lines = text.split("\n");
189
+ if (lines[0]?.startsWith("No matches"))
190
+ return { tool: "find", names: [] };
191
+ if (lines.some((l) => l.startsWith("… ")))
192
+ throw new Unsupported(`the find tool lists at most ${FIND_LIMIT} slots and this ontology has more (${lines[0]}).`);
193
+ const known = ont.ofType("Slot").map((s) => s.name);
194
+ const names = [];
195
+ for (const line of lines.slice(1)) {
196
+ const rest = /^- (?:property|relationship) (.*)$/.exec(line)?.[1];
197
+ const name = rest === undefined ? undefined : leadingName(rest, known, [" on ", ": "]);
198
+ if (name === undefined)
199
+ throw unreadable("find", line);
200
+ const on = /^ on (.*?): (?:property|relationship)/.exec(rest.slice(name.length))?.[1];
201
+ if (on?.split(", ").some((c) => context.has(c)))
202
+ names.push(name);
203
+ }
204
+ return { tool: "find", names: [...new Set(names)] };
205
+ }
206
+ // The check --------------------------------------------------------------
207
+ function withNumbers(ont) {
208
+ const natural = new Intl.Collator("en", { numeric: true });
209
+ const all = ont.ofType("CompetencyQuestion");
210
+ // The order `okb` numbers them in: oldest first, ties by id (numbers compared as numbers).
211
+ return [...all]
212
+ .sort((a, b) => {
213
+ const ca = a.createdAt ?? "";
214
+ const cb = b.createdAt ?? "";
215
+ return (ca < cb ? -1 : ca > cb ? 1 : 0) || natural.compare(a.id, b.id);
216
+ })
217
+ .map((q, i) => ({ q, number: i + 1 }));
218
+ }
219
+ async function checkOne(ont, call, q, number) {
220
+ const base = { number, id: q.id, text: q.text, missing: [], extra: [], actual: [] };
221
+ if (!q.answer)
222
+ return { ...base, status: "none" };
223
+ const match = q.answer.match ?? "exact";
224
+ const stored = q.answer.query;
225
+ let parsed;
226
+ try {
227
+ parsed = checkQuery(stored);
228
+ }
229
+ catch (err) {
230
+ if (!(err instanceof OkbError))
231
+ throw err;
232
+ return { ...base, status: "unsupported", missing: q.answer.expect, match, unsupported: `the stored query isn't one the tools understand: ${err.message}` };
233
+ }
234
+ try {
235
+ let got;
236
+ if ("find" in parsed)
237
+ got = await viaFind(ont, call, parsed.find);
238
+ else if ("slots" in parsed)
239
+ got = await viaSlots(ont, call, parsed.slots);
240
+ else
241
+ got = slotKind(ont, parsed.traverse.slot) === "property" ? await viaGetProperty(ont, call, parsed.traverse) : await viaTraverse(ont, call, parsed.traverse);
242
+ const result = { ...base, ...compare([...new Set(got.names)], q.answer.expect, match), tool: got.tool };
243
+ const where = "find" in parsed ? parsed.find.where : undefined;
244
+ const star = Object.values(where ?? {}).some((v) => (Array.isArray(v) ? v : [v]).some((x) => x === "*"));
245
+ return star ? { ...result, note: STAR_NOTE } : result;
246
+ }
247
+ catch (err) {
248
+ if (err instanceof Unsupported)
249
+ return { ...base, status: "unsupported", missing: q.answer.expect, match, unsupported: err.message };
250
+ if (err instanceof ToolFailed)
251
+ return { ...base, status: "fail", missing: q.answer.expect, match, error: err.message };
252
+ if (err instanceof OkbMcpError)
253
+ return { ...base, status: "fail", missing: q.answer.expect, match, error: err.message };
254
+ throw err;
255
+ }
256
+ }
257
+ /** Asks every question that has a stored answer through the server's tools, in number order. */
258
+ export async function checkQuestionsThroughServer(ont, options = {}) {
259
+ const questions = withNumbers(ont);
260
+ if (options.call)
261
+ return Promise.all(questions.map(({ q, number }) => checkOne(ont, options.call, q, number)));
262
+ const server = createServer(ont);
263
+ const [serverEnd, clientEnd] = InMemoryTransport.createLinkedPair();
264
+ const client = new Client({ name: "okb-mcp-check", version: "0" });
265
+ await Promise.all([server.connect(serverEnd), client.connect(clientEnd)]);
266
+ const call = async (name, args) => {
267
+ const res = (await client.callTool({ name, arguments: args }));
268
+ return { text: (res.content ?? []).map((c) => c.text ?? "").join("\n"), isError: res.isError === true };
269
+ };
270
+ try {
271
+ const results = [];
272
+ for (const { q, number } of questions)
273
+ results.push(await checkOne(ont, call, q, number));
274
+ return results;
275
+ }
276
+ finally {
277
+ await client.close();
278
+ await server.close();
279
+ }
280
+ }
281
+ /** One line per result, worded like `okb cq check`. */
282
+ export function describeResult(r) {
283
+ const head = `${r.number}. ${r.text}`;
284
+ if (r.status === "none")
285
+ return `${head}: no answer stored (okb cq answer ${r.number} --query '...' --expect ...)`;
286
+ const note = r.note ? ` Note: ${r.note}` : "";
287
+ if (r.status === "pass")
288
+ return `${head}: pass (${r.actual.length ? r.actual.join(", ") : "no names"})${note}`;
289
+ if (r.status === "unsupported")
290
+ return `${head}: can't be asked through the tools: ${r.unsupported}`;
291
+ if (r.error)
292
+ return `${head}: can't run the query: ${r.error}`;
293
+ const parts = [r.missing.length ? `missing ${r.missing.join(", ")}` : "", r.extra.length && r.match !== "includes" ? `extra ${r.extra.join(", ")}` : ""].filter(Boolean);
294
+ return `${head}: fail, ${parts.join("; ")}${note}`;
295
+ }
package/dist/cli.js CHANGED
@@ -1,18 +1,33 @@
1
1
  #!/usr/bin/env node
2
- // Usage: node src/cli.ts <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source]
2
+ // Usage: node src/cli.ts <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source] [--skills none|bundled|all]
3
3
  // [--snapshot-id <id> --snapshot-version <version>]
4
4
  import path from "node:path";
5
5
  import { parseArgs } from "node:util";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
7
  import { OkbMcpError } from "./errors.js";
8
+ import { kbSkillNames, SKILL_SETS } from "./skills.js";
8
9
  import { loadForServing } from "./serving.js";
9
10
  import { createServer } from "./server.js";
10
11
  import { EVIDENCE_MODES } from "./tools.js";
11
- const USAGE = `Usage: okb-mcp <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source]
12
+ // `okb-mcp check <folder>` asks the competency questions through the tools instead of starting the server.
13
+ if (process.argv[2] === "check")
14
+ process.exit(await (await import("./check-cli.js")).main(process.argv.slice(3)));
15
+ // `okb-mcp skills [<folder>]`, `okb-mcp skills install` and `okb-mcp skills status` list, install and check the skills.
16
+ if (process.argv[2] === "skills")
17
+ process.exit(await (await import("./skills-cli.js")).main(process.argv.slice(3)));
18
+ const USAGE = `Usage: okb-mcp <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source] [--skills none|bundled|all]
12
19
  [--snapshot-id <id> --snapshot-version <version>]
13
20
 
14
21
  Serves an okb ontology (the folder with okb.json, nodes.jsonl and edges.jsonl) over MCP on stdio.
15
22
 
23
+ Other commands:
24
+ okb-mcp check <ontology-folder> ask the competency questions through the tools
25
+ okb-mcp skills [<ontology-folder>] list the skills the server can serve
26
+ okb-mcp skills install install the bundled skills into a skills folder
27
+ okb-mcp skills status check the installed skills against the bundled ones
28
+ Run one with --help for its options. A folder named check or skills has to be written ./check or ./skills,
29
+ or the word is taken as the command.
30
+
16
31
  --quotes full show each rule's verbatim source quote and where it came from (default)
17
32
  --quotes locator show only where it came from: document, heading, line, link
18
33
  --quotes none show neither
@@ -26,6 +41,13 @@ Serves an okb ontology (the folder with okb.json, nodes.jsonl and edges.jsonl) o
26
41
  because it gives the agent the documents as well as the structure.
27
42
  Works only with --quotes full, since the documents contain the quotes.
28
43
 
44
+ --skills none serve no skills
45
+ --skills bundled serve the skills this package ships, today query-kb, through the MCP
46
+ skills extension (default)
47
+ --skills all also serve the skills in the KB's skills/ folder. They're instructions
48
+ the KB's author wrote and the agent follows, so use \`all\` only for a KB
49
+ you trust.
50
+
29
51
  --snapshot-id <id> --snapshot-version <version>
30
52
  report which data this is as the eval-kit://snapshot resource, JSON
31
53
  {"id", "version"}, so an eval harness can check it before a run. The
@@ -43,6 +65,7 @@ const { positionals, values } = (() => {
43
65
  quotes: { type: "string" },
44
66
  "include-unverified": { type: "boolean" },
45
67
  "read-source": { type: "boolean" },
68
+ skills: { type: "string" },
46
69
  "snapshot-id": { type: "string" },
47
70
  "snapshot-version": { type: "string" },
48
71
  help: { type: "boolean", short: "h" },
@@ -67,6 +90,10 @@ if (!EVIDENCE_MODES.includes(quotes)) {
67
90
  if (values["read-source"] && quotes !== "full") {
68
91
  fail(`--read-source can't be combined with --quotes ${quotes}: read_source returns the documents' own text, quotes included. Use --quotes full, or leave --read-source off.`);
69
92
  }
93
+ const skillSet = values.skills ?? "bundled";
94
+ if (!SKILL_SETS.includes(skillSet)) {
95
+ fail(`--skills must be one of ${SKILL_SETS.join(", ")}, not "${skillSet}".`);
96
+ }
70
97
  const snapshotId = values["snapshot-id"];
71
98
  const snapshotVersion = values["snapshot-version"];
72
99
  if ((snapshotId === undefined) !== (snapshotVersion === undefined) || snapshotId === "" || snapshotVersion === "") {
@@ -86,4 +113,24 @@ if (held.rules > 0) {
86
113
  console.error(`okb-mcp: holding back ${held.rules} unverified rule${held.rules === 1 ? "" : "s"}` +
87
114
  `${held.links ? ` and ${held.links} link${held.links === 1 ? "" : "s"} they justify` : ""}. Use --include-unverified to serve them.`);
88
115
  }
89
- await createServer(ontology, { evidence: quotes, readSource: values["read-source"] ? { root } : undefined, snapshot }).connect(new StdioServerTransport());
116
+ let server;
117
+ try {
118
+ server = createServer(ontology, {
119
+ evidence: quotes,
120
+ readSource: values["read-source"] ? { root } : undefined,
121
+ snapshot,
122
+ skills: skillSet === "all" ? { kb: root } : skillSet,
123
+ });
124
+ }
125
+ catch (err) {
126
+ fail(err instanceof OkbMcpError ? err.message : String(err));
127
+ }
128
+ // Also stderr: which author-written instructions go out, or how many are held back.
129
+ const kbSkills = skillSet === "none" ? [] : kbSkillNames(root);
130
+ if (skillSet === "all" && kbSkills.length > 0) {
131
+ console.error(`okb-mcp: serving ${kbSkills.length} skill${kbSkills.length === 1 ? "" : "s"} from the KB's skills/ folder: ${kbSkills.join(", ")}.`);
132
+ }
133
+ else if (skillSet === "bundled" && kbSkills.length > 0) {
134
+ console.error(`okb-mcp: the KB has ${kbSkills.length} skill${kbSkills.length === 1 ? "" : "s"} in skills/ that aren't served. Use --skills all to serve ${kbSkills.length === 1 ? "it" : "them"}.`);
135
+ }
136
+ await server.connect(new StdioServerTransport());
package/dist/graph.d.ts CHANGED
@@ -76,6 +76,19 @@ export declare function resolveRelationship(ont: Ontology, ref: string): {
76
76
  slot: OkbNode;
77
77
  backwards: boolean;
78
78
  };
79
+ /** A property's value or values, comma-separated, for `get`. `splitValues` is its inverse. */
80
+ export declare function showValues(value: unknown): string;
81
+ /**
82
+ * Reads the values `showValues` wrote from the start of `text`: split on ", " outside quoted strings. An unquoted value
83
+ * also ends at any of `stops` (text that follows the values on the line, such as an annotation or a description), and
84
+ * a quoted one may be followed by one. Returns the values and what is left after them.
85
+ */
86
+ export declare function readValues(text: string, stops?: readonly string[]): {
87
+ values: string[];
88
+ rest: string;
89
+ };
90
+ /** The values in `text` as `showValues` wrote them: split on ", " outside quoted strings. */
91
+ export declare function splitValues(text: string): string[];
79
92
  export interface Citation {
80
93
  quote: string;
81
94
  source: string;