From 9fa0f74e4587216ddc9ca1d0b19f302316190bdb Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:43:16 +0000 Subject: [PATCH] fix(search-events): Keep the agent's absolute window when a period is also passed For structured queries with an explicit `period`, the handler dropped the embedded agent's absolute `start`/`end` and searched the whole period. Callers that name a fixed window in the query and send `period` as an outer guard got rolling-period results without being told. Use the overlap of the agent's absolute range and the period instead. It can only narrow the period; with no overlap, the period is kept. --- .../src/tools/catalog/search-events.test.ts | 92 +++++++++++++++++++ .../src/tools/support/search-events/search.ts | 59 +++++++++++- 2 files changed, 148 insertions(+), 3 deletions(-) diff --git a/packages/mcp-core/src/tools/catalog/search-events.test.ts b/packages/mcp-core/src/tools/catalog/search-events.test.ts index 5f6a82246..0e31464bc 100644 --- a/packages/mcp-core/src/tools/catalog/search-events.test.ts +++ b/packages/mcp-core/src/tools/catalog/search-events.test.ts @@ -3419,6 +3419,98 @@ describe("search_events", () => { expect(validatedQueries.at(-1)).not.toContain("message:"); }); + describe("explicit period with an absolute range from the agent", () => { + const HOUR_MS = 3_600_000; + + const runWithAgentRange = async (range: { start: string; end: string }) => { + // The query names a fixed window in prose next to structured filters, + // and the caller also sends `period` as an outer guard. + mockGenerateText.mockResolvedValueOnce( + mockAIResponse( + "errors", + "environment:production is:unresolved", + ["count()", "count_unique(user.id)"], + undefined, + "-count()", + range, + ), + ); + const requests: URLSearchParams[] = []; + mswServer.use( + http.get( + "https://sentry.io/api/0/organizations/test-org/events/", + ({ request }) => { + requests.push(new URL(request.url).searchParams); + return HttpResponse.json({ data: [] }); + }, + ), + ); + + await runSearchEvents( + { + organizationSlug: "test-org", + regionUrl: null, + projectSlug: null, + dataset: "errors", + query: `Between ${range.start} and ${range.end}, environment:production is:unresolved, count() and count_unique(user.id)`, + period: "3d", + limit: 10, + includeExplanation: false, + }, + { + constraints: { + organizationSlug: null, + regionUrl: null, + projectSlug: null, + }, + accessToken: "test-token", + userId: "1", + }, + { lockDataset: true }, + ); + + expect(requests).toHaveLength(1); + return requests[0]!; + }; + + it("searches the agent's absolute window inside the period", async () => { + const start = new Date(Date.now() - 30 * HOUR_MS).toISOString(); + const end = new Date(Date.now() - 2 * HOUR_MS).toISOString(); + + const request = await runWithAgentRange({ start, end }); + + expect(request.get("query")).toBe("environment:production is:unresolved"); + expect(request.has("statsPeriod")).toBe(false); + expect(request.get("start")).toBe(start); + expect(request.get("end")).toBe(end); + }); + + it("clips an absolute window that starts before the period", async () => { + const before = Date.now(); + const start = new Date(before - 5 * 24 * HOUR_MS).toISOString(); + const end = new Date(before - 2 * HOUR_MS).toISOString(); + + const request = await runWithAgentRange({ start, end }); + + expect(request.has("statsPeriod")).toBe(false); + const clippedStart = Date.parse(request.get("start")!); + expect(clippedStart).toBeGreaterThanOrEqual(before - 3 * 24 * HOUR_MS); + expect(clippedStart).toBeLessThanOrEqual(Date.now() - 3 * 24 * HOUR_MS); + expect(request.get("end")).toBe(end); + }); + + it("keeps the period when the absolute window is outside it", async () => { + const request = await runWithAgentRange({ + start: "2020-01-01T00:00:00Z", + end: "2020-01-02T00:00:00Z", + }); + + expect(request.get("statsPeriod")).toBe("3d"); + expect(request.has("start")).toBe(false); + expect(request.has("end")).toBe(false); + }); + }); + it("rejects partial full-text downgrades when a duplicate structured key remains", async () => { // Set-based key comparison would miss this: custom remains present after // custom:foo is dropped into message full-text. diff --git a/packages/mcp-core/src/tools/support/search-events/search.ts b/packages/mcp-core/src/tools/support/search-events/search.ts index 2f070b83f..e8ba0cfb6 100644 --- a/packages/mcp-core/src/tools/support/search-events/search.ts +++ b/packages/mcp-core/src/tools/support/search-events/search.ts @@ -144,6 +144,58 @@ function parseAgentTimeRange( return undefined; } +const PERIOD_UNIT_MS = { + m: 60_000, + h: 3_600_000, + d: 86_400_000, + w: 604_800_000, +} as const; + +/** + * Narrow an explicit relative `period` to the agent's absolute range. + * + * The agent returns `start`/`end` when the query names a fixed window, often + * with `period` sent as an outer guard. Keeping only `period` would silently + * search the whole period. The overlap of the two can only narrow `period`, so + * it is always safe; without an overlap, `period` is kept. + */ +function narrowPeriodToAgentRange( + period: string, + agentRange: + | { statsPeriod?: string; start?: string; end?: string } + | undefined, +): { statsPeriod?: string; start?: string; end?: string } { + const periodMatch = /^(\d+)([mhdw])$/.exec(period); + if (!agentRange?.start || !agentRange.end || !periodMatch) { + return { statsPeriod: period }; + } + const start = Date.parse(agentRange.start); + const end = Date.parse(agentRange.end); + const now = Date.now(); + const periodStart = + now - + Number(periodMatch[1]) * + PERIOD_UNIT_MS[periodMatch[2] as keyof typeof PERIOD_UNIT_MS]; + const narrowedStart = Math.max(start, periodStart); + const narrowedEnd = Math.min(end, now); + if ( + Number.isNaN(narrowedStart + narrowedEnd) || + narrowedStart >= narrowedEnd + ) { + return { statsPeriod: period }; + } + return { + start: + narrowedStart === start + ? agentRange.start + : new Date(narrowedStart).toISOString(), + end: + narrowedEnd === end + ? agentRange.end + : new Date(narrowedEnd).toISOString(), + }; +} + function buildRequestFields( dataset: PublicEventsDataset | "replays", fields: string[], @@ -932,10 +984,11 @@ async function executeSearchEvents( explanation = parsed.explanation; environment = params.environment ?? parsed.environment; + const agentTimeRange = parseAgentTimeRange(parsed.timeRange); timeParams = - shouldTrustExplicitSearchParams && hasExplicitPeriod - ? { statsPeriod: params.period } - : (parseAgentTimeRange(parsed.timeRange) ?? { statsPeriod: "14d" }); + shouldTrustExplicitSearchParams && params.period !== undefined + ? narrowPeriodToAgentRange(params.period, agentTimeRange) + : (agentTimeRange ?? { statsPeriod: "14d" }); if (dataset === "replays") { fields = [];