@vibescope/mcp-server 0.2.4 → 0.2.6

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/src/setup.ts ADDED
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Vibescope Setup Wizard
3
+ * Guides users through setting up Vibescope MCP integration
4
+ *
5
+ * Usage: vibescope-cli setup
6
+ */
7
+
8
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
9
+ import { createInterface } from 'node:readline';
10
+ import { homedir, platform } from 'node:os';
11
+ import { join, dirname } from 'node:path';
12
+ import { exec } from 'node:child_process';
13
+
14
+ const VIBESCOPE_SETTINGS_URL = 'https://vibescope.dev/dashboard/settings';
15
+ const DEFAULT_SUPABASE_URL = 'https://uuneucmuubpgswvfijwd.supabase.co';
16
+
17
+ // ============================================================================
18
+ // Types
19
+ // ============================================================================
20
+
21
+ export interface IdeConfig {
22
+ name: string;
23
+ displayName: string;
24
+ configPath: string;
25
+ detected: boolean;
26
+ configFormat: 'mcp-json' | 'settings-json';
27
+ }
28
+
29
+ // ============================================================================
30
+ // Config Path Helpers
31
+ // ============================================================================
32
+
33
+ function getClaudeDesktopConfigPath(): string {
34
+ const plat = platform();
35
+ const home = homedir();
36
+
37
+ if (plat === 'darwin') {
38
+ return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
39
+ } else if (plat === 'win32') {
40
+ return join(home, 'AppData', 'Roaming', 'Claude', 'claude_desktop_config.json');
41
+ } else {
42
+ return join(home, '.config', 'Claude', 'claude_desktop_config.json');
43
+ }
44
+ }
45
+
46
+ function getCursorConfigPath(): string {
47
+ const plat = platform();
48
+ const home = homedir();
49
+
50
+ if (plat === 'darwin') {
51
+ return join(home, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json');
52
+ } else if (plat === 'win32') {
53
+ return join(home, 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json');
54
+ } else {
55
+ return join(home, '.config', 'Cursor', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json');
56
+ }
57
+ }
58
+
59
+ function getGeminiConfigPath(): string {
60
+ return join(homedir(), '.gemini', 'settings.json');
61
+ }
62
+
63
+ // ============================================================================
64
+ // IDE Detection
65
+ // ============================================================================
66
+
67
+ export function detectIdes(): IdeConfig[] {
68
+ const ides: IdeConfig[] = [
69
+ {
70
+ name: 'claude-code',
71
+ displayName: 'Claude Code (CLI)',
72
+ configPath: '.mcp.json',
73
+ detected: true,
74
+ configFormat: 'mcp-json',
75
+ },
76
+ {
77
+ name: 'claude-desktop',
78
+ displayName: 'Claude Desktop',
79
+ configPath: getClaudeDesktopConfigPath(),
80
+ detected: existsSync(dirname(getClaudeDesktopConfigPath())),
81
+ configFormat: 'mcp-json',
82
+ },
83
+ {
84
+ name: 'cursor',
85
+ displayName: 'Cursor',
86
+ configPath: getCursorConfigPath(),
87
+ detected: existsSync(dirname(getCursorConfigPath())),
88
+ configFormat: 'mcp-json',
89
+ },
90
+ {
91
+ name: 'gemini',
92
+ displayName: 'Gemini CLI',
93
+ configPath: getGeminiConfigPath(),
94
+ detected: true,
95
+ configFormat: 'settings-json',
96
+ },
97
+ ];
98
+
99
+ return ides;
100
+ }
101
+
102
+ // ============================================================================
103
+ // User Prompts
104
+ // ============================================================================
105
+
106
+ async function prompt(question: string): Promise<string> {
107
+ const rl = createInterface({
108
+ input: process.stdin,
109
+ output: process.stdout,
110
+ });
111
+
112
+ return new Promise((resolve) => {
113
+ rl.question(question, (answer) => {
114
+ rl.close();
115
+ resolve(answer.trim());
116
+ });
117
+ });
118
+ }
119
+
120
+ async function promptSelect(question: string, options: { label: string; value: string }[]): Promise<string> {
121
+ console.log('\n' + question + '\n');
122
+ options.forEach((opt, i) => {
123
+ console.log(' ' + (i + 1) + ') ' + opt.label);
124
+ });
125
+
126
+ const answer = await prompt('\nEnter number: ');
127
+ const index = parseInt(answer, 10) - 1;
128
+
129
+ if (index >= 0 && index < options.length) {
130
+ return options[index].value;
131
+ }
132
+
133
+ console.log('Invalid selection, using first option.');
134
+ return options[0].value;
135
+ }
136
+
137
+ // ============================================================================
138
+ // Browser & Validation
139
+ // ============================================================================
140
+
141
+ function openBrowser(url: string): Promise<void> {
142
+ return new Promise((resolve) => {
143
+ const plat = platform();
144
+ let cmd: string;
145
+
146
+ if (plat === 'darwin') {
147
+ cmd = 'open "' + url + '"';
148
+ } else if (plat === 'win32') {
149
+ cmd = 'start "" "' + url + '"';
150
+ } else {
151
+ cmd = 'xdg-open "' + url + '"';
152
+ }
153
+
154
+ exec(cmd, (error) => {
155
+ if (error) {
156
+ console.log('\nCould not open browser automatically.');
157
+ console.log('Please visit: ' + url + '\n');
158
+ }
159
+ resolve();
160
+ });
161
+ });
162
+ }
163
+
164
+ export async function validateApiKey(apiKey: string): Promise<{ valid: boolean; message: string }> {
165
+ try {
166
+ const response = await fetch(DEFAULT_SUPABASE_URL + '/rest/v1/api_keys?key=eq.' + apiKey + '&select=id', {
167
+ headers: {
168
+ 'apikey': apiKey,
169
+ 'Authorization': 'Bearer ' + apiKey,
170
+ },
171
+ });
172
+
173
+ if (response.ok) {
174
+ return { valid: true, message: 'API key validated successfully!' };
175
+ } else {
176
+ return { valid: false, message: 'API key appears to be invalid.' };
177
+ }
178
+ } catch {
179
+ return { valid: true, message: 'Could not validate API key (network issue), but proceeding.' };
180
+ }
181
+ }
182
+
183
+ // ============================================================================
184
+ // Config Management
185
+ // ============================================================================
186
+
187
+ export function readExistingConfig(configPath: string): Record<string, unknown> {
188
+ if (existsSync(configPath)) {
189
+ try {
190
+ return JSON.parse(readFileSync(configPath, 'utf-8'));
191
+ } catch {
192
+ return {};
193
+ }
194
+ }
195
+ return {};
196
+ }
197
+
198
+ export function writeConfig(configPath: string, config: Record<string, unknown>): void {
199
+ const dir = dirname(configPath);
200
+ if (!existsSync(dir)) {
201
+ mkdirSync(dir, { recursive: true });
202
+ }
203
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
204
+ }
205
+
206
+ export function generateMcpConfig(apiKey: string, ide: IdeConfig): Record<string, unknown> {
207
+ const vibescopeServer = {
208
+ command: 'npx',
209
+ args: ['-y', '-p', '@vibescope/mcp-server@latest', 'vibescope-mcp'],
210
+ env: {
211
+ VIBESCOPE_API_KEY: apiKey,
212
+ },
213
+ };
214
+
215
+ // Gemini CLI uses a different config format with additional options
216
+ if (ide.configFormat === 'settings-json') {
217
+ return {
218
+ mcpServers: {
219
+ vibescope: {
220
+ ...vibescopeServer,
221
+ timeout: 30000,
222
+ trust: true,
223
+ },
224
+ },
225
+ };
226
+ }
227
+
228
+ // Standard MCP config for Claude Code, Claude Desktop, Cursor
229
+ return {
230
+ mcpServers: {
231
+ vibescope: vibescopeServer,
232
+ },
233
+ };
234
+ }
235
+
236
+ // ============================================================================
237
+ // Main Setup Flow
238
+ // ============================================================================
239
+
240
+ export async function runSetup(): Promise<void> {
241
+ console.log('\n=================================');
242
+ console.log(' Vibescope Setup Wizard');
243
+ console.log('=================================\n');
244
+
245
+ // Step 1: Detect IDEs
246
+ const ides = detectIdes();
247
+ const detectedIdes = ides.filter(ide => ide.detected);
248
+
249
+ console.log('Available development environments:');
250
+ detectedIdes.forEach(ide => {
251
+ console.log(' - ' + ide.displayName);
252
+ });
253
+
254
+ // Step 2: Select IDE to configure
255
+ let selectedIde: IdeConfig;
256
+ if (detectedIdes.length === 1) {
257
+ selectedIde = detectedIdes[0];
258
+ console.log('\nConfiguring for ' + selectedIde.displayName + '...');
259
+ } else {
260
+ const ideChoice = await promptSelect(
261
+ 'Which environment do you want to configure?',
262
+ detectedIdes.map(ide => ({ label: ide.displayName, value: ide.name }))
263
+ );
264
+ selectedIde = ides.find(ide => ide.name === ideChoice) || detectedIdes[0];
265
+ }
266
+
267
+ // Step 3: Check if config already exists
268
+ if (existsSync(selectedIde.configPath)) {
269
+ const existingConfig = readExistingConfig(selectedIde.configPath);
270
+ const hasMcpServers = 'mcpServers' in existingConfig;
271
+ const hasVibescope = hasMcpServers &&
272
+ typeof existingConfig.mcpServers === 'object' &&
273
+ existingConfig.mcpServers !== null &&
274
+ 'vibescope' in (existingConfig.mcpServers as Record<string, unknown>);
275
+
276
+ if (hasVibescope) {
277
+ const overwrite = await prompt('\nVibescope is already configured. Reconfigure? (y/N): ');
278
+ if (overwrite.toLowerCase() !== 'y') {
279
+ console.log('\nSetup cancelled. Your existing configuration is preserved.');
280
+ return;
281
+ }
282
+ }
283
+ }
284
+
285
+ // Step 4: Get API key
286
+ console.log('\n--- Step 1: Get your API key ---\n');
287
+ console.log('Opening Vibescope settings page in your browser...');
288
+ console.log("Create an API key if you don't have one, then copy it.\n");
289
+
290
+ await openBrowser(VIBESCOPE_SETTINGS_URL);
291
+
292
+ const apiKey = await prompt('Paste your Vibescope API key: ');
293
+
294
+ if (!apiKey) {
295
+ console.error('\nError: API key is required.');
296
+ process.exit(1);
297
+ }
298
+
299
+ // Validate API key
300
+ console.log('\nValidating API key...');
301
+ const validation = await validateApiKey(apiKey);
302
+ console.log(validation.message);
303
+
304
+ if (!validation.valid) {
305
+ const proceed = await prompt('Proceed anyway? (y/N): ');
306
+ if (proceed.toLowerCase() !== 'y') {
307
+ process.exit(1);
308
+ }
309
+ }
310
+
311
+ // Step 5: Write configuration
312
+ console.log('\n--- Step 2: Writing Configuration ---\n');
313
+
314
+ const mcpConfig = generateMcpConfig(apiKey, selectedIde);
315
+
316
+ // Merge with existing config if present
317
+ const existingConfig = readExistingConfig(selectedIde.configPath);
318
+ const existingMcpServers = typeof existingConfig.mcpServers === 'object' && existingConfig.mcpServers !== null
319
+ ? existingConfig.mcpServers as Record<string, unknown>
320
+ : {};
321
+ const newMcpServers = mcpConfig.mcpServers as Record<string, unknown>;
322
+
323
+ const mergedConfig = {
324
+ ...existingConfig,
325
+ mcpServers: {
326
+ ...existingMcpServers,
327
+ ...newMcpServers,
328
+ },
329
+ };
330
+
331
+ writeConfig(selectedIde.configPath, mergedConfig);
332
+
333
+ console.log('Configuration written to: ' + selectedIde.configPath);
334
+
335
+ // Step 6: IDE-specific next steps
336
+ console.log('\n=================================');
337
+ console.log(' Setup Complete!');
338
+ console.log('=================================\n');
339
+
340
+ switch (selectedIde.name) {
341
+ case 'claude-code':
342
+ console.log('Next steps:');
343
+ console.log(' 1. Restart Claude Code (or run: claude mcp reload)');
344
+ console.log(' 2. Verify connection: claude mcp list');
345
+ console.log(' 3. Start using Vibescope in your conversation');
346
+ break;
347
+ case 'claude-desktop':
348
+ console.log('Next steps:');
349
+ console.log(' 1. Restart Claude Desktop');
350
+ console.log(' 2. Vibescope tools will be available in your conversations');
351
+ break;
352
+ case 'cursor':
353
+ console.log('Next steps:');
354
+ console.log(' 1. Restart Cursor');
355
+ console.log(' 2. Open the MCP settings to verify Vibescope is connected');
356
+ break;
357
+ case 'gemini':
358
+ console.log('Next steps:');
359
+ console.log(' 1. Restart Gemini CLI');
360
+ console.log(' 2. Verify connection: gemini mcp list');
361
+ console.log(' 3. Start using Vibescope in your conversation');
362
+ break;
363
+ default:
364
+ console.log('Next steps:');
365
+ console.log(' 1. Restart your IDE/CLI');
366
+ console.log(' 2. Verify Vibescope is connected');
367
+ }
368
+
369
+ console.log('\nHappy building!\n');
370
+ }
@@ -1,4 +1,4 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
2
2
  import {
3
3
  estimateTokens,
4
4
  createTokenUsage,
@@ -96,13 +96,23 @@ describe('estimateTokens', () => {
96
96
  expect(tokens).toBeGreaterThanOrEqual(1);
97
97
  });
98
98
 
99
- it('should handle circular reference gracefully', () => {
99
+ it('should handle circular reference gracefully and log warning', () => {
100
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
101
+
100
102
  const obj: Record<string, unknown> = { name: 'test' };
101
103
  obj.self = obj; // Create circular reference
102
104
 
103
105
  // Should not throw, should return minimal estimate
104
106
  const tokens = estimateTokens(obj);
105
107
  expect(tokens).toBe(1);
108
+
109
+ // Should log a warning about the serialization failure
110
+ expect(warnSpy).toHaveBeenCalledTimes(1);
111
+ expect(warnSpy).toHaveBeenCalledWith(
112
+ expect.stringContaining('[Vibescope] Token estimation failed:')
113
+ );
114
+
115
+ warnSpy.mockRestore();
106
116
  });
107
117
 
108
118
  it('should handle objects with toJSON method', () => {
@@ -37,8 +37,10 @@ export function estimateTokens(obj: unknown): number {
37
37
  try {
38
38
  const json = JSON.stringify(obj);
39
39
  return Math.max(1, Math.ceil(json.length / 4));
40
- } catch {
41
- // If JSON serialization fails, return a minimal estimate
40
+ } catch (error) {
41
+ // Log warning when serialization fails (e.g., circular references, BigInt)
42
+ const errorMessage = error instanceof Error ? error.message : String(error);
43
+ console.warn(`[Vibescope] Token estimation failed: ${errorMessage}. Returning minimal estimate of 1 token.`);
42
44
  return 1;
43
45
  }
44
46
  }