Skip to content

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

feat(api): run hosted MCP browser sessions on the credits left (#5568)

Rakshith Ramprakash033f42f87c27
diff --git a/apps/api/src/controllers/v2/__tests__/browser-mcp-credits.test.ts b/apps/api/src/controllers/v2/__tests__/browser-mcp-credits.test.ts
index 91592e84b..9a1bfbeb8 100644
--- a/apps/api/src/controllers/v2/__tests__/browser-mcp-credits.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/browser-mcp-credits.test.ts
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
billTeam: vi.fn(),
recordRequestCredits: vi.fn(),
getHangarBrowser: vi.fn(),
+ createHangarBrowser: vi.fn(),
+ insertSession: vi.fn(),
}));
vi.mock("../../../config", async importOriginal => {
@@ -46,26 +48,14 @@ vi.mock("../../../lib/hangar", async importOriginal => {
const actual = await importOriginal<typeof import("../../../lib/hangar")>();
return {
...actual,
- createHangarBrowser: vi.fn(async (key: string) => ({
- id: `browser-${key}`,
- cdp_url: "wss://cdp.test",
- view_url: null,
- control_url: null,
- playlist_url: null,
- max_expires_at: null,
- })),
+ createHangarBrowser: mocks.createHangarBrowser,
getHangarBrowser: mocks.getHangarBrowser,
stopHangarBrowser: vi.fn(async () => {}),
};
});
vi.mock("../../../lib/browser-sessions", () => ({
- insertBrowserSession: vi.fn(async (row: { id: string }) => ({
- ...row,
- cdp_url: "wss://cdp.test",
- cdp_path: "",
- cdp_interactive_path: "",
- })),
+ insertBrowserSession: mocks.insertSession,
completeBrowserSessionSettlement: vi.fn(),
getBrowserSession: vi.fn(),
getBrowserSessionFromScrape: vi.fn(),
@@ -109,8 +99,9 @@ vi.mock("../../../services/logging/log_job", () => ({
logRequest: vi.fn(async () => {}),
}));
-import { browserCreateController } from "../browser";
+import { browserCreateController, browserError } from "../browser";
import {
+ createBrowserSession,
reserveBrowserPromptCredits,
settleBrowserSession,
} from "../../../lib/browser-lifecycle";
@@ -184,9 +175,47 @@ beforeEach(() => {
mocks.usedPrompt.mockResolvedValue(false);
mocks.billTeam.mockResolvedValue({ success: true });
mocks.recordRequestCredits.mockResolvedValue(true);
- mocks.getHangarBrowser.mockResolvedValue({ status: "running" });
+ mocks.getHangarBrowser.mockResolvedValue({
+ status: "running",
+ created_at: Math.floor(Date.now() / 1000),
+ });
+ mocks.createHangarBrowser.mockImplementation(async (key: string) => ({
+ id: `browser-${key}`,
+ cdp_url: "wss://cdp.test",
+ view_url: null,
+ control_url: null,
+ playlist_url: null,
+ max_expires_at: null,
+ }));
+ mocks.insertSession.mockImplementation(async (row: { id: string }) => ({
+ ...row,
+ cdp_url: "wss://cdp.test",
+ cdp_path: "",
+ cdp_interactive_path: "",
+ }));
});
+const RESETS_AT = Date.parse("2026-11-04T00:00:00.000Z");
+
+// Autumn answers an MCP credits check from MCP credits plus the org's own
+// credits, and a team credits check from the team's grants plus the org's.
+function balances({
+ mcp = 0,
+ org = 0,
+ team = 0,
+}: {
+ mcp?: number;
+ org?: number;
+ team?: number;
+}) {
+ mocks.checkCredits.mockImplementation(
+ async ({ featureId, value }: { featureId?: string; value: number }) => {
+ const remaining = featureId === "MCP_CREDITS" ? mcp + org : team + org;
+ return { allowed: value <= remaining, remaining, resetsAt: RESETS_AT };
+ },
+ );
+}
+
describe("browser sessions from hosted MCP calls", () => {
it("checks MCP credits for a hosted session and marks it hosted", async () => {
const res = await create(true);
@@ -306,3 +335,151 @@ describe("browser sessions from hosted MCP calls", () => {
},
);
});
+
+describe("hosted MCP browser sessions under the full charge", () => {
+ const createOptions = {
+ blockAds: true,
+ ttl: 600,
+ activityTtl: 300,
+ streamWebView: false,
+ recordSession: false,
+ };
+
+ async function createForPrompt() {
+ const req = makeReq(true);
+ const { session } = await createBrowserSession(req as any, {
+ ...createOptions,
+ prompt: true,
+ });
+ return { req, session };
+ }
+
+ it("runs the full session when MCP credits cover it", async () => {
+ balances({ mcp: 100 });
+
+ expect((await create(true)).statusCode).toBe(200);
+ expect(mocks.createHangarBrowser).toHaveBeenCalledWith(
+ expect.any(String),
+ TEAM_ID,
+ expect.objectContaining({ ttl: 600 }),
+ );
+ await reserveBrowserPromptCredits(makeReq(true) as any, session);
+ expect(mocks.markUsedPrompt).toHaveBeenCalledWith("session-1");
+ });
+
+ it("shortens a new session to the MCP credits left", async () => {
+ balances({ mcp: 12 });
+
+ const res = await create(true);
+ expect(res.statusCode).toBe(200);
+ expect(mocks.createHangarBrowser).toHaveBeenCalledWith(
+ expect.any(String),
+ TEAM_ID,
+ expect.objectContaining({ ttl: 360 }),
+ );
+ expect(mocks.insertSession).toHaveBeenCalledWith(
+ expect.objectContaining({ ttl_total: 360 }),
+ );
+ expect(mocks.markHostedMcp).toHaveBeenCalledWith(res.body.id);
+ });
+
+ it("sizes a session about to be prompted for the MCP credits left", async () => {
+ balances({ mcp: 45 });
+
+ const { req, session: created } = await createForPrompt();
+ expect(mocks.createHangarBrowser).toHaveBeenCalledWith(
+ expect.any(String),
+ TEAM_ID,
+ expect.objectContaining({ ttl: 385 }),
+ );
+ expect(created.ttl_total).toBe(385);
+
+ await reserveBrowserPromptCredits(req as any, {
+ ...session,
+ ttl_total: created.ttl_total,
+ });
+ expect(mocks.checkCredits).toHaveBeenLastCalledWith(
+ expect.objectContaining({ value: 45, featureId: "MCP_CREDITS" }),
+ );
+ expect(mocks.markUsedPrompt).toHaveBeenCalledWith("session-1");
+ expect(mocks.markHostedMcp).toHaveBeenCalledWith("session-1");
+ });
+
+ it("counts the org's own credits after MCP credits", async () => {
+ balances({ mcp: 40, org: 40 });
+ await createForPrompt();
+ expect(mocks.createHangarBrowser).toHaveBeenLastCalledWith(
+ expect.any(String),
+ TEAM_ID,
+ expect.objectContaining({ ttl: 600 }),
+ );
+
+ balances({ mcp: 20, org: 30 });
+ await createForPrompt();
+ expect(mocks.createHangarBrowser).toHaveBeenLastCalledWith(
+ expect.any(String),
+ TEAM_ID,
+ expect.objectContaining({ ttl: 428 }),
+ );
+ });
+
+ it("sizes a session on a team grant to what the grant covers", async () => {
+ balances({ mcp: 10, team: 40 });
+
+ const { session: created } = await createForPrompt();
+ expect(created.ttl_total).toBe(342);
+ expect(mocks.markHostedMcp).not.toHaveBeenCalled();
+ });
+
+ it("refuses a session below the minimum and names the daily allowance", async () => {
+ balances({ mcp: 5 });
+
+ const res = makeRes();
+ const error = await createForPrompt().catch(error => error);
+ browserError(res as unknown as Response, error);
+ expect(res.statusCode).toBe(402);
+ expect(res.body).toMatchObject({
+ success: false,
+ code: "mcp_credits_exhausted",
+ });
+ expect(res.body.error).toContain("daily MCP credit allowance");
+ expect(res.body.error).toContain("resets at 2026-11-04T00:00:00.000Z");
+ expect(mocks.createHangarBrowser).not.toHaveBeenCalled();
+ });
+
+ it("refuses a prompt on a running session the credits can't fully cover", async () => {
+ balances({ mcp: 45 });
+
+ const res = makeRes();
+ const error = await reserveBrowserPromptCredits(
+ makeReq(true) as any,
+ session,
+ ).catch(error => error);
+ browserError(res as unknown as Response, error);
+ expect(res.statusCode).toBe(402);
+ expect(res.body.code).toBe("mcp_credits_exhausted");
+ expect(res.body.error).toContain("daily MCP credit allowance");
+ expect(mocks.markUsedPrompt).not.toHaveBeenCalled();
+ });
+
+ it("bills a shortened session for no more than its lifetime", async () => {
+ mocks.cameFromHostedMcp.mockResolvedValue(true);
+ mocks.usedPrompt.mockResolvedValue(true);
+ mocks.settleOnce.mockImplementation(async (_id: string, compute: any) => ({
+ creditsBilled: await compute({ ...session, should_bill: true }),
+ newlySettled: true,
+ }));
+
+ await settleBrowserSession({ ...session, scrape_id: "scrape-1" }, {
+ status: "stopped",
+ created_at: 1000,
+ ended_at: 1385,
+ } as any);
+ expect(mocks.billTeam).toHaveBeenCalledWith(TEAM_ID, "org-1", 45, null, {
+ endpoint: "interact",
+ jobId: "session-1",
+ chargeId: "session-1:destroy",
+ hostedMcp: true,
+ });
+ });
+});
diff --git a/apps/api/src/controllers/v2/__tests__/scrape-browser.test.ts b/apps/api/src/controllers/v2/__tests__/scrape-browser.test.ts
index 9a1b2b2c2..32b0dc2ec 100644
--- a/apps/api/src/controllers/v2/__tests__/scrape-browser.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/scrape-browser.test.ts
@@ -34,6 +34,7 @@ import {
reserveBrowserPromptCredits,
} from "../../../lib/browser-lifecycle";
import { logRequest } from "../../../services/logging/log_job";
+import { autumnService } from "../../../services/autumn/autumn.service";
import { getModel } from "../../../lib/generic-ai";
import { generateText } from "ai";
import * as langsmith from "../../../lib/scrape-interact/langsmith";
@@ -106,6 +107,7 @@ vi.mock("../../../lib/keyless", () => ({
keylessTeamUuid: vi.fn(() => null),
updateKeylessBrowserCredits: vi.fn(async () => true),
adjustKeylessCredits: vi.fn(async () => {}),
+ KEYLESS_FREE_TIER_LIMIT_MESSAGE: "Keyless limit reached.",
}));
vi.mock("../../../lib/scrape-interact/langsmith", () => ({
sanitizeUrlForTrace: (url: string) => url,
@@ -170,8 +172,10 @@ vi.mock("../../../services/logging/log_job", () => ({
vi.mock("../../../services/autumn/autumn.service", () => ({
DEFAULT_TEAM_LIMITS: { concurrency_limit: 2, rate_limit_multiplier: 1 },
+ CREDITS_FEATURE_ID: "CREDITS",
autumnService: {
checkCredits: vi.fn(async () => ({ allowed: true })),
+ hostedMcpFeatureId: vi.fn(async () => "MCP_CREDITS"),
},
}));
@@ -667,6 +671,39 @@ describe("scrapeInteractController", () => {
);
});
+ it("returns the hosted MCP refusal code when the session can't be created", async () => {
+ config.USE_DB_AUTHENTICATION = true;
+ vi.mocked(readScrapeJobState).mockResolvedValueOnce({
+ status: "completed",
+ requestId: "scrape-123",
+ completedAtMs: Date.now(),
+ creditsBilled: 1,
+ replay: { targetUrl: "https://example.com", waitForMs: 0, actions: [] },
+ } as any);
+ vi.mocked(autumnService.checkCredits).mockResolvedValue({
+ allowed: false,
+ } as any);
+ const res = buildRes();
+ await scrapeInteractController(
+ {
+ params: { jobId: "scrape-123" },
+ body: { prompt: "click the button" },
+ headers: {},
+ auth: { team_id: "team-123", hostedMcp: true },
+ acuc: { org_id: "org-123" },
+ } as any,
+ res,
+ );
+ expect(res.status).toHaveBeenCalledWith(402);
+ expect(res.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ code: "mcp_credits_exhausted",
+ }),
+ );
+ expect(createHangarBrowser).not.toHaveBeenCalled();
+ });
+
it.each([
browserExecuteController,
browserDeleteController,
diff --git a/apps/api/src/controllers/v2/browser.ts b/apps/api/src/controllers/v2/browser.ts
index cbc13b2f7..ad41ba259 100644
--- a/apps/api/src/controllers/v2/browser.ts
+++ b/apps/api/src/controllers/v2/browser.ts
@@ -106,6 +106,9 @@ export function browserError(
error instanceof BrowserSessionError || error instanceof HangarError;
return res.status(knownError ? error.status : 502).json({
success: false,
+ ...(error instanceof BrowserSessionError && error.code
+ ? { code: error.code }
+ : {}),
error: knownError ? error.message : "Browser operation failed.",
});
}
diff --git a/apps/api/src/controllers/v2/scrape-browser.ts b/apps/api/src/controllers/v2/scrape-browser.ts
index 7ca2d8686..e79533b0e 100644
--- a/apps/api/src/controllers/v2/scrape-browser.ts
+++ b/apps/api/src/controllers/v2/scrape-browser.ts
@@ -300,6 +300,7 @@ async function scrapeInteractInternal(
logger,
browserOptions,
zeroDataRetention,
+ Boolean(prompt && !rawCode),
);
if (created.error === true) {
// A keyless limit body carries the caller's own link, so match on it
@@ -498,6 +499,7 @@ async function createSessionForScrape(
logger: typeof _logger,
browserOptions: BrowserOptions,
zeroDataRetention: boolean,
+ prompt: boolean,
) {
try {
const { session } = await createBrowserSession(req, {
@@ -505,6 +507,7 @@ async function createSessionForScrape(
...browserOptions,
scrapeId,
zeroDataRetention,
+ prompt,
initialize: async browserId => {
const replay = await executeHangarBrowser(browserId, {
code: buildReplayScript(replayContext),
@@ -542,7 +545,13 @@ async function createSessionForScrape(
const body =
message === KEYLESS_FREE_TIER_LIMIT_MESSAGE
? await keylessLimitBody(req.auth.team_id, "v2_browser", req)
- : { success: false as const, error: message };
+ : {
+ success: false as const,
+ ...(error instanceof BrowserSessionError && error.code
+ ? { code: error.code }
+ : {}),
+ error: message,
+ };
return { error: true as const, status, body };
}
}
diff --git a/apps/api/src/lib/browser-billing.ts b/apps/api/src/lib/browser-billing.ts
index 730c28f5c..0cd9403e9 100644
--- a/apps/api/src/lib/browser-billing.ts
+++ b/apps/api/src/lib/browser-billing.ts
@@ -21,3 +21,17 @@ export function calculateBrowserSessionCredits(
const minCredits = Math.ceil(creditsPerHour / 60);
return Math.max(minCredits, Math.ceil(hours * creditsPerHour));
}
+
+/** The longest session, in whole seconds, whose charge stays within `credits`. */
+export function browserSecondsForCredits(
+ credits: number,
+ creditsPerHour: number,
+): number {
+ let seconds = Math.floor((credits * 3600) / creditsPerHour);
+ while (
+ seconds > 0 &&
+ calculateBrowserSessionCredits(seconds * 1000, creditsPerHour) > credits
+ )
+ seconds--;
+ return seconds;
+}
diff --git a/apps/api/src/lib/browser-lifecycle.ts b/apps/api/src/lib/browser-lifecycle.ts
index de2e035f1..ec9c3c298 100644
--- a/apps/api/src/lib/browser-lifecycle.ts
+++ b/apps/api/src/lib/browser-lifecycle.ts
@@ -28,6 +28,7 @@ import {
import {
calculateBrowserSessionCredits,
browserCreditsPerHour,
+ browserSecondsForCredits,
} from "./browser-billing";
import { HOBBY_CONCURRENCY_LIMIT } from "./concurrency-limit";
import {
@@ -40,7 +41,10 @@ import {
DEFAULT_TEAM_LIMITS,
} from "../services/autumn/autumn.service";
import { billTeam } from "../services/billing/credit_billing";
-import { checkHostedMcpCredits } from "../services/autumn/hosted-mcp-gate";
+import {
+ checkHostedMcpCredits,
+ hostedMcpCreditsRefusal,
+} from "../services/autumn/hosted-mcp-gate";
import type { TrackCreditsParams } from "../services/autumn/types";
import { orgIdForTeam } from "./team-org";
import { logRequest } from "../services/logging/log_job";
@@ -64,6 +68,7 @@ export class BrowserSessionError extends Error {
constructor(
public status: number,
message: string,
+ public code?: string,
) {
super(message);
this.name = "BrowserSessionError";
@@ -71,24 +76,59 @@ export class BrowserSessionError extends Error {
}
/**
- * A browser charge's credit check. A hosted MCP call that MCP credits can't
- * cover is billed on the team's own credits from here on, like an API-key call.
+ * Checks a browser charge of `params.value` credits and returns how many the
+ * session may spend. A hosted MCP call the full charge doesn't fit is admitted
+ * for the largest charge from `minimum` up that MCP credits, then the team's
+ * own credits, cover, and the caller caps the session to it. A hosted call on
+ * the team's credits is billed there from here on, like an API-key call. Any
+ * other call gets the full charge or `refusal`.
*/
-async function checkBrowserCredits(
+async function reserveBrowserCredits(
req: RequestWithAuth<any, any, any>,
params: TrackCreditsParams,
-) {
- if (!req.auth.hostedMcp)
- return {
- result: await autumnService.checkCredits(params),
- onTeamCredits: false,
- };
- const gate = await checkHostedMcpCredits({
- ...params,
- featureId: CREDITS_FEATURE_ID,
- });
- if (gate.onTeamCredits) req.auth.hostedMcp = false;
- return gate;
+ minimum: number,
+ refusal: string,
+): Promise<{ credits: number; onTeamCredits: boolean }> {
+ if (!req.auth.hostedMcp) {
+ const result = await autumnService.checkCredits(params);
+ if (result !== null && !result.allowed)
+ throw new BrowserSessionError(402, refusal);
+ return { credits: params.value, onTeamCredits: false };
+ }
+ const check = (value: number) =>
+ checkHostedMcpCredits({
+ ...params,
+ value,
+ featureId: CREDITS_FEATURE_ID,
+ });
+ const full = await check(params.value);
+ let admitted =
+ full.result === null || full.result.allowed
+ ? { gate: full, credits: params.value }
+ : undefined;
+ // Autumn decides which balances pay, so ask it rather than add balances up.
+ let [low, high] = admitted ? [1, 0] : [minimum, params.value - 1];
+ while (low <= high) {
+ const credits = Math.floor((low + high) / 2);
+ const gate = await check(credits);
+ if (gate.result?.allowed) {
+ admitted = { gate, credits };
+ low = credits + 1;
+ } else {
+ high = credits - 1;
+ }
+ }
+ if (!admitted)
+ throw new BrowserSessionError(
+ 402,
+ hostedMcpCreditsRefusal(full.result?.resetsAt),
+ "mcp_credits_exhausted",
+ );
+ if (admitted.gate.onTeamCredits) req.auth.hostedMcp = false;
+ return {
+ credits: admitted.credits,
+ onTeamCredits: admitted.gate.onTeamCredits,
+ };
}
/** Returns the effective session policy and rejects disallowed ZDR requests. */
@@ -154,6 +194,8 @@ export async function createBrowserSession(
recordSession: boolean;
zeroDataRetention?: boolean;
scrapeId?: string;
+ /** Size the session for the prompt rate, for a call about to prompt it. */
+ prompt?: boolean;
shouldBill?: boolean;
requestId?: string;
initialize?: (browserId: string) => Promise<void>;
@@ -192,11 +234,13 @@ async function createBrowserSessionInternal(
const invalidInterop = invalidAgentInteropError(req);
if (invalidInterop) throw invalidInterop;
const shouldBill = options.shouldBill ?? true;
- const estimatedCredits = shouldBill
- ? calculateBrowserSessionCredits(
- options.ttl * 1000,
- browserCreditsPerHour(false, zeroDataRetention),
- )
+ const creditsPerHour = browserCreditsPerHour(
+ options.prompt === true,
+ zeroDataRetention,
+ );
+ let ttl = options.ttl;
+ let estimatedCredits = shouldBill
+ ? calculateBrowserSessionCredits(ttl * 1000, creditsPerHour)
: 0;
const teamLimit =
req.acuc?.concurrency_limit ?? DEFAULT_TEAM_LIMITS.concurrency_limit;
@@ -208,21 +252,25 @@ async function createBrowserSessionInternal(
? Math.max(teamLimit, HOBBY_CONCURRENCY_LIMIT)
: teamLimit;
if (shouldBill && req.acuc?.org_id) {
- const { result: credit } = await checkBrowserCredits(req, {
- teamId: req.auth.team_id,
- orgId: req.acuc.org_id,
- value: estimatedCredits,
- properties: {
- source: "browserCreate",
- path: req.path,
- apiKeyId: req.acuc?.api_key_id ?? null,
+ const { credits } = await reserveBrowserCredits(
+ req,
+ {
+ teamId: req.auth.team_id,
+ orgId: req.acuc.org_id,
+ value: estimatedCredits,
+ properties: {
+ source: "browserCreate",
+ path: req.path,
+ apiKeyId: req.acuc?.api_key_id ?? null,
+ },
},
- });
- if (credit !== null && !credit.allowed)
- throw new BrowserSessionError(
- 402,
- `Insufficient credits for a ${options.ttl}s browser session (requires ~${estimatedCredits} credits).`,
- );
+ calculateBrowserSessionCredits(60_000, creditsPerHour),
+ `Insufficient credits for a ${options.ttl}s browser session (requires ~${estimatedCredits} credits).`,
+ );
+ if (credits < estimatedCredits) {
+ ttl = browserSecondsForCredits(credits, creditsPerHour);
+ estimatedCredits = credits;
+ }
}
const id = uuidv7();
let browserId: string | undefined;
@@ -231,7 +279,7 @@ async function createBrowserSessionInternal(
!(await reserveExternalSlot(
req.auth.team_id,
id,
- (options.ttl + 300) * 1000,
+ (ttl + 300) * 1000,
limit,
))
)
@@ -249,6 +297,7 @@ async function createBrowserSessionInternal(
throw new BrowserSessionError(429, KEYLESS_FREE_TIER_LIMIT_MESSAGE);
const browser = await createHangarBrowser(id, req.auth.team_id, {
...options,
+ ttl,
zeroDataRetention,
usOnly: isUsOnly(req.acuc?.flags),
});
@@ -282,7 +331,7 @@ async function createBrowserSessionInternal(
cdp_interactive_path: browser.control_url ?? "",
stream_web_view: options.streamWebView,
status: "active",
- ttl_total: options.ttl,
+ ttl_total: ttl,
ttl_without_activity: options.activityTtl,
credits_used: null,
profile_name: options.profile?.name ?? null,
@@ -477,22 +526,23 @@ export async function reserveBrowserPromptCredits(
);
let onTeamCredits = false;
if (session.should_bill && req.acuc?.org_id) {
- const gate = await checkBrowserCredits(req, {
- teamId: session.team_id,
- orgId: req.acuc.org_id,
- value: credits,
- properties: {
- source: "browserPrompt",
- path: req.path,
- apiKeyId: req.acuc?.api_key_id ?? null,
+ // Hangar can't shorten a running browser, so a prompt needs the whole
+ // session's charge at the prompt rate.
+ ({ onTeamCredits } = await reserveBrowserCredits(
+ req,
+ {
+ teamId: session.team_id,
+ orgId: req.acuc.org_id,
+ value: credits,
+ properties: {
+ source: "browserPrompt",
+ path: req.path,
+ apiKeyId: req.acuc?.api_key_id ?? null,
+ },
},
- });
- if (gate.result !== null && !gate.result.allowed)
- throw new BrowserSessionError(
- 402,
- "Insufficient credits for a browser prompt session.",
- );
- onTeamCredits = gate.onTeamCredits;
+ credits,
+ "Insufficient credits for a browser prompt session.",
+ ));
}
// The same row lock guards settlement: a prompt admitted before stop
// records its rate before billing reads it, and a later prompt cannot
diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.ts
index 93efebba8..141b856f6 100644
--- a/apps/api/src/routes/shared.ts
+++ b/apps/api/src/routes/shared.ts
@@ -30,7 +30,10 @@ import {
CREDITS_FEATURE_ID,
} from "../services/autumn/autumn.service";
import { getTeamBalance } from "../services/autumn/usage";
-import { checkHostedMcpCredits } from "../services/autumn/hosted-mcp-gate";
+import {
+ checkHostedMcpCredits,
+ hostedMcpCreditsRefusal,
+} from "../services/autumn/hosted-mcp-gate";
import { getApiKeySpendLimit } from "../lib/api-key-spend-limit";
import {
ThirdPartyDataTermsRequiredError,
@@ -331,7 +334,7 @@ export function checkCreditsMiddleware(
code: "mcp_credits_exhausted",
requested_credits: requestedCredits,
...(resetsAt ? { resets_at: resetsAt } : {}),
- error: `Insufficient credits for this connected-app request. Hosted MCP calls (from apps such as ChatGPT, Claude or Codex) spend a daily MCP credit allowance first and then your team's credits, and neither can cover this request${resetsAt ? `; the allowance resets at ${resetsAt}` : ""}. To continue now, add credits or upgrade your plan at https://firecrawl.dev/pricing.`,
+ error: hostedMcpCreditsRefusal(autumnResult.resetsAt),
});
}
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index e38ec9184..141f117ec 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -674,7 +674,7 @@ v2Router.post(
authMiddleware(RateLimiterMode.Browser, { allowAgentManagedKey: true }),
inferIntegrationMiddleware,
countryCheck,
- checkCreditsMiddleware(2),
+ checkCreditsMiddleware(2, undefined, { mcpCredits: true }),
wrap(browserCreateController),
);
diff --git a/apps/api/src/services/autumn/hosted-mcp-gate.ts b/apps/api/src/services/autumn/hosted-mcp-gate.ts
index f04aef50d..4699bf761 100644
--- a/apps/api/src/services/autumn/hosted-mcp-gate.ts
+++ b/apps/api/src/services/autumn/hosted-mcp-gate.ts
@@ -3,6 +3,12 @@ import type { TrackCreditsParams } from "./types";
type CheckResult = Awaited<ReturnType<typeof autumnService.checkCredits>>;
+/** The refusal for a hosted MCP charge neither MCP credits nor the team's own credits cover. */
+export function hostedMcpCreditsRefusal(resetsAt?: number): string {
+ const resets = resetsAt ? new Date(resetsAt).toISOString() : undefined;
+ return `Insufficient credits for this connected-app request. Hosted MCP calls (from apps such as ChatGPT, Claude or Codex) spend a daily MCP credit allowance first and then your team's credits, and neither can cover this request${resets ? `; the allowance resets at ${resets}` : ""}. To continue now, add credits or upgrade your plan at https://firecrawl.dev/pricing.`;
+}
+
/**
* Checks a hosted MCP charge on MCP credits, the balance it is billed to, and
* when they refuse it, on the team's own `featureId` balance, where team-scoped