Skip to content

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

feat(api): add the Code Search gateway route

Karan Lokchandani6b9d01fb7255
diff --git a/apps/api/src/__tests__/snips/v2/code.test.ts b/apps/api/src/__tests__/snips/v2/code.test.ts
new file mode 100644
index 000000000..7e56032a5
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v2/code.test.ts
@@ -0,0 +1,270 @@
+import { config } from "../../../config";
+import { describeIf, TEST_PRODUCTION } from "../lib";
+import { creditUsage, idmux, researchPostRaw, researchRaw } from "./lib";
+import { and, desc, eq } from "drizzle-orm";
+import { db } from "../../../db/connection";
+import * as schema from "../../../db/schema";
+
+const HAS_RESEARCH = !!config.RESEARCH_PROXY_URL;
+const KEYLESS_ENABLED =
+ process.env.KEYLESS_REQUESTS_PER_DAY !== undefined &&
+ process.env.KEYLESS_CREDITS_PER_DAY !== undefined;
+
+const CANONICAL_PATH = "/v2/search/code/search";
+const UPSTREAM_MIRROR_PATH = "/v2/code/search";
+
+const COVERAGE_STATUSES = ["ok", "degraded", "unavailable", "skipped"];
+
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+const sleepForBilling = () => sleep(40000);
+
+async function waitForSingleRow<T>(
+ fetcher: () => Promise<T | null>,
+ timeoutMs: number = 10000,
+ intervalMs: number = 250,
+): Promise<T | null> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const row = await fetcher();
+ if (row) return row;
+ await sleep(intervalMs);
+ }
+ return null;
+}
+
+describeIf(HAS_RESEARCH)("Code Search API", () => {
+ it("serves code search from the canonical mount", async () => {
+ const identity = await idmux({
+ name: "code/canonical search",
+ credits: 100,
+ });
+
+ const res = await researchRaw(
+ CANONICAL_PATH,
+ { query: "how do I configure retries", k: 3 },
+ identity,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(Array.isArray(res.body.results)).toBe(true);
+ for (const type of ["doc", "issue", "pull_request", "readme"]) {
+ expect(COVERAGE_STATUSES).toContain(res.body.coverage[type]);
+ }
+ expect(typeof res.body.reranked).toBe("boolean");
+
+ for (const result of res.body.results) {
+ expect(typeof result.id).toBe("string");
+ expect(typeof result.url).toBe("string");
+ expect(["doc", "issue", "pull_request", "readme"]).toContain(result.type);
+ expect(Array.isArray(result.passages)).toBe(true);
+ expect(result.license).toBeUndefined();
+ }
+ }, 120000);
+
+ it("serves the same search from a POST body", async () => {
+ const identity = await idmux({
+ name: "code/post body",
+ credits: 100,
+ });
+
+ const res = await researchPostRaw(
+ CANONICAL_PATH,
+ { query: "graceful shutdown", k: 2, types: ["issue", "readme"] },
+ identity,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(Array.isArray(res.body.results)).toBe(true);
+ for (const result of res.body.results) {
+ expect(["issue", "readme"]).toContain(result.type);
+ }
+ expect(res.body.coverage.doc).toBe("skipped");
+ expect(res.body.coverage.pull_request).toBe("skipped");
+ }, 120000);
+
+ it("serves code search from the upstream-mirror mount", async () => {
+ const identity = await idmux({
+ name: "code/mirror mount",
+ credits: 100,
+ });
+
+ const res = await researchRaw(
+ UPSTREAM_MIRROR_PATH,
+ { query: "connection pool sizing", k: 1 },
+ identity,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(Array.isArray(res.body.results)).toBe(true);
+ }, 120000);
+
+ it("keeps the upstream casing on repo enrollment status", async () => {
+ const identity = await idmux({
+ name: "code/repo status casing",
+ credits: 100,
+ });
+
+ const res = await researchRaw(
+ CANONICAL_PATH,
+ {
+ query: "rate limit handling",
+ k: 1,
+ repos: "firecrawl/firecrawl",
+ types: "issue",
+ },
+ identity,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(Array.isArray(res.body.repos)).toBe(true);
+ expect(res.body.repos[0]).toMatchObject({
+ repo: "firecrawl/firecrawl",
+ types: { pullRequest: expect.any(Boolean) },
+ });
+ }, 120000);
+
+ it("rejects unknown params and an out-of-bound k", async () => {
+ const identity = await idmux({
+ name: "code/invalid input",
+ credits: 100,
+ });
+
+ for (const params of [
+ { query: "retries", magic: "true" } as any,
+ { query: "retries", k: 101 },
+ ]) {
+ const res = await researchRaw(CANONICAL_PATH, params, identity);
+ expect(res.statusCode).toBe(400);
+ expect(res.body.success).toBe(false);
+ }
+ });
+
+ it("logs the code search request kind with origin and integration", async () => {
+ if (!config.USE_DB_AUTHENTICATION) return;
+
+ const identity = await idmux({
+ name: "code/logs metadata",
+ credits: 100,
+ });
+ const query = `code metadata ${Date.now()}`;
+
+ const res = await researchRaw(
+ CANONICAL_PATH,
+ { query, k: 1, integration: "_research_test" },
+ identity,
+ { "X-Origin": "mcp" },
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+
+ const requestLog = await waitForSingleRow<{
+ origin: string | null;
+ integration: string | null;
+ }>(async () => {
+ const data = await db
+ .select({
+ origin: schema.requests.origin,
+ integration: schema.requests.integration,
+ })
+ .from(schema.requests)
+ .where(
+ and(
+ eq(schema.requests.team_id, identity.teamId),
+ eq(schema.requests.kind, "research_code_search"),
+ eq(schema.requests.target_hint, query),
+ ),
+ )
+ .orderBy(desc(schema.requests.created_at))
+ .limit(1);
+ return data[0] ?? null;
+ });
+
+ expect(requestLog).not.toBeNull();
+ expect(requestLog?.origin).toBe("mcp");
+ expect(requestLog?.integration).toBe("_research_test");
+ }, 120000);
+
+ it("writes a usage row with the billed credits", async () => {
+ if (!config.USE_DB_AUTHENTICATION) return;
+
+ const identity = await idmux({
+ name: "code/logs usage",
+ credits: 100,
+ });
+ const query = `code usage ${Date.now()}`;
+
+ const res = await researchRaw(CANONICAL_PATH, { query, k: 3 }, identity);
+ expect(res.statusCode).toBe(200);
+
+ const expected = Math.ceil(res.body.results.length / 10) * 2;
+ const usageLog = await waitForSingleRow<{
+ credits_cost: number;
+ num_results: number;
+ is_successful: boolean;
+ }>(async () => {
+ const data = await db
+ .select({
+ credits_cost: schema.research_code_searches.credits_cost,
+ num_results: schema.research_code_searches.num_results,
+ is_successful: schema.research_code_searches.is_successful,
+ })
+ .from(schema.research_code_searches)
+ .where(eq(schema.research_code_searches.target, query))
+ .orderBy(desc(schema.research_code_searches.created_at))
+ .limit(1);
+ return data[0] ?? null;
+ });
+
+ expect(usageLog).not.toBeNull();
+ expect(usageLog?.is_successful).toBe(true);
+ expect(usageLog?.num_results).toBe(res.body.results.length);
+ expect(usageLog?.credits_cost).toBe(expected);
+ }, 120000);
+
+ describeIf(KEYLESS_ENABLED)("keyless code search", () => {
+ it("permits keyless access on the canonical mount", async () => {
+ const res = await researchRaw(CANONICAL_PATH, {
+ query: "retry backoff",
+ k: 1,
+ });
+
+ expect(res.statusCode).not.toBe(401);
+ }, 120000);
+
+ it("refuses keyless access on the upstream-mirror mount", async () => {
+ const res = await researchRaw(UPSTREAM_MIRROR_PATH, {
+ query: "retry backoff",
+ k: 1,
+ });
+
+ expect(res.statusCode).toBe(401);
+ }, 120000);
+ });
+
+ describeIf(TEST_PRODUCTION)("code search billing", () => {
+ it("bills by returned result count", async () => {
+ const identity = await idmux({
+ name: "code/bills by results",
+ credits: 100,
+ });
+ const before = (await creditUsage(identity)).remainingCredits;
+
+ const res = await researchRaw(
+ CANONICAL_PATH,
+ { query: "cancel an in-flight request", k: 11 },
+ identity,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+ const expectedCredits = Math.ceil(res.body.results.length / 10) * 2;
+
+ await sleepForBilling();
+ const after = (await creditUsage(identity)).remainingCredits;
+ expect(before - after).toBe(expectedCredits);
+ }, 180000);
+ });
+});
diff --git a/apps/api/src/__tests__/snips/v2/lib.ts b/apps/api/src/__tests__/snips/v2/lib.ts
index 9199a9698..32ad050b1 100644
--- a/apps/api/src/__tests__/snips/v2/lib.ts
+++ b/apps/api/src/__tests__/snips/v2/lib.ts
@@ -723,6 +723,20 @@ export async function researchRaw(
return query ? req.query(query) : req;
}
+export async function researchPostRaw(
+ path: string,
+ body: Record<string, unknown>,
+ identity?: Identity,
+) {
+ const req = request(TEST_API_URL)
+ .post(path)
+ .set("Content-Type", "application/json");
+ if (identity) {
+ req.set("Authorization", `Bearer ${identity.apiKey}`);
+ }
+ return req.send(body);
+}
+
export async function searchRawFull(
body: SearchRequestInput,
identity: Identity,
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts
index 20523fe2e..f72628e3a 100644
--- a/apps/api/src/controllers/auth.ts
+++ b/apps/api/src/controllers/auth.ts
@@ -478,9 +478,11 @@ async function handleKeylessAuth(
? "search"
: mode === RateLimiterMode.Research
? "research"
- : mode === RateLimiterMode.BrowserExecute
- ? "interact"
- : "scrape";
+ : mode === RateLimiterMode.CodeSearch
+ ? "code"
+ : mode === RateLimiterMode.BrowserExecute
+ ? "interact"
+ : "scrape";
let result: Awaited<ReturnType<typeof consumeKeylessRequest>>;
try {
diff --git a/apps/api/src/controllers/v2/research-proxy.ts b/apps/api/src/controllers/v2/research-proxy.ts
index ca7a905ee..15e6d1a58 100644
--- a/apps/api/src/controllers/v2/research-proxy.ts
+++ b/apps/api/src/controllers/v2/research-proxy.ts
@@ -92,6 +92,48 @@ const githubSearchSchema = z.strictObject({
...commonQuery,
});
+const starsSchema = z.coerce.number().int().nonnegative().optional();
+
+const booleanFlag = z
+ .union([z.boolean(), z.enum(["true", "false"])])
+ .optional()
+ .transform(value =>
+ value === undefined ? undefined : value === true || value === "true",
+ );
+
+const codeSearchSchema = z.strictObject({
+ query: z.string().min(1),
+ k: kSchema(100),
+ types: multiString,
+ repos: multiString,
+ sources: multiString,
+ passages: kSchema(5),
+ language: z.string().min(1).optional(),
+ topic: multiString,
+ license: z.string().min(1).optional(),
+ min_stars: starsSchema,
+ max_stars: starsSchema,
+ archived: booleanFlag,
+ fork: booleanFlag,
+ ...commonQuery,
+});
+
+const CODE_SEARCH_QUERY_KEYS = [
+ "query",
+ "k",
+ "types",
+ "repos",
+ "sources",
+ "passages",
+ "language",
+ "topic",
+ "license",
+ "min_stars",
+ "max_stars",
+ "archived",
+ "fork",
+];
+
type ResearchEndpointConfig = {
kind: ResearchRequestKind;
table: ResearchTableName;
@@ -259,7 +301,8 @@ function createResearchController(
teamId: authedReq.auth.team_id,
});
- const parsed = schema.safeParse(req.query);
+ const source = req.method === "POST" ? (req.body ?? {}) : req.query;
+ const parsed = schema.safeParse(source);
if (!parsed.success) {
logger.warn("Invalid research query", { error: parsed.error.issues });
return researchError(
@@ -483,3 +526,23 @@ export function createResearchRouter(options: { legacy?: boolean } = {}) {
return router;
}
+
+export function createCodeRouter() {
+ const router = express.Router();
+
+ const controller = wrap(
+ createResearchController(codeSearchSchema, CODE_SEARCH_QUERY_KEYS, {
+ kind: "research_code_search",
+ table: "research_code_searches",
+ action: "searchCode",
+ targetHint: params => String(params.query),
+ upstreamPath: () => "/v2/code/search",
+ billAs: "search",
+ }),
+ );
+
+ router.get("/search", controller);
+ router.post("/search", controller);
+
+ return router;
+}
diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.ts
index af0485a39..0d6357af3 100644
--- a/apps/api/src/db/schema/public.ts
+++ b/apps/api/src/db/schema/public.ts
@@ -206,6 +206,10 @@ export const research_github_searches = researchEndpointTable(
"research_github_searches",
);
+export const research_code_searches = researchEndpointTable(
+ "research_code_searches",
+);
+
export const deterministic_json_scripts = pgTable(
"deterministic_json_scripts",
{
diff --git a/apps/api/src/lib/key-restriction.test.ts b/apps/api/src/lib/key-restriction.test.ts
index 2595cdcfb..dc3a9d773 100644
--- a/apps/api/src/lib/key-restriction.test.ts
+++ b/apps/api/src/lib/key-restriction.test.ts
@@ -84,6 +84,15 @@ describe("classifyEndpoint", () => {
expect(classifyEndpoint("/v2/search")).toMatchObject({ group: "search" });
});
+ it("groups code search with research on both mounts", () => {
+ expect(classifyEndpoint("/v2/search/code/search")).toMatchObject({
+ group: "research",
+ });
+ expect(classifyEndpoint("/v2/code/search")).toMatchObject({
+ group: "research",
+ });
+ });
+
it("marks account/metadata endpoints as always allowed", () => {
expect(classifyEndpoint("/v2/team/credit-usage")).toMatchObject({
alwaysAllowed: true,
@@ -136,6 +145,19 @@ describe("isEndpointAllowed", () => {
expect(isEndpointAllowed("/v2/search", c).allowed).toBe(false);
});
+ it("gates code search on the research group, not the web-search group", () => {
+ const research = config({ allowedEndpoints: ["research"] });
+ expect(isEndpointAllowed("/v2/search/code/search", research).allowed).toBe(
+ true,
+ );
+ expect(isEndpointAllowed("/v2/code/search", research).allowed).toBe(true);
+
+ const webSearch = config({ allowedEndpoints: ["search"] });
+ expect(isEndpointAllowed("/v2/search/code/search", webSearch).allowed).toBe(
+ false,
+ );
+ });
+
it("always allows account/metadata endpoints for restricted keys", () => {
const c = config({ allowedEndpoints: ["scrape"] });
expect(isEndpointAllowed("/v2/team/credit-usage", c).allowed).toBe(true);
diff --git a/apps/api/src/lib/key-restriction.ts b/apps/api/src/lib/key-restriction.ts
index 9a67b0d5b..fc8d2fced 100644
--- a/apps/api/src/lib/key-restriction.ts
+++ b/apps/api/src/lib/key-restriction.ts
@@ -111,6 +111,7 @@ const ENDPOINT_GROUPS: [string[], string][] = [
[["crawl"], "crawl"],
[["map"], "map"],
[["search", "research"], "research"],
+ [["search", "code"], "research"],
[["search"], "search"],
[["extract"], "extract"],
[["agent"], "agent"],
@@ -119,6 +120,7 @@ const ENDPOINT_GROUPS: [string[], string][] = [
[["interact"], "browser"],
[["monitor"], "monitor"],
[["research"], "research"],
+ [["code"], "research"],
[["llmstxt"], "llmstxt"],
[["deep-research"], "deep-research"],
[["fireclaw"], "fireclaw"],
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index da6361cf9..78c077131 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -79,7 +79,10 @@ import {
testTeamSiemLoggingController,
} from "../controllers/v2/team-siem-logging";
import { supportProxyController } from "../controllers/v2/support-proxy";
-import { createResearchRouter } from "../controllers/v2/research-proxy";
+import {
+ createCodeRouter,
+ createResearchRouter,
+} from "../controllers/v2/research-proxy";
import {
scrapeInteractController,
scrapeStopInteractiveBrowserController,
@@ -642,4 +645,16 @@ if (config.RESEARCH_PROXY_URL) {
authMiddleware(RateLimiterMode.Research),
createResearchRouter({ legacy: true }),
);
+
+ v2Router.use(
+ "/search/code",
+ authMiddleware(RateLimiterMode.CodeSearch, { allowKeyless: true }),
+ createCodeRouter(),
+ );
+
+ v2Router.use(
+ "/code",
+ authMiddleware(RateLimiterMode.CodeSearch),
+ createCodeRouter(),
+ );
}
diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.ts
index 1809cdfba..7914734c4 100644
--- a/apps/api/src/services/logging/log_job.ts
+++ b/apps/api/src/services/logging/log_job.ts
@@ -50,6 +50,7 @@ const tableMap: Record<string, PgTable> = {
research_paper_reads: schema.research_paper_reads,
research_related_papers: schema.research_related_papers,
research_github_searches: schema.research_github_searches,
+ research_code_searches: schema.research_code_searches,
extracts: schema.extracts,
maps: schema.maps,
llmstxts: schema.llmstxts,
@@ -176,7 +177,8 @@ type LoggedRequest = {
| "research_paper_inspect"
| "research_paper_read"
| "research_related_papers"
- | "research_github_search";
+ | "research_github_search"
+ | "research_code_search";
api_version: string;
team_id: string;
origin?: string;
@@ -506,14 +508,16 @@ export type ResearchRequestKind =
| "research_paper_inspect"
| "research_paper_read"
| "research_related_papers"
- | "research_github_search";
+ | "research_github_search"
+ | "research_code_search";
export type ResearchTableName =
| "research_paper_searches"
| "research_paper_inspects"
| "research_paper_reads"
| "research_related_papers"
- | "research_github_searches";
+ | "research_github_searches"
+ | "research_code_searches";
type LoggedResearchEndpoint = {
table: ResearchTableName;
diff --git a/apps/api/src/services/rate-limiter.ts b/apps/api/src/services/rate-limiter.ts
index 0450c270d..9804ae872 100644
--- a/apps/api/src/services/rate-limiter.ts
+++ b/apps/api/src/services/rate-limiter.ts
@@ -35,6 +35,7 @@ const fallbackRateLimits: Record<RateLimiterMode, number> = {
supportAsk: 3,
supportDocsSearch: 3,
research: 100,
+ codeSearch: 100,
};
/**
diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts
index e3e5cd8e3..114b3165c 100644
--- a/apps/api/src/types.ts
+++ b/apps/api/src/types.ts
@@ -159,6 +159,7 @@ export enum RateLimiterMode {
SupportAsk = "supportAsk",
SupportDocsSearch = "supportDocsSearch",
Research = "research",
+ CodeSearch = "codeSearch",
}
export type AuthResponse =