@anurag134/nexusmcp 0.0.0-stage → 1.0.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.
Files changed (33) hide show
  1. package/README.md +45 -2
  2. package/dist/index.js +208 -0
  3. package/dist/samples/mock-gitlab.js +88 -0
  4. package/dist/src/common/type.js +1 -0
  5. package/dist/src/common/utils.js +28 -0
  6. package/dist/src/database/db.js +151 -0
  7. package/dist/src/database/type.js +1 -0
  8. package/dist/src/module/checkpoint/controller.js +30 -0
  9. package/dist/src/module/checkpoint/service.js +59 -0
  10. package/dist/src/module/checkpoint/type.js +1 -0
  11. package/dist/src/module/checkpoint/utils.js +41 -0
  12. package/dist/src/module/dashboard/controller.js +39 -0
  13. package/dist/src/module/dashboard/service.js +86 -0
  14. package/dist/src/module/dashboard/type.js +1 -0
  15. package/dist/src/module/dashboard/utils.js +874 -0
  16. package/dist/src/module/mcp/controller.js +35 -0
  17. package/dist/src/module/mcp/service.js +254 -0
  18. package/dist/src/module/mcp/type.js +1 -0
  19. package/dist/src/module/mcp/utils.js +24 -0
  20. package/dist/src/module/router/controller.js +16 -0
  21. package/dist/src/module/router/service.js +56 -0
  22. package/dist/src/module/router/type.js +1 -0
  23. package/dist/src/module/router/utils.js +77 -0
  24. package/dist/src/module/security/controller.js +15 -0
  25. package/dist/src/module/security/service.js +124 -0
  26. package/dist/src/module/security/type.js +6 -0
  27. package/dist/src/module/security/utils.js +210 -0
  28. package/dist/src/module/upstream/controller.js +353 -0
  29. package/dist/src/module/upstream/service.js +344 -0
  30. package/dist/src/module/upstream/type.js +1 -0
  31. package/dist/src/module/upstream/utils.js +135 -0
  32. package/dist/tools/github-publisher/index.js +187 -0
  33. package/package.json +38 -4
@@ -0,0 +1,210 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { RiskTier } from "./type.js";
6
+ export class SecurityUtils {
7
+ static VAULT_MARKER = "__OS_VAULT__";
8
+ static ENV_REF_REGEX = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
9
+ static isEnvReference(value) {
10
+ return this.ENV_REF_REGEX.test(value);
11
+ }
12
+ static resolveEnvReference(value) {
13
+ const match = value.match(this.ENV_REF_REGEX);
14
+ if (!match) {
15
+ return value;
16
+ }
17
+ return process.env[match[1]] || "";
18
+ }
19
+ static storeOsSecret(vaultDir, serverId, key, value) {
20
+ const account = `NexusMCP:${serverId}:${key}`;
21
+ try {
22
+ if (process.platform === "darwin") {
23
+ execFileSync("security", ["add-generic-password", "-a", account, "-s", "NexusMCP", "-w", value, "-U"], { stdio: "ignore" });
24
+ return;
25
+ }
26
+ if (process.platform === "linux") {
27
+ execFileSync("secret-tool", ["store", "--label", account, "service", "NexusMCP", "account", account], { input: value, stdio: ["pipe", "ignore", "ignore"] });
28
+ return;
29
+ }
30
+ if (process.platform === "win32") {
31
+ if (!fs.existsSync(vaultDir)) {
32
+ fs.mkdirSync(vaultDir, { recursive: true });
33
+ }
34
+ const safeName = Buffer.from(`${serverId}:${key}`).toString("base64url");
35
+ const targetFile = path.join(vaultDir, `${safeName}.dpapi`);
36
+ const psScript = [
37
+ "$sec = ConvertTo-SecureString -String $env:NEXUS_SECRET_INPUT -AsPlainText -Force;",
38
+ "$enc = ConvertFrom-SecureString -SecureString $sec;",
39
+ "[System.IO.File]::WriteAllText($env:NEXUS_SECRET_FILE, $enc)"
40
+ ].join(" ");
41
+ execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", psScript], {
42
+ env: { ...process.env, NEXUS_SECRET_INPUT: value, NEXUS_SECRET_FILE: targetFile },
43
+ stdio: "ignore",
44
+ windowsHide: true
45
+ });
46
+ return;
47
+ }
48
+ }
49
+ catch {
50
+ // Fall back to in-memory only if OS keychain/DPAPI is unavailable
51
+ }
52
+ }
53
+ static loadOsSecret(vaultDir, serverId, key) {
54
+ const account = `NexusMCP:${serverId}:${key}`;
55
+ try {
56
+ if (process.platform === "darwin") {
57
+ return execFileSync("security", ["find-generic-password", "-a", account, "-s", "NexusMCP", "-w"], {
58
+ encoding: "utf-8",
59
+ stdio: ["ignore", "pipe", "ignore"]
60
+ }).trim();
61
+ }
62
+ if (process.platform === "linux") {
63
+ return execFileSync("secret-tool", ["lookup", "service", "NexusMCP", "account", account], {
64
+ encoding: "utf-8",
65
+ stdio: ["ignore", "pipe", "ignore"]
66
+ }).trim();
67
+ }
68
+ if (process.platform === "win32") {
69
+ const safeName = Buffer.from(`${serverId}:${key}`).toString("base64url");
70
+ const targetFile = path.join(vaultDir, `${safeName}.dpapi`);
71
+ if (!fs.existsSync(targetFile)) {
72
+ return "";
73
+ }
74
+ const psScript = [
75
+ "$enc = [System.IO.File]::ReadAllText($env:NEXUS_SECRET_FILE).Trim();",
76
+ "$sec = ConvertTo-SecureString -String $enc;",
77
+ "$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec);",
78
+ "try { [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) } finally { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }"
79
+ ].join(" ");
80
+ return execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", psScript], {
81
+ env: { ...process.env, NEXUS_SECRET_FILE: targetFile },
82
+ encoding: "utf-8",
83
+ stdio: ["ignore", "pipe", "ignore"],
84
+ windowsHide: true
85
+ }).replace(/\r?\n$/, "");
86
+ }
87
+ }
88
+ catch {
89
+ return "";
90
+ }
91
+ return "";
92
+ }
93
+ static deleteOsSecretsForServer(vaultDir, serverId) {
94
+ try {
95
+ if (process.platform === "win32" && fs.existsSync(vaultDir)) {
96
+ const prefix = Buffer.from(`${serverId}:`).toString("base64url").slice(0, 12);
97
+ for (const file of fs.readdirSync(vaultDir)) {
98
+ if (file.endsWith(".dpapi") && file.startsWith(prefix)) {
99
+ fs.unlinkSync(path.join(vaultDir, file));
100
+ }
101
+ }
102
+ }
103
+ }
104
+ catch {
105
+ // Ignore cleanup errors
106
+ }
107
+ }
108
+ static getDefaultVaultDir() {
109
+ return path.join(os.homedir(), ".nexusmcp", "vault");
110
+ }
111
+ static extractRiskSurface(toolName, args) {
112
+ const contentTools = new Set([
113
+ "push_files",
114
+ "create_or_update_file",
115
+ "create_issue",
116
+ "update_issue",
117
+ "add_issue_comment",
118
+ "create_pull_request"
119
+ ]);
120
+ if (!contentTools.has(toolName)) {
121
+ return `${toolName} ${JSON.stringify(args)}`;
122
+ }
123
+ const parts = [toolName];
124
+ if (typeof args.path === "string")
125
+ parts.push(args.path);
126
+ if (typeof args.branch === "string")
127
+ parts.push(args.branch);
128
+ if (typeof args.message === "string")
129
+ parts.push(args.message);
130
+ if (Array.isArray(args.files)) {
131
+ for (const f of args.files) {
132
+ if (f && typeof f === "object" && typeof f.path === "string") {
133
+ parts.push(String(f.path));
134
+ }
135
+ }
136
+ }
137
+ return parts.join(" ");
138
+ }
139
+ static CRITICAL_PATTERNS = [
140
+ /\brm\s+(-[rfRF]+)?\s+([/~]|\*)/i,
141
+ /\bdrop\s+(database|table|schema)\b/i,
142
+ /\bgit\s+push\s+.*(--force|-f)\b/i,
143
+ /\.env\b/i,
144
+ /\bcurl\b.*\|\s*(sh|bash)/i
145
+ ];
146
+ static MUTATING_PATTERNS = [
147
+ /\b(npm|yarn|pnpm|cargo|pip|dotnet)\s+(install|add|update|remove)\b/i,
148
+ /\b(git\s+(commit|merge|rebase|checkout|branch))\b/i,
149
+ /\b(create|write|delete|update|drop|truncate|alter)\b/i
150
+ ];
151
+ static assessRisk(actionText) {
152
+ for (const pattern of this.CRITICAL_PATTERNS) {
153
+ if (pattern.test(actionText)) {
154
+ return {
155
+ tier: RiskTier.CRITICAL,
156
+ reason: `Action matches critical safety rule: ${pattern.source}`,
157
+ isAllowed: false
158
+ };
159
+ }
160
+ }
161
+ for (const pattern of this.MUTATING_PATTERNS) {
162
+ if (pattern.test(actionText)) {
163
+ return {
164
+ tier: RiskTier.MUTATING,
165
+ reason: "Action performs mutating changes to repository or state.",
166
+ isAllowed: true
167
+ };
168
+ }
169
+ }
170
+ return {
171
+ tier: RiskTier.SAFE,
172
+ reason: "Action is read-only or safe.",
173
+ isAllowed: true
174
+ };
175
+ }
176
+ static getStandardRules() {
177
+ return [
178
+ {
179
+ name: "GitHub / Provider Token",
180
+ pattern: /\b(gh[pousr]_[a-zA-Z0-9]{20,}|github_pat_[a-zA-Z0-9_]{20,}|sk-[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16})\b/g,
181
+ mask: "[REDACTED_TOKEN]"
182
+ },
183
+ {
184
+ name: "Bearer Token",
185
+ pattern: /bearer\s+[a-zA-Z0-9_\-\.=:_+/]{16,}/gi,
186
+ mask: "Bearer [REDACTED_TOKEN]"
187
+ },
188
+ {
189
+ name: "Generic Secret / Key",
190
+ pattern: /(api[_-]?key|secret|password|passwd|token|auth)\s*[:=]\s*["']?([a-zA-Z0-9_\-]{8,})["']?/gi,
191
+ mask: "$1: [REDACTED_SECRET]"
192
+ },
193
+ {
194
+ name: "Email Address",
195
+ pattern: /[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+/gi,
196
+ mask: "[REDACTED_EMAIL]"
197
+ },
198
+ {
199
+ name: "Private Key Header",
200
+ pattern: /-----BEGIN\s+(RSA|EC|DSA|OPENSSH|PGP)?\s*PRIVATE\s+KEY-----[\s\S]*?-----END\s+(RSA|EC|DSA|OPENSSH|PGP)?\s*PRIVATE\s+KEY-----/gi,
201
+ mask: "[REDACTED_PRIVATE_KEY]"
202
+ },
203
+ {
204
+ name: "Credit Card",
205
+ pattern: /\b(?:\d{4}[ -]?){3}\d{4}\b/g,
206
+ mask: "[REDACTED_CARD]"
207
+ }
208
+ ];
209
+ }
210
+ }
@@ -0,0 +1,353 @@
1
+ import { UpstreamUtils } from "./utils.js";
2
+ import { CommonUtils } from "../../common/utils.js";
3
+ export class UpstreamController {
4
+ upstreamService;
5
+ db;
6
+ securityService;
7
+ constructor(upstreamService, db, securityService) {
8
+ this.upstreamService = upstreamService;
9
+ this.db = db;
10
+ this.securityService = securityService;
11
+ }
12
+ registerRoutes(server) {
13
+ server.get("/api/upstream/servers", this.listServers.bind(this));
14
+ server.get("/api/upstream/registry", this.searchRegistry.bind(this));
15
+ server.post("/api/upstream/extract", this.extractFromSource.bind(this));
16
+ server.post("/api/upstream/servers", this.addServer.bind(this));
17
+ server.post("/api/upstream/import", this.importMcpJson.bind(this));
18
+ server.post("/api/upstream/disconnect-all", this.disconnectAll.bind(this));
19
+ server.delete("/api/upstream/servers", this.removeAll.bind(this));
20
+ server.get("/api/upstream/servers/:id/logs", this.getLogs.bind(this));
21
+ server.delete("/api/upstream/servers/:id", this.deleteServer.bind(this));
22
+ server.post("/api/upstream/servers/:id/reconnect", this.reconnectServer.bind(this));
23
+ }
24
+ async searchRegistry(req, reply) {
25
+ const query = (req.query?.q || "").trim();
26
+ if (!query) {
27
+ reply.send(CommonUtils.successResponse([]));
28
+ return;
29
+ }
30
+ const slug = query.toLowerCase().replace(/[^a-z0-9-]/g, "");
31
+ const officialPkgUrl = slug ? `https://registry.npmjs.org/${encodeURIComponent(`@modelcontextprotocol/server-${slug}`)}` : "";
32
+ const mcpUrl = `https://registry.modelcontextprotocol.io/v0/servers?search=${encodeURIComponent(query)}&limit=5`;
33
+ const npmUrl = `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(`mcp server ${query}`)}&size=6`;
34
+ const [officialRes, mcpRes, npmRes] = await Promise.allSettled([
35
+ officialPkgUrl ? fetch(officialPkgUrl) : Promise.reject(new Error("skip")),
36
+ fetch(mcpUrl),
37
+ fetch(npmUrl)
38
+ ]);
39
+ const results = [];
40
+ const seen = new Set();
41
+ if (officialRes.status === "fulfilled" && officialRes.value.ok) {
42
+ const pkg = (await officialRes.value.json());
43
+ if (pkg.name) {
44
+ seen.add(pkg.name);
45
+ const repoUrl = pkg.repository?.url?.replace(/^git\+/, "").replace(/\.git$/, "") || pkg.homepage || "";
46
+ results.push({
47
+ id: pkg.name,
48
+ shortName: slug || pkg.name,
49
+ title: `${pkg.name} (Official)`,
50
+ description: pkg.description || `Official MCP server for ${query}`,
51
+ websiteUrl: repoUrl,
52
+ command: "npx",
53
+ args: ["-y", pkg.name],
54
+ envVars: [],
55
+ extractSource: pkg.name
56
+ });
57
+ }
58
+ }
59
+ if (npmRes.status === "fulfilled" && npmRes.value.ok) {
60
+ const npmData = (await npmRes.value.json());
61
+ for (const obj of npmData.objects || []) {
62
+ const pkg = obj.package;
63
+ if (seen.has(pkg.name)) {
64
+ continue;
65
+ }
66
+ seen.add(pkg.name);
67
+ const shortName = (pkg.name.split("/").pop() || pkg.name).replace(/^server-/, "").replace(/[^a-zA-Z0-9_-]/g, "-");
68
+ results.push({
69
+ id: pkg.name,
70
+ shortName,
71
+ title: pkg.name,
72
+ description: pkg.description || "",
73
+ websiteUrl: pkg.links?.repository || pkg.links?.npm || "",
74
+ command: "npx",
75
+ args: ["-y", pkg.name],
76
+ envVars: [],
77
+ extractSource: pkg.name
78
+ });
79
+ }
80
+ }
81
+ if (mcpRes.status === "fulfilled" && mcpRes.value.ok) {
82
+ const mcpData = (await mcpRes.value.json());
83
+ for (const entry of mcpData.servers || []) {
84
+ const s = entry.server;
85
+ const npmPkg = s.packages?.find(p => p.registryType === "npm");
86
+ const pypiPkg = s.packages?.find(p => p.registryType === "pypi");
87
+ const remote = s.remotes?.[0];
88
+ let command = "";
89
+ let args = [];
90
+ let envVars = [];
91
+ let extractSource;
92
+ if (npmPkg) {
93
+ command = "npx";
94
+ args = ["-y", npmPkg.identifier];
95
+ extractSource = npmPkg.identifier;
96
+ envVars = (npmPkg.environmentVariables || []).map(v => ({
97
+ name: v.name,
98
+ description: v.description || "",
99
+ isSecret: Boolean(v.isSecret)
100
+ }));
101
+ }
102
+ else if (pypiPkg) {
103
+ command = "uvx";
104
+ args = [pypiPkg.identifier];
105
+ envVars = (pypiPkg.environmentVariables || []).map(v => ({
106
+ name: v.name,
107
+ description: v.description || "",
108
+ isSecret: Boolean(v.isSecret)
109
+ }));
110
+ }
111
+ else if (remote) {
112
+ command = "npx";
113
+ args = ["-y", "mcp-remote", remote.url];
114
+ }
115
+ if (!command || seen.has(s.name)) {
116
+ continue;
117
+ }
118
+ seen.add(s.name);
119
+ const shortName = (s.name.split("/").pop() || s.name).replace(/[^a-zA-Z0-9_-]/g, "-");
120
+ results.push({
121
+ id: s.name,
122
+ shortName,
123
+ title: s.title || s.name,
124
+ description: s.description || "",
125
+ websiteUrl: s.websiteUrl || "",
126
+ command,
127
+ args,
128
+ envVars,
129
+ extractSource
130
+ });
131
+ }
132
+ }
133
+ reply.send(CommonUtils.successResponse(results));
134
+ }
135
+ async extractFromSource(req, reply) {
136
+ const source = (req.body?.source || "").trim();
137
+ if (!source) {
138
+ reply.status(400).send(CommonUtils.errorResponse("Provide a GitHub URL or npm package name."));
139
+ return;
140
+ }
141
+ let markdown = "";
142
+ let sourceUrl = source;
143
+ const fallbackName = (source.split("/").pop() || "mcp-server").replace(/^server-/, "").replace(/[^a-zA-Z0-9_-]/g, "-") || "mcp-server";
144
+ const githubUrls = UpstreamUtils.resolveGithubReadmeUrls(source);
145
+ if (githubUrls.length > 0) {
146
+ for (const url of githubUrls) {
147
+ try {
148
+ const res = await fetch(url);
149
+ if (res.ok) {
150
+ markdown = await res.text();
151
+ sourceUrl = url;
152
+ break;
153
+ }
154
+ }
155
+ catch {
156
+ // Try next branch candidate
157
+ }
158
+ }
159
+ }
160
+ else {
161
+ try {
162
+ const npmRes = await fetch(`https://registry.npmjs.org/${encodeURIComponent(source)}`);
163
+ if (npmRes.ok) {
164
+ const pkgData = (await npmRes.json());
165
+ markdown = pkgData.readme || "";
166
+ const repoUrl = pkgData.repository?.url?.replace(/^git\+/, "").replace(/\.git$/, "");
167
+ if (repoUrl) {
168
+ sourceUrl = repoUrl;
169
+ }
170
+ if (!markdown && repoUrl) {
171
+ for (const url of UpstreamUtils.resolveGithubReadmeUrls(repoUrl)) {
172
+ const ghRes = await fetch(url);
173
+ if (ghRes.ok) {
174
+ markdown = await ghRes.text();
175
+ break;
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+ catch (err) {
182
+ reply.status(502).send(CommonUtils.errorResponse(err instanceof Error ? err.message : String(err)));
183
+ return;
184
+ }
185
+ }
186
+ const extracted = markdown
187
+ ? UpstreamUtils.extractMcpConfigsFromMarkdown(markdown, fallbackName)
188
+ : [];
189
+ const isNpmPackage = githubUrls.length === 0;
190
+ if (extracted.length > 0) {
191
+ const preferred = extracted.find(c => c.command !== "docker" && c.command !== "podman");
192
+ const chosen = preferred ? { ...preferred } : { ...extracted[0] };
193
+ if (!preferred && isNpmPackage && (chosen.command === "docker" || chosen.command === "podman")) {
194
+ chosen.command = "npx";
195
+ chosen.args = ["-y", source];
196
+ }
197
+ if (chosen.envVars.length === 0) {
198
+ chosen.envVars = UpstreamUtils.extractEnvHintsFromMarkdown(markdown);
199
+ }
200
+ chosen.sourceUrl = sourceUrl;
201
+ reply.send(CommonUtils.successResponse(chosen));
202
+ return;
203
+ }
204
+ const envHints = markdown ? UpstreamUtils.extractEnvHintsFromMarkdown(markdown) : [];
205
+ const fallback = {
206
+ name: fallbackName,
207
+ command: githubUrls.length > 0 ? "npx" : "npx",
208
+ args: githubUrls.length > 0 ? [] : ["-y", source],
209
+ envVars: envHints,
210
+ sourceUrl
211
+ };
212
+ reply.send(CommonUtils.successResponse(fallback));
213
+ }
214
+ async listServers(_req, reply) {
215
+ const servers = this.db.getAllServers().map(s => {
216
+ const parsedEnv = CommonUtils.safeJsonParse(s.env || "{}", {});
217
+ const maskedEnv = this.securityService.maskEnvForDisplay(parsedEnv);
218
+ return {
219
+ ...s,
220
+ env: JSON.stringify(maskedEnv)
221
+ };
222
+ });
223
+ reply.send(CommonUtils.successResponse(servers));
224
+ }
225
+ async addServer(req, reply) {
226
+ const body = req.body;
227
+ if (!body?.name || !body?.command) {
228
+ reply.status(400).send(CommonUtils.errorResponse("Name and command are required."));
229
+ return;
230
+ }
231
+ const existingServer = body.id
232
+ ? this.db.getServerById(body.id)
233
+ : this.db.getServerByName(body.name);
234
+ const serverId = existingServer ? existingServer.id : (body.id || CommonUtils.generateId("srv"));
235
+ const argsJson = JSON.stringify(body.args || []);
236
+ const envMarkers = this.securityService.persistSecretsAndReturnMarkers(serverId, body.env || {});
237
+ const envJson = JSON.stringify(envMarkers);
238
+ this.db.upsertServer({
239
+ id: serverId,
240
+ name: body.name,
241
+ transport: body.transport || "stdio",
242
+ command: body.command,
243
+ args: argsJson,
244
+ url: body.url || null,
245
+ env: envJson,
246
+ status: "disconnected",
247
+ error_message: null,
248
+ created_at: existingServer ? existingServer.created_at : Date.now(),
249
+ updated_at: Date.now()
250
+ });
251
+ const connected = await this.upstreamService.connectStdioServer({
252
+ id: serverId,
253
+ name: body.name,
254
+ transport: body.transport || "stdio",
255
+ command: body.command,
256
+ args: body.args,
257
+ env: envMarkers
258
+ });
259
+ reply.send(CommonUtils.successResponse({ serverId, connected }));
260
+ }
261
+ async importMcpJson(req, reply) {
262
+ const body = req.body;
263
+ if (!body?.mcpServers || typeof body.mcpServers !== "object") {
264
+ reply.status(400).send(CommonUtils.errorResponse("Invalid JSON: expected { \"mcpServers\": { ... } }."));
265
+ return;
266
+ }
267
+ const configs = [];
268
+ const results = [];
269
+ for (const [name, entry] of Object.entries(body.mcpServers)) {
270
+ if (!entry.command) {
271
+ continue;
272
+ }
273
+ const existing = this.db.getServerByName(name);
274
+ const serverId = existing ? existing.id : CommonUtils.generateId("srv");
275
+ const envMarkers = this.securityService.persistSecretsAndReturnMarkers(serverId, entry.env || {});
276
+ this.db.upsertServer({
277
+ id: serverId,
278
+ name,
279
+ transport: "stdio",
280
+ command: entry.command,
281
+ args: JSON.stringify(entry.args || []),
282
+ url: entry.url || null,
283
+ env: JSON.stringify(envMarkers),
284
+ status: "connecting",
285
+ error_message: null,
286
+ created_at: existing ? existing.created_at : Date.now(),
287
+ updated_at: Date.now()
288
+ });
289
+ configs.push({
290
+ id: serverId,
291
+ name,
292
+ transport: "stdio",
293
+ command: entry.command,
294
+ args: entry.args || [],
295
+ env: envMarkers
296
+ });
297
+ results.push({ name, serverId, status: "connecting" });
298
+ }
299
+ void this.upstreamService.connectManyServers(configs, 6);
300
+ reply.send(CommonUtils.successResponse({ imported: results.length, queued: true, results }));
301
+ }
302
+ async getLogs(req, reply) {
303
+ const serverId = req.params.id;
304
+ const server = this.db.getServerById(serverId);
305
+ if (!server) {
306
+ reply.status(404).send(CommonUtils.errorResponse("Server not found"));
307
+ return;
308
+ }
309
+ const logs = this.upstreamService.getServerLogs(serverId);
310
+ const combinedText = `${server.error_message || ""}\n${logs.join("\n")}`;
311
+ const detectedMissingEnvVars = UpstreamUtils.detectMissingEnvVars(combinedText);
312
+ reply.send(CommonUtils.successResponse({
313
+ serverId,
314
+ name: server.name,
315
+ status: server.status,
316
+ error_message: server.error_message,
317
+ logs,
318
+ detectedMissingEnvVars
319
+ }));
320
+ }
321
+ async disconnectAll(_req, reply) {
322
+ this.upstreamService.disconnectAll();
323
+ reply.send(CommonUtils.successResponse({ disconnectedAll: true }));
324
+ }
325
+ async removeAll(_req, reply) {
326
+ this.upstreamService.removeAll();
327
+ reply.send(CommonUtils.successResponse({ removedAll: true }));
328
+ }
329
+ async deleteServer(req, reply) {
330
+ const serverId = req.params.id;
331
+ this.upstreamService.disconnectServer(serverId);
332
+ this.securityService.removeServerSecrets(serverId);
333
+ this.db.deleteServer(serverId);
334
+ reply.send(CommonUtils.successResponse({ deleted: true, serverId }));
335
+ }
336
+ async reconnectServer(req, reply) {
337
+ const serverId = req.params.id;
338
+ const server = this.db.getServerById(serverId);
339
+ if (!server) {
340
+ reply.status(404).send(CommonUtils.errorResponse("Server not found"));
341
+ return;
342
+ }
343
+ const connected = await this.upstreamService.connectStdioServer({
344
+ id: server.id,
345
+ name: server.name,
346
+ transport: "stdio",
347
+ command: server.command || undefined,
348
+ args: CommonUtils.safeJsonParse(server.args || "[]", []),
349
+ env: CommonUtils.safeJsonParse(server.env || "{}", {})
350
+ });
351
+ reply.send(CommonUtils.successResponse({ serverId, connected }));
352
+ }
353
+ }