-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathmcp-config.ts
More file actions
637 lines (579 loc) · 18 KB
/
mcp-config.ts
File metadata and controls
637 lines (579 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import * as fs from 'fs';
import * as path from 'path';
import * as childProcess from 'child_process';
import * as Sentry from '@sentry/node';
import chalk from 'chalk';
// @ts-expect-error - clack is ESM and TS complains about that. It works though
import * as clack from '@clack/prompts';
import { abortIfCancelled, showCopyPasteInstructions } from './index';
const SENTRY_MCP_BASE_URL = 'https://mcp.sentry.dev/mcp';
// Type definitions for MCP configurations
interface CursorMcpConfig {
mcpServers?: Record<string, { url: string }>;
}
interface VsCodeMcpConfig {
servers?: Record<string, { url: string; type: string }>;
}
interface ClaudeCodeMcpConfig {
mcpServers?: Record<string, { url: string }>;
}
interface OpenCodeMcpConfig {
$schema?: string;
mcp?: Record<string, { type: string; url: string; oauth?: object }>;
}
/**
* Constructs the MCP URL with optional org and project slugs
*/
function getMcpUrl(orgSlug?: string, projectSlug?: string): string {
if (orgSlug && projectSlug) {
return `${SENTRY_MCP_BASE_URL}/${orgSlug}/${projectSlug}`;
}
return SENTRY_MCP_BASE_URL;
}
function ensureDir(dirpath: string): void {
fs.mkdirSync(dirpath, { recursive: true });
}
async function readJsonIfExists(filepath: string): Promise<unknown | null> {
try {
const txt = await fs.promises.readFile(filepath, 'utf8');
return JSON.parse(txt) as unknown;
} catch {
return null;
}
}
async function writeJson(filepath: string, obj: unknown): Promise<void> {
ensureDir(path.dirname(filepath));
await fs.promises.writeFile(filepath, JSON.stringify(obj, null, 2), 'utf8');
}
function getCursorMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
mcpServers: {
Sentry: {
url: getMcpUrl(orgSlug, projectSlug),
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
function getVsCodeMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
servers: {
Sentry: {
url: getMcpUrl(orgSlug, projectSlug),
type: 'http',
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
function getClaudeCodeMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
mcpServers: {
Sentry: {
url: getMcpUrl(orgSlug, projectSlug),
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
function getJetBrainsMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
mcpServers: {
Sentry: {
url: getMcpUrl(orgSlug, projectSlug),
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
function getOpenCodeMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
$schema: 'https://opencode.ai/config.json',
mcp: {
Sentry: {
type: 'remote',
url: getMcpUrl(orgSlug, projectSlug),
oauth: {},
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
function getGenericMcpJsonSnippet(
orgSlug?: string,
projectSlug?: string,
): string {
const obj = {
mcpServers: {
Sentry: {
url: getMcpUrl(orgSlug, projectSlug),
},
},
} as const;
return JSON.stringify(obj, null, 2);
}
type McpConfigResult = {
filename: string;
action: 'created' | 'updated';
};
async function addCursorMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<McpConfigResult> {
const filename = path.join('.cursor', 'mcp.json');
const file = path.join(process.cwd(), filename);
const existing = await readJsonIfExists(file);
if (!existing) {
await writeJson(
file,
JSON.parse(getCursorMcpJsonSnippet(orgSlug, projectSlug)),
);
return { filename, action: 'created' };
}
try {
const updated = { ...existing } as CursorMcpConfig;
updated.mcpServers = updated.mcpServers || {};
updated.mcpServers['Sentry'] = {
url: getMcpUrl(orgSlug, projectSlug),
};
await writeJson(file, updated);
return { filename, action: 'updated' };
} catch {
throw new Error('Failed to update .cursor/mcp.json');
}
}
async function addVsCodeMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<McpConfigResult> {
const filename = path.join('.vscode', 'mcp.json');
const file = path.join(process.cwd(), filename);
const existing = await readJsonIfExists(file);
if (!existing) {
await writeJson(
file,
JSON.parse(getVsCodeMcpJsonSnippet(orgSlug, projectSlug)),
);
return { filename, action: 'created' };
}
try {
const updated = { ...existing } as VsCodeMcpConfig;
updated.servers = updated.servers || {};
updated.servers['Sentry'] = {
url: getMcpUrl(orgSlug, projectSlug),
type: 'http',
};
await writeJson(file, updated);
return { filename, action: 'updated' };
} catch {
throw new Error('Failed to update .vscode/mcp.json');
}
}
async function addClaudeCodeMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<McpConfigResult> {
const filename = '.mcp.json';
const file = path.join(process.cwd(), filename);
const existing = await readJsonIfExists(file);
if (!existing) {
await writeJson(
file,
JSON.parse(getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug)),
);
return { filename, action: 'created' };
}
try {
const updated = { ...existing } as ClaudeCodeMcpConfig;
updated.mcpServers = updated.mcpServers || {};
updated.mcpServers['Sentry'] = {
url: getMcpUrl(orgSlug, projectSlug),
};
await writeJson(file, updated);
return { filename, action: 'updated' };
} catch {
throw new Error('Failed to update .mcp.json');
}
}
async function addOpenCodeMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<McpConfigResult> {
const filename = 'opencode.json';
const file = path.join(process.cwd(), filename);
const existing = await readJsonIfExists(file);
if (!existing) {
await writeJson(
file,
JSON.parse(getOpenCodeMcpJsonSnippet(orgSlug, projectSlug)),
);
return { filename, action: 'created' };
}
try {
const updated = { ...existing } as OpenCodeMcpConfig;
updated.$schema ||= 'https://opencode.ai/config.json';
updated.mcp = updated.mcp || {};
updated.mcp['Sentry'] = {
type: 'remote',
url: getMcpUrl(orgSlug, projectSlug),
oauth: {},
};
await writeJson(file, updated);
return { filename, action: 'updated' };
} catch {
throw new Error('Failed to update opencode.json');
}
}
/**
* Copies text to clipboard across different platforms
*/
async function copyToClipboard(text: string): Promise<boolean> {
try {
const platform = process.platform;
let command: string;
if (platform === 'darwin') {
command = 'pbcopy';
} else if (platform === 'win32') {
command = 'clip';
} else {
// Linux
command = 'xclip -selection clipboard';
}
const proc = childProcess.spawn(command, [], { shell: true });
proc.stdin.write(text);
proc.stdin.end();
return new Promise((resolve) => {
proc.on('close', (code) => {
resolve(code === 0);
});
proc.on('error', () => {
resolve(false);
});
});
} catch {
return false;
}
}
/**
* Shows MCP configuration for JetBrains IDEs with copy-to-clipboard option
*/
async function showJetBrainsMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<void> {
const configSnippet = getJetBrainsMcpJsonSnippet(orgSlug, projectSlug);
clack.log.info(
chalk.cyan('For JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.):'),
);
clack.log.info(
chalk.dim(
"Add the following configuration to your IDE's MCP settings.\n" +
'See: https://www.jetbrains.com/help/webstorm/mcp-server.html',
),
);
// Display the configuration
// eslint-disable-next-line no-console
console.log('\n' + chalk.green(configSnippet) + '\n');
// Ask if user wants to copy to clipboard
const shouldCopy: boolean = await abortIfCancelled(
clack.select({
message: 'Copy configuration to clipboard?',
options: [
{ label: 'Yes', value: true },
{ label: 'No', value: false },
],
initialValue: true,
}),
);
if (shouldCopy) {
const copied = await copyToClipboard(configSnippet);
if (copied) {
clack.log.success('Configuration copied to clipboard!');
Sentry.setTag('mcp-clipboard-copy', 'success');
} else {
clack.log.warn(
'Failed to copy to clipboard. Please copy the configuration above manually.',
);
Sentry.setTag('mcp-clipboard-copy', 'failed');
}
} else {
Sentry.setTag('mcp-clipboard-copy', 'declined');
}
clack.log.info(
chalk.dim(
'Note: You may need to restart your IDE for MCP changes to take effect.',
),
);
}
/**
* Shows generic MCP configuration for unsupported IDEs with copy-to-clipboard option
*/
async function showGenericMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<void> {
const configSnippet = getGenericMcpJsonSnippet(orgSlug, projectSlug);
clack.log.info(chalk.cyan('Generic MCP configuration for your IDE:'));
clack.log.info(
chalk.dim(
'If your IDE supports MCP servers, you can use the following configuration.\n' +
"Please consult your IDE's documentation for how to add MCP server configurations.",
),
);
// Display the configuration
// eslint-disable-next-line no-console
console.log('\n' + chalk.green(configSnippet) + '\n');
// Ask if user wants to copy to clipboard
const shouldCopy: boolean = await abortIfCancelled(
clack.select({
message: 'Copy configuration to clipboard?',
options: [
{ label: 'Yes', value: true },
{ label: 'No', value: false },
],
initialValue: true,
}),
);
if (shouldCopy) {
const copied = await copyToClipboard(configSnippet);
if (copied) {
clack.log.success('Configuration copied to clipboard!');
Sentry.setTag('mcp-clipboard-copy', 'success');
} else {
clack.log.warn(
'Failed to copy to clipboard. Please copy the configuration above manually.',
);
Sentry.setTag('mcp-clipboard-copy', 'failed');
}
} else {
Sentry.setTag('mcp-clipboard-copy', 'declined');
}
clack.log.info(
chalk.dim(
'Note: The exact configuration format may vary depending on your IDE.\n' +
"If your IDE doesn't support MCP yet, please check back later or open an issue at:\n" +
'https://github.com/getsentry/sentry-wizard/issues',
),
);
}
/**
* Explains what MCP is and its benefits for Sentry users
*/
async function explainMCP(): Promise<boolean> {
clack.log.info(chalk.cyan('What is MCP (Model Context Protocol)?'));
clack.log.info(
chalk.dim(
'MCP is a protocol that allows AI assistants in your IDE to interact with external tools and services.\n\n' +
'The Sentry MCP server enables AI assistants to:\n' +
' • Query and analyze your Sentry issues directly from your IDE\n' +
' • Get context about errors and performance problems\n' +
' • Help debug issues with production data insights\n' +
' • Suggest fixes based on real error patterns\n\n' +
"This makes it easier to fix bugs by bringing Sentry's insights directly into your development workflow.\n\n" +
'Learn more: ' +
chalk.cyan('https://docs.sentry.io/product/sentry-mcp/'),
),
);
// Ask again after explanation
const shouldAddAfterExplanation: boolean = await abortIfCancelled(
clack.select({
message: 'Would you like to configure MCP for your IDE now?',
options: [
{ label: 'Yes', value: true },
{ label: 'No', value: false, hint: 'You can add it later anytime' },
],
initialValue: true,
}),
);
return shouldAddAfterExplanation;
}
/**
* Offers to add a project-scoped MCP server configuration for the Sentry MCP.
* Supports Cursor, VS Code, and Claude Code.
* @param orgSlug - Optional organization slug to include in the MCP URL
* @param projectSlug - Optional project slug to include in the MCP URL
*/
export async function offerProjectScopedMcpConfig(
orgSlug?: string,
projectSlug?: string,
): Promise<void> {
type InitialChoice = 'yes' | 'no' | 'explain';
const initialChoice: InitialChoice = await abortIfCancelled(
clack.select<
{ value: InitialChoice; label: string; hint?: string }[],
InitialChoice
>({
message:
'Optionally add a project-scoped MCP server configuration for the Sentry MCP?',
options: [
{ label: 'Yes', value: 'yes' },
{ label: 'No', value: 'no', hint: 'You can add it later anytime' },
{
label: 'What is MCP?',
value: 'explain',
hint: 'Learn about MCP benefits',
},
],
initialValue: 'yes',
}),
);
let shouldAdd: boolean;
if (initialChoice === 'explain') {
Sentry.setTag('mcp-choice', 'explain');
shouldAdd = await explainMCP();
Sentry.setTag('mcp-configured-after-explain', shouldAdd);
} else {
shouldAdd = initialChoice === 'yes';
Sentry.setTag('mcp-choice', initialChoice);
}
if (!shouldAdd) {
Sentry.setTag('mcp-configured', false);
return;
}
Sentry.setTag('mcp-configured', true);
type EditorChoice =
| 'cursor'
| 'vscode'
| 'claudeCode'
| 'openCode'
| 'jetbrains'
| 'other';
const editors: EditorChoice[] = await abortIfCancelled(
clack.multiselect({
message: 'Which editor(s) do you want to configure?',
options: [
{ value: 'cursor', label: 'Cursor (project .cursor/mcp.json)' },
{ value: 'vscode', label: 'VS Code (project .vscode/mcp.json)' },
{ value: 'claudeCode', label: 'Claude Code (project .mcp.json)' },
{ value: 'openCode', label: 'OpenCode (project opencode.json)' },
{
value: 'jetbrains',
label: 'JetBrains IDE (WebStorm, IntelliJ IDEA, PyCharm, etc.)',
hint: 'Manual configuration required',
},
{
value: 'other',
label: 'I use a different IDE',
hint: "We'll show you the configuration to copy",
},
],
required: false,
}),
);
// If no editors were selected, return early
if (!editors || editors.length === 0) {
clack.log.info('No editors selected. You can add MCP configuration later.');
Sentry.setTag('mcp-configured', false);
return;
}
// Track number of editors selected
Sentry.setTag('mcp-editors-count', editors.length);
// Collect results for auto-configured editors to show consolidated output
const configResults: McpConfigResult[] = [];
let hasOpenCode = false;
// Configure each selected editor
for (const editor of editors) {
// Track which editor is being configured
Sentry.setTag('mcp-editor', editor);
try {
switch (editor) {
case 'cursor':
configResults.push(await addCursorMcpConfig(orgSlug, projectSlug));
break;
case 'vscode':
configResults.push(await addVsCodeMcpConfig(orgSlug, projectSlug));
break;
case 'claudeCode':
configResults.push(
await addClaudeCodeMcpConfig(orgSlug, projectSlug),
);
break;
case 'openCode':
configResults.push(await addOpenCodeMcpConfig(orgSlug, projectSlug));
hasOpenCode = true;
break;
case 'jetbrains':
await showJetBrainsMcpConfig(orgSlug, projectSlug);
Sentry.setTag('mcp-config-manual', true);
break;
case 'other':
await showGenericMcpConfig(orgSlug, projectSlug);
Sentry.setTag('mcp-config-manual', true);
break;
}
Sentry.setTag(`mcp-config-${editor}-success`, true);
} catch (e) {
Sentry.setTag(`mcp-config-${editor}-success`, false);
Sentry.setTag('mcp-config-fallback', true);
clack.log.warn(
chalk.yellow(
`Failed to write MCP config for ${editor} automatically. Please copy/paste the snippet below into your project config file.`,
),
);
// Fallback: show per-editor instructions
if (editor === 'cursor') {
await showCopyPasteInstructions({
filename: path.join('.cursor', 'mcp.json'),
codeSnippet: getCursorMcpJsonSnippet(orgSlug, projectSlug),
hint: 'create the file if it does not exist',
});
} else if (editor === 'vscode') {
await showCopyPasteInstructions({
filename: path.join('.vscode', 'mcp.json'),
codeSnippet: getVsCodeMcpJsonSnippet(orgSlug, projectSlug),
hint: 'create the file if it does not exist',
});
} else if (editor === 'claudeCode') {
await showCopyPasteInstructions({
filename: '.mcp.json',
codeSnippet: getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug),
hint: 'create the file if it does not exist',
});
} else if (editor === 'openCode') {
await showCopyPasteInstructions({
filename: 'opencode.json',
codeSnippet: getOpenCodeMcpJsonSnippet(orgSlug, projectSlug),
hint: 'create the file if it does not exist',
});
}
}
}
// Show consolidated output for auto-configured editors
if (configResults.length > 0) {
const created = configResults.filter((r) => r.action === 'created');
const updated = configResults.filter((r) => r.action === 'updated');
const parts: string[] = [];
if (created.length > 0) {
const files = created.map((r) => chalk.cyan(r.filename)).join(' and ');
parts.push(`${files} created`);
}
if (updated.length > 0) {
const files = updated.map((r) => chalk.cyan(r.filename)).join(' and ');
parts.push(`${files} updated`);
}
clack.log.success(parts.join(', ') + '.');
clack.log.success('Added project-scoped Sentry MCP configuration.');
clack.log.info(
chalk.dim(
hasOpenCode
? 'Note: You may need to reload your editor or restart OpenCode for MCP changes to take effect.'
: 'Note: You may need to reload your editor for MCP changes to take effect.',
),
);
}
}