Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions packages/mcp-core/src/tools/catalog/search-events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
59 changes: 56 additions & 3 deletions packages/mcp-core/src/tools/support/search-events/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down Expand Up @@ -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 = [];
Expand Down
Loading