@smartbear/mcp 0.3.0 → 0.5.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.
@@ -0,0 +1,687 @@
1
+ import NodeCache from "node-cache";
2
+ import { z } from "zod";
3
+ import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from "../common/info.js";
4
+ import { CurrentUserAPI, ErrorAPI, Configuration } from "./client/index.js";
5
+ import { ProjectAPI } from "./client/api/Project.js";
6
+ import { FilterObjectSchema, toQueryString } from "./client/api/filters.js";
7
+ const HUB_PREFIX = "00000";
8
+ const DEFAULT_DOMAIN = "bugsnag.com";
9
+ const HUB_DOMAIN = "bugsnag.smartbear.com";
10
+ const cacheKeys = {
11
+ ORG: "bugsnag_org",
12
+ PROJECTS: "bugsnag_projects",
13
+ CURRENT_PROJECT: "bugsnag_current_project",
14
+ CURRENT_PROJECT_EVENT_FILTERS: "bugsnag_current_project_event_filters",
15
+ };
16
+ // Exclude certain event fields from the project event filters to improve agent usage
17
+ const EXCLUDED_EVENT_FIELDS = new Set([
18
+ "search" // This is searches multiple fields and is more a convenience for humans, we're removing to avoid over-matching
19
+ ]);
20
+ const PERMITTED_UPDATE_OPERATIONS = [
21
+ "override_severity",
22
+ "open",
23
+ "fix",
24
+ "ignore",
25
+ "discard",
26
+ "undiscard"
27
+ ];
28
+ export class BugsnagClient {
29
+ currentUserApi;
30
+ errorsApi;
31
+ cache;
32
+ projectApi;
33
+ projectApiKey;
34
+ apiEndpoint;
35
+ appEndpoint;
36
+ name = "Bugsnag";
37
+ prefix = "bugsnag";
38
+ constructor(token, projectApiKey, endpoint) {
39
+ this.apiEndpoint = this.getEndpoint("api", projectApiKey, endpoint);
40
+ this.appEndpoint = this.getEndpoint("app", projectApiKey, endpoint);
41
+ const config = new Configuration({
42
+ authToken: token,
43
+ headers: {
44
+ "User-Agent": `${MCP_SERVER_NAME}/${MCP_SERVER_VERSION}`,
45
+ "Content-Type": "application/json",
46
+ "X-Bugsnag-API": "true",
47
+ "X-Version": "2",
48
+ },
49
+ basePath: this.apiEndpoint,
50
+ });
51
+ this.currentUserApi = new CurrentUserAPI(config);
52
+ this.errorsApi = new ErrorAPI(config);
53
+ this.cache = new NodeCache();
54
+ this.projectApi = new ProjectAPI(config);
55
+ this.projectApiKey = projectApiKey;
56
+ }
57
+ async initialize() {
58
+ // Trigger caching of org and projects
59
+ await this.getProjects();
60
+ await this.getCurrentProject();
61
+ }
62
+ getHost(apiKey, subdomain) {
63
+ if (apiKey && apiKey.startsWith(HUB_PREFIX)) {
64
+ return `https://${subdomain}.${HUB_DOMAIN}`;
65
+ }
66
+ else {
67
+ return `https://${subdomain}.${DEFAULT_DOMAIN}`;
68
+ }
69
+ }
70
+ // If the endpoint is not provided, it will use the default API endpoint based on the project API key.
71
+ // if the project api key is not provided, the endpoint will be the default API endpoint.
72
+ // if the endpoint is provided, it will be used as is for custom domains, or normalized for known domains.
73
+ getEndpoint(subdomain, apiKey, endpoint) {
74
+ let subDomainEndpoint;
75
+ if (!endpoint) {
76
+ if (apiKey && apiKey.startsWith(HUB_PREFIX)) {
77
+ subDomainEndpoint = `https://${subdomain}.${HUB_DOMAIN}`;
78
+ }
79
+ else {
80
+ subDomainEndpoint = `https://${subdomain}.${DEFAULT_DOMAIN}`;
81
+ }
82
+ }
83
+ else {
84
+ // check if the endpoint matches either the HUB_DOMAIN or DEFAULT_DOMAIN
85
+ const url = new URL(endpoint);
86
+ if (url.hostname.endsWith(HUB_DOMAIN) || url.hostname.endsWith(DEFAULT_DOMAIN)) {
87
+ // For known domains (Hub or Bugsnag), always use HTTPS and standard format
88
+ if (url.hostname.endsWith(HUB_DOMAIN)) {
89
+ subDomainEndpoint = `https://${subdomain}.${HUB_DOMAIN}`;
90
+ }
91
+ else {
92
+ subDomainEndpoint = `https://${subdomain}.${DEFAULT_DOMAIN}`;
93
+ }
94
+ }
95
+ else {
96
+ // For custom domains, use the endpoint exactly as provided
97
+ subDomainEndpoint = endpoint;
98
+ }
99
+ }
100
+ return subDomainEndpoint;
101
+ }
102
+ async getDashboardUrl(project) {
103
+ return `${this.appEndpoint}/${(await this.getOrganization()).slug}/${project.slug}`;
104
+ }
105
+ async getErrorUrl(project, errorId, queryString = '') {
106
+ const dashboardUrl = await this.getDashboardUrl(project);
107
+ return `${dashboardUrl}/errors/${errorId}${queryString}`;
108
+ }
109
+ async getOrganization() {
110
+ let org = this.cache.get(cacheKeys.ORG);
111
+ if (!org) {
112
+ const response = await this.currentUserApi.listUserOrganizations();
113
+ const orgs = response.body || [];
114
+ if (!orgs || orgs.length === 0) {
115
+ throw new Error("No organizations found for the current user.");
116
+ }
117
+ org = orgs[0];
118
+ this.cache.set(cacheKeys.ORG, org);
119
+ }
120
+ return org;
121
+ }
122
+ // This method retrieves all projects for the organization stored in the cache.
123
+ // If no projects are found in the cache, it fetches them from the API and
124
+ // stores them in the cache for future use.
125
+ // It throws an error if no organizations are found in the cache.
126
+ async getProjects() {
127
+ let projects = this.cache.get(cacheKeys.PROJECTS);
128
+ if (!projects) {
129
+ const org = await this.getOrganization();
130
+ const options = {
131
+ paginate: true
132
+ };
133
+ const response = await this.currentUserApi.getOrganizationProjects(org.id, options);
134
+ projects = response.body || [];
135
+ this.cache.set(cacheKeys.PROJECTS, projects);
136
+ }
137
+ return projects;
138
+ }
139
+ async getProject(projectId) {
140
+ const projects = await this.getProjects();
141
+ return projects.find((p) => p.id === projectId) || null;
142
+ }
143
+ async getCurrentProject() {
144
+ let project = this.cache.get(cacheKeys.CURRENT_PROJECT) ?? null;
145
+ if (!project && this.projectApiKey) {
146
+ const projects = await this.getProjects();
147
+ project = projects.find((p) => p.api_key === this.projectApiKey) ?? null;
148
+ if (!project) {
149
+ throw new Error(`Unable to find project with API key ${this.projectApiKey} in organization.`);
150
+ }
151
+ this.cache.set(cacheKeys.CURRENT_PROJECT, project);
152
+ if (project) {
153
+ this.cache.set(cacheKeys.CURRENT_PROJECT_EVENT_FILTERS, await this.getProjectEventFilters(project));
154
+ }
155
+ }
156
+ return project;
157
+ }
158
+ async getProjectEventFilters(project) {
159
+ let filtersResponse = (await this.projectApi.listProjectEventFields(project.id)).body;
160
+ if (!filtersResponse || filtersResponse.length === 0) {
161
+ throw new Error(`No event fields found for project ${project.name}.`);
162
+ }
163
+ filtersResponse = filtersResponse.filter(field => !EXCLUDED_EVENT_FIELDS.has(field.display_id));
164
+ return filtersResponse;
165
+ }
166
+ async getEvent(eventId, projectId) {
167
+ const projectIds = projectId ? [projectId] : (await this.getProjects()).map((p) => p.id);
168
+ const projectEvents = await Promise.all(projectIds.map((projectId) => this.errorsApi.viewEventById(projectId, eventId).catch(_e => null)));
169
+ return projectEvents.find(event => event && !!event.body)?.body || null;
170
+ }
171
+ async updateError(projectId, errorId, operation, options) {
172
+ const errorUpdateRequest = {
173
+ operation: operation,
174
+ ...options
175
+ };
176
+ const response = await this.errorsApi.updateErrorOnProject(projectId, errorId, errorUpdateRequest);
177
+ return response.status === 200 || response.status === 204;
178
+ }
179
+ async getInputProject(projectId) {
180
+ if (typeof projectId === 'string') {
181
+ const maybeProject = await this.getProject(projectId);
182
+ if (!maybeProject) {
183
+ throw new Error(`Project with ID ${projectId} not found.`);
184
+ }
185
+ return maybeProject;
186
+ }
187
+ else {
188
+ const currentProject = await this.getCurrentProject();
189
+ if (!currentProject) {
190
+ throw new Error('No current project found. Please provide a projectId or configure a project API key.');
191
+ }
192
+ return currentProject;
193
+ }
194
+ }
195
+ registerTools(register, getInput) {
196
+ if (!this.projectApiKey) {
197
+ register({
198
+ title: "List Projects",
199
+ summary: "List all projects in the organization with optional pagination",
200
+ purpose: "Retrieve available projects for browsing and selecting which project to analyze",
201
+ useCases: [
202
+ "Browse available projects when no specific project API key is configured",
203
+ "Find project IDs needed for other tools",
204
+ "Get an overview of all projects in the organization"
205
+ ],
206
+ parameters: [
207
+ {
208
+ name: "page_size",
209
+ type: z.number(),
210
+ description: "Number of projects to return per page for pagination",
211
+ required: false,
212
+ examples: ["10", "25", "50"]
213
+ },
214
+ {
215
+ name: "page",
216
+ type: z.number(),
217
+ description: "Page number to return (starts from 1)",
218
+ required: false,
219
+ examples: ["1", "2", "3"]
220
+ }
221
+ ],
222
+ examples: [
223
+ {
224
+ description: "Get first 10 projects",
225
+ parameters: {
226
+ page_size: 10,
227
+ page: 1
228
+ },
229
+ expectedOutput: "JSON array of project objects with IDs, names, and metadata",
230
+ },
231
+ {
232
+ description: "Get all projects (no pagination)",
233
+ parameters: {},
234
+ expectedOutput: "JSON array of all available projects"
235
+ }
236
+ ],
237
+ hints: [
238
+ "Use pagination for organizations with many projects to avoid large responses",
239
+ "Project IDs from this list can be used with other tools when no project API key is configured"
240
+ ]
241
+ }, async (args, _extra) => {
242
+ let projects = await this.getProjects();
243
+ if (!projects || projects.length === 0) {
244
+ return {
245
+ content: [{ type: "text", text: "No projects found." }],
246
+ };
247
+ }
248
+ if (args.page_size || args.page) {
249
+ const pageSize = args.page_size || 10;
250
+ const page = args.page || 1;
251
+ projects = projects.slice((page - 1) * pageSize, page * pageSize);
252
+ }
253
+ const result = {
254
+ data: projects,
255
+ count: projects.length,
256
+ };
257
+ return {
258
+ content: [{ type: "text", text: JSON.stringify(result) }],
259
+ };
260
+ });
261
+ }
262
+ register({
263
+ title: "Get Error",
264
+ summary: "Get full details on an error, including aggregated and summarized data across all events (occurrences) and details of the latest event (occurrence), such as breadcrumbs, metadata and the stacktrace. Use the filters parameter to narrow down the summaries further.",
265
+ purpose: "Retrieve all the information required on a specified error to understand who it is affecting and why.",
266
+ useCases: [
267
+ "Investigate a specific error found through the List Project Errors tool",
268
+ "Understand which types of user are affected by the error using summarized event data",
269
+ "Get error details for debugging and root cause analysis",
270
+ "Retrieve error metadata for incident reports and documentation"
271
+ ],
272
+ parameters: [
273
+ {
274
+ name: "errorId",
275
+ type: z.string(),
276
+ required: true,
277
+ description: "Unique identifier of the error to retrieve",
278
+ examples: ["6863e2af8c857c0a5023b411"]
279
+ },
280
+ ...(this.projectApiKey ? [] : [
281
+ {
282
+ name: "projectId",
283
+ type: z.string(),
284
+ required: true,
285
+ description: "ID of the project containing the error",
286
+ }
287
+ ]),
288
+ {
289
+ name: "filters",
290
+ type: FilterObjectSchema,
291
+ required: false,
292
+ description: "Apply filters to narrow down the error list. Use the List Project Event Filters tool to discover available filter fields",
293
+ examples: [
294
+ '{"error.status": [{"type": "eq", "value": "open"}]}',
295
+ '{"event.since": [{"type": "eq", "value": "7d"}]} // Relative time: last 7 days',
296
+ '{"event.since": [{"type": "eq", "value": "2018-05-20T00:00:00Z"}]} // ISO 8601 UTC format',
297
+ '{"user.email": [{"type": "eq", "value": "user@example.com"}]}'
298
+ ],
299
+ constraints: [
300
+ "Time filters support ISO 8601 format (e.g. 2018-05-20T00:00:00Z) or relative format (e.g. 7d, 24h)",
301
+ "ISO 8601 times must be in UTC and use extended format",
302
+ "Relative time periods: h (hours), d (days)"
303
+ ]
304
+ }
305
+ ],
306
+ outputFormat: "JSON object containing: " +
307
+ " - error_details: Aggregated data about the error, including first and last seen occurrence" +
308
+ " - latest_event: Detailed information about the most recent occurrence of the error, including stacktrace, breadcrumbs, user and context" +
309
+ " - pivots: List of pivots (summaries) for the error, which can be used to analyze patterns in occurrences" +
310
+ " - url: A link to the error in the dashboard - this should be shown to the user for them to perform further analysis",
311
+ examples: [
312
+ {
313
+ description: "Get details for a specific error",
314
+ parameters: {
315
+ errorId: "6863e2af8c857c0a5023b411"
316
+ },
317
+ expectedOutput: "JSON object with error details including message, stack trace, occurrence count, and metadata"
318
+ }
319
+ ],
320
+ hints: [
321
+ "Error IDs can be found using the List Project Errors tool",
322
+ "Use this after filtering errors to get detailed information about specific errors",
323
+ "If you used a filter to get this error, you can pass the same filters here to restrict the results or apply further filters",
324
+ "The URL provided in the response points should be shown to the user in all cases as it allows them to view the error in the dashboard and perform further analysis",
325
+ ],
326
+ }, async (args, _extra) => {
327
+ const project = await this.getInputProject(args.projectId);
328
+ if (!args.errorId)
329
+ throw new Error("Both projectId and errorId arguments are required");
330
+ const errorDetails = (await this.errorsApi.viewErrorOnProject(project.id, args.errorId)).body;
331
+ if (!errorDetails) {
332
+ throw new Error(`Error with ID ${args.errorId} not found in project ${project.id}.`);
333
+ }
334
+ // Build query parameters
335
+ const params = new URLSearchParams();
336
+ // Add sorting and pagination parameters to get the latest event
337
+ params.append('sort', 'timestamp');
338
+ params.append('direction', 'desc');
339
+ params.append('per_page', '1');
340
+ params.append('full_reports', 'true');
341
+ const filters = {
342
+ "error": [{ type: "eq", value: args.errorId }],
343
+ ...args.filters
344
+ };
345
+ const filtersQueryString = toQueryString(filters);
346
+ const listEventsQueryString = `?${params}&${filtersQueryString}`;
347
+ // Get the latest event for this error using the events endpoint with filters
348
+ let latestEvent = null;
349
+ try {
350
+ const eventsResponse = await this.errorsApi.listEventsOnProject(project.id, listEventsQueryString);
351
+ const events = eventsResponse.body || [];
352
+ latestEvent = events[0] || null;
353
+ }
354
+ catch (e) {
355
+ console.warn("Failed to fetch latest event:", e);
356
+ // Continue without latest event rather than failing the entire request
357
+ }
358
+ const content = {
359
+ error_details: errorDetails,
360
+ latest_event: latestEvent,
361
+ pivots: (await this.errorsApi.listErrorPivots(project.id, args.errorId)).body || [],
362
+ url: await this.getErrorUrl(project, args.errorId, `?${filtersQueryString}`),
363
+ };
364
+ return {
365
+ content: [{ type: "text", text: JSON.stringify(content) }]
366
+ };
367
+ });
368
+ register({
369
+ title: "Get Event Details",
370
+ summary: "Get detailed information about a specific event using its dashboard URL",
371
+ purpose: "Retrieve event details directly from a dashboard URL for quick debugging",
372
+ useCases: [
373
+ "Get event details when given a dashboard URL from a user or notification",
374
+ "Extract event information from shared links or browser URLs",
375
+ "Quick lookup of event details without needing separate project and event IDs"
376
+ ],
377
+ parameters: [
378
+ {
379
+ name: "link",
380
+ type: z.string(),
381
+ description: "Full URL to the event details page in the BugSnag dashboard (web interface)",
382
+ required: true,
383
+ examples: [
384
+ "https://app.bugsnag.com/my-org/my-project/errors/6863e2af8c857c0a5023b411?event_id=6863e2af012caf1d5c320000"
385
+ ],
386
+ constraints: [
387
+ "Must be a valid dashboard URL containing project slug and event_id parameter"
388
+ ]
389
+ }
390
+ ],
391
+ examples: [
392
+ {
393
+ description: "Get event details from a dashboard URL",
394
+ parameters: {
395
+ link: "https://app.bugsnag.com/my-org/my-project/errors/6863e2af8c857c0a5023b411?event_id=6863e2af012caf1d5c320000"
396
+ },
397
+ expectedOutput: "JSON object with complete event details including stack trace, metadata, and context"
398
+ }
399
+ ],
400
+ hints: [
401
+ "The URL must contain both project slug in the path and event_id in query parameters",
402
+ "This is useful when users share BugSnag dashboard URLs and you need to extract the event data"
403
+ ]
404
+ }, async (args, _extra) => {
405
+ if (!args.link)
406
+ throw new Error("link argument is required");
407
+ const url = new URL(args.link);
408
+ const eventId = url.searchParams.get("event_id");
409
+ const projectSlug = url.pathname.split('/')[2];
410
+ if (!projectSlug || !eventId)
411
+ throw new Error("Both projectSlug and eventId must be present in the link");
412
+ // get the project id from list of projects
413
+ const projects = await this.getProjects();
414
+ const projectId = projects.find((p) => p.slug === projectSlug)?.id;
415
+ if (!projectId) {
416
+ throw new Error("Project with the specified slug not found.");
417
+ }
418
+ const response = await this.getEvent(eventId, projectId);
419
+ return {
420
+ content: [{ type: "text", text: JSON.stringify(response) }],
421
+ };
422
+ });
423
+ // Dynamically infer the filters schema from cached project event fields
424
+ register({
425
+ title: "List Project Errors",
426
+ summary: "List and search errors in a project using customizable filters and pagination",
427
+ purpose: "Retrieve filtered list of errors from a project for analysis, debugging, and reporting",
428
+ useCases: [
429
+ "Debug recent application errors by filtering for open errors in the last 7 days",
430
+ "Generate error reports for stakeholders by filtering specific error types or severity levels",
431
+ "Monitor error trends over time using date range filters",
432
+ "Find errors affecting specific users or environments using metadata filters"
433
+ ],
434
+ parameters: [
435
+ {
436
+ name: "filters",
437
+ type: FilterObjectSchema,
438
+ description: "Apply filters to narrow down the error list. Use the List Project Event Filters tool to discover available filter fields",
439
+ required: false,
440
+ examples: [
441
+ '{"error.status": [{"type": "eq", "value": "open"}]}',
442
+ '{"event.since": [{"type": "eq", "value": "7d"}]} // Relative time: last 7 days',
443
+ '{"event.since": [{"type": "eq", "value": "2018-05-20T00:00:00Z"}]} // ISO 8601 UTC format',
444
+ '{"user.email": [{"type": "eq", "value": "user@example.com"}]}'
445
+ ],
446
+ constraints: [
447
+ "Time filters support ISO 8601 format (e.g. 2018-05-20T00:00:00Z) or relative format (e.g. 7d, 24h)",
448
+ "ISO 8601 times must be in UTC and use extended format",
449
+ "Relative time periods: h (hours), d (days)"
450
+ ]
451
+ },
452
+ {
453
+ name: "sort",
454
+ type: z.enum(["first_seen", "last_seen", "events", "users", "unsorted"]),
455
+ description: "Field to sort the errors by (default: last_seen)",
456
+ required: false,
457
+ examples: ["last_seen"]
458
+ },
459
+ {
460
+ name: "direction",
461
+ type: z.enum(["asc", "desc"]).default("desc"),
462
+ description: "Sort direction for ordering results",
463
+ required: false,
464
+ examples: ["desc"]
465
+ },
466
+ {
467
+ name: "per_page",
468
+ type: z.number().min(1).max(100),
469
+ description: "How many results to return per page.",
470
+ required: false,
471
+ examples: ["30", "50", "100"]
472
+ },
473
+ {
474
+ name: "next",
475
+ type: z.string().url(),
476
+ description: "URL for retrieving the next page of results. Use the value in the previous response to get the next page when more results are available.",
477
+ required: false,
478
+ examples: ["https://api.bugsnag.com/projects/515fb9337c1074f6fd000003/errors?offset=30&per_page=30&sort=last_seen"],
479
+ constraints: ["Only values provided in the output from this tool can be used. Do not attempt to construct it manually."]
480
+ },
481
+ ...(this.projectApiKey ? [] : [
482
+ {
483
+ name: "projectId",
484
+ type: z.string(),
485
+ description: "ID of the project to query for errors",
486
+ required: true,
487
+ }
488
+ ])
489
+ ],
490
+ examples: [
491
+ {
492
+ description: "Find errors affecting a specific user in the last 24 hours",
493
+ parameters: {
494
+ filters: {
495
+ "user.email": [{ "type": "eq", "value": "user@example.com" }],
496
+ "event.since": [{ "type": "eq", "value": "24h" }]
497
+ }
498
+ },
499
+ expectedOutput: "JSON object with a list of errors in the 'data' field, a count of the current page of results in the 'count' field, and a total count of all results in the 'total' field"
500
+ },
501
+ {
502
+ description: "Get the 10 open errors with the most users affected in the last 30 days",
503
+ parameters: {
504
+ filters: {
505
+ "event.since": [{ "type": "eq", "value": "30d" }],
506
+ "error.status": [{ "type": "eq", "value": "open" }]
507
+ },
508
+ sort: "users",
509
+ direction: "desc",
510
+ per_page: 10
511
+ },
512
+ expectedOutput: "JSON object with a list of errors in the 'data' field, a count of the current page of results in the 'count' field, and a total count of all results in the 'total' field"
513
+ },
514
+ {
515
+ description: "Get the next 50 results",
516
+ parameters: {
517
+ next: "https://api.bugsnag.com/projects/515fb9337c1074f6fd000003/errors?base=2025-08-29T13%3A11%3A37Z&direction=desc&filters%5Berror.status%5D%5B%5D%5Btype%5D=eq&filters%5Berror.status%5D%5B%5D%5Bvalue%5D=open&offset=10&per_page=10&sort=users",
518
+ per_page: 50
519
+ },
520
+ expectedOutput: "JSON object with a list of errors in the 'data' field, a count of the current page of results in the 'count' field, and a total count of all results in the 'total' field"
521
+ }
522
+ ],
523
+ hints: [
524
+ "Use list_project_event_filters tool first to discover valid filter field names for your project",
525
+ "Combine multiple filters to narrow results - filters are applied with AND logic",
526
+ "For time filters: use relative format (7d, 24h) for recent periods or ISO 8601 UTC format (2018-05-20T00:00:00Z) for specific dates",
527
+ "Common time filters: event.since (from this time), event.before (until this time)",
528
+ "There may not be any errors matching the filters - this is not a problem with the tool, in fact it might be a good thing that the user's application had no errors",
529
+ "This tool returns paged results. The 'count' field indicates the number of results returned in the current page, and the 'total' field indicates the total number of results across all pages.",
530
+ "If the output contains a 'next' value, there are more results available - call this tool again supplying the next URL as a parameter to retrieve the next page.",
531
+ "Do not modify the next URL as this can cause incorrect results. The only other parameter that can be used with 'next' is 'per_page' to control the page size."
532
+ ]
533
+ }, async (args, _extra) => {
534
+ const project = await this.getInputProject(args.projectId);
535
+ // Validate filter keys against cached event fields
536
+ if (args.filters) {
537
+ const eventFields = this.cache.get(cacheKeys.CURRENT_PROJECT_EVENT_FILTERS) || [];
538
+ const validKeys = new Set(eventFields.map(f => f.display_id));
539
+ for (const key of Object.keys(args.filters)) {
540
+ if (!validKeys.has(key)) {
541
+ throw new Error(`Invalid filter key: ${key}`);
542
+ }
543
+ }
544
+ }
545
+ const options = {};
546
+ if (args.filters)
547
+ options.filters = args.filters;
548
+ if (args.sort !== undefined)
549
+ options.sort = args.sort;
550
+ if (args.direction !== undefined)
551
+ options.direction = args.direction;
552
+ if (args.per_page !== undefined)
553
+ options.per_page = args.per_page;
554
+ if (args.next !== undefined)
555
+ options.next = args.next;
556
+ const response = await this.errorsApi.listProjectErrors(project.id, options);
557
+ const errors = response.body || [];
558
+ const totalCount = response.headers.get('X-Total-Count');
559
+ const linkHeader = response.headers.get('Link');
560
+ const result = {
561
+ data: errors,
562
+ count: errors.length,
563
+ total: totalCount ? parseInt(totalCount) : undefined,
564
+ next: linkHeader?.match(/<([^>]+)>/)?.[1],
565
+ };
566
+ return {
567
+ content: [{ type: "text", text: JSON.stringify(result) }],
568
+ };
569
+ });
570
+ register({
571
+ title: "List Project Event Filters",
572
+ summary: "Get available event filter fields for the current project",
573
+ purpose: "Discover valid filter field names and options that can be used with the List Errors or Get Error tools",
574
+ useCases: [
575
+ "Discover what filter fields are available before searching for errors",
576
+ "Find the correct field names for filtering by user, environment, or custom metadata",
577
+ "Understand filter options and data types for building complex queries"
578
+ ],
579
+ parameters: [],
580
+ examples: [
581
+ {
582
+ description: "Get all available filter fields",
583
+ parameters: {},
584
+ expectedOutput: "JSON array of EventField objects containing display_id, custom flag, and filter/pivot options"
585
+ }
586
+ ],
587
+ hints: [
588
+ "Use this tool before the List Errors or Get Error tools to understand available filters",
589
+ "Look for display_id field in the response - these are the field names to use in filters"
590
+ ]
591
+ }, async (_args, _extra) => {
592
+ const projectFields = this.cache.get(cacheKeys.CURRENT_PROJECT_EVENT_FILTERS);
593
+ if (!projectFields)
594
+ throw new Error("No event filters found in cache.");
595
+ return {
596
+ content: [{ type: "text", text: JSON.stringify(projectFields) }],
597
+ };
598
+ });
599
+ register({
600
+ title: "Update Error",
601
+ summary: "Update the status of an error",
602
+ purpose: "Change an error's workflow state, such as marking it as resolved or ignored",
603
+ useCases: [
604
+ "Mark an error as open, fixed or ignored",
605
+ "Discard or un-discard an error",
606
+ "Update the severity of an error"
607
+ ],
608
+ parameters: [
609
+ ...(this.projectApiKey ? [] : [
610
+ {
611
+ name: "projectId",
612
+ type: z.string(),
613
+ description: "ID of the project that contains the error to be updated",
614
+ required: true,
615
+ }
616
+ ]),
617
+ {
618
+ name: "errorId",
619
+ type: z.string(),
620
+ description: "ID of the error to update",
621
+ required: true,
622
+ examples: ["6863e2af8c857c0a5023b411"]
623
+ },
624
+ {
625
+ name: "operation",
626
+ type: z.enum(PERMITTED_UPDATE_OPERATIONS),
627
+ description: "The operation to apply to the error",
628
+ required: true,
629
+ examples: ["fix", "open", "ignore", "discard", "undiscard"]
630
+ }
631
+ ],
632
+ examples: [
633
+ {
634
+ description: "Mark an error as fixed",
635
+ parameters: {
636
+ errorId: "6863e2af8c857c0a5023b411",
637
+ operation: "fix"
638
+ },
639
+ expectedOutput: "Success response indicating the error was marked as fixed"
640
+ }
641
+ ],
642
+ hints: [
643
+ "Only use valid operations - BugSnag may reject invalid values"
644
+ ],
645
+ readOnly: false,
646
+ idempotent: false,
647
+ }, async (args, _extra) => {
648
+ const { errorId, operation } = args;
649
+ const project = await this.getInputProject(args.projectId);
650
+ let severity = undefined;
651
+ if (operation === 'override_severity') {
652
+ // illicit the severity from the user
653
+ const result = await getInput({
654
+ message: "Please provide the new severity for the error (e.g. 'info', 'warning', 'error', 'critical')",
655
+ requestedSchema: {
656
+ type: "object",
657
+ properties: {
658
+ severity: {
659
+ type: "string",
660
+ enum: ['info', 'warning', 'error'],
661
+ description: "The new severity level for the error"
662
+ }
663
+ }
664
+ },
665
+ required: ["severity"]
666
+ });
667
+ if (result.action === "accept" && result.content?.severity) {
668
+ severity = result.content.severity;
669
+ }
670
+ }
671
+ const result = await this.updateError(project.id, errorId, operation, { severity });
672
+ return {
673
+ content: [{ type: "text", text: JSON.stringify({ success: result }) }],
674
+ };
675
+ });
676
+ }
677
+ registerResources(register) {
678
+ register("event", "{id}", async (uri, variables, _extra) => {
679
+ return {
680
+ contents: [{
681
+ uri: uri.href,
682
+ text: JSON.stringify(await this.getEvent(variables.id))
683
+ }]
684
+ };
685
+ });
686
+ }
687
+ }