@sentry/mcp-server 0.28.0 → 0.29.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 (41) hide show
  1. package/dist/cli/parse.cjs +1 -1
  2. package/dist/cli/parse.d.cts +1 -1
  3. package/dist/cli/parse.d.cts.map +1 -1
  4. package/dist/cli/parse.d.ts +1 -1
  5. package/dist/cli/parse.d.ts.map +1 -1
  6. package/dist/cli/parse.js +1 -1
  7. package/dist/cli/resolve.d.cts +1 -1
  8. package/dist/cli/resolve.d.ts +1 -1
  9. package/dist/cli/types.d.cts +1 -1
  10. package/dist/cli/types.d.ts +1 -1
  11. package/dist/cli/usage.cjs +1 -1
  12. package/dist/cli/usage.js +1 -1
  13. package/dist/index.cjs +1653 -78
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +1653 -78
  16. package/dist/index.js.map +1 -1
  17. package/dist/{parse-B9o4fVyT.js → parse-CEJNfXug.js} +4 -1
  18. package/dist/parse-CEJNfXug.js.map +1 -0
  19. package/dist/{parse-c_3eNB2Z.cjs → parse-DFk2004x.cjs} +4 -1
  20. package/dist/parse-DFk2004x.cjs.map +1 -0
  21. package/dist/{stdio-By-q6V_4.js → stdio-BG3LYhUm.js} +3 -3
  22. package/dist/{stdio-By-q6V_4.js.map → stdio-BG3LYhUm.js.map} +1 -1
  23. package/dist/{stdio-CjpLGbyD.cjs → stdio-CUTR3lwv.cjs} +3 -3
  24. package/dist/{stdio-CjpLGbyD.cjs.map → stdio-CUTR3lwv.cjs.map} +1 -1
  25. package/dist/transports/stdio.cjs +1 -1
  26. package/dist/transports/stdio.js +1 -1
  27. package/dist/{types-BlGRNCea.d.ts → types-DWpWltcD.d.cts} +3 -1
  28. package/dist/types-DWpWltcD.d.cts.map +1 -0
  29. package/dist/{types--Ysz5ZMd.d.cts → types-rOTvxXQO.d.ts} +3 -1
  30. package/dist/types-rOTvxXQO.d.ts.map +1 -0
  31. package/dist/{usage-D9Tpyb5N.cjs → usage-BZayoeC1.cjs} +2 -1
  32. package/dist/usage-BZayoeC1.cjs.map +1 -0
  33. package/dist/{usage-DR57Krum.js → usage-Bw3IN4iE.js} +2 -1
  34. package/dist/usage-Bw3IN4iE.js.map +1 -0
  35. package/package.json +4 -4
  36. package/dist/parse-B9o4fVyT.js.map +0 -1
  37. package/dist/parse-c_3eNB2Z.cjs.map +0 -1
  38. package/dist/types--Ysz5ZMd.d.cts.map +0 -1
  39. package/dist/types-BlGRNCea.d.ts.map +0 -1
  40. package/dist/usage-D9Tpyb5N.cjs.map +0 -1
  41. package/dist/usage-DR57Krum.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  const require_chunk = require('./chunk-DoeelZqw.cjs');
3
3
  const require_resolve = require('./resolve-DFUPLqHE.cjs');
4
- const require_stdio = require('./stdio-CjpLGbyD.cjs');
4
+ const require_stdio = require('./stdio-CUTR3lwv.cjs');
5
5
  const require_config_CEjP2CYO = require('./config-CEjP2CYO-CZKUamRu.cjs');
6
- const require_usage = require('./usage-D9Tpyb5N.cjs');
7
- const require_parse = require('./parse-c_3eNB2Z.cjs');
6
+ const require_usage = require('./usage-BZayoeC1.cjs');
7
+ const require_parse = require('./parse-DFk2004x.cjs');
8
8
  const zod = require_chunk.__toESM(require("zod"));
9
9
  const node_util = require_chunk.__toESM(require("node:util"));
10
10
  const __sentry_core = require_chunk.__toESM(require("@sentry/core"));
@@ -1752,7 +1752,7 @@ function logIssue(error, contextsOrOptions, attachmentsArg) {
1752
1752
  }
1753
1753
 
1754
1754
  //#endregion
1755
- //#region ../mcp-core/dist/schema-VoUcElu5.js
1755
+ //#region ../mcp-core/dist/schema-Db6vIKRE.js
1756
1756
  /**
1757
1757
  * Schema for Sentry API error responses.
1758
1758
  *
@@ -1796,7 +1796,11 @@ const ProjectSchema = zod.z.object({
1796
1796
  id: zod.z.union([zod.z.string(), zod.z.number()]),
1797
1797
  slug: zod.z.string(),
1798
1798
  name: zod.z.string(),
1799
- platform: zod.z.string().nullable().optional()
1799
+ platform: zod.z.string().nullable().optional(),
1800
+ hasProfiles: zod.z.boolean().optional(),
1801
+ hasReplays: zod.z.boolean().optional(),
1802
+ hasLogs: zod.z.boolean().optional(),
1803
+ firstTransactionEvent: zod.z.boolean().optional()
1800
1804
  }).passthrough();
1801
1805
  const ProjectListSchema = zod.z.array(ProjectSchema);
1802
1806
  const ClientKeySchema = zod.z.object({
@@ -1877,7 +1881,8 @@ const IssueSchema = zod.z.object({
1877
1881
  title: zod.z.string().nullable().optional(),
1878
1882
  location: zod.z.string().nullable().optional(),
1879
1883
  value: zod.z.string().nullable().optional()
1880
- }).optional()
1884
+ }).optional(),
1885
+ seerFixabilityScore: zod.z.number().nullable().optional()
1881
1886
  }).passthrough();
1882
1887
  const IssueListSchema = zod.z.array(IssueSchema);
1883
1888
  const FrameInterface = zod.z.object({
@@ -2272,6 +2277,150 @@ const TraceIssueSchema = zod.z.object({
2272
2277
  * objects when there are errors not directly associated with spans.
2273
2278
  */
2274
2279
  const TraceSchema = zod.z.array(zod.z.union([TraceSpanSchema, TraceIssueSchema]));
2280
+ /**
2281
+ * Schema for individual frames in a flamegraph.
2282
+ *
2283
+ * Represents a single stack frame with file/function information and
2284
+ * whether it's application code or library code.
2285
+ */
2286
+ const FlamegraphFrameSchema = zod.z.object({
2287
+ file: zod.z.string(),
2288
+ image: zod.z.string().optional(),
2289
+ is_application: zod.z.boolean(),
2290
+ line: zod.z.number(),
2291
+ name: zod.z.string(),
2292
+ path: zod.z.string().optional(),
2293
+ fingerprint: zod.z.number()
2294
+ }).passthrough();
2295
+ /**
2296
+ * Schema for aggregated performance statistics for a single frame.
2297
+ *
2298
+ * Contains sample counts, total weight/duration, and performance percentiles
2299
+ * (p75, p95, p99) for the frame across all samples.
2300
+ */
2301
+ const FlamegraphFrameInfoSchema = zod.z.object({
2302
+ count: zod.z.number(),
2303
+ weight: zod.z.number(),
2304
+ sumDuration: zod.z.number(),
2305
+ sumSelfTime: zod.z.number(),
2306
+ p75Duration: zod.z.number(),
2307
+ p95Duration: zod.z.number(),
2308
+ p99Duration: zod.z.number()
2309
+ }).passthrough();
2310
+ /**
2311
+ * Schema for profile metadata within a flamegraph response.
2312
+ *
2313
+ * Links to individual profile IDs and their time ranges.
2314
+ */
2315
+ const FlamegraphProfileMetadataSchema = zod.z.object({
2316
+ project_id: zod.z.number(),
2317
+ profile_id: zod.z.string(),
2318
+ start: zod.z.number(),
2319
+ end: zod.z.number()
2320
+ }).passthrough();
2321
+ /**
2322
+ * Schema for a single profile within a flamegraph (typically one per thread).
2323
+ *
2324
+ * Contains arrays of samples (call stack patterns), their occurrence counts,
2325
+ * durations, and relative weights.
2326
+ */
2327
+ const FlamegraphProfileSchema = zod.z.object({
2328
+ endValue: zod.z.number(),
2329
+ isMainThread: zod.z.boolean(),
2330
+ name: zod.z.string(),
2331
+ samples: zod.z.array(zod.z.array(zod.z.number())),
2332
+ startValue: zod.z.number(),
2333
+ threadID: zod.z.number(),
2334
+ type: zod.z.string(),
2335
+ unit: zod.z.string(),
2336
+ weights: zod.z.array(zod.z.number()),
2337
+ sample_durations_ns: zod.z.array(zod.z.number()),
2338
+ sample_counts: zod.z.array(zod.z.number())
2339
+ }).passthrough();
2340
+ /**
2341
+ * Schema for flamegraph API response.
2342
+ *
2343
+ * Flamegraphs provide pre-aggregated CPU profiling data with:
2344
+ * - Unique call stack patterns (samples)
2345
+ * - Performance statistics (counts, durations, percentiles)
2346
+ * - Frame metadata (file, function, is_application)
2347
+ *
2348
+ * This is the primary data source for profile analysis as it's
2349
+ * already aggregated and includes percentile calculations.
2350
+ */
2351
+ const FlamegraphSchema = zod.z.object({
2352
+ activeProfileIndex: zod.z.number(),
2353
+ metadata: zod.z.record(zod.z.unknown()).optional(),
2354
+ platform: zod.z.string(),
2355
+ profiles: zod.z.array(FlamegraphProfileSchema),
2356
+ projectID: zod.z.number(),
2357
+ shared: zod.z.object({
2358
+ frames: zod.z.array(FlamegraphFrameSchema),
2359
+ frame_infos: zod.z.array(FlamegraphFrameInfoSchema),
2360
+ profiles: zod.z.array(FlamegraphProfileMetadataSchema)
2361
+ }),
2362
+ transactionName: zod.z.string().optional(),
2363
+ metrics: zod.z.unknown().optional()
2364
+ }).passthrough();
2365
+ /**
2366
+ * Schema for individual frames in raw profile chunk data.
2367
+ *
2368
+ * Similar to FlamegraphFrameSchema but uses different field names
2369
+ * (function instead of name, in_app instead of is_application).
2370
+ * Many fields are optional as the API may not include them for all frames.
2371
+ */
2372
+ const ProfileFrameSchema = zod.z.object({
2373
+ filename: zod.z.string().nullable().optional(),
2374
+ function: zod.z.string(),
2375
+ in_app: zod.z.boolean(),
2376
+ lineno: zod.z.number().nullable().optional(),
2377
+ module: zod.z.string().nullable().optional(),
2378
+ abs_path: zod.z.string().nullable().optional(),
2379
+ platform: zod.z.string().nullable().optional(),
2380
+ data: zod.z.record(zod.z.unknown()).optional()
2381
+ }).passthrough();
2382
+ /**
2383
+ * Schema for individual samples in raw profile chunk data.
2384
+ *
2385
+ * Each sample represents a point-in-time snapshot of the call stack,
2386
+ * with a reference to the stack_id and thread_id.
2387
+ */
2388
+ const ProfileSampleSchema = zod.z.object({
2389
+ stack_id: zod.z.number(),
2390
+ thread_id: zod.z.string(),
2391
+ timestamp: zod.z.number()
2392
+ }).passthrough();
2393
+ /**
2394
+ * Schema for raw profile chunk data.
2395
+ *
2396
+ * Contains the raw sampling data including:
2397
+ * - frames: All unique stack frames
2398
+ * - samples: Individual sample points with timestamps
2399
+ * - stacks: Arrays of frame indices forming call stacks
2400
+ * - thread_metadata: Information about profiled threads
2401
+ *
2402
+ * This is used for deep-dive analysis when flamegraph data isn't sufficient.
2403
+ */
2404
+ const ProfileChunkSchema = zod.z.object({
2405
+ chunk_id: zod.z.string(),
2406
+ profiler_id: zod.z.string(),
2407
+ environment: zod.z.string().nullable(),
2408
+ platform: zod.z.string(),
2409
+ release: zod.z.string(),
2410
+ version: zod.z.string(),
2411
+ profile: zod.z.object({
2412
+ frames: zod.z.array(ProfileFrameSchema),
2413
+ samples: zod.z.array(ProfileSampleSchema),
2414
+ stacks: zod.z.array(zod.z.array(zod.z.number())),
2415
+ thread_metadata: zod.z.record(zod.z.object({ name: zod.z.string().nullable() }).passthrough())
2416
+ })
2417
+ }).passthrough();
2418
+ /**
2419
+ * Schema for profile chunks API response wrapper.
2420
+ *
2421
+ * The API returns chunks in an array wrapper, even for single chunk requests.
2422
+ */
2423
+ const ProfileChunkResponseSchema = zod.z.object({ chunks: zod.z.array(ProfileChunkSchema) }).passthrough();
2275
2424
 
2276
2425
  //#endregion
2277
2426
  //#region ../mcp-core/dist/errors-ZBQnDL3L.js
@@ -2489,7 +2638,7 @@ function createApiError(message, status, detail, responseBody) {
2489
2638
  }
2490
2639
 
2491
2640
  //#endregion
2492
- //#region ../mcp-core/dist/client-B2nQcl5S.js
2641
+ //#region ../mcp-core/dist/client-Cpo5HP9Z.js
2493
2642
  /**
2494
2643
  * Mapping of common network error codes to user-friendly messages.
2495
2644
  * These help users understand and resolve connection issues.
@@ -3621,6 +3770,93 @@ var SentryApiService = class {
3621
3770
  const body = await this.requestJSON(`/organizations/${organizationSlug}/trace/${traceId}/?${queryParams.toString()}`, void 0, opts);
3622
3771
  return TraceSchema.parse(body);
3623
3772
  }
3773
+ /**
3774
+ * Retrieves flamegraph data for a transaction.
3775
+ *
3776
+ * Flamegraphs provide pre-aggregated CPU profiling data including:
3777
+ * - Unique call stack patterns (samples)
3778
+ * - Performance statistics (counts, durations, percentiles)
3779
+ * - Frame metadata (file, function, is_application)
3780
+ *
3781
+ * This is the primary data source for profile analysis as it includes
3782
+ * aggregated hot paths and percentile calculations (p75, p95, p99).
3783
+ *
3784
+ * @param params Query parameters
3785
+ * @param params.organizationSlug Organization identifier
3786
+ * @param params.projectId Project ID or slug
3787
+ * @param params.transactionName Transaction name to analyze (e.g., "/api/users")
3788
+ * @param params.statsPeriod Time period for analysis (e.g., "7d", "14d", "30d")
3789
+ * @param opts Request options
3790
+ * @returns Flamegraph with pre-aggregated profiling data
3791
+ *
3792
+ * @example
3793
+ * ```typescript
3794
+ * const flamegraph = await apiService.getFlamegraph({
3795
+ * organizationSlug: "my-org",
3796
+ * projectId: 1,
3797
+ * transactionName: "/api/users",
3798
+ * statsPeriod: "7d"
3799
+ * });
3800
+ * console.log(`Analyzed ${flamegraph.profiles.length} profiles`);
3801
+ * ```
3802
+ */
3803
+ async getFlamegraph({ organizationSlug, projectId, transactionName, statsPeriod = "7d" }, opts) {
3804
+ const queryParams = new URLSearchParams();
3805
+ queryParams.set("project", projectId.toString());
3806
+ const escapedTransaction = transactionName.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
3807
+ queryParams.set("query", `event.type:transaction transaction:"${escapedTransaction}"`);
3808
+ queryParams.set("statsPeriod", statsPeriod);
3809
+ const path = `/organizations/${organizationSlug}/profiling/flamegraph/?${queryParams.toString()}`;
3810
+ const body = await this.requestJSON(path, void 0, opts);
3811
+ return FlamegraphSchema.parse(body);
3812
+ }
3813
+ /**
3814
+ * Retrieves raw profile chunk data for detailed analysis.
3815
+ *
3816
+ * Profile chunks contain:
3817
+ * - frames: All unique stack frames
3818
+ * - samples: Individual sample points with timestamps
3819
+ * - stacks: Arrays of frame indices forming call stacks
3820
+ * - thread_metadata: Information about profiled threads
3821
+ *
3822
+ * This is used for deep-dive analysis when flamegraph data isn't sufficient.
3823
+ * Most use cases should use getFlamegraph() instead, as it provides
3824
+ * pre-aggregated data that's easier to work with.
3825
+ *
3826
+ * @param params Query parameters
3827
+ * @param params.organizationSlug Organization identifier
3828
+ * @param params.profilerId Profiler ID from flamegraph output
3829
+ * @param params.projectId Project ID or slug
3830
+ * @param params.start Start time (ISO format)
3831
+ * @param params.end End time (ISO format)
3832
+ * @param opts Request options
3833
+ * @returns Raw profile chunk data
3834
+ * @throws ApiNotFoundError if no profile chunk is found
3835
+ *
3836
+ * @example
3837
+ * ```typescript
3838
+ * const chunk = await apiService.getProfileChunk({
3839
+ * organizationSlug: "my-org",
3840
+ * profilerId: "041bde57b9844e36b8b7e5734efae5f7",
3841
+ * projectId: 1,
3842
+ * start: "2024-01-01T00:00:00Z",
3843
+ * end: "2024-01-01T01:00:00Z"
3844
+ * });
3845
+ * console.log(`Chunk has ${chunk.profile.samples.length} samples`);
3846
+ * ```
3847
+ */
3848
+ async getProfileChunk({ organizationSlug, profilerId, projectId, start, end }, opts) {
3849
+ const queryParams = new URLSearchParams();
3850
+ queryParams.set("profiler_id", profilerId);
3851
+ queryParams.set("project", projectId.toString());
3852
+ queryParams.set("start", start);
3853
+ queryParams.set("end", end);
3854
+ const path = `/organizations/${organizationSlug}/profiling/chunks/?${queryParams.toString()}`;
3855
+ const body = await this.requestJSON(path, void 0, opts);
3856
+ const response = ProfileChunkResponseSchema.parse(body);
3857
+ if (!response.chunks || response.chunks.length === 0) throw new ApiNotFoundError(`No profile chunk found for profiler_id ${profilerId}`, void 0, body);
3858
+ return response.chunks[0];
3859
+ }
3624
3860
  };
3625
3861
 
3626
3862
  //#endregion
@@ -3656,7 +3892,7 @@ function validateRegionUrl(regionUrl, baseHost) {
3656
3892
  }
3657
3893
 
3658
3894
  //#endregion
3659
- //#region ../mcp-core/dist/api-DVbaHIM5.js
3895
+ //#region ../mcp-core/dist/api-e7vVEVb7.js
3660
3896
  /**
3661
3897
  * Create a Sentry API service from server context with optional region override
3662
3898
  * @param context - Server context containing host and access token
@@ -3677,7 +3913,7 @@ function apiServiceFromContext(context$1, opts = {}) {
3677
3913
  }
3678
3914
 
3679
3915
  //#endregion
3680
- //#region ../mcp-core/dist/whoami-CEHtgXJv.js
3916
+ //#region ../mcp-core/dist/whoami-CjTUNFbc.js
3681
3917
  var whoami_default = defineTool({
3682
3918
  name: "whoami",
3683
3919
  description: [
@@ -3710,7 +3946,7 @@ var whoami_default = defineTool({
3710
3946
  });
3711
3947
 
3712
3948
  //#endregion
3713
- //#region ../mcp-core/dist/find-organizations-Bs2wsqQ7.js
3949
+ //#region ../mcp-core/dist/find-organizations-C2lSjcCf.js
3714
3950
  const RESULT_LIMIT$2 = 25;
3715
3951
  var find_organizations_default = defineTool({
3716
3952
  name: "find_organizations",
@@ -3762,7 +3998,7 @@ var find_organizations_default = defineTool({
3762
3998
  });
3763
3999
 
3764
4000
  //#endregion
3765
- //#region ../mcp-core/dist/find-teams-CgsSmQ8X.js
4001
+ //#region ../mcp-core/dist/find-teams-gmGseaeL.js
3766
4002
  const RESULT_LIMIT$1 = 25;
3767
4003
  var find_teams_default = defineTool({
3768
4004
  name: "find_teams",
@@ -3810,7 +4046,7 @@ var find_teams_default = defineTool({
3810
4046
  });
3811
4047
 
3812
4048
  //#endregion
3813
- //#region ../mcp-core/dist/find-projects-Cxw1nnPQ.js
4049
+ //#region ../mcp-core/dist/find-projects-Cl9eTqeO.js
3814
4050
  const RESULT_LIMIT = 25;
3815
4051
  var find_projects_default = defineTool({
3816
4052
  name: "find_projects",
@@ -3854,7 +4090,7 @@ var find_projects_default = defineTool({
3854
4090
  });
3855
4091
 
3856
4092
  //#endregion
3857
- //#region ../mcp-core/dist/find-releases-zWgFsagR.js
4093
+ //#region ../mcp-core/dist/find-releases-BCe2NuH3.js
3858
4094
  var find_releases_default = defineTool({
3859
4095
  name: "find_releases",
3860
4096
  skills: ["inspect"],
@@ -4102,7 +4338,18 @@ function getOutputForAutofixStep(step) {
4102
4338
  }
4103
4339
 
4104
4340
  //#endregion
4105
- //#region ../mcp-core/dist/formatting-BhgNMv3a.js
4341
+ //#region ../mcp-core/dist/formatting-AtkcRYxR.js
4342
+ /**
4343
+ * Convert Seer fixability score to actionability label.
4344
+ * Thresholds match Sentry core: src/sentry/seer/autofix/constants.py
4345
+ */
4346
+ function getSeerActionabilityLabel(score) {
4347
+ if (score > .76) return "super_high";
4348
+ if (score > .66) return "high";
4349
+ if (score > .4) return "medium";
4350
+ if (score > .25) return "low";
4351
+ return "super_low";
4352
+ }
4106
4353
  const LANGUAGE_EXTENSIONS = {
4107
4354
  ".java": "java",
4108
4355
  ".py": "python",
@@ -5028,6 +5275,7 @@ function formatIssueOutput({ organizationSlug, issue, event, apiService, autofix
5028
5275
  }
5029
5276
  if (issue.issueType) output += `**Issue Type**: ${issue.issueType}\n`;
5030
5277
  if (issue.issueCategory) output += `**Issue Category**: ${issue.issueCategory}\n`;
5278
+ if (issue.seerFixabilityScore != null) output += `**Seer Actionability**: ${getSeerActionabilityLabel(issue.seerFixabilityScore)}\n`;
5031
5279
  output += `**Platform**: ${issue.platform}\n`;
5032
5280
  output += `**Project**: ${issue.project.name}\n`;
5033
5281
  output += `**URL**: ${apiService.getIssueUrl(organizationSlug, issue.shortId)}\n`;
@@ -5099,7 +5347,7 @@ function enhanceNotFoundError(error, params) {
5099
5347
  }
5100
5348
 
5101
5349
  //#endregion
5102
- //#region ../mcp-core/dist/get-issue-details-CsNkINzN.js
5350
+ //#region ../mcp-core/dist/get-issue-details-FSTw8nkJ.js
5103
5351
  var get_issue_details_default = defineTool({
5104
5352
  name: "get_issue_details",
5105
5353
  skills: [
@@ -5108,6 +5356,7 @@ var get_issue_details_default = defineTool({
5108
5356
  "seer"
5109
5357
  ],
5110
5358
  requiredScopes: ["event:read"],
5359
+ hideInExperimentalMode: true,
5111
5360
  description: [
5112
5361
  "Get detailed information about a specific Sentry issue by ID.",
5113
5362
  "",
@@ -5280,7 +5529,7 @@ function shouldFetchTraceForEvent(event) {
5280
5529
  }
5281
5530
 
5282
5531
  //#endregion
5283
- //#region ../mcp-core/dist/get-issue-tag-values-B4lzlivL.js
5532
+ //#region ../mcp-core/dist/get-issue-tag-values-BJe1EySg.js
5284
5533
  var get_issue_tag_values_default = defineTool({
5285
5534
  name: "get_issue_tag_values",
5286
5535
  skills: ["inspect"],
@@ -5395,7 +5644,7 @@ var get_issue_tag_values_default = defineTool({
5395
5644
  });
5396
5645
 
5397
5646
  //#endregion
5398
- //#region ../mcp-core/dist/get-trace-details-DAPondqS.js
5647
+ //#region ../mcp-core/dist/get-trace-details-Cd0Bw2-L.js
5399
5648
  const MAX_DEPTH = 2;
5400
5649
  const MINIMUM_DURATION_THRESHOLD_MS = 10;
5401
5650
  const MIN_MEANINGFUL_CHILD_DURATION = 5;
@@ -5404,6 +5653,8 @@ var get_trace_details_default = defineTool({
5404
5653
  name: "get_trace_details",
5405
5654
  skills: ["inspect"],
5406
5655
  requiredScopes: ["event:read"],
5656
+ requiredCapabilities: ["traces"],
5657
+ hideInExperimentalMode: true,
5407
5658
  description: [
5408
5659
  "Get detailed information about a specific Sentry trace by ID.",
5409
5660
  "",
@@ -5694,7 +5945,7 @@ function formatTraceOutput({ organizationSlug, traceId, traceMeta, trace: trace$
5694
5945
  }
5695
5946
 
5696
5947
  //#endregion
5697
- //#region ../mcp-core/dist/get-event-attachment-C-huGpTH.js
5948
+ //#region ../mcp-core/dist/get-event-attachment-ef7VExVM.js
5698
5949
  var get_event_attachment_default = defineTool({
5699
5950
  name: "get_event_attachment",
5700
5951
  skills: ["inspect"],
@@ -5842,7 +6093,7 @@ function formatAssignedTo(assignedTo) {
5842
6093
  }
5843
6094
 
5844
6095
  //#endregion
5845
- //#region ../mcp-core/dist/update-issue-BArI_SjL.js
6096
+ //#region ../mcp-core/dist/update-issue-bzyciFSm.js
5846
6097
  var update_issue_default = defineTool({
5847
6098
  name: "update_issue",
5848
6099
  skills: ["triage"],
@@ -9133,7 +9384,7 @@ function createOpenAI(options = {}) {
9133
9384
  var openai = createOpenAI({ compatibility: "strict" });
9134
9385
 
9135
9386
  //#endregion
9136
- //#region ../mcp-core/dist/openai-provider-Cc13TpEA.js
9387
+ //#region ../mcp-core/dist/openai-provider-BIi3UaOY.js
9137
9388
  const DEFAULT_OPENAI_MODEL = "gpt-5";
9138
9389
  let configuredBaseUrl$1;
9139
9390
  /**
@@ -10272,7 +10523,7 @@ function createAnthropic(options = {}) {
10272
10523
  var anthropic = createAnthropic();
10273
10524
 
10274
10525
  //#endregion
10275
- //#region ../mcp-core/dist/anthropic-provider-DOE-j9k3.js
10526
+ //#region ../mcp-core/dist/anthropic-provider-B1kgWCoH.js
10276
10527
  const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-5";
10277
10528
  let configuredBaseUrl;
10278
10529
  /**
@@ -10300,7 +10551,7 @@ function getAnthropicModel(model) {
10300
10551
  }
10301
10552
 
10302
10553
  //#endregion
10303
- //#region ../mcp-core/dist/provider-factory-BPN0JlR3.js
10554
+ //#region ../mcp-core/dist/provider-factory-BksPJetW.js
10304
10555
  let configuredProvider;
10305
10556
  /**
10306
10557
  * Configure the embedded agent provider explicitly.
@@ -10317,6 +10568,12 @@ function setProviderBaseUrls(config) {
10317
10568
  if (config.anthropicBaseUrl) setAnthropicBaseUrl(config.anthropicBaseUrl);
10318
10569
  }
10319
10570
  /**
10571
+ * Check if both API keys are present, indicating a conflict.
10572
+ */
10573
+ function detectProviderConflict() {
10574
+ return Boolean(process.env.ANTHROPIC_API_KEY) && Boolean(process.env.OPENAI_API_KEY);
10575
+ }
10576
+ /**
10320
10577
  * Check if the API key exists for a given provider type.
10321
10578
  */
10322
10579
  function hasApiKeyForProvider(type) {
@@ -10357,25 +10614,32 @@ function buildProvider(type) {
10357
10614
  }
10358
10615
  }
10359
10616
  /**
10617
+ * Resolve provider type from configuration and environment.
10618
+ * Returns undefined if no provider can be resolved or if there's a conflict.
10619
+ */
10620
+ function resolveProviderType() {
10621
+ if (configuredProvider) return configuredProvider;
10622
+ const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10623
+ if (envProvider === "openai" || envProvider === "anthropic") return envProvider;
10624
+ if (detectProviderConflict()) return void 0;
10625
+ if (process.env.ANTHROPIC_API_KEY) return "anthropic";
10626
+ if (process.env.OPENAI_API_KEY) return "openai";
10627
+ return void 0;
10628
+ }
10629
+ /**
10360
10630
  * Get the current agent provider based on configuration.
10361
10631
  *
10362
10632
  * Resolution order:
10363
10633
  * 1. Explicit configuration via setAgentProvider()
10364
10634
  * 2. EMBEDDED_AGENT_PROVIDER environment variable
10365
- * 3. Auto-detect: check ANTHROPIC_API_KEY, then OPENAI_API_KEY
10366
- * 4. Throw ConfigurationError if no provider available
10635
+ * 3. Detect conflicts when both API keys are present
10636
+ * 4. Auto-detect: check ANTHROPIC_API_KEY, then OPENAI_API_KEY
10637
+ * 5. Throw ConfigurationError if no provider available
10367
10638
  */
10368
10639
  function getAgentProvider() {
10369
- let providerType = configuredProvider;
10370
- if (!providerType) {
10371
- const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10372
- if (envProvider === "openai" || envProvider === "anthropic") providerType = envProvider;
10373
- }
10640
+ const providerType = resolveProviderType();
10374
10641
  if (providerType && !hasApiKeyForProvider(providerType)) throw new ConfigurationError(`Provider "${providerType}" is configured but ${getApiKeyName(providerType)} is not set. Please set the API key environment variable.`);
10375
- if (!providerType) {
10376
- if (process.env.ANTHROPIC_API_KEY) providerType = "anthropic";
10377
- else if (process.env.OPENAI_API_KEY) providerType = "openai";
10378
- }
10642
+ if (!providerType && detectProviderConflict()) throw new ConfigurationError("Both ANTHROPIC_API_KEY and OPENAI_API_KEY are set. Please specify which provider to use by setting the EMBEDDED_AGENT_PROVIDER environment variable to 'openai' or 'anthropic'.");
10379
10643
  if (!providerType) throw new ConfigurationError("No embedded agent provider configured. Set OPENAI_API_KEY or ANTHROPIC_API_KEY environment variable, or use --agent-provider flag to specify a provider.");
10380
10644
  return buildProvider(providerType);
10381
10645
  }
@@ -10393,15 +10657,11 @@ function hasAgentProvider() {
10393
10657
  }
10394
10658
  /**
10395
10659
  * Get the resolved provider type without throwing.
10396
- * Returns undefined if no provider is available or API key is missing.
10660
+ * Returns undefined if no provider is available, API key is missing, or both API keys are present without explicit selection.
10397
10661
  */
10398
10662
  function getResolvedProviderType() {
10399
- if (configuredProvider) return hasApiKeyForProvider(configuredProvider) ? configuredProvider : void 0;
10400
- const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10401
- if (envProvider === "openai" || envProvider === "anthropic") return hasApiKeyForProvider(envProvider) ? envProvider : void 0;
10402
- if (process.env.ANTHROPIC_API_KEY) return "anthropic";
10403
- if (process.env.OPENAI_API_KEY) return "openai";
10404
- return void 0;
10663
+ const providerType = resolveProviderType();
10664
+ return providerType && hasApiKeyForProvider(providerType) ? providerType : void 0;
10405
10665
  }
10406
10666
 
10407
10667
  //#endregion
@@ -15680,7 +15940,7 @@ function trimStartOfStream() {
15680
15940
  var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
15681
15941
 
15682
15942
  //#endregion
15683
- //#region ../mcp-core/dist/callEmbeddedAgent-BoQGUoqc.js
15943
+ //#region ../mcp-core/dist/callEmbeddedAgent-B-OOjWCj.js
15684
15944
  /**
15685
15945
  * Call an embedded agent with tool call capture
15686
15946
  * This is the standard way to call embedded AI agents within MCP tools
@@ -20769,7 +21029,7 @@ Use these examples as patterns for constructing your query.`;
20769
21029
  }
20770
21030
 
20771
21031
  //#endregion
20772
- //#region ../mcp-core/dist/agent-ChQa0if8.js
21032
+ //#region ../mcp-core/dist/agent-BWQdDemR.js
20773
21033
  const searchEventsAgentOutputSchema = zod.z.object({
20774
21034
  dataset: zod.z.enum([
20775
21035
  "spans",
@@ -21040,7 +21300,7 @@ function formatSpanResults(params) {
21040
21300
  }
21041
21301
 
21042
21302
  //#endregion
21043
- //#region ../mcp-core/dist/handler-DdfFan0E.js
21303
+ //#region ../mcp-core/dist/handler-DnOi9PpE.js
21044
21304
  var handler_default = defineTool({
21045
21305
  name: "search_events",
21046
21306
  skills: [
@@ -21181,7 +21441,7 @@ var handler_default = defineTool({
21181
21441
  });
21182
21442
 
21183
21443
  //#endregion
21184
- //#region ../mcp-core/dist/create-team-ybunuUI_.js
21444
+ //#region ../mcp-core/dist/create-team-BCT36Aw6.js
21185
21445
  var create_team_default = defineTool({
21186
21446
  name: "create_team",
21187
21447
  skills: ["project-management"],
@@ -21236,7 +21496,7 @@ var create_team_default = defineTool({
21236
21496
  });
21237
21497
 
21238
21498
  //#endregion
21239
- //#region ../mcp-core/dist/create-project-BozSQ6GO.js
21499
+ //#region ../mcp-core/dist/create-project-ml-im-rK.js
21240
21500
  var create_project_default = defineTool({
21241
21501
  name: "create_project",
21242
21502
  skills: ["project-management"],
@@ -21313,7 +21573,7 @@ var create_project_default = defineTool({
21313
21573
  });
21314
21574
 
21315
21575
  //#endregion
21316
- //#region ../mcp-core/dist/update-project-CSbOMuOW.js
21576
+ //#region ../mcp-core/dist/update-project-xYXR2Zc0.js
21317
21577
  var update_project_default = defineTool({
21318
21578
  name: "update_project",
21319
21579
  skills: ["project-management"],
@@ -21431,7 +21691,7 @@ var update_project_default = defineTool({
21431
21691
  });
21432
21692
 
21433
21693
  //#endregion
21434
- //#region ../mcp-core/dist/create-dsn-BymieFiV.js
21694
+ //#region ../mcp-core/dist/create-dsn-DfkcMX0d.js
21435
21695
  var create_dsn_default = defineTool({
21436
21696
  name: "create_dsn",
21437
21697
  skills: ["project-management"],
@@ -21491,7 +21751,7 @@ var create_dsn_default = defineTool({
21491
21751
  });
21492
21752
 
21493
21753
  //#endregion
21494
- //#region ../mcp-core/dist/find-dsns-_H3b8I5-.js
21754
+ //#region ../mcp-core/dist/find-dsns-Dwe6GuMG.js
21495
21755
  var find_dsns_default = defineTool({
21496
21756
  name: "find_dsns",
21497
21757
  skills: ["project-management"],
@@ -21592,7 +21852,7 @@ async function retryWithBackoff(fn, { maxRetries = 3, initialDelay = 1e3, should
21592
21852
  }
21593
21853
 
21594
21854
  //#endregion
21595
- //#region ../mcp-core/dist/analyze-issue-with-seer-C6Ke4lsw.js
21855
+ //#region ../mcp-core/dist/analyze-issue-with-seer-52UV39g3.js
21596
21856
  var analyze_issue_with_seer_default = defineTool({
21597
21857
  name: "analyze_issue_with_seer",
21598
21858
  skills: ["seer"],
@@ -21863,7 +22123,7 @@ var search_docs_default = defineTool({
21863
22123
  });
21864
22124
 
21865
22125
  //#endregion
21866
- //#region ../mcp-core/dist/get-doc-Ce6QYANY.js
22126
+ //#region ../mcp-core/dist/get-doc-aRAOW368.js
21867
22127
  var get_doc_default = defineTool({
21868
22128
  name: "get_doc",
21869
22129
  skills: ["docs"],
@@ -22090,7 +22350,7 @@ function getCommonPatterns(dataset) {
22090
22350
  }
22091
22351
 
22092
22352
  //#endregion
22093
- //#region ../mcp-core/dist/config-C3fctASk.js
22353
+ //#region ../mcp-core/dist/config-DUCtK3n7.js
22094
22354
  /**
22095
22355
  * Configuration for the search-issues agent
22096
22356
  */
@@ -22121,6 +22381,10 @@ BUILT-IN FIELDS:
22121
22381
  - assignedOrSuggested: Issues assigned to OR suggested for a user (broader match)
22122
22382
  - userCount: Number of unique users affected
22123
22383
  - eventCount: Total number of events
22384
+ - issue.seer_actionability: Seer's AI-assessed fix difficulty (super_high, high, medium, low, super_low)
22385
+ Use for: "easy to fix", "simple fixes", "quick wins", "low-hanging fruit", "actionable issues", "trivial"
22386
+ Values represent how likely Seer can automatically fix the issue.
22387
+ super_high = very easy/trivial, high = easy, medium = moderate, low/super_low = harder to fix
22124
22388
 
22125
22389
  COMMON QUERY PATTERNS:
22126
22390
  - Unresolved issues: is:unresolved (NO level filter unless explicitly requested)
@@ -22132,6 +22396,10 @@ COMMON QUERY PATTERNS:
22132
22396
  - User feedback: issueCategory:feedback
22133
22397
  - Recent feedback: issueCategory:feedback lastSeen:-7d
22134
22398
  - Feedback from production: issueCategory:feedback environment:production
22399
+ - Easy to fix issues: is:unresolved issue.seer_actionability:[high,super_high]
22400
+ - Quick wins: is:unresolved issue.seer_actionability:[high,super_high]
22401
+ - Very easy/trivial fixes: is:unresolved issue.seer_actionability:super_high
22402
+ - Actionable issues: is:unresolved issue.seer_actionability:[medium,high,super_high]
22135
22403
 
22136
22404
  SORTING RULES:
22137
22405
  1. CRITICAL: Sort MUST go in the separate "sort" field, NEVER in the "query" field
@@ -22157,6 +22425,10 @@ EXAMPLES:
22157
22425
  "assigned to john@example.com" → query: "assignedOrSuggested:john@example.com", sort: "date"
22158
22426
  "show me user feedback" → query: "issueCategory:feedback", sort: "date"
22159
22427
  "feedback from the last week" → query: "issueCategory:feedback lastSeen:-7d", sort: "date"
22428
+ "easy to fix bugs" → query: "is:unresolved issue.seer_actionability:[high,super_high]", sort: "date"
22429
+ "show me quick wins" → query: "is:unresolved issue.seer_actionability:[high,super_high]", sort: "user"
22430
+ "trivial issues to fix" → query: "is:unresolved issue.seer_actionability:super_high", sort: "date"
22431
+ "actionable errors" → query: "is:unresolved issue.seer_actionability:[medium,high,super_high]", sort: "freq"
22160
22432
 
22161
22433
  NEVER: query: "is:unresolved sort:user" ← Sort goes in separate field!
22162
22434
 
@@ -22170,7 +22442,7 @@ Always use the issueFields tool to discover available fields when needed.
22170
22442
  Use the whoami tool when you need to resolve 'me' references.`;
22171
22443
 
22172
22444
  //#endregion
22173
- //#region ../mcp-core/dist/agent-qJanDgXA.js
22445
+ //#region ../mcp-core/dist/agent-CbZD6I99.js
22174
22446
  const searchIssuesAgentOutputSchema = zod.z.object({
22175
22447
  query: zod.z.string().describe("The Sentry issue search query"),
22176
22448
  sort: zod.z.enum([
@@ -22203,7 +22475,7 @@ async function searchIssuesAgent(options) {
22203
22475
  }
22204
22476
 
22205
22477
  //#endregion
22206
- //#region ../mcp-core/dist/formatters-BcLCXcro.js
22478
+ //#region ../mcp-core/dist/formatters-EefHn4Td.js
22207
22479
  /**
22208
22480
  * Format an explanation for how a natural language query was translated
22209
22481
  */
@@ -22257,6 +22529,7 @@ function formatIssueResults(params) {
22257
22529
  output += `- **First seen**: ${formatDate(issue.firstSeen)}\n`;
22258
22530
  output += `- **Last seen**: ${formatDate(issue.lastSeen)}\n`;
22259
22531
  if (issue.culprit) output += `- **Culprit**: \`${issue.culprit}\`\n`;
22532
+ if (issue.seerFixabilityScore != null) output += `- **Seer Actionability**: ${getSeerActionabilityLabel(issue.seerFixabilityScore)}\n`;
22260
22533
  output += "\n";
22261
22534
  });
22262
22535
  output += "## Next Steps\n\n";
@@ -22287,7 +22560,7 @@ function formatDate(dateString) {
22287
22560
  }
22288
22561
 
22289
22562
  //#endregion
22290
- //#region ../mcp-core/dist/handler-DriMefmS.js
22563
+ //#region ../mcp-core/dist/handler-6FQ-M_Hc.js
22291
22564
  var handler_default$1 = defineTool({
22292
22565
  name: "search_issues",
22293
22566
  skills: [
@@ -22822,7 +23095,7 @@ Received: ${params.issueUrl}`);
22822
23095
  }
22823
23096
 
22824
23097
  //#endregion
22825
- //#region ../mcp-core/dist/agent-BGV8TUGG.js
23098
+ //#region ../mcp-core/dist/agent-BS8FSFrZ.js
22826
23099
  const searchIssueEventsAgentOutputSchema = zod.z.object({
22827
23100
  query: zod.z.string().describe("Sentry query filters for tags/fields (NOT including issue: prefix - handler adds that)"),
22828
23101
  fields: zod.z.array(zod.z.string()).describe("Array of field names to return in results"),
@@ -22864,7 +23137,7 @@ async function searchIssueEventsAgent(options) {
22864
23137
  }
22865
23138
 
22866
23139
  //#endregion
22867
- //#region ../mcp-core/dist/handler-dNZGGGFd.js
23140
+ //#region ../mcp-core/dist/handler-CnIAtQSZ.js
22868
23141
  var handler_default$2 = defineTool({
22869
23142
  name: "search_issue_events",
22870
23143
  skills: ["inspect", "triage"],
@@ -22985,7 +23258,7 @@ The user may include various parameters to pass to those tools in their prompt.
22985
23258
  You MUST return tool results directly without interpreting them.`;
22986
23259
 
22987
23260
  //#endregion
22988
- //#region ../mcp-core/dist/agent-2JRDh9Lm.js
23261
+ //#region ../mcp-core/dist/agent-BFhtnTf9.js
22989
23262
  /**
22990
23263
  * Output schema for the embedded agent.
22991
23264
  * The agent returns the final result string directly from its tool calls.
@@ -23006,7 +23279,27 @@ async function useSentryAgent(options) {
23006
23279
  }
23007
23280
 
23008
23281
  //#endregion
23009
- //#region ../mcp-core/dist/list-issues-DpmIWiEG.js
23282
+ //#region ../mcp-core/dist/types-CsTmoXmm.js
23283
+ /**
23284
+ * Resolves a tool description to a string.
23285
+ * Handles both static strings and dynamic description functions.
23286
+ */
23287
+ function resolveDescription(description$73, context$1) {
23288
+ return typeof description$73 === "function" ? description$73(context$1) : description$73;
23289
+ }
23290
+ /**
23291
+ * Determines if a tool should be visible based on experimental mode.
23292
+ * - Tools with `experimental: true` are only visible when experimentalMode is true
23293
+ * - Tools with `hideInExperimentalMode: true` are hidden when experimentalMode is true
23294
+ */
23295
+ function isToolVisibleInMode(tool$1, experimentalMode) {
23296
+ if (tool$1.experimental && !experimentalMode) return false;
23297
+ if (tool$1.hideInExperimentalMode && experimentalMode) return false;
23298
+ return true;
23299
+ }
23300
+
23301
+ //#endregion
23302
+ //#region ../mcp-core/dist/list-issues-5UocH4Yv.js
23010
23303
  var list_issues_default = defineTool({
23011
23304
  name: "list_issues",
23012
23305
  skills: [
@@ -23089,7 +23382,7 @@ var list_issues_default = defineTool({
23089
23382
  });
23090
23383
 
23091
23384
  //#endregion
23092
- //#region ../mcp-core/dist/list-events-BCMaD3UM.js
23385
+ //#region ../mcp-core/dist/list-events-B2eHsG5k.js
23093
23386
  const DEFAULT_FIELDS = {
23094
23387
  errors: require_config_CEjP2CYO.RECOMMENDED_FIELDS.errors.basic,
23095
23388
  logs: require_config_CEjP2CYO.RECOMMENDED_FIELDS.logs.basic,
@@ -23211,7 +23504,7 @@ var list_events_default = defineTool({
23211
23504
  });
23212
23505
 
23213
23506
  //#endregion
23214
- //#region ../mcp-core/dist/list-issue-events-D2EcLe8P.js
23507
+ //#region ../mcp-core/dist/list-issue-events-CpB246ug.js
23215
23508
  var list_issue_events_default = defineTool({
23216
23509
  name: "list_issue_events",
23217
23510
  skills: ["inspect", "triage"],
@@ -23295,7 +23588,1214 @@ var list_issue_events_default = defineTool({
23295
23588
  });
23296
23589
 
23297
23590
  //#endregion
23298
- //#region ../mcp-core/dist/error-handling-DFJ-iOAP.js
23591
+ //#region ../mcp-core/dist/analyzer-DtlTbDTS.js
23592
+ /**
23593
+ * Analyzes flamegraph data to extract hot paths (most CPU-intensive call stacks).
23594
+ *
23595
+ * Hot paths are merged when duplicate stacks appear, sorted by total duration
23596
+ * (most time spent), and limited to maxHotPaths. Each path includes the full
23597
+ * call stack with depth tracking.
23598
+ *
23599
+ * Note: Call stacks are stored leaf-to-root (main frame at end) for efficient
23600
+ * flamegraph/call tree merging. User code filtering is done during formatting.
23601
+ *
23602
+ * @param flamegraph Flamegraph data from API
23603
+ * @param options Analysis options
23604
+ * @returns Array of hot paths sorted by duration (descending)
23605
+ */
23606
+ function analyzeHotPathsFromFlamegraph(flamegraph, options) {
23607
+ const profile = flamegraph.profiles[0];
23608
+ if (!profile) return [];
23609
+ const frames = flamegraph.shared.frames;
23610
+ const frameInfos = flamegraph.shared.frame_infos;
23611
+ const totalSamples = profile.sample_counts.reduce((a, b) => a + b, 0);
23612
+ const mergedStacks = /* @__PURE__ */ new Map();
23613
+ for (let idx = 0; idx < profile.samples.length; idx++) {
23614
+ const stackIndices = profile.samples[idx];
23615
+ const sampleCount = profile.sample_counts[idx] || 0;
23616
+ const duration = profile.sample_durations_ns[idx] || 0;
23617
+ const weight = profile.weights[idx] || 0;
23618
+ const stackKey = stackIndices.join(",");
23619
+ const existing = mergedStacks.get(stackKey);
23620
+ if (existing) {
23621
+ existing.sampleCount += sampleCount;
23622
+ existing.duration += duration;
23623
+ existing.weight += weight;
23624
+ } else mergedStacks.set(stackKey, {
23625
+ stackIndices,
23626
+ sampleCount,
23627
+ duration,
23628
+ weight
23629
+ });
23630
+ }
23631
+ const hotPaths = Array.from(mergedStacks.values()).map((merged) => {
23632
+ const callStack = reconstructCallStack([...merged.stackIndices].reverse(), frames, frameInfos);
23633
+ const userCodeFrames = callStack.filter((f) => f.frame.is_application);
23634
+ return {
23635
+ stackIndices: merged.stackIndices,
23636
+ sampleCount: merged.sampleCount,
23637
+ duration: merged.duration,
23638
+ weight: merged.weight,
23639
+ percentOfTotal: totalSamples > 0 ? merged.sampleCount / totalSamples * 100 : 0,
23640
+ callStack,
23641
+ userCodeFrames
23642
+ };
23643
+ });
23644
+ return hotPaths.sort((a, b) => b.duration - a.duration).slice(0, options.maxHotPaths);
23645
+ }
23646
+ /** Default frame info for missing data */
23647
+ const DEFAULT_FRAME_INFO = {
23648
+ count: 0,
23649
+ weight: 0,
23650
+ sumDuration: 0,
23651
+ sumSelfTime: 0,
23652
+ p75Duration: 0,
23653
+ p95Duration: 0,
23654
+ p99Duration: 0
23655
+ };
23656
+ /** Default frame for missing data */
23657
+ const DEFAULT_FRAME = {
23658
+ file: "unknown",
23659
+ name: "unknown",
23660
+ line: 0,
23661
+ is_application: false,
23662
+ fingerprint: 0
23663
+ };
23664
+ /**
23665
+ * Reconstructs a call stack from frame indices with depth tracking.
23666
+ *
23667
+ * Frames are ordered leaf-to-root (leaf at index 0, root at end) for efficient
23668
+ * flamegraph/call tree merging. This allows top-down traversal and early
23669
+ * termination when merging stacks.
23670
+ *
23671
+ * @param stackIndices Array of frame indices forming the call stack (leaf to root)
23672
+ * @param frames All frames from flamegraph
23673
+ * @param frameInfos Performance stats for each frame
23674
+ * @returns Reconstructed call stack with metadata (leaf first, root last)
23675
+ */
23676
+ function reconstructCallStack(stackIndices, frames, frameInfos) {
23677
+ const stackLength = stackIndices.length;
23678
+ return stackIndices.map((frameIdx, idx) => ({
23679
+ frame: frames[frameIdx] || DEFAULT_FRAME,
23680
+ frameInfo: frameInfos[frameIdx] || DEFAULT_FRAME_INFO,
23681
+ depth: idx,
23682
+ isLeaf: idx === 0,
23683
+ isRoot: idx === stackLength - 1,
23684
+ frameIndex: frameIdx
23685
+ }));
23686
+ }
23687
+ /**
23688
+ * Identifies hotspot frames (functions consuming the most CPU time).
23689
+ *
23690
+ * Hotspots are individual functions that appear frequently in profiles,
23691
+ * sorted by total weight (time spent in that function across all samples).
23692
+ *
23693
+ * @param flamegraph Flamegraph data from API
23694
+ * @param options Analysis options
23695
+ * @returns Array of hotspot frames sorted by weight (descending)
23696
+ */
23697
+ function identifyHotspotFramesFromFlamegraph(flamegraph, options) {
23698
+ const frames = flamegraph.shared.frames;
23699
+ const frameInfos = flamegraph.shared.frame_infos;
23700
+ const totalSamples = flamegraph.profiles.reduce((sum, profile) => sum + profile.sample_counts.reduce((a, b) => a + b, 0), 0);
23701
+ const hotspots = frames.map((frame, idx) => {
23702
+ const frameInfo = frameInfos[idx] || DEFAULT_FRAME_INFO;
23703
+ return {
23704
+ frame,
23705
+ frameInfo,
23706
+ percentOfTotal: totalSamples > 0 ? frameInfo.count / totalSamples * 100 : 0,
23707
+ frameIndex: idx
23708
+ };
23709
+ }).filter((h) => !options.focusOnUserCode || h.frame.is_application).sort((a, b) => b.frameInfo.weight - a.frameInfo.weight).slice(0, 20);
23710
+ return hotspots;
23711
+ }
23712
+ /**
23713
+ * Generates performance insights based on percentile analysis.
23714
+ *
23715
+ * Analyzes p75, p95, and p99 latencies to identify:
23716
+ * - High variance (inconsistent performance)
23717
+ * - Consistently slow functions (high median)
23718
+ * - Hot functions (called very frequently)
23719
+ * - Consistent functions (low variance)
23720
+ *
23721
+ * @param frameInfo Performance statistics for a frame
23722
+ * @returns Array of insights
23723
+ */
23724
+ function generatePerformanceInsights(frameInfo) {
23725
+ const insights = [];
23726
+ if (frameInfo.p99Duration > frameInfo.p75Duration * 3) insights.push({
23727
+ type: "high_variance",
23728
+ icon: "⚠️",
23729
+ message: "High variance: Performance varies significantly across calls"
23730
+ });
23731
+ if (frameInfo.p75Duration > 1e8) insights.push({
23732
+ type: "consistently_slow",
23733
+ icon: "🐌",
23734
+ message: "Consistently slow: Median execution time is high"
23735
+ });
23736
+ if (frameInfo.count > 1e3) insights.push({
23737
+ type: "hot_function",
23738
+ icon: "🔥",
23739
+ message: "Hot function: Called very frequently"
23740
+ });
23741
+ if (insights.length === 0 && frameInfo.p99Duration <= frameInfo.p75Duration * 1.5) insights.push({
23742
+ type: "consistent",
23743
+ icon: "✅",
23744
+ message: "Consistent: Low performance variance"
23745
+ });
23746
+ return insights;
23747
+ }
23748
+ /**
23749
+ * Compares frame statistics between baseline and current to detect regressions.
23750
+ *
23751
+ * Analyzes percentage change in weight (total CPU time) and classifies changes:
23752
+ * - Major regression: >20% slower
23753
+ * - Minor regression: 10-20% slower
23754
+ * - Improvement: Faster
23755
+ * - No change: <10% change
23756
+ *
23757
+ * @param baseline Baseline flamegraph data
23758
+ * @param current Current flamegraph data
23759
+ * @param options Comparison options
23760
+ * @returns Array of frame comparisons sorted by regression severity
23761
+ */
23762
+ function compareFrameStats(baseline, current, options) {
23763
+ const baselineFrames = baseline.shared.frames;
23764
+ const currentFrames = current.shared.frames;
23765
+ const baselineInfos = baseline.shared.frame_infos;
23766
+ const currentInfos = current.shared.frame_infos;
23767
+ const frameMap = /* @__PURE__ */ new Map();
23768
+ baselineFrames.forEach((frame, idx) => {
23769
+ const existing = frameMap.get(frame.fingerprint) || {};
23770
+ frameMap.set(frame.fingerprint, {
23771
+ ...existing,
23772
+ baselineIdx: idx
23773
+ });
23774
+ });
23775
+ currentFrames.forEach((frame, idx) => {
23776
+ const existing = frameMap.get(frame.fingerprint) || {};
23777
+ frameMap.set(frame.fingerprint, {
23778
+ ...existing,
23779
+ currentIdx: idx
23780
+ });
23781
+ });
23782
+ const comparisons = [];
23783
+ for (const [fingerprint, indices] of frameMap.entries()) {
23784
+ if (indices.baselineIdx === void 0 || indices.currentIdx === void 0) continue;
23785
+ const baselineFrame = baselineFrames[indices.baselineIdx];
23786
+ const currentFrame = currentFrames[indices.currentIdx];
23787
+ const baselineInfo = baselineInfos[indices.baselineIdx] || DEFAULT_FRAME_INFO;
23788
+ const currentInfo = currentInfos[indices.currentIdx] || DEFAULT_FRAME_INFO;
23789
+ if (options.focusOnUserCode && !currentFrame.is_application) continue;
23790
+ const percentChange = baselineInfo.sumDuration > 0 ? (currentInfo.sumDuration - baselineInfo.sumDuration) / baselineInfo.sumDuration * 100 : 0;
23791
+ let changeType;
23792
+ if (percentChange > 20) changeType = "major_regression";
23793
+ else if (percentChange > 10) changeType = "minor_regression";
23794
+ else if (percentChange < -10) changeType = "improvement";
23795
+ else changeType = "no_change";
23796
+ comparisons.push({
23797
+ frame: currentFrame,
23798
+ baseline: baselineInfo,
23799
+ current: currentInfo,
23800
+ percentChange,
23801
+ changeType
23802
+ });
23803
+ }
23804
+ const severityOrder = {
23805
+ major_regression: 0,
23806
+ minor_regression: 1,
23807
+ no_change: 2,
23808
+ improvement: 3
23809
+ };
23810
+ return comparisons.sort((a, b) => severityOrder[a.changeType] - severityOrder[b.changeType] || b.percentChange - a.percentChange);
23811
+ }
23812
+ const MICROSECOND = 1e3;
23813
+ const MILLISECOND = 1e6;
23814
+ const SECOND = 1e9;
23815
+ /**
23816
+ * Formats duration from nanoseconds to human-readable string.
23817
+ *
23818
+ * @param ns Duration in nanoseconds
23819
+ * @returns Formatted duration string (e.g., "157ms", "1.2s")
23820
+ */
23821
+ function formatDuration(ns) {
23822
+ if (ns < MILLISECOND) return `${(ns / MICROSECOND).toFixed(0)}µs`;
23823
+ if (ns < SECOND) return `${(ns / MILLISECOND).toFixed(0)}ms`;
23824
+ return `${(ns / SECOND).toFixed(1)}s`;
23825
+ }
23826
+ /**
23827
+ * Formats a percentage value for display.
23828
+ *
23829
+ * @param value Percentage value (0-100)
23830
+ * @returns Formatted percentage string (e.g., "45.2%", "0.1%")
23831
+ */
23832
+ function formatPercentage(value) {
23833
+ if (value < 1) return `${value.toFixed(2)}%`;
23834
+ return `${value.toFixed(1)}%`;
23835
+ }
23836
+ /**
23837
+ * Checks if a flamegraph has valid profile data.
23838
+ *
23839
+ * Validates that the flamegraph contains at least one profile with frames.
23840
+ * Used to determine if analysis can proceed.
23841
+ *
23842
+ * @param flamegraph Flamegraph data from API
23843
+ * @returns True if the flamegraph has valid profile data
23844
+ */
23845
+ function hasProfileData(flamegraph) {
23846
+ return flamegraph.profiles.length > 0 && flamegraph.shared.frames.length > 0;
23847
+ }
23848
+
23849
+ //#endregion
23850
+ //#region ../mcp-core/dist/formatter-DnTyNWUz.js
23851
+ /**
23852
+ * Maps a change type to its corresponding status icon.
23853
+ */
23854
+ const CHANGE_TYPE_ICONS = {
23855
+ major_regression: "🚨",
23856
+ minor_regression: "⚠️",
23857
+ improvement: "✅",
23858
+ no_change: "➖"
23859
+ };
23860
+ /**
23861
+ * Determines the overall comparison status based on regression/improvement counts.
23862
+ */
23863
+ function determineComparisonStatus(majorCount, minorCount, improvementCount) {
23864
+ if (majorCount > 0) return "⚠️ Performance Regression Detected";
23865
+ if (minorCount > 0) return "⚠️ Minor Performance Changes Detected";
23866
+ if (improvementCount > 0) return "✅ Performance Improvements Detected";
23867
+ return "✅ No Significant Changes";
23868
+ }
23869
+ /**
23870
+ * Truncates a file location string for table display.
23871
+ */
23872
+ function truncateLocation(location, maxLength = 30) {
23873
+ if (location.length <= maxLength) return location;
23874
+ return `...${location.slice(-(maxLength - 3))}`;
23875
+ }
23876
+ /**
23877
+ * Formats flamegraph analysis for a single transaction.
23878
+ *
23879
+ * Produces markdown output with:
23880
+ * - Transaction information
23881
+ * - Performance summary (user code vs library)
23882
+ * - Top slow functions table
23883
+ * - Hot paths with recommendations
23884
+ * - Actionable next steps
23885
+ *
23886
+ * @param flamegraph Flamegraph data from API
23887
+ * @param options Formatting options
23888
+ * @returns Markdown-formatted analysis
23889
+ */
23890
+ function formatFlamegraphAnalysis(flamegraph, options) {
23891
+ const sections = [];
23892
+ sections.push(formatTransactionInfo(flamegraph));
23893
+ sections.push(formatPerformanceSummary(flamegraph, options));
23894
+ const hotPaths = analyzeHotPathsFromFlamegraph(flamegraph, options);
23895
+ sections.push(formatHotPaths(hotPaths, flamegraph, options));
23896
+ sections.push(formatActionableSteps(hotPaths, options));
23897
+ return sections.join("\n\n");
23898
+ }
23899
+ /**
23900
+ * Formats transaction information section.
23901
+ */
23902
+ function formatTransactionInfo(flamegraph) {
23903
+ const profile = flamegraph.profiles[0];
23904
+ const totalSamples = profile?.sample_counts.reduce((a, b) => a + b, 0) || 0;
23905
+ const totalDuration = profile?.sample_durations_ns.reduce((a, b) => a + b, 0) || 0;
23906
+ return [
23907
+ `# Profile Analysis: ${flamegraph.transactionName || "Unknown Transaction"}`,
23908
+ "",
23909
+ "## Transaction Information",
23910
+ `- **Transaction**: ${flamegraph.transactionName || "Unknown"}`,
23911
+ `- **Project ID**: ${flamegraph.projectID}`,
23912
+ `- **Platform**: ${flamegraph.platform || "Unknown"}`,
23913
+ `- **Total Profiles**: ${flamegraph.shared.profiles.length}`,
23914
+ `- **Total Samples**: ${totalSamples.toLocaleString()}`,
23915
+ `- **Estimated Total Time**: ${formatDuration(totalDuration)}`
23916
+ ].join("\n");
23917
+ }
23918
+ /**
23919
+ * Formats performance summary section.
23920
+ */
23921
+ function formatPerformanceSummary(flamegraph, options) {
23922
+ const hotspots = identifyHotspotFramesFromFlamegraph(flamegraph, { focusOnUserCode: false });
23923
+ let userCodeTime = 0;
23924
+ let libraryTime = 0;
23925
+ for (const h of hotspots) if (h.frame.is_application) userCodeTime += h.frameInfo.sumDuration;
23926
+ else libraryTime += h.frameInfo.sumDuration;
23927
+ const totalTime = userCodeTime + libraryTime;
23928
+ const userPercent = totalTime > 0 ? userCodeTime / totalTime * 100 : 0;
23929
+ const libraryPercent = totalTime > 0 ? libraryTime / totalTime * 100 : 0;
23930
+ const sections = [
23931
+ "## Performance Summary",
23932
+ "",
23933
+ "### Code Breakdown",
23934
+ `- **Total User Code Time**: ${formatDuration(userCodeTime)} (${formatPercentage(userPercent)})`,
23935
+ `- **Total Library Time**: ${formatDuration(libraryTime)} (${formatPercentage(libraryPercent)})`
23936
+ ];
23937
+ const topFunctions = identifyHotspotFramesFromFlamegraph(flamegraph, options).slice(0, 10);
23938
+ if (topFunctions.length > 0) {
23939
+ sections.push("", "### Top Slow Functions");
23940
+ sections.push("");
23941
+ sections.push("| Function | File:Line | Samples | % Time | p75 | p95 | p99 | Insights |");
23942
+ sections.push("|----------|-----------|---------|--------|-----|-----|-----|----------|");
23943
+ for (const func of topFunctions) {
23944
+ const insights = generatePerformanceInsights(func.frameInfo);
23945
+ const insightText = insights.map((i) => i.icon).join(" ");
23946
+ const location = truncateLocation(`${func.frame.file}:${func.frame.line}`);
23947
+ sections.push(`| \`${func.frame.name}\` | ${location} | ${func.frameInfo.count.toLocaleString()} | ${formatPercentage(func.percentOfTotal)} | ${formatDuration(func.frameInfo.p75Duration)} | ${formatDuration(func.frameInfo.p95Duration)} | ${formatDuration(func.frameInfo.p99Duration)} | ${insightText} |`);
23948
+ }
23949
+ }
23950
+ return sections.join("\n");
23951
+ }
23952
+ /**
23953
+ * Formats hot paths section.
23954
+ */
23955
+ function formatHotPaths(hotPaths, flamegraph, options) {
23956
+ if (hotPaths.length === 0) return "## Hot Paths\n\nNo significant hot paths found.";
23957
+ const sections = ["## Top Hot Paths", ""];
23958
+ hotPaths.forEach((path, idx) => {
23959
+ if (idx > 0) sections.push("---", "");
23960
+ sections.push(`### Path #${idx + 1}: ${formatPercentage(path.percentOfTotal)} of execution time`);
23961
+ sections.push("");
23962
+ sections.push(`**${path.sampleCount.toLocaleString()} samples** across ${flamegraph.shared.profiles.length} profiles`);
23963
+ sections.push("");
23964
+ const framesToShow = options.focusOnUserCode ? path.userCodeFrames : path.callStack;
23965
+ if (framesToShow.length > 0) {
23966
+ sections.push("```");
23967
+ const displayFrames = [...framesToShow].reverse();
23968
+ displayFrames.forEach((frame, i) => {
23969
+ const indent = " ".repeat(i);
23970
+ const marker$2 = frame.frame.is_application ? "[YOUR CODE]" : "[library]";
23971
+ const isLeaf = i === displayFrames.length - 1;
23972
+ const suffix = isLeaf && options.focusOnUserCode ? " ← PRIMARY BOTTLENECK" : "";
23973
+ sections.push(`${indent}${frame.frame.file}:${frame.frame.name}:${frame.frame.line} ${marker$2}${suffix}`);
23974
+ });
23975
+ sections.push("```");
23976
+ sections.push("");
23977
+ }
23978
+ const leafFrame = path.callStack[0];
23979
+ if (leafFrame) {
23980
+ const insights = generatePerformanceInsights(leafFrame.frameInfo);
23981
+ sections.push("**Performance Characteristics:**");
23982
+ sections.push(`- **p75**: ${formatDuration(leafFrame.frameInfo.p75Duration)}`);
23983
+ sections.push(`- **p95**: ${formatDuration(leafFrame.frameInfo.p95Duration)}`);
23984
+ sections.push(`- **p99**: ${formatDuration(leafFrame.frameInfo.p99Duration)}${insights.some((i) => i.type === "high_variance") ? " (⚠️ High variance - some calls are very slow)" : ""}`);
23985
+ sections.push("");
23986
+ sections.push("**💡 Recommendation:**");
23987
+ sections.push(`This path accounts for ${formatPercentage(path.percentOfTotal)} of CPU time.${insights.some((i) => i.type === "high_variance") ? " The high p99 indicates some operations are very slow." : ""}`);
23988
+ sections.push("");
23989
+ }
23990
+ });
23991
+ return sections.join("\n");
23992
+ }
23993
+ /**
23994
+ * Formats actionable next steps section.
23995
+ */
23996
+ function formatActionableSteps(hotPaths, options) {
23997
+ const sections = [
23998
+ "## Actionable Next Steps",
23999
+ "",
24000
+ "### Immediate Actions (High Impact)"
24001
+ ];
24002
+ const topPath = hotPaths[0];
24003
+ if (topPath) {
24004
+ const frameToRecommend = options.focusOnUserCode ? topPath.userCodeFrames[0] : topPath.callStack[0];
24005
+ if (frameToRecommend) sections.push(`1. **Optimize \`${frameToRecommend.frame.name}\` function** - Accounts for ${formatPercentage(topPath.percentOfTotal)} of CPU time`);
24006
+ }
24007
+ sections.push("2. **Add caching layer** - Consider caching frequently accessed data", "3. **Review query patterns** - Look for N+1 queries or inefficient data access", "", "### Investigation Actions", "1. **Compare with baseline**: Use get_profile with compareAgainstPeriod to check for regressions");
24008
+ return sections.join("\n");
24009
+ }
24010
+ /**
24011
+ * Formats flamegraph comparison for regression detection.
24012
+ *
24013
+ * Produces markdown output with:
24014
+ * - Comparison summary
24015
+ * - Key changes table
24016
+ * - Regressions detected
24017
+ * - Suggested investigation steps
24018
+ *
24019
+ * @param baseline Baseline flamegraph data
24020
+ * @param current Current flamegraph data
24021
+ * @param options Formatting options
24022
+ * @returns Markdown-formatted comparison
24023
+ */
24024
+ function formatFlamegraphComparison(baseline, current, options) {
24025
+ const sections = [];
24026
+ sections.push(`# Profile Comparison: ${current.transactionName || "Unknown Transaction"}`);
24027
+ sections.push("");
24028
+ sections.push("## Summary");
24029
+ const comparisons = compareFrameStats(baseline, current, options);
24030
+ const majorRegressions = comparisons.filter((c) => c.changeType === "major_regression");
24031
+ const minorRegressions = comparisons.filter((c) => c.changeType === "minor_regression");
24032
+ const improvements = comparisons.filter((c) => c.changeType === "improvement");
24033
+ const status = determineComparisonStatus(majorRegressions.length, minorRegressions.length, improvements.length);
24034
+ sections.push(`- **Status**: ${status}`);
24035
+ sections.push("");
24036
+ if (comparisons.length > 0) {
24037
+ sections.push("## Key Changes");
24038
+ sections.push("");
24039
+ sections.push("| Function | File:Line | Baseline | Current | Change | Status |");
24040
+ sections.push("|----------|-----------|----------|---------|--------|--------|");
24041
+ for (const comp of comparisons.slice(0, 10)) {
24042
+ const location = truncateLocation(`${comp.frame.file}:${comp.frame.line}`);
24043
+ const statusIcon = CHANGE_TYPE_ICONS[comp.changeType];
24044
+ const change = comp.percentChange > 0 ? `+${formatPercentage(comp.percentChange)}` : formatPercentage(comp.percentChange);
24045
+ sections.push(`| \`${comp.frame.name}\` | ${location} | ${formatDuration(comp.baseline.sumDuration)} | ${formatDuration(comp.current.sumDuration)} | ${change} | ${statusIcon} |`);
24046
+ }
24047
+ sections.push("");
24048
+ }
24049
+ if (majorRegressions.length > 0) {
24050
+ sections.push("## Major Regressions Detected");
24051
+ sections.push("");
24052
+ for (const reg of majorRegressions.slice(0, 5)) {
24053
+ sections.push(`### 🚨 \`${reg.frame.name}\``);
24054
+ sections.push(`- **Change**: +${formatPercentage(reg.percentChange)} slower`);
24055
+ sections.push(`- **Impact**: ${formatDuration(reg.baseline.sumDuration)} → ${formatDuration(reg.current.sumDuration)}`);
24056
+ sections.push(`- **Location**: ${reg.frame.file}:${reg.frame.line}`);
24057
+ sections.push("");
24058
+ sections.push("**Suggested Action**: Investigate recent changes to this function");
24059
+ sections.push("");
24060
+ }
24061
+ }
24062
+ return sections.join("\n");
24063
+ }
24064
+
24065
+ //#endregion
24066
+ //#region ../mcp-core/dist/url-helpers-eQ8-mYIs.js
24067
+ /**
24068
+ * Parses a Sentry URL and extracts resource type and identifiers.
24069
+ *
24070
+ * Supported URL patterns:
24071
+ * - Issue: `/issues/{issueId}` or `/organizations/{org}/issues/{issueId}`
24072
+ * - Event: `/issues/{issueId}/events/{eventId}`
24073
+ * - Trace: `/explore/traces/trace/{traceId}` or `/performance/trace/{traceId}`
24074
+ * - Profile: `/explore/profiling/profile/{project}/flamegraph/` with query params
24075
+ * - Replay: `/replays/{replayId}/`
24076
+ * - Monitor: `/crons/{monitorSlug}/` or `/monitors/{monitorSlug}/`
24077
+ * - Release: `/releases/{version}/`
24078
+ *
24079
+ * Organization slug is extracted from:
24080
+ * 1. Subdomain (e.g., `my-org.sentry.io`)
24081
+ * 2. Path (e.g., `/organizations/my-org/...` or `/my-org/issues/...`)
24082
+ *
24083
+ * @param url - A Sentry URL to parse
24084
+ * @returns Parsed URL with resource type and identifiers
24085
+ * @throws UserInputError if the URL is invalid or cannot be parsed
24086
+ *
24087
+ * @example
24088
+ * // Issue URL
24089
+ * parseSentryUrl("https://my-org.sentry.io/issues/PROJECT-123")
24090
+ * // { type: "issue", organizationSlug: "my-org", issueId: "PROJECT-123" }
24091
+ *
24092
+ * @example
24093
+ * // Replay URL
24094
+ * parseSentryUrl("https://my-org.sentry.io/replays/abc123def456/")
24095
+ * // { type: "replay", organizationSlug: "my-org", replayId: "abc123def456" }
24096
+ *
24097
+ * @example
24098
+ * // Monitor URL
24099
+ * parseSentryUrl("https://my-org.sentry.io/crons/my-cron-job/")
24100
+ * // { type: "monitor", organizationSlug: "my-org", monitorSlug: "my-cron-job" }
24101
+ */
24102
+ function parseSentryUrl(url) {
24103
+ if (!url || typeof url !== "string") throw new UserInputError("Invalid Sentry URL. URL must be a non-empty string.");
24104
+ if (!url.startsWith("http://") && !url.startsWith("https://")) throw new UserInputError("Invalid Sentry URL. Must start with http:// or https://");
24105
+ let parsedUrl;
24106
+ try {
24107
+ parsedUrl = new URL(url);
24108
+ } catch {
24109
+ throw new UserInputError(`Invalid Sentry URL. Unable to parse URL: ${url}`);
24110
+ }
24111
+ const pathParts = parsedUrl.pathname.split("/").filter(Boolean);
24112
+ const organizationSlug = extractOrganizationSlug(parsedUrl, pathParts);
24113
+ return identifyResource(parsedUrl, pathParts, organizationSlug);
24114
+ }
24115
+ /**
24116
+ * Extracts organization slug from URL.
24117
+ *
24118
+ * Checks in order:
24119
+ * 1. `/organizations/{org}/...` path format
24120
+ * 2. `/{org}/issues/...` path format (org before known segments)
24121
+ * 3. Subdomain (e.g., `my-org.sentry.io`) - excluding region prefixes
24122
+ */
24123
+ function extractOrganizationSlug(parsedUrl, pathParts) {
24124
+ if (pathParts.includes("organizations")) {
24125
+ const orgIndex = pathParts.indexOf("organizations");
24126
+ const slug = pathParts[orgIndex + 1];
24127
+ if (slug) return slug;
24128
+ }
24129
+ const knownSegments = [
24130
+ "issues",
24131
+ "explore",
24132
+ "performance",
24133
+ "projects",
24134
+ "settings",
24135
+ "replays",
24136
+ "releases",
24137
+ "crons",
24138
+ "monitors",
24139
+ "alerts",
24140
+ "feedback",
24141
+ "dashboards",
24142
+ "discover",
24143
+ "insights"
24144
+ ];
24145
+ if (pathParts.length > 1 && knownSegments.includes(pathParts[1])) return pathParts[0];
24146
+ const hostParts = parsedUrl.hostname.split(".");
24147
+ const regionPrefixes = [
24148
+ "us",
24149
+ "eu",
24150
+ "de",
24151
+ "www"
24152
+ ];
24153
+ if (hostParts.length >= 2 && !regionPrefixes.includes(hostParts[0])) return hostParts[0];
24154
+ throw new UserInputError("Invalid Sentry URL. Could not determine organization from URL.");
24155
+ }
24156
+ /**
24157
+ * Identifies the resource type and extracts relevant identifiers.
24158
+ */
24159
+ function identifyResource(parsedUrl, pathParts, organizationSlug) {
24160
+ const profilingIndex = pathParts.indexOf("profiling");
24161
+ if (profilingIndex !== -1 && pathParts[profilingIndex + 1] === "profile") {
24162
+ const projectSlug = pathParts[profilingIndex + 2];
24163
+ const profilerId = parsedUrl.searchParams.get("profilerId") || void 0;
24164
+ const start = parsedUrl.searchParams.get("start") || void 0;
24165
+ const end = parsedUrl.searchParams.get("end") || void 0;
24166
+ return {
24167
+ type: "profile",
24168
+ organizationSlug,
24169
+ projectSlug,
24170
+ profilerId,
24171
+ start,
24172
+ end
24173
+ };
24174
+ }
24175
+ const replaysIndex = pathParts.indexOf("replays");
24176
+ if (replaysIndex !== -1) {
24177
+ const replayId = pathParts[replaysIndex + 1];
24178
+ if (replayId && replayId !== "selectors") return {
24179
+ type: "replay",
24180
+ organizationSlug,
24181
+ replayId
24182
+ };
24183
+ }
24184
+ const cronsIndex = pathParts.indexOf("crons");
24185
+ const monitorsIndex = pathParts.indexOf("monitors");
24186
+ const monitorPathIndex = cronsIndex !== -1 ? cronsIndex : monitorsIndex;
24187
+ if (monitorPathIndex !== -1) {
24188
+ const nextPart = pathParts[monitorPathIndex + 1];
24189
+ if (nextPart && nextPart !== "new") {
24190
+ const afterNext = pathParts[monitorPathIndex + 2];
24191
+ if (afterNext && afterNext !== "details") return {
24192
+ type: "monitor",
24193
+ organizationSlug,
24194
+ projectSlug: nextPart,
24195
+ monitorSlug: afterNext
24196
+ };
24197
+ return {
24198
+ type: "monitor",
24199
+ organizationSlug,
24200
+ monitorSlug: nextPart
24201
+ };
24202
+ }
24203
+ }
24204
+ const releasesIndex = pathParts.indexOf("releases");
24205
+ if (releasesIndex !== -1) {
24206
+ const releaseVersion = pathParts[releasesIndex + 1];
24207
+ if (releaseVersion && releaseVersion !== "new-events" && releaseVersion !== "all-events") return {
24208
+ type: "release",
24209
+ organizationSlug,
24210
+ releaseVersion
24211
+ };
24212
+ }
24213
+ const traceIndex = pathParts.indexOf("trace");
24214
+ if (traceIndex !== -1) {
24215
+ const traceId = pathParts[traceIndex + 1];
24216
+ if (traceId) {
24217
+ const nodeParam = parsedUrl.searchParams.get("node");
24218
+ let spanId;
24219
+ if (nodeParam?.startsWith("span-")) spanId = nodeParam.slice(5);
24220
+ return {
24221
+ type: "trace",
24222
+ organizationSlug,
24223
+ traceId,
24224
+ spanId
24225
+ };
24226
+ }
24227
+ }
24228
+ if (pathParts.includes("performance") && pathParts.includes("summary")) {
24229
+ const transaction = parsedUrl.searchParams.get("transaction") || void 0;
24230
+ if (transaction) return {
24231
+ type: "unknown",
24232
+ organizationSlug,
24233
+ transaction
24234
+ };
24235
+ }
24236
+ const issuesIndex = pathParts.indexOf("issues");
24237
+ if (issuesIndex !== -1) {
24238
+ const issueId = pathParts[issuesIndex + 1];
24239
+ if (issueId) {
24240
+ const eventsIndex = pathParts.indexOf("events", issuesIndex);
24241
+ if (eventsIndex !== -1) {
24242
+ const eventId = pathParts[eventsIndex + 1];
24243
+ if (eventId) return {
24244
+ type: "event",
24245
+ organizationSlug,
24246
+ issueId,
24247
+ eventId
24248
+ };
24249
+ }
24250
+ return {
24251
+ type: "issue",
24252
+ organizationSlug,
24253
+ issueId
24254
+ };
24255
+ }
24256
+ }
24257
+ return {
24258
+ type: "unknown",
24259
+ organizationSlug
24260
+ };
24261
+ }
24262
+ /**
24263
+ * Checks if a URL appears to be a Sentry profile URL.
24264
+ *
24265
+ * @param url - URL to check
24266
+ * @returns True if the URL looks like a profile URL
24267
+ */
24268
+ function isProfileUrl(url) {
24269
+ try {
24270
+ const parsed = parseSentryUrl(url);
24271
+ return parsed.type === "profile";
24272
+ } catch {
24273
+ return false;
24274
+ }
24275
+ }
24276
+
24277
+ //#endregion
24278
+ //#region ../mcp-core/dist/get-profile-DftJNHhz.js
24279
+ /**
24280
+ * Resolves profile parameters from URL or explicit params.
24281
+ * URL takes precedence if provided and valid.
24282
+ */
24283
+ function resolveProfileParams(params) {
24284
+ if (params.profileUrl) {
24285
+ if (!isProfileUrl(params.profileUrl)) throw new UserInputError("Invalid profile URL. URL must be a Sentry profile URL (containing /profiling/profile/).");
24286
+ const parsed = parseSentryUrl(params.profileUrl);
24287
+ return {
24288
+ organizationSlug: parsed.organizationSlug,
24289
+ projectSlugOrId: parsed.projectSlug ?? params.projectSlugOrId ?? void 0,
24290
+ transactionName: params.transactionName ?? void 0
24291
+ };
24292
+ }
24293
+ if (!params.organizationSlug) throw new UserInputError("Organization slug is required. Provide either a profileUrl or organizationSlug parameter.");
24294
+ return {
24295
+ organizationSlug: params.organizationSlug,
24296
+ projectSlugOrId: params.projectSlugOrId ?? void 0,
24297
+ transactionName: params.transactionName ?? void 0
24298
+ };
24299
+ }
24300
+ var get_profile_default = defineTool({
24301
+ name: "get_profile",
24302
+ skills: ["inspect"],
24303
+ requiredScopes: ["event:read"],
24304
+ requiredCapabilities: ["profiles"],
24305
+ hideInExperimentalMode: true,
24306
+ description: [
24307
+ "Analyze CPU profiling data to identify performance bottlenecks and detect regressions.",
24308
+ "",
24309
+ "USE THIS TOOL WHEN:",
24310
+ "- User asks why a specific endpoint/transaction is slow",
24311
+ "- User wants to understand where CPU time is spent",
24312
+ "- User asks about performance bottlenecks",
24313
+ "- User wants to compare performance between time periods",
24314
+ "- User shares a Sentry profile URL",
24315
+ "",
24316
+ "RETURNS:",
24317
+ "- Hot paths (call stacks consuming the most CPU time)",
24318
+ "- Performance percentiles (p75, p95, p99) for each function",
24319
+ "- User code vs library code breakdown",
24320
+ "- Actionable recommendations for optimization",
24321
+ "- Regression analysis when comparing periods",
24322
+ "",
24323
+ "<examples>",
24324
+ "### Analyze from URL (with transaction name)",
24325
+ "```",
24326
+ "get_profile(",
24327
+ " profileUrl='https://my-org.sentry.io/explore/profiling/profile/backend/flamegraph/?profilerId=abc123',",
24328
+ " transactionName='/api/users'",
24329
+ ")",
24330
+ "```",
24331
+ "",
24332
+ "### Analyze by transaction name",
24333
+ "```",
24334
+ "get_profile(",
24335
+ " organizationSlug='my-org',",
24336
+ " transactionName='/api/users',",
24337
+ " projectSlugOrId='backend'",
24338
+ ")",
24339
+ "```",
24340
+ "",
24341
+ "### Compare performance between periods",
24342
+ "```",
24343
+ "get_profile(",
24344
+ " organizationSlug='my-org',",
24345
+ " transactionName='/api/users',",
24346
+ " projectSlugOrId='backend',",
24347
+ " statsPeriod='7d',",
24348
+ " compareAgainstPeriod='14d'",
24349
+ ")",
24350
+ "```",
24351
+ "</examples>",
24352
+ "",
24353
+ "<hints>",
24354
+ "- Use `focusOnUserCode: true` (default) to filter out library code",
24355
+ "- High p99 relative to p75 indicates inconsistent performance",
24356
+ "- Use compareAgainstPeriod to detect regressions over time",
24357
+ "- Transaction names are case-sensitive",
24358
+ "</hints>"
24359
+ ].join("\n"),
24360
+ inputSchema: {
24361
+ profileUrl: zod.z.string().url().optional().describe("Sentry profile URL. If provided, organization and project are extracted from URL. transactionName is still required."),
24362
+ organizationSlug: ParamOrganizationSlug.optional(),
24363
+ regionUrl: ParamRegionUrl.nullable().default(null),
24364
+ projectSlugOrId: zod.z.union([zod.z.string(), zod.z.number()]).optional().describe("Project slug or numeric ID"),
24365
+ transactionName: zod.z.string().trim().optional().describe("Transaction name (e.g., '/api/users', 'POST /graphql')"),
24366
+ statsPeriod: zod.z.string().default("7d").describe("Time period: '1h', '24h', '7d', '14d', '30d' (default: '7d')"),
24367
+ compareAgainstPeriod: zod.z.string().optional().describe("Compare against this baseline period (e.g., '14d', '30d'). Enables regression detection."),
24368
+ focusOnUserCode: zod.z.boolean().default(true).describe("Show only user code (is_application: true). Set to false to include library code."),
24369
+ maxHotPaths: zod.z.number().int().min(1).max(20).default(10).describe("Number of hot paths to display (1-20, default: 10)")
24370
+ },
24371
+ annotations: {
24372
+ readOnlyHint: true,
24373
+ openWorldHint: false
24374
+ },
24375
+ async handler(params, context$1) {
24376
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
24377
+ const resolved = resolveProfileParams({
24378
+ profileUrl: params.profileUrl,
24379
+ organizationSlug: params.organizationSlug,
24380
+ projectSlugOrId: params.projectSlugOrId,
24381
+ transactionName: params.transactionName
24382
+ });
24383
+ const { organizationSlug, projectSlugOrId, transactionName } = resolved;
24384
+ if (!projectSlugOrId) throw new UserInputError("Project is required. Please provide a projectSlugOrId parameter or include it in the profile URL.");
24385
+ if (!transactionName) throw new UserInputError("Transaction name is required for flamegraph analysis. Please provide a transactionName parameter.");
24386
+ let projectId;
24387
+ if (typeof projectSlugOrId === "number" || isNumericId(String(projectSlugOrId))) {
24388
+ projectId = projectSlugOrId;
24389
+ (0, __sentry_core.setTag)("project.id", String(projectSlugOrId));
24390
+ } else {
24391
+ const project = await apiService.getProject({
24392
+ organizationSlug,
24393
+ projectSlugOrId: String(projectSlugOrId)
24394
+ });
24395
+ projectId = project.id;
24396
+ (0, __sentry_core.setTag)("project.slug", String(projectSlugOrId));
24397
+ (0, __sentry_core.setTag)("project.id", String(project.id));
24398
+ }
24399
+ (0, __sentry_core.setTag)("organization.slug", organizationSlug);
24400
+ (0, __sentry_core.setTag)("transaction.name", transactionName);
24401
+ if (params.compareAgainstPeriod) {
24402
+ (0, __sentry_core.setTag)("baseline.period", params.compareAgainstPeriod);
24403
+ (0, __sentry_core.setTag)("current.period", params.statsPeriod);
24404
+ const [baselineFlamegraph, currentFlamegraph] = await Promise.all([apiService.getFlamegraph({
24405
+ organizationSlug,
24406
+ projectId,
24407
+ transactionName,
24408
+ statsPeriod: params.compareAgainstPeriod
24409
+ }), apiService.getFlamegraph({
24410
+ organizationSlug,
24411
+ projectId,
24412
+ transactionName,
24413
+ statsPeriod: params.statsPeriod
24414
+ })]);
24415
+ const hasBaselineData = hasProfileData(baselineFlamegraph);
24416
+ const hasCurrentData = hasProfileData(currentFlamegraph);
24417
+ if (!hasBaselineData && !hasCurrentData) return [
24418
+ `# Profile Comparison: ${transactionName}`,
24419
+ "",
24420
+ "## No Profile Data Found",
24421
+ "",
24422
+ `No profiling data found for transaction **${transactionName}** in either time period.`,
24423
+ "",
24424
+ "**Possible reasons:**",
24425
+ "- Transaction name doesn't match exactly (names are case-sensitive)",
24426
+ "- No profiles collected for this transaction",
24427
+ "- Profiling may not be enabled for this project",
24428
+ "",
24429
+ "**Suggestions:**",
24430
+ "- Verify the exact transaction name using search_events",
24431
+ "- Check if profiling is enabled for this project"
24432
+ ].join("\n");
24433
+ if (!hasBaselineData) return [
24434
+ `# Profile Comparison: ${transactionName}`,
24435
+ "",
24436
+ "## Insufficient Baseline Data",
24437
+ "",
24438
+ `No profiling data found for the baseline period (${params.compareAgainstPeriod}).`,
24439
+ `Current period (${params.statsPeriod}) has data.`,
24440
+ "",
24441
+ "**Suggestion:** Try a shorter baseline period or analyze the current period only by removing compareAgainstPeriod."
24442
+ ].join("\n");
24443
+ if (!hasCurrentData) return [
24444
+ `# Profile Comparison: ${transactionName}`,
24445
+ "",
24446
+ "## Insufficient Current Data",
24447
+ "",
24448
+ `No profiling data found for the current period (${params.statsPeriod}).`,
24449
+ `Baseline period (${params.compareAgainstPeriod}) has data.`,
24450
+ "",
24451
+ "**Suggestion:** The transaction may not have been executed recently. Try a longer current period."
24452
+ ].join("\n");
24453
+ return formatFlamegraphComparison(baselineFlamegraph, currentFlamegraph, { focusOnUserCode: params.focusOnUserCode });
24454
+ }
24455
+ const flamegraph = await apiService.getFlamegraph({
24456
+ organizationSlug,
24457
+ projectId,
24458
+ transactionName,
24459
+ statsPeriod: params.statsPeriod
24460
+ });
24461
+ if (!hasProfileData(flamegraph)) return [
24462
+ `# Profile Analysis: ${transactionName}`,
24463
+ "",
24464
+ "## No Profile Data Found",
24465
+ "",
24466
+ `No profiling data found for transaction **${transactionName}** in the last ${params.statsPeriod}.`,
24467
+ "",
24468
+ "**Possible reasons:**",
24469
+ "- Transaction name doesn't match exactly (names are case-sensitive)",
24470
+ "- No profiles collected for this transaction in the time period",
24471
+ "- Profiling may not be enabled for this project",
24472
+ "- Transaction may not have been executed recently",
24473
+ "",
24474
+ "**Suggestions:**",
24475
+ "- Verify the exact transaction name using search_events",
24476
+ "- Try a longer time period (e.g., '30d')",
24477
+ "- Check if profiling is enabled for this project"
24478
+ ].join("\n");
24479
+ return formatFlamegraphAnalysis(flamegraph, {
24480
+ focusOnUserCode: params.focusOnUserCode,
24481
+ maxHotPaths: params.maxHotPaths
24482
+ });
24483
+ }
24484
+ });
24485
+
24486
+ //#endregion
24487
+ //#region ../mcp-core/dist/get-sentry-resource-C5iJbYjO.js
24488
+ /**
24489
+ * Resource types fully supported with API integration.
24490
+ */
24491
+ const FULLY_SUPPORTED_TYPES = [
24492
+ "issue",
24493
+ "event",
24494
+ "trace",
24495
+ "profile"
24496
+ ];
24497
+ /**
24498
+ * Validates and resolves resource parameters from URL or explicit params.
24499
+ */
24500
+ function resolveResourceParams(params) {
24501
+ if (params.url) {
24502
+ const parsed = parseSentryUrl(params.url);
24503
+ return resolveFromParsedUrl(parsed, params);
24504
+ }
24505
+ if (!params.resourceType) throw new UserInputError("Either `url` or `resourceType` must be provided. Use `url` to automatically detect the resource type, or specify `resourceType` explicitly.");
24506
+ if (!FULLY_SUPPORTED_TYPES.includes(params.resourceType)) throw new UserInputError(`Invalid resourceType: ${params.resourceType}. Supported types: ${FULLY_SUPPORTED_TYPES.join(", ")}`);
24507
+ if (!params.organizationSlug) throw new UserInputError("`organizationSlug` is required when using explicit `resourceType`.");
24508
+ const resourceType = params.resourceType;
24509
+ const organizationSlug = params.organizationSlug;
24510
+ switch (resourceType) {
24511
+ case "issue":
24512
+ if (!params.issueId) throw new UserInputError("`issueId` is required for resource type 'issue'.");
24513
+ return {
24514
+ type: "issue",
24515
+ organizationSlug,
24516
+ issueId: params.issueId
24517
+ };
24518
+ case "event":
24519
+ if (!params.issueId || !params.eventId) throw new UserInputError("`issueId` and `eventId` are required for resource type 'event'.");
24520
+ return {
24521
+ type: "event",
24522
+ organizationSlug,
24523
+ issueId: params.issueId,
24524
+ eventId: params.eventId
24525
+ };
24526
+ case "trace":
24527
+ if (!params.traceId) throw new UserInputError("`traceId` is required for resource type 'trace'.");
24528
+ return {
24529
+ type: "trace",
24530
+ organizationSlug,
24531
+ traceId: params.traceId
24532
+ };
24533
+ case "profile":
24534
+ if (!params.projectSlug) throw new UserInputError("`projectSlug` is required for resource type 'profile'.");
24535
+ if (!params.transactionName) throw new UserInputError("`transactionName` is required for resource type 'profile'.");
24536
+ return {
24537
+ type: "profile",
24538
+ organizationSlug,
24539
+ projectSlug: params.projectSlug,
24540
+ profilerId: params.profilerId ?? void 0,
24541
+ transactionName: params.transactionName
24542
+ };
24543
+ }
24544
+ }
24545
+ /**
24546
+ * Resolves params from a parsed Sentry URL.
24547
+ */
24548
+ function resolveFromParsedUrl(parsed, params) {
24549
+ const { type, organizationSlug } = parsed;
24550
+ if (type === "unknown") {
24551
+ if (parsed.transaction) throw new UserInputError(`Detected a performance summary URL for transaction "${parsed.transaction}". Use \`get_profile\` with the transaction name to analyze performance data, or \`search_events\` to find traces for this transaction.`);
24552
+ throw new UserInputError("Could not determine resource type from URL. Supported URL patterns: issues, events, traces, profiles, replays, monitors, and releases.");
24553
+ }
24554
+ switch (type) {
24555
+ case "issue":
24556
+ if (!parsed.issueId) throw new UserInputError("Could not extract issue ID from URL.");
24557
+ return {
24558
+ type: "issue",
24559
+ organizationSlug,
24560
+ issueId: parsed.issueId
24561
+ };
24562
+ case "event":
24563
+ if (!parsed.issueId || !parsed.eventId) throw new UserInputError("Could not extract issue ID and event ID from URL.");
24564
+ return {
24565
+ type: "event",
24566
+ organizationSlug,
24567
+ issueId: parsed.issueId,
24568
+ eventId: parsed.eventId
24569
+ };
24570
+ case "trace":
24571
+ if (!parsed.traceId) throw new UserInputError("Could not extract trace ID from URL.");
24572
+ return {
24573
+ type: "trace",
24574
+ organizationSlug,
24575
+ traceId: parsed.traceId,
24576
+ spanId: parsed.spanId
24577
+ };
24578
+ case "profile": {
24579
+ if (!parsed.projectSlug) throw new UserInputError("Could not extract project slug from profile URL.");
24580
+ const transactionName = params.transactionName ?? void 0;
24581
+ return {
24582
+ type: "profile",
24583
+ organizationSlug,
24584
+ projectSlug: parsed.projectSlug,
24585
+ profilerId: parsed.profilerId,
24586
+ transactionName
24587
+ };
24588
+ }
24589
+ case "replay":
24590
+ if (!parsed.replayId) throw new UserInputError("Could not extract replay ID from URL.");
24591
+ return {
24592
+ type: "replay",
24593
+ organizationSlug,
24594
+ replayId: parsed.replayId
24595
+ };
24596
+ case "monitor":
24597
+ if (!parsed.monitorSlug) throw new UserInputError("Could not extract monitor slug from URL.");
24598
+ return {
24599
+ type: "monitor",
24600
+ organizationSlug,
24601
+ monitorSlug: parsed.monitorSlug,
24602
+ projectSlug: parsed.projectSlug
24603
+ };
24604
+ case "release":
24605
+ if (!parsed.releaseVersion) throw new UserInputError("Could not extract release version from URL.");
24606
+ return {
24607
+ type: "release",
24608
+ organizationSlug,
24609
+ releaseVersion: parsed.releaseVersion
24610
+ };
24611
+ }
24612
+ }
24613
+ /**
24614
+ * Generates a helpful message for recognized but not fully supported resource types.
24615
+ */
24616
+ function generateUnsupportedResourceMessage(resolved) {
24617
+ const { type, organizationSlug } = resolved;
24618
+ switch (type) {
24619
+ case "replay": {
24620
+ const replayUrl = `https://${organizationSlug}.sentry.io/replays/${resolved.replayId}/`;
24621
+ return [
24622
+ "# Replay Detected",
24623
+ "",
24624
+ `**Organization**: ${organizationSlug}`,
24625
+ `**Replay ID**: ${resolved.replayId}`,
24626
+ "",
24627
+ "Session replay support is coming soon. In the meantime:",
24628
+ "",
24629
+ `- **View in Sentry**: [Open Replay](${replayUrl})`,
24630
+ "- **Find related issues**: Use `search_issues` with the replay's time range",
24631
+ `- **Search events**: Use \`search_events\` with query \`replay_id:${resolved.replayId}\` to find events associated with this replay`
24632
+ ].join("\n");
24633
+ }
24634
+ case "monitor": {
24635
+ const monitorPath = resolved.projectSlug ? `${resolved.projectSlug}/${resolved.monitorSlug}` : resolved.monitorSlug;
24636
+ const monitorUrl = `https://${organizationSlug}.sentry.io/crons/${monitorPath}/`;
24637
+ return [
24638
+ "# Cron Monitor Detected",
24639
+ "",
24640
+ `**Organization**: ${organizationSlug}`,
24641
+ `**Monitor**: ${resolved.monitorSlug}`,
24642
+ resolved.projectSlug ? `**Project**: ${resolved.projectSlug}` : "",
24643
+ "",
24644
+ "Cron monitor support is coming soon. In the meantime:",
24645
+ "",
24646
+ `- **View in Sentry**: [Open Monitor](${monitorUrl})`,
24647
+ `- **Search issues**: Use \`search_issues\` with query \`monitor.slug:${resolved.monitorSlug}\` to find issues from this monitor`
24648
+ ].filter(Boolean).join("\n");
24649
+ }
24650
+ case "release": {
24651
+ const releaseUrl = `https://${organizationSlug}.sentry.io/releases/${resolved.releaseVersion}/`;
24652
+ return [
24653
+ "# Release Detected",
24654
+ "",
24655
+ `**Organization**: ${organizationSlug}`,
24656
+ `**Release**: ${resolved.releaseVersion}`,
24657
+ "",
24658
+ "To get release information:",
24659
+ "",
24660
+ `- **View in Sentry**: [Open Release](${releaseUrl})`,
24661
+ `- **Find releases**: Use \`find_releases(organizationSlug='${organizationSlug}')\` to list releases and their details`,
24662
+ `- **Search issues**: Use \`search_issues\` with query \`release:${resolved.releaseVersion}\` to find issues in this release`
24663
+ ].join("\n");
24664
+ }
24665
+ default: return `Unsupported resource type: ${type}`;
24666
+ }
24667
+ }
24668
+ var get_sentry_resource_default = defineTool({
24669
+ name: "get_sentry_resource",
24670
+ skills: ["inspect"],
24671
+ requiredScopes: ["event:read"],
24672
+ experimental: true,
24673
+ description: [
24674
+ "Unified entry point for fetching Sentry resources. Auto-detects resource type from URL or accepts explicit type and identifiers.",
24675
+ "",
24676
+ "USE THIS TOOL WHEN:",
24677
+ "- User provides a Sentry URL (any type: issue, event, trace, profile, replay, monitor, release)",
24678
+ "- User wants to fetch a specific resource by type and ID",
24679
+ "",
24680
+ "FULLY SUPPORTED:",
24681
+ "- **issue**: Fetch issue details by ID",
24682
+ "- **event**: Fetch specific event within an issue",
24683
+ "- **trace**: Fetch trace details (supports span focus from URL)",
24684
+ "- **profile**: Fetch and analyze CPU profiling data",
24685
+ "",
24686
+ "URL RECOGNIZED (returns helpful guidance):",
24687
+ "- **replay**: Session replay URLs",
24688
+ "- **monitor**: Cron monitor URLs",
24689
+ "- **release**: Release URLs",
24690
+ "",
24691
+ "<examples>",
24692
+ "### URL mode (auto-detect type)",
24693
+ "```",
24694
+ "get_sentry_resource(url='https://my-org.sentry.io/issues/PROJECT-123')",
24695
+ "get_sentry_resource(url='https://my-org.sentry.io/explore/traces/trace/abc123...')",
24696
+ "get_sentry_resource(url='https://my-org.sentry.io/replays/def456...')",
24697
+ "```",
24698
+ "",
24699
+ "### Explicit mode - Issue",
24700
+ "```",
24701
+ "get_sentry_resource(",
24702
+ " resourceType='issue',",
24703
+ " organizationSlug='my-org',",
24704
+ " issueId='PROJECT-123'",
24705
+ ")",
24706
+ "```",
24707
+ "",
24708
+ "### Explicit mode - Trace",
24709
+ "```",
24710
+ "get_sentry_resource(",
24711
+ " resourceType='trace',",
24712
+ " organizationSlug='my-org',",
24713
+ " traceId='a4d1aae7216b47ff8117cf4e09ce9d0a'",
24714
+ ")",
24715
+ "```",
24716
+ "</examples>",
24717
+ "",
24718
+ "<hints>",
24719
+ "- URL mode is simplest: just pass the Sentry URL and the tool auto-detects the resource type",
24720
+ "- For explicit mode, required params depend on resourceType:",
24721
+ " - issue: organizationSlug, issueId",
24722
+ " - event: organizationSlug, issueId, eventId",
24723
+ " - trace: organizationSlug, traceId",
24724
+ " - profile: organizationSlug, projectSlug, transactionName",
24725
+ "</hints>"
24726
+ ].join("\n"),
24727
+ inputSchema: {
24728
+ url: zod.z.string().url().optional().describe("Sentry URL. Auto-detects resource type (issue, event, trace, profile, replay, monitor, release) from URL pattern."),
24729
+ resourceType: zod.z.enum([
24730
+ "issue",
24731
+ "event",
24732
+ "trace",
24733
+ "profile"
24734
+ ]).optional().describe("Resource type when not using URL. Required params depend on type."),
24735
+ organizationSlug: ParamOrganizationSlug.optional(),
24736
+ regionUrl: ParamRegionUrl.nullable().default(null),
24737
+ issueId: zod.z.string().toUpperCase().trim().optional().describe("Issue ID (e.g., 'PROJECT-123'). Required for issue/event types."),
24738
+ eventId: zod.z.string().trim().optional().describe("Event ID. Required for event type."),
24739
+ traceId: zod.z.string().trim().optional().describe("Trace ID (32-char hex string). Required for trace type."),
24740
+ projectSlug: zod.z.string().toLowerCase().trim().optional().describe("Project slug. Required for profile type."),
24741
+ profilerId: zod.z.string().trim().optional().describe("Profiler ID (optional for profile type)."),
24742
+ transactionName: zod.z.string().trim().optional().describe("Transaction name (e.g., 'GET /api/users'). Required for profile type.")
24743
+ },
24744
+ annotations: {
24745
+ readOnlyHint: true,
24746
+ openWorldHint: true
24747
+ },
24748
+ async handler(params, context$1) {
24749
+ const resolved = resolveResourceParams({
24750
+ url: params.url,
24751
+ resourceType: params.resourceType,
24752
+ organizationSlug: params.organizationSlug,
24753
+ issueId: params.issueId,
24754
+ eventId: params.eventId,
24755
+ traceId: params.traceId,
24756
+ projectSlug: params.projectSlug,
24757
+ profilerId: params.profilerId,
24758
+ transactionName: params.transactionName
24759
+ });
24760
+ (0, __sentry_core.setTag)("resource.type", resolved.type);
24761
+ (0, __sentry_core.setTag)("organization.slug", resolved.organizationSlug);
24762
+ if (resolved.type === "replay" || resolved.type === "monitor" || resolved.type === "release") return generateUnsupportedResourceMessage(resolved);
24763
+ switch (resolved.type) {
24764
+ case "issue": return get_issue_details_default.handler({
24765
+ organizationSlug: resolved.organizationSlug,
24766
+ issueId: resolved.issueId,
24767
+ regionUrl: params.regionUrl
24768
+ }, context$1);
24769
+ case "event": return get_issue_details_default.handler({
24770
+ organizationSlug: resolved.organizationSlug,
24771
+ issueId: resolved.issueId,
24772
+ eventId: resolved.eventId,
24773
+ regionUrl: params.regionUrl
24774
+ }, context$1);
24775
+ case "trace": return get_trace_details_default.handler({
24776
+ organizationSlug: resolved.organizationSlug,
24777
+ traceId: resolved.traceId,
24778
+ regionUrl: params.regionUrl
24779
+ }, context$1);
24780
+ case "profile": return get_profile_default.handler({
24781
+ organizationSlug: resolved.organizationSlug,
24782
+ projectSlugOrId: resolved.projectSlug,
24783
+ transactionName: resolved.transactionName,
24784
+ regionUrl: params.regionUrl,
24785
+ statsPeriod: "7d",
24786
+ focusOnUserCode: true,
24787
+ maxHotPaths: 10
24788
+ }, context$1);
24789
+ default: {
24790
+ const _exhaustiveCheck = resolved.type;
24791
+ throw new Error(`Unhandled resource type: ${_exhaustiveCheck}`);
24792
+ }
24793
+ }
24794
+ }
24795
+ });
24796
+
24797
+ //#endregion
24798
+ //#region ../mcp-core/dist/error-handling-edUevt-o.js
23299
24799
  /**
23300
24800
  * Type guard to identify user input validation errors.
23301
24801
  */
@@ -23386,7 +24886,7 @@ async function formatErrorForUser(error) {
23386
24886
  }
23387
24887
 
23388
24888
  //#endregion
23389
- //#region ../mcp-core/dist/constraint-helpers-D80X658i.js
24889
+ //#region ../mcp-core/dist/constraint-helpers-8S_8iDNk.js
23390
24890
  /**
23391
24891
  * Determines which tool parameter keys should be filtered out of the schema
23392
24892
  * because they will be injected from constraints.
@@ -23410,7 +24910,7 @@ async function formatErrorForUser(error) {
23410
24910
  */
23411
24911
  function getConstraintKeysToFilter(constraints, toolInputSchema) {
23412
24912
  return Object.entries(constraints).flatMap(([key, value]) => {
23413
- if (!value) return [];
24913
+ if (!value || typeof value !== "string") return [];
23414
24914
  const keys = [];
23415
24915
  if (key in toolInputSchema) keys.push(key);
23416
24916
  if (key === "projectSlug" && "projectSlugOrId" in toolInputSchema && !("projectSlugOrId" in constraints && constraints.projectSlugOrId)) keys.push("projectSlugOrId");
@@ -23439,7 +24939,7 @@ function getConstraintKeysToFilter(constraints, toolInputSchema) {
23439
24939
  */
23440
24940
  function getConstraintParametersToInject(constraints, toolInputSchema) {
23441
24941
  return Object.fromEntries(Object.entries(constraints).flatMap(([key, value]) => {
23442
- if (!value) return [];
24942
+ if (!value || typeof value !== "string") return [];
23443
24943
  const entries = [];
23444
24944
  if (key in toolInputSchema) entries.push([key, value]);
23445
24945
  if (key === "projectSlug" && "projectSlugOrId" in toolInputSchema && !("projectSlugOrId" in constraints && constraints.projectSlugOrId)) entries.push(["projectSlugOrId", value]);
@@ -23448,7 +24948,7 @@ function getConstraintParametersToInject(constraints, toolInputSchema) {
23448
24948
  }
23449
24949
 
23450
24950
  //#endregion
23451
- //#region ../mcp-core/dist/server-CbkVklfg.js
24951
+ //#region ../mcp-core/dist/server-CECYn4UB.js
23452
24952
  /**
23453
24953
  * Format tool calls into a readable trace
23454
24954
  */
@@ -23511,7 +25011,7 @@ var handler_default$3 = defineTool({
23511
25011
  async handler(params, context$1) {
23512
25012
  const [clientTransport, serverTransport] = __modelcontextprotocol_sdk_inMemory_js.InMemoryTransport.createLinkedPair();
23513
25013
  const toolsToExclude = new Set(["use_sentry", ...SIMPLE_REPLACEMENT_TOOLS]);
23514
- const toolsForAgent = Object.fromEntries(Object.entries(tools_default).filter(([key]) => !toolsToExclude.has(key)));
25014
+ const toolsForAgent = Object.fromEntries(Object.entries(tools_default).filter(([key, tool$1]) => !toolsToExclude.has(key) && isToolVisibleInMode(tool$1, context$1.experimentalMode ?? false)));
23515
25015
  const server$1 = buildServer({
23516
25016
  context: context$1,
23517
25017
  tools: toolsForAgent
@@ -23583,7 +25083,9 @@ var tools_default = {
23583
25083
  use_sentry: handler_default$3,
23584
25084
  list_issues: list_issues_default,
23585
25085
  list_events: list_events_default,
23586
- list_issue_events: list_issue_events_default
25086
+ list_issue_events: list_issue_events_default,
25087
+ get_profile: get_profile_default,
25088
+ get_sentry_resource: get_sentry_resource_default
23587
25089
  };
23588
25090
  /**
23589
25091
  * Creates and configures a complete MCP server with Sentry instrumentation.
@@ -23621,7 +25123,7 @@ var tools_default = {
23621
25123
  * return createMcpHandler(server, { route: "/mcp" })(request, env, ctx);
23622
25124
  * ```
23623
25125
  */
23624
- function buildServer({ context: context$1, agentMode = false, tools: customTools }) {
25126
+ function buildServer({ context: context$1, agentMode = false, experimentalMode = false, tools: customTools }) {
23625
25127
  const server$1 = new __modelcontextprotocol_sdk_server_mcp_js.McpServer({
23626
25128
  name: MCP_SERVER_NAME,
23627
25129
  version: require_stdio.LIB_VERSION
@@ -23630,6 +25132,7 @@ function buildServer({ context: context$1, agentMode = false, tools: customTools
23630
25132
  server: server$1,
23631
25133
  context: context$1,
23632
25134
  agentMode,
25135
+ experimentalMode,
23633
25136
  tools: customTools
23634
25137
  });
23635
25138
  return (0, __sentry_core.wrapMcpServerWithSentry)(server$1);
@@ -23643,13 +25146,14 @@ function buildServer({ context: context$1, agentMode = false, tools: customTools
23643
25146
  *
23644
25147
  * In agent mode, only the use_sentry tool is registered, bypassing authorization checks.
23645
25148
  */
23646
- function configureServer({ server: server$1, context: context$1, agentMode = false, tools: customTools }) {
25149
+ function configureServer({ server: server$1, context: context$1, agentMode = false, experimentalMode = false, tools: customTools }) {
23647
25150
  let toolsToRegister = agentMode ? { use_sentry: tools_default.use_sentry } : customTools ?? tools_default;
23648
25151
  if (!agentMode && !customTools) {
23649
25152
  const hasAgent = hasAgentProvider();
23650
25153
  const toolsToExclude = new Set(hasAgent ? SIMPLE_REPLACEMENT_TOOLS : AGENT_DEPENDENT_TOOLS);
23651
25154
  toolsToRegister = Object.fromEntries(Object.entries(toolsToRegister).filter(([key]) => !toolsToExclude.has(key)));
23652
25155
  }
25156
+ if (!agentMode) toolsToRegister = Object.fromEntries(Object.entries(toolsToRegister).filter(([, tool$1]) => isToolVisibleInMode(tool$1, experimentalMode)));
23653
25157
  const grantedSkills = context$1.grantedSkills ? new Set(context$1.grantedSkills) : void 0;
23654
25158
  server$1.server.onerror = (error) => {
23655
25159
  const transportLogOptions = {
@@ -23688,9 +25192,15 @@ function configureServer({ server: server$1, context: context$1, agentMode = fal
23688
25192
  }
23689
25193
  if (!allowed) continue;
23690
25194
  if (toolKey === "find_organizations" && context$1.constraints.organizationSlug || toolKey === "find_projects" && context$1.constraints.projectSlug) continue;
25195
+ if (experimentalMode && context$1.constraints.projectSlug && context$1.constraints.projectCapabilities && tool$1.requiredCapabilities?.length) {
25196
+ const caps = context$1.constraints.projectCapabilities;
25197
+ const hasAllCapabilities = tool$1.requiredCapabilities.every((cap) => caps[cap] === true);
25198
+ if (!hasAllCapabilities) continue;
25199
+ }
23691
25200
  const constraintKeysToFilter = new Set(getConstraintKeysToFilter(context$1.constraints, tool$1.inputSchema));
23692
25201
  const filteredInputSchema = Object.fromEntries(Object.entries(tool$1.inputSchema).filter(([key]) => !constraintKeysToFilter.has(key)));
23693
- server$1.tool(tool$1.name, tool$1.description, filteredInputSchema, tool$1.annotations, async (params, extra) => {
25202
+ const resolvedDescription = resolveDescription(tool$1.description, { experimentalMode });
25203
+ server$1.tool(tool$1.name, resolvedDescription, filteredInputSchema, tool$1.annotations, async (params, extra) => {
23694
25204
  const activeSpan = (0, __sentry_core.getActiveSpan)();
23695
25205
  if (activeSpan) {
23696
25206
  if (context$1.constraints.organizationSlug) activeSpan.setAttribute("sentry-mcp.constraint-organization", context$1.constraints.organizationSlug);
@@ -23730,7 +25240,7 @@ function configureServer({ server: server$1, context: context$1, agentMode = fal
23730
25240
  }
23731
25241
 
23732
25242
  //#endregion
23733
- //#region ../mcp-core/dist/sentry-CTKJG5Bs.js
25243
+ //#region ../mcp-core/dist/sentry-BuGpDJQH.js
23734
25244
  const SCRUB_PATTERNS = [
23735
25245
  {
23736
25246
  pattern: /\bsk-[a-zA-Z0-9]{48}\b/g,
@@ -23873,14 +25383,71 @@ setProviderBaseUrls({
23873
25383
  });
23874
25384
  if (cfg.openaiModel) process.env.OPENAI_MODEL = cfg.openaiModel;
23875
25385
  if (cfg.anthropicModel) process.env.ANTHROPIC_MODEL = cfg.anthropicModel;
25386
+ function hasProviderConflict() {
25387
+ const hasAnthropic = Boolean(process.env.ANTHROPIC_API_KEY);
25388
+ const hasOpenAI = Boolean(process.env.OPENAI_API_KEY);
25389
+ const hasExplicitProvider = cfg.agentProvider || process.env.EMBEDDED_AGENT_PROVIDER;
25390
+ return hasAnthropic && hasOpenAI && !hasExplicitProvider;
25391
+ }
25392
+ function getConfiguredProvider() {
25393
+ return cfg.agentProvider || process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
25394
+ }
25395
+ function hasProviderMismatch() {
25396
+ const configured = getConfiguredProvider();
25397
+ if (!configured) return { mismatch: false };
25398
+ const hasAnthropic = Boolean(process.env.ANTHROPIC_API_KEY);
25399
+ const hasOpenAI = Boolean(process.env.OPENAI_API_KEY);
25400
+ if (configured === "openai" && !hasOpenAI && hasAnthropic) return {
25401
+ mismatch: true,
25402
+ configured: "openai",
25403
+ availableKey: "ANTHROPIC_API_KEY"
25404
+ };
25405
+ if (configured === "anthropic" && !hasAnthropic && hasOpenAI) return {
25406
+ mismatch: true,
25407
+ configured: "anthropic",
25408
+ availableKey: "OPENAI_API_KEY"
25409
+ };
25410
+ return { mismatch: false };
25411
+ }
25412
+ function getProviderSource() {
25413
+ if (cli.agentProvider) return "explicitly configured";
25414
+ if (process.env.EMBEDDED_AGENT_PROVIDER) return "from EMBEDDED_AGENT_PROVIDER";
25415
+ return "auto-detected";
25416
+ }
23876
25417
  const resolvedProvider = getResolvedProviderType();
23877
25418
  if (!resolvedProvider) {
23878
- console.warn("Warning: No LLM API key found (OPENAI_API_KEY or ANTHROPIC_API_KEY).");
23879
- console.warn("The following AI-powered search tools will be unavailable:");
23880
- console.warn(" - search_events, search_issues, search_issue_events, use_sentry");
23881
- console.warn("Use list_issues and list_events for direct Sentry query syntax instead.");
25419
+ const mismatchInfo = hasProviderMismatch();
25420
+ if (hasProviderConflict()) {
25421
+ console.warn("Warning: Both ANTHROPIC_API_KEY and OPENAI_API_KEY are set, but no provider is explicitly configured.");
25422
+ console.warn("Please set EMBEDDED_AGENT_PROVIDER='openai' or 'anthropic' to specify which provider to use.");
25423
+ console.warn("AI-powered search tools will be unavailable until a provider is selected.");
25424
+ } else if (mismatchInfo.mismatch) {
25425
+ const expectedKey = mismatchInfo.configured === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
25426
+ const configuredViaCliFlag = Boolean(cli.agentProvider);
25427
+ const providerSetting = configuredViaCliFlag ? `--agent-provider=${mismatchInfo.configured}` : `EMBEDDED_AGENT_PROVIDER='${mismatchInfo.configured}'`;
25428
+ const changeProviderHint = configuredViaCliFlag ? "Change --agent-provider to match your available API key" : "Change EMBEDDED_AGENT_PROVIDER to match your available API key";
25429
+ console.warn(`Warning: ${providerSetting} but ${expectedKey} is not set.`);
25430
+ console.warn(`Found ${mismatchInfo.availableKey} instead. Either:`);
25431
+ console.warn(` - Set ${expectedKey} to use the ${mismatchInfo.configured} provider, or`);
25432
+ console.warn(` - ${changeProviderHint}`);
25433
+ console.warn("AI-powered search tools will be unavailable until this is resolved.");
25434
+ } else {
25435
+ console.warn("Warning: No LLM API key found (OPENAI_API_KEY or ANTHROPIC_API_KEY).");
25436
+ console.warn("The following AI-powered search tools will be unavailable:");
25437
+ console.warn(" - search_events, search_issues, search_issue_events, use_sentry");
25438
+ console.warn("Use list_issues and list_events for direct Sentry query syntax instead.");
25439
+ }
25440
+ console.warn("");
25441
+ } else {
25442
+ const providerSource = getProviderSource();
25443
+ console.warn(`Using ${resolvedProvider} for AI-powered search tools (${providerSource}).`);
25444
+ if (providerSource === "auto-detected") {
25445
+ console.warn("Deprecation warning: Auto-detection of LLM provider is deprecated.");
25446
+ console.warn(`Please set EMBEDDED_AGENT_PROVIDER='${resolvedProvider}' explicitly.`);
25447
+ console.warn("Auto-detection will be removed in a future release.");
25448
+ }
23882
25449
  console.warn("");
23883
- } else console.warn(`Using ${resolvedProvider} for AI-powered search tools.`);
25450
+ }
23884
25451
  __sentry_node.init({
23885
25452
  dsn: cfg.sentryDsn,
23886
25453
  sendDefaultPii: true,
@@ -23890,6 +25457,7 @@ __sentry_node.init({
23890
25457
  "mcp.server_version": require_stdio.LIB_VERSION,
23891
25458
  "mcp.transport": "stdio",
23892
25459
  "mcp.agent_mode": cli.agent ? "true" : "false",
25460
+ "mcp.experimental_mode": cli.experimental ? "true" : "false",
23893
25461
  "sentry.host": cfg.sentryHost,
23894
25462
  "mcp.mcp-url": cfg.mcpUrl
23895
25463
  } },
@@ -23909,6 +25477,10 @@ if (cli.agent) {
23909
25477
  console.warn("The use_sentry tool provides access to all Sentry operations through natural language.");
23910
25478
  console.warn("");
23911
25479
  }
25480
+ if (cli.experimental) {
25481
+ console.warn("Experimental mode enabled: Experimental tools are available.");
25482
+ console.warn("");
25483
+ }
23912
25484
  const SENTRY_TIMEOUT = 5e3;
23913
25485
  async function shutdown(signal) {
23914
25486
  console.error(`${signal} received, shutting down...`);
@@ -23938,11 +25510,14 @@ const context = {
23938
25510
  },
23939
25511
  sentryHost: cfg.sentryHost,
23940
25512
  mcpUrl: cfg.mcpUrl,
23941
- openaiBaseUrl: cfg.openaiBaseUrl
25513
+ openaiBaseUrl: cfg.openaiBaseUrl,
25514
+ agentMode: cli.agent,
25515
+ experimentalMode: cli.experimental
23942
25516
  };
23943
25517
  const server = buildServer({
23944
25518
  context,
23945
- agentMode: cli.agent
25519
+ agentMode: cli.agent,
25520
+ experimentalMode: cli.experimental
23946
25521
  });
23947
25522
  require_stdio.startStdio(server, context).catch(async (err) => {
23948
25523
  console.error("Server error:", err);