@ontology-kit/mcp 0.0.0-stage → 0.3.0-bootstrap.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +98 -2
- package/bin/okb-mcp.js +8 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +89 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/graph.d.ts +99 -0
- package/dist/graph.js +246 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/server.d.ts +33 -0
- package/dist/server.js +127 -0
- package/dist/serving.d.ts +41 -0
- package/dist/serving.js +66 -0
- package/dist/source.d.ts +13 -0
- package/dist/source.js +125 -0
- package/dist/tools.d.ts +55 -0
- package/dist/tools.js +547 -0
- package/package.json +58 -3
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,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ontology-kit/mcp
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
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
|
+
| `--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
|
+
## Tools
|
|
31
|
+
|
|
32
|
+
| Tool | What it does |
|
|
33
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
34
|
+
| `describe_ontology` | An overview: what the KB covers, the class tree, properties, relationships and how many rules it holds. Call it first. |
|
|
35
|
+
| `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. |
|
|
36
|
+
| `get` | Everything about one class, instance, property, relationship, rule or source: description, properties, relationships with their conditions, and the rules that govern it. |
|
|
37
|
+
| `traverse` | Follow one relationship from one or more starting points, forward or backward, up to three hops. |
|
|
38
|
+
| `list_rules` | The rules, filtered by what they govern, by modality or by text. A class includes the rules of its parent classes. |
|
|
39
|
+
| `read_source` | With `--read-source` only: one section of a cited document by heading, or a range of lines. |
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
`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.
|
|
44
|
+
|
|
45
|
+
## Evidence modes
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
| Mode | The agent sees |
|
|
50
|
+
| --------- | -------------------------------------------------------------------- |
|
|
51
|
+
| `full` | The quote and where it came from. |
|
|
52
|
+
| `locator` | Where it came from (document, heading, line, link) and not the text. |
|
|
53
|
+
| `none` | Neither. The rule's statement and any caveat about it stay. |
|
|
54
|
+
|
|
55
|
+
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
|
+
`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
|
+
|
|
59
|
+
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
|
+
## Unverified rules
|
|
62
|
+
|
|
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
|
+
|
|
65
|
+
## Use it from code
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { createServer, loadForServing, SNAPSHOT_URI } from "@ontology-kit/mcp";
|
|
71
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
72
|
+
|
|
73
|
+
const { ontology, held, root } = loadForServing("path/to/ontology-folder", { includeUnverified: false });
|
|
74
|
+
console.error(`holding back ${held.rules} rules and ${held.links} links`);
|
|
75
|
+
|
|
76
|
+
const server = createServer(ontology, {
|
|
77
|
+
evidence: "locator", // "full" (default), "locator" or "none"
|
|
78
|
+
// readSource: { root }, // also serve read_source, reading documents from the ontology folder (needs evidence "full")
|
|
79
|
+
snapshot: { id: "lumen-demo", version: "2026-01-01" }, // served at SNAPSHOT_URI, never as a tool
|
|
80
|
+
});
|
|
81
|
+
await server.connect(new StdioServerTransport());
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Export | What it is |
|
|
85
|
+
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
86
|
+
| `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 }`. |
|
|
87
|
+
| `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. |
|
|
88
|
+
| `SNAPSHOT_URI` | `eval-kit://snapshot`, the resource that reports the `snapshot` option as JSON `{"id", "version"}`. |
|
|
89
|
+
| `EVIDENCE_MODES`, `Evidence` | The three modes, and their type. |
|
|
90
|
+
| `ServerOptions`, `Snapshot`, `HeldBack`, `ServingOptions` | The option and result types. |
|
|
91
|
+
| `OkbMcpError` | The error for a bad folder or an unknown name. Tool calls return it to the agent as a tool error. |
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pnpm --filter @ontology-kit/mcp test
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
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);
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Usage: node src/cli.ts <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source]
|
|
3
|
+
// [--snapshot-id <id> --snapshot-version <version>]
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
+
import { OkbMcpError } from "./errors.js";
|
|
8
|
+
import { loadForServing } from "./serving.js";
|
|
9
|
+
import { createServer } from "./server.js";
|
|
10
|
+
import { EVIDENCE_MODES } from "./tools.js";
|
|
11
|
+
const USAGE = `Usage: okb-mcp <ontology-folder> [--quotes full|locator|none] [--include-unverified] [--read-source]
|
|
12
|
+
[--snapshot-id <id> --snapshot-version <version>]
|
|
13
|
+
|
|
14
|
+
Serves an okb ontology (the folder with okb.json, nodes.jsonl and edges.jsonl) over MCP on stdio.
|
|
15
|
+
|
|
16
|
+
--quotes full show each rule's verbatim source quote and where it came from (default)
|
|
17
|
+
--quotes locator show only where it came from: document, heading, line, link
|
|
18
|
+
--quotes none show neither
|
|
19
|
+
|
|
20
|
+
--include-unverified also serve rules that haven't been verified against their quote.
|
|
21
|
+
By default they're held back, as \`okb export\` does, along with any
|
|
22
|
+
link whose \`rule\` property points at one.
|
|
23
|
+
|
|
24
|
+
--read-source also serve read_source: the text of a cited document, by heading or
|
|
25
|
+
line range, from the files the ontology's sources name. Off by default,
|
|
26
|
+
because it gives the agent the documents as well as the structure.
|
|
27
|
+
Works only with --quotes full, since the documents contain the quotes.
|
|
28
|
+
|
|
29
|
+
--snapshot-id <id> --snapshot-version <version>
|
|
30
|
+
report which data this is as the eval-kit://snapshot resource, JSON
|
|
31
|
+
{"id", "version"}, so an eval harness can check it before a run. The
|
|
32
|
+
model never sees it. Give both or neither.
|
|
33
|
+
`;
|
|
34
|
+
function fail(message) {
|
|
35
|
+
console.error(message);
|
|
36
|
+
process.exit(2);
|
|
37
|
+
}
|
|
38
|
+
const { positionals, values } = (() => {
|
|
39
|
+
try {
|
|
40
|
+
return parseArgs({
|
|
41
|
+
allowPositionals: true,
|
|
42
|
+
options: {
|
|
43
|
+
quotes: { type: "string" },
|
|
44
|
+
"include-unverified": { type: "boolean" },
|
|
45
|
+
"read-source": { type: "boolean" },
|
|
46
|
+
"snapshot-id": { type: "string" },
|
|
47
|
+
"snapshot-version": { type: "string" },
|
|
48
|
+
help: { type: "boolean", short: "h" },
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
return fail(`${err.message}\n\n${USAGE}`);
|
|
54
|
+
}
|
|
55
|
+
})();
|
|
56
|
+
if (values.help) {
|
|
57
|
+
console.error(USAGE);
|
|
58
|
+
process.exit(0);
|
|
59
|
+
}
|
|
60
|
+
const dir = positionals[0];
|
|
61
|
+
if (!dir)
|
|
62
|
+
fail(USAGE);
|
|
63
|
+
const quotes = values.quotes ?? "full";
|
|
64
|
+
if (!EVIDENCE_MODES.includes(quotes)) {
|
|
65
|
+
fail(`--quotes must be one of ${EVIDENCE_MODES.join(", ")}, not "${quotes}".`);
|
|
66
|
+
}
|
|
67
|
+
if (values["read-source"] && quotes !== "full") {
|
|
68
|
+
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
|
+
}
|
|
70
|
+
const snapshotId = values["snapshot-id"];
|
|
71
|
+
const snapshotVersion = values["snapshot-version"];
|
|
72
|
+
if ((snapshotId === undefined) !== (snapshotVersion === undefined) || snapshotId === "" || snapshotVersion === "") {
|
|
73
|
+
fail("--snapshot-id and --snapshot-version go together, and neither can be empty.");
|
|
74
|
+
}
|
|
75
|
+
const snapshot = snapshotId && snapshotVersion ? { id: snapshotId, version: snapshotVersion } : undefined;
|
|
76
|
+
let loaded;
|
|
77
|
+
try {
|
|
78
|
+
loaded = loadForServing(path.resolve(dir), { includeUnverified: values["include-unverified"] ?? false });
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
fail(err instanceof OkbMcpError ? err.message : String(err));
|
|
82
|
+
}
|
|
83
|
+
const { ontology, held, root } = loaded;
|
|
84
|
+
if (held.rules > 0) {
|
|
85
|
+
// stderr, so an operator sees it in the MCP client's logs without it reaching the agent.
|
|
86
|
+
console.error(`okb-mcp: holding back ${held.rules} unverified rule${held.rules === 1 ? "" : "s"}` +
|
|
87
|
+
`${held.links ? ` and ${held.links} link${held.links === 1 ? "" : "s"} they justify` : ""}. Use --include-unverified to serve them.`);
|
|
88
|
+
}
|
|
89
|
+
await createServer(ontology, { evidence: quotes, readSource: values["read-source"] ? { root } : undefined, snapshot }).connect(new StdioServerTransport());
|
package/dist/errors.d.ts
ADDED
package/dist/errors.js
ADDED
package/dist/graph.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type OkbNode, type Ontology, type SlotNode } from "@ontology-kit/reader";
|
|
2
|
+
type Bag = Record<string, unknown>;
|
|
3
|
+
/** A node's fields by name, for the optional fields the typed union doesn't share. */
|
|
4
|
+
export declare const bag: (n: OkbNode) => Bag;
|
|
5
|
+
/** What a node is called: its name, or for a source document its title. */
|
|
6
|
+
export declare function displayName(n: OkbNode): string;
|
|
7
|
+
export declare function byName(a: OkbNode, b: OkbNode): number;
|
|
8
|
+
/** "Segmented Control", "SegmentedControl" and "segmented-control" all squash to the same string. */
|
|
9
|
+
export declare function squash(s: string): string;
|
|
10
|
+
export declare function asStrings(v: unknown): string[];
|
|
11
|
+
export declare const parents: (ont: Ontology, id: string) => OkbNode[];
|
|
12
|
+
export declare const children: (ont: Ontology, id: string) => OkbNode[];
|
|
13
|
+
/** Nearest first. Excludes the class itself. */
|
|
14
|
+
export declare const ancestors: (ont: Ontology, id: string) => OkbNode[];
|
|
15
|
+
export declare const descendants: (ont: Ontology, id: string) => OkbNode[];
|
|
16
|
+
/** Instances of a class and its subclasses (or of the class alone), by name. */
|
|
17
|
+
export declare function instancesOf(ont: Ontology, classId: string, { direct }?: {
|
|
18
|
+
direct?: boolean | undefined;
|
|
19
|
+
}): OkbNode[];
|
|
20
|
+
/** A node's own classes first, then their ancestors. */
|
|
21
|
+
export declare function classesOf(ont: Ontology, node: OkbNode): OkbNode[];
|
|
22
|
+
/**
|
|
23
|
+
* Finds one node by id, `type:Name`, exact name, synonym, or (when it's unambiguous) a case-insensitive
|
|
24
|
+
* substring of a name. More forgiving than the reader's `find`, which matches a whole name only. Throws
|
|
25
|
+
* with the candidates when the reference is unknown or ambiguous.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolve(ont: Ontology, ref: string, types?: string[]): OkbNode;
|
|
28
|
+
export interface PropertyValue {
|
|
29
|
+
slot: OkbNode;
|
|
30
|
+
value: unknown;
|
|
31
|
+
/** The class whose fixed value this is, when the node states none of its own. */
|
|
32
|
+
inheritedFrom: OkbNode | undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Property slots (not relationships) and their values for a class or instance, with inheritance, by slot name. */
|
|
35
|
+
export declare function propertyValues(ont: Ontology, node: OkbNode): PropertyValue[];
|
|
36
|
+
/** Slots attached to the class or inherited from its ancestors. `from` is the class that declares each. */
|
|
37
|
+
export declare function slotsOf(ont: Ontology, classNode: OkbNode): {
|
|
38
|
+
slot: OkbNode;
|
|
39
|
+
from: OkbNode;
|
|
40
|
+
}[];
|
|
41
|
+
/** How each relationship edge type is named from either end, read once per call. */
|
|
42
|
+
export interface RelNames {
|
|
43
|
+
/** The relationship's own (forward) name. */
|
|
44
|
+
name(type: string): string;
|
|
45
|
+
/** True when the relationship has a declared inverse name. */
|
|
46
|
+
hasInverse(type: string): boolean;
|
|
47
|
+
/** The name from the other end: the declared inverse, else "name (incoming)". */
|
|
48
|
+
inverseLabel(type: string): string;
|
|
49
|
+
}
|
|
50
|
+
export declare function relNames(ont: Ontology): RelNames;
|
|
51
|
+
/** The slots that store a relationship, by name. An inverse is the same relationship, so it isn't listed. */
|
|
52
|
+
export declare function relationshipSlots(ont: Ontology): SlotNode[];
|
|
53
|
+
export interface RelationshipEnd {
|
|
54
|
+
/** The relationship as the reader sees it from this node (the inverse name when incoming). */
|
|
55
|
+
label: string;
|
|
56
|
+
/** The relationship's own (forward) name, whichever end the node is on. */
|
|
57
|
+
relName: string;
|
|
58
|
+
/** True when `label` is a declared inverse name rather than a generated one. */
|
|
59
|
+
hasInverse: boolean;
|
|
60
|
+
direction: "out" | "in";
|
|
61
|
+
other: OkbNode;
|
|
62
|
+
props: Record<string, unknown>;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Every relationship value on the node, both directions, from the edges `queryGet` returns. Class-level
|
|
66
|
+
* edges to instances are facts about every member, so a node also gets those of its classes.
|
|
67
|
+
*/
|
|
68
|
+
export declare function relationshipsOf(ont: Ontology, node: OkbNode, { inherited }?: {
|
|
69
|
+
inherited?: boolean | undefined;
|
|
70
|
+
}): RelationshipEnd[];
|
|
71
|
+
/**
|
|
72
|
+
* Resolves `preferredOver`, `PREFERRED_OVER` or `preferred over` to a relationship slot. `backwards` says
|
|
73
|
+
* the slot named is the inverse of the one that stores the edges, so it reads them against their stored direction.
|
|
74
|
+
*/
|
|
75
|
+
export declare function resolveRelationship(ont: Ontology, ref: string): {
|
|
76
|
+
slot: OkbNode;
|
|
77
|
+
backwards: boolean;
|
|
78
|
+
};
|
|
79
|
+
export interface Citation {
|
|
80
|
+
quote: string;
|
|
81
|
+
source: string;
|
|
82
|
+
locator: string;
|
|
83
|
+
lines: string | undefined;
|
|
84
|
+
link: string | undefined;
|
|
85
|
+
}
|
|
86
|
+
export interface Rule {
|
|
87
|
+
id: string;
|
|
88
|
+
modality: string;
|
|
89
|
+
statement: string;
|
|
90
|
+
/** SUPPORTED, or why a reader should be careful. */
|
|
91
|
+
caveat: string | undefined;
|
|
92
|
+
citations: Citation[];
|
|
93
|
+
}
|
|
94
|
+
/** Rules that govern the node itself. */
|
|
95
|
+
export declare const rulesGoverning: (ont: Ontology, nodeId: string) => OkbNode[];
|
|
96
|
+
export declare function describeRule(ont: Ontology, rule: OkbNode): Rule;
|
|
97
|
+
/** The passages a node cites, each with its source document and place in it. */
|
|
98
|
+
export declare function citationsFor(ont: Ontology, nodeId: string): Citation[];
|
|
99
|
+
export {};
|
package/dist/graph.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// Reading the served ontology the way the tools need it: names, forgiving lookup, rules and their
|
|
2
|
+
// citations, relationships with their labels. Everything goes through the reader (`Ontology`, `ont.rel`,
|
|
3
|
+
// the query layer); nothing here knows how relationships are stored.
|
|
4
|
+
import { edgeProps, isStructuralEdgeType, queryGet, queryTraverse, querySlots, } from "@ontology-kit/reader";
|
|
5
|
+
import { OkbMcpError } from "./errors.js";
|
|
6
|
+
/** A node's fields by name, for the optional fields the typed union doesn't share. */
|
|
7
|
+
export const bag = (n) => n;
|
|
8
|
+
/** What a node is called: its name, or for a source document its title. */
|
|
9
|
+
export function displayName(n) {
|
|
10
|
+
const b = bag(n);
|
|
11
|
+
return String(b.name ?? b.title ?? n.id);
|
|
12
|
+
}
|
|
13
|
+
export function byName(a, b) {
|
|
14
|
+
return displayName(a).localeCompare(displayName(b));
|
|
15
|
+
}
|
|
16
|
+
/** "Segmented Control", "SegmentedControl" and "segmented-control" all squash to the same string. */
|
|
17
|
+
export function squash(s) {
|
|
18
|
+
return s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
19
|
+
}
|
|
20
|
+
export function asStrings(v) {
|
|
21
|
+
return Array.isArray(v) ? v.map(String) : typeof v === "string" ? [v] : [];
|
|
22
|
+
}
|
|
23
|
+
function nodes(ont, ids) {
|
|
24
|
+
const out = [];
|
|
25
|
+
for (const id of ids) {
|
|
26
|
+
const n = ont.get(id);
|
|
27
|
+
if (n)
|
|
28
|
+
out.push(n);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
// Classes ---------------------------------------------------------------
|
|
33
|
+
export const parents = (ont, id) => nodes(ont, ont.parents(id)).filter((n) => n.type === "Class");
|
|
34
|
+
export const children = (ont, id) => nodes(ont, ont.children(id)).filter((n) => n.type === "Class").sort(byName);
|
|
35
|
+
/** Nearest first. Excludes the class itself. */
|
|
36
|
+
export const ancestors = (ont, id) => nodes(ont, ont.ancestors(id));
|
|
37
|
+
export const descendants = (ont, id) => nodes(ont, ont.descendants(id));
|
|
38
|
+
/** Instances of a class and its subclasses (or of the class alone), by name. */
|
|
39
|
+
export function instancesOf(ont, classId, { direct = false } = {}) {
|
|
40
|
+
const ids = direct ? [classId] : [classId, ...ont.descendants(classId)];
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
return ids
|
|
43
|
+
.flatMap((id) => nodes(ont, ont.sources(id, "INSTANCE_OF")))
|
|
44
|
+
.filter((n) => n.type === "Instance" && !seen.has(n.id) && seen.add(n.id))
|
|
45
|
+
.sort(byName);
|
|
46
|
+
}
|
|
47
|
+
/** A node's own classes first, then their ancestors. */
|
|
48
|
+
export function classesOf(ont, node) {
|
|
49
|
+
if (node.type === "Class")
|
|
50
|
+
return [node, ...ancestors(ont, node.id)];
|
|
51
|
+
const own = nodes(ont, ont.targets(node.id, "INSTANCE_OF")).filter((n) => n.type === "Class");
|
|
52
|
+
const seen = new Set(own.map((c) => c.id));
|
|
53
|
+
const out = [...own];
|
|
54
|
+
for (const c of own)
|
|
55
|
+
for (const a of ancestors(ont, c.id))
|
|
56
|
+
if (!seen.has(a.id))
|
|
57
|
+
(seen.add(a.id), out.push(a));
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
// Lookup ----------------------------------------------------------------
|
|
61
|
+
const NAMED_TYPES = new Set(["Class", "Slot", "Instance", "Rule", "Source"]);
|
|
62
|
+
function capitalize(s) {
|
|
63
|
+
return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Finds one node by id, `type:Name`, exact name, synonym, or (when it's unambiguous) a case-insensitive
|
|
67
|
+
* substring of a name. More forgiving than the reader's `find`, which matches a whole name only. Throws
|
|
68
|
+
* with the candidates when the reference is unknown or ambiguous.
|
|
69
|
+
*/
|
|
70
|
+
export function resolve(ont, ref, types) {
|
|
71
|
+
const allowed = (n) => !types || types.includes(n.type);
|
|
72
|
+
const raw = ref.trim();
|
|
73
|
+
const direct = ont.get(raw);
|
|
74
|
+
if (direct && allowed(direct))
|
|
75
|
+
return direct;
|
|
76
|
+
const prefixed = /^(class|slot|instance|rule|source):(.+)$/i.exec(raw);
|
|
77
|
+
const wantType = prefixed ? capitalize(prefixed[1]) : undefined;
|
|
78
|
+
const text = (prefixed ? prefixed[2] : raw).trim().toLowerCase();
|
|
79
|
+
const pool = ont.nodes.filter((n) => NAMED_TYPES.has(n.type) && allowed(n) && (!wantType || n.type === wantType));
|
|
80
|
+
const exact = pool.filter((n) => displayName(n).toLowerCase() === text || squash(displayName(n)) === squash(text));
|
|
81
|
+
const synonym = pool.filter((n) => asStrings(bag(n).synonyms).some((s) => s.toLowerCase() === text));
|
|
82
|
+
const partial = pool.filter((n) => displayName(n).toLowerCase().includes(text) || squash(displayName(n)).includes(squash(text)));
|
|
83
|
+
for (const tier of [exact, synonym, partial]) {
|
|
84
|
+
if (tier.length === 1)
|
|
85
|
+
return tier[0];
|
|
86
|
+
if (tier.length > 1) {
|
|
87
|
+
// A class and a slot sharing a name is the usual ambiguity; the class is almost always meant.
|
|
88
|
+
const classes = tier.filter((n) => n.type === "Class");
|
|
89
|
+
if (classes.length === 1 && tier !== partial)
|
|
90
|
+
return classes[0];
|
|
91
|
+
throw new OkbMcpError(`"${ref}" is ambiguous. Did you mean: ${tier.slice(0, 8).map((n) => `${n.type.toLowerCase()}:${displayName(n)}`).join(", ")}?`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const near = pool.filter((n) => text.split(/\s+/).some((w) => w.length > 2 && displayName(n).toLowerCase().includes(w))).slice(0, 5);
|
|
95
|
+
throw new OkbMcpError(`Nothing named "${ref}"${types ? ` (looking for ${types.join(" or ").toLowerCase()})` : ""}.` +
|
|
96
|
+
(near.length ? ` Similar: ${near.map((n) => displayName(n)).join(", ")}.` : " Try `find` to search."));
|
|
97
|
+
}
|
|
98
|
+
/** Property slots (not relationships) and their values for a class or instance, with inheritance, by slot name. */
|
|
99
|
+
export function propertyValues(ont, node) {
|
|
100
|
+
if (node.type !== "Class" && node.type !== "Instance")
|
|
101
|
+
return [];
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const slot of querySlots(ont, { of: node.id })) {
|
|
104
|
+
if (slot.relationship)
|
|
105
|
+
continue;
|
|
106
|
+
const hits = queryTraverse(ont, { from: node.id, slot: slot.id });
|
|
107
|
+
if (hits.length === 0)
|
|
108
|
+
continue;
|
|
109
|
+
const via = hits[0].inheritedFrom;
|
|
110
|
+
out.push({
|
|
111
|
+
slot: ont.require(slot.id),
|
|
112
|
+
value: hits.length === 1 ? hits[0].value : hits.map((h) => h.value),
|
|
113
|
+
inheritedFrom: via ? ont.get(via) : undefined,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return out.sort((a, b) => String(bag(a.slot).name).localeCompare(String(bag(b.slot).name)));
|
|
117
|
+
}
|
|
118
|
+
/** Slots attached to the class or inherited from its ancestors. `from` is the class that declares each. */
|
|
119
|
+
export function slotsOf(ont, classNode) {
|
|
120
|
+
const out = [];
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
for (const c of [classNode, ...ancestors(ont, classNode.id)]) {
|
|
123
|
+
for (const s of nodes(ont, ont.ownSlots(c.id))) {
|
|
124
|
+
if (s.type === "Slot" && !seen.has(s.id))
|
|
125
|
+
(seen.add(s.id), out.push({ slot: s, from: c }));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
export function relNames(ont) {
|
|
131
|
+
const slots = new Map();
|
|
132
|
+
const inverse = new Map();
|
|
133
|
+
for (const [type, slotId] of ont.rel.edgeTypes()) {
|
|
134
|
+
const slot = ont.get(slotId);
|
|
135
|
+
if (!slot)
|
|
136
|
+
continue;
|
|
137
|
+
slots.set(type, slot);
|
|
138
|
+
const other = ont.inverses(slotId).map((id) => ont.get(id)).find((s) => s?.type === "Slot");
|
|
139
|
+
if (other)
|
|
140
|
+
inverse.set(type, displayName(other));
|
|
141
|
+
}
|
|
142
|
+
const name = (type) => (slots.has(type) ? displayName(slots.get(type)) : type);
|
|
143
|
+
return {
|
|
144
|
+
name,
|
|
145
|
+
hasInverse: (type) => inverse.has(type),
|
|
146
|
+
inverseLabel: (type) => inverse.get(type) ?? `${name(type)} (incoming)`,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/** The slots that store a relationship, by name. An inverse is the same relationship, so it isn't listed. */
|
|
150
|
+
export function relationshipSlots(ont) {
|
|
151
|
+
return ont.ofType("Slot").filter((s) => s.valueType === "Instance" && ont.rel.isPrimary(s.id)).sort(byName);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Every relationship value on the node, both directions, from the edges `queryGet` returns. Class-level
|
|
155
|
+
* edges to instances are facts about every member, so a node also gets those of its classes.
|
|
156
|
+
*/
|
|
157
|
+
export function relationshipsOf(ont, node, { inherited = true } = {}) {
|
|
158
|
+
const names = relNames(ont);
|
|
159
|
+
const out = [];
|
|
160
|
+
const add = (e, direction, inheritedFrom) => {
|
|
161
|
+
const other = ont.get(direction === "out" ? e.to : e.from);
|
|
162
|
+
if (!other || isStructuralEdgeType(e.type))
|
|
163
|
+
return;
|
|
164
|
+
const props = edgeProps(e);
|
|
165
|
+
out.push({
|
|
166
|
+
label: direction === "out" ? names.name(e.type) : names.inverseLabel(e.type),
|
|
167
|
+
relName: names.name(e.type),
|
|
168
|
+
hasInverse: names.hasInverse(e.type),
|
|
169
|
+
direction,
|
|
170
|
+
other,
|
|
171
|
+
props: inheritedFrom ? { ...props, inheritedFrom: displayName(inheritedFrom) } : props,
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
const own = queryGet(ont, node.id);
|
|
175
|
+
for (const e of own.out)
|
|
176
|
+
add(e, "out");
|
|
177
|
+
for (const e of own.in)
|
|
178
|
+
add(e, "in");
|
|
179
|
+
if (inherited) {
|
|
180
|
+
const have = new Set(out.map((r) => `${r.label}|${r.direction}|${r.other.id}`));
|
|
181
|
+
for (const c of classesOf(ont, node)) {
|
|
182
|
+
if (c.id === node.id)
|
|
183
|
+
continue;
|
|
184
|
+
for (const e of queryGet(ont, c.id).out) {
|
|
185
|
+
const target = ont.get(e.to);
|
|
186
|
+
if (target?.type !== "Instance" || isStructuralEdgeType(e.type))
|
|
187
|
+
continue; // only values that are facts about the members
|
|
188
|
+
const key = `${names.name(e.type)}|out|${target.id}`;
|
|
189
|
+
if (have.has(key))
|
|
190
|
+
continue;
|
|
191
|
+
have.add(key);
|
|
192
|
+
add(e, "out", c);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return out.sort((a, b) => a.label.localeCompare(b.label) || displayName(a.other).localeCompare(displayName(b.other)));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Resolves `preferredOver`, `PREFERRED_OVER` or `preferred over` to a relationship slot. `backwards` says
|
|
200
|
+
* the slot named is the inverse of the one that stores the edges, so it reads them against their stored direction.
|
|
201
|
+
*/
|
|
202
|
+
export function resolveRelationship(ont, ref) {
|
|
203
|
+
const want = squash(ref);
|
|
204
|
+
const slots = ont.ofType("Slot").filter((s) => ont.rel.spec(s.id) !== null);
|
|
205
|
+
const hit = slots.find((s) => squash(String(s.relType ?? "")) === want || squash(s.name) === want);
|
|
206
|
+
if (hit)
|
|
207
|
+
return { slot: hit, backwards: ont.rel.spec(hit.id).reverse };
|
|
208
|
+
const known = relationshipSlots(ont).map((s) => s.name).join(", ");
|
|
209
|
+
throw new OkbMcpError(`No relationship called "${ref}". Relationships in this ontology: ${known || "none"}.`);
|
|
210
|
+
}
|
|
211
|
+
/** Rules that govern the node itself. */
|
|
212
|
+
export const rulesGoverning = (ont, nodeId) => nodes(ont, ont.sources(nodeId, "GOVERNS")).filter((n) => n.type === "Rule");
|
|
213
|
+
export function describeRule(ont, rule) {
|
|
214
|
+
const b = bag(rule);
|
|
215
|
+
const status = b.verification?.status;
|
|
216
|
+
let caveat;
|
|
217
|
+
if (b.extractionConfidence === "corrected")
|
|
218
|
+
caveat = "corrected from the first draft";
|
|
219
|
+
else if (status && status !== "SUPPORTED")
|
|
220
|
+
caveat = `verification: ${status.toLowerCase()}`;
|
|
221
|
+
else if (b.extracted && !b.verification)
|
|
222
|
+
caveat = "not verified against its quote";
|
|
223
|
+
return {
|
|
224
|
+
id: rule.id,
|
|
225
|
+
modality: String(b.modality ?? ""),
|
|
226
|
+
statement: String(b.statement ?? b.name ?? rule.id),
|
|
227
|
+
caveat,
|
|
228
|
+
citations: citationsFor(ont, rule.id),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/** The passages a node cites, each with its source document and place in it. */
|
|
232
|
+
export function citationsFor(ont, nodeId) {
|
|
233
|
+
return nodes(ont, ont.targets(nodeId, "CITES"))
|
|
234
|
+
.filter((n) => n.type === "SourceLocation")
|
|
235
|
+
.map((loc) => {
|
|
236
|
+
const l = bag(loc);
|
|
237
|
+
const source = nodes(ont, ont.targets(loc.id, "PART_OF")).find((s) => s.type === "Source");
|
|
238
|
+
return {
|
|
239
|
+
quote: String(l.quote ?? ""),
|
|
240
|
+
source: source ? displayName(source) : "unknown source",
|
|
241
|
+
locator: String(l.locator ?? ""),
|
|
242
|
+
lines: typeof l.lines === "string" || typeof l.lines === "number" ? String(l.lines) : undefined,
|
|
243
|
+
link: typeof l.sourceLink === "string" ? l.sourceLink : typeof l.pageLink === "string" ? l.pageLink : undefined,
|
|
244
|
+
};
|
|
245
|
+
});
|
|
246
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { OkbMcpError } from "./errors.js";
|
|
2
|
+
export { loadForServing, type HeldBack, type ServingOptions } from "./serving.js";
|
|
3
|
+
export { createServer, SNAPSHOT_URI, type ServerOptions, type Snapshot } from "./server.js";
|
|
4
|
+
export { EVIDENCE_MODES, type Evidence } from "./tools.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// The public API, for embedding the server in another program. Anything not exported here is internal.
|
|
2
|
+
export { OkbMcpError } from "./errors.js";
|
|
3
|
+
export { loadForServing } from "./serving.js";
|
|
4
|
+
export { createServer, SNAPSHOT_URI } from "./server.js";
|
|
5
|
+
export { EVIDENCE_MODES } from "./tools.js";
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import type { Ontology } from "@ontology-kit/reader";
|
|
3
|
+
import { type Evidence } from "./tools.js";
|
|
4
|
+
export interface ServerOptions {
|
|
5
|
+
/** What tool results show of the evidence behind a rule. Default: the full quote. */
|
|
6
|
+
evidence?: Evidence;
|
|
7
|
+
/**
|
|
8
|
+
* Also serve `read_source`, which returns the text of a cited source document by heading or line range, and
|
|
9
|
+
* show each source's `localPath` in results. `root` is the ontology folder that each `localPath` is relative
|
|
10
|
+
* to: `loadForServing` returns it. Needs `evidence: "full"`. Default: off.
|
|
11
|
+
*/
|
|
12
|
+
readSource?: {
|
|
13
|
+
root: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Report which data this server loaded, as Eval Kit's snapshot resource: `eval-kit://snapshot`, served as
|
|
17
|
+
* JSON `{"id", "version"}`. It's a resource, not a tool, so the model never sees it. Default: not served.
|
|
18
|
+
*/
|
|
19
|
+
snapshot?: Snapshot;
|
|
20
|
+
}
|
|
21
|
+
export interface Snapshot {
|
|
22
|
+
id: string;
|
|
23
|
+
version: string;
|
|
24
|
+
}
|
|
25
|
+
/** The resource URI Eval Kit reads a server's snapshot report from. */
|
|
26
|
+
export declare const SNAPSHOT_URI = "eval-kit://snapshot";
|
|
27
|
+
/** This package's version, read from its package.json (one level above both src/ and dist/). */
|
|
28
|
+
export declare const VERSION: string;
|
|
29
|
+
/**
|
|
30
|
+
* Builds the server for an ontology. The ontology is served as given: to hold back rules that aren't
|
|
31
|
+
* verified, load it with `loadForServing`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createServer(ont: Ontology, { evidence, readSource: readSourceOptions, snapshot }?: ServerOptions): McpServer;
|