Skip to content

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

fix(auth): accept an agent run's hosted MCP key from the trusted agent service (#4805)

Rakshith Ramprakash7d6a07e255c5
diff --git a/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts b/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts
new file mode 100644
index 000000000..9c86ae119
--- /dev/null
+++ b/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts
@@ -0,0 +1,335 @@
+import express from "express";
+import request from "supertest";
+
+// The real exchangeRouter, authMiddleware and auth.ts; only I/O is mocked.
+const mocks = vi.hoisted(() => ({
+ authChunk: vi.fn(),
+ upstreamFetch: vi.fn(),
+ exchangeRequest: vi.fn(),
+ acceptedProviders: vi.fn(),
+}));
+
+vi.mock("../../db/connection", () => ({ db: {}, dbRr: {}, dbIndex: {} }));
+vi.mock("../../db/rpc", () => ({
+ authCreditUsageChunk: mocks.authChunk,
+ authCreditUsageChunkFromTeam: vi.fn(),
+ getAgentFreeRequestsLeft: vi.fn(),
+}));
+vi.mock("../../services/redis", () => ({
+ getValue: vi.fn().mockResolvedValue(null),
+ setValue: vi.fn(),
+ deleteKey: vi.fn(),
+}));
+vi.mock("../../services/redlock", () => ({
+ redlock: { using: vi.fn(async (_k, _t, _o, fn) => fn({ aborted: false })) },
+}));
+vi.mock("ioredis", () => ({ default: class {} }));
+vi.mock("../../services/rate-limiter", async importOriginal => ({
+ ...(await importOriginal<typeof import("../../services/rate-limiter")>()),
+ getRateLimiter: vi.fn(() => ({ consume: vi.fn() })),
+ getAutumnRateLimiter: vi.fn(() => ({ consume: vi.fn() })),
+ redisRateLimitClient: {
+ set: vi.fn().mockResolvedValue("OK"),
+ get: vi.fn().mockResolvedValue(null),
+ del: vi.fn().mockResolvedValue(1),
+ },
+}));
+vi.mock("../../services/autumn/autumn.service", async importOriginal => {
+ const actual =
+ await importOriginal<
+ typeof import("../../services/autumn/autumn.service")
+ >();
+ return {
+ ...actual,
+ autumnService: {
+ getRateLimitMultiplier: vi.fn().mockResolvedValue(1),
+ getKnownRateLimitMultiplier: vi.fn().mockResolvedValue(1),
+ },
+ };
+});
+vi.mock("../../services/agent-sponsor", () => ({
+ getAgentSponsorStatus: vi.fn().mockResolvedValue(null),
+}));
+vi.mock("../../services/queue-service", () => ({
+ getRedisConnection: vi.fn(() => ({ sadd: vi.fn() })),
+ getBillingQueue: vi.fn(() => ({ add: vi.fn() })),
+}));
+vi.mock("../../services/logging/log_job", () => ({
+ logRequest: vi.fn(),
+ logProviderScrape: vi.fn(),
+}));
+vi.mock("../../services/alexandria/client", () => ({
+ exchangeRequest: mocks.exchangeRequest,
+}));
+vi.mock("../../services/alexandria/terms", async importOriginal => ({
+ ...(await importOriginal<typeof import("../../services/alexandria/terms")>()),
+ acceptedProviders: mocks.acceptedProviders,
+}));
+vi.mock("undici", async importOriginal => ({
+ ...(await importOriginal<typeof import("undici")>()),
+ fetch: mocks.upstreamFetch,
+}));
+
+import { config } from "../../config";
+import { exchangeRouter } from "../../routes/exchange";
+
+const MANAGED_KEY = "22222222-2222-4222-8222-222222222222";
+const SECRET = "agent-secret";
+const TERMS = { key: "fred-terms", version: "2026-01", digest: "abc" };
+
+function managedRow(flags: Record<string, unknown> | null = null) {
+ return {
+ api_key: MANAGED_KEY,
+ api_key_id: 7,
+ api_key_id_text: "7",
+ team_id: "team-mcp",
+ org_id: "org-mcp",
+ is_banned: false,
+ flags: { exchangeRetrieve: true, ...flags },
+ credential_purpose: "hosted_mcp_oauth",
+ };
+}
+
+// auth_chunk_1 answers only when the key's purpose matches the lookup's.
+function keyResolvesAs(flags?: Record<string, unknown>) {
+ mocks.authChunk.mockImplementation(
+ async (_db: unknown, key: string, purpose = "general") =>
+ key === MANAGED_KEY && purpose === "hosted_mcp_oauth"
+ ? [managedRow(flags)]
+ : [],
+ );
+}
+
+const app = express();
+app.use(express.json());
+app.use("/exchange", exchangeRouter);
+
+const retrieveCall = { provider: "fred", capability: "series/observations" };
+
+type Interop = "none" | "header" | "body" | "wrong";
+
+function send(
+ method: "get" | "post",
+ path: string,
+ interop: Interop,
+ body: Record<string, unknown> = {},
+) {
+ let req = request(app)
+ [method](path)
+ .set("authorization", `Bearer ${MANAGED_KEY}`);
+ if (interop === "header") req = req.set("x-firecrawl-agent-interop", SECRET);
+ if (interop === "wrong")
+ req = req.set("x-firecrawl-agent-interop", "not-the-secret");
+ const payload =
+ interop === "body"
+ ? {
+ ...body,
+ __agentInterop: {
+ auth: SECRET,
+ requestId: "req-1",
+ shouldBill: true,
+ },
+ }
+ : body;
+ return method === "post" ? req.send(payload) : req;
+}
+
+const OPTED_IN = [
+ {
+ name: "GET /exchange/discover",
+ method: "get" as const,
+ path: "/exchange/discover",
+ },
+ {
+ name: "GET /exchange/discover/:cohort",
+ method: "get" as const,
+ path: "/exchange/discover/finance?expand=all",
+ },
+ {
+ name: "GET /exchange/discover?q=",
+ method: "get" as const,
+ path: "/exchange/discover?q=gdp&limit=10",
+ },
+ {
+ name: "POST /exchange/retrieve",
+ method: "post" as const,
+ path: "/exchange/retrieve",
+ body: retrieveCall,
+ },
+ {
+ name: "POST /exchange/publisher/bounties",
+ method: "post" as const,
+ path: "/exchange/publisher/bounties",
+ body: { title: "Find GDP", description: "Quarterly figures" },
+ },
+];
+
+describe("hosted MCP keys on the Exchange routes the agent calls", () => {
+ const original = {
+ USE_DB_AUTHENTICATION: config.USE_DB_AUTHENTICATION,
+ AGENT_INTEROP_SECRET: config.AGENT_INTEROP_SECRET,
+ FIRE_EXCHANGE_URL: config.FIRE_EXCHANGE_URL,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ config.USE_DB_AUTHENTICATION = true;
+ config.AGENT_INTEROP_SECRET = SECRET;
+ config.FIRE_EXCHANGE_URL = "https://exchange.test";
+ keyResolvesAs();
+ mocks.upstreamFetch.mockImplementation(
+ async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
+ );
+ mocks.acceptedProviders.mockResolvedValue(new Map());
+ // Terms requirements answer, then a quote that stops before execution.
+ mocks.exchangeRequest.mockImplementation(async ({ path }) =>
+ path === "/v1/provider-terms/requirements"
+ ? {
+ status: 200,
+ body: {
+ providers: [{ provider: "fred", required: true, terms: TERMS }],
+ },
+ }
+ : { status: 409, body: { success: false, error: "stop here" } },
+ );
+ });
+
+ afterEach(() => {
+ Object.assign(config, original);
+ });
+
+ for (const route of OPTED_IN) {
+ it(`${route.name}: 401 without interop`, async () => {
+ const response = await send(route.method, route.path, "none", route.body);
+ expect(response.status).toBe(401);
+ expect(mocks.upstreamFetch).not.toHaveBeenCalled();
+ expect(mocks.exchangeRequest).not.toHaveBeenCalled();
+ });
+
+ it(`${route.name}: 401 with a wrong interop secret`, async () => {
+ const response = await send(
+ route.method,
+ route.path,
+ "wrong",
+ route.body,
+ );
+ expect(response.status).toBe(401);
+ expect(mocks.upstreamFetch).not.toHaveBeenCalled();
+ expect(mocks.exchangeRequest).not.toHaveBeenCalled();
+ });
+
+ // The legacy /exchange/retrieve body is strict and cannot carry the block.
+ const modes: Interop[] =
+ route.method === "post" && route.path !== "/exchange/retrieve"
+ ? ["header", "body"]
+ : ["header"];
+ for (const mode of modes) {
+ it(`${route.name}: authenticated with a valid interop ${mode}`, async () => {
+ const response = await send(route.method, route.path, mode, route.body);
+ expect(response.status).not.toBe(401);
+ expect(
+ mocks.upstreamFetch.mock.calls.length +
+ mocks.exchangeRequest.mock.calls.length,
+ ).toBeGreaterThan(0);
+ });
+ }
+ }
+
+ it("proxies discover and bounties under the key's own team", async () => {
+ await send("get", "/exchange/discover?q=gdp", "header");
+ await send("post", "/exchange/publisher/bounties", "header", {
+ title: "t",
+ description: "d",
+ team_id: "attacker-team",
+ });
+ for (const [, init] of mocks.upstreamFetch.mock.calls) {
+ expect(init.headers["x-exchange-team-id"]).toBe("team-mcp");
+ }
+ expect(mocks.upstreamFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ [
+ "POST /exchange/provider-terms/accept",
+ "post",
+ "/exchange/provider-terms/accept",
+ ],
+ ["GET /exchange/analytics", "get", "/exchange/analytics"],
+ [
+ "POST /exchange/publisher/bounties/:id/claim",
+ "post",
+ "/exchange/publisher/bounties/b-1/claim",
+ ],
+ ["POST /exchange/records/fetch", "post", "/exchange/records/fetch"],
+ ] as const)(
+ "%s is not opted in: 401 even with the secret",
+ async (_name, method, path) => {
+ const response = await send(method, path, "header");
+ expect(response.status).toBe(401);
+ expect(mocks.upstreamFetch).not.toHaveBeenCalled();
+ },
+ );
+
+ describe("provider terms gate", () => {
+ it("blocks retrieve when the key's team has not accepted the terms", async () => {
+ const response = await send(
+ "post",
+ "/exchange/retrieve",
+ "header",
+ retrieveCall,
+ );
+
+ expect(response.status).toBe(403);
+ expect(JSON.stringify(response.body)).toContain("fred-terms");
+ // Only the requirements lookup ran; no quote, no execution.
+ expect(mocks.exchangeRequest.mock.calls.map(([arg]) => arg.path)).toEqual(
+ ["/v1/provider-terms/requirements"],
+ );
+ expect(mocks.acceptedProviders).toHaveBeenCalledWith(
+ "team-mcp",
+ "org-mcp",
+ );
+ });
+
+ it("blocks retrieve when access is disabled for the key's organization", async () => {
+ keyResolvesAs({
+ organizationDataSourceAccess: {
+ fred: { status: "disabled", disabledReason: "admin" },
+ },
+ });
+
+ const response = await send(
+ "post",
+ "/exchange/retrieve",
+ "header",
+ retrieveCall,
+ );
+
+ expect(response.status).toBe(403);
+ expect(mocks.exchangeRequest.mock.calls.map(([arg]) => arg.path)).toEqual(
+ ["/v1/provider-terms/requirements"],
+ );
+ });
+
+ it("lets retrieve past the gate only once the key's team has accepted", async () => {
+ keyResolvesAs({
+ organizationDataSourceAccess: {
+ fred: {
+ status: "enabled",
+ termsKey: TERMS.key,
+ termsVersion: TERMS.version,
+ },
+ },
+ });
+
+ await send("post", "/exchange/retrieve", "header", retrieveCall);
+
+ expect(mocks.exchangeRequest.mock.calls.map(([arg]) => arg.path)).toEqual(
+ ["/v1/provider-terms/requirements", "/v1/retrieve/quote"],
+ );
+ expect(mocks.exchangeRequest).toHaveBeenCalledWith(
+ expect.objectContaining({ teamId: "team-mcp" }),
+ );
+ });
+ });
+});
diff --git a/apps/api/src/controllers/__tests__/auth.test.ts b/apps/api/src/controllers/__tests__/auth.test.ts
index 29a436be0..05b3d3bdb 100644
--- a/apps/api/src/controllers/__tests__/auth.test.ts
+++ b/apps/api/src/controllers/__tests__/auth.test.ts
@@ -720,6 +720,367 @@ describe("authenticateUser", () => {
});
});
+ describe("agent-managed key fallback", () => {
+ const managedKey = "22222222-2222-4222-8222-222222222222";
+ const managedRow = {
+ api_key: managedKey,
+ api_key_id: 7,
+ team_id: "team-mcp",
+ org_id: "org-mcp",
+ flags: null,
+ credential_purpose: "hosted_mcp_oauth",
+ };
+ const request = ({
+ key = managedKey,
+ body,
+ headers = {},
+ }: {
+ key?: string;
+ body?: unknown;
+ headers?: Record<string, unknown>;
+ } = {}) => ({
+ headers: { authorization: `Bearer ${key}`, ...headers },
+ socket: { remoteAddress: "127.0.0.1" },
+ body,
+ });
+ const interopBody = (auth: string) => ({
+ __agentInterop: { auth, requestId: "req-1", shouldBill: true },
+ });
+ const allow = { allowAgentManagedKey: true };
+ const lookupsFor = (purpose: string) =>
+ vi
+ .mocked(authCreditUsageChunk)
+ .mock.calls.filter(([, , p]) => (p ?? "general") === purpose);
+
+ beforeEach(() => {
+ config.USE_DB_AUTHENTICATION = true;
+ config.AGENT_INTEROP_SECRET = "agent-secret";
+ vi.mocked(getValue).mockResolvedValue(null);
+ vi.mocked(redlock.using).mockImplementation(
+ async (_keys, _ttl, _options, fn) => fn({ aborted: false } as never),
+ );
+ // Mirrors auth_chunk_1: a row only when the key's purpose matches.
+ vi.mocked(authCreditUsageChunk).mockImplementation(
+ async (_db, key, purpose = "general") =>
+ key === managedKey && purpose === "hosted_mcp_oauth"
+ ? [{ ...managedRow }]
+ : [],
+ );
+ });
+
+ it("rejects a hosted_mcp_oauth key without agent interop", async () => {
+ const auth = await authenticateUser(
+ request(),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual({
+ success: false,
+ error: "Unauthorized: Invalid token",
+ status: 401,
+ });
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("accepts a hosted_mcp_oauth key with a valid interop body", async () => {
+ const auth = await authenticateUser(
+ request({ body: interopBody("agent-secret") }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual(
+ expect.objectContaining({
+ success: true,
+ team_id: "team-mcp",
+ org_id: "org-mcp",
+ }),
+ );
+ if (!auth.success) throw new Error("expected fallback auth to succeed");
+ expect(auth.chunk?.api_key).toBe(managedKey);
+ // The managed lookup reads the primary and never touches the cache.
+ expect(authCreditUsageChunk).toHaveBeenLastCalledWith(
+ db,
+ managedKey,
+ "hosted_mcp_oauth",
+ );
+ expect(setValue).not.toHaveBeenCalledWith(
+ expect.stringContaining("hosted_mcp_oauth"),
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it("accepts a hosted_mcp_oauth key with a valid interop header on a bodiless call", async () => {
+ const auth = await authenticateUser(
+ request({ headers: { "x-firecrawl-agent-interop": "agent-secret" } }),
+ {},
+ RateLimiterMode.BrowserExecute,
+ allow,
+ );
+
+ expect(auth).toEqual(
+ expect.objectContaining({ success: true, team_id: "team-mcp" }),
+ );
+ });
+
+ it("still bills and rate-limits against the key's own team", async () => {
+ const consume = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(getAutumnRateLimiter).mockReturnValue({ consume } as never);
+
+ await authenticateUser(
+ request({ body: interopBody("agent-secret") }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(autumnService.getRateLimitMultiplier).toHaveBeenCalledWith(
+ "team-mcp",
+ "org-mcp",
+ );
+ expect(consume).toHaveBeenCalledWith("team-mcp");
+ });
+
+ it.each([
+ ["body", { body: interopBody("not-the-secret") }],
+ [
+ "header",
+ { headers: { "x-firecrawl-agent-interop": "not-the-secret" } },
+ ],
+ [
+ "repeated header",
+ { headers: { "x-firecrawl-agent-interop": ["agent-secret"] } },
+ ],
+ ])("rejects a wrong interop secret in the %s", async (_where, parts) => {
+ const auth = await authenticateUser(
+ request(parts),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual(expect.objectContaining({ status: 401 }));
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("rejects when no interop secret is configured", async () => {
+ config.AGENT_INTEROP_SECRET = undefined;
+
+ const auth = await authenticateUser(
+ request({ body: interopBody("agent-secret") }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual(expect.objectContaining({ status: 401 }));
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("rejects on a route that has not opted in", async () => {
+ const auth = await authenticateUser(
+ request({ body: interopBody("agent-secret") }),
+ {},
+ RateLimiterMode.Crawl,
+ );
+
+ expect(auth).toEqual(expect.objectContaining({ status: 401 }));
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("rejects an unknown or revoked key even with valid interop", async () => {
+ // Revoking a grant deletes its managed key, so both lookups miss.
+ const auth = await authenticateUser(
+ request({
+ key: "33333333-3333-4333-8333-333333333333",
+ body: interopBody("agent-secret"),
+ }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual({
+ success: false,
+ error: "Unauthorized: Invalid token",
+ status: 401,
+ });
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(1);
+ });
+
+ it("still rejects a banned team reached through the fallback", async () => {
+ vi.mocked(authCreditUsageChunk).mockImplementation(
+ async (_db, key, purpose = "general") =>
+ key === managedKey && purpose === "hosted_mcp_oauth"
+ ? [{ ...managedRow, is_banned: true }]
+ : [],
+ );
+
+ const auth = await authenticateUser(
+ request({ body: interopBody("agent-secret") }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual(expect.objectContaining({ status: 403 }));
+ });
+
+ it("resolves a general key through the general lookup only", async () => {
+ const generalKey = "00000000-0000-4000-8000-000000000000";
+ vi.mocked(authCreditUsageChunk).mockImplementation(
+ async (_db, key, purpose = "general") =>
+ key === generalKey && purpose === "general"
+ ? [{ ...managedRow, api_key: generalKey, team_id: "team-1" }]
+ : [],
+ );
+
+ for (const parts of [{}, { body: interopBody("agent-secret") }]) {
+ const auth = await authenticateUser(
+ request({ key: generalKey, ...parts }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+ expect(auth).toEqual(
+ expect.objectContaining({ success: true, team_id: "team-1" }),
+ );
+ }
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("takes the team only from the key's row, never from the request", async () => {
+ const consume = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(getAutumnRateLimiter).mockReturnValue({ consume } as never);
+
+ const auth = await authenticateUser(
+ request({
+ body: {
+ team_id: "attacker-team",
+ teamId: "attacker-team",
+ __agentInterop: {
+ auth: "agent-secret",
+ requestId: "req-1",
+ shouldBill: true,
+ team_id: "attacker-team",
+ teamId: "attacker-team",
+ },
+ },
+ headers: {
+ "x-firecrawl-team-id": "attacker-team",
+ "x-team-id": "attacker-team",
+ },
+ }),
+ {},
+ RateLimiterMode.Browser,
+ allow,
+ );
+
+ expect(auth).toEqual(
+ expect.objectContaining({
+ success: true,
+ team_id: "team-mcp",
+ org_id: "org-mcp",
+ }),
+ );
+ if (!auth.success) throw new Error("expected fallback auth to succeed");
+ expect(auth.chunk?.team_id).toBe("team-mcp");
+ expect(autumnService.getRateLimitMultiplier).toHaveBeenCalledWith(
+ "team-mcp",
+ "org-mcp",
+ );
+ expect(consume).toHaveBeenCalledWith("team-mcp");
+ expect(JSON.stringify(auth)).not.toContain("attacker-team");
+ });
+
+ it("leaves shouldBill: false untouched for the controllers", async () => {
+ const body = {
+ __agentInterop: {
+ auth: "agent-secret",
+ requestId: "req-1",
+ shouldBill: false,
+ },
+ };
+ const req = request({ body });
+
+ const auth = await authenticateUser(
+ req,
+ {},
+ RateLimiterMode.Scrape,
+ allow,
+ );
+
+ // Auth resolves the team as for a billed request and never rewrites the
+ // block; scrape/search/batch-scrape/parse read shouldBill from it later.
+ expect(auth).toEqual(
+ expect.objectContaining({ success: true, team_id: "team-mcp" }),
+ );
+ expect(req.body).toBe(body);
+ expect(body.__agentInterop).toEqual({
+ auth: "agent-secret",
+ requestId: "req-1",
+ shouldBill: false,
+ });
+ });
+
+ it("treats shouldBill: false on a general key exactly as before", async () => {
+ const generalKey = "00000000-0000-4000-8000-000000000000";
+ vi.mocked(authCreditUsageChunk).mockImplementation(
+ async (_db, key, purpose = "general") =>
+ key === generalKey && purpose === "general"
+ ? [{ ...managedRow, api_key: generalKey, team_id: "team-1" }]
+ : [],
+ );
+
+ const results: Awaited<ReturnType<typeof authenticateUser>>[] = [];
+ for (const shouldBill of [true, false]) {
+ results.push(
+ await authenticateUser(
+ request({
+ key: generalKey,
+ body: {
+ __agentInterop: {
+ auth: "agent-secret",
+ requestId: "req-1",
+ shouldBill,
+ },
+ },
+ }),
+ {},
+ RateLimiterMode.Scrape,
+ allow,
+ ),
+ );
+ }
+
+ expect(results[0]).toEqual(results[1]);
+ expect(results[1]).toEqual(
+ expect.objectContaining({ success: true, team_id: "team-1" }),
+ );
+ expect(lookupsFor("hosted_mcp_oauth")).toHaveLength(0);
+ });
+
+ it("floors the rate multiplier for a header-only trusted request", async () => {
+ await authenticateUser(
+ request({ headers: { "x-firecrawl-agent-interop": "agent-secret" } }),
+ {},
+ RateLimiterMode.BrowserExecute,
+ allow,
+ );
+
+ expect(getAutumnRateLimiter).toHaveBeenCalledWith(
+ RateLimiterMode.BrowserExecute,
+ HOBBY_RATE_LIMIT_MULTIPLIER,
+ null,
+ );
+ });
+ });
+
it("leaves the preview token on the static rate limiter", async () => {
config.USE_DB_AUTHENTICATION = true;
config.PREVIEW_TOKEN = "preview-token";
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts
index aeaad01e8..5a49389a5 100644
--- a/apps/api/src/controllers/auth.ts
+++ b/apps/api/src/controllers/auth.ts
@@ -11,7 +11,10 @@ import {
getRateLimitOverride,
HOBBY_RATE_LIMIT_MULTIPLIER,
} from "../services/rate-limiter";
-import { isAgentInteropSecretValid } from "../lib/agent-interop";
+import {
+ AGENT_INTEROP_HEADER,
+ isAgentInteropSecretValid,
+} from "../lib/agent-interop";
import {
KEYLESS_FREE_TIER_LIMIT_MESSAGE,
consumeKeylessRequest,
@@ -636,7 +639,7 @@ export async function authenticateUser(
req,
res,
mode: RateLimiterMode,
- options?: { allowKeyless?: boolean },
+ options?: AuthenticateOptions,
): Promise<AuthResponse> {
const bypassChunk = mockACUC();
bypassChunk.is_extract =
@@ -688,21 +691,31 @@ async function buildAuthenticatedRateLimiter(
return getAutumnRateLimiter(mode, multiplier, flags);
}
+export type AuthenticateOptions = {
+ allowKeyless?: boolean;
+ // Route opt-in: a trusted agent-interop request may authenticate with a
+ // hosted_mcp_oauth key, which agent runs started from the hosted MCP carry.
+ allowAgentManagedKey?: boolean;
+};
+
/**
- * Whether the request carries a valid `__agentInterop` secret, i.e. comes from
- * the trusted internal agent service. Read from the raw body because auth runs
- * before the controller's zod parse — the same shape checkCreditsMiddleware
- * relies on. Presence of the block alone is never trusted; only the secret.
+ * Whether the request carries a valid agent-interop secret, i.e. comes from
+ * the trusted internal agent service. Read from the raw body (auth runs before
+ * the controller's zod parse) or, for bodiless calls, from AGENT_INTEROP_HEADER.
+ * Presence of the block or header alone is never trusted; only the secret.
*/
function isTrustedAgentInteropRequest(req): boolean {
- return isAgentInteropSecretValid(req.body?.__agentInterop?.auth);
+ return (
+ isAgentInteropSecretValid(req.body?.__agentInterop?.auth) ||
+ isAgentInteropSecretValid(req.headers?.[AGENT_INTEROP_HEADER])
+ );
}
async function supaAuthenticateUser(
req,
res,
mode: RateLimiterMode,
- options?: { allowKeyless?: boolean },
+ options?: AuthenticateOptions,
): Promise<AuthResponse> {
const authHeader =
req.headers.authorization ??
@@ -730,7 +743,8 @@ async function supaAuthenticateUser(
// the team's own bucket, so a free team (×1) gets throttled by its own agent.
// Floor trusted agent traffic at the hobby multiplier; paid plans already
// meet it and are unchanged.
- const minRateMultiplier = isTrustedAgentInteropRequest(req)
+ const trustedAgentInterop = isTrustedAgentInteropRequest(req);
+ const minRateMultiplier = trustedAgentInterop
? HOBBY_RATE_LIMIT_MULTIPLIER
: undefined;
@@ -874,6 +888,23 @@ async function supaAuthenticateUser(
chunk = await getACUC(normalizedApi, false, true, RateLimiterMode.Scrape);
+ // Agent runs from the hosted MCP hold the grant's hosted_mcp_oauth key,
+ // not a general one. Accept it only from the trusted agent service, only
+ // on opted-in routes, and only via the uncached primary-read lookup.
+ if (
+ chunk === null &&
+ options?.allowAgentManagedKey === true &&
+ trustedAgentInterop
+ ) {
+ chunk = await getACUC(
+ normalizedApi,
+ false,
+ false,
+ RateLimiterMode.Scrape,
+ "hosted_mcp_oauth",
+ );
+ }
+
if (chunk === null) {
return {
success: false,
diff --git a/apps/api/src/lib/agent-interop.ts b/apps/api/src/lib/agent-interop.ts
index f5c7795ce..66f15647f 100644
--- a/apps/api/src/lib/agent-interop.ts
+++ b/apps/api/src/lib/agent-interop.ts
@@ -1,6 +1,9 @@
import { timingSafeEqual } from "node:crypto";
import { config } from "../config";
+// Header form of `__agentInterop.auth`, for calls with no JSON body (DELETE, GET).
+export const AGENT_INTEROP_HEADER = "x-firecrawl-agent-interop";
+
export function isAgentInteropSecretValid(provided: unknown): boolean {
const expected = config.AGENT_INTEROP_SECRET;
if (
diff --git a/apps/api/src/routes/exchange.ts b/apps/api/src/routes/exchange.ts
index bc97c2a21..b6875a4c6 100644
--- a/apps/api/src/routes/exchange.ts
+++ b/apps/api/src/routes/exchange.ts
@@ -157,7 +157,9 @@ export const exchangeRouter = express.Router();
// Dashboard and publisher routes below stay on the flat Labs limit.
exchangeRouter.get(
"/discover{/*path}",
- authMiddleware(RateLimiterMode.ExchangeDiscover),
+ authMiddleware(RateLimiterMode.ExchangeDiscover, {
+ allowAgentManagedKey: true,
+ }),
wrap(exchangeProxy(DISCOVER_TIMEOUT_MS, { requiresRetrieveFlag: false })),
);
@@ -195,7 +197,7 @@ exchangeRouter.post(
exchangeRouter.post(
"/retrieve",
- authMiddleware(RateLimiterMode.Exchange),
+ authMiddleware(RateLimiterMode.Exchange, { allowAgentManagedKey: true }),
wrap((req, res) =>
providerScrapeController(req as RequestWithAuth<any, any, any>, res, true),
),
@@ -257,7 +259,7 @@ exchangeRouter.get(
exchangeRouter.post(
"/publisher/bounties",
- authMiddleware(RateLimiterMode.Labs),
+ authMiddleware(RateLimiterMode.Labs, { allowAgentManagedKey: true }),
bountyBlocklistMiddleware,
wrap(exchangeProxy(ANALYTICS_TIMEOUT_MS, { requiresRetrieveFlag: false })),
);
diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.ts
index be70acb9a..addb9fcd0 100644
--- a/apps/api/src/routes/shared.ts
+++ b/apps/api/src/routes/shared.ts
@@ -277,6 +277,7 @@ export function authMiddleware(
rateLimiterMode: RateLimiterMode,
options: {
allowKeyless?: boolean | ((req: RequestWithMaybeAuth) => boolean);
+ allowAgentManagedKey?: boolean;
} = {},
): (req: RequestWithMaybeAuth, res: Response, next: NextFunction) => void {
return (req, res, next) => {
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 63c6f6dca..1fe51a759 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -190,7 +190,10 @@ v2Router.post(
"/search",
agentHintsMiddleware("search"),
researchCategoryNoticeMiddleware,
- authMiddleware(RateLimiterMode.Search, { allowKeyless: true }),
+ authMiddleware(RateLimiterMode.Search, {
+ allowKeyless: true,
+ allowAgentManagedKey: true,
+ }),
countryCheck,
checkCreditsMiddleware(undefined, SEARCH_CREDITS_FEATURE_ID),
blocklistMiddleware,
@@ -237,7 +240,10 @@ v2Router.post(
v2Router.post(
"/scrape",
agentHintsMiddleware("scrape"),
- authMiddleware(RateLimiterMode.Scrape, { allowKeyless: true }),
+ authMiddleware(RateLimiterMode.Scrape, {
+ allowKeyless: true,
+ allowAgentManagedKey: true,
+ }),
countryCheck,
checkCreditsMiddleware(1),
scrapeBlocklistMiddleware,
@@ -267,7 +273,7 @@ v2Router.delete(
v2Router.post(
"/batch/scrape",
- authMiddleware(RateLimiterMode.Scrape),
+ authMiddleware(RateLimiterMode.Scrape, { allowAgentManagedKey: true }),
countryCheck,
checkCreditsMiddleware(),
blocklistMiddleware,
@@ -344,14 +350,14 @@ v2Router.ws(
v2Router.get(
"/batch/scrape/:jobId",
- authMiddleware(RateLimiterMode.CrawlStatus),
+ authMiddleware(RateLimiterMode.CrawlStatus, { allowAgentManagedKey: true }),
validateJobIdParam,
wrap((req: any, res: any) => crawlStatusController(req, res, true)),
);
v2Router.delete(
"/batch/scrape/:jobId",
- authMiddleware(RateLimiterMode.CrawlStatus),
+ authMiddleware(RateLimiterMode.CrawlStatus, { allowAgentManagedKey: true }),
validateJobIdParam,
wrap(crawlCancelController),
);
@@ -628,7 +634,7 @@ v2Router.post("/slack/events", wrap(slackEventsController));
v2Router.post(
["/browser", "/interact"],
- authMiddleware(RateLimiterMode.Browser),
+ authMiddleware(RateLimiterMode.Browser, { allowAgentManagedKey: true }),
countryCheck,
checkCreditsMiddleware(2),
wrap(browserCreateController),
@@ -666,7 +672,9 @@ v2Router.delete(
v2Router.delete(
["/browser/:sessionId", "/interact/:sessionId"],
- authMiddleware(RateLimiterMode.BrowserExecute),
+ authMiddleware(RateLimiterMode.BrowserExecute, {
+ allowAgentManagedKey: true,
+ }),
wrap(browserDeleteController),
);