@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.
- package/README.md +45 -2
- package/dist/index.js +208 -0
- package/dist/samples/mock-gitlab.js +88 -0
- package/dist/src/common/type.js +1 -0
- package/dist/src/common/utils.js +28 -0
- package/dist/src/database/db.js +151 -0
- package/dist/src/database/type.js +1 -0
- package/dist/src/module/checkpoint/controller.js +30 -0
- package/dist/src/module/checkpoint/service.js +59 -0
- package/dist/src/module/checkpoint/type.js +1 -0
- package/dist/src/module/checkpoint/utils.js +41 -0
- package/dist/src/module/dashboard/controller.js +39 -0
- package/dist/src/module/dashboard/service.js +86 -0
- package/dist/src/module/dashboard/type.js +1 -0
- package/dist/src/module/dashboard/utils.js +874 -0
- package/dist/src/module/mcp/controller.js +35 -0
- package/dist/src/module/mcp/service.js +254 -0
- package/dist/src/module/mcp/type.js +1 -0
- package/dist/src/module/mcp/utils.js +24 -0
- package/dist/src/module/router/controller.js +16 -0
- package/dist/src/module/router/service.js +56 -0
- package/dist/src/module/router/type.js +1 -0
- package/dist/src/module/router/utils.js +77 -0
- package/dist/src/module/security/controller.js +15 -0
- package/dist/src/module/security/service.js +124 -0
- package/dist/src/module/security/type.js +6 -0
- package/dist/src/module/security/utils.js +210 -0
- package/dist/src/module/upstream/controller.js +353 -0
- package/dist/src/module/upstream/service.js +344 -0
- package/dist/src/module/upstream/type.js +1 -0
- package/dist/src/module/upstream/utils.js +135 -0
- package/dist/tools/github-publisher/index.js +187 -0
- package/package.json +38 -4
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# NexusMCP
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Local-First MCP Gateway & Semantic Tool Router**
|
|
4
|
+
|
|
5
|
+
Connect 50+ MCP servers behind a single local gateway without blowing up your AI client's context window or exposing your credentials.
|
|
6
|
+
|
|
7
|
+
## Why NexusMCP?
|
|
8
|
+
|
|
9
|
+
- **Semantic Tool Routing (`nexus_search_tools`)**: Indexes all upstream tools in memory and returns only the top relevant tools for a task, saving ~250 context tokens per filtered-out tool.
|
|
10
|
+
- **Zero-Credential Database (OS-Native Vault)**: Secrets are stored in your OS credential layer (Windows DPAPI, macOS Keychain, Linux Secret Service) rather than SQLite, and active secret values + common token patterns (`ghp_`, `github_pat_`, `sk-`, `AKIA`, Bearer tokens) are redacted before any tool output reaches an AI model.
|
|
11
|
+
- **`mcp.json` Control Plane**: Paste or edit standard `mcp.json` directly, or search the official MCP Registry / npm and auto-extract `mcp.json` and environment variables from repo READMEs.
|
|
12
|
+
- **Parallel Startup & Live Diagnostics**: Connects upstream servers in parallel (`concurrency = 6`) with live progress tracking, `stderr` capture, cold-start `npx` retry, and inline missing-env Quick Fix.
|
|
13
|
+
- **1-Click IDE Migration**: Wrap or restore `~/.cursor/mcp.json` (`nexusmcp wrap` / `nexusmcp unwrap`).
|
|
14
|
+
- **Automatic Port Fallback**: Automatically switches to `3001+` if port `3000` is already occupied (or pass `--port <number>`).
|
|
15
|
+
|
|
16
|
+
## Quick Start
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx -y @anurag134/nexusmcp
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Open **`http://localhost:3000`** (or the port printed in your terminal) to add servers via `mcp.json`, then connect your AI IDE to:
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"mcpServers": {
|
|
27
|
+
"nexusmcp": {
|
|
28
|
+
"url": "http://localhost:3000/mcp/sse"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## CLI Commands
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
nexusmcp # Start gateway and local control plane UI
|
|
38
|
+
nexusmcp --port 4500 # Start on a custom port
|
|
39
|
+
nexusmcp wrap # Import ~/.cursor/mcp.json and route Cursor through NexusMCP
|
|
40
|
+
nexusmcp unwrap # Restore original ~/.cursor/mcp.json backup
|
|
41
|
+
nexusmcp list # List registered servers and indexed tool count
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Requirements
|
|
45
|
+
|
|
46
|
+
- **Node.js 24+** (uses built-in `node:sqlite`)
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import Fastify from "fastify";
|
|
3
|
+
import cors from "@fastify/cors";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import dotenv from "dotenv";
|
|
8
|
+
import { DatabaseService } from "./src/database/db.js";
|
|
9
|
+
import { SecurityService } from "./src/module/security/service.js";
|
|
10
|
+
import { SecurityController } from "./src/module/security/controller.js";
|
|
11
|
+
import { RouterService } from "./src/module/router/service.js";
|
|
12
|
+
import { RouterController } from "./src/module/router/controller.js";
|
|
13
|
+
import { UpstreamService } from "./src/module/upstream/service.js";
|
|
14
|
+
import { UpstreamController } from "./src/module/upstream/controller.js";
|
|
15
|
+
import { CheckpointService } from "./src/module/checkpoint/service.js";
|
|
16
|
+
import { CheckpointController } from "./src/module/checkpoint/controller.js";
|
|
17
|
+
import { McpService } from "./src/module/mcp/service.js";
|
|
18
|
+
import { McpController } from "./src/module/mcp/controller.js";
|
|
19
|
+
import { DashboardService } from "./src/module/dashboard/service.js";
|
|
20
|
+
import { DashboardController } from "./src/module/dashboard/controller.js";
|
|
21
|
+
import { CommonUtils } from "./src/common/utils.js";
|
|
22
|
+
dotenv.config();
|
|
23
|
+
export class Application {
|
|
24
|
+
server;
|
|
25
|
+
config;
|
|
26
|
+
db;
|
|
27
|
+
securityService;
|
|
28
|
+
routerService;
|
|
29
|
+
upstreamService;
|
|
30
|
+
checkpointService;
|
|
31
|
+
mcpService;
|
|
32
|
+
dashboardService;
|
|
33
|
+
constructor() {
|
|
34
|
+
this.config = this.loadConfig();
|
|
35
|
+
this.ensureDataDirectory(this.config.dbPath);
|
|
36
|
+
this.db = new DatabaseService({ path: this.config.dbPath });
|
|
37
|
+
this.securityService = new SecurityService(path.dirname(this.config.dbPath));
|
|
38
|
+
this.routerService = new RouterService();
|
|
39
|
+
this.upstreamService = new UpstreamService(this.db, this.routerService, this.securityService);
|
|
40
|
+
this.checkpointService = new CheckpointService(process.cwd());
|
|
41
|
+
this.mcpService = new McpService(this.db, this.routerService, this.upstreamService, this.securityService, this.checkpointService);
|
|
42
|
+
this.dashboardService = new DashboardService(this.db, this.routerService, this.securityService);
|
|
43
|
+
this.server = Fastify({
|
|
44
|
+
logger: false,
|
|
45
|
+
bodyLimit: 10 * 1024 * 1024
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
loadConfig() {
|
|
49
|
+
const defaultDataDir = path.join(os.homedir(), ".nexusmcp");
|
|
50
|
+
let cliPort;
|
|
51
|
+
const portIdx = process.argv.findIndex(a => a === "--port" || a === "-p");
|
|
52
|
+
if (portIdx !== -1 && process.argv[portIdx + 1]) {
|
|
53
|
+
const parsed = Number(process.argv[portIdx + 1]);
|
|
54
|
+
if (Number.isInteger(parsed) && parsed > 0 && parsed < 65536) {
|
|
55
|
+
cliPort = parsed;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
port: cliPort || Number(process.env.PORT || 3000),
|
|
60
|
+
host: process.env.HOST || "0.0.0.0",
|
|
61
|
+
dbPath: process.env.DATABASE_PATH || path.join(defaultDataDir, "nexus.db"),
|
|
62
|
+
configPath: process.env.CONFIG_PATH || path.join(defaultDataDir, "nexus.config.json")
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
ensureDataDirectory(dbFilePath) {
|
|
66
|
+
const dir = path.dirname(dbFilePath);
|
|
67
|
+
if (!fs.existsSync(dir)) {
|
|
68
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async runCli(command, args) {
|
|
72
|
+
if (command === "wrap") {
|
|
73
|
+
try {
|
|
74
|
+
const result = this.dashboardService.wrapIdeConfig();
|
|
75
|
+
process.stdout.write(`\n✔ Wrapped Cursor config successfully! Imported ${result.serversImported} servers.\n`);
|
|
76
|
+
process.stdout.write(`Backup saved to: ${result.backupPath}\n\n`);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
process.stderr.write(`Error wrapping config: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
if (command === "unwrap") {
|
|
84
|
+
try {
|
|
85
|
+
this.dashboardService.unwrapIdeConfig();
|
|
86
|
+
process.stdout.write("\n✔ Restored original Cursor config successfully.\n\n");
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
process.stderr.write(`Error unwrapping config: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
90
|
+
}
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
if (command === "rollback") {
|
|
94
|
+
const result = this.checkpointService.rollbackLatest();
|
|
95
|
+
process.stdout.write(`\n${result.message}\n\n`);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
if (command === "diff") {
|
|
99
|
+
const result = this.checkpointService.getDiff();
|
|
100
|
+
process.stdout.write(`\n${result.diff}\n\n`);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
if (command === "list") {
|
|
104
|
+
const servers = this.db.getAllServers();
|
|
105
|
+
const tools = this.db.getAllActiveTools();
|
|
106
|
+
process.stdout.write(`\n--- NexusMCP Connected Servers (${servers.length}) ---\n`);
|
|
107
|
+
for (const s of servers) {
|
|
108
|
+
process.stdout.write(`• ${s.name} [${s.transport}] - Status: ${s.status}\n`);
|
|
109
|
+
}
|
|
110
|
+
process.stdout.write(`\n--- Total Indexed Tools: ${tools.length} ---\n\n`);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
if (command === "add") {
|
|
114
|
+
const name = args[0];
|
|
115
|
+
const cmd = args.slice(1).join(" ");
|
|
116
|
+
if (!name || !cmd) {
|
|
117
|
+
process.stdout.write("Usage: nexusmcp add <server-name> <command>\nExample: nexusmcp add gitlab npx -y @gitlab/mcp-server\n");
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
const serverId = CommonUtils.generateId("srv");
|
|
121
|
+
this.db.upsertServer({
|
|
122
|
+
id: serverId,
|
|
123
|
+
name,
|
|
124
|
+
transport: "stdio",
|
|
125
|
+
command: cmd,
|
|
126
|
+
args: JSON.stringify([]),
|
|
127
|
+
url: null,
|
|
128
|
+
env: JSON.stringify({}),
|
|
129
|
+
status: "disconnected",
|
|
130
|
+
error_message: null,
|
|
131
|
+
created_at: Date.now(),
|
|
132
|
+
updated_at: Date.now()
|
|
133
|
+
});
|
|
134
|
+
process.stdout.write(`✔ Server "${name}" added to NexusMCP catalog.\n`);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
async start() {
|
|
140
|
+
await this.server.register(cors, {
|
|
141
|
+
origin: true,
|
|
142
|
+
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
|
|
143
|
+
});
|
|
144
|
+
const mcpController = new McpController(this.mcpService);
|
|
145
|
+
const upstreamController = new UpstreamController(this.upstreamService, this.db, this.securityService);
|
|
146
|
+
const routerController = new RouterController(this.routerService);
|
|
147
|
+
const securityController = new SecurityController(this.securityService);
|
|
148
|
+
const checkpointController = new CheckpointController(this.checkpointService);
|
|
149
|
+
const dashboardController = new DashboardController(this.dashboardService);
|
|
150
|
+
mcpController.registerRoutes(this.server);
|
|
151
|
+
upstreamController.registerRoutes(this.server);
|
|
152
|
+
routerController.registerRoutes(this.server);
|
|
153
|
+
securityController.registerRoutes(this.server);
|
|
154
|
+
checkpointController.registerRoutes(this.server);
|
|
155
|
+
dashboardController.registerRoutes(this.server);
|
|
156
|
+
this.registerSignalHandlers();
|
|
157
|
+
const boundPort = await this.listenWithFallback(this.config.port, this.config.host);
|
|
158
|
+
this.config.port = boundPort;
|
|
159
|
+
this.dashboardService.setPort(boundPort);
|
|
160
|
+
process.stdout.write(`\n⚡ NexusMCP Gateway listening at http://${this.config.host}:${boundPort}\n`);
|
|
161
|
+
process.stdout.write(`📊 Web Dashboard: http://localhost:${boundPort}\n`);
|
|
162
|
+
process.stdout.write(`🔌 MCP Endpoint: http://localhost:${boundPort}/mcp/sse\n\n`);
|
|
163
|
+
void this.upstreamService.initializeFromDatabase();
|
|
164
|
+
}
|
|
165
|
+
async listenWithFallback(startPort, host) {
|
|
166
|
+
for (let offset = 0; offset < 15; offset++) {
|
|
167
|
+
const candidate = startPort + offset;
|
|
168
|
+
try {
|
|
169
|
+
await this.server.listen({ port: candidate, host });
|
|
170
|
+
if (offset > 0) {
|
|
171
|
+
process.stdout.write(`ℹ Port ${startPort} is in use — automatically switched to port ${candidate}.\n`);
|
|
172
|
+
}
|
|
173
|
+
return candidate;
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
const code = err?.code;
|
|
177
|
+
if (code === "EADDRINUSE" && offset < 14) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
throw err;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return startPort;
|
|
184
|
+
}
|
|
185
|
+
registerSignalHandlers() {
|
|
186
|
+
const shutdown = async () => {
|
|
187
|
+
this.mcpService.shutdown();
|
|
188
|
+
this.upstreamService.disconnectAll();
|
|
189
|
+
this.upstreamService.shutdown();
|
|
190
|
+
this.db.close();
|
|
191
|
+
await this.server.close();
|
|
192
|
+
process.exit(0);
|
|
193
|
+
};
|
|
194
|
+
process.on("SIGINT", shutdown);
|
|
195
|
+
process.on("SIGTERM", shutdown);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const app = new Application();
|
|
199
|
+
const cliArg = process.argv[2];
|
|
200
|
+
if (cliArg && ["wrap", "unwrap", "list", "add", "rollback", "diff"].includes(cliArg)) {
|
|
201
|
+
app.runCli(cliArg, process.argv.slice(3)).then(() => process.exit(0));
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
app.start().catch((err) => {
|
|
205
|
+
process.stderr.write(`Fatal Error during startup: ${err}\n`);
|
|
206
|
+
process.exit(1);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import readline from "node:readline";
|
|
2
|
+
export class MockGitLabServer {
|
|
3
|
+
static start() {
|
|
4
|
+
const rl = readline.createInterface({
|
|
5
|
+
input: process.stdin,
|
|
6
|
+
output: process.stdout,
|
|
7
|
+
terminal: false
|
|
8
|
+
});
|
|
9
|
+
rl.on("line", (line) => {
|
|
10
|
+
try {
|
|
11
|
+
const req = JSON.parse(line);
|
|
12
|
+
if (req.method === "initialize") {
|
|
13
|
+
process.stdout.write(JSON.stringify({
|
|
14
|
+
jsonrpc: "2.0",
|
|
15
|
+
id: req.id,
|
|
16
|
+
result: {
|
|
17
|
+
protocolVersion: "2024-11-05",
|
|
18
|
+
capabilities: { tools: {} },
|
|
19
|
+
serverInfo: { name: "mock-gitlab", version: "1.0.0" }
|
|
20
|
+
}
|
|
21
|
+
}) + "\n");
|
|
22
|
+
}
|
|
23
|
+
else if (req.method === "tools/list") {
|
|
24
|
+
process.stdout.write(JSON.stringify({
|
|
25
|
+
jsonrpc: "2.0",
|
|
26
|
+
id: req.id,
|
|
27
|
+
result: {
|
|
28
|
+
tools: [
|
|
29
|
+
{
|
|
30
|
+
name: "gitlab_create_mr",
|
|
31
|
+
description: "Creates a new merge request in a GitLab project repository.",
|
|
32
|
+
inputSchema: {
|
|
33
|
+
type: "object",
|
|
34
|
+
properties: {
|
|
35
|
+
title: { type: "string" },
|
|
36
|
+
source_branch: { type: "string" },
|
|
37
|
+
target_branch: { type: "string" }
|
|
38
|
+
},
|
|
39
|
+
required: ["title", "source_branch"]
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "gitlab_get_diff",
|
|
44
|
+
description: "Retrieves the commit diffs and code changes for an active merge request.",
|
|
45
|
+
inputSchema: {
|
|
46
|
+
type: "object",
|
|
47
|
+
properties: {
|
|
48
|
+
mr_id: { type: "number" }
|
|
49
|
+
},
|
|
50
|
+
required: ["mr_id"]
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: "gitlab_add_comment",
|
|
55
|
+
description: "Adds a code review comment or discussion note to a GitLab merge request.",
|
|
56
|
+
inputSchema: {
|
|
57
|
+
type: "object",
|
|
58
|
+
properties: {
|
|
59
|
+
mr_id: { type: "number" },
|
|
60
|
+
comment: { type: "string" }
|
|
61
|
+
},
|
|
62
|
+
required: ["mr_id", "comment"]
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
}) + "\n");
|
|
68
|
+
}
|
|
69
|
+
else if (req.method === "tools/call") {
|
|
70
|
+
process.stdout.write(JSON.stringify({
|
|
71
|
+
jsonrpc: "2.0",
|
|
72
|
+
id: req.id,
|
|
73
|
+
result: {
|
|
74
|
+
content: [
|
|
75
|
+
{
|
|
76
|
+
type: "text",
|
|
77
|
+
text: `Mock GitLab success: executed ${req.params?.name} with arguments: ${JSON.stringify(req.params?.arguments)}. User email: dev-team@internal.corp, Token: glpat-super-secret-12345`
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}
|
|
81
|
+
}) + "\n");
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch { }
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
MockGitLabServer.start();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
export class CommonUtils {
|
|
3
|
+
static generateId(prefix = "id") {
|
|
4
|
+
return `${prefix}_${randomUUID().replace(/-/g, "").substring(0, 12)}`;
|
|
5
|
+
}
|
|
6
|
+
static successResponse(data) {
|
|
7
|
+
return {
|
|
8
|
+
success: true,
|
|
9
|
+
data,
|
|
10
|
+
timestamp: Date.now()
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
static errorResponse(message) {
|
|
14
|
+
return {
|
|
15
|
+
success: false,
|
|
16
|
+
error: message,
|
|
17
|
+
timestamp: Date.now()
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
static safeJsonParse(raw, fallback) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(raw);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return fallback;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
export class DatabaseService {
|
|
3
|
+
db;
|
|
4
|
+
constructor(config) {
|
|
5
|
+
this.db = new DatabaseSync(config.path);
|
|
6
|
+
this.initializeSchema();
|
|
7
|
+
}
|
|
8
|
+
initializeSchema() {
|
|
9
|
+
this.db.exec("PRAGMA journal_mode = WAL;");
|
|
10
|
+
this.db.exec("PRAGMA foreign_keys = ON;");
|
|
11
|
+
this.db.exec(`
|
|
12
|
+
CREATE TABLE IF NOT EXISTS servers (
|
|
13
|
+
id TEXT PRIMARY KEY,
|
|
14
|
+
name TEXT UNIQUE NOT NULL,
|
|
15
|
+
transport TEXT NOT NULL,
|
|
16
|
+
command TEXT,
|
|
17
|
+
args TEXT,
|
|
18
|
+
url TEXT,
|
|
19
|
+
env TEXT,
|
|
20
|
+
status TEXT NOT NULL DEFAULT 'disconnected',
|
|
21
|
+
error_message TEXT,
|
|
22
|
+
created_at INTEGER NOT NULL,
|
|
23
|
+
updated_at INTEGER NOT NULL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
CREATE TABLE IF NOT EXISTS tools (
|
|
27
|
+
id TEXT PRIMARY KEY,
|
|
28
|
+
server_id TEXT NOT NULL,
|
|
29
|
+
name TEXT UNIQUE NOT NULL,
|
|
30
|
+
description TEXT NOT NULL,
|
|
31
|
+
schema_json TEXT NOT NULL,
|
|
32
|
+
domain TEXT NOT NULL,
|
|
33
|
+
is_active INTEGER NOT NULL DEFAULT 1,
|
|
34
|
+
created_at INTEGER NOT NULL,
|
|
35
|
+
FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
39
|
+
id TEXT PRIMARY KEY,
|
|
40
|
+
client_name TEXT NOT NULL,
|
|
41
|
+
connected_at INTEGER NOT NULL,
|
|
42
|
+
last_active INTEGER NOT NULL,
|
|
43
|
+
is_active INTEGER NOT NULL DEFAULT 1
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
CREATE TABLE IF NOT EXISTS audit_logs (
|
|
47
|
+
id TEXT PRIMARY KEY,
|
|
48
|
+
session_id TEXT NOT NULL,
|
|
49
|
+
tool_name TEXT NOT NULL,
|
|
50
|
+
parameters TEXT NOT NULL,
|
|
51
|
+
duration_ms INTEGER NOT NULL,
|
|
52
|
+
status TEXT NOT NULL,
|
|
53
|
+
tokens_saved INTEGER NOT NULL DEFAULT 0,
|
|
54
|
+
created_at INTEGER NOT NULL
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
CREATE INDEX IF NOT EXISTS idx_tools_server ON tools(server_id);
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_tools_domain ON tools(domain);
|
|
59
|
+
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
|
|
60
|
+
`);
|
|
61
|
+
}
|
|
62
|
+
upsertServer(server) {
|
|
63
|
+
const stmt = this.db.prepare(`
|
|
64
|
+
INSERT INTO servers (id, name, transport, command, args, url, env, status, error_message, created_at, updated_at)
|
|
65
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
66
|
+
ON CONFLICT(name) DO UPDATE SET
|
|
67
|
+
transport = excluded.transport,
|
|
68
|
+
command = excluded.command,
|
|
69
|
+
args = excluded.args,
|
|
70
|
+
url = excluded.url,
|
|
71
|
+
env = excluded.env,
|
|
72
|
+
status = excluded.status,
|
|
73
|
+
error_message = excluded.error_message,
|
|
74
|
+
updated_at = excluded.updated_at
|
|
75
|
+
`);
|
|
76
|
+
stmt.run(server.id, server.name, server.transport, server.command, server.args, server.url, server.env, server.status, server.error_message, server.created_at, server.updated_at);
|
|
77
|
+
}
|
|
78
|
+
updateServerStatus(id, status, error = null) {
|
|
79
|
+
const stmt = this.db.prepare(`
|
|
80
|
+
UPDATE servers SET status = ?, error_message = ?, updated_at = ? WHERE id = ?
|
|
81
|
+
`);
|
|
82
|
+
stmt.run(status, error, Date.now(), id);
|
|
83
|
+
}
|
|
84
|
+
getAllServers() {
|
|
85
|
+
return this.db.prepare("SELECT * FROM servers ORDER BY name ASC").all();
|
|
86
|
+
}
|
|
87
|
+
getServerById(id) {
|
|
88
|
+
return this.db.prepare("SELECT * FROM servers WHERE id = ?").get(id);
|
|
89
|
+
}
|
|
90
|
+
getServerByName(name) {
|
|
91
|
+
return this.db.prepare("SELECT * FROM servers WHERE name = ?").get(name);
|
|
92
|
+
}
|
|
93
|
+
deleteServer(id) {
|
|
94
|
+
this.db.prepare("DELETE FROM servers WHERE id = ?").run(id);
|
|
95
|
+
}
|
|
96
|
+
upsertTool(tool) {
|
|
97
|
+
const stmt = this.db.prepare(`
|
|
98
|
+
INSERT INTO tools (id, server_id, name, description, schema_json, domain, is_active, created_at)
|
|
99
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
100
|
+
ON CONFLICT(name) DO UPDATE SET
|
|
101
|
+
server_id = excluded.server_id,
|
|
102
|
+
description = excluded.description,
|
|
103
|
+
schema_json = excluded.schema_json,
|
|
104
|
+
domain = excluded.domain,
|
|
105
|
+
is_active = excluded.is_active
|
|
106
|
+
`);
|
|
107
|
+
stmt.run(tool.id, tool.server_id, tool.name, tool.description, tool.schema_json, tool.domain, tool.is_active, tool.created_at);
|
|
108
|
+
}
|
|
109
|
+
clearToolsByServerId(serverId) {
|
|
110
|
+
this.db.prepare("DELETE FROM tools WHERE server_id = ?").run(serverId);
|
|
111
|
+
}
|
|
112
|
+
getAllActiveTools() {
|
|
113
|
+
return this.db.prepare("SELECT * FROM tools WHERE is_active = 1").all();
|
|
114
|
+
}
|
|
115
|
+
getToolByName(name) {
|
|
116
|
+
return this.db.prepare("SELECT * FROM tools WHERE name = ? AND is_active = 1").get(name);
|
|
117
|
+
}
|
|
118
|
+
registerSession(session) {
|
|
119
|
+
const stmt = this.db.prepare(`
|
|
120
|
+
INSERT INTO sessions (id, client_name, connected_at, last_active, is_active)
|
|
121
|
+
VALUES (?, ?, ?, ?, ?)
|
|
122
|
+
ON CONFLICT(id) DO UPDATE SET last_active = excluded.last_active, is_active = 1
|
|
123
|
+
`);
|
|
124
|
+
stmt.run(session.id, session.client_name, session.connected_at, session.last_active, session.is_active);
|
|
125
|
+
}
|
|
126
|
+
closeSession(sessionId) {
|
|
127
|
+
this.db.prepare("UPDATE sessions SET is_active = 0, last_active = ? WHERE id = ?").run(Date.now(), sessionId);
|
|
128
|
+
}
|
|
129
|
+
logAudit(log) {
|
|
130
|
+
const stmt = this.db.prepare(`
|
|
131
|
+
INSERT INTO audit_logs (id, session_id, tool_name, parameters, duration_ms, status, tokens_saved, created_at)
|
|
132
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
133
|
+
`);
|
|
134
|
+
stmt.run(log.id, log.session_id, log.tool_name, log.parameters, log.duration_ms, log.status, log.tokens_saved, log.created_at);
|
|
135
|
+
}
|
|
136
|
+
getAuditStats() {
|
|
137
|
+
const row = this.db.prepare(`
|
|
138
|
+
SELECT COUNT(*) as total_calls, COALESCE(SUM(tokens_saved), 0) as tokens_saved FROM audit_logs
|
|
139
|
+
`).get();
|
|
140
|
+
return {
|
|
141
|
+
total_calls: Number(row?.total_calls || 0),
|
|
142
|
+
tokens_saved: Number(row?.tokens_saved || 0)
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
getRecentLogs(limit = 20) {
|
|
146
|
+
return this.db.prepare("SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT ?").all(limit);
|
|
147
|
+
}
|
|
148
|
+
close() {
|
|
149
|
+
this.db.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { CommonUtils } from "../../common/utils.js";
|
|
2
|
+
export class CheckpointController {
|
|
3
|
+
checkpointService;
|
|
4
|
+
constructor(checkpointService) {
|
|
5
|
+
this.checkpointService = checkpointService;
|
|
6
|
+
}
|
|
7
|
+
registerRoutes(server) {
|
|
8
|
+
server.post("/api/checkpoint/create", this.createCheckpoint.bind(this));
|
|
9
|
+
server.post("/api/checkpoint/rollback", this.rollback.bind(this));
|
|
10
|
+
server.get("/api/checkpoint/diff", this.getDiff.bind(this));
|
|
11
|
+
server.get("/api/checkpoint/list", this.listCheckpoints.bind(this));
|
|
12
|
+
}
|
|
13
|
+
async createCheckpoint(req, reply) {
|
|
14
|
+
const name = req.body?.name || "manual_checkpoint";
|
|
15
|
+
const record = this.checkpointService.createCheckpoint(name);
|
|
16
|
+
reply.send(CommonUtils.successResponse(record));
|
|
17
|
+
}
|
|
18
|
+
async rollback(_req, reply) {
|
|
19
|
+
const result = this.checkpointService.rollbackLatest();
|
|
20
|
+
reply.send(CommonUtils.successResponse(result));
|
|
21
|
+
}
|
|
22
|
+
async getDiff(_req, reply) {
|
|
23
|
+
const diff = this.checkpointService.getDiff();
|
|
24
|
+
reply.send(CommonUtils.successResponse(diff));
|
|
25
|
+
}
|
|
26
|
+
async listCheckpoints(_req, reply) {
|
|
27
|
+
const list = this.checkpointService.listCheckpoints();
|
|
28
|
+
reply.send(CommonUtils.successResponse(list));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { CheckpointUtils } from "./utils.js";
|
|
2
|
+
import { CommonUtils } from "../../common/utils.js";
|
|
3
|
+
export class CheckpointService {
|
|
4
|
+
checkpoints = [];
|
|
5
|
+
cwd;
|
|
6
|
+
constructor(workspaceDir = process.cwd()) {
|
|
7
|
+
this.cwd = workspaceDir;
|
|
8
|
+
}
|
|
9
|
+
createCheckpoint(name) {
|
|
10
|
+
if (!CheckpointUtils.isGitRepository(this.cwd)) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
const hash = CheckpointUtils.createStashCommit(this.cwd);
|
|
14
|
+
if (!hash) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
const record = {
|
|
18
|
+
id: CommonUtils.generateId("chk"),
|
|
19
|
+
name,
|
|
20
|
+
commitHash: hash,
|
|
21
|
+
createdAt: Date.now()
|
|
22
|
+
};
|
|
23
|
+
this.checkpoints.push(record);
|
|
24
|
+
if (this.checkpoints.length > 50) {
|
|
25
|
+
this.checkpoints.shift();
|
|
26
|
+
}
|
|
27
|
+
return record;
|
|
28
|
+
}
|
|
29
|
+
rollbackLatest() {
|
|
30
|
+
if (!CheckpointUtils.isGitRepository(this.cwd)) {
|
|
31
|
+
return { success: false, restoredCommit: "", message: "Workspace is not a Git repository." };
|
|
32
|
+
}
|
|
33
|
+
const latest = this.checkpoints.pop();
|
|
34
|
+
if (!latest) {
|
|
35
|
+
return { success: false, restoredCommit: "", message: "No checkpoints available to rollback to." };
|
|
36
|
+
}
|
|
37
|
+
const restored = CheckpointUtils.restoreCommit(this.cwd, latest.commitHash);
|
|
38
|
+
return {
|
|
39
|
+
success: restored,
|
|
40
|
+
restoredCommit: latest.commitHash,
|
|
41
|
+
message: restored
|
|
42
|
+
? `Successfully reverted workspace to checkpoint "${latest.name}" (${latest.commitHash.substring(0, 7)}).`
|
|
43
|
+
: `Failed to restore git tree to commit ${latest.commitHash}.`
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
getDiff() {
|
|
47
|
+
if (!CheckpointUtils.isGitRepository(this.cwd)) {
|
|
48
|
+
return { hasChanges: false, diff: "Not a Git repository." };
|
|
49
|
+
}
|
|
50
|
+
const diffText = CheckpointUtils.getGitDiff(this.cwd);
|
|
51
|
+
return {
|
|
52
|
+
hasChanges: diffText.length > 0,
|
|
53
|
+
diff: diffText || "Workspace clean. No unstaged or staged diffs."
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
listCheckpoints() {
|
|
57
|
+
return [...this.checkpoints];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
export class CheckpointUtils {
|
|
3
|
+
static isGitRepository(cwd) {
|
|
4
|
+
try {
|
|
5
|
+
execSync("git rev-parse --is-inside-work-tree", { cwd, stdio: "ignore" });
|
|
6
|
+
return true;
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
static createStashCommit(cwd) {
|
|
13
|
+
try {
|
|
14
|
+
const output = execSync("git stash create", { cwd, encoding: "utf-8" }).trim();
|
|
15
|
+
if (output.length > 0) {
|
|
16
|
+
return output;
|
|
17
|
+
}
|
|
18
|
+
return execSync("git rev-parse HEAD", { cwd, encoding: "utf-8" }).trim();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
static restoreCommit(cwd, commitHash) {
|
|
25
|
+
try {
|
|
26
|
+
execSync(`git read-tree --reset -u ${commitHash}`, { cwd, stdio: "ignore" });
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
static getGitDiff(cwd) {
|
|
34
|
+
try {
|
|
35
|
+
return execSync("git diff HEAD", { cwd, encoding: "utf-8" }).trim();
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|