@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/dist/server.js ADDED
@@ -0,0 +1,130 @@
1
+ // The MCP server: five tools over an okb ontology, and read_source when asked. Started by cli.ts.
2
+ import { readFileSync } from "node:fs";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { z } from "zod";
5
+ import { OkbMcpError } from "./errors.js";
6
+ import { loadSkills, serveSkills } from "./skills.js";
7
+ import { readSource } from "./source.js";
8
+ import { describeOntology, find, get, listRules, traverse } from "./tools.js";
9
+ /** The resource URI Eval Kit reads a server's snapshot report from. */
10
+ export const SNAPSHOT_URI = "eval-kit://snapshot";
11
+ /** This package's version, read from its package.json (one level above both src/ and dist/). */
12
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
+ /** Wording for the tool descriptions, which the model reads: they must match what the results actually contain. */
14
+ function evidenceWording(evidence) {
15
+ switch (evidence) {
16
+ case "full":
17
+ return {
18
+ search: "names, descriptions, rule statements and quoted source text",
19
+ get: "the rules that govern it, and the verbatim source passages behind them",
20
+ rules: "the verbatim quote it came from",
21
+ ruleQuery: "Words to look for in the rule or its quote",
22
+ };
23
+ case "locator":
24
+ return {
25
+ search: "names, descriptions and rule statements",
26
+ get: "the rules that govern it, and where in the source documents each came from",
27
+ rules: "where in the source documents it came from",
28
+ ruleQuery: "Words to look for in the rule",
29
+ };
30
+ case "none":
31
+ return {
32
+ search: "names, descriptions and rule statements",
33
+ get: "and the rules that govern it",
34
+ rules: "its statement",
35
+ ruleQuery: "Words to look for in the rule",
36
+ };
37
+ }
38
+ }
39
+ /**
40
+ * Builds the server for an ontology. The ontology is served as given: to hold back rules that aren't
41
+ * verified, load it with `loadForServing`.
42
+ */
43
+ export function createServer(ont, { evidence = "full", readSource: readSourceOptions, snapshot, skills = "bundled" } = {}) {
44
+ const withReadSource = readSourceOptions !== undefined;
45
+ if (withReadSource && !readSourceOptions.root)
46
+ throw new OkbMcpError("read_source needs the ontology folder: pass `readSource: { root }`, where root is what loadForServing returns.");
47
+ if (withReadSource && evidence !== "full") {
48
+ throw new OkbMcpError(`read_source returns the documents' own text, quotes included, so it can't be served with evidence "${evidence}". Use "full", or leave read_source off.`);
49
+ }
50
+ const name = String(ont.meta.name || "ontology");
51
+ const words = evidenceWording(evidence);
52
+ const server = new McpServer({ name: `okb-${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`, version: VERSION });
53
+ /** Runs a tool, returning ordinary mistakes (unknown names) to the model as tool errors it can act on. */
54
+ const run = (fn) => {
55
+ try {
56
+ return { content: [{ type: "text", text: fn() }] };
57
+ }
58
+ catch (err) {
59
+ if (err instanceof OkbMcpError)
60
+ return { content: [{ type: "text", text: err.message }], isError: true };
61
+ throw err;
62
+ }
63
+ };
64
+ server.registerTool("describe_ontology", {
65
+ description: `Overview of the ${name} knowledge base: what it covers, the class hierarchy, properties, relationships and how many rules it holds. Call this first to learn what exists and what to search for.`,
66
+ }, async () => run(() => describeOntology(ont, evidence)));
67
+ server.registerTool("find", {
68
+ description: `Search or filter the knowledge base. Free-text \`query\` matches ${words.search}. ` +
69
+ "`class` lists the members of a class (including subclasses). `where` filters on values the thing has: " +
70
+ "where={shippedIn: \"lumen-web\"}, or \"*\" for any value. `allows` filters classes by the values their properties permit: " +
71
+ "allows={size: \"large\"} finds components that support a large size. Abstract categories are left out of filtered results, so you get the " +
72
+ "members. Use this for 'which ...' and 'list every ...' questions.",
73
+ inputSchema: {
74
+ query: z.string().optional().describe("Words to search for"),
75
+ type: z.enum(["class", "instance", "slot", "rule", "source"]).optional().describe("Only return this kind of thing"),
76
+ class: z.string().optional().describe("Only members (and subclasses) of this class"),
77
+ where: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional()
78
+ .describe("Property or relationship name → the value it has (\"*\" for any value)"),
79
+ allows: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional()
80
+ .describe("Property name → a value the class permits (\"*\" for classes that have the property)"),
81
+ limit: z.number().int().min(1).max(200).optional().describe("Maximum results (default 25)"),
82
+ },
83
+ }, async (args) => run(() => find(ont, args, evidence, withReadSource)));
84
+ server.registerTool("get", {
85
+ description: "Everything the knowledge base says about one class, instance, property, relationship, rule or source: description, properties, " +
86
+ `relationships (with conditions), ${words.get}. Accepts a name or id.`,
87
+ inputSchema: { name: z.string().describe("Name or id, such as Button, lumen-web, or rule.modals-must-trap-focus-while-open") },
88
+ }, async ({ name }) => run(() => get(ont, name, evidence, withReadSource)));
89
+ server.registerTool("traverse", {
90
+ description: "Follow one relationship from one or more starting points. Use for questions that connect things " +
91
+ "('what is preferred over X', 'what is built on Y'). `depth` follows the relationship further (up to 3).",
92
+ inputSchema: {
93
+ from: z.array(z.string()).min(1).describe("Names of the starting classes or instances"),
94
+ relationship: z.string().describe("Relationship name, such as preferredOver (see describe_ontology)"),
95
+ direction: z.enum(["out", "in"]).optional().describe("out follows links away from the start; in reads them backwards"),
96
+ depth: z.number().int().min(1).max(3).optional().describe("How many hops (default 1)"),
97
+ },
98
+ }, async (args) => run(() => traverse(ont, args)));
99
+ server.registerTool("list_rules", {
100
+ description: `List documented rules and recommendations, each with its modality (MUST, SHOULD, MUST_NOT...) and ${words.rules}. ` +
101
+ "Filter by what it governs, by modality, or by text. Rules from parent classes are included for a class.",
102
+ inputSchema: {
103
+ about: z.string().optional().describe("Class or instance the rules should govern"),
104
+ modality: z.string().optional().describe("MUST, MUST_NOT, SHOULD or MAY"),
105
+ query: z.string().optional().describe(words.ruleQuery),
106
+ limit: z.number().int().min(1).max(100).optional().describe("Maximum rules (default 25)"),
107
+ },
108
+ }, async (args) => run(() => listRules(ont, args, evidence)));
109
+ if (withReadSource) {
110
+ server.registerTool("read_source", {
111
+ description: "Read the original text of a source document: one section by heading, or a range of lines. Use the document, heading and " +
112
+ "line numbers that other results cite. With neither heading nor lines it returns the document's outline. Long sections " +
113
+ "are cut off with a note saying which lines to ask for next.",
114
+ inputSchema: {
115
+ source: z.string().describe("Name of the source document, such as Button"),
116
+ heading: z.string().optional().describe("Heading to read, or a path such as \"Examples › Grow Prop\""),
117
+ lines: z.string().optional().describe("Line range such as \"40-72\", or one line"),
118
+ },
119
+ }, async (args) => run(() => readSource(ont, readSourceOptions.root, args)));
120
+ }
121
+ if (snapshot) {
122
+ if (!snapshot.id || !snapshot.version)
123
+ throw new OkbMcpError("A snapshot needs a non-empty id and version.");
124
+ const report = JSON.stringify({ id: snapshot.id, version: snapshot.version });
125
+ server.registerResource("snapshot", SNAPSHOT_URI, { title: "Snapshot", description: "The data snapshot this server serves, for an eval harness to verify.", mimeType: "application/json" }, (uri) => ({ contents: [{ uri: uri.href, mimeType: "application/json", text: report }] }));
126
+ }
127
+ if (skills !== "none")
128
+ serveSkills(server, loadSkills(skills));
129
+ return server;
130
+ }
@@ -0,0 +1,41 @@
1
+ import { Ontology, type GraphEdge, type OkbNode } from "@ontology-kit/reader";
2
+ /** What was left out of the served ontology because it isn't verified. */
3
+ export interface HeldBack {
4
+ rules: number;
5
+ /** Relationship links justified only by a held-back rule. */
6
+ links: number;
7
+ }
8
+ export interface ServingOptions {
9
+ /**
10
+ * Serve rules that haven't been verified against their quote. By default they're held back, as
11
+ * `okb export` does: a rule nobody has checked shouldn't reach an agent as if it were fact.
12
+ */
13
+ includeUnverified?: boolean;
14
+ }
15
+ /** The test `okb export` uses: only a rule whose verification is SUPPORTED counts (an approved correction is recorded as SUPPORTED too). */
16
+ export declare function isVerified(rule: OkbNode): boolean;
17
+ /**
18
+ * Removes every trace of the rules that aren't verified: the rule and its edges (GOVERNS, CITES,
19
+ * REFINES, FULFILLS), relationship links whose `rule` edge property points at it, and quotes that only
20
+ * held-back rules cite (otherwise a source listing would still show the text).
21
+ *
22
+ * A relationship is stored as one edge per link, an inverse pair included, so dropping the edge drops
23
+ * the link from both ends.
24
+ */
25
+ export declare function holdBack(nodes: readonly OkbNode[], edges: readonly GraphEdge[]): {
26
+ nodes: OkbNode[];
27
+ edges: GraphEdge[];
28
+ held: HeldBack;
29
+ };
30
+ /**
31
+ * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
32
+ * view of the folder without the rules that aren't verified (see `holdBack`), so the tools never need to
33
+ * filter and nothing can leak. `held` says how much was left out. `root` is the folder that holds `okb.json` (the reader looks in the parents of the path given), which
34
+ * `createServer` needs to read the documents that sources point to. Any okb format version the reader
35
+ * loads works, including folders still on `nodes.json` and `edges.json`.
36
+ */
37
+ export declare function loadForServing(folder: string, { includeUnverified }?: ServingOptions): {
38
+ ontology: Ontology;
39
+ held: HeldBack;
40
+ root: string;
41
+ };
@@ -0,0 +1,67 @@
1
+ // Loading a KB to serve it: the reader's `Ontology`, with everything that isn't verified held back.
2
+ import path from "node:path";
3
+ import { Ontology, edgeProps, findRoot, OkbError } from "@ontology-kit/reader";
4
+ import { OkbMcpError } from "./errors.js";
5
+ /** The test `okb export` uses: only a rule whose verification is SUPPORTED counts (an approved correction is recorded as SUPPORTED too). */
6
+ export function isVerified(rule) {
7
+ return rule.type === "Rule" && rule.verification?.status === "SUPPORTED";
8
+ }
9
+ /**
10
+ * Removes every trace of the rules that aren't verified: the rule and its edges (GOVERNS, CITES,
11
+ * REFINES, FULFILLS), relationship links whose `rule` edge property points at it, and quotes that only
12
+ * held-back rules cite (otherwise a source listing would still show the text).
13
+ *
14
+ * A relationship is stored as one edge per link, an inverse pair included, so dropping the edge drops
15
+ * the link from both ends.
16
+ */
17
+ export function holdBack(nodes, edges) {
18
+ const hidden = new Set(nodes.filter((n) => n.type === "Rule" && !isVerified(n)).map((n) => n.id));
19
+ if (hidden.size === 0)
20
+ return { nodes: [...nodes], edges: [...edges], held: { rules: 0, links: 0 } };
21
+ const citers = new Map();
22
+ for (const e of edges)
23
+ if (e.type === "CITES")
24
+ (citers.get(e.to) ?? citers.set(e.to, []).get(e.to)).push(e.from);
25
+ const orphanQuotes = new Set(nodes
26
+ .filter((n) => n.type === "SourceLocation" && (citers.get(n.id) ?? []).length > 0 && citers.get(n.id).every((c) => hidden.has(c)))
27
+ .map((n) => n.id));
28
+ const gone = (id) => hidden.has(id) || orphanQuotes.has(id);
29
+ let links = 0;
30
+ const kept = edges.filter((e) => {
31
+ if (gone(e.from) || gone(e.to))
32
+ return false;
33
+ const rule = edgeProps(e).rule;
34
+ if (typeof rule === "string" && hidden.has(rule)) {
35
+ links++;
36
+ return false;
37
+ }
38
+ return true;
39
+ });
40
+ return { nodes: nodes.filter((n) => !gone(n.id)), edges: kept, held: { rules: hidden.size, links } };
41
+ }
42
+ /**
43
+ * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
44
+ * view of the folder without the rules that aren't verified (see `holdBack`), so the tools never need to
45
+ * filter and nothing can leak. `held` says how much was left out. `root` is the folder that holds `okb.json` (the reader looks in the parents of the path given), which
46
+ * `createServer` needs to read the documents that sources point to. Any okb format version the reader
47
+ * loads works, including folders still on `nodes.json` and `edges.json`.
48
+ */
49
+ export function loadForServing(folder, { includeUnverified = false } = {}) {
50
+ let full;
51
+ try {
52
+ full = Ontology.load(folder);
53
+ }
54
+ catch (err) {
55
+ if (err instanceof OkbError)
56
+ throw new OkbMcpError(err.message);
57
+ throw err;
58
+ }
59
+ // `Ontology.load` walks up to the folder that holds okb.json, so the documents and skills are read from there too.
60
+ const root = findRoot(folder) ?? path.resolve(folder);
61
+ if (includeUnverified)
62
+ return { ontology: full, held: { rules: 0, links: 0 }, root };
63
+ const { nodes, edges, held } = holdBack(full.nodes, full.edges);
64
+ if (held.rules === 0)
65
+ return { ontology: full, held, root };
66
+ return { ontology: Ontology.fromData(nodes, edges, full.manifest), held, root };
67
+ }
@@ -0,0 +1,65 @@
1
+ /** Where skills go when `--dir` isn't given: `$OKB_SKILLS_DIR`, else `~/.claude/skills`, as `okb skills install` does. */
2
+ export declare function defaultSkillsDir(env?: NodeJS.ProcessEnv): string;
3
+ export interface SkillListing {
4
+ name: string;
5
+ source: "bundled" | "kb";
6
+ /** Why the server would refuse it; the other fields are then absent. */
7
+ error?: string;
8
+ files?: number;
9
+ bytes?: number;
10
+ /** The digest of SKILL.md, as `skills/list` reports it. */
11
+ digest?: string;
12
+ description?: string;
13
+ /** Every file with its digest and size, as `skills/list` reports them. */
14
+ resources?: {
15
+ path: string;
16
+ digest: string;
17
+ size: number;
18
+ }[];
19
+ }
20
+ /** The bundled skills and, for a KB folder, each skill in its `skills/` folder. A broken KB skill is listed with its reason. */
21
+ export declare function listSkills(kb?: string): SkillListing[];
22
+ /**
23
+ * - `current`: installed, at this package's version and files.
24
+ * - `stale`: a link elsewhere, a broken link, or a copy at another version. Only a broken link is replaced without `--force`.
25
+ * - `modified`: a copy at this version whose files differ.
26
+ * - `foreign`: something that isn't this skill. Install leaves it alone unless told to `--force`.
27
+ * - `missing`: not installed.
28
+ */
29
+ type State = "current" | "stale" | "modified" | "foreign" | "missing";
30
+ interface Report {
31
+ name: string;
32
+ path: string;
33
+ state: State;
34
+ how?: "link" | "copy";
35
+ version?: string;
36
+ /** A link whose target is gone: the one stale case that is safe to replace without `--force`. */
37
+ dangling?: boolean;
38
+ detail: string;
39
+ }
40
+ export declare function skillsStatus(dir: string): Report[];
41
+ /** Gives the answer to a question, or `undefined` when the input ended. Tests pass their own. */
42
+ export type Ask = (question: string) => Promise<string | undefined>;
43
+ /** Asks on the terminal, with `node:readline`. */
44
+ export declare const terminalAsk: Ask;
45
+ export interface InstallOptions {
46
+ copy?: boolean;
47
+ force?: boolean;
48
+ /** Where answers come from. The default reads the terminal. */
49
+ ask?: Ask;
50
+ /** Whether there is a person to ask. The default is that both stdin and stdout are terminals. */
51
+ interactive?: boolean;
52
+ /** The clock for the backup folder's name. */
53
+ now?: () => Date;
54
+ /** The folder holding the skills to install. The default is this package's own; tests use another. */
55
+ source?: string;
56
+ }
57
+ /**
58
+ * Installs the bundled skills. Checks everything first, so a refusal or a "no" changes nothing. Something that would be replaced and might
59
+ * lose something (an older or edited copy, a folder that isn't this skill, a link to somewhere else) is shown and the person is asked,
60
+ * once per skill. Without a terminal it is refused unless `force`. A replaced folder is kept in `<dir>.backup/`. Returns one line per skill.
61
+ */
62
+ export declare function installSkills(dirOption: string, opts?: InstallOptions): Promise<string[]>;
63
+ /** Runs a `skills` subcommand and returns the exit code: 0 on success, 1 for an invalid or missing skill, 2 on a usage error or refusal. */
64
+ export declare function main(argv: string[], io?: Pick<InstallOptions, "ask" | "interactive" | "now">): Promise<number>;
65
+ export {};