@edgegap/mcp 0.7.2 → 0.10.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.
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Finds the copies of the Edgegap skills installed on this machine and updates
3
+ * them. Local (stdio) server only: it reads the developer's home and project
4
+ * folders and can run their package managers, which neither the hosted Worker
5
+ * nor a self-hosted container can or should do.
6
+ *
7
+ * Updates come from two places only: the developer's own package manager (the
8
+ * skills CLI, `claude plugin update`), or the files bundled in this release of
9
+ * @edgegap/mcp. Skill text is never downloaded here.
10
+ */
11
+ import { execFile } from 'node:child_process';
12
+ import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
13
+ import { homedir } from 'node:os';
14
+ import { dirname, join, resolve, sep } from 'node:path';
15
+ import { SKILLS_PACK } from './skills.js';
16
+ import { SKILL_NAME_RE, compareVersions, skillVersionOf } from './skillsversion.js';
17
+ export function defaultSkillsEnv() {
18
+ return {
19
+ home: homedir(),
20
+ cwd: process.cwd(),
21
+ platform: process.platform,
22
+ readText: (path) => readFile(path, 'utf8').catch(() => undefined),
23
+ writeText: async (path, text) => {
24
+ await mkdir(dirname(path), { recursive: true });
25
+ await writeFile(path, text, 'utf8');
26
+ },
27
+ isManaged: async (dir) => {
28
+ const link = await lstat(dir).then((s) => s.isSymbolicLink()).catch(() => false);
29
+ const git = await lstat(join(dir, '.git')).then(() => true).catch(() => false);
30
+ return link || git;
31
+ },
32
+ run: (cmd, args, cwd) => new Promise((resolvePromise, reject) => {
33
+ // npx and claude are .cmd shims on Windows, which only start through a
34
+ // shell. Every argument here is a fixed flag or a name matching
35
+ // SKILL_NAME_RE, so nothing reaches the shell that could be parsed.
36
+ const win = process.platform === 'win32';
37
+ const child = execFile(cmd, args, {
38
+ cwd,
39
+ shell: win,
40
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', CI: '1' },
41
+ timeout: 120_000,
42
+ killSignal: 'SIGKILL',
43
+ maxBuffer: 4 * 1024 * 1024,
44
+ windowsHide: true,
45
+ }, (err, stdout, stderr) => {
46
+ const out = `${stdout}${stderr}`.replace(/\x1b\[[0-9;?]*[A-Za-z]|\r/g, '').trim();
47
+ if (err)
48
+ reject(new Error(`${cmd} ${args.join(' ')} failed: ${err.message}\n${out}`));
49
+ else
50
+ resolvePromise(out);
51
+ });
52
+ // A prompting CLI fails at once on a closed stdin instead of hanging until the timeout.
53
+ child.stdin?.end();
54
+ }),
55
+ };
56
+ }
57
+ const SOURCE_RE = /^(https:\/\/github\.com\/|git@github\.com:|github:)?edgegap\/(llm-agent-skills|edgegap-agent-skills)(\.git)?\/?$/i;
58
+ // The skills CLI keeps one copy in .agents/skills when it installs for several
59
+ // agents, and copies into the agent's own folder when it installs for one.
60
+ const SKILL_DIRS = ['.agents/skills', '.claude/skills', '.codex/skills', '.cursor/skills', '.config/opencode/skills'];
61
+ const PLUGIN_ID = 'edgegap@edgegap';
62
+ function parseJson(text) {
63
+ if (!text)
64
+ return undefined;
65
+ try {
66
+ return JSON.parse(text);
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /** Skill names a skills CLI lock file records as coming from the Edgegap skills repo. */
73
+ function namesInLock(text) {
74
+ const lock = parseJson(text);
75
+ return Object.entries(lock?.skills ?? {})
76
+ .filter(([name, s]) => SKILL_NAME_RE.test(name) && (SOURCE_RE.test(s?.source ?? '') || SOURCE_RE.test(s?.sourceUrl ?? '')))
77
+ .map(([name]) => name)
78
+ .sort();
79
+ }
80
+ /** The oldest copy of a skill under root's skill folders, so one stale copy still counts. */
81
+ async function readCopies(env, root, name) {
82
+ let oldest;
83
+ for (const d of SKILL_DIRS) {
84
+ const dir = join(root, d, name);
85
+ const text = await env.readText(join(dir, 'SKILL.md'));
86
+ if (text === undefined)
87
+ continue;
88
+ const version = skillVersionOf(text);
89
+ if (!oldest || (version && (!oldest.version || compareVersions(version, oldest.version) < 0)))
90
+ oldest = { name, version, dir };
91
+ }
92
+ return oldest;
93
+ }
94
+ async function cliInstall(env, kind, where, lockPath, root) {
95
+ const names = namesInLock(await env.readText(lockPath));
96
+ if (names.length === 0)
97
+ return undefined;
98
+ const skills = await Promise.all(names.map(async (n) => (await readCopies(env, root, n)) ?? { name: n, dir: join(root, SKILL_DIRS[0], n) }));
99
+ return { kind, where, skills };
100
+ }
101
+ async function pluginInstall(env) {
102
+ const registry = parseJson(await env.readText(join(env.home, '.claude', 'plugins', 'installed_plugins.json')));
103
+ const installPath = registry?.plugins?.[PLUGIN_ID]?.[0]?.installPath;
104
+ if (!installPath)
105
+ return undefined;
106
+ const skills = [];
107
+ for (const s of SKILLS_PACK.skills) {
108
+ const dir = join(installPath, 'skills', s.name);
109
+ const text = await env.readText(join(dir, 'SKILL.md'));
110
+ if (text !== undefined)
111
+ skills.push({ name: s.name, version: skillVersionOf(text), dir });
112
+ }
113
+ return { kind: 'claude-plugin', where: `Claude Code plugin ${PLUGIN_ID}`, skills };
114
+ }
115
+ /** Skills copied by hand into an agent's skills folder: no lock file, no plugin. */
116
+ async function copiedSkills(env, root, where, claimed) {
117
+ const found = [];
118
+ for (const d of SKILL_DIRS) {
119
+ const skills = [];
120
+ for (const s of SKILLS_PACK.skills) {
121
+ const dir = join(root, d, s.name);
122
+ if (claimed.has(dir))
123
+ continue;
124
+ const text = await env.readText(join(dir, 'SKILL.md'));
125
+ // Only the Edgegap skill of that name, not someone's own skill that reuses it.
126
+ if (text === undefined || !text.includes(`name: ${s.name}`))
127
+ continue;
128
+ skills.push({ name: s.name, version: skillVersionOf(text), dir });
129
+ }
130
+ if (skills.length)
131
+ found.push({ kind: 'copy', where: `${where} ${join(root, d)}`, skills });
132
+ }
133
+ return found;
134
+ }
135
+ /** Every install of the Edgegap skills this server can see: user-wide, this project, and the Claude Code plugin. */
136
+ export async function findSkillsInstalls(env) {
137
+ const managed = (await Promise.all([
138
+ cliInstall(env, 'skills-cli-global', 'skills CLI, user-wide', join(env.home, '.agents', '.skill-lock.json'), env.home),
139
+ cliInstall(env, 'skills-cli-project', 'skills CLI, this project', join(env.cwd, 'skills-lock.json'), env.cwd),
140
+ pluginInstall(env),
141
+ ])).filter((i) => i !== undefined);
142
+ // A skills CLI install writes into the same folders as a hand copy; count it once.
143
+ const claimed = new Set();
144
+ for (const i of managed) {
145
+ for (const s of i.skills) {
146
+ for (const root of [env.home, env.cwd])
147
+ for (const d of SKILL_DIRS)
148
+ claimed.add(join(root, d, s.name));
149
+ }
150
+ }
151
+ const copies = [
152
+ ...(await copiedSkills(env, env.home, 'copied user-wide into', claimed)),
153
+ ...(resolve(env.cwd) !== resolve(env.home) ? await copiedSkills(env, env.cwd, 'copied into this project,', claimed) : []),
154
+ ];
155
+ return [...managed, ...copies];
156
+ }
157
+ /** The commands that update a managed install, as argv lists. Copies have none. */
158
+ export function updateCommands(install, outdated) {
159
+ const names = outdated.filter((n) => SKILL_NAME_RE.test(n));
160
+ switch (install.kind) {
161
+ case 'skills-cli-global':
162
+ return [['npx', '-y', 'skills', 'update', ...names, '-g', '-y']];
163
+ case 'skills-cli-project':
164
+ return [['npx', '-y', 'skills', 'update', ...names, '-p', '-y']];
165
+ case 'claude-plugin':
166
+ return [
167
+ ['claude', 'plugin', 'marketplace', 'update', 'edgegap'],
168
+ ['claude', 'plugin', 'update', PLUGIN_ID],
169
+ ];
170
+ case 'copy':
171
+ return [];
172
+ }
173
+ }
174
+ /**
175
+ * Rewrites a hand-copied skill from the files bundled in this release. Files
176
+ * the developer added are left alone. Refused for symlinks and git checkouts:
177
+ * those are someone's working copy, not an install.
178
+ */
179
+ export async function replaceFromBundle(env, skill) {
180
+ const bundled = SKILLS_PACK.skills.find((s) => s.name === skill.name);
181
+ if (!bundled)
182
+ throw new Error(`${skill.name} is not in the bundled pack`);
183
+ if (await env.isManaged(skill.dir)) {
184
+ throw new Error(`${skill.dir} is a symlink or a git checkout, so it was left alone; update it with git`);
185
+ }
186
+ const root = resolve(skill.dir);
187
+ for (const f of bundled.files) {
188
+ const target = resolve(root, ...f.path.split('/'));
189
+ if (!target.startsWith(root + sep))
190
+ throw new Error(`refused to write outside ${root}: ${f.path}`);
191
+ await env.writeText(target, f.content);
192
+ }
193
+ return `${skill.name} ${skill.version ?? '?'} → ${bundled.version} (${bundled.files.length} files from @edgegap/mcp's bundle)`;
194
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Which Edgegap skills pack is the latest, so the skill tools can say when
3
+ * this server, or a copy of the skills on the developer's machine, is behind.
4
+ *
5
+ * Reads only version numbers from github.com/edgegap/llm-agent-skills, never
6
+ * skill text: updated skills reach agents through this server's own release
7
+ * (the bundle in src/skills.generated.ts) or the developer's package manager,
8
+ * not through anything fetched at run time. Uses only fetch, so the hosted
9
+ * Worker can run it too.
10
+ */
11
+ import { SKILLS_PACK } from './skills.js';
12
+ /** raw.githubusercontent.com root of the skills repo's main branch. */
13
+ export const DEFAULT_SKILLS_RAW = 'https://raw.githubusercontent.com/edgegap/llm-agent-skills/main';
14
+ /** Skill names as the pack writes them; anything else is not looked up. */
15
+ export const SKILL_NAME_RE = /^edgegap(?:-[a-z0-9]+)*$/;
16
+ /** Turns EDGEGAP_SKILLS_CHECK and EDGEGAP_SKILLS_RAW_URL into options. */
17
+ export function skillsCheckFromEnv(env) {
18
+ const off = /^(0|off|false|no)$/i.test(env.EDGEGAP_SKILLS_CHECK?.trim() ?? '');
19
+ const raw = env.EDGEGAP_SKILLS_RAW_URL?.trim();
20
+ // Only https, or plain http to this machine for tests.
21
+ const usable = raw && (/^https:\/\/[^/]+/.test(raw) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$)/.test(raw));
22
+ return { enabled: !off, rawBase: (usable ? raw : DEFAULT_SKILLS_RAW).replace(/\/+$/, '') };
23
+ }
24
+ /** -1, 0 or 1 for two X.Y.Z versions; anything unparseable sorts first. */
25
+ export function compareVersions(a, b) {
26
+ const parse = (v) => (/^\d+\.\d+\.\d+$/.test(v) ? v.split('.').map(Number) : [-1, -1, -1]);
27
+ const pa = parse(a);
28
+ const pb = parse(b);
29
+ for (let i = 0; i < 3; i++) {
30
+ if (pa[i] !== pb[i])
31
+ return pa[i] < pb[i] ? -1 : 1;
32
+ }
33
+ return 0;
34
+ }
35
+ /** metadata.version from a SKILL.md's frontmatter, e.g. ` version: "0.1.14"`. */
36
+ export function skillVersionOf(skillMd) {
37
+ const fm = skillMd?.replace(/\r\n/g, '\n').match(/^---\n([\s\S]*?)\n---/)?.[1];
38
+ const m = fm?.match(/^metadata:\s*\n(?:[ \t]+.*\n)*?[ \t]+version:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m);
39
+ return m?.[1];
40
+ }
41
+ async function getText(url, timeoutMs) {
42
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
43
+ if (!res.ok)
44
+ throw new Error(`GET ${url} returned ${res.status}`);
45
+ return res.text();
46
+ }
47
+ const CACHE_MS = 60 * 60 * 1000;
48
+ let packCache;
49
+ /** The pack version on GitHub main (.claude-plugin/plugin.json), cached for an hour. */
50
+ export async function latestPack(opts) {
51
+ if (!opts.enabled)
52
+ return { error: 'the check is off (EDGEGAP_SKILLS_CHECK=off)' };
53
+ if (packCache && packCache.key === opts.rawBase && Date.now() - packCache.at < CACHE_MS)
54
+ return packCache.value;
55
+ let value;
56
+ try {
57
+ const plugin = JSON.parse(await getText(`${opts.rawBase}/.claude-plugin/plugin.json`, opts.timeoutMs ?? 3_000));
58
+ const v = typeof plugin.version === 'string' && /^\d+\.\d+\.\d+$/.test(plugin.version) ? plugin.version : undefined;
59
+ value = v ? { version: v } : { error: 'plugin.json on GitHub has no X.Y.Z version' };
60
+ }
61
+ catch (err) {
62
+ value = { error: `GitHub could not be reached (${err.message})` };
63
+ }
64
+ // Failures are cached too, so an offline machine pays the timeout once an hour, not per call.
65
+ packCache = { at: Date.now(), key: opts.rawBase, value };
66
+ return value;
67
+ }
68
+ /**
69
+ * Latest version of each named skill: GitHub main where it answers, otherwise
70
+ * the version bundled in this server. `source` says which.
71
+ */
72
+ export async function latestSkillVersions(names, opts) {
73
+ const out = {};
74
+ await Promise.all([...new Set(names)].filter((n) => SKILL_NAME_RE.test(n)).map(async (name) => {
75
+ const bundled = SKILLS_PACK.skills.find((s) => s.name === name)?.version;
76
+ let remote;
77
+ if (opts.enabled) {
78
+ try {
79
+ remote = skillVersionOf(await getText(`${opts.rawBase}/skills/${name}/SKILL.md`, opts.timeoutMs ?? 5_000));
80
+ }
81
+ catch {
82
+ remote = undefined;
83
+ }
84
+ }
85
+ if (remote && (!bundled || compareVersions(remote, bundled) >= 0))
86
+ out[name] = { version: remote, source: 'github' };
87
+ else if (bundled)
88
+ out[name] = { version: bundled, source: 'bundled' };
89
+ else
90
+ out[name] = { source: 'unknown' };
91
+ }));
92
+ return out;
93
+ }
94
+ /** What edgegap_list_skills and edgegap_get_skill say about the pack this server serves. */
95
+ export function servedPackStatus(latest, hosted) {
96
+ if (!latest.version)
97
+ return { latest_pack: `unknown: ${latest.error}` };
98
+ const behind = compareVersions(SKILLS_PACK.version, latest.version) < 0;
99
+ return {
100
+ latest_pack: latest.version,
101
+ served_is_latest: !behind,
102
+ ...(behind
103
+ ? {
104
+ update: hosted
105
+ ? `Pack ${latest.version} is on GitHub; this hosted server still serves ${SKILLS_PACK.version} until its next release. The skills served here are still correct to follow.`
106
+ : `Pack ${latest.version} is on GitHub; this server bundles ${SKILLS_PACK.version}. A newer @edgegap/mcp may carry it: restart the server through npx -y @edgegap/mcp@latest, or update the Edgegap extension. The bundled skills are still correct to follow.`,
107
+ }
108
+ : {}),
109
+ };
110
+ }