@ontology-kit/mcp 0.0.0-stage → 0.3.0-alpha.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alan B Smith
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,154 @@
1
- # Temporary Holding Version
1
+ # @ontology-kit/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server that gives an agent a knowledge base built with [okb](https://ontology-kit.dev). The agent can look up classes, instances and relationships, follow links, and read the rules a document states, each with the evidence behind it. It reads the KB's folder and changes nothing in it.
4
+
5
+ It needs Node 24 or newer. It ships with okb and at okb's version, and reads the okb file formats the reader package loads.
6
+
7
+ ## Run it
8
+
9
+ ```bash
10
+ npx @ontology-kit/mcp path/to/ontology-folder
11
+ ```
12
+
13
+ From a checkout of this repository, run the sources: `node packages/mcp/src/cli.ts packages/okb/examples/wine`.
14
+
15
+ The server speaks MCP over stdio, so you start it from an MCP client, for example in a client's settings:
16
+
17
+ ```json
18
+ { "mcpServers": { "wine": { "command": "okb-mcp", "args": ["path/to/ontology-folder"] } } }
19
+ ```
20
+
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
+
23
+ | Option | What it does |
24
+ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
25
+ | `--quotes full\|locator\|none` | How much of each rule's evidence the agent sees (see below). Default `full`. |
26
+ | `--include-unverified` | Also serve rules that haven't been verified (see below). |
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`. |
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. |
30
+
31
+ ## Tools
32
+
33
+ | Tool | What it does |
34
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | `describe_ontology` | An overview: what the KB covers, the class tree, properties, relationships and how many rules it holds. Call it first. |
36
+ | `find` | Search by words, or filter: `class` for the members of a class, `where` for values a thing has (`"*"` for any value), `allows` for values a class permits. |
37
+ | `get` | Everything about one class, instance, property, relationship, rule or source: description, properties, relationships with their conditions, and the rules that govern it. |
38
+ | `traverse` | Follow one relationship from one or more starting points, forward or backward, up to three hops. |
39
+ | `list_rules` | The rules, filtered by what they govern, by modality or by text. A class includes the rules of its parent classes. |
40
+ | `read_source` | With `--read-source` only: one section of a cited document by heading, or a range of lines. |
41
+
42
+ Names are forgiving: `Segmented Control`, `segmentedcontrol` and an id all find the same class, and a name that matches nothing comes back with similar names.
43
+
44
+ `find`, `get` and `traverse` read the KB through the reader's query layer (`queryFind`, `queryGet`, `queryTraverse` and `querySlots`), so a question gets the same answer here as from `okb query` and a stored competency question. The server adds what the layer leaves out on purpose: free-text search, the `allows` filter, name matching that ignores punctuation, evidence modes and the text a model reads. The tools' text isn't a stable interface and may change in any release. Their names and arguments follow this package's version.
45
+
46
+ ## Evidence modes
47
+
48
+ An okb rule cites a verbatim quote from a source document. `--quotes` decides what the agent sees of it. The KB always keeps the quote.
49
+
50
+ | Mode | The agent sees |
51
+ | --------- | -------------------------------------------------------------------- |
52
+ | `full` | The quote and where it came from. |
53
+ | `locator` | Where it came from (document, heading, line, link) and not the text. |
54
+ | `none` | Neither. The rule's statement and any caveat about it stay. |
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`.
57
+
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).
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.
61
+
62
+ ## Unverified rules
63
+
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.
118
+
119
+ ## Use it from code
120
+
121
+ The package's one export lets a program start the server itself, for example an evaluation runner that serves a KB to the agent it is testing.
122
+
123
+ ```ts
124
+ import { createServer, loadForServing, SNAPSHOT_URI } from "@ontology-kit/mcp";
125
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
126
+
127
+ const { ontology, held, root } = loadForServing("path/to/ontology-folder", { includeUnverified: false });
128
+ console.error(`holding back ${held.rules} rules and ${held.links} links`);
129
+
130
+ const server = createServer(ontology, {
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"
133
+ // readSource: { root }, // also serve read_source, reading documents from the ontology folder (needs evidence "full")
134
+ snapshot: { id: "lumen-demo", version: "2026-01-01" }, // served at SNAPSHOT_URI, never as a tool
135
+ });
136
+ await server.connect(new StdioServerTransport());
137
+ ```
138
+
139
+ | Export | What it is |
140
+ | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
141
+ | `loadForServing(folder, options?)` | Loads a folder with the reader and, unless `includeUnverified` is set, returns a view without the unverified rules. Returns `{ ontology, held: { rules, links }, root }`. |
142
+ | `createServer(ontology, options?)` | Builds the `McpServer` for the reader's `Ontology`. It serves the ontology as given, so pass the one `loadForServing` returned to keep unverified rules out. |
143
+ | `SNAPSHOT_URI` | `eval-kit://snapshot`, the resource that reports the `snapshot` option as JSON `{"id", "version"}`. |
144
+ | `EVIDENCE_MODES`, `Evidence` | The three modes, and their type. |
145
+ | `ServerOptions`, `Snapshot`, `HeldBack`, `ServingOptions` | The option and result types. |
146
+ | `OkbMcpError` | The error for a bad folder or an unknown name. Tool calls return it to the agent as a tool error. |
147
+
148
+ ## Development
149
+
150
+ ```bash
151
+ pnpm --filter @ontology-kit/mcp test
152
+ ```
153
+
154
+ The tests run the server on a small fictional fixture (`tests/fixtures/lumen`, a UI kit), on a hand-built KB with rules in every verification state, on a KB built by the okb CLI, and on the wine and espresso examples. The fixture is in the current format. Rebuild it with the okb CLI rather than editing its files, and check it with `okb validate --all`.
package/bin/okb-mcp.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // In a source checkout (src/ exists) this runs the TypeScript sources, which Node runs by stripping
3
+ // types, so a stale dist/ is never used while developing. The published package ships dist/ and not
4
+ // src/, so an installed server runs the compiled CLI.
5
+ import { existsSync } from "node:fs";
6
+
7
+ const sources = new URL("../src/cli.ts", import.meta.url);
8
+ await import(existsSync(sources) ? sources.href : new URL("../dist/cli.js", import.meta.url).href);
@@ -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.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};