Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(api): retry failed tool discovery and answer 503 when a tools-only search gets nothing (#5231)

Erik Engervall37eb1f0e39ce
diff --git a/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts b/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
index 6815abee2..4c39d630b 100644
--- a/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
@@ -51,6 +51,10 @@ vi.mock("../../../lib/key-restriction", () => ({
checkKeyEndpointRestriction: vi.fn().mockResolvedValue({ allowed: true }),
}));
+vi.mock("../../../lib/alexandria-activity", () => ({
+ markAlexandriaActivity: vi.fn(),
+}));
+
vi.mock("../../../lib/logger", () => ({
logger: {
info: vi.fn(),
@@ -357,3 +361,61 @@ describe("gov category gov_searches ledger", () => {
expect(res.status).toHaveBeenCalledWith(200);
});
});
+
+describe("tool discovery availability", () => {
+ const unavailable = executeResult({
+ response: { tools: [] },
+ totalResultsCount: 0,
+ indexResultsCount: 0,
+ searchCredits: 0,
+ totalCredits: 0,
+ toolsWarning: "Some tool discovery results are unavailable.",
+ toolsUnavailable: true,
+ });
+
+ it("answers a retryable 503 when a tools-only search finds nothing because discovery failed", async () => {
+ mockExecuteSearch.mockResolvedValue(unavailable);
+ const res = makeRes();
+
+ await searchController(
+ makeReq({ query: "weather", sources: [{ type: "alexandria" }] }),
+ res,
+ );
+
+ expect(res.status).toHaveBeenCalledWith(503);
+ expect(res.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ code: "TOOL_DISCOVERY_UNAVAILABLE",
+ }),
+ );
+ expect(mockLogSearch).toHaveBeenCalledWith(
+ expect.objectContaining({ is_successful: false, credits_cost: 0 }),
+ );
+ });
+
+ it("keeps the partial success when web results answered", async () => {
+ mockExecuteSearch.mockResolvedValue({
+ ...unavailable,
+ response: { web: developerResults, tools: [] },
+ totalResultsCount: 2,
+ });
+ const res = makeRes();
+
+ await searchController(
+ makeReq({
+ query: "weather",
+ sources: [{ type: "web" }, { type: "alexandria" }],
+ }),
+ res,
+ );
+
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: true,
+ warning: "Some tool discovery results are unavailable.",
+ }),
+ );
+ });
+});
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 59cc186a9..568bdf28d 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -473,6 +473,33 @@ async function searchControllerInner(
logger,
);
+ if (toolsOnly && result.toolsUnavailable) {
+ const error =
+ "Tool discovery is temporarily unavailable. Retry the request.";
+ setSpanAttributes(span, { "search.status_code": 503 });
+ logSearch({
+ id: jobId,
+ request_id: agentRequestId ?? jobId,
+ query: req.body.query,
+ is_successful: false,
+ error,
+ results: result.response as any,
+ num_results: 0,
+ time_taken: (Date.now() - middlewareStartTime) / 1000,
+ team_id: req.auth.team_id,
+ options: req.body,
+ credits_cost: 0,
+ zeroDataRetention,
+ }).catch(error => {
+ logger.error("Failed to log search", { error, jobId });
+ });
+ return res.status(503).json({
+ success: false,
+ code: "TOOL_DISCOVERY_UNAVAILABLE",
+ error,
+ });
+ }
+
// Bill team for search credits only (scrape jobs bill themselves)
if (!isSearchPreview && shouldBill) {
billTeam(
diff --git a/apps/api/src/lib/error-serde.ts b/apps/api/src/lib/error-serde.ts
index 006ac7eb8..aa9ba5b51 100644
--- a/apps/api/src/lib/error-serde.ts
+++ b/apps/api/src/lib/error-serde.ts
@@ -104,6 +104,7 @@ const errorMap: Record<ErrorCodes, any> = {
BAD_REQUEST: null,
BAD_REQUEST_INVALID_JSON: null,
INDEX_DAILY_LIMIT: null,
+ TOOL_DISCOVERY_UNAVAILABLE: null,
PARSE_UNSUPPORTED_OPTIONS: null,
// Agent thread rejections are API-level, never transported through workers.
diff --git a/apps/api/src/lib/error.ts b/apps/api/src/lib/error.ts
index 9c0fe10f6..cb815056a 100644
--- a/apps/api/src/lib/error.ts
+++ b/apps/api/src/lib/error.ts
@@ -36,6 +36,7 @@ export type ErrorCodes =
| "SCRAPE_BRANDING_NOT_SUPPORTED"
| "AGENT_INDEX_ONLY"
| "INDEX_DAILY_LIMIT"
+ | "TOOL_DISCOVERY_UNAVAILABLE"
| "SCRAPE_AUDIO_UNSUPPORTED_URL"
| "SCRAPE_VIDEO_UNSUPPORTED_URL"
| "SCRAPE_MEDIA_ACCESS_DENIED"
diff --git a/apps/api/src/search/alexandria.test.ts b/apps/api/src/search/alexandria.test.ts
index e03008dcb..3c81ad891 100644
--- a/apps/api/src/search/alexandria.test.ts
+++ b/apps/api/src/search/alexandria.test.ts
@@ -157,3 +157,51 @@ it("keeps tools when optional navigation is absent, extended or malformed", asyn
expect(result.items[0]).toMatchObject({ next: undefined });
expect(result.items[2]).toMatchObject({ next: undefined });
});
+
+it("retries a failed discovery leg once", async () => {
+ request
+ .mockResolvedValueOnce({ status: 503, body: {} })
+ .mockResolvedValueOnce({
+ status: 200,
+ body: { success: true, creditsCost: 0, data: { items: [tool] } },
+ });
+ const result = await discoverTools(input, logger);
+ expect(logger.warn).toHaveBeenCalledWith(
+ "Semantic tool discovery unavailable",
+ expect.objectContaining({ attempt: 1 }),
+ );
+ expect(request).toHaveBeenCalledTimes(2);
+ expect(result.items).toHaveLength(1);
+ expect(result.warning).toBeUndefined();
+ expect(result.unavailable).toBeUndefined();
+});
+
+it("reports discovery unavailable when every leg fails", async () => {
+ request.mockResolvedValue({ status: 503, body: {} });
+ const result = await discoverTools(
+ { ...input, urls: ["https://example.com/records"] },
+ logger,
+ );
+ expect(request).toHaveBeenCalledTimes(4);
+ expect(result.items).toEqual([]);
+ expect(result.warning).toBeTruthy();
+ expect(result.unavailable).toBe(true);
+});
+
+it("keeps partial results when only one leg fails", async () => {
+ request.mockImplementation(async args =>
+ args.path === "/v1/skills/resolve"
+ ? { status: 503, body: {} }
+ : {
+ status: 200,
+ body: { success: true, creditsCost: 0, data: { items: [tool] } },
+ },
+ );
+ const result = await discoverTools(
+ { ...input, urls: ["https://example.com/records"] },
+ logger,
+ );
+ expect(result.items).toHaveLength(1);
+ expect(result.warning).toBeTruthy();
+ expect(result.unavailable).toBeUndefined();
+});
diff --git a/apps/api/src/search/alexandria.ts b/apps/api/src/search/alexandria.ts
index 28ff52b80..433d3973a 100644
--- a/apps/api/src/search/alexandria.ts
+++ b/apps/api/src/search/alexandria.ts
@@ -13,6 +13,8 @@ export const isAlexandriaSource = (source: { type: string }) =>
type ToolDiscovery = {
items: DiscoveredTool[];
warning?: string;
+ /** Every discovery leg failed and nothing was found. */
+ unavailable?: true;
};
type SourceLike = string | { type: string };
@@ -54,7 +56,8 @@ export async function discoverTools(
const deadline = Date.now() + Math.min(10000, input.timeoutMs);
const items = new Map<string, DetailedDiscoveredTool>();
const selected = { semantic: new Set<string>(), domain: new Set<string>() };
- let failed = false;
+ let attempted = 0;
+ let answered = 0;
const remaining = () => {
if (Date.now() >= deadline) throw new Error("Tool discovery timed out");
return deadline - Date.now();
@@ -122,15 +125,24 @@ export async function discoverTools(
});
}
};
- if (input.query) {
- try {
+ const leg = async (message: string, run: () => Promise<void>) => {
+ attempted++;
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await run();
+ answered++;
+ return;
+ } catch (error) {
+ logger.warn(message, { error, attempt });
+ if (attempt >= 2 || Date.now() >= deadline) return;
+ }
+ }
+ };
+ if (input.query)
+ await leg("Semantic tool discovery unavailable", async () => {
for (const tool of await lookup({ query: input.query }))
merge(tool, "semantic");
- } catch (error) {
- failed = true;
- logger.warn("Semantic tool discovery unavailable", { error });
- }
- }
+ });
const urls = [...new Set(input.urls ?? [])].filter(value => {
const url = URL.parse(value);
return (
@@ -141,8 +153,8 @@ export async function discoverTools(
value.length <= 8192
);
});
- if (urls.length) {
- try {
+ if (urls.length)
+ await leg("Domain tool discovery unavailable", async () => {
// Resolve domains once; Exchange owns matching and provider visibility.
for (let i = 0; i < urls.length; i += 100) {
const result = await exchangeRequest({
@@ -212,11 +224,7 @@ export async function discoverTools(
);
}
}
- } catch (error) {
- failed = true;
- logger.warn("Domain tool discovery unavailable", { error });
- }
- }
+ });
return {
items: [...items.values()].map(tool =>
input.toolDetail === "compact"
@@ -227,8 +235,11 @@ export async function discoverTools(
}
: tool,
),
- ...(failed
+ ...(answered < attempted
? { warning: "Some tool discovery results are unavailable." }
: {}),
+ ...(attempted && !answered && !items.size
+ ? { unavailable: true as const }
+ : {}),
};
}
diff --git a/apps/api/src/search/execute.test.ts b/apps/api/src/search/execute.test.ts
index 6bd6aca29..9090c21bb 100644
--- a/apps/api/src/search/execute.test.ts
+++ b/apps/api/src/search/execute.test.ts
@@ -116,6 +116,21 @@ it("tool-only search never runs or bills SERP", async () => {
expect(result.response.tools).toEqual([{ id: "fred/series/observations" }]);
});
+it("passes through unavailable tool discovery", async () => {
+ mocks.discoverTools.mockResolvedValue({
+ items: [],
+ warning: "Some tool discovery results are unavailable.",
+ unavailable: true,
+ });
+ const result = await executeSearch(
+ { ...options([]), sources: [{ type: "alexandria" }] },
+ { ...context, flags: { exchangeRetrieve: true } },
+ logger,
+ );
+ expect(result.toolsUnavailable).toBe(true);
+ expect(result.response.tools).toEqual([]);
+});
+
it("mixed search bills only normal web results", async () => {
mocks.search.mockResolvedValue({ web: [developerResult] });
const result = await executeSearch(
diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.ts
index 77230f8e7..257fcace3 100644
--- a/apps/api/src/search/execute.ts
+++ b/apps/api/src/search/execute.ts
@@ -74,6 +74,7 @@ interface SearchContext {
interface SearchExecuteResult {
toolsWarning?: string;
+ toolsUnavailable?: boolean;
response: SearchV2Response;
totalResultsCount: number;
indexResultsCount: number;
@@ -261,6 +262,7 @@ export async function executeSearch(
const indexResultsCount = indexResults.length;
totalResultsCount += indexResultsCount;
let toolsWarning: string | undefined;
+ let toolsUnavailable = false;
if (
!zeroDataRetention &&
@@ -288,6 +290,7 @@ export async function executeSearch(
);
searchResponse.tools = discovery.items;
toolsWarning = discovery.warning;
+ toolsUnavailable = discovery.unavailable === true;
}
const isZDR = options.enterprise?.includes("zdr");
@@ -448,6 +451,7 @@ export async function executeSearch(
return {
response: searchResponse,
toolsWarning,
+ toolsUnavailable,
totalResultsCount,
indexResultsCount,
searchCredits,