@ontology-kit/mcp 0.3.0-bootstrap.0 → 0.4.0-alpha.9

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/graph.js CHANGED
@@ -208,6 +208,55 @@ export function resolveRelationship(ont, ref) {
208
208
  const known = relationshipSlots(ont).map((s) => s.name).join(", ");
209
209
  throw new OkbMcpError(`No relationship called "${ref}". Relationships in this ontology: ${known || "none"}.`);
210
210
  }
211
+ // Property values as text -----------------------------------------------
212
+ /** Text that `splitValues` or the `get` tool's own annotations (`(from X)`, `(inherited from X)`) would misread, so it is written as a JSON string. */
213
+ const NEEDS_QUOTES = /, |^"|[\r\n]| — | \(inherited from | \((?:from|inherited from) [^)]*\)$/;
214
+ /** One value of a property as the `get` tool prints it. Text that would read as a list, a quote, a second line or an annotation is written as a JSON string, so ordinary values keep their plain form. */
215
+ function valueText(v) {
216
+ if (typeof v === "string")
217
+ return NEEDS_QUOTES.test(v) ? JSON.stringify(v) : v;
218
+ if (v && typeof v === "object")
219
+ return JSON.stringify(v);
220
+ return String(v);
221
+ }
222
+ /** A property's value or values, comma-separated, for `get`. `splitValues` is its inverse. */
223
+ export function showValues(value) {
224
+ return (Array.isArray(value) ? value : [value]).map(valueText).join(", ");
225
+ }
226
+ /**
227
+ * Reads the values `showValues` wrote from the start of `text`: split on ", " outside quoted strings. An unquoted value
228
+ * also ends at any of `stops` (text that follows the values on the line, such as an annotation or a description), and
229
+ * a quoted one may be followed by one. Returns the values and what is left after them.
230
+ */
231
+ export function readValues(text, stops = []) {
232
+ const values = [];
233
+ const after = [", ", ...stops].map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
234
+ const quotedAt = new RegExp(`^"(?:[^"\\\\]|\\\\.)*"(?=${after}|$)`);
235
+ let i = 0;
236
+ while (i <= text.length) {
237
+ const quoted = quotedAt.exec(text.slice(i))?.[0];
238
+ let token;
239
+ if (quoted !== undefined) {
240
+ token = JSON.parse(quoted);
241
+ i += quoted.length;
242
+ }
243
+ else {
244
+ const ends = [", ", ...stops].map((x) => text.indexOf(x, i)).filter((x) => x !== -1);
245
+ const end = ends.length ? Math.min(...ends) : text.length;
246
+ token = text.slice(i, end);
247
+ i = end;
248
+ }
249
+ values.push(token);
250
+ if (!text.startsWith(", ", i))
251
+ break;
252
+ i += 2; // the ", "
253
+ }
254
+ return { values, rest: text.slice(i) };
255
+ }
256
+ /** The values in `text` as `showValues` wrote them: split on ", " outside quoted strings. */
257
+ export function splitValues(text) {
258
+ return readValues(text).values;
259
+ }
211
260
  /** Rules that govern the node itself. */
212
261
  export const rulesGoverning = (ont, nodeId) => nodes(ont, ont.sources(nodeId, "GOVERNS")).filter((n) => n.type === "Rule");
213
262
  export function describeRule(ont, rule) {
package/dist/server.d.ts CHANGED
@@ -17,6 +17,15 @@ export interface ServerOptions {
17
17
  * JSON `{"id", "version"}`. It's a resource, not a tool, so the model never sees it. Default: not served.
18
18
  */
19
19
  snapshot?: Snapshot;
20
+ /**
21
+ * Which skills to serve through the MCP skills extension. `"bundled"` serves the skills this package ships
22
+ * (`query-kb`). `{ kb }` serves those plus the skill folders in `<kb>/skills/`, where `kb` is the ontology
23
+ * folder (`loadForServing` returns it as `root`); those are instructions the KB's author wrote, so pass it only
24
+ * for a KB you trust. `"none"` serves no skills and the server advertises no skills capability. Default: `"bundled"`.
25
+ */
26
+ skills?: "none" | "bundled" | {
27
+ kb: string;
28
+ };
20
29
  }
21
30
  export interface Snapshot {
22
31
  id: string;
@@ -30,4 +39,4 @@ export declare const VERSION: string;
30
39
  * Builds the server for an ontology. The ontology is served as given: to hold back rules that aren't
31
40
  * verified, load it with `loadForServing`.
32
41
  */
33
- export declare function createServer(ont: Ontology, { evidence, readSource: readSourceOptions, snapshot }?: ServerOptions): McpServer;
42
+ export declare function createServer(ont: Ontology, { evidence, readSource: readSourceOptions, snapshot, skills }?: ServerOptions): McpServer;
package/dist/server.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { z } from "zod";
5
5
  import { OkbMcpError } from "./errors.js";
6
+ import { loadSkills, serveSkills } from "./skills.js";
6
7
  import { readSource } from "./source.js";
7
8
  import { describeOntology, find, get, listRules, traverse } from "./tools.js";
8
9
  /** The resource URI Eval Kit reads a server's snapshot report from. */
@@ -39,7 +40,7 @@ function evidenceWording(evidence) {
39
40
  * Builds the server for an ontology. The ontology is served as given: to hold back rules that aren't
40
41
  * verified, load it with `loadForServing`.
41
42
  */
42
- export function createServer(ont, { evidence = "full", readSource: readSourceOptions, snapshot } = {}) {
43
+ export function createServer(ont, { evidence = "full", readSource: readSourceOptions, snapshot, skills = "bundled" } = {}) {
43
44
  const withReadSource = readSourceOptions !== undefined;
44
45
  if (withReadSource && !readSourceOptions.root)
45
46
  throw new OkbMcpError("read_source needs the ontology folder: pass `readSource: { root }`, where root is what loadForServing returns.");
@@ -123,5 +124,7 @@ export function createServer(ont, { evidence = "full", readSource: readSourceOpt
123
124
  const report = JSON.stringify({ id: snapshot.id, version: snapshot.version });
124
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 }] }));
125
126
  }
127
+ if (skills !== "none")
128
+ serveSkills(server, loadSkills(skills));
126
129
  return server;
127
130
  }
package/dist/serving.d.ts CHANGED
@@ -30,7 +30,7 @@ export declare function holdBack(nodes: readonly OkbNode[], edges: readonly Grap
30
30
  /**
31
31
  * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
32
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 resolved folder, which
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
34
  * `createServer` needs to read the documents that sources point to. Any okb format version the reader
35
35
  * loads works, including folders still on `nodes.json` and `edges.json`.
36
36
  */
package/dist/serving.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Loading a KB to serve it: the reader's `Ontology`, with everything that isn't verified held back.
2
2
  import path from "node:path";
3
- import { Ontology, edgeProps, OkbError } from "@ontology-kit/reader";
3
+ import { Ontology, edgeProps, findRoot, OkbError } from "@ontology-kit/reader";
4
4
  import { OkbMcpError } from "./errors.js";
5
5
  /** The test `okb export` uses: only a rule whose verification is SUPPORTED counts (an approved correction is recorded as SUPPORTED too). */
6
6
  export function isVerified(rule) {
@@ -42,7 +42,7 @@ export function holdBack(nodes, edges) {
42
42
  /**
43
43
  * Loads an ontology folder for serving. Unless `includeUnverified` is set, the returned ontology is a
44
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 resolved folder, which
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
46
  * `createServer` needs to read the documents that sources point to. Any okb format version the reader
47
47
  * loads works, including folders still on `nodes.json` and `edges.json`.
48
48
  */
@@ -56,7 +56,8 @@ export function loadForServing(folder, { includeUnverified = false } = {}) {
56
56
  throw new OkbMcpError(err.message);
57
57
  throw err;
58
58
  }
59
- const root = path.resolve(folder);
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);
60
61
  if (includeUnverified)
61
62
  return { ontology: full, held: { rules: 0, links: 0 }, root };
62
63
  const { nodes, edges, held } = holdBack(full.nodes, full.edges);
@@ -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 {};
@@ -0,0 +1,395 @@
1
+ // The `okb-mcp skills` subcommands: list the skills the server can serve, install the bundled ones, check what's installed.
2
+ // Reads skills with `skills.ts`, so the numbers are the ones the server serves. It doesn't use okb, which installs its own skills.
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { createInterface } from "node:readline";
6
+ import path from "node:path";
7
+ import { parseArgs } from "node:util";
8
+ import { OkbMcpError } from "./errors.js";
9
+ import { BUNDLED_SKILLS_DIR, isLinkedSkillsRoot, KB_SKILLS_FOLDER, loadSkill } from "./skills.js";
10
+ const USAGE = `Usage: okb-mcp skills [<ontology-folder>] [--json]
11
+ okb-mcp skills install [--dir <folder>] [--copy] [--force]
12
+ okb-mcp skills status [--dir <folder>] [--json]
13
+
14
+ okb-mcp skills [<ontology-folder>]
15
+ Lists the skills the server can serve: the bundled ones, and with a folder also the ones in its
16
+ skills/ folder. Those are instructions the KB's author wrote, and the server serves them only with
17
+ --skills all. Shows each one's source, file count, size, the digest of its SKILL.md and its
18
+ description. A skill that fails the server's checks is listed with the reason, and the exit code is 1.
19
+
20
+ okb-mcp skills install
21
+ Puts the bundled skills (today query-kb) where Claude Code and Cursor load them from, for a host
22
+ that doesn't support the MCP skills extension. It never installs a KB's own skills. By default each
23
+ skill is a link to the folder in this package, so updating the package updates the skill.
24
+ --dir <folder> the skills folder (default $OKB_SKILLS_DIR, else ~/.claude/skills)
25
+ --copy copy the folders instead of linking to them
26
+ --force replace without asking (for scripts and CI)
27
+ If something other than a link to this package is there (an older or edited copy, a folder that isn't
28
+ this skill, a link to somewhere else), it shows what it found and which files differ, and asks
29
+ "Replace it? (y/N)". Only y or yes continues; the old folder is moved to <skills folder>.backup/
30
+ (a link needs no backup). Without a terminal it refuses unless you pass --force.
31
+
32
+ okb-mcp skills status
33
+ Says for each bundled skill whether it's installed and whether its version matches this package.
34
+ Exits 1 when one is missing or out of date.
35
+ `;
36
+ const SUBCOMMANDS = ["install", "status"];
37
+ /** Where skills go when `--dir` isn't given: `$OKB_SKILLS_DIR`, else `~/.claude/skills`, as `okb skills install` does. */
38
+ export function defaultSkillsDir(env = process.env) {
39
+ return env.OKB_SKILLS_DIR || path.join(homedir(), ".claude", "skills");
40
+ }
41
+ function listing(skill, source) {
42
+ const main = skill.files.find((f) => f.uri === skill.uri);
43
+ return {
44
+ name: skill.name,
45
+ source,
46
+ files: skill.files.length,
47
+ bytes: skill.files.reduce((n, f) => n + f.size, 0),
48
+ digest: main.digest,
49
+ description: String(skill.frontmatter.description).trim(),
50
+ resources: skill.files.map((f) => ({ path: f.uri.slice(`skill://${skill.name}/`.length), digest: f.digest, size: f.size })),
51
+ };
52
+ }
53
+ /** The bundled skills and, for a KB folder, each skill in its `skills/` folder. A broken KB skill is listed with its reason. */
54
+ export function listSkills(kb) {
55
+ const out = [];
56
+ const bundled = new Set();
57
+ for (const e of readdirSync(BUNDLED_SKILLS_DIR, { withFileTypes: true })) {
58
+ if (!e.isDirectory() || e.name.startsWith("."))
59
+ continue;
60
+ const skill = loadSkill(path.join(BUNDLED_SKILLS_DIR, e.name)); // a broken bundled skill is a bug in the package, so let it throw
61
+ bundled.add(skill.name);
62
+ out.push(listing(skill, "bundled"));
63
+ }
64
+ if (kb) {
65
+ const dir = path.join(kb, KB_SKILLS_FOLDER);
66
+ if (isLinkedSkillsRoot(dir)) {
67
+ out.push({ name: KB_SKILLS_FOLDER, source: "kb", error: `${dir} is a symbolic link. The ${KB_SKILLS_FOLDER}/ folder has to be a real folder inside the KB.` });
68
+ }
69
+ else if (existsSync(dir)) {
70
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
71
+ if (e.name.startsWith("."))
72
+ continue;
73
+ const where = path.join(dir, e.name);
74
+ try {
75
+ if (!e.isDirectory() || lstatSync(where).isSymbolicLink())
76
+ throw new OkbMcpError(`${where} isn't a skill folder. ${KB_SKILLS_FOLDER}/ holds only folders, one per skill.`);
77
+ const skill = loadSkill(where);
78
+ if (bundled.has(skill.name))
79
+ throw new OkbMcpError(`The KB's skill "${skill.name}" has the name of a skill the server bundles. Rename its folder and \`name\`.`);
80
+ out.push(listing(skill, "kb"));
81
+ }
82
+ catch (err) {
83
+ if (!(err instanceof OkbMcpError))
84
+ throw err;
85
+ out.push({ name: e.name, source: "kb", error: err.message });
86
+ }
87
+ }
88
+ }
89
+ }
90
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
91
+ }
92
+ const size = (n) => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KiB`);
93
+ function describeListing(l) {
94
+ const label = l.source === "bundled" ? "bundled" : "from the KB";
95
+ if (l.error)
96
+ return [`${l.name} (${label}): invalid. ${l.error}`];
97
+ return [`${l.name} (${label}): ${l.files} file${l.files === 1 ? "" : "s"}, ${size(l.bytes)}, SKILL.md ${l.digest}`, ` ${l.description}`];
98
+ }
99
+ // ---------- install and status
100
+ /** The version a skill says it is: its `**Version X.Y.Z.**` line. */
101
+ function versionOf(dir) {
102
+ try {
103
+ return /^\*\*Version ([^\s*]+?)\.\*\*/m.exec(readFileSync(path.join(dir, "SKILL.md"), "utf8"))?.[1];
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ function tree(dir, base = "") {
110
+ return readdirSync(path.join(dir, base), { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? tree(dir, path.join(base, e.name)) : [path.join(base, e.name)])).sort();
111
+ }
112
+ function sameTree(a, b) {
113
+ const fa = tree(a);
114
+ const fb = tree(b);
115
+ return fa.length === fb.length && fa.every((f, i) => f === fb[i] && readFileSync(path.join(a, f)).equals(readFileSync(path.join(b, f))));
116
+ }
117
+ function inspect(name, dir, from) {
118
+ const target = path.join(dir, name);
119
+ const source = path.join(from, name);
120
+ const want = versionOf(source);
121
+ let st;
122
+ try {
123
+ st = lstatSync(target);
124
+ }
125
+ catch {
126
+ return { name, path: target, state: "missing", detail: "not installed" };
127
+ }
128
+ if (st.isSymbolicLink()) {
129
+ const to = path.resolve(dir, readlinkSync(target));
130
+ if (!existsSync(target))
131
+ return { name, path: target, state: "stale", how: "link", dangling: true, detail: `a link to ${to}, which no longer exists (an update moved the package?)` };
132
+ if (realpathSync(target) === realpathSync(source))
133
+ return { name, path: target, state: "current", how: "link", version: want, detail: `linked to this package, version ${want}` };
134
+ return { name, path: target, state: "stale", how: "link", version: versionOf(target), detail: `linked to ${to}, not to this package` };
135
+ }
136
+ const found = st.isDirectory() ? versionOf(target) : undefined;
137
+ if (!found)
138
+ return { name, path: target, state: "foreign", detail: st.isDirectory() ? "a folder that isn't this package's skill" : "a file, not a skill folder" };
139
+ if (found !== want)
140
+ return { name, path: target, state: "stale", how: "copy", version: found, detail: `a copy at version ${found}, this package is ${want}` };
141
+ if (!sameTree(target, source))
142
+ return { name, path: target, state: "modified", how: "copy", version: found, detail: `a copy at version ${found} whose files differ from this package's` };
143
+ return { name, path: target, state: "current", how: "copy", version: found, detail: `a copy of this package's skill, version ${want}` };
144
+ }
145
+ /** Whether install must ask before replacing this: anything that isn't missing, current, or a dangling link. */
146
+ function needsAsk(r) {
147
+ if (r.state === "foreign" || r.state === "modified")
148
+ return true;
149
+ return r.state === "stale" && !r.dangling;
150
+ }
151
+ /** `realpathSync` that also works for a folder that doesn't exist yet: the real path of its nearest existing ancestor, plus the rest. */
152
+ function realpathLoose(p) {
153
+ const rest = [];
154
+ let cur = path.resolve(p);
155
+ while (!existsSync(cur) && path.dirname(cur) !== cur) {
156
+ rest.unshift(path.basename(cur));
157
+ cur = path.dirname(cur);
158
+ }
159
+ return path.join(realpathSync(cur), ...rest);
160
+ }
161
+ /** Refuses a skills folder that is, or holds, this package's own `skills/` folder: installing there would replace the bundled skill with a link to itself. */
162
+ function refuseOwnFolder(dir) {
163
+ const real = realpathLoose(dir);
164
+ const bundled = realpathSync(BUNDLED_SKILLS_DIR);
165
+ if (real === bundled || bundled.startsWith(real + path.sep) || real.startsWith(bundled + path.sep)) {
166
+ const what = real === bundled ? "this package's own skills folder" : real.startsWith(bundled + path.sep) ? `inside this package's own skills folder (${bundled})` : `a folder that holds this package's own skills folder (${bundled})`;
167
+ throw new OkbMcpError(`${dir} is ${what}, so installing there would replace or break the bundled skills. Choose another skills folder with --dir.`);
168
+ }
169
+ }
170
+ function bundledNames(from) {
171
+ return readdirSync(from, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync(path.join(from, e.name, "SKILL.md"))).map((e) => e.name).sort();
172
+ }
173
+ export function skillsStatus(dir) {
174
+ return bundledNames(BUNDLED_SKILLS_DIR).map((n) => inspect(n, path.resolve(dir), BUNDLED_SKILLS_DIR));
175
+ }
176
+ /** Asks on the terminal, with `node:readline`. */
177
+ export const terminalAsk = (question) => new Promise((resolve) => {
178
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
179
+ let answered = false;
180
+ rl.on("close", () => {
181
+ if (!answered)
182
+ resolve(undefined);
183
+ });
184
+ rl.question(question, (answer) => {
185
+ answered = true;
186
+ rl.close();
187
+ resolve(answer);
188
+ });
189
+ });
190
+ /** Files that differ, only in the installed folder, only in the packaged one. */
191
+ function compare(found, source) {
192
+ const old = tree(found);
193
+ const now = tree(source);
194
+ return {
195
+ differ: old.filter((f) => now.includes(f) && !readFileSync(path.join(found, f)).equals(readFileSync(path.join(source, f)))),
196
+ onlyOld: old.filter((f) => !now.includes(f)),
197
+ onlyNew: now.filter((f) => !old.includes(f)),
198
+ };
199
+ }
200
+ /** Where a replaced folder is kept: a sibling of the skills folder, since a host loads every folder in it that has a SKILL.md. */
201
+ const backupRoot = (dir) => `${dir}.backup`;
202
+ const stamp = (d) => d.toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
203
+ /** Moves `from` to `to`, copying when they are on different filesystems. */
204
+ function moveTo(from, to) {
205
+ mkdirSync(path.dirname(to), { recursive: true });
206
+ try {
207
+ renameSync(from, to);
208
+ }
209
+ catch (err) {
210
+ if (err.code !== "EXDEV")
211
+ throw err;
212
+ cpSync(from, to, { recursive: true, verbatimSymlinks: true });
213
+ rmSync(from, { recursive: true, force: true });
214
+ }
215
+ }
216
+ /** What the person sees before the question: what is there, how it differs, what would change and what is kept. */
217
+ function explain(r, source, want, backup) {
218
+ const lines = [`${r.name}: ${r.path} is ${r.detail}.`];
219
+ let looked;
220
+ try {
221
+ looked = lstatSync(r.path).isSymbolicLink() ? realpathSync(r.path) : r.path;
222
+ if (!lstatSync(looked).isDirectory())
223
+ looked = undefined;
224
+ }
225
+ catch {
226
+ looked = undefined;
227
+ }
228
+ if (looked) {
229
+ const d = compare(looked, source);
230
+ if (d.differ.length)
231
+ lines.push(` Files that differ from the packaged skill: ${d.differ.join(", ")}`);
232
+ if (d.onlyOld.length)
233
+ lines.push(` Files only in the installed folder (the packaged skill doesn't have them): ${d.onlyOld.join(", ")}`);
234
+ if (d.onlyNew.length)
235
+ lines.push(` Files only in the packaged skill (missing from the installed one): ${d.onlyNew.join(", ")}`);
236
+ if (!d.differ.length && !d.onlyOld.length && !d.onlyNew.length)
237
+ lines.push(" Its files are the same as the packaged skill's.");
238
+ }
239
+ lines.push(` It would be replaced with ${want === "copy" ? "a copy of" : "a link to"} ${source}.`);
240
+ lines.push(backup ? ` The old one is moved, not deleted, and kept in ${backup}.` : " A link needs no backup: only the link is replaced, and what it points to isn't touched.");
241
+ return lines.join("\n");
242
+ }
243
+ /**
244
+ * Installs the bundled skills. Checks everything first, so a refusal or a "no" changes nothing. Something that would be replaced and might
245
+ * 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,
246
+ * once per skill. Without a terminal it is refused unless `force`. A replaced folder is kept in `<dir>.backup/`. Returns one line per skill.
247
+ */
248
+ export async function installSkills(dirOption, opts = {}) {
249
+ const dir = path.resolve(dirOption);
250
+ const want = opts.copy ? "copy" : "link";
251
+ const from = opts.source ?? BUNDLED_SKILLS_DIR;
252
+ const interactive = opts.interactive ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY));
253
+ const ask = opts.ask ?? terminalAsk;
254
+ const at = stamp((opts.now ?? (() => new Date()))());
255
+ refuseOwnFolder(dir);
256
+ const before = bundledNames(from).map((n) => inspect(n, dir, from));
257
+ const toAsk = before.filter(needsAsk);
258
+ const backups = new Map();
259
+ for (const r of toAsk)
260
+ if (!lstatSync(r.path).isSymbolicLink())
261
+ backups.set(r.name, path.join(backupRoot(dir), `${r.name}-${at}`));
262
+ if (toAsk.length && !opts.force) {
263
+ if (!interactive) {
264
+ const why = toAsk.map((r) => ` ${r.path}: ${r.detail}`).join("\n");
265
+ const them = toAsk.length === 1 ? "it" : "them";
266
+ throw new OkbMcpError(`Not installing: ${toAsk.length === 1 ? "this isn't" : "these aren't"} this package's to replace.\n${why}\nNothing was changed. Move ${them} away, run okb-mcp skills install in a terminal to be asked, or pass --force to replace ${them} and put the ${want === "copy" ? "copies" : "links"} in place. A replaced folder is kept in ${backupRoot(dir)}.`);
267
+ }
268
+ for (const r of toAsk) {
269
+ const answer = await ask(`${explain(r, path.join(from, r.name), want, backups.get(r.name))}\nReplace it? (y/N) `);
270
+ if (!/^\s*(y|yes)\s*$/i.test(answer ?? ""))
271
+ throw new OkbMcpError(`Not installing: the answer for ${r.name} wasn't y. Nothing was changed.`);
272
+ }
273
+ }
274
+ mkdirSync(dir, { recursive: true });
275
+ const lines = [];
276
+ for (const r of before) {
277
+ const source = path.join(from, r.name);
278
+ const verb = want === "copy" ? "copied" : "linked";
279
+ if (r.state === "current" && r.how === want) {
280
+ lines.push(`${r.name}: already ${verb}, version ${r.version}`);
281
+ continue;
282
+ }
283
+ const tmp = path.join(dir, `.${r.name}.okb-mcp-${process.pid}`);
284
+ rmSync(tmp, { recursive: true, force: true });
285
+ if (want === "copy")
286
+ cpSync(source, tmp, { recursive: true });
287
+ else
288
+ symlinkSync(source, tmp, "junction");
289
+ let kept = "";
290
+ if (r.state === "missing")
291
+ renameSync(tmp, r.path);
292
+ else {
293
+ // Move the old one aside, activate the new one, then dispose of the old: an interruption leaves one of them in place, never neither.
294
+ // Renaming a link moves the link, not its target.
295
+ const old = path.join(dir, `.${r.name}.okb-mcp-old-${process.pid}`);
296
+ rmSync(old, { recursive: true, force: true });
297
+ renameSync(r.path, old);
298
+ try {
299
+ renameSync(tmp, r.path);
300
+ }
301
+ catch (err) {
302
+ renameSync(old, r.path);
303
+ rmSync(tmp, { recursive: true, force: true });
304
+ throw err;
305
+ }
306
+ const backup = backups.get(r.name);
307
+ if (backup) {
308
+ moveTo(old, backup);
309
+ kept = `; the old one is kept in ${backup}`;
310
+ }
311
+ else
312
+ rmSync(old, { recursive: true, force: true }); // on a link this removes the link, not its target
313
+ }
314
+ lines.push(`${r.name}: ${verb}${r.state === "missing" ? "" : ` (replaced ${r.detail}${kept})`}`);
315
+ }
316
+ return lines;
317
+ }
318
+ // ---------- entry point
319
+ /** 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. */
320
+ export async function main(argv, io = {}) {
321
+ const sub = SUBCOMMANDS.includes(argv[0] ?? "") ? argv[0] : undefined;
322
+ const args = sub ? argv.slice(1) : argv;
323
+ let parsed;
324
+ try {
325
+ parsed = parseArgs({
326
+ args,
327
+ allowPositionals: true,
328
+ options: { dir: { type: "string" }, copy: { type: "boolean" }, force: { type: "boolean" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
329
+ });
330
+ }
331
+ catch (err) {
332
+ console.error(`${err.message}\n\n${USAGE}`);
333
+ return 2;
334
+ }
335
+ const { values, positionals } = parsed;
336
+ if (values.help) {
337
+ console.error(USAGE);
338
+ return 0;
339
+ }
340
+ const flagsFor = { install: ["dir", "copy", "force"], status: ["dir", "json"], list: ["json"] }[sub ?? "list"];
341
+ const stray = Object.keys(values).filter((k) => k !== "help" && !flagsFor.includes(k));
342
+ if (stray.length || positionals.length > (sub ? 0 : 1)) {
343
+ console.error(`${stray.length ? `--${stray[0]} doesn't go with ${sub ? `skills ${sub}` : "skills"}.` : "Too many arguments."}\n\n${USAGE}`);
344
+ return 2;
345
+ }
346
+ try {
347
+ if (!sub) {
348
+ const kb = positionals[0] ? path.resolve(positionals[0]) : undefined;
349
+ if (kb && !existsSync(kb))
350
+ throw new OkbMcpError(`${kb} doesn't exist.`);
351
+ const skills = listSkills(kb);
352
+ if (values.json)
353
+ console.log(JSON.stringify({ skills }, null, 2));
354
+ else {
355
+ for (const l of skills)
356
+ for (const line of describeListing(l))
357
+ console.log(line);
358
+ if (skills.some((l) => l.source === "kb")) {
359
+ console.log("\nThe KB's own skills are instructions its author wrote. The server serves them only with --skills all, so use that only for a KB you trust.");
360
+ }
361
+ else if (kb)
362
+ console.log(`\nThe KB has no skills of its own in ${path.join(kb, KB_SKILLS_FOLDER)}.`);
363
+ }
364
+ return skills.some((l) => l.error) ? 1 : 0;
365
+ }
366
+ const dir = values.dir ?? defaultSkillsDir();
367
+ if (sub === "install") {
368
+ const lines = await installSkills(dir, { copy: values.copy, force: values.force, ...io });
369
+ console.log(`Skills in ${path.resolve(dir)}`);
370
+ for (const l of lines)
371
+ console.log(` ${l}`);
372
+ console.log("Start a new session so the host loads them. The bundled skills only: a KB's own skills aren't installed.");
373
+ return 0;
374
+ }
375
+ const reports = skillsStatus(dir);
376
+ if (values.json)
377
+ console.log(JSON.stringify({ dir: path.resolve(dir), skills: reports }, null, 2));
378
+ else {
379
+ console.log(`Skills in ${path.resolve(dir)}`);
380
+ const label = { current: "up to date", stale: "out of date", modified: "modified", foreign: "not this skill", missing: "not installed" };
381
+ for (const r of reports)
382
+ console.log(` ${r.name}: ${label[r.state]}${r.state === "missing" ? "" : `, ${r.detail}`}`);
383
+ if (reports.some((r) => r.state !== "current"))
384
+ console.log("Run okb-mcp skills install to fix this. It asks before replacing a copy or a link to somewhere else; scripts pass --force.");
385
+ }
386
+ return reports.every((r) => r.state === "current") ? 0 : 1;
387
+ }
388
+ catch (err) {
389
+ if (err instanceof OkbMcpError) {
390
+ console.error(err.message);
391
+ return 2;
392
+ }
393
+ throw err;
394
+ }
395
+ }
@@ -0,0 +1,49 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ /** The capability name a host looks for. */
3
+ export declare const SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
4
+ /** The folder in a KB folder that holds the KB's own skills, one folder per skill. */
5
+ export declare const KB_SKILLS_FOLDER = "skills";
6
+ /** Limits. The file count and total size are the extension's own; the rest are ours. */
7
+ export declare const SKILL_LIMITS: {
8
+ /** Files in one skill, `SKILL.md` included. */
9
+ readonly files: 512;
10
+ /** Total bytes of one skill's files (16 MiB). */
11
+ readonly bytes: number;
12
+ /** Bytes in `SKILL.md`, because a host puts the whole file in the agent's context. */
13
+ readonly skillMd: 100000;
14
+ readonly nameLength: 64;
15
+ readonly descriptionLength: 1024;
16
+ };
17
+ interface SkillFile {
18
+ uri: string;
19
+ bytes: Buffer;
20
+ digest: string;
21
+ size: number;
22
+ }
23
+ export interface Skill {
24
+ name: string;
25
+ uri: string;
26
+ frontmatter: Record<string, unknown>;
27
+ files: SkillFile[];
28
+ }
29
+ /** The same folder as a path. */
30
+ export declare const BUNDLED_SKILLS_DIR: string;
31
+ /** Reads and checks one skill folder. Throws `OkbMcpError` naming the folder and what's wrong. */
32
+ export declare function loadSkill(dir: string): Skill;
33
+ /** The KB's `skills/` folder as a link: it could lead anywhere, so it is refused as a skill link inside it is. */
34
+ export declare function isLinkedSkillsRoot(skillsDir: string): boolean;
35
+ /** The skill sets the CLI offers, as `--skills` values. */
36
+ export declare const SKILL_SETS: readonly ["none", "bundled", "all"];
37
+ /** The names of the skill folders in `<kbRoot>/skills/`, sorted, without reading or checking them. */
38
+ export declare function kbSkillNames(kbRoot: string): string[];
39
+ /**
40
+ * The skills to serve: the ones this package bundles, plus, for `{ kb }`, those in `<kb>/skills/`. Only the sets
41
+ * asked for are read, so a broken KB skill can't stop a server that doesn't serve them. Throws `OkbMcpError` if
42
+ * a skill that is read is invalid or two share a name.
43
+ */
44
+ export declare function loadSkills(set?: "bundled" | {
45
+ kb: string;
46
+ }): Skill[];
47
+ /** Declares the extension on a server, answers `skills/list` and `skills/get`, and serves each file with `resources/read`. */
48
+ export declare function serveSkills(server: McpServer, skills: readonly Skill[]): void;
49
+ export {};