@sentry/mcp-server 0.25.0 → 0.27.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 (56) 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.cjs +1 -1
  8. package/dist/cli/resolve.d.cts +1 -1
  9. package/dist/cli/resolve.d.ts +1 -1
  10. package/dist/cli/resolve.js +1 -1
  11. package/dist/cli/types.d.cts +1 -1
  12. package/dist/cli/types.d.ts +1 -1
  13. package/dist/cli/usage.cjs +1 -1
  14. package/dist/cli/usage.js +1 -1
  15. package/dist/{config-BoFBjXRq-CGHqlnJ9.cjs → config-CEjP2CYO-CZKUamRu.cjs} +2 -2
  16. package/dist/{config-BoFBjXRq-CGHqlnJ9.cjs.map → config-CEjP2CYO-CZKUamRu.cjs.map} +1 -1
  17. package/dist/{config-BoFBjXRq-CMdBQOkQ.js → config-CEjP2CYO-DNCUeo0R.js} +2 -2
  18. package/dist/{config-BoFBjXRq-CMdBQOkQ.js.map → config-CEjP2CYO-DNCUeo0R.js.map} +1 -1
  19. package/dist/config-CwE3_vz4.cjs +7 -0
  20. package/dist/{config-BEgU9ylR.js → config-HqPAzoGg.js} +1 -1
  21. package/dist/index.cjs +2573 -243
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.js +2571 -241
  24. package/dist/index.js.map +1 -1
  25. package/dist/{parse-46t_fITC.js → parse-B9o4fVyT.js} +12 -1
  26. package/dist/parse-B9o4fVyT.js.map +1 -0
  27. package/dist/{parse-BjIH83SX.cjs → parse-c_3eNB2Z.cjs} +12 -1
  28. package/dist/parse-c_3eNB2Z.cjs.map +1 -0
  29. package/dist/{resolve-CdTP9riu.cjs → resolve-DFUPLqHE.cjs} +11 -1
  30. package/dist/resolve-DFUPLqHE.cjs.map +1 -0
  31. package/dist/{resolve-Cg3SH2zt.js → resolve-DpUhCbfh.js} +11 -1
  32. package/dist/resolve-DpUhCbfh.js.map +1 -0
  33. package/dist/{stdio-CwqdTAhY.js → stdio-D7VKnapT.js} +3 -3
  34. package/dist/{stdio-CwqdTAhY.js.map → stdio-D7VKnapT.js.map} +1 -1
  35. package/dist/{stdio-Cl-Ib8bu.cjs → stdio-Dv01oTty.cjs} +3 -3
  36. package/dist/{stdio-Cl-Ib8bu.cjs.map → stdio-Dv01oTty.cjs.map} +1 -1
  37. package/dist/transports/stdio.cjs +1 -1
  38. package/dist/transports/stdio.js +1 -1
  39. package/dist/{types-D5f00mg9.d.ts → types--Ysz5ZMd.d.cts} +12 -1
  40. package/dist/types--Ysz5ZMd.d.cts.map +1 -0
  41. package/dist/{types-DpmAC3S8.d.cts → types-BlGRNCea.d.ts} +12 -1
  42. package/dist/types-BlGRNCea.d.ts.map +1 -0
  43. package/dist/{usage-DD58xBe3.cjs → usage-D9Tpyb5N.cjs} +15 -5
  44. package/dist/usage-D9Tpyb5N.cjs.map +1 -0
  45. package/dist/{usage-BzYvqaru.js → usage-DR57Krum.js} +15 -5
  46. package/dist/usage-DR57Krum.js.map +1 -0
  47. package/package.json +6 -6
  48. package/dist/config-rZ982IEm.cjs +0 -7
  49. package/dist/parse-46t_fITC.js.map +0 -1
  50. package/dist/parse-BjIH83SX.cjs.map +0 -1
  51. package/dist/resolve-CdTP9riu.cjs.map +0 -1
  52. package/dist/resolve-Cg3SH2zt.js.map +0 -1
  53. package/dist/types-D5f00mg9.d.ts.map +0 -1
  54. package/dist/types-DpmAC3S8.d.cts.map +0 -1
  55. package/dist/usage-BzYvqaru.js.map +0 -1
  56. package/dist/usage-DD58xBe3.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { ALL_SKILLS, SKILLS, finalize, getIssueUrl, getIssuesSearchUrl, getTraceUrl, isEnabledBySkills, isSentryHost } from "./resolve-Cg3SH2zt.js";
3
- import { LIB_VERSION, USER_AGENT, startStdio } from "./stdio-CwqdTAhY.js";
4
- import { RECOMMENDED_FIELDS, systemPrompt } from "./config-BoFBjXRq-CMdBQOkQ.js";
5
- import { buildUsage } from "./usage-BzYvqaru.js";
6
- import { merge, parseArgv, parseEnv } from "./parse-46t_fITC.js";
2
+ import { ALL_SKILLS, SKILLS, finalize, getIssueUrl, getIssuesSearchUrl, getTraceUrl, isEnabledBySkills, isSentryHost } from "./resolve-DpUhCbfh.js";
3
+ import { LIB_VERSION, USER_AGENT, startStdio } from "./stdio-D7VKnapT.js";
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";
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-BO1YtJIJ.js
1786
+ //#region ../mcp-core/dist/schema-VoUcElu5.js
1787
1787
  /**
1788
1788
  * Schema for Sentry API error responses.
1789
1789
  *
@@ -2206,6 +2206,31 @@ const EventAttachmentSchema = z.object({
2206
2206
  });
2207
2207
  const EventAttachmentListSchema = z.array(EventAttachmentSchema);
2208
2208
  /**
2209
+ * Schema for individual tag values within an issue's tag distribution.
2210
+ *
2211
+ * Represents a single value's occurrence count and percentage within a tag.
2212
+ */
2213
+ const IssueTagValueSchema = z.object({
2214
+ key: z.string().nullable().optional(),
2215
+ name: z.string().nullable().optional(),
2216
+ value: z.string().nullable(),
2217
+ count: z.number(),
2218
+ lastSeen: z.string().datetime().nullable().optional(),
2219
+ firstSeen: z.string().datetime().nullable().optional()
2220
+ });
2221
+ /**
2222
+ * Schema for Sentry issue tag values response.
2223
+ *
2224
+ * Contains aggregate counts of unique tag values for an issue,
2225
+ * useful for understanding the distribution of tags like URL, browser, etc.
2226
+ */
2227
+ const IssueTagValuesSchema = z.object({
2228
+ key: z.string(),
2229
+ name: z.string(),
2230
+ totalValues: z.number(),
2231
+ topValues: z.array(IssueTagValueSchema)
2232
+ });
2233
+ /**
2209
2234
  * Schema for Sentry trace metadata response.
2210
2235
  *
2211
2236
  * Contains high-level statistics about a trace including span counts,
@@ -2495,7 +2520,7 @@ function createApiError(message, status, detail, responseBody) {
2495
2520
  }
2496
2521
 
2497
2522
  //#endregion
2498
- //#region ../mcp-core/dist/client-DsM0pHqr.js
2523
+ //#region ../mcp-core/dist/client-DXmt8umX.js
2499
2524
  /**
2500
2525
  * Mapping of common network error codes to user-friendly messages.
2501
2526
  * These help users understand and resolve connection issues.
@@ -2593,6 +2618,27 @@ var SentryApiService = class {
2593
2618
  return isSentryHost(this.host);
2594
2619
  }
2595
2620
  /**
2621
+ * Validates and applies time parameters to a URLSearchParams object.
2622
+ *
2623
+ * Enforces mutual exclusivity between relative (statsPeriod) and
2624
+ * absolute (start/end) time ranges, and ensures start/end are paired.
2625
+ *
2626
+ * @param queryParams The URLSearchParams to modify
2627
+ * @param statsPeriod Relative time period (e.g., "24h", "7d")
2628
+ * @param start Absolute start time (ISO 8601)
2629
+ * @param end Absolute end time (ISO 8601)
2630
+ * @throws {ApiValidationError} If time parameters are invalid
2631
+ */
2632
+ applyTimeParams(queryParams, statsPeriod, start, end) {
2633
+ if (statsPeriod && (start || end)) throw new ApiValidationError("Cannot use both statsPeriod and start/end parameters. Use either statsPeriod for relative time or start/end for absolute time.");
2634
+ if (start && !end || !start && end) throw new ApiValidationError("Both start and end parameters must be provided together for absolute time ranges.");
2635
+ if (statsPeriod) queryParams.set("statsPeriod", statsPeriod);
2636
+ else if (start && end) {
2637
+ queryParams.set("start", start);
2638
+ queryParams.set("end", end);
2639
+ }
2640
+ }
2641
+ /**
2596
2642
  * Internal method for making authenticated requests to Sentry API.
2597
2643
  *
2598
2644
  * Handles:
@@ -3187,13 +3233,7 @@ var SentryApiService = class {
3187
3233
  const searchQuery = new URLSearchParams();
3188
3234
  if (dataset) searchQuery.set("dataset", dataset);
3189
3235
  if (project) searchQuery.set("project", project);
3190
- if (statsPeriod && (start || end)) throw new ApiValidationError("Cannot use both statsPeriod and start/end parameters. Use either statsPeriod for relative time or start/end for absolute time.");
3191
- if (start && !end || !start && end) throw new ApiValidationError("Both start and end parameters must be provided together for absolute time ranges.");
3192
- if (statsPeriod) searchQuery.set("statsPeriod", statsPeriod);
3193
- else if (start && end) {
3194
- searchQuery.set("start", start);
3195
- searchQuery.set("end", end);
3196
- }
3236
+ this.applyTimeParams(searchQuery, statsPeriod, start, end);
3197
3237
  if (useCache !== void 0) searchQuery.set("useCache", useCache ? "1" : "0");
3198
3238
  if (useFlagsBackend !== void 0) searchQuery.set("useFlagsBackend", useFlagsBackend ? "1" : "0");
3199
3239
  const body = await this.requestJSON(searchQuery.toString() ? `/organizations/${organizationSlug}/tags/?${searchQuery.toString()}` : `/organizations/${organizationSlug}/tags/`, void 0, opts);
@@ -3233,13 +3273,7 @@ var SentryApiService = class {
3233
3273
  queryParams.set("itemType", itemType);
3234
3274
  queryParams.set("attributeType", attributeType);
3235
3275
  if (project) queryParams.set("project", project);
3236
- if (statsPeriod && (start || end)) throw new ApiValidationError("Cannot use both statsPeriod and start/end parameters. Use either statsPeriod for relative time or start/end for absolute time.");
3237
- if (start && !end || !start && end) throw new ApiValidationError("Both start and end parameters must be provided together for absolute time ranges.");
3238
- if (statsPeriod) queryParams.set("statsPeriod", statsPeriod);
3239
- else if (start && end) {
3240
- queryParams.set("start", start);
3241
- queryParams.set("end", end);
3242
- }
3276
+ this.applyTimeParams(queryParams, statsPeriod, start, end);
3243
3277
  const url = `/organizations/${organizationSlug}/trace-items/attributes/?${queryParams.toString()}`;
3244
3278
  const body = await this.requestJSON(url, void 0, opts);
3245
3279
  return Array.isArray(body) ? body : [];
@@ -3293,6 +3327,35 @@ var SentryApiService = class {
3293
3327
  const body = await this.requestJSON(`/organizations/${organizationSlug}/issues/${issueId}/`, void 0, opts);
3294
3328
  return IssueSchema.parse(body);
3295
3329
  }
3330
+ /**
3331
+ * Retrieves tag value distribution for a specific issue.
3332
+ *
3333
+ * Returns aggregate counts of unique tag values, useful for understanding
3334
+ * how an issue is distributed across different tag values (e.g., URLs,
3335
+ * browsers, environments).
3336
+ *
3337
+ * @param params Query parameters
3338
+ * @param params.organizationSlug Organization identifier
3339
+ * @param params.issueId Issue identifier (short ID or numeric ID)
3340
+ * @param params.tagKey Tag key to get values for (e.g., "url", "browser", "environment")
3341
+ * @param opts Request options
3342
+ * @returns Tag value distribution with counts and percentages
3343
+ *
3344
+ * @example
3345
+ * ```typescript
3346
+ * const tagValues = await apiService.getIssueTagValues({
3347
+ * organizationSlug: "my-org",
3348
+ * issueId: "PROJECT-123",
3349
+ * tagKey: "url"
3350
+ * });
3351
+ * console.log(`Total unique values: ${tagValues.totalValues}`);
3352
+ * tagValues.topValues.forEach(v => console.log(`${v.value}: ${v.count}`));
3353
+ * ```
3354
+ */
3355
+ async getIssueTagValues({ organizationSlug, issueId, tagKey }, opts) {
3356
+ const body = await this.requestJSON(`/organizations/${organizationSlug}/issues/${issueId}/tags/${tagKey}/`, void 0, opts);
3357
+ return IssueTagValuesSchema.parse(body);
3358
+ }
3296
3359
  async getEventForIssue({ organizationSlug, issueId, eventId }, opts) {
3297
3360
  const body = await this.requestJSON(`/organizations/${organizationSlug}/issues/${issueId}/events/${eventId}/`, void 0, opts);
3298
3361
  const parseResult = EventSchema.safeParse(body);
@@ -3326,6 +3389,26 @@ var SentryApiService = class {
3326
3389
  eventId: "latest"
3327
3390
  }, opts);
3328
3391
  }
3392
+ /**
3393
+ * Lists events for a specific issue.
3394
+ * Uses the issue-specific endpoint which already filters by issue ID.
3395
+ *
3396
+ * @see https://docs.sentry.io/api/events/list-an-issues-events/
3397
+ */
3398
+ async listEventsForIssue({ organizationSlug, issueId, query, limit = 50, sort, statsPeriod, start, end, full = false }, opts) {
3399
+ const params = new URLSearchParams();
3400
+ if (query) params.append("query", query);
3401
+ params.append("per_page", String(limit));
3402
+ if (sort) params.append("sort", sort);
3403
+ if (statsPeriod) params.append("statsPeriod", statsPeriod);
3404
+ else if (start && end) {
3405
+ params.append("start", start);
3406
+ params.append("end", end);
3407
+ }
3408
+ if (full) params.append("full", "true");
3409
+ const apiUrl = `/organizations/${organizationSlug}/issues/${issueId}/events/?${params.toString()}`;
3410
+ return await this.requestJSON(apiUrl, void 0, opts);
3411
+ }
3329
3412
  async listEventAttachments({ organizationSlug, projectSlug, eventId }, opts) {
3330
3413
  const body = await this.requestJSON(`/projects/${organizationSlug}/${projectSlug}/events/${eventId}/attachments/`, void 0, opts);
3331
3414
  return EventAttachmentListSchema.parse(body);
@@ -3413,13 +3496,7 @@ var SentryApiService = class {
3413
3496
  queryParams.set("per_page", params.limit.toString());
3414
3497
  queryParams.set("query", params.query);
3415
3498
  queryParams.set("dataset", "errors");
3416
- if (params.statsPeriod && (params.start || params.end)) throw new ApiValidationError("Cannot use both statsPeriod and start/end parameters. Use either statsPeriod for relative time or start/end for absolute time.");
3417
- if (params.start && !params.end || !params.start && params.end) throw new ApiValidationError("Both start and end parameters must be provided together for absolute time ranges.");
3418
- if (params.statsPeriod) queryParams.set("statsPeriod", params.statsPeriod);
3419
- else if (params.start && params.end) {
3420
- queryParams.set("start", params.start);
3421
- queryParams.set("end", params.end);
3422
- }
3499
+ this.applyTimeParams(queryParams, params.statsPeriod, params.start, params.end);
3423
3500
  if (params.projectId) queryParams.set("project", params.projectId);
3424
3501
  let apiSort = params.sort;
3425
3502
  if (params.sort?.includes("(") && !params.sort?.includes("equation|")) {
@@ -3447,13 +3524,7 @@ var SentryApiService = class {
3447
3524
  queryParams.set("per_page", params.limit.toString());
3448
3525
  queryParams.set("query", params.query);
3449
3526
  queryParams.set("dataset", params.dataset);
3450
- if (params.statsPeriod && (params.start || params.end)) throw new ApiValidationError("Cannot use both statsPeriod and start/end parameters. Use either statsPeriod for relative time or start/end for absolute time.");
3451
- if (params.start && !params.end || !params.start && params.end) throw new ApiValidationError("Both start and end parameters must be provided together for absolute time ranges.");
3452
- if (params.statsPeriod) queryParams.set("statsPeriod", params.statsPeriod);
3453
- else if (params.start && params.end) {
3454
- queryParams.set("start", params.start);
3455
- queryParams.set("end", params.end);
3456
- }
3527
+ this.applyTimeParams(queryParams, params.statsPeriod, params.start, params.end);
3457
3528
  if (params.projectId) queryParams.set("project", params.projectId);
3458
3529
  if (params.dataset === "spans") queryParams.set("sampling", "NORMAL");
3459
3530
  let apiSort = params.sort;
@@ -3616,7 +3687,7 @@ function validateRegionUrl(regionUrl, baseHost) {
3616
3687
  }
3617
3688
 
3618
3689
  //#endregion
3619
- //#region ../mcp-core/dist/api-DxBbW5xK.js
3690
+ //#region ../mcp-core/dist/api-DgBjJzAN.js
3620
3691
  /**
3621
3692
  * Create a Sentry API service from server context with optional region override
3622
3693
  * @param context - Server context containing host and access token
@@ -3637,7 +3708,7 @@ function apiServiceFromContext(context$1, opts = {}) {
3637
3708
  }
3638
3709
 
3639
3710
  //#endregion
3640
- //#region ../mcp-core/dist/whoami-Ri2i43vR.js
3711
+ //#region ../mcp-core/dist/whoami-B_pOoN0T.js
3641
3712
  var whoami_default = defineTool({
3642
3713
  name: "whoami",
3643
3714
  description: [
@@ -3670,7 +3741,7 @@ var whoami_default = defineTool({
3670
3741
  });
3671
3742
 
3672
3743
  //#endregion
3673
- //#region ../mcp-core/dist/find-organizations-Cf2YI972.js
3744
+ //#region ../mcp-core/dist/find-organizations-DudCkGim.js
3674
3745
  const RESULT_LIMIT$2 = 25;
3675
3746
  var find_organizations_default = defineTool({
3676
3747
  name: "find_organizations",
@@ -3722,7 +3793,7 @@ var find_organizations_default = defineTool({
3722
3793
  });
3723
3794
 
3724
3795
  //#endregion
3725
- //#region ../mcp-core/dist/find-teams-C_HR4IHN.js
3796
+ //#region ../mcp-core/dist/find-teams-BP0pLsvf.js
3726
3797
  const RESULT_LIMIT$1 = 25;
3727
3798
  var find_teams_default = defineTool({
3728
3799
  name: "find_teams",
@@ -3770,7 +3841,7 @@ var find_teams_default = defineTool({
3770
3841
  });
3771
3842
 
3772
3843
  //#endregion
3773
- //#region ../mcp-core/dist/find-projects-DLZN7tox.js
3844
+ //#region ../mcp-core/dist/find-projects-YtaNsBaH.js
3774
3845
  const RESULT_LIMIT = 25;
3775
3846
  var find_projects_default = defineTool({
3776
3847
  name: "find_projects",
@@ -3814,7 +3885,7 @@ var find_projects_default = defineTool({
3814
3885
  });
3815
3886
 
3816
3887
  //#endregion
3817
- //#region ../mcp-core/dist/find-releases-B5iKG6ZO.js
3888
+ //#region ../mcp-core/dist/find-releases-BVBIICgY.js
3818
3889
  var find_releases_default = defineTool({
3819
3890
  name: "find_releases",
3820
3891
  skills: ["inspect"],
@@ -3963,7 +4034,7 @@ function parseIssueId(issueId) {
3963
4034
  * @returns Object containing the parsed organization slug and issue ID
3964
4035
  * @throws Error if the input is invalid
3965
4036
  */
3966
- function parseIssueParams({ issueUrl, issueId, organizationSlug }) {
4037
+ function parseIssueParams$1({ issueUrl, issueId, organizationSlug }) {
3967
4038
  if (issueUrl) {
3968
4039
  const resolved = extractIssueId(issueUrl);
3969
4040
  if (!resolved) throw new Error("Invalid Sentry issue URL. Path should contain '/issues/{issue_id}'");
@@ -4062,7 +4133,7 @@ function getOutputForAutofixStep(step) {
4062
4133
  }
4063
4134
 
4064
4135
  //#endregion
4065
- //#region ../mcp-core/dist/formatting-CbPBuuTP.js
4136
+ //#region ../mcp-core/dist/formatting-BhgNMv3a.js
4066
4137
  const LANGUAGE_EXTENSIONS = {
4067
4138
  ".java": "java",
4068
4139
  ".py": "python",
@@ -5026,6 +5097,7 @@ function formatIssueOutput({ organizationSlug, issue, event, apiService, autofix
5026
5097
  output += "# Using this information\n\n";
5027
5098
  output += `- You can reference the IssueID in commit messages (e.g. \`Fixes ${issue.shortId}\`) to automatically close the issue when the commit is merged.\n`;
5028
5099
  output += "- The stacktrace includes both first-party application code as well as third-party code, its important to triage to first-party code.\n";
5100
+ output += `- To search for specific occurrences or filter events within this issue, use \`search_issue_events(organizationSlug='${organizationSlug}', issueId='${issue.shortId}', naturalLanguageQuery='your query')\`\n`;
5029
5101
  return output;
5030
5102
  }
5031
5103
 
@@ -5058,7 +5130,7 @@ function enhanceNotFoundError(error, params) {
5058
5130
  }
5059
5131
 
5060
5132
  //#endregion
5061
- //#region ../mcp-core/dist/get-issue-details-CzHzJZi2.js
5133
+ //#region ../mcp-core/dist/get-issue-details-U818j2tY.js
5062
5134
  var get_issue_details_default = defineTool({
5063
5135
  name: "get_issue_details",
5064
5136
  skills: [
@@ -5169,7 +5241,7 @@ var get_issue_details_default = defineTool({
5169
5241
  }
5170
5242
  if (!params.issueUrl && !params.issueId) throw new UserInputError("Either `issueId` or `issueUrl` must be provided");
5171
5243
  if (!params.issueUrl && !params.organizationSlug) throw new UserInputError("`organizationSlug` is required when providing `issueId`");
5172
- const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams({
5244
+ const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams$1({
5173
5245
  organizationSlug: params.organizationSlug,
5174
5246
  issueId: params.issueId,
5175
5247
  issueUrl: params.issueUrl
@@ -5239,7 +5311,122 @@ function shouldFetchTraceForEvent(event) {
5239
5311
  }
5240
5312
 
5241
5313
  //#endregion
5242
- //#region ../mcp-core/dist/get-trace-details-DGzLP_Mo.js
5314
+ //#region ../mcp-core/dist/get-issue-tag-values-tupBr2Mu.js
5315
+ var get_issue_tag_values_default = defineTool({
5316
+ name: "get_issue_tag_values",
5317
+ skills: ["inspect"],
5318
+ requiredScopes: ["event:read"],
5319
+ description: [
5320
+ "Get tag value distribution for a specific Sentry issue.",
5321
+ "",
5322
+ "Use this tool when you need to:",
5323
+ "- Understand how an issue is distributed across different tag values",
5324
+ "- Get aggregate counts of unique tag values (e.g., 'how many unique URLs are affected')",
5325
+ "- Analyze which browsers, environments, or URLs are most impacted by an issue",
5326
+ "- View the tag distributions page data programmatically",
5327
+ "",
5328
+ "Common tag keys:",
5329
+ "- `url`: Request URLs affected by the issue",
5330
+ "- `browser`: Browser types and versions",
5331
+ "- `browser.name`: Browser names only",
5332
+ "- `os`: Operating systems",
5333
+ "- `environment`: Deployment environments (production, staging, etc.)",
5334
+ "- `release`: Software releases",
5335
+ "- `device`: Device types",
5336
+ "- `user`: Affected users",
5337
+ "",
5338
+ "<examples>",
5339
+ "### Get URL distribution for an issue",
5340
+ "```",
5341
+ "get_issue_tag_values(organizationSlug='my-organization', issueId='PROJECT-123', tagKey='url')",
5342
+ "```",
5343
+ "",
5344
+ "### Get browser distribution using issue URL",
5345
+ "```",
5346
+ "get_issue_tag_values(issueUrl='https://sentry.io/issues/PROJECT-123/', tagKey='browser')",
5347
+ "```",
5348
+ "",
5349
+ "### Get environment distribution",
5350
+ "```",
5351
+ "get_issue_tag_values(organizationSlug='my-organization', issueId='PROJECT-123', tagKey='environment')",
5352
+ "```",
5353
+ "</examples>",
5354
+ "",
5355
+ "<hints>",
5356
+ "- If user provides a Sentry URL, pass the ENTIRE URL to issueUrl parameter unchanged",
5357
+ "- Common tag keys: url, browser, browser.name, os, environment, release, device, user",
5358
+ "- Tag keys are case-sensitive",
5359
+ "</hints>"
5360
+ ].join("\n"),
5361
+ inputSchema: {
5362
+ organizationSlug: ParamOrganizationSlug.optional(),
5363
+ regionUrl: ParamRegionUrl.nullable().default(null),
5364
+ issueId: ParamIssueShortId.optional(),
5365
+ issueUrl: ParamIssueUrl.optional(),
5366
+ tagKey: z.string().trim().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/, "Tag key must contain only alphanumeric characters, dots, hyphens, and underscores, and must start with an alphanumeric character").describe("The tag key to get values for (e.g., 'url', 'browser', 'environment', 'release').")
5367
+ },
5368
+ annotations: {
5369
+ readOnlyHint: true,
5370
+ openWorldHint: true
5371
+ },
5372
+ async handler(params, context$1) {
5373
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
5374
+ if (!params.issueUrl && !params.issueId) throw new UserInputError("Either `issueId` or `issueUrl` must be provided");
5375
+ if (!params.issueUrl && !params.organizationSlug) throw new UserInputError("`organizationSlug` is required when providing `issueId`");
5376
+ if (!params.tagKey) throw new UserInputError("`tagKey` is required. Common values: url, browser, environment, release, os, device, user");
5377
+ const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams$1({
5378
+ organizationSlug: params.organizationSlug,
5379
+ issueId: params.issueId,
5380
+ issueUrl: params.issueUrl
5381
+ });
5382
+ setTag("organization.slug", orgSlug);
5383
+ let tagValues;
5384
+ try {
5385
+ tagValues = await apiService.getIssueTagValues({
5386
+ organizationSlug: orgSlug,
5387
+ issueId: parsedIssueId,
5388
+ tagKey: params.tagKey
5389
+ });
5390
+ } catch (error) {
5391
+ if (error instanceof ApiNotFoundError) throw enhanceNotFoundError(error, {
5392
+ organizationSlug: orgSlug,
5393
+ issueId: parsedIssueId,
5394
+ tagKey: params.tagKey
5395
+ });
5396
+ throw error;
5397
+ }
5398
+ let output = `# Tag Distribution: ${tagValues.name}\n\n`;
5399
+ output += `**Issue**: ${parsedIssueId}\n`;
5400
+ output += `**Tag Key**: \`${tagValues.key}\`\n`;
5401
+ output += `**Total Unique Values**: ${tagValues.totalValues}\n\n`;
5402
+ if (tagValues.topValues.length === 0) {
5403
+ output += "No values found for this tag.\n";
5404
+ return output;
5405
+ }
5406
+ output += "## Top Values\n\n";
5407
+ output += "| Value | Count | First Seen | Last Seen |\n";
5408
+ output += "|-------|-------|------------|----------|\n";
5409
+ for (const value of tagValues.topValues) {
5410
+ const firstSeen = value.firstSeen ? new Date(value.firstSeen).toISOString().split("T")[0] : "-";
5411
+ const lastSeen = value.lastSeen ? new Date(value.lastSeen).toISOString().split("T")[0] : "-";
5412
+ const rawValue = value.value ?? "(null)";
5413
+ let displayValue = rawValue.length > 60 ? `${rawValue.substring(0, 57)}...` : rawValue;
5414
+ displayValue = displayValue.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/`/g, "\\`").replace(/\n/g, " ");
5415
+ output += `| \`${displayValue}\` | ${value.count} | ${firstSeen} | ${lastSeen} |\n`;
5416
+ }
5417
+ if (tagValues.topValues.length > 0 && tagValues.totalValues > 0) {
5418
+ const shownCount = tagValues.topValues.length;
5419
+ output += `\n*Showing top ${shownCount} of ${tagValues.totalValues} unique values*\n`;
5420
+ }
5421
+ output += "\n## Using this information\n\n";
5422
+ output += `- Use \`get_issue_details(organizationSlug='${orgSlug}', issueId='${parsedIssueId}')\` to see the full issue details\n`;
5423
+ output += `- Try other tag keys like: url, browser, environment, release, os, device, user\n`;
5424
+ return output;
5425
+ }
5426
+ });
5427
+
5428
+ //#endregion
5429
+ //#region ../mcp-core/dist/get-trace-details-DDDetJqp.js
5243
5430
  const MAX_DEPTH = 2;
5244
5431
  const MINIMUM_DURATION_THRESHOLD_MS = 10;
5245
5432
  const MIN_MEANINGFUL_CHILD_DURATION = 5;
@@ -5538,7 +5725,7 @@ function formatTraceOutput({ organizationSlug, traceId, traceMeta, trace: trace$
5538
5725
  }
5539
5726
 
5540
5727
  //#endregion
5541
- //#region ../mcp-core/dist/get-event-attachment-4_XbtsrW.js
5728
+ //#region ../mcp-core/dist/get-event-attachment-itWm1HrK.js
5542
5729
  var get_event_attachment_default = defineTool({
5543
5730
  name: "get_event_attachment",
5544
5731
  skills: ["inspect"],
@@ -5674,7 +5861,7 @@ var get_event_attachment_default = defineTool({
5674
5861
  });
5675
5862
 
5676
5863
  //#endregion
5677
- //#region ../mcp-core/dist/formatting-DJFcfTJG.js
5864
+ //#region ../mcp-core/dist/formatting-CIwRyNGU.js
5678
5865
  /**
5679
5866
  * Helper function to format assignedTo field for display
5680
5867
  */
@@ -5686,7 +5873,7 @@ function formatAssignedTo(assignedTo) {
5686
5873
  }
5687
5874
 
5688
5875
  //#endregion
5689
- //#region ../mcp-core/dist/update-issue-BSKY4Du1.js
5876
+ //#region ../mcp-core/dist/update-issue-DA_N-toV.js
5690
5877
  var update_issue_default = defineTool({
5691
5878
  name: "update_issue",
5692
5879
  skills: ["triage"],
@@ -5754,7 +5941,7 @@ var update_issue_default = defineTool({
5754
5941
  if (!params.issueUrl && !params.issueId) throw new UserInputError("Either `issueId` or `issueUrl` must be provided");
5755
5942
  if (!params.issueUrl && !params.organizationSlug) throw new UserInputError("`organizationSlug` is required when providing `issueId`");
5756
5943
  if (!params.status && !params.assignedTo) throw new UserInputError("At least one of `status` or `assignedTo` must be provided to update the issue");
5757
- const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams({
5944
+ const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams$1({
5758
5945
  organizationSlug: params.organizationSlug,
5759
5946
  issueId: params.issueId,
5760
5947
  issueUrl: params.issueUrl
@@ -5983,6 +6170,20 @@ var name10$1 = "AI_NoSuchModelError";
5983
6170
  var marker11$1 = `vercel.ai.error.${name10$1}`;
5984
6171
  var symbol11$1 = Symbol.for(marker11$1);
5985
6172
  var _a11$1;
6173
+ var NoSuchModelError = class extends AISDKError {
6174
+ constructor({ errorName = name10$1, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
6175
+ super({
6176
+ name: errorName,
6177
+ message
6178
+ });
6179
+ this[_a11$1] = true;
6180
+ this.modelId = modelId;
6181
+ this.modelType = modelType;
6182
+ }
6183
+ static isInstance(error) {
6184
+ return AISDKError.hasMarker(error, marker11$1);
6185
+ }
6186
+ };
5986
6187
  _a11$1 = symbol11$1;
5987
6188
  var name11$1 = "AI_TooManyEmbeddingValuesForCallError";
5988
6189
  var marker12$1 = `vercel.ai.error.${name11$1}`;
@@ -6518,6 +6719,10 @@ var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, fai
6518
6719
  throw error;
6519
6720
  }
6520
6721
  };
6722
+ async function resolve(value) {
6723
+ if (typeof value === "function") value = value();
6724
+ return Promise.resolve(value);
6725
+ }
6521
6726
  var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
6522
6727
  const responseBody = await response.text();
6523
6728
  const responseHeaders = extractResponseHeaders(response);
@@ -6833,7 +7038,7 @@ function getResponseMetadata({ id, model, created }) {
6833
7038
  timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
6834
7039
  };
6835
7040
  }
6836
- function prepareTools({ mode, useLegacyFunctionCalling = false, structuredOutputs }) {
7041
+ function prepareTools$1({ mode, useLegacyFunctionCalling = false, structuredOutputs }) {
6837
7042
  var _a$2;
6838
7043
  const tools = ((_a$2 = mode.tools) == null ? void 0 : _a$2.length) ? mode.tools : void 0;
6839
7044
  const toolWarnings = [];
@@ -7061,7 +7266,7 @@ var OpenAIChatLanguageModel = class {
7061
7266
  }
7062
7267
  switch (type) {
7063
7268
  case "regular": {
7064
- const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools({
7269
+ const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools$1({
7065
7270
  mode,
7066
7271
  useLegacyFunctionCalling,
7067
7272
  structuredOutputs: this.supportsStructuredOutputs
@@ -8959,7 +9164,7 @@ function createOpenAI(options = {}) {
8959
9164
  var openai = createOpenAI({ compatibility: "strict" });
8960
9165
 
8961
9166
  //#endregion
8962
- //#region ../mcp-core/dist/openai-provider-BwPDNx0z.js
9167
+ //#region ../mcp-core/dist/openai-provider-BhiGfaFk.js
8963
9168
  const DEFAULT_OPENAI_MODEL = "gpt-5";
8964
9169
  const VALID_REASONING_EFFORTS = [
8965
9170
  "low",
@@ -8967,13 +9172,13 @@ const VALID_REASONING_EFFORTS = [
8967
9172
  "high"
8968
9173
  ];
8969
9174
  const DEFAULT_REASONING_EFFORT = "low";
8970
- let configuredBaseUrl;
9175
+ let configuredBaseUrl$1;
8971
9176
  /**
8972
9177
  * Configure the OpenAI base URL (CLI flag only, not environment variable).
8973
9178
  * This must be called explicitly - it cannot be set via environment variables for security.
8974
9179
  */
8975
9180
  function setOpenAIBaseUrl(baseUrl) {
8976
- configuredBaseUrl = baseUrl;
9181
+ configuredBaseUrl$1 = baseUrl;
8977
9182
  }
8978
9183
  /**
8979
9184
  * Retrieve an OpenAI language model configured from environment variables and explicit config.
@@ -8995,89 +9200,1323 @@ function getOpenAIModel(model) {
8995
9200
  throw new Error(`Invalid OPENAI_REASONING_EFFORT value: "${envReasoningEffort}". Must be one of: ${validValues}, or "" (empty string to disable). Default is "${DEFAULT_REASONING_EFFORT}".`);
8996
9201
  }
8997
9202
  const factory = createOpenAI({
8998
- ...configuredBaseUrl && { baseURL: configuredBaseUrl },
9203
+ ...configuredBaseUrl$1 && { baseURL: configuredBaseUrl$1 },
8999
9204
  headers: { "User-Agent": USER_AGENT }
9000
9205
  });
9001
9206
  return factory(model ?? defaultModel, { ...reasoningEffort && { reasoningEffort } });
9002
9207
  }
9003
9208
 
9004
9209
  //#endregion
9005
- //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js
9006
- const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
9007
- const defaultOptions = {
9008
- name: void 0,
9009
- $refStrategy: "root",
9010
- basePath: ["#"],
9011
- effectStrategy: "input",
9012
- pipeStrategy: "all",
9013
- dateStrategy: "format:date-time",
9014
- mapStrategy: "entries",
9015
- removeAdditionalStrategy: "passthrough",
9016
- allowedAdditionalProperties: true,
9017
- rejectedAdditionalProperties: false,
9018
- definitionPath: "definitions",
9019
- target: "jsonSchema7",
9020
- strictUnions: false,
9021
- definitions: {},
9022
- errorMessages: false,
9023
- markdownDescription: false,
9024
- patternStrategy: "escape",
9025
- applyRegexFlags: false,
9026
- emailStrategy: "format:email",
9027
- base64Strategy: "contentEncoding:base64",
9028
- nameStrategy: "ref",
9029
- openAiAnyTypeName: "OpenAiAnyType"
9030
- };
9031
- const getDefaultOptions = (options) => typeof options === "string" ? {
9032
- ...defaultOptions,
9033
- name: options
9034
- } : {
9035
- ...defaultOptions,
9036
- ...options
9037
- };
9038
-
9039
- //#endregion
9040
- //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js
9041
- const getRefs = (options) => {
9042
- const _options = getDefaultOptions(options);
9043
- const currentPath = _options.name !== void 0 ? [
9044
- ..._options.basePath,
9045
- _options.definitionPath,
9046
- _options.name
9047
- ] : _options.basePath;
9048
- return {
9049
- ..._options,
9050
- flags: { hasReferencedOpenAiAnyType: false },
9051
- currentPath,
9052
- propertyPath: void 0,
9053
- seen: new Map(Object.entries(_options.definitions).map(([name$2, def]) => [def._def, {
9054
- def: def._def,
9055
- path: [
9056
- ..._options.basePath,
9057
- _options.definitionPath,
9058
- name$2
9059
- ],
9060
- jsonSchema: void 0
9061
- }]))
9210
+ //#region ../../node_modules/.pnpm/@ai-sdk+anthropic@1.2.12_zod@3.25.76/node_modules/@ai-sdk/anthropic/dist/index.mjs
9211
+ var anthropicErrorDataSchema = z.object({
9212
+ type: z.literal("error"),
9213
+ error: z.object({
9214
+ type: z.string(),
9215
+ message: z.string()
9216
+ })
9217
+ });
9218
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
9219
+ errorSchema: anthropicErrorDataSchema,
9220
+ errorToMessage: (data) => data.error.message
9221
+ });
9222
+ function prepareTools(mode) {
9223
+ var _a$2;
9224
+ const tools = ((_a$2 = mode.tools) == null ? void 0 : _a$2.length) ? mode.tools : void 0;
9225
+ const toolWarnings = [];
9226
+ const betas = /* @__PURE__ */ new Set();
9227
+ if (tools == null) return {
9228
+ tools: void 0,
9229
+ tool_choice: void 0,
9230
+ toolWarnings,
9231
+ betas
9062
9232
  };
9063
- };
9064
-
9065
- //#endregion
9066
- //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
9067
- function addErrorMessage(res, key, errorMessage, refs) {
9068
- if (!refs?.errorMessages) return;
9069
- if (errorMessage) res.errorMessage = {
9070
- ...res.errorMessage,
9071
- [key]: errorMessage
9233
+ const anthropicTools2 = [];
9234
+ for (const tool$1 of tools) switch (tool$1.type) {
9235
+ case "function":
9236
+ anthropicTools2.push({
9237
+ name: tool$1.name,
9238
+ description: tool$1.description,
9239
+ input_schema: tool$1.parameters
9240
+ });
9241
+ break;
9242
+ case "provider-defined":
9243
+ switch (tool$1.id) {
9244
+ case "anthropic.computer_20250124":
9245
+ betas.add("computer-use-2025-01-24");
9246
+ anthropicTools2.push({
9247
+ name: tool$1.name,
9248
+ type: "computer_20250124",
9249
+ display_width_px: tool$1.args.displayWidthPx,
9250
+ display_height_px: tool$1.args.displayHeightPx,
9251
+ display_number: tool$1.args.displayNumber
9252
+ });
9253
+ break;
9254
+ case "anthropic.computer_20241022":
9255
+ betas.add("computer-use-2024-10-22");
9256
+ anthropicTools2.push({
9257
+ name: tool$1.name,
9258
+ type: "computer_20241022",
9259
+ display_width_px: tool$1.args.displayWidthPx,
9260
+ display_height_px: tool$1.args.displayHeightPx,
9261
+ display_number: tool$1.args.displayNumber
9262
+ });
9263
+ break;
9264
+ case "anthropic.text_editor_20250124":
9265
+ betas.add("computer-use-2025-01-24");
9266
+ anthropicTools2.push({
9267
+ name: tool$1.name,
9268
+ type: "text_editor_20250124"
9269
+ });
9270
+ break;
9271
+ case "anthropic.text_editor_20241022":
9272
+ betas.add("computer-use-2024-10-22");
9273
+ anthropicTools2.push({
9274
+ name: tool$1.name,
9275
+ type: "text_editor_20241022"
9276
+ });
9277
+ break;
9278
+ case "anthropic.bash_20250124":
9279
+ betas.add("computer-use-2025-01-24");
9280
+ anthropicTools2.push({
9281
+ name: tool$1.name,
9282
+ type: "bash_20250124"
9283
+ });
9284
+ break;
9285
+ case "anthropic.bash_20241022":
9286
+ betas.add("computer-use-2024-10-22");
9287
+ anthropicTools2.push({
9288
+ name: tool$1.name,
9289
+ type: "bash_20241022"
9290
+ });
9291
+ break;
9292
+ default:
9293
+ toolWarnings.push({
9294
+ type: "unsupported-tool",
9295
+ tool: tool$1
9296
+ });
9297
+ break;
9298
+ }
9299
+ break;
9300
+ default:
9301
+ toolWarnings.push({
9302
+ type: "unsupported-tool",
9303
+ tool: tool$1
9304
+ });
9305
+ break;
9306
+ }
9307
+ const toolChoice = mode.toolChoice;
9308
+ if (toolChoice == null) return {
9309
+ tools: anthropicTools2,
9310
+ tool_choice: void 0,
9311
+ toolWarnings,
9312
+ betas
9072
9313
  };
9073
- }
9074
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
9075
- res[key] = value;
9076
- addErrorMessage(res, key, errorMessage, refs);
9077
- }
9078
-
9079
- //#endregion
9080
- //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
9314
+ const type = toolChoice.type;
9315
+ switch (type) {
9316
+ case "auto": return {
9317
+ tools: anthropicTools2,
9318
+ tool_choice: { type: "auto" },
9319
+ toolWarnings,
9320
+ betas
9321
+ };
9322
+ case "required": return {
9323
+ tools: anthropicTools2,
9324
+ tool_choice: { type: "any" },
9325
+ toolWarnings,
9326
+ betas
9327
+ };
9328
+ case "none": return {
9329
+ tools: void 0,
9330
+ tool_choice: void 0,
9331
+ toolWarnings,
9332
+ betas
9333
+ };
9334
+ case "tool": return {
9335
+ tools: anthropicTools2,
9336
+ tool_choice: {
9337
+ type: "tool",
9338
+ name: toolChoice.toolName
9339
+ },
9340
+ toolWarnings,
9341
+ betas
9342
+ };
9343
+ default: {
9344
+ const _exhaustiveCheck = type;
9345
+ throw new UnsupportedFunctionalityError({ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` });
9346
+ }
9347
+ }
9348
+ }
9349
+ function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warnings }) {
9350
+ var _a$2, _b, _c, _d;
9351
+ const betas = /* @__PURE__ */ new Set();
9352
+ const blocks = groupIntoBlocks(prompt);
9353
+ let system = void 0;
9354
+ const messages = [];
9355
+ function getCacheControl(providerMetadata) {
9356
+ var _a2$2;
9357
+ const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
9358
+ const cacheControlValue = (_a2$2 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a2$2 : anthropic2 == null ? void 0 : anthropic2.cache_control;
9359
+ return cacheControlValue;
9360
+ }
9361
+ for (let i = 0; i < blocks.length; i++) {
9362
+ const block = blocks[i];
9363
+ const isLastBlock = i === blocks.length - 1;
9364
+ const type = block.type;
9365
+ switch (type) {
9366
+ case "system": {
9367
+ if (system != null) throw new UnsupportedFunctionalityError({ functionality: "Multiple system messages that are separated by user/assistant messages" });
9368
+ system = block.messages.map(({ content, providerMetadata }) => ({
9369
+ type: "text",
9370
+ text: content,
9371
+ cache_control: getCacheControl(providerMetadata)
9372
+ }));
9373
+ break;
9374
+ }
9375
+ case "user": {
9376
+ const anthropicContent = [];
9377
+ for (const message of block.messages) {
9378
+ const { role, content } = message;
9379
+ switch (role) {
9380
+ case "user": {
9381
+ for (let j = 0; j < content.length; j++) {
9382
+ const part = content[j];
9383
+ const isLastPart = j === content.length - 1;
9384
+ const cacheControl = (_a$2 = getCacheControl(part.providerMetadata)) != null ? _a$2 : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
9385
+ switch (part.type) {
9386
+ case "text": {
9387
+ anthropicContent.push({
9388
+ type: "text",
9389
+ text: part.text,
9390
+ cache_control: cacheControl
9391
+ });
9392
+ break;
9393
+ }
9394
+ case "image": {
9395
+ anthropicContent.push({
9396
+ type: "image",
9397
+ source: part.image instanceof URL ? {
9398
+ type: "url",
9399
+ url: part.image.toString()
9400
+ } : {
9401
+ type: "base64",
9402
+ media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
9403
+ data: convertUint8ArrayToBase64(part.image)
9404
+ },
9405
+ cache_control: cacheControl
9406
+ });
9407
+ break;
9408
+ }
9409
+ case "file": {
9410
+ if (part.mimeType !== "application/pdf") throw new UnsupportedFunctionalityError({ functionality: "Non-PDF files in user messages" });
9411
+ betas.add("pdfs-2024-09-25");
9412
+ anthropicContent.push({
9413
+ type: "document",
9414
+ source: part.data instanceof URL ? {
9415
+ type: "url",
9416
+ url: part.data.toString()
9417
+ } : {
9418
+ type: "base64",
9419
+ media_type: "application/pdf",
9420
+ data: part.data
9421
+ },
9422
+ cache_control: cacheControl
9423
+ });
9424
+ break;
9425
+ }
9426
+ }
9427
+ }
9428
+ break;
9429
+ }
9430
+ case "tool": {
9431
+ for (let i2 = 0; i2 < content.length; i2++) {
9432
+ const part = content[i2];
9433
+ const isLastPart = i2 === content.length - 1;
9434
+ const cacheControl = (_c = getCacheControl(part.providerMetadata)) != null ? _c : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
9435
+ const toolResultContent = part.content != null ? part.content.map((part2) => {
9436
+ var _a2$2;
9437
+ switch (part2.type) {
9438
+ case "text": return {
9439
+ type: "text",
9440
+ text: part2.text,
9441
+ cache_control: void 0
9442
+ };
9443
+ case "image": return {
9444
+ type: "image",
9445
+ source: {
9446
+ type: "base64",
9447
+ media_type: (_a2$2 = part2.mimeType) != null ? _a2$2 : "image/jpeg",
9448
+ data: part2.data
9449
+ },
9450
+ cache_control: void 0
9451
+ };
9452
+ }
9453
+ }) : JSON.stringify(part.result);
9454
+ anthropicContent.push({
9455
+ type: "tool_result",
9456
+ tool_use_id: part.toolCallId,
9457
+ content: toolResultContent,
9458
+ is_error: part.isError,
9459
+ cache_control: cacheControl
9460
+ });
9461
+ }
9462
+ break;
9463
+ }
9464
+ default: {
9465
+ const _exhaustiveCheck = role;
9466
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
9467
+ }
9468
+ }
9469
+ }
9470
+ messages.push({
9471
+ role: "user",
9472
+ content: anthropicContent
9473
+ });
9474
+ break;
9475
+ }
9476
+ case "assistant": {
9477
+ const anthropicContent = [];
9478
+ for (let j = 0; j < block.messages.length; j++) {
9479
+ const message = block.messages[j];
9480
+ const isLastMessage = j === block.messages.length - 1;
9481
+ const { content } = message;
9482
+ for (let k = 0; k < content.length; k++) {
9483
+ const part = content[k];
9484
+ const isLastContentPart = k === content.length - 1;
9485
+ const cacheControl = (_d = getCacheControl(part.providerMetadata)) != null ? _d : isLastContentPart ? getCacheControl(message.providerMetadata) : void 0;
9486
+ switch (part.type) {
9487
+ case "text": {
9488
+ anthropicContent.push({
9489
+ type: "text",
9490
+ text: isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text,
9491
+ cache_control: cacheControl
9492
+ });
9493
+ break;
9494
+ }
9495
+ case "reasoning": {
9496
+ if (sendReasoning) anthropicContent.push({
9497
+ type: "thinking",
9498
+ thinking: part.text,
9499
+ signature: part.signature,
9500
+ cache_control: cacheControl
9501
+ });
9502
+ else warnings.push({
9503
+ type: "other",
9504
+ message: "sending reasoning content is disabled for this model"
9505
+ });
9506
+ break;
9507
+ }
9508
+ case "redacted-reasoning": {
9509
+ anthropicContent.push({
9510
+ type: "redacted_thinking",
9511
+ data: part.data,
9512
+ cache_control: cacheControl
9513
+ });
9514
+ break;
9515
+ }
9516
+ case "tool-call": {
9517
+ anthropicContent.push({
9518
+ type: "tool_use",
9519
+ id: part.toolCallId,
9520
+ name: part.toolName,
9521
+ input: part.args,
9522
+ cache_control: cacheControl
9523
+ });
9524
+ break;
9525
+ }
9526
+ }
9527
+ }
9528
+ }
9529
+ messages.push({
9530
+ role: "assistant",
9531
+ content: anthropicContent
9532
+ });
9533
+ break;
9534
+ }
9535
+ default: {
9536
+ const _exhaustiveCheck = type;
9537
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
9538
+ }
9539
+ }
9540
+ }
9541
+ return {
9542
+ prompt: {
9543
+ system,
9544
+ messages
9545
+ },
9546
+ betas
9547
+ };
9548
+ }
9549
+ function groupIntoBlocks(prompt) {
9550
+ const blocks = [];
9551
+ let currentBlock = void 0;
9552
+ for (const message of prompt) {
9553
+ const { role } = message;
9554
+ switch (role) {
9555
+ case "system": {
9556
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
9557
+ currentBlock = {
9558
+ type: "system",
9559
+ messages: []
9560
+ };
9561
+ blocks.push(currentBlock);
9562
+ }
9563
+ currentBlock.messages.push(message);
9564
+ break;
9565
+ }
9566
+ case "assistant": {
9567
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
9568
+ currentBlock = {
9569
+ type: "assistant",
9570
+ messages: []
9571
+ };
9572
+ blocks.push(currentBlock);
9573
+ }
9574
+ currentBlock.messages.push(message);
9575
+ break;
9576
+ }
9577
+ case "user": {
9578
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
9579
+ currentBlock = {
9580
+ type: "user",
9581
+ messages: []
9582
+ };
9583
+ blocks.push(currentBlock);
9584
+ }
9585
+ currentBlock.messages.push(message);
9586
+ break;
9587
+ }
9588
+ case "tool": {
9589
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
9590
+ currentBlock = {
9591
+ type: "user",
9592
+ messages: []
9593
+ };
9594
+ blocks.push(currentBlock);
9595
+ }
9596
+ currentBlock.messages.push(message);
9597
+ break;
9598
+ }
9599
+ default: {
9600
+ const _exhaustiveCheck = role;
9601
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
9602
+ }
9603
+ }
9604
+ }
9605
+ return blocks;
9606
+ }
9607
+ function mapAnthropicStopReason(finishReason) {
9608
+ switch (finishReason) {
9609
+ case "end_turn":
9610
+ case "stop_sequence": return "stop";
9611
+ case "tool_use": return "tool-calls";
9612
+ case "max_tokens": return "length";
9613
+ default: return "unknown";
9614
+ }
9615
+ }
9616
+ var AnthropicMessagesLanguageModel = class {
9617
+ constructor(modelId, settings, config) {
9618
+ this.specificationVersion = "v1";
9619
+ this.defaultObjectGenerationMode = "tool";
9620
+ this.modelId = modelId;
9621
+ this.settings = settings;
9622
+ this.config = config;
9623
+ }
9624
+ supportsUrl(url) {
9625
+ return url.protocol === "https:";
9626
+ }
9627
+ get provider() {
9628
+ return this.config.provider;
9629
+ }
9630
+ get supportsImageUrls() {
9631
+ return this.config.supportsImageUrls;
9632
+ }
9633
+ async getArgs({ mode, prompt, maxTokens = 4096, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, providerMetadata: providerOptions }) {
9634
+ var _a$2, _b, _c;
9635
+ const type = mode.type;
9636
+ const warnings = [];
9637
+ if (frequencyPenalty != null) warnings.push({
9638
+ type: "unsupported-setting",
9639
+ setting: "frequencyPenalty"
9640
+ });
9641
+ if (presencePenalty != null) warnings.push({
9642
+ type: "unsupported-setting",
9643
+ setting: "presencePenalty"
9644
+ });
9645
+ if (seed != null) warnings.push({
9646
+ type: "unsupported-setting",
9647
+ setting: "seed"
9648
+ });
9649
+ if (responseFormat != null && responseFormat.type !== "text") warnings.push({
9650
+ type: "unsupported-setting",
9651
+ setting: "responseFormat",
9652
+ details: "JSON response format is not supported."
9653
+ });
9654
+ const { prompt: messagesPrompt, betas: messagesBetas } = convertToAnthropicMessagesPrompt({
9655
+ prompt,
9656
+ sendReasoning: (_a$2 = this.settings.sendReasoning) != null ? _a$2 : true,
9657
+ warnings
9658
+ });
9659
+ const anthropicOptions = parseProviderOptions({
9660
+ provider: "anthropic",
9661
+ providerOptions,
9662
+ schema: anthropicProviderOptionsSchema
9663
+ });
9664
+ const isThinking = ((_b = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _b.type) === "enabled";
9665
+ const thinkingBudget = (_c = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _c.budgetTokens;
9666
+ const baseArgs = {
9667
+ model: this.modelId,
9668
+ max_tokens: maxTokens,
9669
+ temperature,
9670
+ top_k: topK,
9671
+ top_p: topP,
9672
+ stop_sequences: stopSequences,
9673
+ ...isThinking && { thinking: {
9674
+ type: "enabled",
9675
+ budget_tokens: thinkingBudget
9676
+ } },
9677
+ system: messagesPrompt.system,
9678
+ messages: messagesPrompt.messages
9679
+ };
9680
+ if (isThinking) {
9681
+ if (thinkingBudget == null) throw new UnsupportedFunctionalityError({ functionality: "thinking requires a budget" });
9682
+ if (baseArgs.temperature != null) {
9683
+ baseArgs.temperature = void 0;
9684
+ warnings.push({
9685
+ type: "unsupported-setting",
9686
+ setting: "temperature",
9687
+ details: "temperature is not supported when thinking is enabled"
9688
+ });
9689
+ }
9690
+ if (topK != null) {
9691
+ baseArgs.top_k = void 0;
9692
+ warnings.push({
9693
+ type: "unsupported-setting",
9694
+ setting: "topK",
9695
+ details: "topK is not supported when thinking is enabled"
9696
+ });
9697
+ }
9698
+ if (topP != null) {
9699
+ baseArgs.top_p = void 0;
9700
+ warnings.push({
9701
+ type: "unsupported-setting",
9702
+ setting: "topP",
9703
+ details: "topP is not supported when thinking is enabled"
9704
+ });
9705
+ }
9706
+ baseArgs.max_tokens = maxTokens + thinkingBudget;
9707
+ }
9708
+ switch (type) {
9709
+ case "regular": {
9710
+ const { tools, tool_choice, toolWarnings, betas: toolsBetas } = prepareTools(mode);
9711
+ return {
9712
+ args: {
9713
+ ...baseArgs,
9714
+ tools,
9715
+ tool_choice
9716
+ },
9717
+ warnings: [...warnings, ...toolWarnings],
9718
+ betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas])
9719
+ };
9720
+ }
9721
+ case "object-json": throw new UnsupportedFunctionalityError({ functionality: "json-mode object generation" });
9722
+ case "object-tool": {
9723
+ const { name: name$2, description: description$73, parameters } = mode.tool;
9724
+ return {
9725
+ args: {
9726
+ ...baseArgs,
9727
+ tools: [{
9728
+ name: name$2,
9729
+ description: description$73,
9730
+ input_schema: parameters
9731
+ }],
9732
+ tool_choice: {
9733
+ type: "tool",
9734
+ name: name$2
9735
+ }
9736
+ },
9737
+ warnings,
9738
+ betas: messagesBetas
9739
+ };
9740
+ }
9741
+ default: {
9742
+ const _exhaustiveCheck = type;
9743
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
9744
+ }
9745
+ }
9746
+ }
9747
+ async getHeaders({ betas, headers }) {
9748
+ return combineHeaders(await resolve(this.config.headers), betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {}, headers);
9749
+ }
9750
+ buildRequestUrl(isStreaming) {
9751
+ var _a$2, _b, _c;
9752
+ return (_c = (_b = (_a$2 = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a$2, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
9753
+ }
9754
+ transformRequestBody(args) {
9755
+ var _a$2, _b, _c;
9756
+ return (_c = (_b = (_a$2 = this.config).transformRequestBody) == null ? void 0 : _b.call(_a$2, args)) != null ? _c : args;
9757
+ }
9758
+ async doGenerate(options) {
9759
+ var _a$2, _b, _c, _d;
9760
+ const { args, warnings, betas } = await this.getArgs(options);
9761
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
9762
+ url: this.buildRequestUrl(false),
9763
+ headers: await this.getHeaders({
9764
+ betas,
9765
+ headers: options.headers
9766
+ }),
9767
+ body: this.transformRequestBody(args),
9768
+ failedResponseHandler: anthropicFailedResponseHandler,
9769
+ successfulResponseHandler: createJsonResponseHandler(anthropicMessagesResponseSchema),
9770
+ abortSignal: options.abortSignal,
9771
+ fetch: this.config.fetch
9772
+ });
9773
+ const { messages: rawPrompt,...rawSettings } = args;
9774
+ let text$1 = "";
9775
+ for (const content of response.content) if (content.type === "text") text$1 += content.text;
9776
+ let toolCalls = void 0;
9777
+ if (response.content.some((content) => content.type === "tool_use")) {
9778
+ toolCalls = [];
9779
+ for (const content of response.content) if (content.type === "tool_use") toolCalls.push({
9780
+ toolCallType: "function",
9781
+ toolCallId: content.id,
9782
+ toolName: content.name,
9783
+ args: JSON.stringify(content.input)
9784
+ });
9785
+ }
9786
+ const reasoning = response.content.filter((content) => content.type === "redacted_thinking" || content.type === "thinking").map((content) => content.type === "thinking" ? {
9787
+ type: "text",
9788
+ text: content.thinking,
9789
+ signature: content.signature
9790
+ } : {
9791
+ type: "redacted",
9792
+ data: content.data
9793
+ });
9794
+ return {
9795
+ text: text$1,
9796
+ reasoning: reasoning.length > 0 ? reasoning : void 0,
9797
+ toolCalls,
9798
+ finishReason: mapAnthropicStopReason(response.stop_reason),
9799
+ usage: {
9800
+ promptTokens: response.usage.input_tokens,
9801
+ completionTokens: response.usage.output_tokens
9802
+ },
9803
+ rawCall: {
9804
+ rawPrompt,
9805
+ rawSettings
9806
+ },
9807
+ rawResponse: {
9808
+ headers: responseHeaders,
9809
+ body: rawResponse
9810
+ },
9811
+ response: {
9812
+ id: (_a$2 = response.id) != null ? _a$2 : void 0,
9813
+ modelId: (_b = response.model) != null ? _b : void 0
9814
+ },
9815
+ warnings,
9816
+ providerMetadata: { anthropic: {
9817
+ cacheCreationInputTokens: (_c = response.usage.cache_creation_input_tokens) != null ? _c : null,
9818
+ cacheReadInputTokens: (_d = response.usage.cache_read_input_tokens) != null ? _d : null
9819
+ } },
9820
+ request: { body: JSON.stringify(args) }
9821
+ };
9822
+ }
9823
+ async doStream(options) {
9824
+ const { args, warnings, betas } = await this.getArgs(options);
9825
+ const body = {
9826
+ ...args,
9827
+ stream: true
9828
+ };
9829
+ const { responseHeaders, value: response } = await postJsonToApi({
9830
+ url: this.buildRequestUrl(true),
9831
+ headers: await this.getHeaders({
9832
+ betas,
9833
+ headers: options.headers
9834
+ }),
9835
+ body: this.transformRequestBody(body),
9836
+ failedResponseHandler: anthropicFailedResponseHandler,
9837
+ successfulResponseHandler: createEventSourceResponseHandler(anthropicMessagesChunkSchema),
9838
+ abortSignal: options.abortSignal,
9839
+ fetch: this.config.fetch
9840
+ });
9841
+ const { messages: rawPrompt,...rawSettings } = args;
9842
+ let finishReason = "unknown";
9843
+ const usage = {
9844
+ promptTokens: NaN,
9845
+ completionTokens: NaN
9846
+ };
9847
+ const toolCallContentBlocks = {};
9848
+ let providerMetadata = void 0;
9849
+ let blockType = void 0;
9850
+ return {
9851
+ stream: response.pipeThrough(new TransformStream({ transform(chunk, controller) {
9852
+ var _a$2, _b, _c, _d;
9853
+ if (!chunk.success) {
9854
+ controller.enqueue({
9855
+ type: "error",
9856
+ error: chunk.error
9857
+ });
9858
+ return;
9859
+ }
9860
+ const value = chunk.value;
9861
+ switch (value.type) {
9862
+ case "ping": return;
9863
+ case "content_block_start": {
9864
+ const contentBlockType = value.content_block.type;
9865
+ blockType = contentBlockType;
9866
+ switch (contentBlockType) {
9867
+ case "text":
9868
+ case "thinking": return;
9869
+ case "redacted_thinking": {
9870
+ controller.enqueue({
9871
+ type: "redacted-reasoning",
9872
+ data: value.content_block.data
9873
+ });
9874
+ return;
9875
+ }
9876
+ case "tool_use": {
9877
+ toolCallContentBlocks[value.index] = {
9878
+ toolCallId: value.content_block.id,
9879
+ toolName: value.content_block.name,
9880
+ jsonText: ""
9881
+ };
9882
+ return;
9883
+ }
9884
+ default: {
9885
+ const _exhaustiveCheck = contentBlockType;
9886
+ throw new Error(`Unsupported content block type: ${_exhaustiveCheck}`);
9887
+ }
9888
+ }
9889
+ }
9890
+ case "content_block_stop": {
9891
+ if (toolCallContentBlocks[value.index] != null) {
9892
+ const contentBlock = toolCallContentBlocks[value.index];
9893
+ controller.enqueue({
9894
+ type: "tool-call",
9895
+ toolCallType: "function",
9896
+ toolCallId: contentBlock.toolCallId,
9897
+ toolName: contentBlock.toolName,
9898
+ args: contentBlock.jsonText
9899
+ });
9900
+ delete toolCallContentBlocks[value.index];
9901
+ }
9902
+ blockType = void 0;
9903
+ return;
9904
+ }
9905
+ case "content_block_delta": {
9906
+ const deltaType = value.delta.type;
9907
+ switch (deltaType) {
9908
+ case "text_delta": {
9909
+ controller.enqueue({
9910
+ type: "text-delta",
9911
+ textDelta: value.delta.text
9912
+ });
9913
+ return;
9914
+ }
9915
+ case "thinking_delta": {
9916
+ controller.enqueue({
9917
+ type: "reasoning",
9918
+ textDelta: value.delta.thinking
9919
+ });
9920
+ return;
9921
+ }
9922
+ case "signature_delta": {
9923
+ if (blockType === "thinking") controller.enqueue({
9924
+ type: "reasoning-signature",
9925
+ signature: value.delta.signature
9926
+ });
9927
+ return;
9928
+ }
9929
+ case "input_json_delta": {
9930
+ const contentBlock = toolCallContentBlocks[value.index];
9931
+ controller.enqueue({
9932
+ type: "tool-call-delta",
9933
+ toolCallType: "function",
9934
+ toolCallId: contentBlock.toolCallId,
9935
+ toolName: contentBlock.toolName,
9936
+ argsTextDelta: value.delta.partial_json
9937
+ });
9938
+ contentBlock.jsonText += value.delta.partial_json;
9939
+ return;
9940
+ }
9941
+ default: {
9942
+ const _exhaustiveCheck = deltaType;
9943
+ throw new Error(`Unsupported delta type: ${_exhaustiveCheck}`);
9944
+ }
9945
+ }
9946
+ }
9947
+ case "message_start": {
9948
+ usage.promptTokens = value.message.usage.input_tokens;
9949
+ usage.completionTokens = value.message.usage.output_tokens;
9950
+ providerMetadata = { anthropic: {
9951
+ cacheCreationInputTokens: (_a$2 = value.message.usage.cache_creation_input_tokens) != null ? _a$2 : null,
9952
+ cacheReadInputTokens: (_b = value.message.usage.cache_read_input_tokens) != null ? _b : null
9953
+ } };
9954
+ controller.enqueue({
9955
+ type: "response-metadata",
9956
+ id: (_c = value.message.id) != null ? _c : void 0,
9957
+ modelId: (_d = value.message.model) != null ? _d : void 0
9958
+ });
9959
+ return;
9960
+ }
9961
+ case "message_delta": {
9962
+ usage.completionTokens = value.usage.output_tokens;
9963
+ finishReason = mapAnthropicStopReason(value.delta.stop_reason);
9964
+ return;
9965
+ }
9966
+ case "message_stop": {
9967
+ controller.enqueue({
9968
+ type: "finish",
9969
+ finishReason,
9970
+ usage,
9971
+ providerMetadata
9972
+ });
9973
+ return;
9974
+ }
9975
+ case "error": {
9976
+ controller.enqueue({
9977
+ type: "error",
9978
+ error: value.error
9979
+ });
9980
+ return;
9981
+ }
9982
+ default: {
9983
+ const _exhaustiveCheck = value;
9984
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
9985
+ }
9986
+ }
9987
+ } })),
9988
+ rawCall: {
9989
+ rawPrompt,
9990
+ rawSettings
9991
+ },
9992
+ rawResponse: { headers: responseHeaders },
9993
+ warnings,
9994
+ request: { body: JSON.stringify(body) }
9995
+ };
9996
+ }
9997
+ };
9998
+ var anthropicMessagesResponseSchema = z.object({
9999
+ type: z.literal("message"),
10000
+ id: z.string().nullish(),
10001
+ model: z.string().nullish(),
10002
+ content: z.array(z.discriminatedUnion("type", [
10003
+ z.object({
10004
+ type: z.literal("text"),
10005
+ text: z.string()
10006
+ }),
10007
+ z.object({
10008
+ type: z.literal("thinking"),
10009
+ thinking: z.string(),
10010
+ signature: z.string()
10011
+ }),
10012
+ z.object({
10013
+ type: z.literal("redacted_thinking"),
10014
+ data: z.string()
10015
+ }),
10016
+ z.object({
10017
+ type: z.literal("tool_use"),
10018
+ id: z.string(),
10019
+ name: z.string(),
10020
+ input: z.unknown()
10021
+ })
10022
+ ])),
10023
+ stop_reason: z.string().nullish(),
10024
+ usage: z.object({
10025
+ input_tokens: z.number(),
10026
+ output_tokens: z.number(),
10027
+ cache_creation_input_tokens: z.number().nullish(),
10028
+ cache_read_input_tokens: z.number().nullish()
10029
+ })
10030
+ });
10031
+ var anthropicMessagesChunkSchema = z.discriminatedUnion("type", [
10032
+ z.object({
10033
+ type: z.literal("message_start"),
10034
+ message: z.object({
10035
+ id: z.string().nullish(),
10036
+ model: z.string().nullish(),
10037
+ usage: z.object({
10038
+ input_tokens: z.number(),
10039
+ output_tokens: z.number(),
10040
+ cache_creation_input_tokens: z.number().nullish(),
10041
+ cache_read_input_tokens: z.number().nullish()
10042
+ })
10043
+ })
10044
+ }),
10045
+ z.object({
10046
+ type: z.literal("content_block_start"),
10047
+ index: z.number(),
10048
+ content_block: z.discriminatedUnion("type", [
10049
+ z.object({
10050
+ type: z.literal("text"),
10051
+ text: z.string()
10052
+ }),
10053
+ z.object({
10054
+ type: z.literal("thinking"),
10055
+ thinking: z.string()
10056
+ }),
10057
+ z.object({
10058
+ type: z.literal("tool_use"),
10059
+ id: z.string(),
10060
+ name: z.string()
10061
+ }),
10062
+ z.object({
10063
+ type: z.literal("redacted_thinking"),
10064
+ data: z.string()
10065
+ })
10066
+ ])
10067
+ }),
10068
+ z.object({
10069
+ type: z.literal("content_block_delta"),
10070
+ index: z.number(),
10071
+ delta: z.discriminatedUnion("type", [
10072
+ z.object({
10073
+ type: z.literal("input_json_delta"),
10074
+ partial_json: z.string()
10075
+ }),
10076
+ z.object({
10077
+ type: z.literal("text_delta"),
10078
+ text: z.string()
10079
+ }),
10080
+ z.object({
10081
+ type: z.literal("thinking_delta"),
10082
+ thinking: z.string()
10083
+ }),
10084
+ z.object({
10085
+ type: z.literal("signature_delta"),
10086
+ signature: z.string()
10087
+ })
10088
+ ])
10089
+ }),
10090
+ z.object({
10091
+ type: z.literal("content_block_stop"),
10092
+ index: z.number()
10093
+ }),
10094
+ z.object({
10095
+ type: z.literal("error"),
10096
+ error: z.object({
10097
+ type: z.string(),
10098
+ message: z.string()
10099
+ })
10100
+ }),
10101
+ z.object({
10102
+ type: z.literal("message_delta"),
10103
+ delta: z.object({ stop_reason: z.string().nullish() }),
10104
+ usage: z.object({ output_tokens: z.number() })
10105
+ }),
10106
+ z.object({ type: z.literal("message_stop") }),
10107
+ z.object({ type: z.literal("ping") })
10108
+ ]);
10109
+ var anthropicProviderOptionsSchema = z.object({ thinking: z.object({
10110
+ type: z.union([z.literal("enabled"), z.literal("disabled")]),
10111
+ budgetTokens: z.number().optional()
10112
+ }).optional() });
10113
+ var Bash20241022Parameters = z.object({
10114
+ command: z.string(),
10115
+ restart: z.boolean().optional()
10116
+ });
10117
+ function bashTool_20241022(options = {}) {
10118
+ return {
10119
+ type: "provider-defined",
10120
+ id: "anthropic.bash_20241022",
10121
+ args: {},
10122
+ parameters: Bash20241022Parameters,
10123
+ execute: options.execute,
10124
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10125
+ };
10126
+ }
10127
+ var Bash20250124Parameters = z.object({
10128
+ command: z.string(),
10129
+ restart: z.boolean().optional()
10130
+ });
10131
+ function bashTool_20250124(options = {}) {
10132
+ return {
10133
+ type: "provider-defined",
10134
+ id: "anthropic.bash_20250124",
10135
+ args: {},
10136
+ parameters: Bash20250124Parameters,
10137
+ execute: options.execute,
10138
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10139
+ };
10140
+ }
10141
+ var TextEditor20241022Parameters = z.object({
10142
+ command: z.enum([
10143
+ "view",
10144
+ "create",
10145
+ "str_replace",
10146
+ "insert",
10147
+ "undo_edit"
10148
+ ]),
10149
+ path: z.string(),
10150
+ file_text: z.string().optional(),
10151
+ insert_line: z.number().int().optional(),
10152
+ new_str: z.string().optional(),
10153
+ old_str: z.string().optional(),
10154
+ view_range: z.array(z.number().int()).optional()
10155
+ });
10156
+ function textEditorTool_20241022(options = {}) {
10157
+ return {
10158
+ type: "provider-defined",
10159
+ id: "anthropic.text_editor_20241022",
10160
+ args: {},
10161
+ parameters: TextEditor20241022Parameters,
10162
+ execute: options.execute,
10163
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10164
+ };
10165
+ }
10166
+ var TextEditor20250124Parameters = z.object({
10167
+ command: z.enum([
10168
+ "view",
10169
+ "create",
10170
+ "str_replace",
10171
+ "insert",
10172
+ "undo_edit"
10173
+ ]),
10174
+ path: z.string(),
10175
+ file_text: z.string().optional(),
10176
+ insert_line: z.number().int().optional(),
10177
+ new_str: z.string().optional(),
10178
+ old_str: z.string().optional(),
10179
+ view_range: z.array(z.number().int()).optional()
10180
+ });
10181
+ function textEditorTool_20250124(options = {}) {
10182
+ return {
10183
+ type: "provider-defined",
10184
+ id: "anthropic.text_editor_20250124",
10185
+ args: {},
10186
+ parameters: TextEditor20250124Parameters,
10187
+ execute: options.execute,
10188
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10189
+ };
10190
+ }
10191
+ var Computer20241022Parameters = z.object({
10192
+ action: z.enum([
10193
+ "key",
10194
+ "type",
10195
+ "mouse_move",
10196
+ "left_click",
10197
+ "left_click_drag",
10198
+ "right_click",
10199
+ "middle_click",
10200
+ "double_click",
10201
+ "screenshot",
10202
+ "cursor_position"
10203
+ ]),
10204
+ coordinate: z.array(z.number().int()).optional(),
10205
+ text: z.string().optional()
10206
+ });
10207
+ function computerTool_20241022(options) {
10208
+ return {
10209
+ type: "provider-defined",
10210
+ id: "anthropic.computer_20241022",
10211
+ args: {
10212
+ displayWidthPx: options.displayWidthPx,
10213
+ displayHeightPx: options.displayHeightPx,
10214
+ displayNumber: options.displayNumber
10215
+ },
10216
+ parameters: Computer20241022Parameters,
10217
+ execute: options.execute,
10218
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10219
+ };
10220
+ }
10221
+ var Computer20250124Parameters = z.object({
10222
+ action: z.enum([
10223
+ "key",
10224
+ "hold_key",
10225
+ "type",
10226
+ "cursor_position",
10227
+ "mouse_move",
10228
+ "left_mouse_down",
10229
+ "left_mouse_up",
10230
+ "left_click",
10231
+ "left_click_drag",
10232
+ "right_click",
10233
+ "middle_click",
10234
+ "double_click",
10235
+ "triple_click",
10236
+ "scroll",
10237
+ "wait",
10238
+ "screenshot"
10239
+ ]),
10240
+ coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
10241
+ duration: z.number().optional(),
10242
+ scroll_amount: z.number().optional(),
10243
+ scroll_direction: z.enum([
10244
+ "up",
10245
+ "down",
10246
+ "left",
10247
+ "right"
10248
+ ]).optional(),
10249
+ start_coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
10250
+ text: z.string().optional()
10251
+ });
10252
+ function computerTool_20250124(options) {
10253
+ return {
10254
+ type: "provider-defined",
10255
+ id: "anthropic.computer_20250124",
10256
+ args: {
10257
+ displayWidthPx: options.displayWidthPx,
10258
+ displayHeightPx: options.displayHeightPx,
10259
+ displayNumber: options.displayNumber
10260
+ },
10261
+ parameters: Computer20250124Parameters,
10262
+ execute: options.execute,
10263
+ experimental_toToolResultContent: options.experimental_toToolResultContent
10264
+ };
10265
+ }
10266
+ var anthropicTools = {
10267
+ bash_20241022: bashTool_20241022,
10268
+ bash_20250124: bashTool_20250124,
10269
+ textEditor_20241022: textEditorTool_20241022,
10270
+ textEditor_20250124: textEditorTool_20250124,
10271
+ computer_20241022: computerTool_20241022,
10272
+ computer_20250124: computerTool_20250124
10273
+ };
10274
+ function createAnthropic(options = {}) {
10275
+ var _a$2;
10276
+ const baseURL = (_a$2 = withoutTrailingSlash(options.baseURL)) != null ? _a$2 : "https://api.anthropic.com/v1";
10277
+ const getHeaders = () => ({
10278
+ "anthropic-version": "2023-06-01",
10279
+ "x-api-key": loadApiKey({
10280
+ apiKey: options.apiKey,
10281
+ environmentVariableName: "ANTHROPIC_API_KEY",
10282
+ description: "Anthropic"
10283
+ }),
10284
+ ...options.headers
10285
+ });
10286
+ const createChatModel = (modelId, settings = {}) => new AnthropicMessagesLanguageModel(modelId, settings, {
10287
+ provider: "anthropic.messages",
10288
+ baseURL,
10289
+ headers: getHeaders,
10290
+ fetch: options.fetch,
10291
+ supportsImageUrls: true
10292
+ });
10293
+ const provider = function(modelId, settings) {
10294
+ if (new.target) throw new Error("The Anthropic model function cannot be called with the new keyword.");
10295
+ return createChatModel(modelId, settings);
10296
+ };
10297
+ provider.languageModel = createChatModel;
10298
+ provider.chat = createChatModel;
10299
+ provider.messages = createChatModel;
10300
+ provider.textEmbeddingModel = (modelId) => {
10301
+ throw new NoSuchModelError({
10302
+ modelId,
10303
+ modelType: "textEmbeddingModel"
10304
+ });
10305
+ };
10306
+ provider.tools = anthropicTools;
10307
+ return provider;
10308
+ }
10309
+ var anthropic = createAnthropic();
10310
+
10311
+ //#endregion
10312
+ //#region ../mcp-core/dist/anthropic-provider-BGKT8f9G.js
10313
+ const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-5";
10314
+ let configuredBaseUrl;
10315
+ /**
10316
+ * Configure the Anthropic base URL (CLI flag only, not environment variable).
10317
+ * This must be called explicitly - it cannot be set via environment variables for security.
10318
+ */
10319
+ function setAnthropicBaseUrl(baseUrl) {
10320
+ configuredBaseUrl = baseUrl;
10321
+ }
10322
+ /**
10323
+ * Retrieve an Anthropic language model configured from environment variables and explicit config.
10324
+ *
10325
+ * Configuration:
10326
+ * - ANTHROPIC_MODEL: Model to use (default: "claude-sonnet-4-5") - env var OK
10327
+ * - Base URL: Must be set via setAnthropicBaseUrl() - NOT from env vars (security risk)
10328
+ */
10329
+ function getAnthropicModel(model) {
10330
+ const defaultModel = process.env.ANTHROPIC_MODEL || DEFAULT_ANTHROPIC_MODEL;
10331
+ const factory = createAnthropic({
10332
+ ...configuredBaseUrl && { baseURL: configuredBaseUrl },
10333
+ headers: { "User-Agent": USER_AGENT }
10334
+ });
10335
+ return factory(model ?? defaultModel);
10336
+ }
10337
+
10338
+ //#endregion
10339
+ //#region ../mcp-core/dist/provider-factory-Bxvb4LE7.js
10340
+ let configuredProvider;
10341
+ /**
10342
+ * Configure the embedded agent provider explicitly.
10343
+ * Call this from CLI to override auto-detection.
10344
+ */
10345
+ function setAgentProvider(provider) {
10346
+ configuredProvider = provider;
10347
+ }
10348
+ /**
10349
+ * Configure base URLs for providers (called from CLI).
10350
+ */
10351
+ function setProviderBaseUrls(config) {
10352
+ if (config.openaiBaseUrl) setOpenAIBaseUrl(config.openaiBaseUrl);
10353
+ if (config.anthropicBaseUrl) setAnthropicBaseUrl(config.anthropicBaseUrl);
10354
+ }
10355
+ /**
10356
+ * Check if the API key exists for a given provider type.
10357
+ */
10358
+ function hasApiKeyForProvider(type) {
10359
+ switch (type) {
10360
+ case "anthropic": return Boolean(process.env.ANTHROPIC_API_KEY);
10361
+ case "openai": return Boolean(process.env.OPENAI_API_KEY);
10362
+ }
10363
+ }
10364
+ /**
10365
+ * Get the expected API key name for a provider type.
10366
+ */
10367
+ function getApiKeyName(type) {
10368
+ switch (type) {
10369
+ case "anthropic": return "ANTHROPIC_API_KEY";
10370
+ case "openai": return "OPENAI_API_KEY";
10371
+ }
10372
+ }
10373
+ /**
10374
+ * Build a provider instance for the given type.
10375
+ */
10376
+ function buildProvider(type) {
10377
+ switch (type) {
10378
+ case "anthropic": return {
10379
+ type: "anthropic",
10380
+ getModel: getAnthropicModel,
10381
+ getProviderOptions: () => ({}),
10382
+ getTemperature: () => void 0
10383
+ };
10384
+ case "openai": return {
10385
+ type: "openai",
10386
+ getModel: getOpenAIModel,
10387
+ getProviderOptions: () => ({ openai: {
10388
+ structuredOutputs: false,
10389
+ strictJsonSchema: false
10390
+ } }),
10391
+ getTemperature: () => 1
10392
+ };
10393
+ }
10394
+ }
10395
+ /**
10396
+ * Get the current agent provider based on configuration.
10397
+ *
10398
+ * Resolution order:
10399
+ * 1. Explicit configuration via setAgentProvider()
10400
+ * 2. EMBEDDED_AGENT_PROVIDER environment variable
10401
+ * 3. Auto-detect: check ANTHROPIC_API_KEY, then OPENAI_API_KEY
10402
+ * 4. Throw ConfigurationError if no provider available
10403
+ */
10404
+ function getAgentProvider() {
10405
+ let providerType = configuredProvider;
10406
+ if (!providerType) {
10407
+ const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10408
+ if (envProvider === "openai" || envProvider === "anthropic") providerType = envProvider;
10409
+ }
10410
+ if (providerType && !hasApiKeyForProvider(providerType)) throw new ConfigurationError(`Provider "${providerType}" is configured but ${getApiKeyName(providerType)} is not set. Please set the API key environment variable.`);
10411
+ if (!providerType) {
10412
+ if (process.env.ANTHROPIC_API_KEY) providerType = "anthropic";
10413
+ else if (process.env.OPENAI_API_KEY) providerType = "openai";
10414
+ }
10415
+ 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.");
10416
+ return buildProvider(providerType);
10417
+ }
10418
+ /**
10419
+ * Check if an embedded agent provider is available.
10420
+ * Returns true if getAgentProvider() would succeed.
10421
+ */
10422
+ function hasAgentProvider() {
10423
+ try {
10424
+ getAgentProvider();
10425
+ return true;
10426
+ } catch {
10427
+ return false;
10428
+ }
10429
+ }
10430
+ /**
10431
+ * Get the resolved provider type without throwing.
10432
+ * Returns undefined if no provider is available or API key is missing.
10433
+ */
10434
+ function getResolvedProviderType() {
10435
+ if (configuredProvider) return hasApiKeyForProvider(configuredProvider) ? configuredProvider : void 0;
10436
+ const envProvider = process.env.EMBEDDED_AGENT_PROVIDER?.toLowerCase();
10437
+ if (envProvider === "openai" || envProvider === "anthropic") return hasApiKeyForProvider(envProvider) ? envProvider : void 0;
10438
+ if (process.env.ANTHROPIC_API_KEY) return "anthropic";
10439
+ if (process.env.OPENAI_API_KEY) return "openai";
10440
+ return void 0;
10441
+ }
10442
+
10443
+ //#endregion
10444
+ //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js
10445
+ const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
10446
+ const defaultOptions = {
10447
+ name: void 0,
10448
+ $refStrategy: "root",
10449
+ basePath: ["#"],
10450
+ effectStrategy: "input",
10451
+ pipeStrategy: "all",
10452
+ dateStrategy: "format:date-time",
10453
+ mapStrategy: "entries",
10454
+ removeAdditionalStrategy: "passthrough",
10455
+ allowedAdditionalProperties: true,
10456
+ rejectedAdditionalProperties: false,
10457
+ definitionPath: "definitions",
10458
+ target: "jsonSchema7",
10459
+ strictUnions: false,
10460
+ definitions: {},
10461
+ errorMessages: false,
10462
+ markdownDescription: false,
10463
+ patternStrategy: "escape",
10464
+ applyRegexFlags: false,
10465
+ emailStrategy: "format:email",
10466
+ base64Strategy: "contentEncoding:base64",
10467
+ nameStrategy: "ref",
10468
+ openAiAnyTypeName: "OpenAiAnyType"
10469
+ };
10470
+ const getDefaultOptions = (options) => typeof options === "string" ? {
10471
+ ...defaultOptions,
10472
+ name: options
10473
+ } : {
10474
+ ...defaultOptions,
10475
+ ...options
10476
+ };
10477
+
10478
+ //#endregion
10479
+ //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js
10480
+ const getRefs = (options) => {
10481
+ const _options = getDefaultOptions(options);
10482
+ const currentPath = _options.name !== void 0 ? [
10483
+ ..._options.basePath,
10484
+ _options.definitionPath,
10485
+ _options.name
10486
+ ] : _options.basePath;
10487
+ return {
10488
+ ..._options,
10489
+ flags: { hasReferencedOpenAiAnyType: false },
10490
+ currentPath,
10491
+ propertyPath: void 0,
10492
+ seen: new Map(Object.entries(_options.definitions).map(([name$2, def]) => [def._def, {
10493
+ def: def._def,
10494
+ path: [
10495
+ ..._options.basePath,
10496
+ _options.definitionPath,
10497
+ name$2
10498
+ ],
10499
+ jsonSchema: void 0
10500
+ }]))
10501
+ };
10502
+ };
10503
+
10504
+ //#endregion
10505
+ //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
10506
+ function addErrorMessage(res, key, errorMessage, refs) {
10507
+ if (!refs?.errorMessages) return;
10508
+ if (errorMessage) res.errorMessage = {
10509
+ ...res.errorMessage,
10510
+ [key]: errorMessage
10511
+ };
10512
+ }
10513
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
10514
+ res[key] = value;
10515
+ addErrorMessage(res, key, errorMessage, refs);
10516
+ }
10517
+
10518
+ //#endregion
10519
+ //#region ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
9081
10520
  const getRelativePath = (pathA, pathB) => {
9082
10521
  let i = 0;
9083
10522
  for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
@@ -13853,8 +15292,8 @@ var SseMCPTransport = class {
13853
15292
  this.headers = headers;
13854
15293
  }
13855
15294
  async start() {
13856
- return new Promise((resolve, reject) => {
13857
- if (this.connected) return resolve();
15295
+ return new Promise((resolve$1, reject) => {
15296
+ if (this.connected) return resolve$1();
13858
15297
  this.abortController = new AbortController();
13859
15298
  const establishConnection = async () => {
13860
15299
  var _a17, _b, _c;
@@ -13889,7 +15328,7 @@ var SseMCPTransport = class {
13889
15328
  this.endpoint = new URL(data, this.url);
13890
15329
  if (this.endpoint.origin !== this.url.origin) throw new MCPClientError({ message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}` });
13891
15330
  this.connected = true;
13892
- resolve();
15331
+ resolve$1();
13893
15332
  } else if (event === "message") try {
13894
15333
  const message = JSONRPCMessageSchema.parse(JSON.parse(data));
13895
15334
  (_a18 = this.onmessage) == null || _a18.call(this, message);
@@ -14028,7 +15467,7 @@ var MCPClient = class {
14028
15467
  }
14029
15468
  }
14030
15469
  async request({ request, resultSchema, options }) {
14031
- return new Promise((resolve, reject) => {
15470
+ return new Promise((resolve$1, reject) => {
14032
15471
  if (this.isClosed) return reject(new MCPClientError({ message: "Attempted to send a request from a closed client" }));
14033
15472
  this.assertCapability(request.method);
14034
15473
  const signal = options == null ? void 0 : options.signal;
@@ -14050,7 +15489,7 @@ var MCPClient = class {
14050
15489
  if (response instanceof Error) return reject(response);
14051
15490
  try {
14052
15491
  const result = resultSchema.parse(response.result);
14053
- resolve(result);
15492
+ resolve$1(result);
14054
15493
  } catch (error) {
14055
15494
  const parseError = new MCPClientError({
14056
15495
  message: "Failed to parse server response",
@@ -14277,7 +15716,7 @@ function trimStartOfStream() {
14277
15716
  var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
14278
15717
 
14279
15718
  //#endregion
14280
- //#region ../mcp-core/dist/callEmbeddedAgent-C4iLIZ6C.js
15719
+ //#region ../mcp-core/dist/callEmbeddedAgent--R3kwqbb.js
14281
15720
  /**
14282
15721
  * Call an embedded agent with tool call capture
14283
15722
  * This is the standard way to call embedded AI agents within MCP tools
@@ -14288,22 +15727,20 @@ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
14288
15727
  */
14289
15728
  async function callEmbeddedAgent({ system, prompt, tools, schema }) {
14290
15729
  const capturedToolCalls = [];
15730
+ const provider = getAgentProvider();
14291
15731
  const result = await generateText({
14292
- model: getOpenAIModel(),
15732
+ model: provider.getModel(),
14293
15733
  system,
14294
15734
  prompt,
14295
15735
  tools,
14296
15736
  maxSteps: 5,
14297
- temperature: 1,
15737
+ ...provider.getTemperature() !== void 0 && { temperature: provider.getTemperature() },
14298
15738
  experimental_output: output_exports.object({ schema }),
14299
15739
  experimental_telemetry: {
14300
15740
  isEnabled: true,
14301
15741
  functionId: "callEmbeddedAgent"
14302
15742
  },
14303
- providerOptions: { openai: {
14304
- structuredOutputs: false,
14305
- strictJsonSchema: false
14306
- } },
15743
+ providerOptions: provider.getProviderOptions(),
14307
15744
  onStepFinish: (event) => {
14308
15745
  if (event.toolCalls && event.toolCalls.length > 0) for (const toolCall of event.toolCalls) capturedToolCalls.push({
14309
15746
  toolName: toolCall.toolName,
@@ -14323,7 +15760,7 @@ async function callEmbeddedAgent({ system, prompt, tools, schema }) {
14323
15760
  }
14324
15761
 
14325
15762
  //#endregion
14326
- //#region ../mcp-core/dist/utils-wepw5Cmn.js
15763
+ //#region ../mcp-core/dist/utils-BhgZ4dUB.js
14327
15764
  /**
14328
15765
  * Standard response schema for all embedded agent tools.
14329
15766
  * Tools return either an error message or the result data, never both.
@@ -14405,7 +15842,7 @@ function agentTool(config) {
14405
15842
  }
14406
15843
 
14407
15844
  //#endregion
14408
- //#region ../mcp-core/dist/otel-semantics-ji8CZiqz.js
15845
+ //#region ../mcp-core/dist/otel-semantics-B5qAIqUa.js
14409
15846
  var namespace$72 = "android";
14410
15847
  var description$72 = "The Android platform on which the Android application is running.\n";
14411
15848
  var attributes$72 = {
@@ -19251,7 +20688,7 @@ function createOtelLookupTool(options) {
19251
20688
  }
19252
20689
 
19253
20690
  //#endregion
19254
- //#region ../mcp-core/dist/whoami-B-N3_K3B.js
20691
+ //#region ../mcp-core/dist/whoami-CnHpsyv0.js
19255
20692
  /**
19256
20693
  * Get the current authenticated user's information from Sentry API
19257
20694
  */
@@ -19280,7 +20717,7 @@ function createWhoamiTool(options) {
19280
20717
  }
19281
20718
 
19282
20719
  //#endregion
19283
- //#region ../mcp-core/dist/utils-Dehfm_qW.js
20720
+ //#region ../mcp-core/dist/utils-CRDu-UNV.js
19284
20721
  function getStringValue(event, key, defaultValue = "") {
19285
20722
  const value = event[key];
19286
20723
  return typeof value === "string" ? value : defaultValue;
@@ -19333,14 +20770,14 @@ function createDatasetAttributesTool(options) {
19333
20770
  "logs"
19334
20771
  ]).describe("The dataset to query attributes for") }),
19335
20772
  execute: async ({ dataset }) => {
19336
- const { BASE_COMMON_FIELDS, DATASET_FIELDS, RECOMMENDED_FIELDS: RECOMMENDED_FIELDS$1, NUMERIC_FIELDS, DATASET_EXAMPLES } = await import("./config-BEgU9ylR.js");
20773
+ const { BASE_COMMON_FIELDS, DATASET_FIELDS, RECOMMENDED_FIELDS: RECOMMENDED_FIELDS$2, NUMERIC_FIELDS, DATASET_EXAMPLES } = await import("./config-HqPAzoGg.js");
19337
20774
  const { attributes: customAttributes, fieldTypes } = await fetchCustomAttributes(apiService, organizationSlug, dataset, projectId);
19338
20775
  const allFields = {
19339
20776
  ...BASE_COMMON_FIELDS,
19340
20777
  ...DATASET_FIELDS[dataset],
19341
20778
  ...customAttributes
19342
20779
  };
19343
- const recommendedFields = RECOMMENDED_FIELDS$1[dataset];
20780
+ const recommendedFields = RECOMMENDED_FIELDS$2[dataset];
19344
20781
  const allFieldTypes = { ...fieldTypes };
19345
20782
  const staticNumericFields = NUMERIC_FIELDS[dataset] || /* @__PURE__ */ new Set();
19346
20783
  for (const field of staticNumericFields) allFieldTypes[field] = "number";
@@ -19368,7 +20805,7 @@ Use these examples as patterns for constructing your query.`;
19368
20805
  }
19369
20806
 
19370
20807
  //#endregion
19371
- //#region ../mcp-core/dist/agent-B24BDcpH.js
20808
+ //#region ../mcp-core/dist/agent-C5-b2G06.js
19372
20809
  const searchEventsAgentOutputSchema = z.object({
19373
20810
  dataset: z.enum([
19374
20811
  "spans",
@@ -19397,7 +20834,6 @@ const searchEventsAgentOutputSchema = z.object({
19397
20834
  * This returns both the translated query result AND the tool calls made by the agent
19398
20835
  */
19399
20836
  async function searchEventsAgent(options) {
19400
- if (!process.env.OPENAI_API_KEY) throw new ConfigurationError("OPENAI_API_KEY environment variable is required for semantic search");
19401
20837
  const datasetAttributesTool = createDatasetAttributesTool({
19402
20838
  apiService: options.apiService,
19403
20839
  organizationSlug: options.organizationSlug,
@@ -19422,7 +20858,7 @@ async function searchEventsAgent(options) {
19422
20858
  }
19423
20859
 
19424
20860
  //#endregion
19425
- //#region ../mcp-core/dist/formatters-CBiThZnb.js
20861
+ //#region ../mcp-core/dist/formatters-CJK-ciCF.js
19426
20862
  /**
19427
20863
  * Format an explanation for how a natural language query was translated
19428
20864
  */
@@ -19640,7 +21076,7 @@ function formatSpanResults(params) {
19640
21076
  }
19641
21077
 
19642
21078
  //#endregion
19643
- //#region ../mcp-core/dist/handler-BV5deuNu.js
21079
+ //#region ../mcp-core/dist/handler-BDtOWjBO.js
19644
21080
  var handler_default = defineTool({
19645
21081
  name: "search_events",
19646
21082
  skills: [
@@ -19781,7 +21217,7 @@ var handler_default = defineTool({
19781
21217
  });
19782
21218
 
19783
21219
  //#endregion
19784
- //#region ../mcp-core/dist/create-team-Dy96alMI.js
21220
+ //#region ../mcp-core/dist/create-team-BNRuwaPN.js
19785
21221
  var create_team_default = defineTool({
19786
21222
  name: "create_team",
19787
21223
  skills: ["project-management"],
@@ -19836,7 +21272,7 @@ var create_team_default = defineTool({
19836
21272
  });
19837
21273
 
19838
21274
  //#endregion
19839
- //#region ../mcp-core/dist/create-project-CgOCqPNP.js
21275
+ //#region ../mcp-core/dist/create-project-CagAItcQ.js
19840
21276
  var create_project_default = defineTool({
19841
21277
  name: "create_project",
19842
21278
  skills: ["project-management"],
@@ -19913,7 +21349,7 @@ var create_project_default = defineTool({
19913
21349
  });
19914
21350
 
19915
21351
  //#endregion
19916
- //#region ../mcp-core/dist/update-project-CMtXKaXN.js
21352
+ //#region ../mcp-core/dist/update-project-C3HNKHy3.js
19917
21353
  var update_project_default = defineTool({
19918
21354
  name: "update_project",
19919
21355
  skills: ["project-management"],
@@ -20031,7 +21467,7 @@ var update_project_default = defineTool({
20031
21467
  });
20032
21468
 
20033
21469
  //#endregion
20034
- //#region ../mcp-core/dist/create-dsn-C-zvRMtE.js
21470
+ //#region ../mcp-core/dist/create-dsn-qX9dkWBv.js
20035
21471
  var create_dsn_default = defineTool({
20036
21472
  name: "create_dsn",
20037
21473
  skills: ["project-management"],
@@ -20091,7 +21527,7 @@ var create_dsn_default = defineTool({
20091
21527
  });
20092
21528
 
20093
21529
  //#endregion
20094
- //#region ../mcp-core/dist/find-dsns-sufkfAux.js
21530
+ //#region ../mcp-core/dist/find-dsns-DQL7wv5D.js
20095
21531
  var find_dsns_default = defineTool({
20096
21532
  name: "find_dsns",
20097
21533
  skills: ["project-management"],
@@ -20142,7 +21578,7 @@ var find_dsns_default = defineTool({
20142
21578
  });
20143
21579
 
20144
21580
  //#endregion
20145
- //#region ../mcp-core/dist/fetch-utils-C6qSgZai.js
21581
+ //#region ../mcp-core/dist/fetch-utils-LjUGSOvJ.js
20146
21582
  /**
20147
21583
  * Fetch with timeout using AbortController
20148
21584
  * @param url - The URL to fetch
@@ -20185,14 +21621,14 @@ async function retryWithBackoff(fn, { maxRetries = 3, initialDelay = 1e3, should
20185
21621
  } catch (error) {
20186
21622
  lastError = error;
20187
21623
  if (attempt === maxRetries || !shouldRetry(error)) throw error;
20188
- await new Promise((resolve) => setTimeout(resolve, delay$1));
21624
+ await new Promise((resolve$1) => setTimeout(resolve$1, delay$1));
20189
21625
  delay$1 = Math.min(delay$1 * 2, 3e4);
20190
21626
  }
20191
21627
  throw lastError;
20192
21628
  }
20193
21629
 
20194
21630
  //#endregion
20195
- //#region ../mcp-core/dist/analyze-issue-with-seer-jcYxRIL1.js
21631
+ //#region ../mcp-core/dist/analyze-issue-with-seer-B6aDeTwi.js
20196
21632
  var analyze_issue_with_seer_default = defineTool({
20197
21633
  name: "analyze_issue_with_seer",
20198
21634
  skills: ["seer"],
@@ -20252,7 +21688,7 @@ var analyze_issue_with_seer_default = defineTool({
20252
21688
  },
20253
21689
  async handler(params, context$1) {
20254
21690
  const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
20255
- const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams({
21691
+ const { organizationSlug: orgSlug, issueId: parsedIssueId } = parseIssueParams$1({
20256
21692
  organizationSlug: params.organizationSlug,
20257
21693
  issueId: params.issueId,
20258
21694
  issueUrl: params.issueUrl
@@ -20277,7 +21713,7 @@ var analyze_issue_with_seer_default = defineTool({
20277
21713
  instruction: params.instruction
20278
21714
  });
20279
21715
  output += `Analysis started with Run ID: ${startResult.run_id}\n\n`;
20280
- await new Promise((resolve) => setTimeout(resolve, 1e3));
21716
+ await new Promise((resolve$1) => setTimeout(resolve$1, 1e3));
20281
21717
  autofixState = await retryWithBackoff(() => apiService.getAutofixState({
20282
21718
  organizationSlug: orgSlug,
20283
21719
  issueId: parsedIssueId
@@ -20334,7 +21770,7 @@ var analyze_issue_with_seer_default = defineTool({
20334
21770
  if (activeStep) output += `Processing: ${activeStep.title}...\n`;
20335
21771
  lastStatus = status;
20336
21772
  }
20337
- await new Promise((resolve) => setTimeout(resolve, SEER_POLLING_INTERVAL));
21773
+ await new Promise((resolve$1) => setTimeout(resolve$1, SEER_POLLING_INTERVAL));
20338
21774
  try {
20339
21775
  autofixState = await retryWithBackoff(() => apiService.getAutofixState({
20340
21776
  organizationSlug: orgSlug,
@@ -20380,7 +21816,7 @@ var analyze_issue_with_seer_default = defineTool({
20380
21816
  });
20381
21817
 
20382
21818
  //#endregion
20383
- //#region ../mcp-core/dist/search-docs-BzvTE9Na.js
21819
+ //#region ../mcp-core/dist/search-docs-yQc8o0ap.js
20384
21820
  var search_docs_default = defineTool({
20385
21821
  name: "search_docs",
20386
21822
  skills: ["docs"],
@@ -20463,7 +21899,7 @@ var search_docs_default = defineTool({
20463
21899
  });
20464
21900
 
20465
21901
  //#endregion
20466
- //#region ../mcp-core/dist/get-doc-CImfwkht.js
21902
+ //#region ../mcp-core/dist/get-doc-BuXsge2G.js
20467
21903
  var get_doc_default = defineTool({
20468
21904
  name: "get_doc",
20469
21905
  skills: ["docs"],
@@ -20540,7 +21976,7 @@ var get_doc_default = defineTool({
20540
21976
  });
20541
21977
 
20542
21978
  //#endregion
20543
- //#region ../mcp-core/dist/dataset-fields-nvbboMpe.js
21979
+ //#region ../mcp-core/dist/dataset-fields-ClLuCTh4.js
20544
21980
  /**
20545
21981
  * Discover available fields for a dataset by querying Sentry's tags API
20546
21982
  */
@@ -20690,11 +22126,11 @@ function getCommonPatterns(dataset) {
20690
22126
  }
20691
22127
 
20692
22128
  //#endregion
20693
- //#region ../mcp-core/dist/config-BFaJp4hW.js
22129
+ //#region ../mcp-core/dist/config-C3fctASk.js
20694
22130
  /**
20695
22131
  * Configuration for the search-issues agent
20696
22132
  */
20697
- const systemPrompt$2 = `You are a Sentry issue search query translator. Convert natural language queries to Sentry issue search syntax.
22133
+ const systemPrompt$3 = `You are a Sentry issue search query translator. Convert natural language queries to Sentry issue search syntax.
20698
22134
 
20699
22135
  IMPORTANT RULES:
20700
22136
  1. Use Sentry issue search syntax, NOT SQL
@@ -20708,13 +22144,16 @@ BUILT-IN FIELDS:
20708
22144
  - level: Severity level (error, warning, info, debug, fatal)
20709
22145
  IMPORTANT: Almost NEVER use this field. Terms like "critical", "important", "severe" refer to IMPACT not level.
20710
22146
  Only use if user explicitly says "error level", "warning level", etc.
22147
+ - issueCategory: Issue classification (error, performance, metric, feedback)
22148
+ IMPORTANT: User feedback from the User Feedback Widget is stored as issues with issueCategory:feedback
22149
+ Use this field when users ask about "user feedback", "feedback submissions", "user reports", etc.
20711
22150
  - environment: Deployment environment (production, staging, development)
20712
22151
  - release: Version/release identifier
20713
22152
  - firstSeen: When the issue was FIRST encountered (use for "new issues", "started", "began")
20714
22153
  WARNING: Excludes ongoing issues that started before the time window
20715
22154
  - lastSeen: When the issue was LAST encountered (use for "from the last", "recent", "active")
20716
22155
  This includes ALL issues seen during the time window, regardless of when they started
20717
- - assigned: Issues explicitly assigned to a user (email or "me")
22156
+ - assigned: Issues explicitly assigned to a user (email or "me")
20718
22157
  - assignedOrSuggested: Issues assigned to OR suggested for a user (broader match)
20719
22158
  - userCount: Number of unique users affected
20720
22159
  - eventCount: Total number of events
@@ -20726,6 +22165,9 @@ COMMON QUERY PATTERNS:
20726
22165
  - New issues: firstSeen:-7d
20727
22166
  - High impact: userCount:>100
20728
22167
  - My work: assignedOrSuggested:me
22168
+ - User feedback: issueCategory:feedback
22169
+ - Recent feedback: issueCategory:feedback lastSeen:-7d
22170
+ - Feedback from production: issueCategory:feedback environment:production
20729
22171
 
20730
22172
  SORTING RULES:
20731
22173
  1. CRITICAL: Sort MUST go in the separate "sort" field, NEVER in the "query" field
@@ -20749,6 +22191,8 @@ EXAMPLES:
20749
22191
  "critical bugs" → query: "level:error is:unresolved", sort: "date"
20750
22192
  "worst issues affecting the most users" → query: "is:unresolved", sort: "user"
20751
22193
  "assigned to john@example.com" → query: "assignedOrSuggested:john@example.com", sort: "date"
22194
+ "show me user feedback" → query: "issueCategory:feedback", sort: "date"
22195
+ "feedback from the last week" → query: "issueCategory:feedback lastSeen:-7d", sort: "date"
20752
22196
 
20753
22197
  NEVER: query: "is:unresolved sort:user" ← Sort goes in separate field!
20754
22198
 
@@ -20762,7 +22206,7 @@ Always use the issueFields tool to discover available fields when needed.
20762
22206
  Use the whoami tool when you need to resolve 'me' references.`;
20763
22207
 
20764
22208
  //#endregion
20765
- //#region ../mcp-core/dist/agent-4n2tvUk3.js
22209
+ //#region ../mcp-core/dist/agent-BDHlBFe8.js
20766
22210
  const searchIssuesAgentOutputSchema = z.object({
20767
22211
  query: z.string().describe("The Sentry issue search query"),
20768
22212
  sort: z.enum([
@@ -20778,9 +22222,8 @@ const searchIssuesAgentOutputSchema = z.object({
20778
22222
  * This returns both the translated query result AND the tool calls made by the agent
20779
22223
  */
20780
22224
  async function searchIssuesAgent(options) {
20781
- if (!process.env.OPENAI_API_KEY) throw new ConfigurationError("OPENAI_API_KEY environment variable is required for semantic search");
20782
22225
  return await callEmbeddedAgent({
20783
- system: systemPrompt$2,
22226
+ system: systemPrompt$3,
20784
22227
  prompt: options.query,
20785
22228
  tools: {
20786
22229
  issueFields: createDatasetFieldsTool({
@@ -20796,7 +22239,7 @@ async function searchIssuesAgent(options) {
20796
22239
  }
20797
22240
 
20798
22241
  //#endregion
20799
- //#region ../mcp-core/dist/formatters-W4LF85x9.js
22242
+ //#region ../mcp-core/dist/formatters-BcLCXcro.js
20800
22243
  /**
20801
22244
  * Format an explanation for how a natural language query was translated
20802
22245
  */
@@ -20839,6 +22282,7 @@ function formatIssueResults(params) {
20839
22282
  output += `## ${index + 1}. [${issue.shortId}](${issueUrl})\n\n`;
20840
22283
  output += `**${issue.title}**\n\n`;
20841
22284
  output += `- **Status**: ${issue.status}\n`;
22285
+ if (issue.issueCategory && issue.issueCategory !== "error") output += `- **Category**: ${issue.issueCategory}\n`;
20842
22286
  output += `- **Users**: ${issue.userCount || 0}\n`;
20843
22287
  output += `- **Events**: ${issue.count || 0}\n`;
20844
22288
  if (issue.assignedTo) {
@@ -20855,6 +22299,8 @@ function formatIssueResults(params) {
20855
22299
  output += "- Get more details about a specific issue: Use the Issue ID with get_issue_details\n";
20856
22300
  output += "- Update issue status: Use update_issue to resolve or assign issues\n";
20857
22301
  output += "- View event counts: Use search_events for aggregated statistics\n";
22302
+ const hasFeedback = issues.some((i) => i.issueCategory === "feedback");
22303
+ if (hasFeedback) output += "- View feedback details: Use get_issue_details to see full feedback content and linked error events\n";
20858
22304
  return output;
20859
22305
  }
20860
22306
  /**
@@ -20873,11 +22319,11 @@ function formatDate(dateString) {
20873
22319
  if (diffHours < 24) return `${diffHours} hour${diffHours === 1 ? "" : "s"} ago`;
20874
22320
  const diffDays = Math.floor(diffHours / 24);
20875
22321
  if (diffDays < 30) return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
20876
- return date.toLocaleDateString();
22322
+ return date.toISOString().split("T")[0];
20877
22323
  }
20878
22324
 
20879
22325
  //#endregion
20880
- //#region ../mcp-core/dist/handler-DqBNjidz.js
22326
+ //#region ../mcp-core/dist/handler-CzGXq51l.js
20881
22327
  var handler_default$1 = defineTool({
20882
22328
  name: "search_issues",
20883
22329
  skills: [
@@ -20897,6 +22343,7 @@ var handler_default$1 = defineTool({
20897
22343
  "- Filtered issue lists: 'unresolved issues', 'critical bugs'",
20898
22344
  "- Issues by impact: 'errors affecting more than 100 users'",
20899
22345
  "- Issues by assignment: 'issues assigned to me'",
22346
+ "- User feedback: 'show me user feedback', 'feedback from last week'",
20900
22347
  "",
20901
22348
  "DO NOT USE FOR COUNTS/AGGREGATIONS:",
20902
22349
  "- 'how many errors' → use search_events",
@@ -20914,6 +22361,7 @@ var handler_default$1 = defineTool({
20914
22361
  "search_issues(organizationSlug='my-org', naturalLanguageQuery='critical bugs from last week')",
20915
22362
  "search_issues(organizationSlug='my-org', naturalLanguageQuery='unhandled errors affecting 100+ users')",
20916
22363
  "search_issues(organizationSlug='my-org', naturalLanguageQuery='issues assigned to me')",
22364
+ "search_issues(organizationSlug='my-org', naturalLanguageQuery='user feedback from production')",
20917
22365
  "</examples>",
20918
22366
  "",
20919
22367
  "<hints>",
@@ -20936,69 +22384,625 @@ var handler_default$1 = defineTool({
20936
22384
  },
20937
22385
  async handler(params, context$1) {
20938
22386
  const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
20939
- setTag("organization.slug", params.organizationSlug);
20940
- if (params.projectSlugOrId) if (isNumericId(params.projectSlugOrId)) setTag("project.id", params.projectSlugOrId);
20941
- else setTag("project.slug", params.projectSlugOrId);
22387
+ setTag("organization.slug", params.organizationSlug);
22388
+ if (params.projectSlugOrId) if (isNumericId(params.projectSlugOrId)) setTag("project.id", params.projectSlugOrId);
22389
+ else setTag("project.slug", params.projectSlugOrId);
22390
+ let projectId;
22391
+ if (params.projectSlugOrId) if (isNumericId(params.projectSlugOrId)) projectId = params.projectSlugOrId;
22392
+ else {
22393
+ const project = await apiService.getProject({
22394
+ organizationSlug: params.organizationSlug,
22395
+ projectSlugOrId: params.projectSlugOrId
22396
+ });
22397
+ projectId = String(project.id);
22398
+ }
22399
+ const agentResult = await searchIssuesAgent({
22400
+ query: params.naturalLanguageQuery,
22401
+ organizationSlug: params.organizationSlug,
22402
+ apiService,
22403
+ projectId
22404
+ });
22405
+ const translatedQuery = agentResult.result;
22406
+ const issues = await apiService.listIssues({
22407
+ organizationSlug: params.organizationSlug,
22408
+ projectSlug: params.projectSlugOrId ?? void 0,
22409
+ query: translatedQuery.query ?? void 0,
22410
+ sortBy: translatedQuery.sort || "date",
22411
+ limit: params.limit
22412
+ });
22413
+ let output = "";
22414
+ if (params.includeExplanation) {
22415
+ output += `# Search Results for "${params.naturalLanguageQuery}"\n\n`;
22416
+ output += `⚠️ **IMPORTANT**: Display these issues as highlighted cards with status indicators, assignee info, and clickable Issue IDs.\n\n`;
22417
+ output += `## Query Translation\n`;
22418
+ output += `Natural language: "${params.naturalLanguageQuery}"\n`;
22419
+ output += `Sentry query: \`${translatedQuery.query}\``;
22420
+ if (translatedQuery.sort) output += `\nSort: ${translatedQuery.sort}`;
22421
+ output += `\n\n`;
22422
+ if (translatedQuery.explanation) {
22423
+ output += formatExplanation(translatedQuery.explanation);
22424
+ output += `\n\n`;
22425
+ }
22426
+ output += formatIssueResults({
22427
+ issues,
22428
+ organizationSlug: params.organizationSlug,
22429
+ projectSlugOrId: params.projectSlugOrId ?? void 0,
22430
+ query: translatedQuery.query,
22431
+ regionUrl: params.regionUrl ?? void 0,
22432
+ naturalLanguageQuery: params.naturalLanguageQuery,
22433
+ skipHeader: true
22434
+ });
22435
+ } else output = formatIssueResults({
22436
+ issues,
22437
+ organizationSlug: params.organizationSlug,
22438
+ projectSlugOrId: params.projectSlugOrId ?? void 0,
22439
+ query: translatedQuery.query,
22440
+ regionUrl: params.regionUrl ?? void 0,
22441
+ naturalLanguageQuery: params.naturalLanguageQuery,
22442
+ skipHeader: false
22443
+ });
22444
+ return output;
22445
+ }
22446
+ });
22447
+
22448
+ //#endregion
22449
+ //#region ../mcp-core/dist/config-mlP4H0sA.js
22450
+ const systemPrompt$2 = `You are a Sentry issue event filter translator. Your job is to:
22451
+ 1. Translate natural language queries into Sentry tag filters for events within a SPECIFIC issue
22452
+ 2. Select appropriate fields to return in the results
22453
+ 3. Determine sort order and time ranges
22454
+
22455
+ IMPORTANT CONTEXT:
22456
+ - You are filtering events WITHIN a specific issue (the API endpoint is already scoped to that issue)
22457
+ - DO NOT include "issue:" in your query - the endpoint filters by issue automatically
22458
+ - Focus on tag-based filtering: release, environment, user, trace ID, URL, etc.
22459
+ - You are working with the "errors" dataset (issues are groups of error events)
22460
+
22461
+ CRITICAL - TAG FIELD VERIFICATION:
22462
+ Before using ANY tag or field, you should call the issueEventFields tool to verify it exists:
22463
+ 1. Available tags vary by project and what data is being sent
22464
+ 2. Using non-existent tags will cause query failures
22465
+ 3. The issueEventFields tool returns ALL available tags for the issue's project
22466
+ 4. Field names may not be what you expect (e.g., "user_agent.original" not "browser")
22467
+
22468
+ TOOL USAGE GUIDELINES:
22469
+ 1. Use issueEventFields tool (no parameters) to discover available tags and fields
22470
+ 2. Use whoami tool when queries reference "me", "my", or "myself" for user.id/user.email
22471
+ 3. CRITICAL: All tools return {error?, result?} format - check for errors before using results
22472
+
22473
+ QUERY CONSTRUCTION:
22474
+ Your query should contain ONLY the filter expressions (tags, operators, values):
22475
+ - CORRECT: "environment:production release:v1.0.5"
22476
+ - CORRECT: "user.email:alice@example.com"
22477
+ - CORRECT: 'url:"*/checkout/*"'
22478
+ - WRONG: "issue:MCP-41 environment:production" ← DO NOT include issue: prefix
22479
+
22480
+ COMMON TAG PATTERNS:
22481
+ - release:VERSION - Filter by software release/version
22482
+ - environment:ENV - Filter by environment (production, staging, development)
22483
+ - user:USER_ID or user.email:EMAIL - Filter by user
22484
+ - trace:TRACE_ID - Filter by distributed trace ID
22485
+ - url:URL_PATTERN - Filter by request URL (use wildcards: "*/path/*")
22486
+ - transaction:NAME - Filter by transaction name
22487
+ - level:LEVEL - Filter by error level (error, warning, fatal, info)
22488
+ - device:DEVICE - Filter by device identifier
22489
+ - os:OS_NAME - Filter by operating system
22490
+ - browser:BROWSER - Filter by browser name
22491
+ - runtime:RUNTIME - Filter by runtime version (e.g., "python 3.11")
22492
+
22493
+ WILDCARD MATCHING:
22494
+ - Use "*" for wildcards in string values
22495
+ - Example: url:"*/checkout/*" matches any URL containing /checkout/
22496
+ - Example: release:"1.2.*" matches any 1.2.x release
22497
+
22498
+ TIME RANGE HANDLING:
22499
+ For time-based queries ("last hour", "yesterday", "from Dec 16"):
22500
+ - Relative: Use statsPeriod ("1h", "24h", "7d", "14d", "30d")
22501
+ - "last hour" → {"statsPeriod": "1h"}
22502
+ - "yesterday" → {"statsPeriod": "24h"}
22503
+ - "last week" → {"statsPeriod": "7d"}
22504
+ - Absolute: Use start/end (ISO 8601 format)
22505
+ - "from Dec 16 2025 17:50 UTC" → {"start": "2025-12-16T17:50:00Z", "end": "2025-12-17T23:59:59Z"}
22506
+ - Default: If no time mentioned, use {"statsPeriod": "14d"}
22507
+
22508
+ FIELD SELECTION:
22509
+ - Use recommended default fields unless user asks for specific data
22510
+ - For custom fields, verify availability with issueEventFields tool
22511
+ - Common useful fields:
22512
+ - id: Event ID
22513
+ - timestamp: When event occurred
22514
+ - title: Event title/message
22515
+ - message: Full error message
22516
+ - level: Error severity
22517
+ - environment: Deployment environment
22518
+ - release: Release version
22519
+ - user.display: User identifier
22520
+ - trace: Trace ID
22521
+ - url: Request URL
22522
+ - device: Device identifier
22523
+ - os: Operating system
22524
+ - runtime: Runtime environment
22525
+
22526
+ SORTING RULES (CRITICAL):
22527
+ 1. ALWAYS specify a sort parameter
22528
+ 2. Default: "-timestamp" (newest first) for time-based browsing
22529
+ 3. Use "-" prefix for descending order
22530
+ 4. CRITICAL: Sort field MUST be included in your fields array
22531
+ 5. Examples:
22532
+ - sort: "-timestamp", fields: ["id", "timestamp", "message"] ✓ CORRECT
22533
+ - sort: "-level", fields: ["id", "timestamp"] ✗ WRONG (level not in fields)
22534
+
22535
+ DO NOT USE:
22536
+ - Aggregate functions (count, avg, sum) - this tool returns individual events, not statistics
22537
+ - SQL syntax (IS NULL, yesterday(), etc.) - use has: operator and timeRange instead
22538
+ - Field existence checks unless necessary (has:field_name, !has:field_name)
22539
+
22540
+ HANDLING "ME" REFERENCES:
22541
+ - If query contains "me", "my errors", "assigned to me", use whoami tool
22542
+ - Replace "me" with actual user.id or user.email value
22543
+ - Example: "my errors" + whoami returns user.email:"alice@example.com"
22544
+ → query: "user.email:alice@example.com"
22545
+
22546
+ YOUR RESPONSE FORMAT:
22547
+ Return a JSON object with:
22548
+ - "query": Tag filter expressions (empty string "" for no filters)
22549
+ - "fields": Array of field names to return (use recommended defaults if not specified)
22550
+ - "sort": Sort parameter (REQUIRED - default to "-timestamp")
22551
+ - "timeRange": Optional time range
22552
+ - Relative: {"statsPeriod": "24h"}
22553
+ - Absolute: {"start": "2025-01-01T00:00:00Z", "end": "2025-01-02T00:00:00Z"}
22554
+ - Omit for default 14-day window
22555
+ - "explanation": Brief explanation of how you translated the query
22556
+
22557
+ CORRECT QUERY EXAMPLES:
22558
+ 1. "events from last hour"
22559
+ → {
22560
+ "query": "",
22561
+ "fields": ["id", "timestamp", "title", "message", "level"],
22562
+ "sort": "-timestamp",
22563
+ "timeRange": {"statsPeriod": "1h"},
22564
+ "explanation": "Filtering to events from last hour, sorted newest first"
22565
+ }
22566
+
22567
+ 2. "production events with release v1.0.5"
22568
+ → {
22569
+ "query": "environment:production release:v1.0.5",
22570
+ "fields": ["id", "timestamp", "title", "environment", "release"],
22571
+ "sort": "-timestamp",
22572
+ "timeRange": {"statsPeriod": "14d"},
22573
+ "explanation": "Filtering to production environment with specific release"
22574
+ }
22575
+
22576
+ 3. "errors affecting user alice@example.com"
22577
+ → {
22578
+ "query": "user.email:alice@example.com",
22579
+ "fields": ["id", "timestamp", "title", "user.display", "message"],
22580
+ "sort": "-timestamp",
22581
+ "timeRange": {"statsPeriod": "14d"},
22582
+ "explanation": "Filtering to events affecting specific user"
22583
+ }
22584
+
22585
+ 4. "events with trace ID abc123"
22586
+ → {
22587
+ "query": "trace:abc123",
22588
+ "fields": ["id", "timestamp", "title", "trace", "url", "transaction"],
22589
+ "sort": "-timestamp",
22590
+ "timeRange": {"statsPeriod": "14d"},
22591
+ "explanation": "Filtering to events with specific trace ID"
22592
+ }
22593
+
22594
+ PROCESS:
22595
+ 1. Analyze the user's natural language query
22596
+ 2. Call issueEventFields tool to discover available tags (if needed)
22597
+ 3. Call whoami tool if query references "me" (if needed)
22598
+ 4. Construct tag filters (WITHOUT "issue:" prefix)
22599
+ 5. Select appropriate fields
22600
+ 6. Determine sort order (default: "-timestamp")
22601
+ 7. Determine time range (if applicable)
22602
+ 8. Return JSON response with explanation
22603
+
22604
+ COMMON ERRORS TO AVOID:
22605
+ - Including "issue:" in query (handler adds this automatically)
22606
+ - Using aggregate functions like count() or avg()
22607
+ - Using non-existent field names (verify with issueEventFields tool)
22608
+ - Forgetting to include sort field in fields array
22609
+ - Using SQL syntax instead of Sentry query syntax`;
22610
+ const ISSUE_EVENT_TAGS = {
22611
+ release: "Software version/release identifier",
22612
+ environment: "Deployment environment (production, staging, development, etc.)",
22613
+ level: "Error severity level (error, warning, fatal, info, debug)",
22614
+ user: "User identifier",
22615
+ "user.id": "User ID",
22616
+ "user.email": "User email address",
22617
+ "user.username": "Username",
22618
+ "user.display": "User display name (formatted)",
22619
+ transaction: "Transaction name/route",
22620
+ url: "Request URL",
22621
+ trace: "Distributed trace ID",
22622
+ device: "Device identifier",
22623
+ "device.family": "Device family",
22624
+ os: "Operating system name",
22625
+ "os.name": "OS name",
22626
+ "os.version": "OS version",
22627
+ runtime: "Runtime environment",
22628
+ "runtime.name": "Runtime name (e.g., CPython)",
22629
+ "runtime.version": "Runtime version",
22630
+ browser: "Browser identifier",
22631
+ "browser.name": "Browser name",
22632
+ "browser.version": "Browser version",
22633
+ handled: "Whether error was handled (true/false)",
22634
+ mechanism: "Error mechanism type",
22635
+ "error.type": "Exception type/class name",
22636
+ "stack.filename": "Source file where error occurred",
22637
+ "stack.function": "Function where error occurred",
22638
+ "stack.module": "Module where error occurred",
22639
+ platform: "SDK platform (javascript, python, etc.)",
22640
+ "sdk.name": "SDK name",
22641
+ "sdk.version": "SDK version",
22642
+ "http.method": "HTTP request method",
22643
+ "http.status_code": "HTTP status code",
22644
+ "user_agent.original": "Original user agent string"
22645
+ };
22646
+ const RECOMMENDED_FIELDS$1 = [
22647
+ "id",
22648
+ "timestamp",
22649
+ "title",
22650
+ "message",
22651
+ "level",
22652
+ "environment",
22653
+ "release",
22654
+ "user.display",
22655
+ "trace",
22656
+ "url"
22657
+ ];
22658
+ const EXAMPLE_QUERIES = [
22659
+ {
22660
+ description: "Events from last hour",
22661
+ output: {
22662
+ query: "",
22663
+ fields: RECOMMENDED_FIELDS$1,
22664
+ sort: "-timestamp",
22665
+ timeRange: { statsPeriod: "1h" }
22666
+ }
22667
+ },
22668
+ {
22669
+ description: "Production events with specific release",
22670
+ output: {
22671
+ query: "environment:production release:09f66121-a5a3-4947-8be1-1454c4cefa3d",
22672
+ fields: [
22673
+ "id",
22674
+ "timestamp",
22675
+ "title",
22676
+ "environment",
22677
+ "release",
22678
+ "user.display"
22679
+ ],
22680
+ sort: "-timestamp",
22681
+ timeRange: { statsPeriod: "7d" }
22682
+ }
22683
+ },
22684
+ {
22685
+ description: "Events affecting specific user",
22686
+ output: {
22687
+ query: "user.email:alice@example.com",
22688
+ fields: [
22689
+ "id",
22690
+ "timestamp",
22691
+ "title",
22692
+ "user.display",
22693
+ "user.email",
22694
+ "message"
22695
+ ],
22696
+ sort: "-timestamp",
22697
+ timeRange: { statsPeriod: "14d" }
22698
+ }
22699
+ },
22700
+ {
22701
+ description: "Events with specific trace ID",
22702
+ output: {
22703
+ query: "trace:abc123def456",
22704
+ fields: [
22705
+ "id",
22706
+ "timestamp",
22707
+ "title",
22708
+ "trace",
22709
+ "url",
22710
+ "transaction"
22711
+ ],
22712
+ sort: "-timestamp",
22713
+ timeRange: { statsPeriod: "14d" }
22714
+ }
22715
+ },
22716
+ {
22717
+ description: "Events from checkout flow",
22718
+ output: {
22719
+ query: "url:\"*/checkout/*\"",
22720
+ fields: [
22721
+ "id",
22722
+ "timestamp",
22723
+ "title",
22724
+ "url",
22725
+ "transaction",
22726
+ "user.display"
22727
+ ],
22728
+ sort: "-timestamp",
22729
+ timeRange: { statsPeriod: "7d" }
22730
+ }
22731
+ },
22732
+ {
22733
+ description: "Fatal errors only",
22734
+ output: {
22735
+ query: "level:fatal",
22736
+ fields: [
22737
+ "id",
22738
+ "timestamp",
22739
+ "title",
22740
+ "level",
22741
+ "message",
22742
+ "error.type"
22743
+ ],
22744
+ sort: "-timestamp",
22745
+ timeRange: { statsPeriod: "30d" }
22746
+ }
22747
+ },
22748
+ {
22749
+ description: "Events on mobile devices",
22750
+ output: {
22751
+ query: "device:mobile OR device.family:mobile",
22752
+ fields: [
22753
+ "id",
22754
+ "timestamp",
22755
+ "title",
22756
+ "device",
22757
+ "device.family",
22758
+ "os",
22759
+ "browser"
22760
+ ],
22761
+ sort: "-timestamp",
22762
+ timeRange: { statsPeriod: "7d" }
22763
+ }
22764
+ },
22765
+ {
22766
+ description: "Events from specific browser",
22767
+ output: {
22768
+ query: "browser.name:Chrome",
22769
+ fields: [
22770
+ "id",
22771
+ "timestamp",
22772
+ "title",
22773
+ "browser.name",
22774
+ "browser.version",
22775
+ "os"
22776
+ ],
22777
+ sort: "-timestamp",
22778
+ timeRange: { statsPeriod: "7d" }
22779
+ }
22780
+ }
22781
+ ];
22782
+
22783
+ //#endregion
22784
+ //#region ../mcp-core/dist/utils-D8xperPO.js
22785
+ /**
22786
+ * Create a tool for the agent to query available tags and fields for issue events
22787
+ * The tool is pre-bound with the API service and organization configured for the appropriate region
22788
+ */
22789
+ function createIssueEventFieldsTool(options) {
22790
+ const { apiService, organizationSlug, projectId } = options;
22791
+ return agentTool({
22792
+ description: "Get available tags and fields for issue events to understand what filters are available",
22793
+ parameters: z.object({}),
22794
+ execute: async () => {
22795
+ const tagsResponse = await apiService.listTags({
22796
+ organizationSlug,
22797
+ dataset: "events",
22798
+ project: projectId,
22799
+ statsPeriod: "14d",
22800
+ useCache: true,
22801
+ useFlagsBackend: true
22802
+ });
22803
+ const availableTags = {};
22804
+ for (const tag of tagsResponse) if (tag.key) {
22805
+ const knownTagDescription = ISSUE_EVENT_TAGS[tag.key];
22806
+ availableTags[tag.key] = tag.name || knownTagDescription || tag.key;
22807
+ }
22808
+ const allTags = {
22809
+ ...ISSUE_EVENT_TAGS,
22810
+ ...availableTags
22811
+ };
22812
+ return `Available Tags and Fields (${Object.keys(allTags).length} total):
22813
+
22814
+ Common Tags:
22815
+ ${Object.entries(ISSUE_EVENT_TAGS).slice(0, 30).map(([key, desc]) => `- ${key}: ${desc}`).join("\n")}
22816
+ ${Object.keys(ISSUE_EVENT_TAGS).length > 30 ? `\n... and ${Object.keys(ISSUE_EVENT_TAGS).length - 30} more common tags` : ""}
22817
+
22818
+ Project-Specific Tags (from API):
22819
+ ${Object.entries(availableTags).filter(([key]) => !ISSUE_EVENT_TAGS[key]).slice(0, 20).map(([key, desc]) => `- ${key}: ${desc}`).join("\n")}
22820
+
22821
+ Recommended Fields for Results:
22822
+ ${RECOMMENDED_FIELDS$1.map((f) => `- ${f}`).join("\n")}
22823
+
22824
+ EXAMPLE QUERIES:
22825
+ ${EXAMPLE_QUERIES.map((ex) => `- "${ex.description}" →\n ${JSON.stringify(ex.output, null, 2)}`).join("\n\n")}
22826
+
22827
+ IMPORTANT:
22828
+ - Use these tag names exactly as shown in your query
22829
+ - Tags are case-insensitive
22830
+ - Use wildcards with quotes: url:"*/checkout/*"
22831
+ - Your query should NOT include "issue:" prefix - the handler adds it automatically`;
22832
+ }
22833
+ });
22834
+ }
22835
+ /**
22836
+ * Parse issue parameters from various input formats
22837
+ * Supports both direct issueId/organizationSlug and issueUrl parsing
22838
+ */
22839
+ function parseIssueParams(params) {
22840
+ if (params.issueUrl) {
22841
+ const orgMatch = params.issueUrl.match(/\/organizations\/([^/]+)\/issues\/([^/?]+)/) || params.issueUrl.match(/https?:\/\/([^.]+)\.sentry\.io\/issues\/([^/?]+)/);
22842
+ if (!orgMatch) throw new UserInputError(`Invalid issue URL format. Expected format like:
22843
+ - https://sentry.io/organizations/my-org/issues/123/
22844
+ - https://my-org.sentry.io/issues/123/
22845
+
22846
+ Received: ${params.issueUrl}`);
22847
+ return {
22848
+ organizationSlug: orgMatch[1],
22849
+ issueId: orgMatch[2]
22850
+ };
22851
+ }
22852
+ if (!params.issueId) throw new UserInputError("Must provide either issueUrl or issueId parameter. Use issueUrl for convenience, or provide both issueId and organizationSlug.");
22853
+ if (!params.organizationSlug) throw new UserInputError("When using issueId parameter, organizationSlug is required. Alternatively, provide issueUrl which includes both organization and issue ID.");
22854
+ return {
22855
+ organizationSlug: params.organizationSlug,
22856
+ issueId: params.issueId
22857
+ };
22858
+ }
22859
+
22860
+ //#endregion
22861
+ //#region ../mcp-core/dist/agent-zpc_iP4u.js
22862
+ const searchIssueEventsAgentOutputSchema = z.object({
22863
+ query: z.string().describe("Sentry query filters for tags/fields (NOT including issue: prefix - handler adds that)"),
22864
+ fields: z.array(z.string()).describe("Array of field names to return in results"),
22865
+ sort: z.string().describe("Sort parameter for results (e.g., -timestamp)"),
22866
+ timeRange: z.union([
22867
+ z.object({ statsPeriod: z.string().describe("Relative time period like '1h', '24h', '7d', '14d'") }),
22868
+ z.object({
22869
+ start: z.string().describe("ISO 8601 start time"),
22870
+ end: z.string().describe("ISO 8601 end time")
22871
+ }),
22872
+ z.null()
22873
+ ]).describe("Time range for filtering events. Use either statsPeriod for relative time or start/end for absolute time. Use null for default 14-day window."),
22874
+ explanation: z.string().describe("Brief explanation of how you translated this query")
22875
+ }).refine((data) => {
22876
+ if (!data.sort || !data.fields || data.fields.length === 0) return true;
22877
+ const sortField = data.sort.startsWith("-") ? data.sort.substring(1) : data.sort;
22878
+ return data.fields.includes(sortField);
22879
+ }, { message: "Sort field must be included in the fields array. Sentry requires that any field used for sorting must also be explicitly selected. Add the sort field to the fields array or choose a different sort field that's already included." });
22880
+ /**
22881
+ * Search issue events agent - translates natural language queries to Sentry tag filters for events within a specific issue
22882
+ * Returns both the translated query result AND the tool calls made by the agent
22883
+ */
22884
+ async function searchIssueEventsAgent(options) {
22885
+ const issueEventFieldsTool = createIssueEventFieldsTool({
22886
+ apiService: options.apiService,
22887
+ organizationSlug: options.organizationSlug,
22888
+ projectId: options.projectId
22889
+ });
22890
+ const whoamiTool = createWhoamiTool({ apiService: options.apiService });
22891
+ return await callEmbeddedAgent({
22892
+ system: systemPrompt$2,
22893
+ prompt: options.query,
22894
+ tools: {
22895
+ issueEventFields: issueEventFieldsTool,
22896
+ whoami: whoamiTool
22897
+ },
22898
+ schema: searchIssueEventsAgentOutputSchema
22899
+ });
22900
+ }
22901
+
22902
+ //#endregion
22903
+ //#region ../mcp-core/dist/handler-9NRJi9hO.js
22904
+ var handler_default$2 = defineTool({
22905
+ name: "search_issue_events",
22906
+ skills: ["inspect", "triage"],
22907
+ requiredScopes: ["event:read"],
22908
+ description: [
22909
+ "Search and filter events within a specific issue using natural language queries.",
22910
+ "",
22911
+ "Use this to filter events by time, environment, release, user, trace ID, or other tags. The tool automatically constrains results to the specified issue.",
22912
+ "",
22913
+ "For cross-issue searches use search_issues, for single event details use get_issue_details.",
22914
+ "",
22915
+ "<examples>",
22916
+ "search_issue_events(issueId='MCP-41', organizationSlug='my-org', naturalLanguageQuery='from last hour')",
22917
+ "search_issue_events(issueUrl='https://sentry.io/.../issues/123/', naturalLanguageQuery='production with release v1.0')",
22918
+ "</examples>"
22919
+ ].join("\n"),
22920
+ inputSchema: {
22921
+ organizationSlug: ParamOrganizationSlug.nullable().default(null).describe("Organization slug. Required when using issueId. Not needed when using issueUrl."),
22922
+ issueId: z.string().optional().describe("Issue ID (e.g., 'MCP-41', 'PROJECT-123'). Requires organizationSlug. Alternatively, use issueUrl."),
22923
+ issueUrl: z.string().url().optional().describe("Full Sentry issue URL (e.g., 'https://sentry.io/organizations/my-org/issues/123/'). Includes both organization and issue ID."),
22924
+ naturalLanguageQuery: z.string().trim().min(1).describe("Natural language description of what events you want to find within this issue. Examples: 'from last hour', 'production with release v1.0', 'affecting user alice@example.com', 'with trace ID abc123'"),
22925
+ projectSlug: ParamProjectSlug.nullable().default(null).describe("Project slug for better tag discovery. Optional - helps find project-specific tags."),
22926
+ regionUrl: ParamRegionUrl.nullable().default(null).describe("Sentry region URL. Optional - defaults to main region."),
22927
+ limit: z.number().min(1).max(100).default(50).describe("Maximum number of events to return (1-100, default: 50)"),
22928
+ includeExplanation: z.boolean().default(false).describe("Include explanation of how the natural language query was translated to Sentry syntax")
22929
+ },
22930
+ annotations: {
22931
+ readOnlyHint: true,
22932
+ openWorldHint: true
22933
+ },
22934
+ async handler(params, context$1) {
22935
+ const { organizationSlug, issueId } = parseIssueParams({
22936
+ organizationSlug: params.organizationSlug,
22937
+ issueId: params.issueId,
22938
+ issueUrl: params.issueUrl
22939
+ });
22940
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
22941
+ setTag("organization.slug", organizationSlug);
22942
+ setTag("issue.id", issueId);
22943
+ if (params.projectSlug) setTag("project.slug", params.projectSlug);
20942
22944
  let projectId;
20943
- if (params.projectSlugOrId) if (isNumericId(params.projectSlugOrId)) projectId = params.projectSlugOrId;
20944
- else {
22945
+ if (params.projectSlug) try {
20945
22946
  const project = await apiService.getProject({
20946
- organizationSlug: params.organizationSlug,
20947
- projectSlugOrId: params.projectSlugOrId
22947
+ organizationSlug,
22948
+ projectSlugOrId: params.projectSlug
20948
22949
  });
20949
22950
  projectId = String(project.id);
22951
+ } catch (error) {
22952
+ console.warn(`Could not resolve project ${params.projectSlug}:`, error);
20950
22953
  }
20951
- const agentResult = await searchIssuesAgent({
22954
+ const agentResult = await searchIssueEventsAgent({
20952
22955
  query: params.naturalLanguageQuery,
20953
- organizationSlug: params.organizationSlug,
22956
+ organizationSlug,
20954
22957
  apiService,
20955
22958
  projectId
20956
22959
  });
20957
- const translatedQuery = agentResult.result;
20958
- const issues = await apiService.listIssues({
20959
- organizationSlug: params.organizationSlug,
20960
- projectSlug: params.projectSlugOrId ?? void 0,
20961
- query: translatedQuery.query ?? void 0,
20962
- sortBy: translatedQuery.sort || "date",
20963
- limit: params.limit
20964
- });
20965
- let output = "";
20966
- if (params.includeExplanation) {
20967
- output += `# Search Results for "${params.naturalLanguageQuery}"\n\n`;
20968
- output += `⚠️ **IMPORTANT**: Display these issues as highlighted cards with status indicators, assignee info, and clickable Issue IDs.\n\n`;
20969
- output += `## Query Translation\n`;
20970
- output += `Natural language: "${params.naturalLanguageQuery}"\n`;
20971
- output += `Sentry query: \`${translatedQuery.query}\``;
20972
- if (translatedQuery.sort) output += `\nSort: ${translatedQuery.sort}`;
20973
- output += `\n\n`;
20974
- if (translatedQuery.explanation) {
20975
- output += formatExplanation(translatedQuery.explanation);
20976
- output += `\n\n`;
22960
+ const parsed = agentResult.result;
22961
+ if (!parsed.sort) throw new UserInputError(`Search Issue Events Agent response missing required 'sort' parameter. Received: ${JSON.stringify(parsed, null, 2)}. The agent must specify how to sort results (e.g., '-timestamp' for newest first).`);
22962
+ const query = parsed.query || "";
22963
+ const requestedFields = parsed.fields || [];
22964
+ const fields = requestedFields.length > 0 ? requestedFields : RECOMMENDED_FIELDS$1;
22965
+ const sortParam = parsed.sort;
22966
+ const timeParams = {};
22967
+ if (parsed.timeRange) {
22968
+ if ("statsPeriod" in parsed.timeRange) timeParams.statsPeriod = parsed.timeRange.statsPeriod;
22969
+ else if ("start" in parsed.timeRange && "end" in parsed.timeRange) {
22970
+ timeParams.start = parsed.timeRange.start;
22971
+ timeParams.end = parsed.timeRange.end;
20977
22972
  }
20978
- output += formatIssueResults({
20979
- issues,
20980
- organizationSlug: params.organizationSlug,
20981
- projectSlugOrId: params.projectSlugOrId ?? void 0,
20982
- query: translatedQuery.query,
20983
- regionUrl: params.regionUrl ?? void 0,
20984
- naturalLanguageQuery: params.naturalLanguageQuery,
20985
- skipHeader: true
20986
- });
20987
- } else output = formatIssueResults({
20988
- issues,
20989
- organizationSlug: params.organizationSlug,
20990
- projectSlugOrId: params.projectSlugOrId ?? void 0,
20991
- query: translatedQuery.query,
20992
- regionUrl: params.regionUrl ?? void 0,
20993
- naturalLanguageQuery: params.naturalLanguageQuery,
20994
- skipHeader: false
22973
+ } else timeParams.statsPeriod = "14d";
22974
+ const eventsResponse = await apiService.listEventsForIssue({
22975
+ organizationSlug,
22976
+ issueId,
22977
+ query,
22978
+ limit: params.limit,
22979
+ sort: sortParam,
22980
+ ...timeParams
22981
+ });
22982
+ const explorerQuery = query ? `issue:${issueId} ${query}` : `issue:${issueId}`;
22983
+ const explorerUrl = apiService.getEventsExplorerUrl(organizationSlug, explorerQuery, projectId, "errors", fields, sortParam, [], [], timeParams.statsPeriod, timeParams.start, timeParams.end);
22984
+ function isValidEventArray(data) {
22985
+ return Array.isArray(data) && data.every((item) => typeof item === "object" && item !== null);
22986
+ }
22987
+ if (!isValidEventArray(eventsResponse)) throw new Error("Invalid event data format from Sentry API: expected array of objects");
22988
+ const eventData = eventsResponse;
22989
+ const naturalLanguageContext = `Events in issue ${issueId}: ${params.naturalLanguageQuery}`;
22990
+ return formatErrorResults({
22991
+ eventData,
22992
+ naturalLanguageQuery: naturalLanguageContext,
22993
+ includeExplanation: params.includeExplanation,
22994
+ apiService,
22995
+ organizationSlug,
22996
+ explorerUrl,
22997
+ sentryQuery: explorerQuery,
22998
+ fields,
22999
+ explanation: parsed.explanation
20995
23000
  });
20996
- return output;
20997
23001
  }
20998
23002
  });
20999
23003
 
21000
23004
  //#endregion
21001
- //#region ../mcp-core/dist/config-Dh25cVhL.js
23005
+ //#region ../mcp-core/dist/config-BJzhfINu.js
21002
23006
  /**
21003
23007
  * Configuration for the use_sentry embedded agent.
21004
23008
  *
@@ -21017,7 +23021,7 @@ The user may include various parameters to pass to those tools in their prompt.
21017
23021
  You MUST return tool results directly without interpreting them.`;
21018
23022
 
21019
23023
  //#endregion
21020
- //#region ../mcp-core/dist/agent-bVTgqfc0.js
23024
+ //#region ../mcp-core/dist/agent-C0SOl71m.js
21021
23025
  /**
21022
23026
  * Output schema for the embedded agent.
21023
23027
  * The agent returns the final result string directly from its tool calls.
@@ -21028,7 +23032,6 @@ const outputSchema = z.object({ result: z.string().describe("The final result fr
21028
23032
  * This returns the final result AND the tool calls made by the agent
21029
23033
  */
21030
23034
  async function useSentryAgent(options) {
21031
- if (!process.env.OPENAI_API_KEY) throw new ConfigurationError("OPENAI_API_KEY environment variable is required for use_sentry tool");
21032
23035
  const prompt = options.request;
21033
23036
  return await callEmbeddedAgent({
21034
23037
  system: systemPrompt$1,
@@ -21039,7 +23042,296 @@ async function useSentryAgent(options) {
21039
23042
  }
21040
23043
 
21041
23044
  //#endregion
21042
- //#region ../mcp-core/dist/error-handling-BVlYIE1J.js
23045
+ //#region ../mcp-core/dist/list-issues-DSk9smZ1.js
23046
+ var list_issues_default = defineTool({
23047
+ name: "list_issues",
23048
+ skills: [
23049
+ "inspect",
23050
+ "triage",
23051
+ "seer"
23052
+ ],
23053
+ requiredScopes: ["event:read"],
23054
+ description: [
23055
+ "List issues using Sentry query syntax directly (no AI/LLM required).",
23056
+ "",
23057
+ "Use this tool when:",
23058
+ "- You know Sentry query syntax already",
23059
+ "- AI-powered search is unavailable (no OPENAI_API_KEY or ANTHROPIC_API_KEY)",
23060
+ "- You want precise control over the query",
23061
+ "",
23062
+ "For natural language queries, use search_issues instead.",
23063
+ "",
23064
+ "Common Query Syntax:",
23065
+ "- is:unresolved - Show unresolved issues only",
23066
+ "- is:unassigned - Show unassigned issues",
23067
+ "- level:error - Filter by error level",
23068
+ "- firstSeen:-24h - First seen in last 24 hours",
23069
+ "- lastSeen:-1h - Last seen in last hour",
23070
+ "- has:user - Issues with user context",
23071
+ "- user.email:user@example.com - Filter by user email",
23072
+ "- environment:production - Filter by environment",
23073
+ "- release:1.0.0 - Filter by release version",
23074
+ "",
23075
+ "Combine queries: is:unresolved is:unassigned level:error",
23076
+ "",
23077
+ "<examples>",
23078
+ "list_issues(organizationSlug='my-org', query='is:unresolved is:unassigned')",
23079
+ "list_issues(organizationSlug='my-org', query='level:error firstSeen:-24h', sort='freq')",
23080
+ "list_issues(organizationSlug='my-org', projectSlugOrId='my-project', query='is:unresolved')",
23081
+ "</examples>",
23082
+ "",
23083
+ "<hints>",
23084
+ "- If the user passes a parameter in the form of name/otherName, it's likely in the format of <organizationSlug>/<projectSlugOrId>.",
23085
+ "- The projectSlugOrId parameter accepts both project slugs (e.g., 'my-project') and numeric IDs (e.g., '123456').",
23086
+ "</hints>"
23087
+ ].join("\n"),
23088
+ inputSchema: {
23089
+ organizationSlug: ParamOrganizationSlug,
23090
+ query: z.string().trim().default("is:unresolved").describe("Sentry issue search query syntax"),
23091
+ projectSlugOrId: z.string().toLowerCase().trim().superRefine(validateSlugOrId).nullable().default(null).describe("Filter by project slug or numeric ID (optional)"),
23092
+ sort: z.enum([
23093
+ "date",
23094
+ "freq",
23095
+ "new",
23096
+ "user"
23097
+ ]).default("date").describe("Sort order: date (last seen), freq (frequency), new (first seen), user (user count)"),
23098
+ limit: z.number().min(1).max(100).default(10).describe("Maximum number of issues to return (1-100)"),
23099
+ regionUrl: ParamRegionUrl.nullable().default(null)
23100
+ },
23101
+ annotations: {
23102
+ readOnlyHint: true,
23103
+ openWorldHint: true
23104
+ },
23105
+ async handler(params, context$1) {
23106
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
23107
+ setTag("organization.slug", params.organizationSlug);
23108
+ if (params.projectSlugOrId) if (isNumericId(params.projectSlugOrId)) setTag("project.id", params.projectSlugOrId);
23109
+ else setTag("project.slug", params.projectSlugOrId);
23110
+ const issues = await apiService.listIssues({
23111
+ organizationSlug: params.organizationSlug,
23112
+ projectSlug: params.projectSlugOrId ?? void 0,
23113
+ query: params.query,
23114
+ sortBy: params.sort,
23115
+ limit: params.limit
23116
+ });
23117
+ return formatIssueResults({
23118
+ issues,
23119
+ organizationSlug: params.organizationSlug,
23120
+ projectSlugOrId: params.projectSlugOrId ?? void 0,
23121
+ query: params.query,
23122
+ regionUrl: params.regionUrl ?? void 0
23123
+ });
23124
+ }
23125
+ });
23126
+
23127
+ //#endregion
23128
+ //#region ../mcp-core/dist/list-events-BVY0RUTR.js
23129
+ const DEFAULT_FIELDS = {
23130
+ errors: RECOMMENDED_FIELDS.errors.basic,
23131
+ logs: RECOMMENDED_FIELDS.logs.basic,
23132
+ spans: RECOMMENDED_FIELDS.spans.basic
23133
+ };
23134
+ var list_events_default = defineTool({
23135
+ name: "list_events",
23136
+ skills: [
23137
+ "inspect",
23138
+ "triage",
23139
+ "seer"
23140
+ ],
23141
+ requiredScopes: ["event:read"],
23142
+ description: [
23143
+ "Search events using Sentry query syntax directly (no AI/LLM required).",
23144
+ "",
23145
+ "Use this tool when:",
23146
+ "- You know Sentry query syntax already",
23147
+ "- AI-powered search is unavailable (no OPENAI_API_KEY or ANTHROPIC_API_KEY)",
23148
+ "- You want precise control over the query",
23149
+ "",
23150
+ "For natural language queries, use search_events instead.",
23151
+ "",
23152
+ "Datasets:",
23153
+ "- errors: Exception/crash events",
23154
+ "- logs: Log entries",
23155
+ "- spans: Performance data, traces, AI/LLM calls",
23156
+ "",
23157
+ "Query Syntax Examples:",
23158
+ "- message:\"connection timeout\"",
23159
+ "- level:error",
23160
+ "- span.op:http.client span.status_code:500",
23161
+ "- log.level:error",
23162
+ "- transaction:/api/users",
23163
+ "",
23164
+ "<examples>",
23165
+ "list_events(organizationSlug='my-org', dataset='errors', query='level:error')",
23166
+ "list_events(organizationSlug='my-org', dataset='spans', query='span.op:db')",
23167
+ "list_events(organizationSlug='my-org', dataset='logs', query='severity:error')",
23168
+ "list_events(organizationSlug='my-org', dataset='errors', fields=['issue', 'count()'], sort='-count()')",
23169
+ "</examples>",
23170
+ "",
23171
+ "<hints>",
23172
+ "- If the user passes a parameter in the form of name/otherName, it's likely in the format of <organizationSlug>/<projectSlug>.",
23173
+ "- Use fields with aggregate functions like count(), avg(), sum() for statistics",
23174
+ "- Sort by -count() for most common, -timestamp for newest",
23175
+ "</hints>"
23176
+ ].join("\n"),
23177
+ inputSchema: {
23178
+ organizationSlug: ParamOrganizationSlug,
23179
+ dataset: z.enum([
23180
+ "errors",
23181
+ "logs",
23182
+ "spans"
23183
+ ]).default("errors").describe("Dataset to query: errors (exceptions), logs, or spans (traces)"),
23184
+ query: z.string().trim().default("").describe("Sentry event search query syntax (empty for all events)"),
23185
+ fields: z.array(z.string()).nullable().default(null).describe("Fields to return. If not specified, uses sensible defaults. Include aggregate functions like count(), avg() for statistics."),
23186
+ sort: z.string().default("-timestamp").describe("Sort field (prefix with - for descending). Use -count() for aggregations."),
23187
+ projectSlug: ParamProjectSlug.nullable().default(null),
23188
+ statsPeriod: z.string().default("14d").describe("Time period: 1h, 24h, 7d, 14d, 30d, etc."),
23189
+ limit: z.number().min(1).max(100).default(10).describe("Maximum number of results to return (1-100)"),
23190
+ regionUrl: ParamRegionUrl.nullable().default(null)
23191
+ },
23192
+ annotations: {
23193
+ readOnlyHint: true,
23194
+ openWorldHint: true
23195
+ },
23196
+ async handler(params, context$1) {
23197
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
23198
+ setTag("organization.slug", params.organizationSlug);
23199
+ if (params.projectSlug) setTag("project.slug", params.projectSlug);
23200
+ let projectId;
23201
+ if (params.projectSlug) {
23202
+ const project = await apiService.getProject({
23203
+ organizationSlug: params.organizationSlug,
23204
+ projectSlugOrId: params.projectSlug
23205
+ });
23206
+ projectId = String(project.id);
23207
+ }
23208
+ const fields = params.fields ?? DEFAULT_FIELDS[params.dataset];
23209
+ const eventsResponse = await apiService.searchEvents({
23210
+ organizationSlug: params.organizationSlug,
23211
+ query: params.query,
23212
+ fields,
23213
+ limit: params.limit,
23214
+ projectId,
23215
+ dataset: params.dataset,
23216
+ sort: params.sort,
23217
+ statsPeriod: params.statsPeriod
23218
+ });
23219
+ function isValidResponse(response) {
23220
+ return typeof response === "object" && response !== null;
23221
+ }
23222
+ function isValidEventArray(data) {
23223
+ return Array.isArray(data) && data.every((item) => typeof item === "object" && item !== null);
23224
+ }
23225
+ if (!isValidResponse(eventsResponse)) throw new Error("Invalid response format from Sentry API");
23226
+ const eventData = eventsResponse.data;
23227
+ if (!isValidEventArray(eventData)) throw new Error("Invalid event data format from Sentry API");
23228
+ const aggregateFunctions = fields.filter((field) => field.includes("(") && field.includes(")"));
23229
+ const groupByFields = fields.filter((field) => !field.includes("(") && !field.includes(")"));
23230
+ const explorerUrl = apiService.getEventsExplorerUrl(params.organizationSlug, params.query, projectId, params.dataset, fields, params.sort, aggregateFunctions, groupByFields, params.statsPeriod);
23231
+ const formatParams = {
23232
+ eventData,
23233
+ naturalLanguageQuery: params.query || `${params.dataset} events`,
23234
+ includeExplanation: false,
23235
+ apiService,
23236
+ organizationSlug: params.organizationSlug,
23237
+ explorerUrl,
23238
+ sentryQuery: params.query,
23239
+ fields
23240
+ };
23241
+ switch (params.dataset) {
23242
+ case "errors": return formatErrorResults(formatParams);
23243
+ case "logs": return formatLogResults(formatParams);
23244
+ case "spans": return formatSpanResults(formatParams);
23245
+ }
23246
+ }
23247
+ });
23248
+
23249
+ //#endregion
23250
+ //#region ../mcp-core/dist/list-issue-events-BOIBq62n.js
23251
+ var list_issue_events_default = defineTool({
23252
+ name: "list_issue_events",
23253
+ skills: ["inspect", "triage"],
23254
+ requiredScopes: ["event:read"],
23255
+ description: [
23256
+ "List events within a specific issue using Sentry query syntax (no AI/LLM required).",
23257
+ "",
23258
+ "Use this tool when:",
23259
+ "- You know Sentry query syntax already",
23260
+ "- AI-powered search is unavailable (no OPENAI_API_KEY or ANTHROPIC_API_KEY)",
23261
+ "- You want precise control over the query",
23262
+ "",
23263
+ "For natural language queries, use search_issue_events instead.",
23264
+ "",
23265
+ "Common Query Filters:",
23266
+ "- environment:production - Filter by environment",
23267
+ "- release:1.0.0 - Filter by release version",
23268
+ "- user.email:alice@example.com - Filter by user email",
23269
+ "- timestamp:>2024-01-01 - Filter by timestamp",
23270
+ "",
23271
+ "<examples>",
23272
+ "list_issue_events(issueUrl='https://sentry.io/organizations/my-org/issues/123/', query='environment:production')",
23273
+ "list_issue_events(issueId='MCP-41', organizationSlug='my-org', query='release:v1.0.0')",
23274
+ "list_issue_events(issueId='PROJECT-123', organizationSlug='my-org', statsPeriod='1h')",
23275
+ "</examples>",
23276
+ "",
23277
+ "<hints>",
23278
+ "- Use issueUrl for convenience (includes org + issue ID)",
23279
+ "- Or provide both issueId and organizationSlug",
23280
+ "- The query filters events WITHIN the issue, no need for issue: prefix",
23281
+ "</hints>"
23282
+ ].join("\n"),
23283
+ inputSchema: {
23284
+ organizationSlug: ParamOrganizationSlug.nullable().default(null).describe("Organization slug. Required when using issueId. Not needed when using issueUrl."),
23285
+ issueId: z.string().optional().describe("Issue ID (e.g., 'MCP-41', 'PROJECT-123'). Requires organizationSlug."),
23286
+ issueUrl: z.string().url().optional().describe("Full Sentry issue URL. Includes both organization and issue ID."),
23287
+ query: z.string().trim().default("").describe("Sentry event search query syntax (empty for all events)"),
23288
+ sort: z.string().default("-timestamp").describe("Sort field (prefix with - for descending). Default: -timestamp"),
23289
+ statsPeriod: z.string().default("14d").describe("Time period: 1h, 24h, 7d, 14d, 30d, etc."),
23290
+ limit: z.number().min(1).max(100).default(50).describe("Maximum number of events to return (1-100)"),
23291
+ regionUrl: ParamRegionUrl.nullable().default(null)
23292
+ },
23293
+ annotations: {
23294
+ readOnlyHint: true,
23295
+ openWorldHint: true
23296
+ },
23297
+ async handler(params, context$1) {
23298
+ const { organizationSlug, issueId } = parseIssueParams({
23299
+ organizationSlug: params.organizationSlug,
23300
+ issueId: params.issueId,
23301
+ issueUrl: params.issueUrl
23302
+ });
23303
+ const apiService = apiServiceFromContext(context$1, { regionUrl: params.regionUrl ?? void 0 });
23304
+ setTag("organization.slug", organizationSlug);
23305
+ setTag("issue.id", issueId);
23306
+ const eventsResponse = await apiService.listEventsForIssue({
23307
+ organizationSlug,
23308
+ issueId,
23309
+ query: params.query,
23310
+ limit: params.limit,
23311
+ sort: params.sort,
23312
+ statsPeriod: params.statsPeriod
23313
+ });
23314
+ function isValidEventArray(data) {
23315
+ return Array.isArray(data) && data.every((item) => typeof item === "object" && item !== null);
23316
+ }
23317
+ if (!isValidEventArray(eventsResponse)) throw new Error("Invalid event data format from Sentry API: expected array of objects");
23318
+ const explorerQuery = params.query ? `issue:${issueId} ${params.query}` : `issue:${issueId}`;
23319
+ const explorerUrl = apiService.getEventsExplorerUrl(organizationSlug, explorerQuery, void 0, "errors", RECOMMENDED_FIELDS$1, params.sort, [], [], params.statsPeriod);
23320
+ return formatErrorResults({
23321
+ eventData: eventsResponse,
23322
+ naturalLanguageQuery: `Events in issue ${issueId}`,
23323
+ includeExplanation: false,
23324
+ apiService,
23325
+ organizationSlug,
23326
+ explorerUrl,
23327
+ sentryQuery: explorerQuery,
23328
+ fields: RECOMMENDED_FIELDS$1
23329
+ });
23330
+ }
23331
+ });
23332
+
23333
+ //#endregion
23334
+ //#region ../mcp-core/dist/error-handling-DFJ-iOAP.js
21043
23335
  /**
21044
23336
  * Type guard to identify user input validation errors.
21045
23337
  */
@@ -21130,7 +23422,7 @@ async function formatErrorForUser(error) {
21130
23422
  }
21131
23423
 
21132
23424
  //#endregion
21133
- //#region ../mcp-core/dist/constraint-helpers-0jgp7p3K.js
23425
+ //#region ../mcp-core/dist/constraint-helpers-D80X658i.js
21134
23426
  /**
21135
23427
  * Determines which tool parameter keys should be filtered out of the schema
21136
23428
  * because they will be injected from constraints.
@@ -21192,7 +23484,7 @@ function getConstraintParametersToInject(constraints, toolInputSchema) {
21192
23484
  }
21193
23485
 
21194
23486
  //#endregion
21195
- //#region ../mcp-core/dist/server-DGF-NUWx.js
23487
+ //#region ../mcp-core/dist/server-obGNre-1.js
21196
23488
  /**
21197
23489
  * Format tool calls into a readable trace
21198
23490
  */
@@ -21211,7 +23503,7 @@ function formatToolCallTrace(toolCalls) {
21211
23503
  }
21212
23504
  return trace$1;
21213
23505
  }
21214
- var handler_default$2 = defineTool({
23506
+ var handler_default$3 = defineTool({
21215
23507
  name: "use_sentry",
21216
23508
  skills: [],
21217
23509
  requiredScopes: [],
@@ -21254,7 +23546,8 @@ var handler_default$2 = defineTool({
21254
23546
  },
21255
23547
  async handler(params, context$1) {
21256
23548
  const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
21257
- const { use_sentry,...toolsForAgent } = tools_default;
23549
+ const toolsToExclude = new Set(["use_sentry", ...SIMPLE_REPLACEMENT_TOOLS]);
23550
+ const toolsForAgent = Object.fromEntries(Object.entries(tools_default).filter(([key]) => !toolsToExclude.has(key)));
21258
23551
  const server$1 = buildServer({
21259
23552
  context: context$1,
21260
23553
  tools: toolsForAgent
@@ -21282,6 +23575,25 @@ var handler_default$2 = defineTool({
21282
23575
  }
21283
23576
  }
21284
23577
  });
23578
+ /**
23579
+ * Tools that require an embedded agent provider (LLM-powered).
23580
+ * These are excluded when no agent provider is configured.
23581
+ * Note: use_sentry is handled separately via agentMode.
23582
+ */
23583
+ const AGENT_DEPENDENT_TOOLS = [
23584
+ "search_events",
23585
+ "search_issues",
23586
+ "search_issue_events"
23587
+ ];
23588
+ /**
23589
+ * Simple tools that replace agent-dependent tools when no provider is available.
23590
+ * These are excluded when an agent provider IS configured.
23591
+ */
23592
+ const SIMPLE_REPLACEMENT_TOOLS = [
23593
+ "list_issues",
23594
+ "list_events",
23595
+ "list_issue_events"
23596
+ ];
21285
23597
  var tools_default = {
21286
23598
  whoami: whoami_default,
21287
23599
  find_organizations: find_organizations_default,
@@ -21289,6 +23601,7 @@ var tools_default = {
21289
23601
  find_projects: find_projects_default,
21290
23602
  find_releases: find_releases_default,
21291
23603
  get_issue_details: get_issue_details_default,
23604
+ get_issue_tag_values: get_issue_tag_values_default,
21292
23605
  get_trace_details: get_trace_details_default,
21293
23606
  get_event_attachment: get_event_attachment_default,
21294
23607
  update_issue: update_issue_default,
@@ -21302,7 +23615,11 @@ var tools_default = {
21302
23615
  search_docs: search_docs_default,
21303
23616
  get_doc: get_doc_default,
21304
23617
  search_issues: handler_default$1,
21305
- use_sentry: handler_default$2
23618
+ search_issue_events: handler_default$2,
23619
+ use_sentry: handler_default$3,
23620
+ list_issues: list_issues_default,
23621
+ list_events: list_events_default,
23622
+ list_issue_events: list_issue_events_default
21306
23623
  };
21307
23624
  /**
21308
23625
  * Creates and configures a complete MCP server with Sentry instrumentation.
@@ -21363,7 +23680,12 @@ function buildServer({ context: context$1, agentMode = false, tools: customTools
21363
23680
  * In agent mode, only the use_sentry tool is registered, bypassing authorization checks.
21364
23681
  */
21365
23682
  function configureServer({ server: server$1, context: context$1, agentMode = false, tools: customTools }) {
21366
- const toolsToRegister = agentMode ? { use_sentry: tools_default.use_sentry } : customTools ?? tools_default;
23683
+ let toolsToRegister = agentMode ? { use_sentry: tools_default.use_sentry } : customTools ?? tools_default;
23684
+ if (!agentMode && !customTools) {
23685
+ const hasAgent = hasAgentProvider();
23686
+ const toolsToExclude = new Set(hasAgent ? SIMPLE_REPLACEMENT_TOOLS : AGENT_DEPENDENT_TOOLS);
23687
+ toolsToRegister = Object.fromEntries(Object.entries(toolsToRegister).filter(([key]) => !toolsToExclude.has(key)));
23688
+ }
21367
23689
  const grantedSkills = context$1.grantedSkills ? new Set(context$1.grantedSkills) : void 0;
21368
23690
  server$1.server.onerror = (error) => {
21369
23691
  const transportLogOptions = {
@@ -21444,7 +23766,7 @@ function configureServer({ server: server$1, context: context$1, agentMode = fal
21444
23766
  }
21445
23767
 
21446
23768
  //#endregion
21447
- //#region ../mcp-core/dist/sentry-Cim_ihS6.js
23769
+ //#region ../mcp-core/dist/sentry-CTKJG5Bs.js
21448
23770
  const SCRUB_PATTERNS = [
21449
23771
  {
21450
23772
  pattern: /\bsk-[a-zA-Z0-9]{48}\b/g,
@@ -21535,8 +23857,11 @@ function scrubValue(value, depth = 0) {
21535
23857
  }
21536
23858
  /**
21537
23859
  * Sentry beforeSend hook that scrubs sensitive data from events
23860
+ * and applies custom fingerprinting for specific error types.
21538
23861
  */
21539
23862
  function sentryBeforeSend(event, hint) {
23863
+ const firstException = event?.exception?.values?.[0];
23864
+ if (firstException?.type === "AI_APICallError" && firstException.value) event.fingerprint = ["AI_APICallError", firstException.value];
21540
23865
  const [scrubbedEvent, didScrub, descriptions] = scrubValue(event);
21541
23866
  if (didScrub) {
21542
23867
  const uniqueDescriptions = [...new Set(descriptions)];
@@ -21577,16 +23902,21 @@ const cfg = (() => {
21577
23902
  die(err instanceof Error ? err.message : String(err));
21578
23903
  }
21579
23904
  })();
21580
- if (!process.env.OPENAI_API_KEY) {
21581
- console.warn("Warning: OPENAI_API_KEY environment variable is not set.");
23905
+ if (cfg.agentProvider) setAgentProvider(cfg.agentProvider);
23906
+ setProviderBaseUrls({
23907
+ openaiBaseUrl: cfg.openaiBaseUrl,
23908
+ anthropicBaseUrl: cfg.anthropicBaseUrl
23909
+ });
23910
+ if (cfg.openaiModel) process.env.OPENAI_MODEL = cfg.openaiModel;
23911
+ if (cfg.anthropicModel) process.env.ANTHROPIC_MODEL = cfg.anthropicModel;
23912
+ const resolvedProvider = getResolvedProviderType();
23913
+ if (!resolvedProvider) {
23914
+ console.warn("Warning: No LLM API key found (OPENAI_API_KEY or ANTHROPIC_API_KEY).");
21582
23915
  console.warn("The following AI-powered search tools will be unavailable:");
21583
- console.warn(" - search_events (natural language event search)");
21584
- console.warn(" - search_issues (natural language issue search)");
21585
- console.warn("All other tools will function normally. To enable AI-powered search, set OPENAI_API_KEY.");
23916
+ console.warn(" - search_events, search_issues, search_issue_events, use_sentry");
23917
+ console.warn("Use list_issues and list_events for direct Sentry query syntax instead.");
21586
23918
  console.warn("");
21587
- }
21588
- setOpenAIBaseUrl(cfg.openaiBaseUrl);
21589
- if (cfg.openaiModel) process.env.OPENAI_MODEL = cfg.openaiModel;
23919
+ } else console.warn(`Using ${resolvedProvider} for AI-powered search tools.`);
21590
23920
  Sentry.init({
21591
23921
  dsn: cfg.sentryDsn,
21592
23922
  sendDefaultPii: true,