@anurag134/nexusmcp 0.0.0-stage → 1.0.1

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 +84 -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 +47 -4
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # NexusMCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Local-First MCP Gateway, Semantic Tool Router & Zero-Trust Security Layer**
4
+
5
+ Connect 50+ MCP servers behind a single local gateway (`http://localhost:3000/mcp/sse`) without flooding your AI client's context window or storing credentials in plain text.
6
+
7
+ > **Demo:** Record a 15-second walkthrough of `http://localhost:3000` (search $\rightarrow$ `mcp.json` connect $\rightarrow$ live logs) and save it as `docs/demo.gif` in your public GitHub repo so it renders on both GitHub and npm:
8
+ >
9
+ > `![NexusMCP Demo](https://raw.githubusercontent.com/Anurag6212/NexusMCP/main/docs/demo.gif)`
10
+
11
+ ---
12
+
13
+ ## The Problem NexusMCP Solves
14
+
15
+ 1. **Context Window Bloat:** Connecting 20–50 MCP servers directly to Cursor or Claude Desktop injects 300+ tool schemas into every prompt (~75,000+ wasted tokens).
16
+ 2. **Credential Trust & `.zshrc` Friction:** Cloud-hosted MCP gateways ask you to paste personal tokens onto someone else's server, while raw CLI setups force users to manually maintain `.env` / `.zshrc` files.
17
+ 3. **Opaque Startup Failures:** When an upstream `npx` or OAuth server fails, IDEs rarely surface `stderr`, cold-start delays, or missing environment variable names clearly.
18
+
19
+ ---
20
+
21
+ ## How It Works (End-to-End Flow)
22
+
23
+ ```mermaid
24
+ flowchart LR
25
+ IDE["AI IDE (Cursor / Claude / Cline)"] -- "1. SSE (/mcp/sse)" --> GW["NexusMCP Gateway"]
26
+ GW -- "2. nexus_search_tools" --> SR["In-Memory Semantic Vector Router"]
27
+ SR -- "Top-K matching tools" --> IDE
28
+ IDE -- "3. nexus_execute" --> SG["Security Gate + OS Vault"]
29
+ SG -- "4. Spawn & inject in memory" --> UP["Upstream MCPs (GitHub, Filesystem, Playwright, ...)"]
30
+ UP -- "5. PII & Token Redaction + Output Pruning" --> IDE
31
+ ```
32
+
33
+ 1. **Single Gateway Connection:** Your IDE connects only to `nexusmcp` (`http://localhost:3000/mcp/sse`), seeing 5 lightweight synthetic tools (`nexus_search_tools`, `nexus_execute`, `nexus_list_servers`, `nexus_rollback`, `nexus_diff`).
34
+ 2. **On-Demand Semantic Routing:** When your AI needs a tool, it calls `nexus_search_tools`. NexusMCP's subword cosine-similarity router returns only the top relevant tools and logs estimated schema tokens saved (~250 tokens per filtered-out tool).
35
+ 3. **Zero-Credential Database:** Secrets entered in `mcp.json` are stored in your **OS-native credential layer** (Windows DPAPI, macOS Keychain, Linux `secret-tool`)—SQLite only stores `"__OS_VAULT__"` markers.
36
+ 4. **Scoped Safety & Output Redaction:** Destructive SQL/shell commands (`DROP DATABASE`, `rm -rf`, `.env` path access) are blocked before execution, and any leaked tokens (`ghp_`, `github_pat_`, `sk-`, `AKIA`, Bearer tokens, or active vault secrets) are redacted from tool outputs before reaching the LLM.
37
+
38
+ ---
39
+
40
+ ## Quick Start (60 Seconds)
41
+
42
+ ### 1. Start NexusMCP locally
43
+
44
+ ```bash
45
+ npx -y @anurag134/nexusmcp
46
+ ```
47
+
48
+ * Requirements: **Node.js 24+** (uses built-in `node:sqlite`).
49
+ * If port `3000` is busy, NexusMCP automatically switches to `3001+` (or pass `--port 4500`).
50
+
51
+ ### 2. Add Upstream MCPs at `http://localhost:3000`
52
+
53
+ - **Paste `mcp.json`:** Drop any standard `{ "mcpServers": { ... } }` config and click **Save & Connect All** (connects up to 6 servers in parallel with a live progress bar).
54
+ - **Search / Auto-Extract:** Type any tool name (e.g. `github`, `postgres`) or paste a GitHub repo URL—NexusMCP queries npm & `registry.modelcontextprotocol.io`, extracts the `mcp.json` + env vars from the README, and populates the editor.
55
+ - **1-Click IDE Migration:** Click **Wrap Cursor Config** (or run `npx -y @anurag134/nexusmcp wrap`) to import `~/.cursor/mcp.json` with automatic backup and restore.
56
+
57
+ ### 3. Connect Your AI IDE
58
+
59
+ Add this single entry to Cursor (`~/.cursor/mcp.json`), Claude Desktop, or VS Code Cline:
60
+
61
+ ```json
62
+ {
63
+ "mcpServers": {
64
+ "nexusmcp": {
65
+ "url": "http://localhost:3000/mcp/sse"
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ *(Use the exact port printed in your terminal or click the SSE pill in the dashboard header to copy it.)*
72
+
73
+ ---
74
+
75
+ ## CLI Reference
76
+
77
+ ```bash
78
+ npx -y @anurag134/nexusmcp # Start gateway + web control plane
79
+ npx -y @anurag134/nexusmcp --port 4500 # Start on a custom port
80
+ npx -y @anurag134/nexusmcp wrap # Import ~/.cursor/mcp.json and wrap Cursor
81
+ npx -y @anurag134/nexusmcp unwrap # Restore original ~/.cursor/mcp.json backup
82
+ npx -y @anurag134/nexusmcp list # List registered servers and indexed tools
83
+ npx -y @anurag134/nexusmcp diff # Inspect git diff since last checkpoint
84
+ npx -y @anurag134/nexusmcp rollback # Roll back to latest git checkpoint
85
+ ```
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 {};