localmcp-cli 0.0.1 → 0.0.11
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 +21 -0
- package/README.md +104 -2
- package/bin/cli.js +26 -1
- package/package.json +21 -9
- package/src/agents/hub.js +663 -0
- package/src/agents/providers.js +840 -0
- package/src/agents/store.js +524 -0
- package/src/cli/options.js +177 -0
- package/src/cli/runtime.js +126 -0
- package/src/cli/service.js +29 -0
- package/src/cli/tunnel.js +242 -0
- package/src/core/audit.js +105 -0
- package/src/core/auth.js +326 -0
- package/src/core/bounded-log.js +39 -0
- package/src/core/config.js +319 -0
- package/src/core/context-discovery.js +245 -0
- package/src/core/mesh.js +103 -0
- package/src/core/protocol.js +112 -0
- package/src/core/updater-client.js +165 -0
- package/src/server.js +260 -0
- package/src/tools/agents.js +149 -0
- package/src/tools/apply-patch.js +454 -0
- package/src/tools/diagnostics.js +158 -0
- package/src/tools/filesystem.js +1122 -0
- package/src/tools/gui-windows.js +268 -0
- package/src/tools/registry.js +119 -0
- package/src/tools/system.js +591 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { existsSync, lstatSync, realpathSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { platformLabel } from "./config.js";
|
|
5
|
+
|
|
6
|
+
export function getStandardSkillCandidates(homedir = os.homedir()) {
|
|
7
|
+
return [
|
|
8
|
+
{ id: "codex", label: "Codex", dir: path.join(homedir, ".codex", "skills") },
|
|
9
|
+
{ id: "claude", label: "Claude Code", dir: path.join(homedir, ".claude", "skills") },
|
|
10
|
+
{ id: "cursor", label: "Cursor", dir: path.join(homedir, ".cursor", "skills") },
|
|
11
|
+
{ id: "gemini-config", label: "Gemini", dir: path.join(homedir, ".gemini", "config", "skills") },
|
|
12
|
+
{
|
|
13
|
+
id: "antigravity",
|
|
14
|
+
label: "Antigravity",
|
|
15
|
+
dir: path.join(homedir, ".gemini", "antigravity", "skills"),
|
|
16
|
+
},
|
|
17
|
+
{ id: "agents", label: "Agents", dir: path.join(homedir, ".agents", "skills") },
|
|
18
|
+
{ id: "dsh", label: "DSH", dir: path.join(homedir, ".dsh", "skills") },
|
|
19
|
+
{ id: "zcode", label: "ZCode", dir: path.join(homedir, ".zcode", "skills") },
|
|
20
|
+
{ id: "workbuddy", label: "WorkBuddy", dir: path.join(homedir, ".workbuddy", "skills") },
|
|
21
|
+
];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function meshPointsToPrimary(dir, primary) {
|
|
25
|
+
const link = path.join(dir, "localmcp-mesh");
|
|
26
|
+
try {
|
|
27
|
+
return (
|
|
28
|
+
lstatSync(link).isSymbolicLink() &&
|
|
29
|
+
path.relative(realpathSync(link), realpathSync(path.join(primary, "localmcp-mesh"))) === ""
|
|
30
|
+
);
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function safeMtimeMs(targetPath) {
|
|
37
|
+
try {
|
|
38
|
+
return statSync(targetPath).mtimeMs || 0;
|
|
39
|
+
} catch {
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function discoverLocalSkills({
|
|
45
|
+
homedir = os.homedir(),
|
|
46
|
+
primarySkillDir = "",
|
|
47
|
+
maxSkillsPreview = 15,
|
|
48
|
+
} = {}) {
|
|
49
|
+
const candidates = getStandardSkillCandidates(homedir);
|
|
50
|
+
const primaryPath = path.resolve(primarySkillDir || path.join(homedir, ".agents", "skills"));
|
|
51
|
+
const selected = candidates.find((item) => path.relative(item.dir, primaryPath) === "") || {
|
|
52
|
+
id: "custom",
|
|
53
|
+
label: "主目录",
|
|
54
|
+
dir: primaryPath,
|
|
55
|
+
};
|
|
56
|
+
if (!candidates.includes(selected)) candidates.push(selected);
|
|
57
|
+
const directories = [];
|
|
58
|
+
let globalMostRecent = null;
|
|
59
|
+
|
|
60
|
+
for (const item of candidates) {
|
|
61
|
+
if (!item.dir || !existsSync(item.dir)) continue;
|
|
62
|
+
let entries = [];
|
|
63
|
+
try {
|
|
64
|
+
entries = readdirSync(item.dir, { withFileTypes: true });
|
|
65
|
+
} catch {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const skills = [];
|
|
70
|
+
for (const entry of entries) {
|
|
71
|
+
if (entry.name.startsWith(".")) continue;
|
|
72
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
73
|
+
const skillDir = path.join(item.dir, entry.name);
|
|
74
|
+
const skillMd = path.join(skillDir, "SKILL.md");
|
|
75
|
+
const hasSkillMd = existsSync(skillMd);
|
|
76
|
+
if (!hasSkillMd) continue;
|
|
77
|
+
let description = "";
|
|
78
|
+
try {
|
|
79
|
+
description =
|
|
80
|
+
readFileSync(skillMd, "utf8")
|
|
81
|
+
.match(/^description:[ \t]*(.+)$/m)?.[1]
|
|
82
|
+
?.trim() || "";
|
|
83
|
+
} catch {}
|
|
84
|
+
const updatedAtMs = Math.max(safeMtimeMs(skillDir), hasSkillMd ? safeMtimeMs(skillMd) : 0);
|
|
85
|
+
const skillInfo = {
|
|
86
|
+
name: entry.name,
|
|
87
|
+
description,
|
|
88
|
+
sourceId: item.id,
|
|
89
|
+
sourceLabel: item.label,
|
|
90
|
+
path: hasSkillMd ? skillMd : skillDir,
|
|
91
|
+
updatedAtMs,
|
|
92
|
+
updatedAt: updatedAtMs > 0 ? new Date(updatedAtMs).toISOString() : "",
|
|
93
|
+
};
|
|
94
|
+
skills.push(skillInfo);
|
|
95
|
+
if (!globalMostRecent || skillInfo.updatedAtMs > globalMostRecent.updatedAtMs) {
|
|
96
|
+
globalMostRecent = skillInfo;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
skills.sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.name.localeCompare(b.name));
|
|
101
|
+
const latestUpdatedAtMs = Math.max(safeMtimeMs(item.dir), skills[0]?.updatedAtMs || 0);
|
|
102
|
+
|
|
103
|
+
directories.push({
|
|
104
|
+
id: item.id,
|
|
105
|
+
label: item.label,
|
|
106
|
+
path: item.dir,
|
|
107
|
+
linked: lstatSync(item.dir).isSymbolicLink() || meshPointsToPrimary(item.dir, primaryPath),
|
|
108
|
+
skillCount: skills.length,
|
|
109
|
+
latestUpdatedAtMs,
|
|
110
|
+
latestUpdatedAt: latestUpdatedAtMs > 0 ? new Date(latestUpdatedAtMs).toISOString() : "",
|
|
111
|
+
_skills: skills,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
directories.sort((a, b) => b.latestUpdatedAtMs - a.latestUpdatedAtMs || b.skillCount - a.skillCount);
|
|
116
|
+
|
|
117
|
+
const primary = directories.find((item) => item.id === selected.id) || {
|
|
118
|
+
...selected,
|
|
119
|
+
path: primaryPath,
|
|
120
|
+
skillCount: 0,
|
|
121
|
+
_skills: [],
|
|
122
|
+
};
|
|
123
|
+
const activeDirectory = {
|
|
124
|
+
id: primary.id,
|
|
125
|
+
label: primary.label,
|
|
126
|
+
path: primary.path,
|
|
127
|
+
skillCount: primary.skillCount,
|
|
128
|
+
latestUpdatedAt: primary.latestUpdatedAt,
|
|
129
|
+
skills: primary._skills.slice(0, maxSkillsPreview).map((s) => s.name),
|
|
130
|
+
};
|
|
131
|
+
const recognized = new Map();
|
|
132
|
+
for (const dir of [primary, ...directories]) {
|
|
133
|
+
for (const { name, description } of dir._skills) {
|
|
134
|
+
if (!recognized.has(name)) recognized.set(name, { name, description });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const mostRecentSkill = globalMostRecent
|
|
139
|
+
? {
|
|
140
|
+
name: globalMostRecent.name,
|
|
141
|
+
sourceLabel: globalMostRecent.sourceLabel,
|
|
142
|
+
path: globalMostRecent.path,
|
|
143
|
+
updatedAt: globalMostRecent.updatedAt,
|
|
144
|
+
}
|
|
145
|
+
: null;
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
skills: [...recognized.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
149
|
+
directories: directories.map(({ _skills, latestUpdatedAtMs: _ms, ...rest }) => rest),
|
|
150
|
+
activeDirectory,
|
|
151
|
+
mostRecentSkill,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function loadGuideState(guideFilePath) {
|
|
156
|
+
if (!guideFilePath || !existsSync(guideFilePath)) {
|
|
157
|
+
return {
|
|
158
|
+
path: guideFilePath || "",
|
|
159
|
+
exists: false,
|
|
160
|
+
rules: [],
|
|
161
|
+
raw: "",
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const raw = readFileSync(guideFilePath, "utf8");
|
|
166
|
+
const rules = raw
|
|
167
|
+
.split(/\r?\n/)
|
|
168
|
+
.map((line) => line.trim())
|
|
169
|
+
.filter((line) => line && !line.startsWith("#") && !line.startsWith(">"))
|
|
170
|
+
.map((line) => (line.startsWith("- ") ? line.slice(2).trim() : line))
|
|
171
|
+
.filter(Boolean)
|
|
172
|
+
.slice(0, 30);
|
|
173
|
+
return {
|
|
174
|
+
path: guideFilePath,
|
|
175
|
+
exists: rules.length > 0 || raw.trim().length > 0,
|
|
176
|
+
rules,
|
|
177
|
+
raw: raw.trim(),
|
|
178
|
+
};
|
|
179
|
+
} catch {
|
|
180
|
+
return {
|
|
181
|
+
path: guideFilePath,
|
|
182
|
+
exists: false,
|
|
183
|
+
rules: [],
|
|
184
|
+
raw: "",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function buildDefaultHints(platform = process.platform) {
|
|
190
|
+
return [
|
|
191
|
+
"修改现有代码或文本优先使用 edit_file(局部替换)或 apply_patch(多文件补丁),避免用 write_file 整文件覆盖大文件。",
|
|
192
|
+
"读取大文件用 read_file 的 offset/limit 按行分页;二进制读写、大文件分片或 URL 上传下载用 transfer_file。",
|
|
193
|
+
"如需检查或无损升级本机 LocalMCP 版本,可直接调用 self_update(先回包再热切换,不断临时隧道、不变密钥)。",
|
|
194
|
+
platform === "win32"
|
|
195
|
+
? "执行终端脚本用 run_shell 或 run_powershell(已内置 pwsh 7 优先与 UTF-8 .ps1 执行):禁止使用 Bash <<EOF heredoc 或 \\\" 转义,请用单引号 @'...'@ here-string、数组参数 & $exe @argList(勿用自动变量 $args)、-LiteralPath 及 curl.exe;需 Linux/GNU 参数时可显式调 grep.exe/ls.exe(coreutils)。删除普通文件优先移入回收站。"
|
|
196
|
+
: "执行终端脚本直接用 run_shell(原生 bash/zsh -lc,支持 cwd 与 timeoutMs);删除普通文件优先移入废纸篓;macOS 桌面 GUI 自动化用 run_applescript。",
|
|
197
|
+
];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function buildServerInstructions({ config }) {
|
|
201
|
+
const osName = platformLabel(config.state.platform);
|
|
202
|
+
const roots = config.state.allowedRoots.join(", ");
|
|
203
|
+
const guide = loadGuideState(config.state.guideFilePath);
|
|
204
|
+
const skills = discoverLocalSkills({ primarySkillDir: config.state.primarySkillDir });
|
|
205
|
+
const defaults = buildDefaultHints(config.state.platform);
|
|
206
|
+
|
|
207
|
+
const lines = [
|
|
208
|
+
`Connected to ${config.state.serverName} (${osName}, v${config.state.version}). Allowed roots: ${roots}.`,
|
|
209
|
+
"Default working practices:",
|
|
210
|
+
...defaults.map((d) => `- ${d}`),
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
if (guide.rules.length > 0) {
|
|
214
|
+
lines.push("", `User guide (${guide.path}):`, ...guide.rules.map((r) => `- ${r}`));
|
|
215
|
+
} else if (guide.path) {
|
|
216
|
+
lines.push(
|
|
217
|
+
"",
|
|
218
|
+
`User guide (${guide.path}): currently empty. If the user shares durable local preferences or workspace paths, you may maintain this file via write_file/edit_file.`,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (skills.directories.length > 0) {
|
|
223
|
+
lines.push(
|
|
224
|
+
"",
|
|
225
|
+
"Discovered local skill directories (read-only accessible; inspect with list_directory/read_file only if relevant):",
|
|
226
|
+
);
|
|
227
|
+
for (const dir of skills.directories) {
|
|
228
|
+
lines.push(
|
|
229
|
+
`- ${dir.label}: ${dir.path} (${dir.skillCount} skills, updated ${dir.latestUpdatedAt || "unknown"})`,
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (skills.activeDirectory) {
|
|
233
|
+
lines.push(
|
|
234
|
+
`Primary skill library [${skills.activeDirectory.label}]: ${skills.activeDirectory.skills.join(", ")}`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (skills.mostRecentSkill) {
|
|
238
|
+
lines.push(
|
|
239
|
+
`Latest modified skill: ${skills.mostRecentSkill.name} (${skills.mostRecentSkill.sourceLabel}) -> ${skills.mostRecentSkill.path}`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return lines.join("\n");
|
|
245
|
+
}
|
package/src/core/mesh.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const name = "localmcp-mesh";
|
|
6
|
+
const targets = new Set(["claude", "workbuddy", "dsh"]);
|
|
7
|
+
const files = {
|
|
8
|
+
"SKILL.md": `---
|
|
9
|
+
name: localmcp-mesh
|
|
10
|
+
description: Discover local agents, dispatch a requested task and read its receipt through LocalMCP.
|
|
11
|
+
---
|
|
12
|
+
Set LOCALMCP_URL to the address copied from LocalMCP. Keep any tunnel key private.
|
|
13
|
+
Run node mesh.mjs list in this skill directory. Choose a registered target or available engine.
|
|
14
|
+
For a user-requested assignment run node mesh.mjs dispatch TARGET "task text".
|
|
15
|
+
Use the returned task.taskId with node mesh.mjs result TASK_ID to read the receipt.
|
|
16
|
+
A queued task is pending until the recipient reports completion.
|
|
17
|
+
`,
|
|
18
|
+
"mesh.mjs": `const [action, target, prompt] = process.argv.slice(2);
|
|
19
|
+
const operations = {
|
|
20
|
+
list: ["agent_list", {}],
|
|
21
|
+
dispatch: ["agent_dispatch", { target, prompt }],
|
|
22
|
+
result: ["agent_result", { task_id: target }],
|
|
23
|
+
};
|
|
24
|
+
if (!Object.hasOwn(operations, action) || (action !== "list" && !target) || (action === "dispatch" && !prompt)) {
|
|
25
|
+
throw Error("Use list, dispatch TARGET PROMPT, or result TASK_ID");
|
|
26
|
+
}
|
|
27
|
+
const [name, args] = operations[action];
|
|
28
|
+
const version = "2026-07-28";
|
|
29
|
+
const response = await fetch(process.env.LOCALMCP_URL, {
|
|
30
|
+
method: "POST", redirect: "error",
|
|
31
|
+
headers: { "content-type": "application/json", "mcp-name": name, "mcp-method": "tools/call", "mcp-protocol-version": version },
|
|
32
|
+
body: JSON.stringify({ id: 1, jsonrpc: "2.0", method: "tools/call", params: {
|
|
33
|
+
name, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": version, "io.modelcontextprotocol/clientCapabilities": {} }
|
|
34
|
+
} }),
|
|
35
|
+
});
|
|
36
|
+
if (!response.ok) throw Error("LocalMCP HTTP " + response.status);
|
|
37
|
+
const data = await response.json();
|
|
38
|
+
if (data.error || data.result?.isError) process.exitCode = 1;
|
|
39
|
+
console.log(JSON.stringify(data.error || data.result?.structuredContent || data.result, null, 2));
|
|
40
|
+
`,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const stat = (file) => fs.lstatSync(file, { throwIfNoEntry: false });
|
|
44
|
+
const primary = (dir, home) => path.resolve(dir || path.join(home, ".agents", "skills"), name);
|
|
45
|
+
function owned(dir) {
|
|
46
|
+
return (
|
|
47
|
+
stat(dir)?.isDirectory() &&
|
|
48
|
+
!stat(dir).isSymbolicLink() &&
|
|
49
|
+
Object.entries(files).every(([key, value]) => {
|
|
50
|
+
const file = path.join(dir, key);
|
|
51
|
+
return stat(file)?.isFile() && fs.readFileSync(file, "utf8") === value;
|
|
52
|
+
})
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
function same(a, b) {
|
|
56
|
+
return path.relative(fs.realpathSync(a), fs.realpathSync(b)) === "";
|
|
57
|
+
}
|
|
58
|
+
export function meshInstalled(dir, home = os.homedir()) {
|
|
59
|
+
return Boolean(owned(primary(dir, home)));
|
|
60
|
+
}
|
|
61
|
+
export function installMesh(dir, selection = [], home = os.homedir()) {
|
|
62
|
+
const dest = primary(dir, home);
|
|
63
|
+
if (selection.some((id) => !targets.has(id))) throw Error("Unknown mesh target");
|
|
64
|
+
const created = [];
|
|
65
|
+
try {
|
|
66
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
67
|
+
if (!stat(dest)) {
|
|
68
|
+
fs.mkdirSync(dest);
|
|
69
|
+
created.push([dest, true]);
|
|
70
|
+
for (const [key, value] of Object.entries(files)) {
|
|
71
|
+
const file = path.join(dest, key);
|
|
72
|
+
fs.writeFileSync(file, value, { flag: "wx" });
|
|
73
|
+
created.push([file, false]);
|
|
74
|
+
}
|
|
75
|
+
} else if (!owned(dest)) throw Error("目录中已有同名技能: " + dest);
|
|
76
|
+
for (const id of new Set(selection)) {
|
|
77
|
+
const parent = path.join(home, "." + id, "skills");
|
|
78
|
+
fs.mkdirSync(parent, { recursive: true });
|
|
79
|
+
if (same(parent, path.dirname(dest))) continue;
|
|
80
|
+
const link = path.join(parent, name);
|
|
81
|
+
if (stat(link)?.isSymbolicLink() && fs.existsSync(link) && same(link, dest)) continue;
|
|
82
|
+
fs.symlinkSync(fs.realpathSync(dest), link, process.platform === "win32" ? "junction" : "dir");
|
|
83
|
+
created.push([link, false]);
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
for (const [file, directory] of created.reverse()) {
|
|
87
|
+
if (directory) fs.rmdirSync(file);
|
|
88
|
+
else fs.unlinkSync(file);
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export function uninstallMesh(dir, home = os.homedir()) {
|
|
94
|
+
const dest = primary(dir, home);
|
|
95
|
+
if (!owned(dest) || fs.readdirSync(dest).length !== Object.keys(files).length)
|
|
96
|
+
throw Error("技能目录内容已变化: " + dest);
|
|
97
|
+
for (const id of targets) {
|
|
98
|
+
const link = path.join(home, "." + id, "skills", name);
|
|
99
|
+
if (stat(link)?.isSymbolicLink() && fs.existsSync(link) && same(link, dest)) fs.unlinkSync(link);
|
|
100
|
+
}
|
|
101
|
+
for (const key of Object.keys(files)) fs.unlinkSync(path.join(dest, key));
|
|
102
|
+
fs.rmdirSync(dest);
|
|
103
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
export function corsHeaders() {
|
|
2
|
+
return {
|
|
3
|
+
"Access-Control-Allow-Origin": "*",
|
|
4
|
+
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
|
|
5
|
+
"Access-Control-Allow-Headers": "Content-Type, Authorization, Accept, Mcp-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name, x-secret-key",
|
|
6
|
+
"Access-Control-Expose-Headers": "Mcp-Session-Id",
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function sendJson(res, statusCode, payload, extraHeaders = {}) {
|
|
11
|
+
res.writeHead(statusCode, {
|
|
12
|
+
...corsHeaders(),
|
|
13
|
+
"content-type": "application/json; charset=utf-8",
|
|
14
|
+
...extraHeaders,
|
|
15
|
+
});
|
|
16
|
+
res.end(JSON.stringify(payload));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function truncateText(text, maxChars = 20000) {
|
|
20
|
+
const str = String(text ?? "");
|
|
21
|
+
if (str.length <= maxChars) {
|
|
22
|
+
return { text: str, truncated: false, originalLength: str.length };
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
text: `${str.slice(0, maxChars)}\n... [truncated ${str.length - maxChars} chars]`,
|
|
26
|
+
truncated: true,
|
|
27
|
+
originalLength: str.length,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function okResult(text, structuredContent = undefined) {
|
|
32
|
+
return {
|
|
33
|
+
content: [{ type: "text", text: String(text ?? "") }],
|
|
34
|
+
...(structuredContent !== undefined ? { structuredContent } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function errorResult(error) {
|
|
39
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
40
|
+
return {
|
|
41
|
+
isError: true,
|
|
42
|
+
content: [{ type: "text", text: message }],
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function toolMeta(invoking, invoked, securitySchemes = undefined) {
|
|
47
|
+
return {
|
|
48
|
+
"openai/toolInvocation/invoking": invoking,
|
|
49
|
+
"openai/toolInvocation/invoked": invoked,
|
|
50
|
+
...(securitySchemes ? { securitySchemes } : {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const CONTROL_SECURITY_SCHEMES = [
|
|
55
|
+
{ type: "noauth" },
|
|
56
|
+
{ type: "oauth2", scopes: ["local.control"] },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
export async function readRpcBody(req) {
|
|
60
|
+
const chunks = [];
|
|
61
|
+
let length = 0;
|
|
62
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
63
|
+
length += chunk.length;
|
|
64
|
+
if (length > 4 * 1024 * 1024) throw new RangeError("Request too large");
|
|
65
|
+
chunks.push(chunk);
|
|
66
|
+
}
|
|
67
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const MODERN = "2026-07-28";
|
|
71
|
+
const supportedVersions = [MODERN, "2025-11-25", "2025-06-18", "2025-03-26"];
|
|
72
|
+
|
|
73
|
+
export async function handleModernRpc(req, res, body, registry, authContext, state) {
|
|
74
|
+
const meta = body?.params?._meta;
|
|
75
|
+
const version = meta?.["io.modelcontextprotocol/protocolVersion"];
|
|
76
|
+
const headers = req.headers;
|
|
77
|
+
if (version === undefined && !headers["mcp-method"] && headers["mcp-protocol-version"] !== MODERN && body?.method !== "server/discover") return false;
|
|
78
|
+
const fail = (status, code, message, data) => {
|
|
79
|
+
sendJson(res, status, { jsonrpc: "2.0", id: body?.id ?? null, error: { code, message, data } });
|
|
80
|
+
return true;
|
|
81
|
+
};
|
|
82
|
+
if (body?.jsonrpc !== "2.0" || !["number", "string"].includes(typeof body.id) || typeof body.method !== "string") {
|
|
83
|
+
return fail(400, -32600, "Invalid request");
|
|
84
|
+
}
|
|
85
|
+
const nameHeader = headers["mcp-name"];
|
|
86
|
+
const encoded = /^=\?base64\?([A-Za-z0-9+/]+={0,2})\?=$/.exec(nameHeader || "");
|
|
87
|
+
const name = encoded ? Buffer.from(encoded[1], "base64").toString("utf8") : nameHeader;
|
|
88
|
+
if (!version || headers["mcp-protocol-version"] !== version || headers["mcp-method"] !== body.method ||
|
|
89
|
+
(body.method === "tools/call" && (!body.params.name || name !== body.params.name))) {
|
|
90
|
+
return fail(400, -32020, "Invalid request headers");
|
|
91
|
+
}
|
|
92
|
+
if (version !== MODERN) return fail(400, -32022, "Unsupported protocol version", { supported: supportedVersions, requested: version });
|
|
93
|
+
const caps = meta["io.modelcontextprotocol/clientCapabilities"];
|
|
94
|
+
if (!caps || typeof caps !== "object" || Array.isArray(caps)) return fail(400, -32602, "Missing client capabilities");
|
|
95
|
+
let result;
|
|
96
|
+
switch (body.method) {
|
|
97
|
+
case "server/discover":
|
|
98
|
+
result = { supportedVersions, capabilities: { tools: {} }, instructions: registry.getInstructions() };
|
|
99
|
+
break;
|
|
100
|
+
case "tools/list":
|
|
101
|
+
result = { tools: registry.descriptors };
|
|
102
|
+
break;
|
|
103
|
+
case "tools/call":
|
|
104
|
+
result = await registry.callTool(body, authContext);
|
|
105
|
+
break;
|
|
106
|
+
default:
|
|
107
|
+
return fail(200, -32601, "Method not found");
|
|
108
|
+
}
|
|
109
|
+
result._meta = { ...result._meta, "io.modelcontextprotocol/serverInfo": { name: state.serverName, version: state.version } };
|
|
110
|
+
sendJson(res, 200, { jsonrpc: "2.0", id: body.id, result });
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_UPDATE_SOURCES = [
|
|
4
|
+
"https://cdn.jsdelivr.net/gh/ssesweb/local-mcp@main/version.json",
|
|
5
|
+
"https://raw.githubusercontent.com/ssesweb/local-mcp/main/version.json",
|
|
6
|
+
"https://api.github.com/repos/ssesweb/local-mcp/releases/latest",
|
|
7
|
+
];
|
|
8
|
+
|
|
9
|
+
export function compareSemver(a, b) {
|
|
10
|
+
const pa = String(a || "0.0.0")
|
|
11
|
+
.replace(/^v/i, "")
|
|
12
|
+
.split(".")
|
|
13
|
+
.map((n) => parseInt(n, 10) || 0);
|
|
14
|
+
const pb = String(b || "0.0.0")
|
|
15
|
+
.replace(/^v/i, "")
|
|
16
|
+
.split(".")
|
|
17
|
+
.map((n) => parseInt(n, 10) || 0);
|
|
18
|
+
for (let i = 0; i < 3; i += 1) {
|
|
19
|
+
if ((pa[i] || 0) !== (pb[i] || 0)) {
|
|
20
|
+
return (pa[i] || 0) > (pb[i] || 0) ? 1 : -1;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function checkRemoteVersion(currentVersion, { sources = DEFAULT_UPDATE_SOURCES } = {}) {
|
|
27
|
+
let lastErr = "";
|
|
28
|
+
for (const url of sources) {
|
|
29
|
+
try {
|
|
30
|
+
const res = await fetch(url, {
|
|
31
|
+
signal: AbortSignal.timeout(6000),
|
|
32
|
+
headers: {
|
|
33
|
+
Accept: "application/json",
|
|
34
|
+
"User-Agent": `LocalMCP/${currentVersion}`,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
if (!res.ok) {
|
|
38
|
+
lastErr = `HTTP ${res.status}`;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const data = await res.json();
|
|
42
|
+
let latestVersion = "";
|
|
43
|
+
let notes = [];
|
|
44
|
+
let releasePage = "https://github.com/ssesweb/local-mcp/releases/latest";
|
|
45
|
+
let patchUrl = "";
|
|
46
|
+
let patchManifestUrl = "";
|
|
47
|
+
|
|
48
|
+
if (data?.version) {
|
|
49
|
+
latestVersion = String(data.version).replace(/^v/i, "").trim();
|
|
50
|
+
notes = Array.isArray(data.notes) ? data.notes.map(String) : [];
|
|
51
|
+
releasePage = data.releasePage || releasePage;
|
|
52
|
+
patchUrl =
|
|
53
|
+
data.downloads?.patch ||
|
|
54
|
+
`https://github.com/ssesweb/local-mcp/releases/download/v${latestVersion}/LocalMCP-${latestVersion}-app-patch.zip`;
|
|
55
|
+
patchManifestUrl =
|
|
56
|
+
data.downloads?.patchManifest ||
|
|
57
|
+
`https://github.com/ssesweb/local-mcp/releases/download/v${latestVersion}/patch-manifest.json`;
|
|
58
|
+
} else if (data?.tag_name) {
|
|
59
|
+
latestVersion = String(data.tag_name).replace(/^v/i, "").trim();
|
|
60
|
+
notes = String(data.body || "")
|
|
61
|
+
.split(/\r?\n/)
|
|
62
|
+
.map((l) => l.replace(/^[-*]\s*/, "").trim())
|
|
63
|
+
.filter(Boolean)
|
|
64
|
+
.slice(0, 6);
|
|
65
|
+
releasePage = data.html_url || releasePage;
|
|
66
|
+
patchUrl = `https://github.com/ssesweb/local-mcp/releases/download/v${latestVersion}/LocalMCP-${latestVersion}-app-patch.zip`;
|
|
67
|
+
patchManifestUrl = `https://github.com/ssesweb/local-mcp/releases/download/v${latestVersion}/patch-manifest.json`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!latestVersion) continue;
|
|
71
|
+
return {
|
|
72
|
+
ok: true,
|
|
73
|
+
currentVersion,
|
|
74
|
+
latestVersion,
|
|
75
|
+
hasUpdate: compareSemver(latestVersion, currentVersion) > 0,
|
|
76
|
+
notes,
|
|
77
|
+
releasePage,
|
|
78
|
+
patchUrl,
|
|
79
|
+
patchManifestUrl,
|
|
80
|
+
checkedAt: new Date().toISOString(),
|
|
81
|
+
};
|
|
82
|
+
} catch (err) {
|
|
83
|
+
lastErr = err instanceof Error ? err.message : String(err);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
ok: false,
|
|
88
|
+
currentVersion,
|
|
89
|
+
latestVersion: currentVersion,
|
|
90
|
+
hasUpdate: false,
|
|
91
|
+
error: `检查更新失败: ${lastErr || "网络不可达"}`,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function invokeSelfUpdate(action = "check", { currentVersion, force = false, timeoutMs = 45000 } = {}) {
|
|
96
|
+
if (typeof process.send === "function") {
|
|
97
|
+
return await new Promise((resolve, reject) => {
|
|
98
|
+
const requestId = randomUUID();
|
|
99
|
+
const timer = setTimeout(() => {
|
|
100
|
+
process.off("message", onMessage);
|
|
101
|
+
reject(new Error(`Desktop supervisor self_update timed out after ${timeoutMs}ms.`));
|
|
102
|
+
}, timeoutMs);
|
|
103
|
+
|
|
104
|
+
function onMessage(msg) {
|
|
105
|
+
if (!msg || msg.type !== "mcp-supervisor-res" || msg.requestId !== requestId) return;
|
|
106
|
+
clearTimeout(timer);
|
|
107
|
+
process.off("message", onMessage);
|
|
108
|
+
if (msg.ok === false && msg.error) {
|
|
109
|
+
reject(new Error(String(msg.error)));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
resolve(msg.result);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
process.on("message", onMessage);
|
|
116
|
+
try {
|
|
117
|
+
process.send({
|
|
118
|
+
type: "mcp-supervisor-req",
|
|
119
|
+
requestId,
|
|
120
|
+
action,
|
|
121
|
+
force: Boolean(force),
|
|
122
|
+
});
|
|
123
|
+
} catch (err) {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
process.off("message", onMessage);
|
|
126
|
+
reject(err);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const remote = await checkRemoteVersion(currentVersion);
|
|
132
|
+
if (action === "check") {
|
|
133
|
+
return {
|
|
134
|
+
...remote,
|
|
135
|
+
mode: "standalone",
|
|
136
|
+
liveHotSwapSupported: false,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!remote.ok) {
|
|
141
|
+
return remote;
|
|
142
|
+
}
|
|
143
|
+
if (!remote.hasUpdate && !force) {
|
|
144
|
+
return {
|
|
145
|
+
ok: true,
|
|
146
|
+
updated: false,
|
|
147
|
+
alreadyLatest: true,
|
|
148
|
+
mode: "standalone",
|
|
149
|
+
currentVersion,
|
|
150
|
+
latestVersion: remote.latestVersion,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
ok: false,
|
|
156
|
+
updated: false,
|
|
157
|
+
mode: "standalone_or_legacy_supervisor",
|
|
158
|
+
currentVersion,
|
|
159
|
+
latestVersion: remote.latestVersion,
|
|
160
|
+
releasePage: remote.releasePage,
|
|
161
|
+
notes: remote.notes,
|
|
162
|
+
message:
|
|
163
|
+
"当前后端运行在独立命令行或旧版桌面壳下(未挂载 IPC 热切换通道)。请先升级一次桌面端至 v0.0.10+,后续即可直接通过 MCP 全自动无感自更新。",
|
|
164
|
+
};
|
|
165
|
+
}
|