@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,874 @@
1
+ import path from "node:path";
2
+ import os from "node:os";
3
+ export class DashboardUtils {
4
+ static getCursorMcpConfigPath() {
5
+ const home = os.homedir();
6
+ if (process.platform === "win32") {
7
+ return path.join(home, ".cursor", "mcp.json");
8
+ }
9
+ return path.join(home, ".cursor", "mcp.json");
10
+ }
11
+ static getClaudeMcpConfigPath() {
12
+ const home = os.homedir();
13
+ if (process.platform === "win32") {
14
+ return path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
15
+ }
16
+ if (process.platform === "darwin") {
17
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
18
+ }
19
+ return path.join(home, ".config", "Claude", "claude_desktop_config.json");
20
+ }
21
+ static getDashboardHtml() {
22
+ return `<!DOCTYPE html>
23
+ <html lang="en">
24
+ <head>
25
+ <meta charset="UTF-8">
26
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
27
+ <title>NexusMCP — Control Plane</title>
28
+ <style>
29
+ :root {
30
+ --bg: #09090b;
31
+ --surface: #111113;
32
+ --surface-2: #18181b;
33
+ --border: #27272a;
34
+ --text: #fafafa;
35
+ --muted: #a1a1aa;
36
+ --subtle: #71717a;
37
+ --primary: #3b82f6;
38
+ --success: #22c55e;
39
+ --danger: #ef4444;
40
+ --mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
41
+ }
42
+ * { box-sizing: border-box; }
43
+ body {
44
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
45
+ background: var(--bg);
46
+ color: var(--text);
47
+ margin: 0;
48
+ padding: 28px 20px;
49
+ line-height: 1.5;
50
+ font-size: 14px;
51
+ }
52
+ .container { max-width: 1080px; margin: 0 auto; }
53
+ header {
54
+ display: flex;
55
+ justify-content: space-between;
56
+ align-items: center;
57
+ padding-bottom: 18px;
58
+ margin-bottom: 24px;
59
+ border-bottom: 1px solid var(--border);
60
+ flex-wrap: wrap;
61
+ gap: 12px;
62
+ }
63
+ .brand { display: flex; align-items: center; gap: 12px; }
64
+ .brand h1 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: -0.02em; }
65
+ .brand span { color: var(--subtle); font-size: 12px; font-family: var(--mono); }
66
+ .header-meta { display: flex; gap: 8px; align-items: center; }
67
+ .pill {
68
+ display: inline-flex;
69
+ align-items: center;
70
+ gap: 6px;
71
+ font-size: 12px;
72
+ padding: 4px 10px;
73
+ border-radius: 6px;
74
+ background: var(--surface-2);
75
+ border: 1px solid var(--border);
76
+ color: var(--muted);
77
+ font-family: var(--mono);
78
+ }
79
+ .dot { width: 7px; height: 7px; border-radius: 50%; display: inline-block; }
80
+ .dot-green { background: var(--success); }
81
+ .dot-red { background: var(--danger); }
82
+ .dot-amber { background: #f59e0b; animation: pulse 1s ease-in-out infinite; }
83
+ .dot-muted { background: var(--subtle); }
84
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
85
+ .spinner {
86
+ width: 12px;
87
+ height: 12px;
88
+ border: 2px solid #3f3f46;
89
+ border-top-color: #f59e0b;
90
+ border-radius: 50%;
91
+ display: inline-block;
92
+ animation: spin 0.7s linear infinite;
93
+ }
94
+ @keyframes spin { to { transform: rotate(360deg); } }
95
+ .progress-banner {
96
+ display: none;
97
+ padding: 12px 18px;
98
+ border-bottom: 1px solid var(--border);
99
+ background: #141417;
100
+ }
101
+ .progress-track {
102
+ width: 100%;
103
+ height: 6px;
104
+ background: var(--bg);
105
+ border-radius: 99px;
106
+ overflow: hidden;
107
+ margin-top: 8px;
108
+ border: 1px solid var(--border);
109
+ }
110
+ .progress-fill {
111
+ height: 100%;
112
+ background: var(--primary);
113
+ transition: width 0.3s ease;
114
+ width: 0%;
115
+ }
116
+
117
+ .metrics {
118
+ display: grid;
119
+ grid-template-columns: repeat(4, 1fr);
120
+ gap: 12px;
121
+ margin-bottom: 24px;
122
+ }
123
+ @media (max-width: 760px) { .metrics { grid-template-columns: repeat(2, 1fr); } }
124
+ .metric {
125
+ background: var(--surface);
126
+ border: 1px solid var(--border);
127
+ border-radius: 8px;
128
+ padding: 14px 16px;
129
+ position: relative;
130
+ }
131
+ .metric-label { font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
132
+ .metric-value { font-size: 22px; font-weight: 600; margin-top: 4px; font-variant-numeric: tabular-nums; }
133
+ .metric-sub { font-size: 11px; color: var(--subtle); margin-top: 2px; font-family: var(--mono); }
134
+ .info-tip {
135
+ position: relative;
136
+ display: inline-flex;
137
+ align-items: center;
138
+ justify-content: center;
139
+ width: 15px;
140
+ height: 15px;
141
+ border-radius: 50%;
142
+ border: 1px solid var(--border);
143
+ background: var(--surface-2);
144
+ color: var(--muted);
145
+ font-size: 10px;
146
+ font-family: var(--mono);
147
+ cursor: help;
148
+ }
149
+ .info-tip .tip-text {
150
+ visibility: hidden;
151
+ opacity: 0;
152
+ position: absolute;
153
+ bottom: calc(100% + 8px);
154
+ left: 50%;
155
+ transform: translateX(-50%);
156
+ width: 230px;
157
+ background: #18181b;
158
+ color: #e4e4e7;
159
+ border: 1px solid #3f3f46;
160
+ border-radius: 6px;
161
+ padding: 8px 10px;
162
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", sans-serif;
163
+ font-size: 11px;
164
+ line-height: 1.45;
165
+ z-index: 20;
166
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
167
+ pointer-events: none;
168
+ transition: opacity 0.15s ease;
169
+ }
170
+ .info-tip:hover .tip-text, .info-tip:focus .tip-text {
171
+ visibility: visible;
172
+ opacity: 1;
173
+ }
174
+
175
+ .panel {
176
+ background: var(--surface);
177
+ border: 1px solid var(--border);
178
+ border-radius: 8px;
179
+ margin-bottom: 20px;
180
+ overflow: hidden;
181
+ }
182
+ .panel-header {
183
+ display: flex;
184
+ justify-content: space-between;
185
+ align-items: center;
186
+ padding: 14px 18px;
187
+ border-bottom: 1px solid var(--border);
188
+ background: var(--surface-2);
189
+ flex-wrap: wrap;
190
+ gap: 10px;
191
+ }
192
+ .panel-title { font-size: 14px; font-weight: 600; margin: 0; }
193
+ .panel-body { padding: 18px; }
194
+
195
+ .field { margin-bottom: 14px; }
196
+ .label { display: block; font-size: 12px; font-weight: 500; color: var(--muted); margin-bottom: 6px; }
197
+ .input, .textarea {
198
+ width: 100%;
199
+ background: var(--bg);
200
+ border: 1px solid var(--border);
201
+ color: var(--text);
202
+ padding: 9px 12px;
203
+ border-radius: 6px;
204
+ font-size: 13px;
205
+ outline: none;
206
+ }
207
+ .input:focus, .textarea:focus { border-color: var(--primary); }
208
+ .mono { font-family: var(--mono); }
209
+ .textarea { min-height: 230px; resize: vertical; line-height: 1.5; }
210
+
211
+ .btn {
212
+ display: inline-flex;
213
+ align-items: center;
214
+ justify-content: center;
215
+ gap: 6px;
216
+ background: var(--text);
217
+ color: var(--bg);
218
+ border: 1px solid transparent;
219
+ padding: 7px 14px;
220
+ border-radius: 6px;
221
+ font-size: 12px;
222
+ font-weight: 600;
223
+ cursor: pointer;
224
+ }
225
+ .btn:hover { opacity: 0.9; }
226
+ .btn:disabled { opacity: 0.45; cursor: not-allowed; }
227
+ .btn-ghost { background: var(--surface-2); color: var(--text); border-color: var(--border); }
228
+ .btn-ghost:hover { border-color: var(--subtle); }
229
+ .btn-danger { background: transparent; color: var(--danger); border-color: #3f1d21; }
230
+ .btn-danger:hover { background: #2a1215; }
231
+ .btn-sm { padding: 4px 9px; font-size: 12px; }
232
+
233
+ table { width: 100%; border-collapse: collapse; text-align: left; }
234
+ th, td { padding: 11px 14px; border-bottom: 1px solid var(--border); vertical-align: top; }
235
+ th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--subtle); font-weight: 600; }
236
+ tr:last-child td { border-bottom: none; }
237
+
238
+ .status-tag {
239
+ display: inline-flex;
240
+ align-items: center;
241
+ gap: 6px;
242
+ font-size: 12px;
243
+ font-family: var(--mono);
244
+ }
245
+ .err-inline {
246
+ margin-top: 5px;
247
+ font-size: 12px;
248
+ color: #fca5a5;
249
+ font-family: var(--mono);
250
+ max-width: 340px;
251
+ word-break: break-word;
252
+ }
253
+ .env-chip {
254
+ display: inline-block;
255
+ font-family: var(--mono);
256
+ font-size: 11px;
257
+ padding: 1px 6px;
258
+ border-radius: 4px;
259
+ background: var(--bg);
260
+ border: 1px solid var(--border);
261
+ color: var(--muted);
262
+ margin: 4px 4px 0 0;
263
+ }
264
+
265
+ .logs-panel {
266
+ background: var(--bg);
267
+ border-top: 1px solid var(--border);
268
+ padding: 14px 18px;
269
+ display: none;
270
+ }
271
+ .logs-panel.open { display: block; }
272
+ .log-stream {
273
+ background: #050507;
274
+ border: 1px solid var(--border);
275
+ border-radius: 6px;
276
+ padding: 12px;
277
+ font-family: var(--mono);
278
+ font-size: 12px;
279
+ line-height: 1.55;
280
+ max-height: 260px;
281
+ overflow-y: auto;
282
+ color: #d4d4d8;
283
+ }
284
+ .log-err { color: #f87171; }
285
+ .log-warn { color: #fbbf24; }
286
+ .hint-box {
287
+ margin-top: 10px;
288
+ padding: 10px 12px;
289
+ border-radius: 6px;
290
+ background: #1c1917;
291
+ border: 1px solid #44403c;
292
+ font-size: 12px;
293
+ color: #fde68a;
294
+ }
295
+ </style>
296
+ </head>
297
+ <body>
298
+ <div class="container">
299
+ <header>
300
+ <div class="brand">
301
+ <h1>NexusMCP</h1>
302
+ <span>local-gateway</span>
303
+ </div>
304
+ <div class="header-meta">
305
+ <span class="pill">OS Keychain / Zero-DB Secrets</span>
306
+ <span class="pill" id="sse-pill" style="cursor: pointer;" title="Click to copy SSE URL" onclick="copySseUrl()"><span class="dot dot-green"></span> <span id="sse-url-text">/mcp/sse</span></span>
307
+ </div>
308
+ </header>
309
+
310
+ <div class="metrics">
311
+ <div class="metric">
312
+ <div class="metric-label">
313
+ Upstream Servers
314
+ <span class="info-tip" tabindex="0">i<span class="tip-text">Total upstream MCP servers registered in NexusMCP, with the live connected count shown below.</span></span>
315
+ </div>
316
+ <div class="metric-value" id="stat-servers">0</div>
317
+ <div class="metric-sub" id="stat-connected">0 connected</div>
318
+ </div>
319
+ <div class="metric">
320
+ <div class="metric-label">
321
+ Indexed Tools
322
+ <span class="info-tip" tabindex="0">i<span class="tip-text">Total active tools currently indexed in NexusMCP's semantic router from connected servers.</span></span>
323
+ </div>
324
+ <div class="metric-value" id="stat-tools">0</div>
325
+ </div>
326
+ <div class="metric">
327
+ <div class="metric-label">
328
+ Tool Executions
329
+ <span class="info-tip" tabindex="0">i<span class="tip-text">Total MCP gateway calls (nexus_search_tools and nexus_execute) logged in the local audit database.</span></span>
330
+ </div>
331
+ <div class="metric-value" id="stat-execs">0</div>
332
+ </div>
333
+ <div class="metric">
334
+ <div class="metric-label">
335
+ Tokens Saved
336
+ <span class="info-tip" tabindex="0">i<span class="tip-text">Estimated context tokens saved by filtering irrelevant tool schemas (~250 tokens/tool) and pruning verbose tool outputs.</span></span>
337
+ </div>
338
+ <div class="metric-value" id="stat-tokens">0</div>
339
+ </div>
340
+ </div>
341
+
342
+ <div class="panel">
343
+ <div class="panel-header">
344
+ <h2 class="panel-title">Add or Update MCP Servers (mcp.json)</h2>
345
+ <span style="font-size: 12px; color: var(--subtle); font-family: var(--mono);">Single Source of Truth</span>
346
+ </div>
347
+
348
+ <div class="panel-body">
349
+ <div class="field" style="background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 12px;">
350
+ <label class="label">Find an MCP Server or Auto-Extract from GitHub / npm README</label>
351
+ <div style="display: flex; gap: 8px;">
352
+ <input type="text" id="registry-q" class="input mono" placeholder="Search by tool name (e.g. github, postgres, slack) OR paste a GitHub URL / npm package..." onkeydown="if(event.key==='Enter') searchOrExtract()" />
353
+ <button type="button" class="btn btn-ghost" id="registry-btn" onclick="searchOrExtract()">Search / Extract</button>
354
+ </div>
355
+ <div id="registry-results" style="margin-top: 10px; display: none;"></div>
356
+ </div>
357
+
358
+ <div class="field">
359
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
360
+ <label class="label" style="margin: 0;">Standard <code>mcp.json</code> Configuration (paste or edit directly)</label>
361
+ <button type="button" class="btn btn-ghost btn-sm" onclick="formatEditorJson()">Format JSON</button>
362
+ </div>
363
+ <textarea id="raw-mcp-json" class="textarea mono" placeholder='{
364
+ "mcpServers": {
365
+ "memory": {
366
+ "command": "npx",
367
+ "args": ["-y", "@modelcontextprotocol/server-memory"]
368
+ }
369
+ }
370
+ }'></textarea>
371
+ </div>
372
+
373
+ <div style="display: flex; align-items: center; gap: 10px;">
374
+ <button type="button" class="btn" id="import-btn" onclick="importMcpJson()">Save &amp; Connect All</button>
375
+ <button type="button" class="btn btn-ghost" onclick="clearEditor()">Clear</button>
376
+ <span id="import-status" style="font-size: 12px; color: var(--muted);"></span>
377
+ </div>
378
+ </div>
379
+ </div>
380
+
381
+ <div class="panel">
382
+ <div class="panel-header">
383
+ <h2 class="panel-title">Upstream Servers</h2>
384
+ <div style="display: flex; gap: 6px; align-items: center;">
385
+ <button type="button" class="btn btn-ghost btn-sm" onclick="loadStats()">Refresh</button>
386
+ <button type="button" class="btn btn-ghost btn-sm" onclick="disconnectAllServers()">Disconnect All</button>
387
+ <button type="button" class="btn btn-danger btn-sm" onclick="removeAllServers()">Remove All</button>
388
+ </div>
389
+ </div>
390
+ <div class="progress-banner" id="progress-banner">
391
+ <div style="display: flex; justify-content: space-between; align-items: center; font-size: 12px; gap: 8px; flex-wrap: wrap;">
392
+ <span style="display: inline-flex; align-items: center; gap: 8px;"><span class="spinner"></span> <strong id="progress-text">Connecting servers in parallel...</strong></span>
393
+ <div style="display: inline-flex; align-items: center; gap: 10px;">
394
+ <span class="mono" style="color: var(--muted);" id="progress-counts"></span>
395
+ <button type="button" class="btn btn-danger btn-sm" onclick="disconnectAllServers()">Stop Connecting</button>
396
+ </div>
397
+ </div>
398
+ <div class="progress-track"><div class="progress-fill" id="progress-fill"></div></div>
399
+ </div>
400
+ <table>
401
+ <thead>
402
+ <tr>
403
+ <th>Server</th>
404
+ <th>Status</th>
405
+ <th>Command &amp; Env Keys</th>
406
+ <th style="text-align: right;">Actions</th>
407
+ </tr>
408
+ </thead>
409
+ <tbody id="servers-table">
410
+ <tr><td colspan="4" style="text-align: center; color: var(--subtle);">Loading...</td></tr>
411
+ </tbody>
412
+ </table>
413
+
414
+ <div class="logs-panel" id="logs-panel">
415
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
416
+ <span style="font-size: 13px; font-weight: 600;" id="logs-title">Server Diagnostics</span>
417
+ <div style="display: flex; gap: 6px;">
418
+ <button type="button" class="btn btn-ghost btn-sm" onclick="refreshOpenLogs()">Refresh Logs</button>
419
+ <button type="button" class="btn btn-ghost btn-sm" onclick="closeLogs()">Close</button>
420
+ </div>
421
+ </div>
422
+ <div class="log-stream" id="log-stream">No logs recorded yet.</div>
423
+ <div id="quick-fix-box" style="display: none; margin-top: 10px; padding: 12px; border-radius: 6px; background: #18181b; border: 1px solid #3f3f46;"></div>
424
+ <div class="hint-box" id="log-hint" style="display: none;"></div>
425
+ </div>
426
+ </div>
427
+
428
+ <div class="panel">
429
+ <div class="panel-header">
430
+ <h2 class="panel-title">IDE Config Migration</h2>
431
+ </div>
432
+ <div class="panel-body" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
433
+ <div style="font-size: 13px; color: var(--muted); max-width: 620px;">
434
+ Import existing servers from <code>~/.cursor/mcp.json</code> into NexusMCP's local OS vault and route Cursor through a single endpoint.
435
+ </div>
436
+ <div style="display: flex; gap: 8px; align-items: center;">
437
+ <button type="button" class="btn btn-ghost" onclick="wrapIde()">Wrap Cursor Config</button>
438
+ <button type="button" class="btn btn-danger" onclick="unwrapIde()">Restore Original</button>
439
+ </div>
440
+ <div id="wrap-msg" style="width: 100%; font-size: 12px; color: var(--primary); display: none;"></div>
441
+ </div>
442
+ </div>
443
+ </div>
444
+
445
+ <script>
446
+ let cachedServers = [];
447
+ let openLogServerId = null;
448
+ let registryItems = [];
449
+
450
+ function esc(str) {
451
+ return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
452
+ }
453
+
454
+ function setEditorConfig(name, command, args, envObj) {
455
+ const entry = { command };
456
+ if (args && args.length > 0) entry.args = args;
457
+ if (envObj && Object.keys(envObj).length > 0) entry.env = envObj;
458
+ const doc = { mcpServers: { [name]: entry } };
459
+ document.getElementById('raw-mcp-json').value = JSON.stringify(doc, null, 2);
460
+ }
461
+
462
+ function formatEditorJson() {
463
+ const el = document.getElementById('raw-mcp-json');
464
+ try {
465
+ el.value = JSON.stringify(JSON.parse(el.value), null, 2);
466
+ document.getElementById('import-status').innerText = '';
467
+ } catch (e) {
468
+ document.getElementById('import-status').innerText = 'Invalid JSON: ' + e.message;
469
+ }
470
+ }
471
+
472
+ function clearEditor() {
473
+ document.getElementById('raw-mcp-json').value = '';
474
+ document.getElementById('import-status').innerText = '';
475
+ }
476
+
477
+ async function searchOrExtract() {
478
+ const q = document.getElementById('registry-q').value.trim();
479
+ const box = document.getElementById('registry-results');
480
+ const btn = document.getElementById('registry-btn');
481
+ if (!q) return;
482
+
483
+ if (q.startsWith('http://') || q.startsWith('https://') || q.startsWith('@')) {
484
+ btn.disabled = true;
485
+ box.style.display = 'block';
486
+ box.innerHTML = '<div style="font-size: 12px; color: var(--muted);">Extracting mcp.json and env vars from README...</div>';
487
+ try {
488
+ await extractAndPopulate(q);
489
+ box.innerHTML = '<div style="font-size: 12px; color: var(--success);">Populated mcp.json below. Replace any placeholder tokens and click Save &amp; Connect All.</div>';
490
+ } catch (e) {
491
+ box.innerHTML = '<div style="font-size: 12px; color: var(--danger);">Failed to extract configuration.</div>';
492
+ } finally {
493
+ btn.disabled = false;
494
+ }
495
+ return;
496
+ }
497
+
498
+ btn.disabled = true;
499
+ box.style.display = 'block';
500
+ box.innerHTML = '<div style="font-size: 12px; color: var(--muted);">Searching npm &amp; official MCP Registry...</div>';
501
+ try {
502
+ const res = await fetch('/api/upstream/registry?q=' + encodeURIComponent(q));
503
+ const json = await res.json();
504
+ registryItems = json.data || [];
505
+ if (registryItems.length === 0) {
506
+ box.innerHTML = '<div style="font-size: 12px; color: var(--subtle);">No MCP packages found for "' + esc(q) + '". Paste a GitHub URL or mcp.json directly.</div>';
507
+ return;
508
+ }
509
+ box.innerHTML = registryItems.map((item, idx) => \`
510
+ <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px; margin-bottom: 6px; background: var(--surface);">
511
+ <div style="min-width: 0;">
512
+ <div style="font-size: 13px; font-weight: 600;">\${esc(item.title)}</div>
513
+ <div style="font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 680px;">\${esc(item.description)}</div>
514
+ <div style="font-size: 11px; color: var(--subtle); font-family: var(--mono); margin-top: 2px;">\${esc(item.command + ' ' + (item.args || []).join(' '))}</div>
515
+ </div>
516
+ <div style="display: flex; gap: 6px; flex-shrink: 0;">
517
+ \${item.websiteUrl ? '<a href="' + esc(item.websiteUrl) + '" target="_blank" rel="noopener" class="btn btn-ghost btn-sm" style="text-decoration:none;">Docs</a>' : ''}
518
+ <button type="button" class="btn btn-sm" onclick="applyRegistryItem(\${idx})">Use</button>
519
+ </div>
520
+ </div>
521
+ \`).join('');
522
+ } catch (e) {
523
+ box.innerHTML = '<div style="font-size: 12px; color: var(--danger);">Failed to query registry.</div>';
524
+ } finally {
525
+ btn.disabled = false;
526
+ }
527
+ }
528
+
529
+ async function extractAndPopulate(source) {
530
+ const res = await fetch('/api/upstream/extract', {
531
+ method: 'POST',
532
+ headers: { 'Content-Type': 'application/json' },
533
+ body: JSON.stringify({ source })
534
+ });
535
+ const json = await res.json();
536
+ if (!json.success || !json.data) {
537
+ throw new Error(json.error || 'Extract failed');
538
+ }
539
+ const cfg = json.data;
540
+ const envObj = {};
541
+ (cfg.envVars || []).forEach(v => {
542
+ envObj[v.name] = v.defaultValue || ('<YOUR_' + v.name + '>');
543
+ });
544
+ setEditorConfig(cfg.name || 'mcp-server', cfg.command || 'npx', cfg.args || [], envObj);
545
+ }
546
+
547
+ async function applyRegistryItem(idx) {
548
+ const item = registryItems[idx];
549
+ if (!item) return;
550
+ const box = document.getElementById('registry-results');
551
+ if (item.extractSource) {
552
+ try {
553
+ await extractAndPopulate(item.extractSource);
554
+ box.innerHTML = '<div style="font-size: 12px; color: var(--success);">Populated mcp.json for ' + esc(item.title) + '. Replace any placeholder tokens and click Save &amp; Connect All.</div>';
555
+ return;
556
+ } catch {
557
+ // Fall back to direct item fields
558
+ }
559
+ }
560
+ const envObj = {};
561
+ (item.envVars || []).forEach(v => { envObj[v.name] = '<YOUR_' + v.name + '>'; });
562
+ setEditorConfig(item.shortName, item.command, item.args || [], envObj);
563
+ }
564
+
565
+ function editServer(id) {
566
+ const srv = cachedServers.find(s => s.id === id);
567
+ if (!srv) return;
568
+ let args = [];
569
+ let envObj = {};
570
+ try { args = JSON.parse(srv.args || '[]'); } catch {}
571
+ try { envObj = JSON.parse(srv.env || '{}'); } catch {}
572
+ setEditorConfig(srv.name, srv.command || 'npx', args, envObj);
573
+ document.getElementById('import-status').innerText = 'Loaded "' + srv.name + '" into mcp.json editor. Unchanged "••••••••" secrets are preserved.';
574
+ window.scrollTo({ top: 0, behavior: 'smooth' });
575
+ }
576
+
577
+ async function importMcpJson() {
578
+ const raw = document.getElementById('raw-mcp-json').value.trim();
579
+ const status = document.getElementById('import-status');
580
+ const btn = document.getElementById('import-btn');
581
+ let parsed;
582
+ try {
583
+ parsed = JSON.parse(raw);
584
+ } catch (e) {
585
+ status.innerText = 'Invalid JSON syntax: ' + e.message;
586
+ return;
587
+ }
588
+ if (!parsed.mcpServers || typeof parsed.mcpServers !== 'object') {
589
+ status.innerText = 'JSON must contain top-level "mcpServers" object.';
590
+ return;
591
+ }
592
+
593
+ btn.disabled = true;
594
+ status.innerText = 'Connecting servers...';
595
+ try {
596
+ const res = await fetch('/api/upstream/import', {
597
+ method: 'POST',
598
+ headers: { 'Content-Type': 'application/json' },
599
+ body: JSON.stringify(parsed)
600
+ });
601
+ const json = await res.json();
602
+ if (json.success) {
603
+ const results = json.data.results || [];
604
+ status.innerText = 'Queued ' + results.length + ' server(s) for parallel connection...';
605
+ await loadStats();
606
+ } else {
607
+ status.innerText = json.error || 'Import failed.';
608
+ }
609
+ } catch (e) {
610
+ status.innerText = 'Import request failed.';
611
+ } finally {
612
+ btn.disabled = false;
613
+ }
614
+ }
615
+
616
+ async function loadStats() {
617
+ try {
618
+ const res = await fetch('/api/dashboard/stats');
619
+ const json = await res.json();
620
+ if (json.success) {
621
+ document.getElementById('stat-servers').innerText = json.data.totalServers;
622
+ document.getElementById('stat-connected').innerText = json.data.connectedServers + ' connected';
623
+ document.getElementById('stat-tools').innerText = json.data.totalTools;
624
+ document.getElementById('stat-execs').innerText = json.data.totalExecutions;
625
+ document.getElementById('stat-tokens').innerText = json.data.tokensSaved.toLocaleString();
626
+ }
627
+ await loadServers();
628
+ } catch (e) {
629
+ console.error(e);
630
+ }
631
+ }
632
+
633
+ async function loadServers() {
634
+ try {
635
+ const res = await fetch('/api/upstream/servers');
636
+ const json = await res.json();
637
+ cachedServers = json.data || [];
638
+ const tbody = document.getElementById('servers-table');
639
+ if (cachedServers.length === 0) {
640
+ tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--subtle); padding: 24px;">No upstream servers registered yet. Search above or paste mcp.json.</td></tr>';
641
+ return;
642
+ }
643
+ tbody.innerHTML = cachedServers.map(s => {
644
+ let envKeys = [];
645
+ let args = [];
646
+ try { envKeys = Object.keys(JSON.parse(s.env || '{}')); } catch {}
647
+ try { args = JSON.parse(s.args || '[]'); } catch {}
648
+ const fullCmd = [s.command || s.url || '', ...args].filter(Boolean).join(' ');
649
+ const dotClass = s.status === 'connected' ? 'dot-green' : (s.status === 'error' ? 'dot-red' : (s.status === 'connecting' ? 'dot-amber' : 'dot-muted'));
650
+ const statusIcon = s.status === 'connecting' ? '<span class="spinner"></span>' : '<span class="dot ' + dotClass + '"></span>';
651
+ const chips = envKeys.map(k => '<span class="env-chip">' + esc(k) + '</span>').join('');
652
+ const errHtml = s.error_message ? '<div class="err-inline">' + esc(s.error_message) + '</div>' : '';
653
+
654
+ return \`
655
+ <tr>
656
+ <td><strong>\${esc(s.name)}</strong><div style="font-size: 11px; color: var(--subtle); font-family: var(--mono);">\${esc(s.transport)}</div></td>
657
+ <td>
658
+ <div class="status-tag">\${statusIcon} \${esc(s.status)}</div>
659
+ \${errHtml}
660
+ </td>
661
+ <td>
662
+ <code class="mono" style="font-size: 12px;">\${esc(fullCmd)}</code>
663
+ <div>\${chips}</div>
664
+ </td>
665
+ <td style="text-align: right; white-space: nowrap;">
666
+ <button type="button" class="btn btn-ghost btn-sm" onclick="viewLogs('\${esc(s.id)}')">Logs</button>
667
+ <button type="button" class="btn btn-ghost btn-sm" onclick="editServer('\${esc(s.id)}')">Edit</button>
668
+ <button type="button" class="btn btn-ghost btn-sm" onclick="reconnectServer('\${esc(s.id)}', this)">Reconnect</button>
669
+ <button type="button" class="btn btn-danger btn-sm" onclick="deleteServer('\${esc(s.id)}')">Remove</button>
670
+ </td>
671
+ </tr>\`;
672
+ }).join('');
673
+ updateProgressBanner(cachedServers);
674
+ } catch (e) {
675
+ console.error(e);
676
+ }
677
+ }
678
+
679
+ let pollTimer = null;
680
+
681
+ function updateProgressBanner(servers) {
682
+ const total = servers.length;
683
+ const connecting = servers.filter(s => s.status === 'connecting').length;
684
+ const connected = servers.filter(s => s.status === 'connected').length;
685
+ const errored = servers.filter(s => s.status === 'error').length;
686
+ const banner = document.getElementById('progress-banner');
687
+
688
+ if (connecting > 0) {
689
+ const settled = total - connecting;
690
+ const pct = total > 0 ? Math.round((settled / total) * 100) : 0;
691
+ banner.style.display = 'block';
692
+ document.getElementById('progress-text').innerText = 'Connecting servers in parallel (' + connecting + ' active)...';
693
+ document.getElementById('progress-counts').innerText = settled + '/' + total + ' finished • ' + connected + ' connected • ' + errored + ' failed';
694
+ document.getElementById('progress-fill').style.width = pct + '%';
695
+ scheduleNextPoll(1500);
696
+ } else {
697
+ banner.style.display = 'none';
698
+ scheduleNextPoll(10000);
699
+ }
700
+ }
701
+
702
+ function scheduleNextPoll(ms) {
703
+ if (pollTimer) clearTimeout(pollTimer);
704
+ pollTimer = setTimeout(loadStats, ms);
705
+ }
706
+
707
+ function buildDiagnosticHint(errorMsg, logsText) {
708
+ const combined = ((errorMsg || '') + ' ' + logsText).toLowerCase();
709
+ if (!combined.trim()) return '';
710
+ if (combined.includes('not found') || combined.includes('enoent') || combined.includes('is not recognized')) {
711
+ return 'Diagnostic Hint: The command or executable was not found in PATH. Check "command" (e.g., use "npx" with args ["-y", "<package>"]).';
712
+ }
713
+ if (combined.includes('timed out')) {
714
+ return 'Diagnostic Hint: Handshake timed out. This usually happens if the MCP server is waiting for interactive browser OAuth, waiting for stdin input, or taking >60s on first-time download.';
715
+ }
716
+ if (combined.includes('401') || combined.includes('403') || combined.includes('unauthorized') || combined.includes('token') || combined.includes('auth')) {
717
+ return 'Diagnostic Hint: Authentication failed. Click "Edit" on this server and verify the required token/credentials in mcp.json.';
718
+ }
719
+ if (combined.includes('exited with code')) {
720
+ return 'Diagnostic Hint: The process exited before completing the MCP initialize handshake. Review the [STDERR] lines above for missing dependencies or invalid arguments.';
721
+ }
722
+ return '';
723
+ }
724
+
725
+ async function viewLogs(id) {
726
+ openLogServerId = id;
727
+ document.getElementById('logs-panel').classList.add('open');
728
+ await refreshOpenLogs();
729
+ }
730
+
731
+ async function refreshOpenLogs() {
732
+ if (!openLogServerId) return;
733
+ const res = await fetch('/api/upstream/servers/' + openLogServerId + '/logs');
734
+ const json = await res.json();
735
+ if (!json.success) return;
736
+ const data = json.data;
737
+ document.getElementById('logs-title').innerText = 'Diagnostics: ' + data.name + ' (' + data.status + ')';
738
+ const stream = document.getElementById('log-stream');
739
+ const logs = data.logs || [];
740
+ if (logs.length === 0) {
741
+ stream.innerText = data.error_message ? '[ERROR] ' + data.error_message : 'No runtime logs captured in this session yet. Click Reconnect to capture live handshake output.';
742
+ } else {
743
+ stream.innerHTML = logs.map(line => {
744
+ const cls = line.includes('[ERROR]') ? 'log-err' : (line.includes('[STDERR]') ? 'log-warn' : '');
745
+ return '<div class="' + cls + '">' + esc(line) + '</div>';
746
+ }).join('');
747
+ stream.scrollTop = stream.scrollHeight;
748
+ }
749
+
750
+ const missingVars = data.detectedMissingEnvVars || [];
751
+ const qfBox = document.getElementById('quick-fix-box');
752
+ if (missingVars.length > 0 && data.status !== 'connected') {
753
+ qfBox.style.display = 'block';
754
+ qfBox.innerHTML = '<div style="font-size: 12px; font-weight: 600; margin-bottom: 8px; color: var(--text);">Quick Fix: Missing Environment Variable Detected</div>'
755
+ + missingVars.map(v => \`
756
+ <div style="display: flex; gap: 8px; align-items: center; margin-bottom: 6px;">
757
+ <code class="mono" style="font-size: 12px; min-width: 220px;">\${esc(v)}</code>
758
+ <input type="password" class="input mono qf-input" data-key="\${esc(v)}" placeholder="Paste value for \${esc(v)}" />
759
+ </div>
760
+ \`).join('')
761
+ + '<button type="button" class="btn btn-sm" style="margin-top: 4px;" onclick="applyQuickFix()">Save Variable &amp; Reconnect</button>';
762
+ } else {
763
+ qfBox.style.display = 'none';
764
+ qfBox.innerHTML = '';
765
+ }
766
+
767
+ const hint = buildDiagnosticHint(data.error_message, logs.join(' '));
768
+ const hintEl = document.getElementById('log-hint');
769
+ if (hint) {
770
+ hintEl.innerText = hint;
771
+ hintEl.style.display = 'block';
772
+ } else {
773
+ hintEl.style.display = 'none';
774
+ }
775
+ }
776
+
777
+ async function applyQuickFix() {
778
+ if (!openLogServerId) return;
779
+ const srv = cachedServers.find(s => s.id === openLogServerId);
780
+ if (!srv) return;
781
+ let env = {};
782
+ try { env = JSON.parse(srv.env || '{}'); } catch {}
783
+ document.querySelectorAll('#quick-fix-box .qf-input').forEach(inp => {
784
+ const k = inp.getAttribute('data-key');
785
+ const v = inp.value.trim();
786
+ if (k && v) env[k] = v;
787
+ });
788
+ let args = [];
789
+ try { args = JSON.parse(srv.args || '[]'); } catch {}
790
+ await fetch('/api/upstream/servers', {
791
+ method: 'POST',
792
+ headers: { 'Content-Type': 'application/json' },
793
+ body: JSON.stringify({ id: srv.id, name: srv.name, command: srv.command, args, transport: 'stdio', env })
794
+ });
795
+ await loadStats();
796
+ await refreshOpenLogs();
797
+ }
798
+
799
+ function closeLogs() {
800
+ openLogServerId = null;
801
+ document.getElementById('logs-panel').classList.remove('open');
802
+ }
803
+
804
+ async function reconnectServer(id, btn) {
805
+ if (btn) {
806
+ btn.disabled = true;
807
+ btn.innerText = 'Connecting...';
808
+ }
809
+ try {
810
+ await fetch('/api/upstream/servers/' + id + '/reconnect', { method: 'POST' });
811
+ await loadStats();
812
+ if (openLogServerId === id) await refreshOpenLogs();
813
+ } finally {
814
+ if (btn) {
815
+ btn.disabled = false;
816
+ btn.innerText = 'Reconnect';
817
+ }
818
+ }
819
+ }
820
+
821
+ async function deleteServer(id) {
822
+ if (!confirm('Remove this server?')) return;
823
+ if (openLogServerId === id) closeLogs();
824
+ await fetch('/api/upstream/servers/' + id, { method: 'DELETE' });
825
+ await loadStats();
826
+ }
827
+
828
+ async function disconnectAllServers() {
829
+ await fetch('/api/upstream/disconnect-all', { method: 'POST' });
830
+ document.getElementById('import-status').innerText = 'Disconnected all servers.';
831
+ await loadStats();
832
+ }
833
+
834
+ async function removeAllServers() {
835
+ if (!confirm('Remove ALL upstream servers and their stored secrets?')) return;
836
+ closeLogs();
837
+ await fetch('/api/upstream/servers', { method: 'DELETE' });
838
+ document.getElementById('import-status').innerText = 'Removed all servers.';
839
+ await loadStats();
840
+ }
841
+
842
+ async function wrapIde() {
843
+ const res = await fetch('/api/dashboard/wrap', { method: 'POST' });
844
+ const json = await res.json();
845
+ const el = document.getElementById('wrap-msg');
846
+ el.style.display = 'block';
847
+ el.innerText = json.success ? 'Wrapped successfully. Imported ' + json.data.serversImported + ' servers.' : json.error;
848
+ await loadStats();
849
+ }
850
+
851
+ async function unwrapIde() {
852
+ const res = await fetch('/api/dashboard/unwrap', { method: 'POST' });
853
+ const json = await res.json();
854
+ const el = document.getElementById('wrap-msg');
855
+ el.style.display = 'block';
856
+ el.innerText = json.success ? 'Restored original Cursor configuration.' : json.error;
857
+ }
858
+
859
+ const sseUrl = window.location.origin + '/mcp/sse';
860
+ document.getElementById('sse-url-text').innerText = sseUrl;
861
+
862
+ function copySseUrl() {
863
+ navigator.clipboard.writeText(sseUrl);
864
+ const el = document.getElementById('sse-url-text');
865
+ el.innerText = 'Copied ' + sseUrl;
866
+ setTimeout(() => { el.innerText = sseUrl; }, 1500);
867
+ }
868
+
869
+ loadStats();
870
+ </script>
871
+ </body>
872
+ </html>`;
873
+ }
874
+ }