@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.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { ALL_SKILLS, SKILLS, finalize, getIssueUrl, getIssuesSearchUrl, getTraceUrl, isEnabledBySkills, isSentryHost } from "./resolve-DpUhCbfh.js";
3
- import { LIB_VERSION, USER_AGENT, startStdio } from "./stdio-By-q6V_4.js";
3
+ import { LIB_VERSION, USER_AGENT, startStdio } from "./stdio-BG3LYhUm.js";
4
4
  import { RECOMMENDED_FIELDS, systemPrompt } from "./config-CEjP2CYO-DNCUeo0R.js";
5
- import { buildUsage } from "./usage-DR57Krum.js";
6
- import { merge, parseArgv, parseEnv } from "./parse-B9o4fVyT.js";
5
+ import { buildUsage } from "./usage-Bw3IN4iE.js";
6
+ import { merge, parseArgv, parseEnv } from "./parse-CEJNfXug.js";
7
7
  import { z } from "zod";
8
8
  import util from "node:util";
9
9
  import { captureException, captureMessage, getActiveSpan, logger, setTag, setUser, withScope, wrapMcpServerWithSentry } from "@sentry/core";
@@ -1783,7 +1783,7 @@ function logIssue(error, contextsOrOptions, attachmentsArg) {
1783
1783
  }
1784
1784
 
1785
1785
  //#endregion
1786
- //#region ../mcp-core/dist/schema-VoUcElu5.js
1786
+ //#region ../mcp-core/dist/schema-Db6vIKRE.js
1787
1787
  /**
1788
1788
  * Schema for Sentry API error responses.
1789
1789
  *
@@ -1827,7 +1827,11 @@ const ProjectSchema = z.object({
1827
1827
  id: z.union([z.string(), z.number()]),
1828
1828
  slug: z.string(),
1829
1829
  name: z.string(),
1830
- platform: z.string().nullable().optional()
1830
+ platform: z.string().nullable().optional(),
1831
+ hasProfiles: z.boolean().optional(),
1832
+ hasReplays: z.boolean().optional(),
1833
+ hasLogs: z.boolean().optional(),
1834
+ firstTransactionEvent: z.boolean().optional()
1831
1835
  }).passthrough();
1832
1836
  const ProjectListSchema = z.array(ProjectSchema);
1833
1837
  const ClientKeySchema = z.object({
@@ -1908,7 +1912,8 @@ const IssueSchema = z.object({
1908
1912
  title: z.string().nullable().optional(),
1909
1913
  location: z.string().nullable().optional(),
1910
1914
  value: z.string().nullable().optional()
1911
- }).optional()
1915
+ }).optional(),
1916
+ seerFixabilityScore: z.number().nullable().optional()
1912
1917
  }).passthrough();
1913
1918
  const IssueListSchema = z.array(IssueSchema);
1914
1919
  const FrameInterface = z.object({
@@ -2303,6 +2308,150 @@ const TraceIssueSchema = z.object({
2303
2308
  * objects when there are errors not directly associated with spans.
2304
2309
  */
2305
2310
  const TraceSchema = z.array(z.union([TraceSpanSchema, TraceIssueSchema]));
2311
+ /**
2312
+ * Schema for individual frames in a flamegraph.
2313
+ *
2314
+ * Represents a single stack frame with file/function information and
2315
+ * whether it's application code or library code.
2316
+ */
2317
+ const FlamegraphFrameSchema = z.object({
2318
+ file: z.string(),
2319
+ image: z.string().optional(),
2320
+ is_application: z.boolean(),
2321
+ line: z.number(),
2322
+ name: z.string(),
2323
+ path: z.string().optional(),
2324
+ fingerprint: z.number()
2325
+ }).passthrough();
2326
+ /**
2327
+ * Schema for aggregated performance statistics for a single frame.
2328
+ *
2329
+ * Contains sample counts, total weight/duration, and performance percentiles
2330
+ * (p75, p95, p99) for the frame across all samples.
2331
+ */
2332
+ const FlamegraphFrameInfoSchema = z.object({
2333
+ count: z.number(),
2334
+ weight: z.number(),
2335
+ sumDuration: z.number(),
2336
+ sumSelfTime: z.number(),
2337
+ p75Duration: z.number(),
2338
+ p95Duration: z.number(),
2339
+ p99Duration: z.number()
2340
+ }).passthrough();
2341
+ /**
2342
+ * Schema for profile metadata within a flamegraph response.
2343
+ *
2344
+ * Links to individual profile IDs and their time ranges.
2345
+ */
2346
+ const FlamegraphProfileMetadataSchema = z.object({
2347
+ project_id: z.number(),
2348
+ profile_id: z.string(),
2349
+ start: z.number(),
2350
+ end: z.number()
2351
+ }).passthrough();
2352
+ /**
2353
+ * Schema for a single profile within a flamegraph (typically one per thread).
2354
+ *
2355
+ * Contains arrays of samples (call stack patterns), their occurrence counts,
2356
+ * durations, and relative weights.
2357
+ */
2358
+ const FlamegraphProfileSchema = z.object({
2359
+ endValue: z.number(),
2360
+ isMainThread: z.boolean(),
2361
+ name: z.string(),
2362
+ samples: z.array(z.array(z.number())),
2363
+ startValue: z.number(),
2364
+ threadID: z.number(),
2365
+ type: z.string(),
2366
+ unit: z.string(),
2367
+ weights: z.array(z.number()),
2368
+ sample_durations_ns: z.array(z.number()),
2369
+ sample_counts: z.array(z.number())
2370
+ }).passthrough();
2371
+ /**
2372
+ * Schema for flamegraph API response.
2373
+ *
2374
+ * Flamegraphs provide pre-aggregated CPU profiling data with:
2375
+ * - Unique call stack patterns (samples)
2376
+ * - Performance statistics (counts, durations, percentiles)
2377
+ * - Frame metadata (file, function, is_application)
2378
+ *
2379
+ * This is the primary data source for profile analysis as it's
2380
+ * already aggregated and includes percentile calculations.
2381
+ */
2382
+ const FlamegraphSchema = z.object({
2383
+ activeProfileIndex: z.number(),
2384
+ metadata: z.record(z.unknown()).optional(),
2385
+ platform: z.string(),
2386
+ profiles: z.array(FlamegraphProfileSchema),
2387
+ projectID: z.number(),
2388
+ shared: z.object({
2389
+ frames: z.array(FlamegraphFrameSchema),
2390
+ frame_infos: z.array(FlamegraphFrameInfoSchema),
2391
+ profiles: z.array(FlamegraphProfileMetadataSchema)
2392
+ }),
2393
+ transactionName: z.string().optional(),
2394
+ metrics: z.unknown().optional()
2395
+ }).passthrough();
2396
+ /**
2397
+ * Schema for individual frames in raw profile chunk data.
2398
+ *
2399
+ * Similar to FlamegraphFrameSchema but uses different field names
2400
+ * (function instead of name, in_app instead of is_application).
2401
+ * Many fields are optional as the API may not include them for all frames.
2402
+ */
2403
+ const ProfileFrameSchema = z.object({
2404
+ filename: z.string().nullable().optional(),
2405
+ function: z.string(),
2406
+ in_app: z.boolean(),
2407
+ lineno: z.number().nullable().optional(),
2408
+ module: z.string().nullable().optional(),
2409
+ abs_path: z.string().nullable().optional(),
2410
+ platform: z.string().nullable().optional(),
2411
+ data: z.record(z.unknown()).optional()
2412
+ }).passthrough();
2413
+ /**
2414
+ * Schema for individual samples in raw profile chunk data.
2415
+ *
2416
+ * Each sample represents a point-in-time snapshot of the call stack,
2417
+ * with a reference to the stack_id and thread_id.
2418
+ */
2419
+ const ProfileSampleSchema = z.object({
2420
+ stack_id: z.number(),
2421
+ thread_id: z.string(),
2422
+ timestamp: z.number()
2423
+ }).passthrough();
2424
+ /**
2425
+ * Schema for raw profile chunk data.
2426
+ *
2427
+ * Contains the raw sampling data including:
2428
+ * - frames: All unique stack frames
2429
+ * - samples: Individual sample points with timestamps
2430
+ * - stacks: Arrays of frame indices forming call stacks
2431
+ * - thread_metadata: Information about profiled threads
2432
+ *
2433
+ * This is used for deep-dive analysis when flamegraph data isn't sufficient.
2434
+ */
2435
+ const ProfileChunkSchema = z.object({
2436
+ chunk_id: z.string(),
2437
+ profiler_id: z.string(),
2438
+ environment: z.string().nullable(),
2439
+ platform: z.string(),
2440
+ release: z.string(),
2441
+ version: z.string(),
2442
+ profile: z.object({
2443
+ frames: z.array(ProfileFrameSchema),
2444
+ samples: z.array(ProfileSampleSchema),
2445
+ stacks: z.array(z.array(z.number())),
2446
+ thread_metadata: z.record(z.object({ name: z.string().nullable() }).passthrough())
2447
+ })
2448
+ }).passthrough();
2449
+ /**
2450
+ * Schema for profile chunks API response wrapper.
2451
+ *
2452
+ * The API returns chunks in an array wrapper, even for single chunk requests.
2453
+ */
2454
+ const ProfileChunkResponseSchema = z.object({ chunks: z.array(ProfileChunkSchema) }).passthrough();
2306
2455
 
2307
2456
  //#endregion
2308
2457
  //#region ../mcp-core/dist/errors-ZBQnDL3L.js
@@ -2520,7 +2669,7 @@ function createApiError(message, status, detail, responseBody) {
2520
2669
  }
2521
2670
 
2522
2671
  //#endregion
2523
- //#region ../mcp-core/dist/client-B2nQcl5S.js
2672
+ //#region ../mcp-core/dist/client-Cpo5HP9Z.js
2524
2673
  /**
2525
2674
  * Mapping of common network error codes to user-friendly messages.
2526
2675
  * These help users understand and resolve connection issues.
@@ -3652,6 +3801,93 @@ var SentryApiService = class {
3652
3801
  const body = await this.requestJSON(`/organizations/${organizationSlug}/trace/${traceId}/?${queryParams.toString()}`, void 0, opts);
3653
3802
  return TraceSchema.parse(body);
3654
3803
  }
3804
+ /**
3805
+ * Retrieves flamegraph data for a transaction.
3806
+ *
3807
+ * Flamegraphs provide pre-aggregated CPU profiling data including:
3808
+ * - Unique call stack patterns (samples)
3809
+ * - Performance statistics (counts, durations, percentiles)
3810
+ * - Frame metadata (file, function, is_application)
3811
+ *
3812
+ * This is the primary data source for profile analysis as it includes
3813
+ * aggregated hot paths and percentile calculations (p75, p95, p99).
3814
+ *
3815
+ * @param params Query parameters
3816
+ * @param params.organizationSlug Organization identifier
3817
+ * @param params.projectId Project ID or slug
3818
+ * @param params.transactionName Transaction name to analyze (e.g., "/api/users")
3819
+ * @param params.statsPeriod Time period for analysis (e.g., "7d", "14d", "30d")
3820
+ * @param opts Request options
3821
+ * @returns Flamegraph with pre-aggregated profiling data
3822
+ *
3823
+ * @example
3824
+ * ```typescript
3825
+ * const flamegraph = await apiService.getFlamegraph({
3826
+ * organizationSlug: "my-org",
3827
+ * projectId: 1,
3828
+ * transactionName: "/api/users",
3829
+ * statsPeriod: "7d"
3830
+ * });
3831
+ * console.log(`Analyzed ${flamegraph.profiles.length} profiles`);
3832
+ * ```
3833
+ */
3834
+ async getFlamegraph({ organizationSlug, projectId, transactionName, statsPeriod = "7d" }, opts) {
3835
+ const queryParams = new URLSearchParams();
3836
+ queryParams.set("project", projectId.toString());
3837
+ const escapedTransaction = transactionName.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
3838
+ queryParams.set("query", `event.type:transaction transaction:"${escapedTransaction}"`);
3839
+ queryParams.set("statsPeriod", statsPeriod);
3840
+ const path = `/organizations/${organizationSlug}/profiling/flamegraph/?${queryParams.toString()}`;
3841
+ const body = await this.requestJSON(path, void 0, opts);
3842
+ return FlamegraphSchema.parse(body);
3843
+ }
3844
+ /**
3845
+ * Retrieves raw profile chunk data for detailed analysis.
3846
+ *
3847
+ * Profile chunks contain:
3848
+ * - frames: All unique stack frames
3849
+ * - samples: Individual sample points with timestamps
3850
+ * - stacks: Arrays of frame indices forming call stacks
3851
+ * - thread_metadata: Information about profiled threads
3852
+ *
3853
+ * This is used for deep-dive analysis when flamegraph data isn't sufficient.
3854
+ * Most use cases should use getFlamegraph() instead, as it provides
3855
+ * pre-aggregated data that's easier to work with.
3856
+ *
3857
+ * @param params Query parameters
3858
+ * @param params.organizationSlug Organization identifier
3859
+ * @param params.profilerId Profiler ID from flamegraph output
3860
+ * @param params.projectId Project ID or slug
3861
+ * @param params.start Start time (ISO format)
3862
+ * @param params.end End time (ISO format)
3863
+ * @param opts Request options
3864
+ * @returns Raw profile chunk data
3865
+ * @throws ApiNotFoundError if no profile chunk is found
3866
+ *
3867
+ * @example
3868
+ * ```typescript
3869
+ * const chunk = await apiService.getProfileChunk({
3870
+ * organizationSlug: "my-org",
3871
+ * profilerId: "041bde57b9844e36b8b7e5734efae5f7",
3872
+ * projectId: 1,
3873
+ * start: "2024-01-01T00:00:00Z",
3874
+ * end: "2024-01-01T01:00:00Z"
3875
+ * });
3876
+ * console.log(`Chunk has ${chunk.profile.samples.length} samples`);
3877
+ * ```
3878
+ */
3879
+ async getProfileChunk({ organizationSlug, profilerId, projectId, start, end }, opts) {
3880
+ const queryParams = new URLSearchParams();
3881
+ queryParams.set("profiler_id", profilerId);
3882
+ queryParams.set("project", projectId.toString());
3883
+ queryParams.set("start", start);
3884
+ queryParams.set("end", end);
3885
+ const path = `/organizations/${organizationSlug}/profiling/chunks/?${queryParams.toString()}`;
3886
+ const body = await this.requestJSON(path, void 0, opts);
3887
+ const response = ProfileChunkResponseSchema.parse(body);
3888
+ if (!response.chunks || response.chunks.length === 0) throw new ApiNotFoundError(`No profile chunk found for profiler_id ${profilerId}`, void 0, body);
3889
+ return response.chunks[0];
3890
+ }
3655
3891
  };
3656
3892
 
3657
3893
  //#endregion
@@ -3687,7 +3923,7 @@ function validateRegionUrl(regionUrl, baseHost) {
3687
3923
  }
3688
3924
 
3689
3925
  //#endregion
3690
- //#region ../mcp-core/dist/api-DVbaHIM5.js
3926
+ //#region ../mcp-core/dist/api-e7vVEVb7.js
3691
3927
  /**
3692
3928
  * Create a Sentry API service from server context with optional region override
3693
3929
  * @param context - Server context containing host and access token
@@ -3708,7 +3944,7 @@ function apiServiceFromContext(context$1, opts = {}) {
3708
3944
  }
3709
3945
 
3710
3946
  //#endregion
3711
- //#region ../mcp-core/dist/whoami-CEHtgXJv.js
3947
+ //#region ../mcp-core/dist/whoami-CjTUNFbc.js
3712
3948
  var whoami_default = defineTool({
3713
3949
  name: "whoami",
3714
3950
  description: [
@@ -3741,7 +3977,7 @@ var whoami_default = defineTool({
3741
3977
  });
3742
3978
 
3743
3979
  //#endregion
3744
- //#region ../mcp-core/dist/find-organizations-Bs2wsqQ7.js
3980
+ //#region ../mcp-core/dist/find-organizations-C2lSjcCf.js
3745
3981
  const RESULT_LIMIT$2 = 25;
3746
3982
  var find_organizations_default = defineTool({
3747
3983
  name: "find_organizations",
@@ -3793,7 +4029,7 @@ var find_organizations_default = defineTool({
3793
4029
  });
3794
4030
 
3795
4031
  //#endregion
3796
- //#region ../mcp-core/dist/find-teams-CgsSmQ8X.js
4032
+ //#region ../mcp-core/dist/find-teams-gmGseaeL.js
3797
4033
  const RESULT_LIMIT$1 = 25;
3798
4034
  var find_teams_default = defineTool({
3799
4035
  name: "find_teams",
@@ -3841,7 +4077,7 @@ var find_teams_default = defineTool({
3841
4077
  });
3842
4078
 
3843
4079
  //#endregion
3844
- //#region ../mcp-core/dist/find-projects-Cxw1nnPQ.js
4080
+ //#region ../mcp-core/dist/find-projects-Cl9eTqeO.js
3845
4081
  const RESULT_LIMIT = 25;
3846
4082
  var find_projects_default = defineTool({
3847
4083
  name: "find_projects",
@@ -3885,7 +4121,7 @@ var find_projects_default = defineTool({
3885
4121
  });
3886
4122
 
3887
4123
  //#endregion
3888
- //#region ../mcp-core/dist/find-releases-zWgFsagR.js
4124
+ //#region ../mcp-core/dist/find-releases-BCe2NuH3.js
3889
4125
  var find_releases_default = defineTool({
3890
4126
  name: "find_releases",
3891
4127
  skills: ["inspect"],
@@ -4133,7 +4369,18 @@ function getOutputForAutofixStep(step) {
4133
4369
  }
4134
4370
 
4135
4371
  //#endregion
4136
- //#region ../mcp-core/dist/formatting-BhgNMv3a.js
4372
+ //#region ../mcp-core/dist/formatting-AtkcRYxR.js
4373
+ /**
4374
+ * Convert Seer fixability score to actionability label.
4375
+ * Thresholds match Sentry core: src/sentry/seer/autofix/constants.py
4376
+ */
4377
+ function getSeerActionabilityLabel(score) {
4378
+ if (score > .76) return "super_high";
4379
+ if (score > .66) return "high";
4380
+ if (score > .4) return "medium";
4381
+ if (score > .25) return "low";
4382
+ return "super_low";
4383
+ }
4137
4384
  const LANGUAGE_EXTENSIONS = {
4138
4385
  ".java": "java",
4139
4386
  ".py": "python",
@@ -5059,6 +5306,7 @@ function formatIssueOutput({ organizationSlug, issue, event, apiService, autofix
5059
5306
  }
5060
5307
  if (issue.issueType) output += `**Issue Type**: ${issue.issueType}\n`;
5061
5308
  if (issue.issueCategory) output += `**Issue Category**: ${issue.issueCategory}\n`;
5309
+ if (issue.seerFixabilityScore != null) output += `**Seer Actionability**: ${getSeerActionabilityLabel(issue.seerFixabilityScore)}\n`;
5062
5310
  output += `**Platform**: ${issue.platform}\n`;
5063
5311
  output += `**Project**: ${issue.project.name}\n`;
5064
5312
  output += `**URL**: ${apiService.getIssueUrl(organizationSlug, issue.shortId)}\n`;
@@ -5130,7 +5378,7 @@ function enhanceNotFoundError(error, params) {
5130
5378
  }
5131
5379
 
5132
5380
  //#endregion
5133
- //#region ../mcp-core/dist/get-issue-details-CsNkINzN.js
5381
+ //#region ../mcp-core/dist/get-issue-details-FSTw8nkJ.js
5134
5382
  var get_issue_details_default = defineTool({
5135
5383
  name: "get_issue_details",
5136
5384
  skills: [
@@ -5139,6 +5387,7 @@ var get_issue_details_default = defineTool({
5139
5387
  "seer"
5140
5388
  ],
5141
5389
  requiredScopes: ["event:read"],
5390
+ hideInExperimentalMode: true,
5142
5391
  description: [
5143
5392
  "Get detailed information about a specific Sentry issue by ID.",
5144
5393
  "",
@@ -5311,7 +5560,7 @@ function shouldFetchTraceForEvent(event) {
5311
5560
  }
5312
5561
 
5313
5562
  //#endregion
5314
- //#region ../mcp-core/dist/get-issue-tag-values-B4lzlivL.js
5563
+ //#region ../mcp-core/dist/get-issue-tag-values-BJe1EySg.js
5315
5564
  var get_issue_tag_values_default = defineTool({
5316
5565
  name: "get_issue_tag_values",
5317
5566
  skills: ["inspect"],
@@ -5426,7 +5675,7 @@ var get_issue_tag_values_default = defineTool({
5426
5675
  });
5427
5676
 
5428
5677
  //#endregion
5429
- //#region ../mcp-core/dist/get-trace-details-DAPondqS.js
5678
+ //#region ../mcp-core/dist/get-trace-details-Cd0Bw2-L.js
5430
5679
  const MAX_DEPTH = 2;
5431
5680
  const MINIMUM_DURATION_THRESHOLD_MS = 10;
5432
5681
  const MIN_MEANINGFUL_CHILD_DURATION = 5;
@@ -5435,6 +5684,8 @@ var get_trace_details_default = defineTool({
5435
5684
  name: "get_trace_details",
5436
5685
  skills: ["inspect"],
5437
5686
  requiredScopes: ["event:read"],
5687
+ requiredCapabilities: ["traces"],
5688
+ hideInExperimentalMode: true,
5438
5689
  description: [
5439
5690
  "Get detailed information about a specific Sentry trace by ID.",
5440
5691
  "",
@@ -5725,7 +5976,7 @@ function formatTraceOutput({ organizationSlug, traceId, traceMeta, trace: trace$
5725
5976
  }
5726
5977
 
5727
5978
  //#endregion
5728
- //#region ../mcp-core/dist/get-event-attachment-C-huGpTH.js
5979
+ //#region ../mcp-core/dist/get-event-attachment-ef7VExVM.js
5729
5980
  var get_event_attachment_default = defineTool({
5730
5981
  name: "get_event_attachment",
5731
5982
  skills: ["inspect"],
@@ -5873,7 +6124,7 @@ function formatAssignedTo(assignedTo) {
5873
6124
  }
5874
6125
 
5875
6126
  //#endregion
5876
- //#region ../mcp-core/dist/update-issue-BArI_SjL.js
6127
+ //#region ../mcp-core/dist/update-issue-bzyciFSm.js
5877
6128
  var update_issue_default = defineTool({
5878
6129
  name: "update_issue",
5879
6130
  skills: ["triage"],
@@ -9164,7 +9415,7 @@ function createOpenAI(options = {}) {
9164
9415
  var openai = createOpenAI({ compatibility: "strict" });
9165
9416
 
9166
9417
  //#endregion
9167
- //#region ../mcp-core/dist/openai-provider-Cc13TpEA.js
9418
+ //#region ../mcp-core/dist/openai-provider-BIi3UaOY.js
9168
9419
  const DEFAULT_OPENAI_MODEL = "gpt-5";
9169
9420
  let configuredBaseUrl$1;
9170
9421
  /**
@@ -10303,7 +10554,7 @@ function createAnthropic(options = {}) {
10303
10554
  var anthropic = createAnthropic();
10304
10555
 
10305
10556
  //#endregion
10306
- //#region ../mcp-core/dist/anthropic-provider-DOE-j9k3.js
10557
+ //#region ../mcp-core/dist/anthropic-provider-B1kgWCoH.js
10307
10558
  const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-5";
10308
10559
  let configuredBaseUrl;
10309
10560
  /**
@@ -10331,7 +10582,7 @@ function getAnthropicModel(model) {
10331
10582
  }
10332
10583
 
10333
10584
  //#endregion
10334
- //#region ../mcp-core/dist/provider-factory-BPN0JlR3.js
10585
+ //#region ../mcp-core/dist/provider-factory-BksPJetW.js
10335
10586
  let configuredProvider;
10336
10587
  /**
10337
10588
  * Configure the embedded agent provider explicitly.
@@ -10348,6 +10599,12 @@ function setProviderBaseUrls(config) {
10348
10599
  if (config.anthropicBaseUrl) setAnthropicBaseUrl(config.anthropicBaseUrl);
10349
10600
  }
10350
10601
  /**
10602
+ * Check if both API keys are present, indicating a conflict.
10603
+ */
10604
+ function detectProviderConflict() {
10605
+ return Boolean(process.env.ANTHROPIC_API_KEY) && Boolean(process.env.OPENAI_API_KEY);
10606
+ }
10607
+ /**
10351
10608
  * Check if the API key exists for a given provider type.
10352
10609
  */
10353
10610
  function hasApiKeyForProvider(type) {
@@ -10388,25 +10645,32 @@ function buildProvider(type) {
10388
10645
  }
10389
10646
  }
10390
10647
  /**
10648
+ * Resolve provider type from configuration and environment.
10649
+ * Returns undefined if no provider can be resolved or if there's a conflict.
10650
+ */
10651
+ function resolveProviderType() {
10652
+ if (configuredProvider) return configuredProvider;
10653
+ const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10654
+ if (envProvider === "openai" || envProvider === "anthropic") return envProvider;
10655
+ if (detectProviderConflict()) return void 0;
10656
+ if (process.env.ANTHROPIC_API_KEY) return "anthropic";
10657
+ if (process.env.OPENAI_API_KEY) return "openai";
10658
+ return void 0;
10659
+ }
10660
+ /**
10391
10661
  * Get the current agent provider based on configuration.
10392
10662
  *
10393
10663
  * Resolution order:
10394
10664
  * 1. Explicit configuration via setAgentProvider()
10395
10665
  * 2. EMBEDDED_AGENT_PROVIDER environment variable
10396
- * 3. Auto-detect: check ANTHROPIC_API_KEY, then OPENAI_API_KEY
10397
- * 4. Throw ConfigurationError if no provider available
10666
+ * 3. Detect conflicts when both API keys are present
10667
+ * 4. Auto-detect: check ANTHROPIC_API_KEY, then OPENAI_API_KEY
10668
+ * 5. Throw ConfigurationError if no provider available
10398
10669
  */
10399
10670
  function getAgentProvider() {
10400
- let providerType = configuredProvider;
10401
- if (!providerType) {
10402
- const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10403
- if (envProvider === "openai" || envProvider === "anthropic") providerType = envProvider;
10404
- }
10671
+ const providerType = resolveProviderType();
10405
10672
  if (providerType && !hasApiKeyForProvider(providerType)) throw new ConfigurationError(`Provider "${providerType}" is configured but ${getApiKeyName(providerType)} is not set. Please set the API key environment variable.`);
10406
- if (!providerType) {
10407
- if (process.env.ANTHROPIC_API_KEY) providerType = "anthropic";
10408
- else if (process.env.OPENAI_API_KEY) providerType = "openai";
10409
- }
10673
+ 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'.");
10410
10674
  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.");
10411
10675
  return buildProvider(providerType);
10412
10676
  }
@@ -10424,15 +10688,11 @@ function hasAgentProvider() {
10424
10688
  }
10425
10689
  /**
10426
10690
  * Get the resolved provider type without throwing.
10427
- * Returns undefined if no provider is available or API key is missing.
10691
+ * Returns undefined if no provider is available, API key is missing, or both API keys are present without explicit selection.
10428
10692
  */
10429
10693
  function getResolvedProviderType() {
10430
- if (configuredProvider) return hasApiKeyForProvider(configuredProvider) ? configuredProvider : void 0;
10431
- const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10432
- if (envProvider === "openai" || envProvider === "anthropic") return hasApiKeyForProvider(envProvider) ? envProvider : void 0;
10433
- if (process.env.ANTHROPIC_API_KEY) return "anthropic";
10434
- if (process.env.OPENAI_API_KEY) return "openai";
10435
- return void 0;
10694
+ const providerType = resolveProviderType();
10695
+ return providerType && hasApiKeyForProvider(providerType) ? providerType : void 0;
10436
10696
  }
10437
10697
 
10438
10698
  //#endregion
@@ -15711,7 +15971,7 @@ function trimStartOfStream() {
15711
15971
  var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
15712
15972
 
15713
15973
  //#endregion
15714
- //#region ../mcp-core/dist/callEmbeddedAgent-BoQGUoqc.js
15974
+ //#region ../mcp-core/dist/callEmbeddedAgent-B-OOjWCj.js
15715
15975
  /**
15716
15976
  * Call an embedded agent with tool call capture
15717
15977
  * This is the standard way to call embedded AI agents within MCP tools
@@ -20800,7 +21060,7 @@ Use these examples as patterns for constructing your query.`;
20800
21060
  }
20801
21061
 
20802
21062
  //#endregion
20803
- //#region ../mcp-core/dist/agent-ChQa0if8.js
21063
+ //#region ../mcp-core/dist/agent-BWQdDemR.js
20804
21064
  const searchEventsAgentOutputSchema = z.object({
20805
21065
  dataset: z.enum([
20806
21066
  "spans",
@@ -21071,7 +21331,7 @@ function formatSpanResults(params) {
21071
21331
  }
21072
21332
 
21073
21333
  //#endregion
21074
- //#region ../mcp-core/dist/handler-DdfFan0E.js
21334
+ //#region ../mcp-core/dist/handler-DnOi9PpE.js
21075
21335
  var handler_default = defineTool({
21076
21336
  name: "search_events",
21077
21337
  skills: [
@@ -21212,7 +21472,7 @@ var handler_default = defineTool({
21212
21472
  });
21213
21473
 
21214
21474
  //#endregion
21215
- //#region ../mcp-core/dist/create-team-ybunuUI_.js
21475
+ //#region ../mcp-core/dist/create-team-BCT36Aw6.js
21216
21476
  var create_team_default = defineTool({
21217
21477
  name: "create_team",
21218
21478
  skills: ["project-management"],
@@ -21267,7 +21527,7 @@ var create_team_default = defineTool({
21267
21527
  });
21268
21528
 
21269
21529
  //#endregion
21270
- //#region ../mcp-core/dist/create-project-BozSQ6GO.js
21530
+ //#region ../mcp-core/dist/create-project-ml-im-rK.js
21271
21531
  var create_project_default = defineTool({
21272
21532
  name: "create_project",
21273
21533
  skills: ["project-management"],
@@ -21344,7 +21604,7 @@ var create_project_default = defineTool({
21344
21604
  });
21345
21605
 
21346
21606
  //#endregion
21347
- //#region ../mcp-core/dist/update-project-CSbOMuOW.js
21607
+ //#region ../mcp-core/dist/update-project-xYXR2Zc0.js
21348
21608
  var update_project_default = defineTool({
21349
21609
  name: "update_project",
21350
21610
  skills: ["project-management"],
@@ -21462,7 +21722,7 @@ var update_project_default = defineTool({
21462
21722
  });
21463
21723
 
21464
21724
  //#endregion
21465
- //#region ../mcp-core/dist/create-dsn-BymieFiV.js
21725
+ //#region ../mcp-core/dist/create-dsn-DfkcMX0d.js
21466
21726
  var create_dsn_default = defineTool({
21467
21727
  name: "create_dsn",
21468
21728
  skills: ["project-management"],
@@ -21522,7 +21782,7 @@ var create_dsn_default = defineTool({
21522
21782
  });
21523
21783
 
21524
21784
  //#endregion
21525
- //#region ../mcp-core/dist/find-dsns-_H3b8I5-.js
21785
+ //#region ../mcp-core/dist/find-dsns-Dwe6GuMG.js
21526
21786
  var find_dsns_default = defineTool({
21527
21787
  name: "find_dsns",
21528
21788
  skills: ["project-management"],
@@ -21623,7 +21883,7 @@ async function retryWithBackoff(fn, { maxRetries = 3, initialDelay = 1e3, should
21623
21883
  }
21624
21884
 
21625
21885
  //#endregion
21626
- //#region ../mcp-core/dist/analyze-issue-with-seer-C6Ke4lsw.js
21886
+ //#region ../mcp-core/dist/analyze-issue-with-seer-52UV39g3.js
21627
21887
  var analyze_issue_with_seer_default = defineTool({
21628
21888
  name: "analyze_issue_with_seer",
21629
21889
  skills: ["seer"],
@@ -21894,7 +22154,7 @@ var search_docs_default = defineTool({
21894
22154
  });
21895
22155
 
21896
22156
  //#endregion
21897
- //#region ../mcp-core/dist/get-doc-Ce6QYANY.js
22157
+ //#region ../mcp-core/dist/get-doc-aRAOW368.js
21898
22158
  var get_doc_default = defineTool({
21899
22159
  name: "get_doc",
21900
22160
  skills: ["docs"],
@@ -22121,7 +22381,7 @@ function getCommonPatterns(dataset) {
22121
22381
  }
22122
22382
 
22123
22383
  //#endregion
22124
- //#region ../mcp-core/dist/config-C3fctASk.js
22384
+ //#region ../mcp-core/dist/config-DUCtK3n7.js
22125
22385
  /**
22126
22386
  * Configuration for the search-issues agent
22127
22387
  */
@@ -22152,6 +22412,10 @@ BUILT-IN FIELDS:
22152
22412
  - assignedOrSuggested: Issues assigned to OR suggested for a user (broader match)
22153
22413
  - userCount: Number of unique users affected
22154
22414
  - eventCount: Total number of events
22415
+ - issue.seer_actionability: Seer's AI-assessed fix difficulty (super_high, high, medium, low, super_low)
22416
+ Use for: "easy to fix", "simple fixes", "quick wins", "low-hanging fruit", "actionable issues", "trivial"
22417
+ Values represent how likely Seer can automatically fix the issue.
22418
+ super_high = very easy/trivial, high = easy, medium = moderate, low/super_low = harder to fix
22155
22419
 
22156
22420
  COMMON QUERY PATTERNS:
22157
22421
  - Unresolved issues: is:unresolved (NO level filter unless explicitly requested)
@@ -22163,6 +22427,10 @@ COMMON QUERY PATTERNS:
22163
22427
  - User feedback: issueCategory:feedback
22164
22428
  - Recent feedback: issueCategory:feedback lastSeen:-7d
22165
22429
  - Feedback from production: issueCategory:feedback environment:production
22430
+ - Easy to fix issues: is:unresolved issue.seer_actionability:[high,super_high]
22431
+ - Quick wins: is:unresolved issue.seer_actionability:[high,super_high]
22432
+ - Very easy/trivial fixes: is:unresolved issue.seer_actionability:super_high
22433
+ - Actionable issues: is:unresolved issue.seer_actionability:[medium,high,super_high]
22166
22434
 
22167
22435
  SORTING RULES:
22168
22436
  1. CRITICAL: Sort MUST go in the separate "sort" field, NEVER in the "query" field
@@ -22188,6 +22456,10 @@ EXAMPLES:
22188
22456
  "assigned to john@example.com" → query: "assignedOrSuggested:john@example.com", sort: "date"
22189
22457
  "show me user feedback" → query: "issueCategory:feedback", sort: "date"
22190
22458
  "feedback from the last week" → query: "issueCategory:feedback lastSeen:-7d", sort: "date"
22459
+ "easy to fix bugs" → query: "is:unresolved issue.seer_actionability:[high,super_high]", sort: "date"
22460
+ "show me quick wins" → query: "is:unresolved issue.seer_actionability:[high,super_high]", sort: "user"
22461
+ "trivial issues to fix" → query: "is:unresolved issue.seer_actionability:super_high", sort: "date"
22462
+ "actionable errors" → query: "is:unresolved issue.seer_actionability:[medium,high,super_high]", sort: "freq"
22191
22463
 
22192
22464
  NEVER: query: "is:unresolved sort:user" ← Sort goes in separate field!
22193
22465
 
@@ -22201,7 +22473,7 @@ Always use the issueFields tool to discover available fields when needed.
22201
22473
  Use the whoami tool when you need to resolve 'me' references.`;
22202
22474
 
22203
22475
  //#endregion
22204
- //#region ../mcp-core/dist/agent-qJanDgXA.js
22476
+ //#region ../mcp-core/dist/agent-CbZD6I99.js
22205
22477
  const searchIssuesAgentOutputSchema = z.object({
22206
22478
  query: z.string().describe("The Sentry issue search query"),
22207
22479
  sort: z.enum([
@@ -22234,7 +22506,7 @@ async function searchIssuesAgent(options) {
22234
22506
  }
22235
22507
 
22236
22508
  //#endregion
22237
- //#region ../mcp-core/dist/formatters-BcLCXcro.js
22509
+ //#region ../mcp-core/dist/formatters-EefHn4Td.js
22238
22510
  /**
22239
22511
  * Format an explanation for how a natural language query was translated
22240
22512
  */
@@ -22288,6 +22560,7 @@ function formatIssueResults(params) {
22288
22560
  output += `- **First seen**: ${formatDate(issue.firstSeen)}\n`;
22289
22561
  output += `- **Last seen**: ${formatDate(issue.lastSeen)}\n`;
22290
22562
  if (issue.culprit) output += `- **Culprit**: \`${issue.culprit}\`\n`;
22563
+ if (issue.seerFixabilityScore != null) output += `- **Seer Actionability**: ${getSeerActionabilityLabel(issue.seerFixabilityScore)}\n`;
22291
22564
  output += "\n";
22292
22565
  });
22293
22566
  output += "## Next Steps\n\n";
@@ -22318,7 +22591,7 @@ function formatDate(dateString) {
22318
22591
  }
22319
22592
 
22320
22593
  //#endregion
22321
- //#region ../mcp-core/dist/handler-DriMefmS.js
22594
+ //#region ../mcp-core/dist/handler-6FQ-M_Hc.js
22322
22595
  var handler_default$1 = defineTool({
22323
22596
  name: "search_issues",
22324
22597
  skills: [
@@ -22853,7 +23126,7 @@ Received: ${params.issueUrl}`);
22853
23126
  }
22854
23127
 
22855
23128
  //#endregion
22856
- //#region ../mcp-core/dist/agent-BGV8TUGG.js
23129
+ //#region ../mcp-core/dist/agent-BS8FSFrZ.js
22857
23130
  const searchIssueEventsAgentOutputSchema = z.object({
22858
23131
  query: z.string().describe("Sentry query filters for tags/fields (NOT including issue: prefix - handler adds that)"),
22859
23132
  fields: z.array(z.string()).describe("Array of field names to return in results"),
@@ -22895,7 +23168,7 @@ async function searchIssueEventsAgent(options) {
22895
23168
  }
22896
23169
 
22897
23170
  //#endregion
22898
- //#region ../mcp-core/dist/handler-dNZGGGFd.js
23171
+ //#region ../mcp-core/dist/handler-CnIAtQSZ.js
22899
23172
  var handler_default$2 = defineTool({
22900
23173
  name: "search_issue_events",
22901
23174
  skills: ["inspect", "triage"],
@@ -23016,7 +23289,7 @@ The user may include various parameters to pass to those tools in their prompt.
23016
23289
  You MUST return tool results directly without interpreting them.`;
23017
23290
 
23018
23291
  //#endregion
23019
- //#region ../mcp-core/dist/agent-2JRDh9Lm.js
23292
+ //#region ../mcp-core/dist/agent-BFhtnTf9.js
23020
23293
  /**
23021
23294
  * Output schema for the embedded agent.
23022
23295
  * The agent returns the final result string directly from its tool calls.
@@ -23037,7 +23310,27 @@ async function useSentryAgent(options) {
23037
23310
  }
23038
23311
 
23039
23312
  //#endregion
23040
- //#region ../mcp-core/dist/list-issues-DpmIWiEG.js
23313
+ //#region ../mcp-core/dist/types-CsTmoXmm.js
23314
+ /**
23315
+ * Resolves a tool description to a string.
23316
+ * Handles both static strings and dynamic description functions.
23317
+ */
23318
+ function resolveDescription(description$73, context$1) {
23319
+ return typeof description$73 === "function" ? description$73(context$1) : description$73;
23320
+ }
23321
+ /**
23322
+ * Determines if a tool should be visible based on experimental mode.
23323
+ * - Tools with `experimental: true` are only visible when experimentalMode is true
23324
+ * - Tools with `hideInExperimentalMode: true` are hidden when experimentalMode is true
23325
+ */
23326
+ function isToolVisibleInMode(tool$1, experimentalMode) {
23327
+ if (tool$1.experimental && !experimentalMode) return false;
23328
+ if (tool$1.hideInExperimentalMode && experimentalMode) return false;
23329
+ return true;
23330
+ }
23331
+
23332
+ //#endregion
23333
+ //#region ../mcp-core/dist/list-issues-5UocH4Yv.js
23041
23334
  var list_issues_default = defineTool({
23042
23335
  name: "list_issues",
23043
23336
  skills: [
@@ -23120,7 +23413,7 @@ var list_issues_default = defineTool({
23120
23413
  });
23121
23414
 
23122
23415
  //#endregion
23123
- //#region ../mcp-core/dist/list-events-BCMaD3UM.js
23416
+ //#region ../mcp-core/dist/list-events-B2eHsG5k.js
23124
23417
  const DEFAULT_FIELDS = {
23125
23418
  errors: RECOMMENDED_FIELDS.errors.basic,
23126
23419
  logs: RECOMMENDED_FIELDS.logs.basic,
@@ -23242,7 +23535,7 @@ var list_events_default = defineTool({
23242
23535
  });
23243
23536
 
23244
23537
  //#endregion
23245
- //#region ../mcp-core/dist/list-issue-events-D2EcLe8P.js
23538
+ //#region ../mcp-core/dist/list-issue-events-CpB246ug.js
23246
23539
  var list_issue_events_default = defineTool({
23247
23540
  name: "list_issue_events",
23248
23541
  skills: ["inspect", "triage"],
@@ -23326,7 +23619,1214 @@ var list_issue_events_default = defineTool({
23326
23619
  });
23327
23620
 
23328
23621
  //#endregion
23329
- //#region ../mcp-core/dist/error-handling-DFJ-iOAP.js
23622
+ //#region ../mcp-core/dist/analyzer-DtlTbDTS.js
23623
+ /**
23624
+ * Analyzes flamegraph data to extract hot paths (most CPU-intensive call stacks).
23625
+ *
23626
+ * Hot paths are merged when duplicate stacks appear, sorted by total duration
23627
+ * (most time spent), and limited to maxHotPaths. Each path includes the full
23628
+ * call stack with depth tracking.
23629
+ *
23630
+ * Note: Call stacks are stored leaf-to-root (main frame at end) for efficient
23631
+ * flamegraph/call tree merging. User code filtering is done during formatting.
23632
+ *
23633
+ * @param flamegraph Flamegraph data from API
23634
+ * @param options Analysis options
23635
+ * @returns Array of hot paths sorted by duration (descending)
23636
+ */
23637
+ function analyzeHotPathsFromFlamegraph(flamegraph, options) {
23638
+ const profile = flamegraph.profiles[0];
23639
+ if (!profile) return [];
23640
+ const frames = flamegraph.shared.frames;
23641
+ const frameInfos = flamegraph.shared.frame_infos;
23642
+ const totalSamples = profile.sample_counts.reduce((a, b) => a + b, 0);
23643
+ const mergedStacks = /* @__PURE__ */ new Map();
23644
+ for (let idx = 0; idx < profile.samples.length; idx++) {
23645
+ const stackIndices = profile.samples[idx];
23646
+ const sampleCount = profile.sample_counts[idx] || 0;
23647
+ const duration = profile.sample_durations_ns[idx] || 0;
23648
+ const weight = profile.weights[idx] || 0;
23649
+ const stackKey = stackIndices.join(",");
23650
+ const existing = mergedStacks.get(stackKey);
23651
+ if (existing) {
23652
+ existing.sampleCount += sampleCount;
23653
+ existing.duration += duration;
23654
+ existing.weight += weight;
23655
+ } else mergedStacks.set(stackKey, {
23656
+ stackIndices,
23657
+ sampleCount,
23658
+ duration,
23659
+ weight
23660
+ });
23661
+ }
23662
+ const hotPaths = Array.from(mergedStacks.values()).map((merged) => {
23663
+ const callStack = reconstructCallStack([...merged.stackIndices].reverse(), frames, frameInfos);
23664
+ const userCodeFrames = callStack.filter((f) => f.frame.is_application);
23665
+ return {
23666
+ stackIndices: merged.stackIndices,
23667
+ sampleCount: merged.sampleCount,
23668
+ duration: merged.duration,
23669
+ weight: merged.weight,
23670
+ percentOfTotal: totalSamples > 0 ? merged.sampleCount / totalSamples * 100 : 0,
23671
+ callStack,
23672
+ userCodeFrames
23673
+ };
23674
+ });
23675
+ return hotPaths.sort((a, b) => b.duration - a.duration).slice(0, options.maxHotPaths);
23676
+ }
23677
+ /** Default frame info for missing data */
23678
+ const DEFAULT_FRAME_INFO = {
23679
+ count: 0,
23680
+ weight: 0,
23681
+ sumDuration: 0,
23682
+ sumSelfTime: 0,
23683
+ p75Duration: 0,
23684
+ p95Duration: 0,
23685
+ p99Duration: 0
23686
+ };
23687
+ /** Default frame for missing data */
23688
+ const DEFAULT_FRAME = {
23689
+ file: "unknown",
23690
+ name: "unknown",
23691
+ line: 0,
23692
+ is_application: false,
23693
+ fingerprint: 0
23694
+ };
23695
+ /**
23696
+ * Reconstructs a call stack from frame indices with depth tracking.
23697
+ *
23698
+ * Frames are ordered leaf-to-root (leaf at index 0, root at end) for efficient
23699
+ * flamegraph/call tree merging. This allows top-down traversal and early
23700
+ * termination when merging stacks.
23701
+ *
23702
+ * @param stackIndices Array of frame indices forming the call stack (leaf to root)
23703
+ * @param frames All frames from flamegraph
23704
+ * @param frameInfos Performance stats for each frame
23705
+ * @returns Reconstructed call stack with metadata (leaf first, root last)
23706
+ */
23707
+ function reconstructCallStack(stackIndices, frames, frameInfos) {
23708
+ const stackLength = stackIndices.length;
23709
+ return stackIndices.map((frameIdx, idx) => ({
23710
+ frame: frames[frameIdx] || DEFAULT_FRAME,
23711
+ frameInfo: frameInfos[frameIdx] || DEFAULT_FRAME_INFO,
23712
+ depth: idx,
23713
+ isLeaf: idx === 0,
23714
+ isRoot: idx === stackLength - 1,
23715
+ frameIndex: frameIdx
23716
+ }));
23717
+ }
23718
+ /**
23719
+ * Identifies hotspot frames (functions consuming the most CPU time).
23720
+ *
23721
+ * Hotspots are individual functions that appear frequently in profiles,
23722
+ * sorted by total weight (time spent in that function across all samples).
23723
+ *
23724
+ * @param flamegraph Flamegraph data from API
23725
+ * @param options Analysis options
23726
+ * @returns Array of hotspot frames sorted by weight (descending)
23727
+ */
23728
+ function identifyHotspotFramesFromFlamegraph(flamegraph, options) {
23729
+ const frames = flamegraph.shared.frames;
23730
+ const frameInfos = flamegraph.shared.frame_infos;
23731
+ const totalSamples = flamegraph.profiles.reduce((sum, profile) => sum + profile.sample_counts.reduce((a, b) => a + b, 0), 0);
23732
+ const hotspots = frames.map((frame, idx) => {
23733
+ const frameInfo = frameInfos[idx] || DEFAULT_FRAME_INFO;
23734
+ return {
23735
+ frame,
23736
+ frameInfo,
23737
+ percentOfTotal: totalSamples > 0 ? frameInfo.count / totalSamples * 100 : 0,
23738
+ frameIndex: idx
23739
+ };
23740
+ }).filter((h) => !options.focusOnUserCode || h.frame.is_application).sort((a, b) => b.frameInfo.weight - a.frameInfo.weight).slice(0, 20);
23741
+ return hotspots;
23742
+ }
23743
+ /**
23744
+ * Generates performance insights based on percentile analysis.
23745
+ *
23746
+ * Analyzes p75, p95, and p99 latencies to identify:
23747
+ * - High variance (inconsistent performance)
23748
+ * - Consistently slow functions (high median)
23749
+ * - Hot functions (called very frequently)
23750
+ * - Consistent functions (low variance)
23751
+ *
23752
+ * @param frameInfo Performance statistics for a frame
23753
+ * @returns Array of insights
23754
+ */
23755
+ function generatePerformanceInsights(frameInfo) {
23756
+ const insights = [];
23757
+ if (frameInfo.p99Duration > frameInfo.p75Duration * 3) insights.push({
23758
+ type: "high_variance",
23759
+ icon: "⚠️",
23760
+ message: "High variance: Performance varies significantly across calls"
23761
+ });
23762
+ if (frameInfo.p75Duration > 1e8) insights.push({
23763
+ type: "consistently_slow",
23764
+ icon: "🐌",
23765
+ message: "Consistently slow: Median execution time is high"
23766
+ });
23767
+ if (frameInfo.count > 1e3) insights.push({
23768
+ type: "hot_function",
23769
+ icon: "🔥",
23770
+ message: "Hot function: Called very frequently"
23771
+ });
23772
+ if (insights.length === 0 && frameInfo.p99Duration <= frameInfo.p75Duration * 1.5) insights.push({
23773
+ type: "consistent",
23774
+ icon: "✅",
23775
+ message: "Consistent: Low performance variance"
23776
+ });
23777
+ return insights;
23778
+ }
23779
+ /**
23780
+ * Compares frame statistics between baseline and current to detect regressions.
23781
+ *
23782
+ * Analyzes percentage change in weight (total CPU time) and classifies changes:
23783
+ * - Major regression: >20% slower
23784
+ * - Minor regression: 10-20% slower
23785
+ * - Improvement: Faster
23786
+ * - No change: <10% change
23787
+ *
23788
+ * @param baseline Baseline flamegraph data
23789
+ * @param current Current flamegraph data
23790
+ * @param options Comparison options
23791
+ * @returns Array of frame comparisons sorted by regression severity
23792
+ */
23793
+ function compareFrameStats(baseline, current, options) {
23794
+ const baselineFrames = baseline.shared.frames;
23795
+ const currentFrames = current.shared.frames;
23796
+ const baselineInfos = baseline.shared.frame_infos;
23797
+ const currentInfos = current.shared.frame_infos;
23798
+ const frameMap = /* @__PURE__ */ new Map();
23799
+ baselineFrames.forEach((frame, idx) => {
23800
+ const existing = frameMap.get(frame.fingerprint) || {};
23801
+ frameMap.set(frame.fingerprint, {
23802
+ ...existing,
23803
+ baselineIdx: idx
23804
+ });
23805
+ });
23806
+ currentFrames.forEach((frame, idx) => {
23807
+ const existing = frameMap.get(frame.fingerprint) || {};
23808
+ frameMap.set(frame.fingerprint, {
23809
+ ...existing,
23810
+ currentIdx: idx
23811
+ });
23812
+ });
23813
+ const comparisons = [];
23814
+ for (const [fingerprint, indices] of frameMap.entries()) {
23815
+ if (indices.baselineIdx === void 0 || indices.currentIdx === void 0) continue;
23816
+ const baselineFrame = baselineFrames[indices.baselineIdx];
23817
+ const currentFrame = currentFrames[indices.currentIdx];
23818
+ const baselineInfo = baselineInfos[indices.baselineIdx] || DEFAULT_FRAME_INFO;
23819
+ const currentInfo = currentInfos[indices.currentIdx] || DEFAULT_FRAME_INFO;
23820
+ if (options.focusOnUserCode && !currentFrame.is_application) continue;
23821
+ const percentChange = baselineInfo.sumDuration > 0 ? (currentInfo.sumDuration - baselineInfo.sumDuration) / baselineInfo.sumDuration * 100 : 0;
23822
+ let changeType;
23823
+ if (percentChange > 20) changeType = "major_regression";
23824
+ else if (percentChange > 10) changeType = "minor_regression";
23825
+ else if (percentChange < -10) changeType = "improvement";
23826
+ else changeType = "no_change";
23827
+ comparisons.push({
23828
+ frame: currentFrame,
23829
+ baseline: baselineInfo,
23830
+ current: currentInfo,
23831
+ percentChange,
23832
+ changeType
23833
+ });
23834
+ }
23835
+ const severityOrder = {
23836
+ major_regression: 0,
23837
+ minor_regression: 1,
23838
+ no_change: 2,
23839
+ improvement: 3
23840
+ };
23841
+ return comparisons.sort((a, b) => severityOrder[a.changeType] - severityOrder[b.changeType] || b.percentChange - a.percentChange);
23842
+ }
23843
+ const MICROSECOND = 1e3;
23844
+ const MILLISECOND = 1e6;
23845
+ const SECOND = 1e9;
23846
+ /**
23847
+ * Formats duration from nanoseconds to human-readable string.
23848
+ *
23849
+ * @param ns Duration in nanoseconds
23850
+ * @returns Formatted duration string (e.g., "157ms", "1.2s")
23851
+ */
23852
+ function formatDuration(ns) {
23853
+ if (ns < MILLISECOND) return `${(ns / MICROSECOND).toFixed(0)}µs`;
23854
+ if (ns < SECOND) return `${(ns / MILLISECOND).toFixed(0)}ms`;
23855
+ return `${(ns / SECOND).toFixed(1)}s`;
23856
+ }
23857
+ /**
23858
+ * Formats a percentage value for display.
23859
+ *
23860
+ * @param value Percentage value (0-100)
23861
+ * @returns Formatted percentage string (e.g., "45.2%", "0.1%")
23862
+ */
23863
+ function formatPercentage(value) {
23864
+ if (value < 1) return `${value.toFixed(2)}%`;
23865
+ return `${value.toFixed(1)}%`;
23866
+ }
23867
+ /**
23868
+ * Checks if a flamegraph has valid profile data.
23869
+ *
23870
+ * Validates that the flamegraph contains at least one profile with frames.
23871
+ * Used to determine if analysis can proceed.
23872
+ *
23873
+ * @param flamegraph Flamegraph data from API
23874
+ * @returns True if the flamegraph has valid profile data
23875
+ */
23876
+ function hasProfileData(flamegraph) {
23877
+ return flamegraph.profiles.length > 0 && flamegraph.shared.frames.length > 0;
23878
+ }
23879
+
23880
+ //#endregion
23881
+ //#region ../mcp-core/dist/formatter-DnTyNWUz.js
23882
+ /**
23883
+ * Maps a change type to its corresponding status icon.
23884
+ */
23885
+ const CHANGE_TYPE_ICONS = {
23886
+ major_regression: "🚨",
23887
+ minor_regression: "⚠️",
23888
+ improvement: "✅",
23889
+ no_change: "➖"
23890
+ };
23891
+ /**
23892
+ * Determines the overall comparison status based on regression/improvement counts.
23893
+ */
23894
+ function determineComparisonStatus(majorCount, minorCount, improvementCount) {
23895
+ if (majorCount > 0) return "⚠️ Performance Regression Detected";
23896
+ if (minorCount > 0) return "⚠️ Minor Performance Changes Detected";
23897
+ if (improvementCount > 0) return "✅ Performance Improvements Detected";
23898
+ return "✅ No Significant Changes";
23899
+ }
23900
+ /**
23901
+ * Truncates a file location string for table display.
23902
+ */
23903
+ function truncateLocation(location, maxLength = 30) {
23904
+ if (location.length <= maxLength) return location;
23905
+ return `...${location.slice(-(maxLength - 3))}`;
23906
+ }
23907
+ /**
23908
+ * Formats flamegraph analysis for a single transaction.
23909
+ *
23910
+ * Produces markdown output with:
23911
+ * - Transaction information
23912
+ * - Performance summary (user code vs library)
23913
+ * - Top slow functions table
23914
+ * - Hot paths with recommendations
23915
+ * - Actionable next steps
23916
+ *
23917
+ * @param flamegraph Flamegraph data from API
23918
+ * @param options Formatting options
23919
+ * @returns Markdown-formatted analysis
23920
+ */
23921
+ function formatFlamegraphAnalysis(flamegraph, options) {
23922
+ const sections = [];
23923
+ sections.push(formatTransactionInfo(flamegraph));
23924
+ sections.push(formatPerformanceSummary(flamegraph, options));
23925
+ const hotPaths = analyzeHotPathsFromFlamegraph(flamegraph, options);
23926
+ sections.push(formatHotPaths(hotPaths, flamegraph, options));
23927
+ sections.push(formatActionableSteps(hotPaths, options));
23928
+ return sections.join("\n\n");
23929
+ }
23930
+ /**
23931
+ * Formats transaction information section.
23932
+ */
23933
+ function formatTransactionInfo(flamegraph) {
23934
+ const profile = flamegraph.profiles[0];
23935
+ const totalSamples = profile?.sample_counts.reduce((a, b) => a + b, 0) || 0;
23936
+ const totalDuration = profile?.sample_durations_ns.reduce((a, b) => a + b, 0) || 0;
23937
+ return [
23938
+ `# Profile Analysis: ${flamegraph.transactionName || "Unknown Transaction"}`,
23939
+ "",
23940
+ "## Transaction Information",
23941
+ `- **Transaction**: ${flamegraph.transactionName || "Unknown"}`,
23942
+ `- **Project ID**: ${flamegraph.projectID}`,
23943
+ `- **Platform**: ${flamegraph.platform || "Unknown"}`,
23944
+ `- **Total Profiles**: ${flamegraph.shared.profiles.length}`,
23945
+ `- **Total Samples**: ${totalSamples.toLocaleString()}`,
23946
+ `- **Estimated Total Time**: ${formatDuration(totalDuration)}`
23947
+ ].join("\n");
23948
+ }
23949
+ /**
23950
+ * Formats performance summary section.
23951
+ */
23952
+ function formatPerformanceSummary(flamegraph, options) {
23953
+ const hotspots = identifyHotspotFramesFromFlamegraph(flamegraph, { focusOnUserCode: false });
23954
+ let userCodeTime = 0;
23955
+ let libraryTime = 0;
23956
+ for (const h of hotspots) if (h.frame.is_application) userCodeTime += h.frameInfo.sumDuration;
23957
+ else libraryTime += h.frameInfo.sumDuration;
23958
+ const totalTime = userCodeTime + libraryTime;
23959
+ const userPercent = totalTime > 0 ? userCodeTime / totalTime * 100 : 0;
23960
+ const libraryPercent = totalTime > 0 ? libraryTime / totalTime * 100 : 0;
23961
+ const sections = [
23962
+ "## Performance Summary",
23963
+ "",
23964
+ "### Code Breakdown",
23965
+ `- **Total User Code Time**: ${formatDuration(userCodeTime)} (${formatPercentage(userPercent)})`,
23966
+ `- **Total Library Time**: ${formatDuration(libraryTime)} (${formatPercentage(libraryPercent)})`
23967
+ ];
23968
+ const topFunctions = identifyHotspotFramesFromFlamegraph(flamegraph, options).slice(0, 10);
23969
+ if (topFunctions.length > 0) {
23970
+ sections.push("", "### Top Slow Functions");
23971
+ sections.push("");
23972
+ sections.push("| Function | File:Line | Samples | % Time | p75 | p95 | p99 | Insights |");
23973
+ sections.push("|----------|-----------|---------|--------|-----|-----|-----|----------|");
23974
+ for (const func of topFunctions) {
23975
+ const insights = generatePerformanceInsights(func.frameInfo);
23976
+ const insightText = insights.map((i) => i.icon).join(" ");
23977
+ const location = truncateLocation(`${func.frame.file}:${func.frame.line}`);
23978
+ 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} |`);
23979
+ }
23980
+ }
23981
+ return sections.join("\n");
23982
+ }
23983
+ /**
23984
+ * Formats hot paths section.
23985
+ */
23986
+ function formatHotPaths(hotPaths, flamegraph, options) {
23987
+ if (hotPaths.length === 0) return "## Hot Paths\n\nNo significant hot paths found.";
23988
+ const sections = ["## Top Hot Paths", ""];
23989
+ hotPaths.forEach((path, idx) => {
23990
+ if (idx > 0) sections.push("---", "");
23991
+ sections.push(`### Path #${idx + 1}: ${formatPercentage(path.percentOfTotal)} of execution time`);
23992
+ sections.push("");
23993
+ sections.push(`**${path.sampleCount.toLocaleString()} samples** across ${flamegraph.shared.profiles.length} profiles`);
23994
+ sections.push("");
23995
+ const framesToShow = options.focusOnUserCode ? path.userCodeFrames : path.callStack;
23996
+ if (framesToShow.length > 0) {
23997
+ sections.push("```");
23998
+ const displayFrames = [...framesToShow].reverse();
23999
+ displayFrames.forEach((frame, i) => {
24000
+ const indent = " ".repeat(i);
24001
+ const marker$2 = frame.frame.is_application ? "[YOUR CODE]" : "[library]";
24002
+ const isLeaf = i === displayFrames.length - 1;
24003
+ const suffix = isLeaf && options.focusOnUserCode ? " ← PRIMARY BOTTLENECK" : "";
24004
+ sections.push(`${indent}${frame.frame.file}:${frame.frame.name}:${frame.frame.line} ${marker$2}${suffix}`);
24005
+ });
24006
+ sections.push("```");
24007
+ sections.push("");
24008
+ }
24009
+ const leafFrame = path.callStack[0];
24010
+ if (leafFrame) {
24011
+ const insights = generatePerformanceInsights(leafFrame.frameInfo);
24012
+ sections.push("**Performance Characteristics:**");
24013
+ sections.push(`- **p75**: ${formatDuration(leafFrame.frameInfo.p75Duration)}`);
24014
+ sections.push(`- **p95**: ${formatDuration(leafFrame.frameInfo.p95Duration)}`);
24015
+ sections.push(`- **p99**: ${formatDuration(leafFrame.frameInfo.p99Duration)}${insights.some((i) => i.type === "high_variance") ? " (⚠️ High variance - some calls are very slow)" : ""}`);
24016
+ sections.push("");
24017
+ sections.push("**💡 Recommendation:**");
24018
+ 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." : ""}`);
24019
+ sections.push("");
24020
+ }
24021
+ });
24022
+ return sections.join("\n");
24023
+ }
24024
+ /**
24025
+ * Formats actionable next steps section.
24026
+ */
24027
+ function formatActionableSteps(hotPaths, options) {
24028
+ const sections = [
24029
+ "## Actionable Next Steps",
24030
+ "",
24031
+ "### Immediate Actions (High Impact)"
24032
+ ];
24033
+ const topPath = hotPaths[0];
24034
+ if (topPath) {
24035
+ const frameToRecommend = options.focusOnUserCode ? topPath.userCodeFrames[0] : topPath.callStack[0];
24036
+ if (frameToRecommend) sections.push(`1. **Optimize \`${frameToRecommend.frame.name}\` function** - Accounts for ${formatPercentage(topPath.percentOfTotal)} of CPU time`);
24037
+ }
24038
+ 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");
24039
+ return sections.join("\n");
24040
+ }
24041
+ /**
24042
+ * Formats flamegraph comparison for regression detection.
24043
+ *
24044
+ * Produces markdown output with:
24045
+ * - Comparison summary
24046
+ * - Key changes table
24047
+ * - Regressions detected
24048
+ * - Suggested investigation steps
24049
+ *
24050
+ * @param baseline Baseline flamegraph data
24051
+ * @param current Current flamegraph data
24052
+ * @param options Formatting options
24053
+ * @returns Markdown-formatted comparison
24054
+ */
24055
+ function formatFlamegraphComparison(baseline, current, options) {
24056
+ const sections = [];
24057
+ sections.push(`# Profile Comparison: ${current.transactionName || "Unknown Transaction"}`);
24058
+ sections.push("");
24059
+ sections.push("## Summary");
24060
+ const comparisons = compareFrameStats(baseline, current, options);
24061
+ const majorRegressions = comparisons.filter((c) => c.changeType === "major_regression");
24062
+ const minorRegressions = comparisons.filter((c) => c.changeType === "minor_regression");
24063
+ const improvements = comparisons.filter((c) => c.changeType === "improvement");
24064
+ const status = determineComparisonStatus(majorRegressions.length, minorRegressions.length, improvements.length);
24065
+ sections.push(`- **Status**: ${status}`);
24066
+ sections.push("");
24067
+ if (comparisons.length > 0) {
24068
+ sections.push("## Key Changes");
24069
+ sections.push("");
24070
+ sections.push("| Function | File:Line | Baseline | Current | Change | Status |");
24071
+ sections.push("|----------|-----------|----------|---------|--------|--------|");
24072
+ for (const comp of comparisons.slice(0, 10)) {
24073
+ const location = truncateLocation(`${comp.frame.file}:${comp.frame.line}`);
24074
+ const statusIcon = CHANGE_TYPE_ICONS[comp.changeType];
24075
+ const change = comp.percentChange > 0 ? `+${formatPercentage(comp.percentChange)}` : formatPercentage(comp.percentChange);
24076
+ sections.push(`| \`${comp.frame.name}\` | ${location} | ${formatDuration(comp.baseline.sumDuration)} | ${formatDuration(comp.current.sumDuration)} | ${change} | ${statusIcon} |`);
24077
+ }
24078
+ sections.push("");
24079
+ }
24080
+ if (majorRegressions.length > 0) {
24081
+ sections.push("## Major Regressions Detected");
24082
+ sections.push("");
24083
+ for (const reg of majorRegressions.slice(0, 5)) {
24084
+ sections.push(`### 🚨 \`${reg.frame.name}\``);
24085
+ sections.push(`- **Change**: +${formatPercentage(reg.percentChange)} slower`);
24086
+ sections.push(`- **Impact**: ${formatDuration(reg.baseline.sumDuration)} → ${formatDuration(reg.current.sumDuration)}`);
24087
+ sections.push(`- **Location**: ${reg.frame.file}:${reg.frame.line}`);
24088
+ sections.push("");
24089
+ sections.push("**Suggested Action**: Investigate recent changes to this function");
24090
+ sections.push("");
24091
+ }
24092
+ }
24093
+ return sections.join("\n");
24094
+ }
24095
+
24096
+ //#endregion
24097
+ //#region ../mcp-core/dist/url-helpers-eQ8-mYIs.js
24098
+ /**
24099
+ * Parses a Sentry URL and extracts resource type and identifiers.
24100
+ *
24101
+ * Supported URL patterns:
24102
+ * - Issue: `/issues/{issueId}` or `/organizations/{org}/issues/{issueId}`
24103
+ * - Event: `/issues/{issueId}/events/{eventId}`
24104
+ * - Trace: `/explore/traces/trace/{traceId}` or `/performance/trace/{traceId}`
24105
+ * - Profile: `/explore/profiling/profile/{project}/flamegraph/` with query params
24106
+ * - Replay: `/replays/{replayId}/`
24107
+ * - Monitor: `/crons/{monitorSlug}/` or `/monitors/{monitorSlug}/`
24108
+ * - Release: `/releases/{version}/`
24109
+ *
24110
+ * Organization slug is extracted from:
24111
+ * 1. Subdomain (e.g., `my-org.sentry.io`)
24112
+ * 2. Path (e.g., `/organizations/my-org/...` or `/my-org/issues/...`)
24113
+ *
24114
+ * @param url - A Sentry URL to parse
24115
+ * @returns Parsed URL with resource type and identifiers
24116
+ * @throws UserInputError if the URL is invalid or cannot be parsed
24117
+ *
24118
+ * @example
24119
+ * // Issue URL
24120
+ * parseSentryUrl("https://my-org.sentry.io/issues/PROJECT-123")
24121
+ * // { type: "issue", organizationSlug: "my-org", issueId: "PROJECT-123" }
24122
+ *
24123
+ * @example
24124
+ * // Replay URL
24125
+ * parseSentryUrl("https://my-org.sentry.io/replays/abc123def456/")
24126
+ * // { type: "replay", organizationSlug: "my-org", replayId: "abc123def456" }
24127
+ *
24128
+ * @example
24129
+ * // Monitor URL
24130
+ * parseSentryUrl("https://my-org.sentry.io/crons/my-cron-job/")
24131
+ * // { type: "monitor", organizationSlug: "my-org", monitorSlug: "my-cron-job" }
24132
+ */
24133
+ function parseSentryUrl(url) {
24134
+ if (!url || typeof url !== "string") throw new UserInputError("Invalid Sentry URL. URL must be a non-empty string.");
24135
+ if (!url.startsWith("http://") && !url.startsWith("https://")) throw new UserInputError("Invalid Sentry URL. Must start with http:// or https://");
24136
+ let parsedUrl;
24137
+ try {
24138
+ parsedUrl = new URL(url);
24139
+ } catch {
24140
+ throw new UserInputError(`Invalid Sentry URL. Unable to parse URL: ${url}`);
24141
+ }
24142
+ const pathParts = parsedUrl.pathname.split("/").filter(Boolean);
24143
+ const organizationSlug = extractOrganizationSlug(parsedUrl, pathParts);
24144
+ return identifyResource(parsedUrl, pathParts, organizationSlug);
24145
+ }
24146
+ /**
24147
+ * Extracts organization slug from URL.
24148
+ *
24149
+ * Checks in order:
24150
+ * 1. `/organizations/{org}/...` path format
24151
+ * 2. `/{org}/issues/...` path format (org before known segments)
24152
+ * 3. Subdomain (e.g., `my-org.sentry.io`) - excluding region prefixes
24153
+ */
24154
+ function extractOrganizationSlug(parsedUrl, pathParts) {
24155
+ if (pathParts.includes("organizations")) {
24156
+ const orgIndex = pathParts.indexOf("organizations");
24157
+ const slug = pathParts[orgIndex + 1];
24158
+ if (slug) return slug;
24159
+ }
24160
+ const knownSegments = [
24161
+ "issues",
24162
+ "explore",
24163
+ "performance",
24164
+ "projects",
24165
+ "settings",
24166
+ "replays",
24167
+ "releases",
24168
+ "crons",
24169
+ "monitors",
24170
+ "alerts",
24171
+ "feedback",
24172
+ "dashboards",
24173
+ "discover",
24174
+ "insights"
24175
+ ];
24176
+ if (pathParts.length > 1 && knownSegments.includes(pathParts[1])) return pathParts[0];
24177
+ const hostParts = parsedUrl.hostname.split(".");
24178
+ const regionPrefixes = [
24179
+ "us",
24180
+ "eu",
24181
+ "de",
24182
+ "www"
24183
+ ];
24184
+ if (hostParts.length >= 2 && !regionPrefixes.includes(hostParts[0])) return hostParts[0];
24185
+ throw new UserInputError("Invalid Sentry URL. Could not determine organization from URL.");
24186
+ }
24187
+ /**
24188
+ * Identifies the resource type and extracts relevant identifiers.
24189
+ */
24190
+ function identifyResource(parsedUrl, pathParts, organizationSlug) {
24191
+ const profilingIndex = pathParts.indexOf("profiling");
24192
+ if (profilingIndex !== -1 && pathParts[profilingIndex + 1] === "profile") {
24193
+ const projectSlug = pathParts[profilingIndex + 2];
24194
+ const profilerId = parsedUrl.searchParams.get("profilerId") || void 0;
24195
+ const start = parsedUrl.searchParams.get("start") || void 0;
24196
+ const end = parsedUrl.searchParams.get("end") || void 0;
24197
+ return {
24198
+ type: "profile",
24199
+ organizationSlug,
24200
+ projectSlug,
24201
+ profilerId,
24202
+ start,
24203
+ end
24204
+ };
24205
+ }
24206
+ const replaysIndex = pathParts.indexOf("replays");
24207
+ if (replaysIndex !== -1) {
24208
+ const replayId = pathParts[replaysIndex + 1];
24209
+ if (replayId && replayId !== "selectors") return {
24210
+ type: "replay",
24211
+ organizationSlug,
24212
+ replayId
24213
+ };
24214
+ }
24215
+ const cronsIndex = pathParts.indexOf("crons");
24216
+ const monitorsIndex = pathParts.indexOf("monitors");
24217
+ const monitorPathIndex = cronsIndex !== -1 ? cronsIndex : monitorsIndex;
24218
+ if (monitorPathIndex !== -1) {
24219
+ const nextPart = pathParts[monitorPathIndex + 1];
24220
+ if (nextPart && nextPart !== "new") {
24221
+ const afterNext = pathParts[monitorPathIndex + 2];
24222
+ if (afterNext && afterNext !== "details") return {
24223
+ type: "monitor",
24224
+ organizationSlug,
24225
+ projectSlug: nextPart,
24226
+ monitorSlug: afterNext
24227
+ };
24228
+ return {
24229
+ type: "monitor",
24230
+ organizationSlug,
24231
+ monitorSlug: nextPart
24232
+ };
24233
+ }
24234
+ }
24235
+ const releasesIndex = pathParts.indexOf("releases");
24236
+ if (releasesIndex !== -1) {
24237
+ const releaseVersion = pathParts[releasesIndex + 1];
24238
+ if (releaseVersion && releaseVersion !== "new-events" && releaseVersion !== "all-events") return {
24239
+ type: "release",
24240
+ organizationSlug,
24241
+ releaseVersion
24242
+ };
24243
+ }
24244
+ const traceIndex = pathParts.indexOf("trace");
24245
+ if (traceIndex !== -1) {
24246
+ const traceId = pathParts[traceIndex + 1];
24247
+ if (traceId) {
24248
+ const nodeParam = parsedUrl.searchParams.get("node");
24249
+ let spanId;
24250
+ if (nodeParam?.startsWith("span-")) spanId = nodeParam.slice(5);
24251
+ return {
24252
+ type: "trace",
24253
+ organizationSlug,
24254
+ traceId,
24255
+ spanId
24256
+ };
24257
+ }
24258
+ }
24259
+ if (pathParts.includes("performance") && pathParts.includes("summary")) {
24260
+ const transaction = parsedUrl.searchParams.get("transaction") || void 0;
24261
+ if (transaction) return {
24262
+ type: "unknown",
24263
+ organizationSlug,
24264
+ transaction
24265
+ };
24266
+ }
24267
+ const issuesIndex = pathParts.indexOf("issues");
24268
+ if (issuesIndex !== -1) {
24269
+ const issueId = pathParts[issuesIndex + 1];
24270
+ if (issueId) {
24271
+ const eventsIndex = pathParts.indexOf("events", issuesIndex);
24272
+ if (eventsIndex !== -1) {
24273
+ const eventId = pathParts[eventsIndex + 1];
24274
+ if (eventId) return {
24275
+ type: "event",
24276
+ organizationSlug,
24277
+ issueId,
24278
+ eventId
24279
+ };
24280
+ }
24281
+ return {
24282
+ type: "issue",
24283
+ organizationSlug,
24284
+ issueId
24285
+ };
24286
+ }
24287
+ }
24288
+ return {
24289
+ type: "unknown",
24290
+ organizationSlug
24291
+ };
24292
+ }
24293
+ /**
24294
+ * Checks if a URL appears to be a Sentry profile URL.
24295
+ *
24296
+ * @param url - URL to check
24297
+ * @returns True if the URL looks like a profile URL
24298
+ */
24299
+ function isProfileUrl(url) {
24300
+ try {
24301
+ const parsed = parseSentryUrl(url);
24302
+ return parsed.type === "profile";
24303
+ } catch {
24304
+ return false;
24305
+ }
24306
+ }
24307
+
24308
+ //#endregion
24309
+ //#region ../mcp-core/dist/get-profile-DftJNHhz.js
24310
+ /**
24311
+ * Resolves profile parameters from URL or explicit params.
24312
+ * URL takes precedence if provided and valid.
24313
+ */
24314
+ function resolveProfileParams(params) {
24315
+ if (params.profileUrl) {
24316
+ if (!isProfileUrl(params.profileUrl)) throw new UserInputError("Invalid profile URL. URL must be a Sentry profile URL (containing /profiling/profile/).");
24317
+ const parsed = parseSentryUrl(params.profileUrl);
24318
+ return {
24319
+ organizationSlug: parsed.organizationSlug,
24320
+ projectSlugOrId: parsed.projectSlug ?? params.projectSlugOrId ?? void 0,
24321
+ transactionName: params.transactionName ?? void 0
24322
+ };
24323
+ }
24324
+ if (!params.organizationSlug) throw new UserInputError("Organization slug is required. Provide either a profileUrl or organizationSlug parameter.");
24325
+ return {
24326
+ organizationSlug: params.organizationSlug,
24327
+ projectSlugOrId: params.projectSlugOrId ?? void 0,
24328
+ transactionName: params.transactionName ?? void 0
24329
+ };
24330
+ }
24331
+ var get_profile_default = defineTool({
24332
+ name: "get_profile",
24333
+ skills: ["inspect"],
24334
+ requiredScopes: ["event:read"],
24335
+ requiredCapabilities: ["profiles"],
24336
+ hideInExperimentalMode: true,
24337
+ description: [
24338
+ "Analyze CPU profiling data to identify performance bottlenecks and detect regressions.",
24339
+ "",
24340
+ "USE THIS TOOL WHEN:",
24341
+ "- User asks why a specific endpoint/transaction is slow",
24342
+ "- User wants to understand where CPU time is spent",
24343
+ "- User asks about performance bottlenecks",
24344
+ "- User wants to compare performance between time periods",
24345
+ "- User shares a Sentry profile URL",
24346
+ "",
24347
+ "RETURNS:",
24348
+ "- Hot paths (call stacks consuming the most CPU time)",
24349
+ "- Performance percentiles (p75, p95, p99) for each function",
24350
+ "- User code vs library code breakdown",
24351
+ "- Actionable recommendations for optimization",
24352
+ "- Regression analysis when comparing periods",
24353
+ "",
24354
+ "<examples>",
24355
+ "### Analyze from URL (with transaction name)",
24356
+ "```",
24357
+ "get_profile(",
24358
+ " profileUrl='https://my-org.sentry.io/explore/profiling/profile/backend/flamegraph/?profilerId=abc123',",
24359
+ " transactionName='/api/users'",
24360
+ ")",
24361
+ "```",
24362
+ "",
24363
+ "### Analyze by transaction name",
24364
+ "```",
24365
+ "get_profile(",
24366
+ " organizationSlug='my-org',",
24367
+ " transactionName='/api/users',",
24368
+ " projectSlugOrId='backend'",
24369
+ ")",
24370
+ "```",
24371
+ "",
24372
+ "### Compare performance between periods",
24373
+ "```",
24374
+ "get_profile(",
24375
+ " organizationSlug='my-org',",
24376
+ " transactionName='/api/users',",
24377
+ " projectSlugOrId='backend',",
24378
+ " statsPeriod='7d',",
24379
+ " compareAgainstPeriod='14d'",
24380
+ ")",
24381
+ "```",
24382
+ "</examples>",
24383
+ "",
24384
+ "<hints>",
24385
+ "- Use `focusOnUserCode: true` (default) to filter out library code",
24386
+ "- High p99 relative to p75 indicates inconsistent performance",
24387
+ "- Use compareAgainstPeriod to detect regressions over time",
24388
+ "- Transaction names are case-sensitive",
24389
+ "</hints>"
24390
+ ].join("\n"),
24391
+ inputSchema: {
24392
+ profileUrl: z.string().url().optional().describe("Sentry profile URL. If provided, organization and project are extracted from URL. transactionName is still required."),
24393
+ organizationSlug: ParamOrganizationSlug.optional(),
24394
+ regionUrl: ParamRegionUrl.nullable().default(null),
24395
+ projectSlugOrId: z.union([z.string(), z.number()]).optional().describe("Project slug or numeric ID"),
24396
+ transactionName: z.string().trim().optional().describe("Transaction name (e.g., '/api/users', 'POST /graphql')"),
24397
+ statsPeriod: z.string().default("7d").describe("Time period: '1h', '24h', '7d', '14d', '30d' (default: '7d')"),
24398
+ compareAgainstPeriod: z.string().optional().describe("Compare against this baseline period (e.g., '14d', '30d'). Enables regression detection."),
24399
+ focusOnUserCode: z.boolean().default(true).describe("Show only user code (is_application: true). Set to false to include library code."),
24400
+ maxHotPaths: z.number().int().min(1).max(20).default(10).describe("Number of hot paths to display (1-20, default: 10)")
24401
+ },
24402
+ annotations: {
24403
+ readOnlyHint: true,
24404
+ openWorldHint: false
24405
+ },
24406
+ async handler(params, context$1) {
24407
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
24408
+ const resolved = resolveProfileParams({
24409
+ profileUrl: params.profileUrl,
24410
+ organizationSlug: params.organizationSlug,
24411
+ projectSlugOrId: params.projectSlugOrId,
24412
+ transactionName: params.transactionName
24413
+ });
24414
+ const { organizationSlug, projectSlugOrId, transactionName } = resolved;
24415
+ if (!projectSlugOrId) throw new UserInputError("Project is required. Please provide a projectSlugOrId parameter or include it in the profile URL.");
24416
+ if (!transactionName) throw new UserInputError("Transaction name is required for flamegraph analysis. Please provide a transactionName parameter.");
24417
+ let projectId;
24418
+ if (typeof projectSlugOrId === "number" || isNumericId(String(projectSlugOrId))) {
24419
+ projectId = projectSlugOrId;
24420
+ setTag("project.id", String(projectSlugOrId));
24421
+ } else {
24422
+ const project = await apiService.getProject({
24423
+ organizationSlug,
24424
+ projectSlugOrId: String(projectSlugOrId)
24425
+ });
24426
+ projectId = project.id;
24427
+ setTag("project.slug", String(projectSlugOrId));
24428
+ setTag("project.id", String(project.id));
24429
+ }
24430
+ setTag("organization.slug", organizationSlug);
24431
+ setTag("transaction.name", transactionName);
24432
+ if (params.compareAgainstPeriod) {
24433
+ setTag("baseline.period", params.compareAgainstPeriod);
24434
+ setTag("current.period", params.statsPeriod);
24435
+ const [baselineFlamegraph, currentFlamegraph] = await Promise.all([apiService.getFlamegraph({
24436
+ organizationSlug,
24437
+ projectId,
24438
+ transactionName,
24439
+ statsPeriod: params.compareAgainstPeriod
24440
+ }), apiService.getFlamegraph({
24441
+ organizationSlug,
24442
+ projectId,
24443
+ transactionName,
24444
+ statsPeriod: params.statsPeriod
24445
+ })]);
24446
+ const hasBaselineData = hasProfileData(baselineFlamegraph);
24447
+ const hasCurrentData = hasProfileData(currentFlamegraph);
24448
+ if (!hasBaselineData && !hasCurrentData) return [
24449
+ `# Profile Comparison: ${transactionName}`,
24450
+ "",
24451
+ "## No Profile Data Found",
24452
+ "",
24453
+ `No profiling data found for transaction **${transactionName}** in either time period.`,
24454
+ "",
24455
+ "**Possible reasons:**",
24456
+ "- Transaction name doesn't match exactly (names are case-sensitive)",
24457
+ "- No profiles collected for this transaction",
24458
+ "- Profiling may not be enabled for this project",
24459
+ "",
24460
+ "**Suggestions:**",
24461
+ "- Verify the exact transaction name using search_events",
24462
+ "- Check if profiling is enabled for this project"
24463
+ ].join("\n");
24464
+ if (!hasBaselineData) return [
24465
+ `# Profile Comparison: ${transactionName}`,
24466
+ "",
24467
+ "## Insufficient Baseline Data",
24468
+ "",
24469
+ `No profiling data found for the baseline period (${params.compareAgainstPeriod}).`,
24470
+ `Current period (${params.statsPeriod}) has data.`,
24471
+ "",
24472
+ "**Suggestion:** Try a shorter baseline period or analyze the current period only by removing compareAgainstPeriod."
24473
+ ].join("\n");
24474
+ if (!hasCurrentData) return [
24475
+ `# Profile Comparison: ${transactionName}`,
24476
+ "",
24477
+ "## Insufficient Current Data",
24478
+ "",
24479
+ `No profiling data found for the current period (${params.statsPeriod}).`,
24480
+ `Baseline period (${params.compareAgainstPeriod}) has data.`,
24481
+ "",
24482
+ "**Suggestion:** The transaction may not have been executed recently. Try a longer current period."
24483
+ ].join("\n");
24484
+ return formatFlamegraphComparison(baselineFlamegraph, currentFlamegraph, { focusOnUserCode: params.focusOnUserCode });
24485
+ }
24486
+ const flamegraph = await apiService.getFlamegraph({
24487
+ organizationSlug,
24488
+ projectId,
24489
+ transactionName,
24490
+ statsPeriod: params.statsPeriod
24491
+ });
24492
+ if (!hasProfileData(flamegraph)) return [
24493
+ `# Profile Analysis: ${transactionName}`,
24494
+ "",
24495
+ "## No Profile Data Found",
24496
+ "",
24497
+ `No profiling data found for transaction **${transactionName}** in the last ${params.statsPeriod}.`,
24498
+ "",
24499
+ "**Possible reasons:**",
24500
+ "- Transaction name doesn't match exactly (names are case-sensitive)",
24501
+ "- No profiles collected for this transaction in the time period",
24502
+ "- Profiling may not be enabled for this project",
24503
+ "- Transaction may not have been executed recently",
24504
+ "",
24505
+ "**Suggestions:**",
24506
+ "- Verify the exact transaction name using search_events",
24507
+ "- Try a longer time period (e.g., '30d')",
24508
+ "- Check if profiling is enabled for this project"
24509
+ ].join("\n");
24510
+ return formatFlamegraphAnalysis(flamegraph, {
24511
+ focusOnUserCode: params.focusOnUserCode,
24512
+ maxHotPaths: params.maxHotPaths
24513
+ });
24514
+ }
24515
+ });
24516
+
24517
+ //#endregion
24518
+ //#region ../mcp-core/dist/get-sentry-resource-C5iJbYjO.js
24519
+ /**
24520
+ * Resource types fully supported with API integration.
24521
+ */
24522
+ const FULLY_SUPPORTED_TYPES = [
24523
+ "issue",
24524
+ "event",
24525
+ "trace",
24526
+ "profile"
24527
+ ];
24528
+ /**
24529
+ * Validates and resolves resource parameters from URL or explicit params.
24530
+ */
24531
+ function resolveResourceParams(params) {
24532
+ if (params.url) {
24533
+ const parsed = parseSentryUrl(params.url);
24534
+ return resolveFromParsedUrl(parsed, params);
24535
+ }
24536
+ 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.");
24537
+ if (!FULLY_SUPPORTED_TYPES.includes(params.resourceType)) throw new UserInputError(`Invalid resourceType: ${params.resourceType}. Supported types: ${FULLY_SUPPORTED_TYPES.join(", ")}`);
24538
+ if (!params.organizationSlug) throw new UserInputError("`organizationSlug` is required when using explicit `resourceType`.");
24539
+ const resourceType = params.resourceType;
24540
+ const organizationSlug = params.organizationSlug;
24541
+ switch (resourceType) {
24542
+ case "issue":
24543
+ if (!params.issueId) throw new UserInputError("`issueId` is required for resource type 'issue'.");
24544
+ return {
24545
+ type: "issue",
24546
+ organizationSlug,
24547
+ issueId: params.issueId
24548
+ };
24549
+ case "event":
24550
+ if (!params.issueId || !params.eventId) throw new UserInputError("`issueId` and `eventId` are required for resource type 'event'.");
24551
+ return {
24552
+ type: "event",
24553
+ organizationSlug,
24554
+ issueId: params.issueId,
24555
+ eventId: params.eventId
24556
+ };
24557
+ case "trace":
24558
+ if (!params.traceId) throw new UserInputError("`traceId` is required for resource type 'trace'.");
24559
+ return {
24560
+ type: "trace",
24561
+ organizationSlug,
24562
+ traceId: params.traceId
24563
+ };
24564
+ case "profile":
24565
+ if (!params.projectSlug) throw new UserInputError("`projectSlug` is required for resource type 'profile'.");
24566
+ if (!params.transactionName) throw new UserInputError("`transactionName` is required for resource type 'profile'.");
24567
+ return {
24568
+ type: "profile",
24569
+ organizationSlug,
24570
+ projectSlug: params.projectSlug,
24571
+ profilerId: params.profilerId ?? void 0,
24572
+ transactionName: params.transactionName
24573
+ };
24574
+ }
24575
+ }
24576
+ /**
24577
+ * Resolves params from a parsed Sentry URL.
24578
+ */
24579
+ function resolveFromParsedUrl(parsed, params) {
24580
+ const { type, organizationSlug } = parsed;
24581
+ if (type === "unknown") {
24582
+ 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.`);
24583
+ throw new UserInputError("Could not determine resource type from URL. Supported URL patterns: issues, events, traces, profiles, replays, monitors, and releases.");
24584
+ }
24585
+ switch (type) {
24586
+ case "issue":
24587
+ if (!parsed.issueId) throw new UserInputError("Could not extract issue ID from URL.");
24588
+ return {
24589
+ type: "issue",
24590
+ organizationSlug,
24591
+ issueId: parsed.issueId
24592
+ };
24593
+ case "event":
24594
+ if (!parsed.issueId || !parsed.eventId) throw new UserInputError("Could not extract issue ID and event ID from URL.");
24595
+ return {
24596
+ type: "event",
24597
+ organizationSlug,
24598
+ issueId: parsed.issueId,
24599
+ eventId: parsed.eventId
24600
+ };
24601
+ case "trace":
24602
+ if (!parsed.traceId) throw new UserInputError("Could not extract trace ID from URL.");
24603
+ return {
24604
+ type: "trace",
24605
+ organizationSlug,
24606
+ traceId: parsed.traceId,
24607
+ spanId: parsed.spanId
24608
+ };
24609
+ case "profile": {
24610
+ if (!parsed.projectSlug) throw new UserInputError("Could not extract project slug from profile URL.");
24611
+ const transactionName = params.transactionName ?? void 0;
24612
+ return {
24613
+ type: "profile",
24614
+ organizationSlug,
24615
+ projectSlug: parsed.projectSlug,
24616
+ profilerId: parsed.profilerId,
24617
+ transactionName
24618
+ };
24619
+ }
24620
+ case "replay":
24621
+ if (!parsed.replayId) throw new UserInputError("Could not extract replay ID from URL.");
24622
+ return {
24623
+ type: "replay",
24624
+ organizationSlug,
24625
+ replayId: parsed.replayId
24626
+ };
24627
+ case "monitor":
24628
+ if (!parsed.monitorSlug) throw new UserInputError("Could not extract monitor slug from URL.");
24629
+ return {
24630
+ type: "monitor",
24631
+ organizationSlug,
24632
+ monitorSlug: parsed.monitorSlug,
24633
+ projectSlug: parsed.projectSlug
24634
+ };
24635
+ case "release":
24636
+ if (!parsed.releaseVersion) throw new UserInputError("Could not extract release version from URL.");
24637
+ return {
24638
+ type: "release",
24639
+ organizationSlug,
24640
+ releaseVersion: parsed.releaseVersion
24641
+ };
24642
+ }
24643
+ }
24644
+ /**
24645
+ * Generates a helpful message for recognized but not fully supported resource types.
24646
+ */
24647
+ function generateUnsupportedResourceMessage(resolved) {
24648
+ const { type, organizationSlug } = resolved;
24649
+ switch (type) {
24650
+ case "replay": {
24651
+ const replayUrl = `https://${organizationSlug}.sentry.io/replays/${resolved.replayId}/`;
24652
+ return [
24653
+ "# Replay Detected",
24654
+ "",
24655
+ `**Organization**: ${organizationSlug}`,
24656
+ `**Replay ID**: ${resolved.replayId}`,
24657
+ "",
24658
+ "Session replay support is coming soon. In the meantime:",
24659
+ "",
24660
+ `- **View in Sentry**: [Open Replay](${replayUrl})`,
24661
+ "- **Find related issues**: Use `search_issues` with the replay's time range",
24662
+ `- **Search events**: Use \`search_events\` with query \`replay_id:${resolved.replayId}\` to find events associated with this replay`
24663
+ ].join("\n");
24664
+ }
24665
+ case "monitor": {
24666
+ const monitorPath = resolved.projectSlug ? `${resolved.projectSlug}/${resolved.monitorSlug}` : resolved.monitorSlug;
24667
+ const monitorUrl = `https://${organizationSlug}.sentry.io/crons/${monitorPath}/`;
24668
+ return [
24669
+ "# Cron Monitor Detected",
24670
+ "",
24671
+ `**Organization**: ${organizationSlug}`,
24672
+ `**Monitor**: ${resolved.monitorSlug}`,
24673
+ resolved.projectSlug ? `**Project**: ${resolved.projectSlug}` : "",
24674
+ "",
24675
+ "Cron monitor support is coming soon. In the meantime:",
24676
+ "",
24677
+ `- **View in Sentry**: [Open Monitor](${monitorUrl})`,
24678
+ `- **Search issues**: Use \`search_issues\` with query \`monitor.slug:${resolved.monitorSlug}\` to find issues from this monitor`
24679
+ ].filter(Boolean).join("\n");
24680
+ }
24681
+ case "release": {
24682
+ const releaseUrl = `https://${organizationSlug}.sentry.io/releases/${resolved.releaseVersion}/`;
24683
+ return [
24684
+ "# Release Detected",
24685
+ "",
24686
+ `**Organization**: ${organizationSlug}`,
24687
+ `**Release**: ${resolved.releaseVersion}`,
24688
+ "",
24689
+ "To get release information:",
24690
+ "",
24691
+ `- **View in Sentry**: [Open Release](${releaseUrl})`,
24692
+ `- **Find releases**: Use \`find_releases(organizationSlug='${organizationSlug}')\` to list releases and their details`,
24693
+ `- **Search issues**: Use \`search_issues\` with query \`release:${resolved.releaseVersion}\` to find issues in this release`
24694
+ ].join("\n");
24695
+ }
24696
+ default: return `Unsupported resource type: ${type}`;
24697
+ }
24698
+ }
24699
+ var get_sentry_resource_default = defineTool({
24700
+ name: "get_sentry_resource",
24701
+ skills: ["inspect"],
24702
+ requiredScopes: ["event:read"],
24703
+ experimental: true,
24704
+ description: [
24705
+ "Unified entry point for fetching Sentry resources. Auto-detects resource type from URL or accepts explicit type and identifiers.",
24706
+ "",
24707
+ "USE THIS TOOL WHEN:",
24708
+ "- User provides a Sentry URL (any type: issue, event, trace, profile, replay, monitor, release)",
24709
+ "- User wants to fetch a specific resource by type and ID",
24710
+ "",
24711
+ "FULLY SUPPORTED:",
24712
+ "- **issue**: Fetch issue details by ID",
24713
+ "- **event**: Fetch specific event within an issue",
24714
+ "- **trace**: Fetch trace details (supports span focus from URL)",
24715
+ "- **profile**: Fetch and analyze CPU profiling data",
24716
+ "",
24717
+ "URL RECOGNIZED (returns helpful guidance):",
24718
+ "- **replay**: Session replay URLs",
24719
+ "- **monitor**: Cron monitor URLs",
24720
+ "- **release**: Release URLs",
24721
+ "",
24722
+ "<examples>",
24723
+ "### URL mode (auto-detect type)",
24724
+ "```",
24725
+ "get_sentry_resource(url='https://my-org.sentry.io/issues/PROJECT-123')",
24726
+ "get_sentry_resource(url='https://my-org.sentry.io/explore/traces/trace/abc123...')",
24727
+ "get_sentry_resource(url='https://my-org.sentry.io/replays/def456...')",
24728
+ "```",
24729
+ "",
24730
+ "### Explicit mode - Issue",
24731
+ "```",
24732
+ "get_sentry_resource(",
24733
+ " resourceType='issue',",
24734
+ " organizationSlug='my-org',",
24735
+ " issueId='PROJECT-123'",
24736
+ ")",
24737
+ "```",
24738
+ "",
24739
+ "### Explicit mode - Trace",
24740
+ "```",
24741
+ "get_sentry_resource(",
24742
+ " resourceType='trace',",
24743
+ " organizationSlug='my-org',",
24744
+ " traceId='a4d1aae7216b47ff8117cf4e09ce9d0a'",
24745
+ ")",
24746
+ "```",
24747
+ "</examples>",
24748
+ "",
24749
+ "<hints>",
24750
+ "- URL mode is simplest: just pass the Sentry URL and the tool auto-detects the resource type",
24751
+ "- For explicit mode, required params depend on resourceType:",
24752
+ " - issue: organizationSlug, issueId",
24753
+ " - event: organizationSlug, issueId, eventId",
24754
+ " - trace: organizationSlug, traceId",
24755
+ " - profile: organizationSlug, projectSlug, transactionName",
24756
+ "</hints>"
24757
+ ].join("\n"),
24758
+ inputSchema: {
24759
+ url: z.string().url().optional().describe("Sentry URL. Auto-detects resource type (issue, event, trace, profile, replay, monitor, release) from URL pattern."),
24760
+ resourceType: z.enum([
24761
+ "issue",
24762
+ "event",
24763
+ "trace",
24764
+ "profile"
24765
+ ]).optional().describe("Resource type when not using URL. Required params depend on type."),
24766
+ organizationSlug: ParamOrganizationSlug.optional(),
24767
+ regionUrl: ParamRegionUrl.nullable().default(null),
24768
+ issueId: z.string().toUpperCase().trim().optional().describe("Issue ID (e.g., 'PROJECT-123'). Required for issue/event types."),
24769
+ eventId: z.string().trim().optional().describe("Event ID. Required for event type."),
24770
+ traceId: z.string().trim().optional().describe("Trace ID (32-char hex string). Required for trace type."),
24771
+ projectSlug: z.string().toLowerCase().trim().optional().describe("Project slug. Required for profile type."),
24772
+ profilerId: z.string().trim().optional().describe("Profiler ID (optional for profile type)."),
24773
+ transactionName: z.string().trim().optional().describe("Transaction name (e.g., 'GET /api/users'). Required for profile type.")
24774
+ },
24775
+ annotations: {
24776
+ readOnlyHint: true,
24777
+ openWorldHint: true
24778
+ },
24779
+ async handler(params, context$1) {
24780
+ const resolved = resolveResourceParams({
24781
+ url: params.url,
24782
+ resourceType: params.resourceType,
24783
+ organizationSlug: params.organizationSlug,
24784
+ issueId: params.issueId,
24785
+ eventId: params.eventId,
24786
+ traceId: params.traceId,
24787
+ projectSlug: params.projectSlug,
24788
+ profilerId: params.profilerId,
24789
+ transactionName: params.transactionName
24790
+ });
24791
+ setTag("resource.type", resolved.type);
24792
+ setTag("organization.slug", resolved.organizationSlug);
24793
+ if (resolved.type === "replay" || resolved.type === "monitor" || resolved.type === "release") return generateUnsupportedResourceMessage(resolved);
24794
+ switch (resolved.type) {
24795
+ case "issue": return get_issue_details_default.handler({
24796
+ organizationSlug: resolved.organizationSlug,
24797
+ issueId: resolved.issueId,
24798
+ regionUrl: params.regionUrl
24799
+ }, context$1);
24800
+ case "event": return get_issue_details_default.handler({
24801
+ organizationSlug: resolved.organizationSlug,
24802
+ issueId: resolved.issueId,
24803
+ eventId: resolved.eventId,
24804
+ regionUrl: params.regionUrl
24805
+ }, context$1);
24806
+ case "trace": return get_trace_details_default.handler({
24807
+ organizationSlug: resolved.organizationSlug,
24808
+ traceId: resolved.traceId,
24809
+ regionUrl: params.regionUrl
24810
+ }, context$1);
24811
+ case "profile": return get_profile_default.handler({
24812
+ organizationSlug: resolved.organizationSlug,
24813
+ projectSlugOrId: resolved.projectSlug,
24814
+ transactionName: resolved.transactionName,
24815
+ regionUrl: params.regionUrl,
24816
+ statsPeriod: "7d",
24817
+ focusOnUserCode: true,
24818
+ maxHotPaths: 10
24819
+ }, context$1);
24820
+ default: {
24821
+ const _exhaustiveCheck = resolved.type;
24822
+ throw new Error(`Unhandled resource type: ${_exhaustiveCheck}`);
24823
+ }
24824
+ }
24825
+ }
24826
+ });
24827
+
24828
+ //#endregion
24829
+ //#region ../mcp-core/dist/error-handling-edUevt-o.js
23330
24830
  /**
23331
24831
  * Type guard to identify user input validation errors.
23332
24832
  */
@@ -23417,7 +24917,7 @@ async function formatErrorForUser(error) {
23417
24917
  }
23418
24918
 
23419
24919
  //#endregion
23420
- //#region ../mcp-core/dist/constraint-helpers-D80X658i.js
24920
+ //#region ../mcp-core/dist/constraint-helpers-8S_8iDNk.js
23421
24921
  /**
23422
24922
  * Determines which tool parameter keys should be filtered out of the schema
23423
24923
  * because they will be injected from constraints.
@@ -23441,7 +24941,7 @@ async function formatErrorForUser(error) {
23441
24941
  */
23442
24942
  function getConstraintKeysToFilter(constraints, toolInputSchema) {
23443
24943
  return Object.entries(constraints).flatMap(([key, value]) => {
23444
- if (!value) return [];
24944
+ if (!value || typeof value !== "string") return [];
23445
24945
  const keys = [];
23446
24946
  if (key in toolInputSchema) keys.push(key);
23447
24947
  if (key === "projectSlug" && "projectSlugOrId" in toolInputSchema && !("projectSlugOrId" in constraints && constraints.projectSlugOrId)) keys.push("projectSlugOrId");
@@ -23470,7 +24970,7 @@ function getConstraintKeysToFilter(constraints, toolInputSchema) {
23470
24970
  */
23471
24971
  function getConstraintParametersToInject(constraints, toolInputSchema) {
23472
24972
  return Object.fromEntries(Object.entries(constraints).flatMap(([key, value]) => {
23473
- if (!value) return [];
24973
+ if (!value || typeof value !== "string") return [];
23474
24974
  const entries = [];
23475
24975
  if (key in toolInputSchema) entries.push([key, value]);
23476
24976
  if (key === "projectSlug" && "projectSlugOrId" in toolInputSchema && !("projectSlugOrId" in constraints && constraints.projectSlugOrId)) entries.push(["projectSlugOrId", value]);
@@ -23479,7 +24979,7 @@ function getConstraintParametersToInject(constraints, toolInputSchema) {
23479
24979
  }
23480
24980
 
23481
24981
  //#endregion
23482
- //#region ../mcp-core/dist/server-CbkVklfg.js
24982
+ //#region ../mcp-core/dist/server-CECYn4UB.js
23483
24983
  /**
23484
24984
  * Format tool calls into a readable trace
23485
24985
  */
@@ -23542,7 +25042,7 @@ var handler_default$3 = defineTool({
23542
25042
  async handler(params, context$1) {
23543
25043
  const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
23544
25044
  const toolsToExclude = new Set(["use_sentry", ...SIMPLE_REPLACEMENT_TOOLS]);
23545
- const toolsForAgent = Object.fromEntries(Object.entries(tools_default).filter(([key]) => !toolsToExclude.has(key)));
25045
+ const toolsForAgent = Object.fromEntries(Object.entries(tools_default).filter(([key, tool$1]) => !toolsToExclude.has(key) && isToolVisibleInMode(tool$1, context$1.experimentalMode ?? false)));
23546
25046
  const server$1 = buildServer({
23547
25047
  context: context$1,
23548
25048
  tools: toolsForAgent
@@ -23614,7 +25114,9 @@ var tools_default = {
23614
25114
  use_sentry: handler_default$3,
23615
25115
  list_issues: list_issues_default,
23616
25116
  list_events: list_events_default,
23617
- list_issue_events: list_issue_events_default
25117
+ list_issue_events: list_issue_events_default,
25118
+ get_profile: get_profile_default,
25119
+ get_sentry_resource: get_sentry_resource_default
23618
25120
  };
23619
25121
  /**
23620
25122
  * Creates and configures a complete MCP server with Sentry instrumentation.
@@ -23652,7 +25154,7 @@ var tools_default = {
23652
25154
  * return createMcpHandler(server, { route: "/mcp" })(request, env, ctx);
23653
25155
  * ```
23654
25156
  */
23655
- function buildServer({ context: context$1, agentMode = false, tools: customTools }) {
25157
+ function buildServer({ context: context$1, agentMode = false, experimentalMode = false, tools: customTools }) {
23656
25158
  const server$1 = new McpServer({
23657
25159
  name: MCP_SERVER_NAME,
23658
25160
  version: LIB_VERSION
@@ -23661,6 +25163,7 @@ function buildServer({ context: context$1, agentMode = false, tools: customTools
23661
25163
  server: server$1,
23662
25164
  context: context$1,
23663
25165
  agentMode,
25166
+ experimentalMode,
23664
25167
  tools: customTools
23665
25168
  });
23666
25169
  return wrapMcpServerWithSentry(server$1);
@@ -23674,13 +25177,14 @@ function buildServer({ context: context$1, agentMode = false, tools: customTools
23674
25177
  *
23675
25178
  * In agent mode, only the use_sentry tool is registered, bypassing authorization checks.
23676
25179
  */
23677
- function configureServer({ server: server$1, context: context$1, agentMode = false, tools: customTools }) {
25180
+ function configureServer({ server: server$1, context: context$1, agentMode = false, experimentalMode = false, tools: customTools }) {
23678
25181
  let toolsToRegister = agentMode ? { use_sentry: tools_default.use_sentry } : customTools ?? tools_default;
23679
25182
  if (!agentMode && !customTools) {
23680
25183
  const hasAgent = hasAgentProvider();
23681
25184
  const toolsToExclude = new Set(hasAgent ? SIMPLE_REPLACEMENT_TOOLS : AGENT_DEPENDENT_TOOLS);
23682
25185
  toolsToRegister = Object.fromEntries(Object.entries(toolsToRegister).filter(([key]) => !toolsToExclude.has(key)));
23683
25186
  }
25187
+ if (!agentMode) toolsToRegister = Object.fromEntries(Object.entries(toolsToRegister).filter(([, tool$1]) => isToolVisibleInMode(tool$1, experimentalMode)));
23684
25188
  const grantedSkills = context$1.grantedSkills ? new Set(context$1.grantedSkills) : void 0;
23685
25189
  server$1.server.onerror = (error) => {
23686
25190
  const transportLogOptions = {
@@ -23719,9 +25223,15 @@ function configureServer({ server: server$1, context: context$1, agentMode = fal
23719
25223
  }
23720
25224
  if (!allowed) continue;
23721
25225
  if (toolKey === "find_organizations" && context$1.constraints.organizationSlug || toolKey === "find_projects" && context$1.constraints.projectSlug) continue;
25226
+ if (experimentalMode && context$1.constraints.projectSlug && context$1.constraints.projectCapabilities && tool$1.requiredCapabilities?.length) {
25227
+ const caps = context$1.constraints.projectCapabilities;
25228
+ const hasAllCapabilities = tool$1.requiredCapabilities.every((cap) => caps[cap] === true);
25229
+ if (!hasAllCapabilities) continue;
25230
+ }
23722
25231
  const constraintKeysToFilter = new Set(getConstraintKeysToFilter(context$1.constraints, tool$1.inputSchema));
23723
25232
  const filteredInputSchema = Object.fromEntries(Object.entries(tool$1.inputSchema).filter(([key]) => !constraintKeysToFilter.has(key)));
23724
- server$1.tool(tool$1.name, tool$1.description, filteredInputSchema, tool$1.annotations, async (params, extra) => {
25233
+ const resolvedDescription = resolveDescription(tool$1.description, { experimentalMode });
25234
+ server$1.tool(tool$1.name, resolvedDescription, filteredInputSchema, tool$1.annotations, async (params, extra) => {
23725
25235
  const activeSpan = getActiveSpan();
23726
25236
  if (activeSpan) {
23727
25237
  if (context$1.constraints.organizationSlug) activeSpan.setAttribute("sentry-mcp.constraint-organization", context$1.constraints.organizationSlug);
@@ -23761,7 +25271,7 @@ function configureServer({ server: server$1, context: context$1, agentMode = fal
23761
25271
  }
23762
25272
 
23763
25273
  //#endregion
23764
- //#region ../mcp-core/dist/sentry-CTKJG5Bs.js
25274
+ //#region ../mcp-core/dist/sentry-BuGpDJQH.js
23765
25275
  const SCRUB_PATTERNS = [
23766
25276
  {
23767
25277
  pattern: /\bsk-[a-zA-Z0-9]{48}\b/g,
@@ -23904,14 +25414,71 @@ setProviderBaseUrls({
23904
25414
  });
23905
25415
  if (cfg.openaiModel) process.env.OPENAI_MODEL = cfg.openaiModel;
23906
25416
  if (cfg.anthropicModel) process.env.ANTHROPIC_MODEL = cfg.anthropicModel;
25417
+ function hasProviderConflict() {
25418
+ const hasAnthropic = Boolean(process.env.ANTHROPIC_API_KEY);
25419
+ const hasOpenAI = Boolean(process.env.OPENAI_API_KEY);
25420
+ const hasExplicitProvider = cfg.agentProvider || process.env.EMBEDDED_AGENT_PROVIDER;
25421
+ return hasAnthropic && hasOpenAI && !hasExplicitProvider;
25422
+ }
25423
+ function getConfiguredProvider() {
25424
+ return cfg.agentProvider || process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
25425
+ }
25426
+ function hasProviderMismatch() {
25427
+ const configured = getConfiguredProvider();
25428
+ if (!configured) return { mismatch: false };
25429
+ const hasAnthropic = Boolean(process.env.ANTHROPIC_API_KEY);
25430
+ const hasOpenAI = Boolean(process.env.OPENAI_API_KEY);
25431
+ if (configured === "openai" && !hasOpenAI && hasAnthropic) return {
25432
+ mismatch: true,
25433
+ configured: "openai",
25434
+ availableKey: "ANTHROPIC_API_KEY"
25435
+ };
25436
+ if (configured === "anthropic" && !hasAnthropic && hasOpenAI) return {
25437
+ mismatch: true,
25438
+ configured: "anthropic",
25439
+ availableKey: "OPENAI_API_KEY"
25440
+ };
25441
+ return { mismatch: false };
25442
+ }
25443
+ function getProviderSource() {
25444
+ if (cli.agentProvider) return "explicitly configured";
25445
+ if (process.env.EMBEDDED_AGENT_PROVIDER) return "from EMBEDDED_AGENT_PROVIDER";
25446
+ return "auto-detected";
25447
+ }
23907
25448
  const resolvedProvider = getResolvedProviderType();
23908
25449
  if (!resolvedProvider) {
23909
- console.warn("Warning: No LLM API key found (OPENAI_API_KEY or ANTHROPIC_API_KEY).");
23910
- console.warn("The following AI-powered search tools will be unavailable:");
23911
- console.warn(" - search_events, search_issues, search_issue_events, use_sentry");
23912
- console.warn("Use list_issues and list_events for direct Sentry query syntax instead.");
25450
+ const mismatchInfo = hasProviderMismatch();
25451
+ if (hasProviderConflict()) {
25452
+ console.warn("Warning: Both ANTHROPIC_API_KEY and OPENAI_API_KEY are set, but no provider is explicitly configured.");
25453
+ console.warn("Please set EMBEDDED_AGENT_PROVIDER='openai' or 'anthropic' to specify which provider to use.");
25454
+ console.warn("AI-powered search tools will be unavailable until a provider is selected.");
25455
+ } else if (mismatchInfo.mismatch) {
25456
+ const expectedKey = mismatchInfo.configured === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
25457
+ const configuredViaCliFlag = Boolean(cli.agentProvider);
25458
+ const providerSetting = configuredViaCliFlag ? `--agent-provider=${mismatchInfo.configured}` : `EMBEDDED_AGENT_PROVIDER='${mismatchInfo.configured}'`;
25459
+ const changeProviderHint = configuredViaCliFlag ? "Change --agent-provider to match your available API key" : "Change EMBEDDED_AGENT_PROVIDER to match your available API key";
25460
+ console.warn(`Warning: ${providerSetting} but ${expectedKey} is not set.`);
25461
+ console.warn(`Found ${mismatchInfo.availableKey} instead. Either:`);
25462
+ console.warn(` - Set ${expectedKey} to use the ${mismatchInfo.configured} provider, or`);
25463
+ console.warn(` - ${changeProviderHint}`);
25464
+ console.warn("AI-powered search tools will be unavailable until this is resolved.");
25465
+ } else {
25466
+ console.warn("Warning: No LLM API key found (OPENAI_API_KEY or ANTHROPIC_API_KEY).");
25467
+ console.warn("The following AI-powered search tools will be unavailable:");
25468
+ console.warn(" - search_events, search_issues, search_issue_events, use_sentry");
25469
+ console.warn("Use list_issues and list_events for direct Sentry query syntax instead.");
25470
+ }
25471
+ console.warn("");
25472
+ } else {
25473
+ const providerSource = getProviderSource();
25474
+ console.warn(`Using ${resolvedProvider} for AI-powered search tools (${providerSource}).`);
25475
+ if (providerSource === "auto-detected") {
25476
+ console.warn("Deprecation warning: Auto-detection of LLM provider is deprecated.");
25477
+ console.warn(`Please set EMBEDDED_AGENT_PROVIDER='${resolvedProvider}' explicitly.`);
25478
+ console.warn("Auto-detection will be removed in a future release.");
25479
+ }
23913
25480
  console.warn("");
23914
- } else console.warn(`Using ${resolvedProvider} for AI-powered search tools.`);
25481
+ }
23915
25482
  Sentry.init({
23916
25483
  dsn: cfg.sentryDsn,
23917
25484
  sendDefaultPii: true,
@@ -23921,6 +25488,7 @@ Sentry.init({
23921
25488
  "mcp.server_version": LIB_VERSION,
23922
25489
  "mcp.transport": "stdio",
23923
25490
  "mcp.agent_mode": cli.agent ? "true" : "false",
25491
+ "mcp.experimental_mode": cli.experimental ? "true" : "false",
23924
25492
  "sentry.host": cfg.sentryHost,
23925
25493
  "mcp.mcp-url": cfg.mcpUrl
23926
25494
  } },
@@ -23940,6 +25508,10 @@ if (cli.agent) {
23940
25508
  console.warn("The use_sentry tool provides access to all Sentry operations through natural language.");
23941
25509
  console.warn("");
23942
25510
  }
25511
+ if (cli.experimental) {
25512
+ console.warn("Experimental mode enabled: Experimental tools are available.");
25513
+ console.warn("");
25514
+ }
23943
25515
  const SENTRY_TIMEOUT = 5e3;
23944
25516
  async function shutdown(signal) {
23945
25517
  console.error(`${signal} received, shutting down...`);
@@ -23969,11 +25541,14 @@ const context = {
23969
25541
  },
23970
25542
  sentryHost: cfg.sentryHost,
23971
25543
  mcpUrl: cfg.mcpUrl,
23972
- openaiBaseUrl: cfg.openaiBaseUrl
25544
+ openaiBaseUrl: cfg.openaiBaseUrl,
25545
+ agentMode: cli.agent,
25546
+ experimentalMode: cli.experimental
23973
25547
  };
23974
25548
  const server = buildServer({
23975
25549
  context,
23976
- agentMode: cli.agent
25550
+ agentMode: cli.agent,
25551
+ experimentalMode: cli.experimental
23977
25552
  });
23978
25553
  startStdio(server, context).catch(async (err) => {
23979
25554
  console.error("Server error:", err);