Skip to content

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

feat(api/agent): add list endpoint that scales properly (#4467)

Gergő Móriczcc82cc9f4ab9
diff --git a/apps/api/src/controllers/v2/agent-list.ts b/apps/api/src/controllers/v2/agent-list.ts
new file mode 100644
index 000000000..875d50cfc
--- /dev/null
+++ b/apps/api/src/controllers/v2/agent-list.ts
@@ -0,0 +1,281 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { config } from "../../config";
+import { db } from "../../db/connection";
+import { agent_session_settings } from "../../db/schema";
+import { clickhouseClient } from "../../lib/clickhouse-client";
+import { AgentListResponse, ErrorResponse, RequestWithAuth } from "./types";
+import { Response } from "express";
+
+type RecentAgent = {
+ id: string;
+ options: any;
+ createdAt: string;
+ status:
+ | "processing"
+ | "succeeded"
+ | "failed"
+ | "cancelled"
+ | "refused"
+ | "credit_limit_reached";
+};
+
+export async function agentListController(
+ req: RequestWithAuth<{}, AgentListResponse>,
+ res: Response<AgentListResponse>,
+) {
+ const limit = 20;
+
+ // Number() (not parseInt) so malformed values like "123abc" are rejected
+ // instead of silently truncated.
+ const parsedBefore = req.query.before
+ ? Number(req.query.before as string)
+ : undefined;
+
+ if (
+ parsedBefore !== undefined &&
+ (isNaN(parsedBefore) ||
+ !isFinite(parsedBefore) ||
+ !Number.isInteger(parsedBefore) ||
+ parsedBefore < 0)
+ ) {
+ return res.status(400).json({
+ success: false,
+ error: "Invalid before timestamp.",
+ });
+ }
+
+ if (!config.USE_DB_AUTHENTICATION) {
+ return res.status(501).json({
+ success: false,
+ error:
+ "This endpoint is only available if your Firecrawl deployment is backed by a database.",
+ });
+ }
+
+ if (!config.EXTRACT_V3_BETA_URL) {
+ throw new Error("Agent beta is not enabled.");
+ }
+
+ if (clickhouseClient === null) {
+ return res.status(501).json({
+ success: false,
+ error: "This endpoint is only available if ClickHouse is configured.",
+ });
+ }
+
+ const [recentResult, dbResult] = await Promise.allSettled([
+ (async () => {
+ const recentRes = await fetch(
+ config.EXTRACT_V3_BETA_URL +
+ "/internal/recent-agents-for-team?teamId=" +
+ req.auth.team_id,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${config.AGENT_INTEROP_SECRET}`,
+ },
+ },
+ );
+
+ if (!recentRes.ok) {
+ throw new Error(
+ "Unexpected response: " +
+ recentRes.statusText +
+ " " +
+ (await recentRes.text()),
+ );
+ }
+
+ return new Map(
+ (await recentRes.json()).map((x: RecentAgent) => [x.id, x]),
+ );
+ })(),
+ (async () => {
+ const requestsRes = await clickhouseClient.query({
+ query:
+ "SELECT id, created_at, target_hint, origin, integration FROM public_requests WHERE team_id = {teamId: UUID} AND kind = 'agent' AND created_at < {before: DateTime} ORDER BY created_at DESC LIMIT {limit: UInt32};",
+ query_params: {
+ teamId: req.auth.team_id,
+ // Fetch one extra row so we can tell whether another page exists
+ // instead of emitting a next cursor whenever the page is full.
+ limit: limit + 1,
+ before:
+ parsedBefore !== undefined
+ ? new Date(parsedBefore).toISOString()
+ : new Date().toISOString(),
+ },
+ format: "JSONEachRow",
+ });
+
+ const bareRequests: {
+ id: string;
+ createdAt: Date;
+ targetHint: string;
+ origin: string;
+ integration: string | null | undefined;
+ }[] = (await requestsRes.json()).map(
+ (x: {
+ id: string;
+ created_at: string;
+ target_hint: string;
+ origin: string;
+ integration: string;
+ }) => ({
+ id: x.id,
+ createdAt: new Date(x.created_at),
+ targetHint: x.target_hint,
+ origin: x.origin,
+ integration: x.integration,
+ }),
+ );
+
+ const agentsRes = await clickhouseClient.query({
+ query:
+ "SELECT id, options, is_successful FROM public_agents WHERE id IN {ids: Array(UUID)};",
+ query_params: {
+ ids: bareRequests.map(x => x.id),
+ },
+ format: "JSONEachRow",
+ });
+ const agentResults: {
+ id: string;
+ options: any;
+ isSuccessful: boolean;
+ error: string | null;
+ }[] = (await agentsRes.json()).map(
+ (x: {
+ id: string;
+ options: any;
+ is_successful: boolean;
+ error: string | null;
+ }) => ({
+ id: x.id,
+ options: x.options,
+ isSuccessful: x.is_successful,
+ error: x.error,
+ }),
+ );
+ const agentMap = new Map(agentResults.map(x => [x.id, x]));
+
+ return new Map(
+ bareRequests
+ .map(x => ({ ...x, agent: agentMap.get(x.id) }))
+ .map(x => [x.id, x]),
+ );
+ })(),
+ ]);
+
+ const recentAgents: Map<string, RecentAgent> =
+ recentResult.status === "fulfilled" ? recentResult.value : new Map();
+
+ // Recent agents are merged into every response, so without this filter they
+ // would repeat on every paginated page. Only include the ones that fall
+ // within the requested page range.
+ if (parsedBefore !== undefined) {
+ for (const [id, agent] of recentAgents) {
+ if (new Date(agent.createdAt).valueOf() >= parsedBefore) {
+ recentAgents.delete(id);
+ }
+ }
+ }
+ if (dbResult.status === "rejected") {
+ throw dbResult.reason;
+ }
+ const dbAgents = dbResult.value;
+
+ const allIds = [...new Set([...recentAgents.keys(), ...dbAgents.keys()])];
+
+ const sessionSettings = await db
+ .select()
+ .from(agent_session_settings)
+ .where(
+ and(
+ inArray(agent_session_settings.session_id, allIds),
+ eq(agent_session_settings.team_id, req.auth.team_id),
+ ),
+ );
+
+ const sessionSettingsMap = new Map(
+ sessionSettings.map(x => [x.session_id, x]),
+ );
+
+ const agents: Exclude<AgentListResponse, ErrorResponse>["agents"] = [];
+
+ for (const id of allIds) {
+ const recent = recentAgents.get(id);
+ const db = dbAgents.get(id);
+ const settings = sessionSettingsMap.get(id);
+
+ agents.push({
+ id: db?.id ?? recent!.id,
+ createdAt: db?.createdAt.toISOString() ?? recent!.createdAt,
+ targetHint:
+ db?.targetHint ??
+ (recent?.options
+ ? (recent.options.urls?.[0] ?? recent.options.prompt ?? "")
+ : ""),
+ origin: db?.origin ?? "api", // recent cannot know origin so we lie
+ integration: db?.integration ?? undefined, // recent cannot know integration so we omit
+ settings: {
+ hidden: settings?.hidden ?? false,
+ starred: settings?.starred ?? false,
+ label: settings?.label ?? undefined,
+ },
+ status: db
+ ? db.agent
+ ? db.agent.isSuccessful
+ ? "completed"
+ : "failed"
+ : "processing"
+ : recent!.status === "processing"
+ ? "processing"
+ : recent!.status === "succeeded"
+ ? "completed"
+ : "failed",
+ options: db?.agent
+ ? {
+ urls: db.agent.options.urls ?? undefined,
+ prompt: db.agent.options.prompt ?? "",
+ schema: db.agent.options.schema ?? undefined,
+ model: db.agent.options.model ?? "spark-1-pro",
+ effort:
+ db.agent.options.effort ??
+ (db.agent.options.model === "spark-2" ? "medium" : undefined),
+ }
+ : recent?.options
+ ? {
+ urls: recent.options.urls ?? undefined,
+ prompt: recent.options.prompt ?? "",
+ schema: recent.options.schema ?? undefined,
+ model: recent.options.modelPreset ?? "spark-1-pro",
+ effort:
+ recent.options.effort ??
+ (recent.options.modelPreset === "spark-2"
+ ? "medium"
+ : undefined),
+ }
+ : undefined,
+ });
+ }
+
+ // The merged list is recent agents followed by ClickHouse rows; sort so the
+ // page is globally ordered by creation time and the next cursor (taken from
+ // the last entry) is correct.
+ agents.sort(
+ (a, b) => new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf(),
+ );
+
+ // The ClickHouse query fetched limit + 1 rows and recent agents are merged
+ // on top, so anything past limit means another page exists. Dropped entries
+ // are older than the new cursor and resurface on the next page.
+ const hasMore = agents.length > limit;
+ const page = agents.slice(0, limit);
+
+ return res.json({
+ success: true,
+ agents: page,
+ next: hasMore
+ ? `${req.protocol}://${req.host}/v2/agent?before=${new Date(page.slice(-1)[0].createdAt).valueOf()}`
+ : undefined,
+ });
+}
diff --git a/apps/api/src/controllers/v2/agent.ts b/apps/api/src/controllers/v2/agent.ts
index 38d77aa3c..0ebe7fd17 100644
--- a/apps/api/src/controllers/v2/agent.ts
+++ b/apps/api/src/controllers/v2/agent.ts
@@ -193,6 +193,9 @@ export async function agentController(
status: passthrough.status,
text,
});
+
+ // TODO: should we try to insert a failed agent row here, since a request is already created? - Mogery
+
return res.status(500).json({
success: false,
error: "Failed to passthrough agent request.",
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 94a83cc65..a71adc0af 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1508,6 +1508,36 @@ export interface ExtractResponse {
creditsUsed?: number;
}
+export type AgentListResponse =
+ | ErrorResponse
+ | {
+ success: true;
+ agents: {
+ id: string;
+ createdAt: string;
+ targetHint: string;
+ origin: string;
+ integration?: string;
+ settings: {
+ hidden: boolean;
+ starred: boolean;
+ label?: string;
+ };
+ status: "processing" | "completed" | "failed";
+ options?: {
+ urls?: string[];
+ prompt: string;
+ schema?: any;
+ // Widened past the known presets on purpose: this is the stored
+ // value from historical runs, and new models ship without an API
+ // type release.
+ model: "spark-1-pro" | "spark-1-mini" | "spark-2" | (string & {});
+ effort?: "low" | "medium" | "high";
+ };
+ }[];
+ next?: string;
+ };
+
export type AgentResponse =
| ErrorResponse
| {
diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.ts
index 79a779c18..c7eb24527 100644
--- a/apps/api/src/db/schema/public.ts
+++ b/apps/api/src/db/schema/public.ts
@@ -51,6 +51,18 @@ export const agent_sponsors = pgTable("agent_sponsors", {
updated_at: ts("updated_at").defaultNow(),
});
+export const agent_session_settings = pgTable("agent_session_settings", {
+ id: uuid("id").notNull(),
+ session_id: uuid("session_id").notNull(),
+ team_id: uuid("team_id").notNull(),
+ hidden: boolean("hidden").default(false),
+ starred: boolean("starred").default(false),
+ label: text("label"),
+ created_at: ts("created_at").defaultNow(),
+ updated_at: ts("updated_at").defaultNow(),
+ share_id: uuid("share_id"),
+});
+
export const agents = pgTable("agents", {
id: uuid("id").notNull(),
request_id: uuid("request_id").notNull(),
diff --git a/apps/api/src/lib/clickhouse-client.ts b/apps/api/src/lib/clickhouse-client.ts
index ed55d878a..efead8bb0 100644
--- a/apps/api/src/lib/clickhouse-client.ts
+++ b/apps/api/src/lib/clickhouse-client.ts
@@ -2,7 +2,7 @@ import { createClient } from "@clickhouse/client";
import { config } from "../config";
import { logger } from "./logger";
-const client = config.CLICKHOUSE_ANALYTICS_URL
+export const clickhouseClient = config.CLICKHOUSE_ANALYTICS_URL
? createClient({
url: config.CLICKHOUSE_ANALYTICS_URL,
database: config.CLICKHOUSE_ANALYTICS_DATABASE ?? "default",
@@ -19,10 +19,10 @@ export async function chInsert(
opts?: { throwOnError?: boolean },
): Promise<boolean> {
if (rows.length === 0) return true;
- if (!client) return false;
+ if (!clickhouseClient) return false;
try {
- await client.insert({
+ await clickhouseClient.insert({
table,
values: rows,
format: "JSONEachRow",
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index c45073164..0ea7ae9ce 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -111,6 +111,7 @@ import {
slackOAuthStartController,
slackStatusController,
} from "../controllers/v2/slack";
+import { agentListController } from "../controllers/v2/agent-list";
export const v2Router = express.Router();
expressWs(express()).applyTo(v2Router);
@@ -376,6 +377,12 @@ v2Router.get(
wrap(extractStatusController),
);
+v2Router.get(
+ "/agent",
+ authMiddleware(RateLimiterMode.ExtractStatus),
+ wrap(agentListController),
+);
+
v2Router.post(
"/agent",
authMiddleware(RateLimiterMode.Extract),
diff --git a/apps/dot-net-sdk/Firecrawl.Tests/ModelsTests.cs b/apps/dot-net-sdk/Firecrawl.Tests/ModelsTests.cs
index 612fbe99c..9c8d14ed2 100644
--- a/apps/dot-net-sdk/Firecrawl.Tests/ModelsTests.cs
+++ b/apps/dot-net-sdk/Firecrawl.Tests/ModelsTests.cs
@@ -623,3 +623,83 @@ public class ModelsTests
Assert.Equal(5, result.ResultsJudged);
}
}
+
+public class AgentListModelsTests
+{
+ private static readonly JsonSerializerOptions JsonOptions = FirecrawlHttpClient.JsonOptions;
+
+ [Fact]
+ public void AgentListResponse_DeserializesCorrectly()
+ {
+ var json = """
+ {
+ "success": true,
+ "agents": [
+ {
+ "id": "018f3c5e-0000-7000-8000-000000000000",
+ "createdAt": "2026-08-31T12:00:00.000Z",
+ "targetHint": "https://example.com",
+ "origin": "api",
+ "integration": "my-app",
+ "settings": { "hidden": false, "starred": true, "label": "prod" },
+ "status": "completed",
+ "options": {
+ "urls": ["https://example.com"],
+ "prompt": "find pricing",
+ "model": "spark-1-pro",
+ "effort": "high"
+ }
+ }
+ ],
+ "next": "https://api.firecrawl.dev/v2/agent?before=1756600000000"
+ }
+ """;
+
+ var response = JsonSerializer.Deserialize<AgentListResponse>(json, JsonOptions);
+
+ Assert.NotNull(response);
+ Assert.True(response.Success);
+ Assert.Equal("https://api.firecrawl.dev/v2/agent?before=1756600000000", response.Next);
+ Assert.NotNull(response.Agents);
+ Assert.Single(response.Agents);
+
+ var agent = response.Agents[0];
+ Assert.Equal("018f3c5e-0000-7000-8000-000000000000", agent.Id);
+ Assert.Equal("2026-08-31T12:00:00.000Z", agent.CreatedAt);
+ Assert.Equal("https://example.com", agent.TargetHint);
+ Assert.Equal("api", agent.Origin);
+ Assert.Equal("my-app", agent.Integration);
+ Assert.Equal("completed", agent.Status);
+
+ Assert.NotNull(agent.Settings);
+ Assert.False(agent.Settings.Hidden);
+ Assert.True(agent.Settings.Starred);
+ Assert.Equal("prod", agent.Settings.Label);
+
+ Assert.NotNull(agent.Options);
+ Assert.Equal("find pricing", agent.Options.Prompt);
+ Assert.Equal("spark-1-pro", agent.Options.Model);
+ Assert.Equal("high", agent.Options.Effort);
+ Assert.NotNull(agent.Options.Urls);
+ Assert.Single(agent.Options.Urls);
+ }
+
+ [Fact]
+ public void AgentListResponse_DeserializesWithoutNext()
+ {
+ var json = """
+ {
+ "success": true,
+ "agents": []
+ }
+ """;
+
+ var response = JsonSerializer.Deserialize<AgentListResponse>(json, JsonOptions);
+
+ Assert.NotNull(response);
+ Assert.True(response.Success);
+ Assert.Null(response.Next);
+ Assert.NotNull(response.Agents);
+ Assert.Empty(response.Agents);
+ }
+}
diff --git a/apps/dot-net-sdk/Firecrawl/FirecrawlClient.cs b/apps/dot-net-sdk/Firecrawl/FirecrawlClient.cs
index 169db89f8..04b31e09e 100644
--- a/apps/dot-net-sdk/Firecrawl/FirecrawlClient.cs
+++ b/apps/dot-net-sdk/Firecrawl/FirecrawlClient.cs
@@ -568,6 +568,32 @@ public class FirecrawlClient
cancellationToken);
}
+ // ================================================================
+ // AGENT
+ // ================================================================
+
+ /// <summary>
+ /// Lists agent runs, most recent first.
+ /// </summary>
+ /// <remarks>
+ /// Pages are fixed at 20 runs. To fetch the next page, pass the before
+ /// value from the previous page's next URL. This method does not
+ /// auto-paginate.
+ /// </remarks>
+ /// <param name="before">Only return agent runs created before this unix millisecond timestamp.</param>
+ /// <param name="cancellationToken">Cancellation token.</param>
+ public async Task<AgentListResponse> ListAgentsAsync(
+ long? before = null,
+ CancellationToken cancellationToken = default)
+ {
+ var query = before.HasValue
+ ? $"?before={Uri.EscapeDataString(before.Value.ToString())}"
+ : string.Empty;
+
+ return await _http.GetAsync<AgentListResponse>(
+ $"/v2/agent{query}", cancellationToken);
+ }
+
// ================================================================
// USAGE & METRICS
// ================================================================
diff --git a/apps/dot-net-sdk/Firecrawl/Models/AgentListModels.cs b/apps/dot-net-sdk/Firecrawl/Models/AgentListModels.cs
new file mode 100644
index 000000000..827112b8d
--- /dev/null
+++ b/apps/dot-net-sdk/Firecrawl/Models/AgentListModels.cs
@@ -0,0 +1,93 @@
+using System.Text.Json.Serialization;
+
+namespace Firecrawl.Models;
+
+/// <summary>
+/// Response from listing agent runs.
+/// </summary>
+public class AgentListResponse
+{
+ [JsonPropertyName("success")]
+ public bool Success { get; set; }
+
+ [JsonPropertyName("agents")]
+ public List<AgentListItem>? Agents { get; set; }
+
+ /// <summary>
+ /// Absolute URL of the next page; only present when more pages exist.
+ /// </summary>
+ [JsonPropertyName("next")]
+ public string? Next { get; set; }
+
+ [JsonPropertyName("error")]
+ public string? Error { get; set; }
+}
+
+/// <summary>
+/// A single agent run as returned by the agent list endpoint.
+/// </summary>
+public class AgentListItem
+{
+ [JsonPropertyName("id")]
+ public string? Id { get; set; }
+
+ [JsonPropertyName("createdAt")]
+ public string? CreatedAt { get; set; }
+
+ [JsonPropertyName("targetHint")]
+ public string? TargetHint { get; set; }
+
+ [JsonPropertyName("origin")]
+ public string? Origin { get; set; }
+
+ [JsonPropertyName("integration")]
+ public string? Integration { get; set; }
+
+ [JsonPropertyName("settings")]
+ public AgentListItemSettings? Settings { get; set; }
+
+ [JsonPropertyName("status")]
+ public string? Status { get; set; }
+
+ [JsonPropertyName("options")]
+ public AgentListItemOptions? Options { get; set; }
+}
+
+/// <summary>
+/// Per-session settings attached to an agent run.
+/// </summary>
+public class AgentListItemSettings
+{
+ [JsonPropertyName("hidden")]
+ public bool Hidden { get; set; }
+
+ [JsonPropertyName("starred")]
+ public bool Starred { get; set; }
+
+ [JsonPropertyName("label")]
+ public string? Label { get; set; }
+}
+
+/// <summary>
+/// Options an agent run was started with.
+/// </summary>
+public class AgentListItemOptions
+{
+ [JsonPropertyName("urls")]
+ public List<string>? Urls { get; set; }
+
+ [JsonPropertyName("prompt")]
+ public string? Prompt { get; set; }
+
+ [JsonPropertyName("schema")]
+ public object? Schema { get; set; }
+
+ [JsonPropertyName("model")]
+ public string? Model { get; set; }
+
+ /// <summary>
+ /// The effort the run used; only present for runs that specified one.
+ /// </summary>
+ [JsonPropertyName("effort")]
+ public string? Effort { get; set; }
+}
diff --git a/apps/elixir-sdk/lib/firecrawl.ex b/apps/elixir-sdk/lib/firecrawl.ex
index fc6f40b2f..7f479fcdd 100644
--- a/apps/elixir-sdk/lib/firecrawl.ex
+++ b/apps/elixir-sdk/lib/firecrawl.ex
@@ -913,6 +913,49 @@ defmodule Firecrawl do
end
+ @list_agents_query_schema NimbleOptions.new!([
+ before: [type: :integer, doc: "Only return agent runs created before this unix millisecond timestamp"]
+ ])
+
+ @list_agents_query_key_mapping %{before: "before"}
+
+ @doc """
+ List agent runs, most recent first
+
+ `GET /agent`
+
+ Tag: Agent
+
+ Pages are fixed at 20 runs. To fetch the next page, pass the `before` value
+ from the previous page's `next` URL. This function does not auto-paginate.
+
+ ## Query Parameters
+
+ * `before` — query parameter `before`
+
+ ## Returns
+
+ * `{:ok, %Req.Response{}}` on success
+ * `{:error, exception}` on HTTP or validation failure
+ """
+ @spec list_agents(keyword(), keyword()) :: response()
+ def list_agents(params \\ [], opts \\ []) do
+ with {:ok, params} <- NimbleOptions.validate(params, @list_agents_query_schema) do
+ Req.get(client(opts), url: "/agent", params: to_query(params, @list_agents_query_key_mapping))
+ end
+ end
+
+
+ @doc """
+ Bang variant of `list_agents`. Raises on error.
+ """
+ @spec list_agents!(keyword(), keyword()) :: Req.Response.t()
+ def list_agents!(params \\ [], opts \\ []) do
+ params = NimbleOptions.validate!(params, @list_agents_query_schema)
+ Req.get!(client(opts), url: "/agent", params: to_query(params, @list_agents_query_key_mapping))
+ end
+
+
@list_browser_sessions_query_schema NimbleOptions.new!([
status: [type: {:in, [:active, :destroyed]}, doc: "Filter sessions by status"]
])
diff --git a/apps/elixir-sdk/test/firecrawl_test.exs b/apps/elixir-sdk/test/firecrawl_test.exs
index 5a00e53d0..68db83368 100644
--- a/apps/elixir-sdk/test/firecrawl_test.exs
+++ b/apps/elixir-sdk/test/firecrawl_test.exs
@@ -279,6 +279,89 @@ defmodule FirecrawlTest do
Firecrawl.get_agent_trace!("job-123", api_key: "test-key", adapter: adapter)
end
+ test "list_agents hits /v2/agent" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body:
+ Jason.encode!(%{
+ "success" => true,
+ "agents" => [
+ %{
+ "id" => "job-123",
+ "createdAt" => "2026-08-31T12:00:00.000Z",
+ "targetHint" => "https://example.com",
+ "origin" => "api",
+ "settings" => %{"hidden" => false, "starred" => true, "label" => "prod"},
+ "status" => "completed",
+ "options" => %{"urls" => ["https://example.com"], "prompt" => "find pricing", "model" => "spark-1-pro"}
+ }
+ ]
+ })
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200} = response} =
+ Firecrawl.list_agents([], api_key: "test-key", adapter: adapter)
+
+ assert_receive {:request, request}
+ assert request.url.path == "/v2/agent"
+ refute Map.has_key?(URI.decode_query(request.url.query || ""), "before")
+
+ body = Jason.decode!(response.body)
+ assert [%{"id" => "job-123", "status" => "completed"}] = body["agents"]
+ end
+
+ test "list_agents sends before query param" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body:
+ Jason.encode!(%{
+ "success" => true,
+ "agents" => [],
+ "next" => "https://api.firecrawl.dev/v2/agent?before=1756600000000"
+ })
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200}} =
+ Firecrawl.list_agents([before: 1_756_600_000_000], api_key: "test-key", adapter: adapter)
+
+ assert_receive {:request, request}
+ assert request.url.path == "/v2/agent"
+ assert URI.decode_query(request.url.query || "")["before"] == "1756600000000"
+ end
+
+ test "list_agents! returns the response on success" do
+ adapter = fn request ->
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body: Jason.encode!(%{"success" => true, "agents" => []})
+ )
+
+ {request, resp}
+ end
+
+ assert %Req.Response{status: 200} =
+ Firecrawl.list_agents!([], api_key: "test-key", adapter: adapter)
+ end
+
test "get_agent_snapshot hits /v2/agent/:id/snapshots/:snapshot_id" do
parent = self()
@@ -614,7 +697,13 @@ defmodule FirecrawlTest do
{:get_agent_trace, 2},
{:get_agent_trace!, 2},
{:get_agent_snapshot, 3},
- {:get_agent_snapshot!, 3}
+ {:get_agent_snapshot!, 3},
+ {:list_agents, 0},
+ {:list_agents, 1},
+ {:list_agents, 2},
+ {:list_agents!, 0},
+ {:list_agents!, 1},
+ {:list_agents!, 2}
]
for {name, arity} <- expected do
diff --git a/apps/go-sdk/agent_test.go b/apps/go-sdk/agent_test.go
index 8bf3a4581..39257fc55 100644
--- a/apps/go-sdk/agent_test.go
+++ b/apps/go-sdk/agent_test.go
@@ -339,3 +339,102 @@ func TestGetAgentSnapshotRequiresIDs(t *testing.T) {
t.Fatalf("expected error for empty snapshot ID")
}
}
+
+func TestListAgentsParsesResponse(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "agents": [{
+ "id": "018f3c5e-0000-7000-8000-000000000000",
+ "createdAt": "2026-08-31T12:00:00.000Z",
+ "targetHint": "https://example.com",
+ "origin": "api",
+ "settings": {"hidden": false, "starred": true, "label": "prod"},
+ "status": "completed",
+ "options": {"urls": ["https://example.com"], "prompt": "find pricing", "model": "spark-1-pro"}
+ }]
+ }`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ resp, err := client.ListAgents(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("ListAgents: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodGet || req.path != "/v2/agent" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if req.query != "" {
+ t.Errorf("query = %q, want empty", req.query)
+ }
+ if len(resp.Agents) != 1 {
+ t.Fatalf("agents = %+v", resp.Agents)
+ }
+ agent := resp.Agents[0]
+ if agent.ID != "018f3c5e-0000-7000-8000-000000000000" || agent.Status != "completed" {
+ t.Errorf("agent = %+v", agent)
+ }
+ if !agent.Settings.Starred || agent.Settings.Label != "prod" {
+ t.Errorf("settings = %+v", agent.Settings)
+ }
+ if agent.Options == nil || agent.Options.Prompt != "find pricing" {
+ t.Errorf("options = %+v", agent.Options)
+ }
+ if resp.Next != "" {
+ t.Errorf("next = %q, want empty", resp.Next)
+ }
+}
+
+func TestListAgentsSendsBefore(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"success":true,"agents":[],"next":"https://api.firecrawl.dev/v2/agent?before=1756600000000"}`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ before := int64(1756600000000)
+ resp, err := client.ListAgents(context.Background(), &ListAgentsOptions{Before: &before})
+ if err != nil {
+ t.Fatalf("ListAgents: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodGet || req.path != "/v2/agent" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if req.query != "before=1756600000000" {
+ t.Errorf("query = %q, want before=1756600000000", req.query)
+ }
+ if resp.Next != "https://api.firecrawl.dev/v2/agent?before=1756600000000" {
+ t.Errorf("next = %q", resp.Next)
+ }
+}
diff --git a/apps/go-sdk/firecrawl.go b/apps/go-sdk/firecrawl.go
index 5eba69099..b6dda544b 100644
--- a/apps/go-sdk/firecrawl.go
+++ b/apps/go-sdk/firecrawl.go
@@ -733,6 +733,34 @@ func (c *Client) GetAgentStatus(ctx context.Context, jobID string) (*AgentStatus
return &resp, nil
}
+// ListAgents lists agent runs, most recent first.
+//
+// Pages are fixed at 20 runs. To fetch the next page, pass the before value
+// from the previous page's Next URL via ListAgentsOptions. This method does
+// not auto-paginate.
+func (c *Client) ListAgents(ctx context.Context, opts *ListAgentsOptions) (*AgentListResponse, error) {
+ values := url.Values{}
+ if opts != nil && opts.Before != nil {
+ values.Set("before", fmt.Sprint(*opts.Before))
+ }
+
+ path := "/v2/agent"
+ if encoded := values.Encode(); encoded != "" {
+ path += "?" + encoded
+ }
+
+ raw, err := c.http.get(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+
+ var resp AgentListResponse
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return nil, &FirecrawlError{Message: fmt.Sprintf("failed to decode response: %v", err)}
+ }
+ return &resp, nil
+}
+
// Agent runs an agent task and waits for completion with auto-polling.
func (c *Client) Agent(ctx context.Context, opts *AgentOptions) (*AgentStatusResponse, error) {
return c.AgentWithPolling(ctx, opts, defaultPollInterval, defaultJobTimeout)
diff --git a/apps/go-sdk/models.go b/apps/go-sdk/models.go
index 49b853cc7..b1fc5dee8 100644
--- a/apps/go-sdk/models.go
+++ b/apps/go-sdk/models.go
@@ -721,6 +721,52 @@ type AgentSnapshotResponse struct {
Error string `json:"error,omitempty"`
}
+// ListAgentsOptions controls agent list pagination.
+type ListAgentsOptions struct {
+ // Before only returns agent runs created before this unix millisecond
+ // timestamp.
+ Before *int64
+}
+
+// AgentListItemSettings represents per-session settings attached to an agent
+// run.
+type AgentListItemSettings struct {
+ Hidden bool `json:"hidden"`
+ Starred bool `json:"starred"`
+ Label string `json:"label,omitempty"`
+}
+
+// AgentListItemOptions represents the options an agent run was started with.
+type AgentListItemOptions struct {
+ URLs []string `json:"urls,omitempty"`
+ Prompt string `json:"prompt,omitempty"`
+ Schema map[string]interface{} `json:"schema,omitempty"`
+ Model string `json:"model,omitempty"`
+ Effort string `json:"effort,omitempty"`
+}
+
+// AgentListItem represents a single agent run in the agent list.
+type AgentListItem struct {
+ ID string `json:"id"`
+ CreatedAt string `json:"createdAt"`
+ TargetHint string `json:"targetHint"`
+ Origin string `json:"origin"`
+ Integration string `json:"integration,omitempty"`
+ Settings AgentListItemSettings `json:"settings"`
+ Status string `json:"status"`
+ Options *AgentListItemOptions `json:"options,omitempty"`
+}
+
+// AgentListResponse is returned when listing agent runs.
+type AgentListResponse struct {
+ Success bool `json:"success"`
+ Agents []AgentListItem `json:"agents,omitempty"`
+ // Next is the absolute URL of the next page, only present when more pages
+ // exist.
+ Next string `json:"next,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
// BrowserCreateResponse is returned when creating a browser session.
type BrowserCreateResponse struct {
Success bool `json:"success"`
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
index 5e11711e1..a1c80885b 100644
--- a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
+++ b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
@@ -641,6 +641,34 @@ public class FirecrawlClient {
return http.get("/v2/agent/" + jobId, AgentStatusResponse.class);
}
+ /**
+ * Lists agent runs, most recent first.
+ *
+ * @return the agent list response
+ */
+ public AgentListResponse listAgents() {
+ return listAgents(null);
+ }
+
+ /**
+ * Lists agent runs, most recent first.
+ *
+ * Pages are fixed at 20 runs. To fetch the next page, pass the before
+ * value from the previous page's next URL. This method does not
+ * auto-paginate.
+ *
+ * @param before only return agent runs created before this unix
+ * millisecond timestamp (nullable)
+ * @return the agent list response
+ */
+ public AgentListResponse listAgents(Long before) {
+ String endpoint = "/v2/agent";
+ if (before != null) {
+ endpoint += "?before=" + before;
+ }
+ return http.get(endpoint, AgentListResponse.class);
+ }
+
/**
* Runs an agent task and waits for completion (auto-polling).
*
@@ -1226,6 +1254,17 @@ public class FirecrawlClient {
return CompletableFuture.supplyAsync(() -> getAgentStatus(jobId), asyncExecutor);
}
+ /**
+ * Asynchronously lists agent runs, most recent first.
+ *
+ * @param before only return agent runs created before this unix
+ * millisecond timestamp (nullable)
+ * @return a CompletableFuture that resolves to the AgentListResponse
+ */
+ public CompletableFuture<AgentListResponse> listAgentsAsync(Long before) {
+ return CompletableFuture.supplyAsync(() -> listAgents(before), asyncExecutor);
+ }
+
/**
* Asynchronously cancels an agent task.
*
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItem.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItem.java
new file mode 100644
index 000000000..7afc2860a
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItem.java
@@ -0,0 +1,33 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * A single agent run as returned by the agent list endpoint.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentListItem {
+
+ private String id;
+ private String createdAt;
+ private String targetHint;
+ private String origin;
+ private String integration;
+ private AgentListItemSettings settings;
+ private String status;
+ private AgentListItemOptions options;
+
+ public String getId() { return id; }
+ public String getCreatedAt() { return createdAt; }
+ public String getTargetHint() { return targetHint; }
+ public String getOrigin() { return origin; }
+ public String getIntegration() { return integration; }
+ public AgentListItemSettings getSettings() { return settings; }
+ public String getStatus() { return status; }
+ public AgentListItemOptions getOptions() { return options; }
+
+ @Override
+ public String toString() {
+ return "AgentListItem{id=" + id + ", status=" + status + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemOptions.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemOptions.java
new file mode 100644
index 000000000..866ceccf1
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemOptions.java
@@ -0,0 +1,29 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.List;
+
+/**
+ * Options an agent run was started with.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentListItemOptions {
+
+ private List<String> urls;
+ private String prompt;
+ private Object schema;
+ private String model;
+ private String effort;
+
+ public List<String> getUrls() { return urls; }
+ public String getPrompt() { return prompt; }
+ public Object getSchema() { return schema; }
+ public String getModel() { return model; }
+ /** The effort the run used; only present for runs that specified one. */
+ public String getEffort() { return effort; }
+
+ @Override
+ public String toString() {
+ return "AgentListItemOptions{prompt=" + prompt + ", model=" + model + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemSettings.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemSettings.java
new file mode 100644
index 000000000..3a0a08bad
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListItemSettings.java
@@ -0,0 +1,23 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Per-session settings attached to an agent run.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentListItemSettings {
+
+ private boolean hidden;
+ private boolean starred;
+ private String label;
+
+ public boolean isHidden() { return hidden; }
+ public boolean isStarred() { return starred; }
+ public String getLabel() { return label; }
+
+ @Override
+ public String toString() {
+ return "AgentListItemSettings{hidden=" + hidden + ", starred=" + starred + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListResponse.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListResponse.java
new file mode 100644
index 000000000..11f3dbae1
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentListResponse.java
@@ -0,0 +1,28 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.List;
+
+/**
+ * Response from listing agent runs.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentListResponse {
+
+ private boolean success;
+ private List<AgentListItem> agents;
+ /** Absolute URL of the next page; only present when more pages exist. */
+ private String next;
+ private String error;
+
+ public boolean isSuccess() { return success; }
+ public List<AgentListItem> getAgents() { return agents; }
+ public String getNext() { return next; }
+ public String getError() { return error; }
+
+ @Override
+ public String toString() {
+ int count = agents != null ? agents.size() : 0;
+ return "AgentListResponse{success=" + success + ", agents=" + count + "}";
+ }
+}
diff --git a/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java b/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java
index a5c2d201b..8dca838b1 100644
--- a/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java
+++ b/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java
@@ -1,6 +1,8 @@
package com.firecrawl;
import com.firecrawl.client.FirecrawlClient;
+import com.firecrawl.models.AgentListItem;
+import com.firecrawl.models.AgentListResponse;
import com.firecrawl.models.AgentOptions;
import com.firecrawl.models.AgentResponse;
import com.firecrawl.models.AgentSnapshotResponse;
@@ -40,7 +42,22 @@ class AgentMockTest {
server.createContext("/v2/agent", exchange -> {
lastRequestPath.set(exchange.getRequestURI().toString());
lastRequestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
- respond(exchange, 200, "{\"success\":true,\"id\":\"job-123\"}");
+ if ("GET".equals(exchange.getRequestMethod())) {
+ respond(exchange, 200, "{"
+ + "\"success\":true,"
+ + "\"agents\":[{"
+ + " \"id\":\"job-123\","
+ + " \"createdAt\":\"2026-08-31T12:00:00.000Z\","
+ + " \"targetHint\":\"https://example.com\","
+ + " \"origin\":\"api\","
+ + " \"settings\":{\"hidden\":false,\"starred\":true,\"label\":\"prod\"},"
+ + " \"status\":\"completed\","
+ + " \"options\":{\"urls\":[\"https://example.com\"],\"prompt\":\"find pricing\",\"model\":\"spark-1-pro\"}"
+ + "}]"
+ + "}");
+ } else {
+ respond(exchange, 200, "{\"success\":true,\"id\":\"job-123\"}");
+ }
});
server.createContext("/v2/agent/job-123/trace", exchange -> {
@@ -198,4 +215,39 @@ class AgentMockTest {
assertEquals("snapshot content here", snapshot.getSnapshot());
assertNull(snapshot.getError());
}
+
+ @Test
+ void testListAgents() {
+ AgentListResponse response = client.listAgents();
+
+ assertEquals("/v2/agent", lastRequestPath.get(),
+ "Should not send a query string by default");
+ assertTrue(response.isSuccess());
+ assertNull(response.getNext());
+ assertNotNull(response.getAgents());
+ assertEquals(1, response.getAgents().size());
+
+ AgentListItem agent = response.getAgents().get(0);
+ assertEquals("job-123", agent.getId());
+ assertEquals("2026-08-31T12:00:00.000Z", agent.getCreatedAt());
+ assertEquals("https://example.com", agent.getTargetHint());
+ assertEquals("api", agent.getOrigin());
+ assertEquals("completed", agent.getStatus());
+ assertNotNull(agent.getSettings());
+ assertFalse(agent.getSettings().isHidden());
+ assertTrue(agent.getSettings().isStarred());
+ assertEquals("prod", agent.getSettings().getLabel());
+ assertNotNull(agent.getOptions());
+ assertEquals("find pricing", agent.getOptions().getPrompt());
+ assertEquals("spark-1-pro", agent.getOptions().getModel());
+ }
+
+ @Test
+ void testListAgentsSendsBefore() {
+ AgentListResponse response = client.listAgents(1756600000000L);
+
+ assertEquals("/v2/agent?before=1756600000000", lastRequestPath.get(),
+ "Should append before query param");
+ assertTrue(response.isSuccess());
+ }
}
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-list.unit.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-list.unit.test.ts
new file mode 100644
index 000000000..f4a1c4034
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-list.unit.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, jest, test } from "@jest/globals";
+import { listAgents } from "../../../v2/methods/agent";
+
+describe("v2.agent listAgents unit", () => {
+ const sampleAgent = {
+ id: "018f3c5e-0000-7000-8000-000000000000",
+ createdAt: "2026-08-31T12:00:00.000Z",
+ targetHint: "https://example.com",
+ origin: "api",
+ settings: { hidden: false, starred: false },
+ status: "completed",
+ options: {
+ urls: ["https://example.com"],
+ prompt: "Find the pricing",
+ model: "spark-1-pro",
+ },
+ };
+
+ test("hits GET /v2/agent without query by default", async () => {
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: { success: true, agents: [sampleAgent] },
+ });
+
+ const res = await listAgents({ get } as any);
+
+ expect(get).toHaveBeenCalledWith("/v2/agent");
+ expect(res.success).toBe(true);
+ expect(res.agents).toHaveLength(1);
+ expect(res.agents![0].id).toBe(sampleAgent.id);
+ expect(res.agents![0].settings.starred).toBe(false);
+ expect(res.next).toBeUndefined();
+ });
+
+ test("passes before as a query param", async () => {
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ agents: [sampleAgent],
+ next: "https://api.firecrawl.dev/v2/agent?before=1756600000000",
+ },
+ });
+
+ const res = await listAgents({ get } as any, { before: 1756600000000 });
+
+ expect(get).toHaveBeenCalledWith("/v2/agent?before=1756600000000");
+ expect(res.next).toBe(
+ "https://api.firecrawl.dev/v2/agent?before=1756600000000",
+ );
+ });
+
+ test("does not auto-paginate when next is present", async () => {
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ agents: [sampleAgent],
+ next: "https://api.firecrawl.dev/v2/agent?before=1756600000000",
+ },
+ });
+
+ const res = await listAgents({ get } as any);
+
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(res.agents).toHaveLength(1);
+ });
+});
diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.ts
index a5993a21e..ede04d4ac 100644
--- a/apps/js-sdk/firecrawl/src/v2/client.ts
+++ b/apps/js-sdk/firecrawl/src/v2/client.ts
@@ -26,7 +26,7 @@ import {
batchScrape as batchWaiter,
} from "./methods/batch";
import { startExtract, getExtractStatus, extract as extractWaiter } from "./methods/extract";
-import { startAgent, getAgentStatus, getAgentTrace, getAgentSnapshot, cancelAgent, agent as agentWaiter } from "./methods/agent";
+import { startAgent, getAgentStatus, getAgentTrace, getAgentSnapshot, cancelAgent, listAgents, agent as agentWaiter } from "./methods/agent";
import {
browser as browserMethod,
browserExecute,
@@ -70,6 +70,8 @@ import type {
AgentStatusResponse,
AgentTraceResponse,
AgentSnapshotResponse,
+ AgentListOptions,
+ AgentListResponse,
CrawlOptions,
BatchScrapeOptions,
PaginationConfig,
@@ -521,6 +523,17 @@ export class FirecrawlClient {
async getAgentStatus(jobId: string): Promise<AgentStatusResponse> {
return getAgentStatus(this.http, jobId);
}
+ /**
+ * List agent runs, most recent first.
+ *
+ * Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ * value from the previous page's `next` URL. This method does not
+ * auto-paginate.
+ * @param options.before Only return runs created before this unix ms timestamp.
+ */
+ async listAgents(options?: AgentListOptions): Promise<AgentListResponse> {
+ return listAgents(this.http, options);
+ }
/**
* Convenience waiter: start an agent and poll until it finishes.
* @param args Agent request plus waiter controls (pollInterval, timeout seconds).
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/agent.ts b/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
index 1a2a116b7..46765e45e 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
@@ -1,4 +1,4 @@
-import { type AgentEffort, type AgentResponse, type AgentSnapshotResponse, type AgentStatusResponse, type AgentTraceResponse, type AgentWebhookConfig, type AuditMetadata, type ThreatProtectionOptions } from "../types";
+import { type AgentEffort, type AgentListOptions, type AgentListResponse, type AgentResponse, type AgentSnapshotResponse, type AgentStatusResponse, type AgentTraceResponse, type AgentWebhookConfig, type AuditMetadata, type ThreatProtectionOptions } from "../types";
import { HttpClient } from "../utils/httpClient";
import { normalizeAxiosError, throwForBadResponse } from "../utils/errorHandler";
import { isZodSchema, zodSchemaToJsonSchema } from "../../utils/zodSchemaToJson";
@@ -61,6 +61,18 @@ export async function getAgentStatus(http: HttpClient, jobId: string): Promise<A
}
}
+export async function listAgents(http: HttpClient, options?: AgentListOptions): Promise<AgentListResponse> {
+ try {
+ const query = options?.before !== undefined ? `?before=${options.before}` : "";
+ const res = await http.get<AgentListResponse>(`/v2/agent${query}`);
+ if (res.status !== 200) throwForBadResponse(res, "list agents");
+ return res.data;
+ } catch (err: any) {
+ if (err?.isAxiosError) return normalizeAxiosError(err, "list agents");
+ throw err;
+ }
+}
+
export async function waitAgent(
http: HttpClient,
jobId: string,
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index 65a76f896..d36ef7866 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -1340,6 +1340,50 @@ export interface AgentStatusResponse {
/** Reasoning effort for agent jobs. Every level runs spark-2. */
export type AgentEffort = "low" | "medium" | "high";
+/** A single agent run as returned by the agent list endpoint. */
+export interface AgentListItem {
+ id: string;
+ createdAt: string;
+ targetHint: string;
+ origin: string;
+ integration?: string;
+ settings: {
+ hidden: boolean;
+ starred: boolean;
+ label?: string;
+ };
+ status: "processing" | "completed" | "failed";
+ options?: {
+ urls?: string[];
+ prompt: string;
+ schema?: unknown;
+ /**
+ * Server-provided model name. Widened past the request-side union on
+ * purpose: new models ship without an SDK release, so pinning this to
+ * known names makes every future model a type error at the call site.
+ */
+ model: "spark-1-pro" | "spark-1-mini" | "spark-2" | (string & {});
+ effort?: AgentEffort;
+ };
+}
+
+export interface AgentListResponse {
+ success: boolean;
+ agents?: AgentListItem[];
+ /**
+ * Absolute URL of the next page (pass its `before` value to listAgents to
+ * continue). Only present when more pages exist.
+ */
+ next?: string;
+ error?: string;
+}
+
+/** Options for listing agent runs. */
+export interface AgentListOptions {
+ /** Only return agent runs created before this unix millisecond timestamp. */
+ before?: number;
+}
+
export type AgentTraceAgentRole = "orchestrator" | "subagent" | "browser" | "system";
export interface AgentTraceAgentIdentity {
diff --git a/apps/php-sdk/src/Client/FirecrawlClient.php b/apps/php-sdk/src/Client/FirecrawlClient.php
index c03d77e18..36a82a9b7 100644
--- a/apps/php-sdk/src/Client/FirecrawlClient.php
+++ b/apps/php-sdk/src/Client/FirecrawlClient.php
@@ -7,6 +7,7 @@ namespace Firecrawl\Client;
use Firecrawl\Exceptions\FirecrawlException;
use Firecrawl\Version;
use Firecrawl\Exceptions\JobTimeoutException;
+use Firecrawl\Models\AgentListResponse;
use Firecrawl\Models\AgentOptions;
use Firecrawl\Models\AgentResponse;
use Firecrawl\Models\AgentSnapshotResponse;
@@ -660,6 +661,23 @@ final class FirecrawlClient
);
}
+ /**
+ * List agent runs, most recent first.
+ *
+ * Pages are fixed at 20 runs. To fetch the next page, pass the before
+ * value from the previous page's next URL. This method does not
+ * auto-paginate.
+ *
+ * @param int|null $before Only return agent runs created before this unix
+ * millisecond timestamp.
+ */
+ public function listAgents(?int $before = null): AgentListResponse
+ {
+ return AgentListResponse::fromArray(
+ $this->http->get('/v2/agent' . $this->query(['before' => $before])),
+ );
+ }
+
// ================================================================
// BROWSER
// ================================================================
diff --git a/apps/php-sdk/src/Laravel/Facades/Firecrawl.php b/apps/php-sdk/src/Laravel/Facades/Firecrawl.php
index dd5963d6e..f4cdc7142 100644
--- a/apps/php-sdk/src/Laravel/Facades/Firecrawl.php
+++ b/apps/php-sdk/src/Laravel/Facades/Firecrawl.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Firecrawl\Laravel\Facades;
use Firecrawl\Client\FirecrawlClient;
+use Firecrawl\Models\AgentListResponse;
use Firecrawl\Models\AgentOptions;
use Firecrawl\Models\AgentStatusResponse;
use Firecrawl\Models\BatchScrapeJob;
@@ -38,6 +39,7 @@ use Illuminate\Support\Facades\Facade;
* @method static SearchData search(string $query, ?SearchOptions $options = null)
* @method static AgentStatusResponse agent(AgentOptions $options, int $pollIntervalSec = 2, int $timeoutSec = 300)
* @method static array<string, mixed> cancelAgent(string $jobId)
+ * @method static AgentListResponse listAgents(?int $before = null)
* @method static BrowserCreateResponse browser(?int $ttl = null, ?int $activityTtl = null, ?bool $streamWebView = null)
* @method static BrowserExecuteResponse browserExecute(string $sessionId, string $code, string $language = 'bash', ?int $timeout = null)
* @method static BrowserDeleteResponse deleteBrowser(string $sessionId)
diff --git a/apps/php-sdk/src/Models/AgentListItem.php b/apps/php-sdk/src/Models/AgentListItem.php
new file mode 100644
index 000000000..21f7c623b
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentListItem.php
@@ -0,0 +1,83 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentListItem
+{
+ /**
+ * @param array{hidden?: bool, starred?: bool, label?: string|null} $settings
+ * @param array{urls?: list<string>, prompt?: string, schema?: mixed, model?: string, effort?: string}|null $options
+ */
+ public function __construct(
+ private readonly ?string $id = null,
+ private readonly ?string $createdAt = null,
+ private readonly ?string $targetHint = null,
+ private readonly ?string $origin = null,
+ private readonly ?string $integration = null,
+ private readonly array $settings = [],
+ private readonly ?string $status = null,
+ private readonly ?array $options = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ $settings = $data['settings'] ?? [];
+ $options = $data['options'] ?? null;
+
+ return new self(
+ id: $data['id'] ?? null,
+ createdAt: $data['createdAt'] ?? null,
+ targetHint: $data['targetHint'] ?? null,
+ origin: $data['origin'] ?? null,
+ integration: $data['integration'] ?? null,
+ settings: is_array($settings) ? $settings : [],
+ status: $data['status'] ?? null,
+ options: is_array($options) ? $options : null,
+ );
+ }
+
+ public function getId(): ?string
+ {
+ return $this->id;
+ }
+
+ public function getCreatedAt(): ?string
+ {
+ return $this->createdAt;
+ }
+
+ public function getTargetHint(): ?string
+ {
+ return $this->targetHint;
+ }
+
+ public function getOrigin(): ?string
+ {
+ return $this->origin;
+ }
+
+ public function getIntegration(): ?string
+ {
+ return $this->integration;
+ }
+
+ /** @return array{hidden?: bool, starred?: bool, label?: string|null} */
+ public function getSettings(): array
+ {
+ return $this->settings;
+ }
+
+ public function getStatus(): ?string
+ {
+ return $this->status;
+ }
+
+ /** @return array{urls?: list<string>, prompt?: string, schema?: mixed, model?: string, effort?: string}|null */
+ public function getOptions(): ?array
+ {
+ return $this->options;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentListResponse.php b/apps/php-sdk/src/Models/AgentListResponse.php
new file mode 100644
index 000000000..672bb1e70
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentListResponse.php
@@ -0,0 +1,61 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentListResponse
+{
+ /**
+ * @param list<AgentListItem> $agents
+ */
+ public function __construct(
+ private readonly bool $success = false,
+ private readonly array $agents = [],
+ private readonly ?string $next = null,
+ private readonly ?string $error = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ $agents = [];
+ $rawAgents = $data['agents'] ?? [];
+ if (is_array($rawAgents)) {
+ foreach ($rawAgents as $agent) {
+ $agents[] = AgentListItem::fromArray($agent);
+ }
+ }
+
+ return new self(
+ success: (bool) ($data['success'] ?? false),
+ agents: $agents,
+ next: $data['next'] ?? null,
+ error: $data['error'] ?? null,
+ );
+ }
+
+ public function isSuccess(): bool
+ {
+ return $this->success;
+ }
+
+ /** @return list<AgentListItem> */
+ public function getAgents(): array
+ {
+ return $this->agents;
+ }
+
+ /**
+ * Absolute URL of the next page; only present when more pages exist.
+ */
+ public function getNext(): ?string
+ {
+ return $this->next;
+ }
+
+ public function getError(): ?string
+ {
+ return $this->error;
+ }
+}
diff --git a/apps/php-sdk/tests/Unit/AgentTest.php b/apps/php-sdk/tests/Unit/AgentTest.php
index 6fb29798a..1c587fea8 100644
--- a/apps/php-sdk/tests/Unit/AgentTest.php
+++ b/apps/php-sdk/tests/Unit/AgentTest.php
@@ -255,3 +255,75 @@ it('surfaces agent snapshot errors', function (): void {
$client->getAgentSnapshot('agent-missing', 'snap-1');
})->throws(FirecrawlException::class, 'Agent job not found');
+
+it('lists agent runs without a query param by default', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode([
+ 'success' => true,
+ 'agents' => [[
+ 'id' => 'agent-123',
+ 'createdAt' => '2026-08-31T12:00:00.000Z',
+ 'targetHint' => 'https://example.com',
+ 'origin' => 'api',
+ 'settings' => ['hidden' => false, 'starred' => true, 'label' => 'prod'],
+ 'status' => 'completed',
+ 'options' => [
+ 'urls' => ['https://example.com'],
+ 'prompt' => 'find pricing',
+ 'model' => 'spark-1-pro',
+ ],
+ ]],
+ ])),
+ ], $history);
+
+ $response = $client->listAgents();
+
+ $request = $history[0]['request'];
+ expect($request->getMethod())->toBe('GET');
+ expect($request->getUri()->getPath())->toBe('/v2/agent');
+ expect($request->getUri()->getQuery())->toBe('');
+
+ expect($response->isSuccess())->toBeTrue();
+ expect($response->getNext())->toBeNull();
+ expect($response->getAgents())->toHaveCount(1);
+
+ $agent = $response->getAgents()[0];
+ expect($agent->getId())->toBe('agent-123');
+ expect($agent->getCreatedAt())->toBe('2026-08-31T12:00:00.000Z');
+ expect($agent->getTargetHint())->toBe('https://example.com');
+ expect($agent->getStatus())->toBe('completed');
+ expect($agent->getSettings()['starred'])->toBeTrue();
+ expect($agent->getSettings()['label'])->toBe('prod');
+ expect($agent->getOptions()['prompt'])->toBe('find pricing');
+});
+
+it('sends the before query param when listing agent runs', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode([
+ 'success' => true,
+ 'agents' => [],
+ 'next' => 'https://api.firecrawl.dev/v2/agent?before=1756600000000',
+ ])),
+ ], $history);
+
+ $response = $client->listAgents(1756600000000);
+
+ $request = $history[0]['request'];
+ expect($request->getMethod())->toBe('GET');
+ expect($request->getUri()->getPath())->toBe('/v2/agent');
+ expect($request->getUri()->getQuery())->toBe('before=1756600000000');
+ expect($response->getNext())->toBe('https://api.firecrawl.dev/v2/agent?before=1756600000000');
+});
+
+it('surfaces agent list errors', function (): void {
+ $client = fakeFirecrawlClient([
+ new Response(400, [], json_encode([
+ 'success' => false,
+ 'error' => 'Invalid before timestamp.',
+ ])),
+ ]);
+
+ $client->listAgents(-1);
+})->throws(FirecrawlException::class, 'Invalid before timestamp.');
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent.py
index b40a4b95f..d97b37c2a 100644
--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent.py
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent.py
@@ -13,9 +13,10 @@ from firecrawl.v2.methods.agent import (
agent,
get_agent_status,
cancel_agent,
+ list_agents,
wait_agent
)
-from firecrawl.v2.types import AgentResponse
+from firecrawl.v2.types import AgentListResponse, AgentResponse
from firecrawl.v2.utils.error_handler import BadRequestError
@@ -217,17 +218,74 @@ class TestAgentMethods:
mock_response = Mock()
mock_response.ok = True
mock_response.json.return_value = {"success": True}
-
+
self.mock_client.delete.return_value = mock_response
-
+
result = cancel_agent(self.mock_client, self.job_id)
-
+
# Check that delete was called with correct endpoint
self.mock_client.delete.assert_called_once_with(f"/v2/agent/{self.job_id}")
-
+
# Check result
assert result is True
+ def test_list_agents(self):
+ """Test listing agent runs without a before param."""
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "agents": [
+ {
+ "id": "agent-1",
+ "createdAt": "2026-08-31T12:00:00.000Z",
+ "targetHint": "https://example.com",
+ "origin": "api",
+ "settings": {"hidden": False, "starred": True, "label": "prod"},
+ "status": "completed",
+ "options": {
+ "urls": ["https://example.com"],
+ "prompt": "Find the pricing",
+ "model": "spark-1-pro",
+ },
+ }
+ ],
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ result = list_agents(self.mock_client)
+
+ self.mock_client.get.assert_called_once_with("/v2/agent")
+
+ assert isinstance(result, AgentListResponse)
+ assert result.success is True
+ assert len(result.agents) == 1
+ assert result.agents[0].id == "agent-1"
+ assert result.agents[0].created_at == "2026-08-31T12:00:00.000Z"
+ assert result.agents[0].target_hint == "https://example.com"
+ assert result.agents[0].settings.starred is True
+ assert result.agents[0].settings.label == "prod"
+ assert result.agents[0].options.prompt == "Find the pricing"
+ assert result.next is None
+
+ def test_list_agents_with_before(self):
+ """Test listing agent runs passes before as a query param."""
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "agents": [],
+ "next": "https://api.firecrawl.dev/v2/agent?before=1756600000000",
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ result = list_agents(self.mock_client, before=1756600000000)
+
+ self.mock_client.get.assert_called_once_with("/v2/agent?before=1756600000000")
+ assert result.next == "https://api.firecrawl.dev/v2/agent?before=1756600000000"
+
@patch('time.sleep')
def test_wait_agent_completed(self, mock_sleep):
"""Test waiting for agent to complete."""
diff --git a/apps/python-sdk/firecrawl/client.py b/apps/python-sdk/firecrawl/client.py
index 42b16ce2d..7574c518f 100644
--- a/apps/python-sdk/firecrawl/client.py
+++ b/apps/python-sdk/firecrawl/client.py
@@ -97,6 +97,7 @@ class V2Proxy:
self.start_agent = client_instance.start_agent
self.get_agent_status = client_instance.get_agent_status
self.cancel_agent = client_instance.cancel_agent
+ self.list_agents = client_instance.list_agents
self.get_agent_trace = client_instance.get_agent_trace
self.get_agent_snapshot = client_instance.get_agent_snapshot
@@ -187,6 +188,7 @@ class AsyncV2Proxy:
self.start_agent = client_instance.start_agent
self.get_agent_status = client_instance.get_agent_status
self.cancel_agent = client_instance.cancel_agent
+ self.list_agents = client_instance.list_agents
self.get_agent_trace = client_instance.get_agent_trace
self.get_agent_snapshot = client_instance.get_agent_snapshot
@@ -311,6 +313,7 @@ class Firecrawl:
self.start_agent = self._v2_client.start_agent
self.get_agent_status = self._v2_client.get_agent_status
self.cancel_agent = self._v2_client.cancel_agent
+ self.list_agents = self._v2_client.list_agents
self.get_agent_trace = self._v2_client.get_agent_trace
self.get_agent_snapshot = self._v2_client.get_agent_snapshot
self.agent = self._v2_client.agent
@@ -448,6 +451,7 @@ class AsyncFirecrawl:
self.start_agent = self._v2_client.start_agent
self.get_agent_status = self._v2_client.get_agent_status
self.cancel_agent = self._v2_client.cancel_agent
+ self.list_agents = self._v2_client.list_agents
self.get_agent_trace = self._v2_client.get_agent_trace
self.get_agent_snapshot = self._v2_client.get_agent_snapshot
self.agent = self._v2_client.agent
diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.py
index b7d47ebc6..700e63e71 100644
--- a/apps/python-sdk/firecrawl/v2/client.py
+++ b/apps/python-sdk/firecrawl/v2/client.py
@@ -1511,6 +1511,21 @@ class FirecrawlClient:
"""
return agent_module.cancel_agent(self.http_client, job_id)
+ def list_agents(self, *, before: Optional[int] = None):
+ """List agent runs, most recent first.
+
+ Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ value from the previous page's `next` URL. This method does not
+ auto-paginate.
+
+ Args:
+ before: Only return agent runs created before this unix ms timestamp
+
+ Returns:
+ AgentListResponse with the list of agent runs and optional next URL
+ """
+ return agent_module.list_agents(self.http_client, before=before)
+
def get_agent_trace(self, job_id: str, *, live_view: bool = False):
"""Get the execution trace of an agent job (spark-2 runs only).
diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.py
index ec1743a9b..6a73a9205 100644
--- a/apps/python-sdk/firecrawl/v2/client_async.py
+++ b/apps/python-sdk/firecrawl/v2/client_async.py
@@ -805,6 +805,21 @@ class AsyncFirecrawlClient:
"""
return await async_agent.cancel_agent(self.async_http_client, job_id)
+ async def list_agents(self, *, before: Optional[int] = None):
+ """List agent runs, most recent first.
+
+ Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ value from the previous page's `next` URL. This method does not
+ auto-paginate.
+
+ Args:
+ before: Only return agent runs created before this unix ms timestamp
+
+ Returns:
+ AgentListResponse with the list of agent runs and optional next URL
+ """
+ return await async_agent.list_agents(self.async_http_client, before=before)
+
async def get_agent_trace(self, job_id: str, *, live_view: bool = False):
"""Get the execution trace of an agent job (spark-2 runs only).
diff --git a/apps/python-sdk/firecrawl/v2/methods/agent.py b/apps/python-sdk/firecrawl/v2/methods/agent.py
index 06e21481d..a857e14fb 100644
--- a/apps/python-sdk/firecrawl/v2/methods/agent.py
+++ b/apps/python-sdk/firecrawl/v2/methods/agent.py
@@ -2,6 +2,7 @@ from typing import Any, Dict, List, Literal, Optional, Union
import time
from ..types import (
+ AgentListResponse,
AgentResponse,
AgentSnapshotResponse,
AgentTraceResponse,
@@ -117,6 +118,33 @@ def get_agent_status(client: HttpClient, job_id: str) -> AgentResponse:
return AgentResponse(**payload)
+def list_agents(
+ client: HttpClient,
+ *,
+ before: Optional[int] = None,
+) -> AgentListResponse:
+ """List agent runs, most recent first.
+
+ Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ value from the previous page's `next` URL. This method does not
+ auto-paginate.
+
+ Args:
+ client: HTTP client instance
+ before: Only return agent runs created before this unix ms timestamp
+
+ Returns:
+ AgentListResponse with the list of agent runs and optional next URL
+ """
+ endpoint = "/v2/agent"
+ if before is not None:
+ endpoint = f"{endpoint}?before={before}"
+ resp = client.get(endpoint)
+ if not resp.ok:
+ handle_response_error(resp, "list agents")
+ return AgentListResponse(**resp.json())
+
+
def wait_agent(
client: HttpClient,
job_id: str,
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/agent.py b/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
index 300b789b1..40015c2f4 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
@@ -2,6 +2,7 @@ from typing import Any, Dict, List, Literal, Optional, Union
import asyncio
from ...types import (
+ AgentListResponse,
AgentResponse,
AgentSnapshotResponse,
AgentTraceResponse,
@@ -117,6 +118,33 @@ async def get_agent_status(client: AsyncHttpClient, job_id: str) -> AgentRespons
return AgentResponse(**payload)
+async def list_agents(
+ client: AsyncHttpClient,
+ *,
+ before: Optional[int] = None,
+) -> AgentListResponse:
+ """List agent runs, most recent first.
+
+ Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ value from the previous page's `next` URL. This method does not
+ auto-paginate.
+
+ Args:
+ client: Async HTTP client instance
+ before: Only return agent runs created before this unix ms timestamp
+
+ Returns:
+ AgentListResponse with the list of agent runs and optional next URL
+ """
+ endpoint = "/v2/agent"
+ if before is not None:
+ endpoint = f"{endpoint}?before={before}"
+ resp = await client.get(endpoint)
+ if not resp.ok:
+ handle_response_error(resp, "list agents")
+ return AgentListResponse(**resp.json())
+
+
async def wait_agent(
client: AsyncHttpClient,
job_id: str,
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index b2ac2f5ca..922f45e6f 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -52,6 +52,10 @@ warnings.filterwarnings(
"ignore",
message='Field name "json" in "MonitorPageSnapshot" shadows an attribute in parent "BaseModel"',
)
+warnings.filterwarnings(
+ "ignore",
+ message='Field name "schema" in "AgentListItemOptions" shadows an attribute in parent "BaseModel"',
+)
T = TypeVar("T")
@@ -1463,6 +1467,55 @@ class AgentResponse(BaseModel):
credits_used: Optional[int] = None
+class AgentListItemSettings(BaseModel):
+ """Per-session settings attached to an agent run."""
+
+ model_config = {"populate_by_name": True}
+
+ hidden: bool = False
+ starred: bool = False
+ label: Optional[str] = None
+
+
+class AgentListItemOptions(BaseModel):
+ """Options an agent run was started with."""
+
+ model_config = {"populate_by_name": True}
+
+ urls: Optional[List[str]] = None
+ prompt: str = ""
+ schema: Optional[Any] = None
+ # Plain str, not a Literal: server-provided, and new models ship without an
+ # SDK release (see AgentResponse.model).
+ model: Optional[str] = None
+ effort: Optional[Literal["low", "medium", "high"]] = None
+
+
+class AgentListItem(BaseModel):
+ """A single agent run as returned by the agent list endpoint."""
+
+ model_config = {"populate_by_name": True}
+
+ id: str
+ created_at: str = Field(alias="createdAt")
+ target_hint: str = Field(alias="targetHint")
+ origin: str = "api"
+ integration: Optional[str] = None
+ settings: AgentListItemSettings = Field(default_factory=AgentListItemSettings)
+ status: Optional[Literal["processing", "completed", "failed"]] = None
+ options: Optional[AgentListItemOptions] = None
+
+
+class AgentListResponse(BaseModel):
+ """Response from GET /v2/agent (list agent runs)."""
+
+ success: Optional[bool] = None
+ agents: Optional[List[AgentListItem]] = None
+ # Absolute URL of the next page; only present when more pages exist.
+ next: Optional[str] = None
+ error: Optional[str] = None
+
+
# Agent trace types (GET /v2/agent/{job_id}/trace).
# These mirror the agent service's canonical event schema (schemaVersion 1):
# usage.recorded events are withheld server-side and agent.started carries no
diff --git a/apps/ruby-sdk/lib/firecrawl.rb b/apps/ruby-sdk/lib/firecrawl.rb
index ea9be7b6d..71a7fb7f7 100644
--- a/apps/ruby-sdk/lib/firecrawl.rb
+++ b/apps/ruby-sdk/lib/firecrawl.rb
@@ -24,6 +24,7 @@ require_relative "firecrawl/models/parse_file"
require_relative "firecrawl/models/parse_options"
require_relative "firecrawl/models/agent_options"
require_relative "firecrawl/models/agent_response"
+require_relative "firecrawl/models/agent_list_response"
require_relative "firecrawl/models/agent_status_response"
require_relative "firecrawl/models/agent_trace_response"
require_relative "firecrawl/models/agent_snapshot_response"
diff --git a/apps/ruby-sdk/lib/firecrawl/client.rb b/apps/ruby-sdk/lib/firecrawl/client.rb
index 9a8f012c9..9182ae013 100644
--- a/apps/ruby-sdk/lib/firecrawl/client.rb
+++ b/apps/ruby-sdk/lib/firecrawl/client.rb
@@ -463,6 +463,20 @@ module Firecrawl
Models::AgentStatusResponse.new(raw)
end
+ # Lists agent tasks, most recent first.
+ #
+ # Pages are fixed at 20 runs. To fetch the next page, pass the before
+ # value from the previous page's next URL. This method does not
+ # auto-paginate.
+ #
+ # @param before [Integer, nil] only return agent runs created before this
+ # unix millisecond timestamp
+ # @return [Models::AgentListResponse]
+ def list_agents(before: nil)
+ raw = @http.get("/v2/agent#{query(before: before)}")
+ Models::AgentListResponse.new(raw)
+ end
+
# Runs an agent task and waits for completion (auto-polling).
#
# @param options [Models::AgentOptions] agent configuration
diff --git a/apps/ruby-sdk/lib/firecrawl/models/agent_list_response.rb b/apps/ruby-sdk/lib/firecrawl/models/agent_list_response.rb
new file mode 100644
index 000000000..36531e54f
--- /dev/null
+++ b/apps/ruby-sdk/lib/firecrawl/models/agent_list_response.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Firecrawl
+ module Models
+ # Response from listing agent tasks.
+ class AgentListResponse
+ attr_reader :success, :agents, :next, :error
+
+ def initialize(raw)
+ @success = raw["success"]
+ @agents = raw["agents"]
+ @next = raw["next"]
+ @error = raw["error"]
+ end
+
+ def to_s
+ "AgentListResponse{success=#{success}, agents=#{agents&.size}}"
+ end
+ end
+ end
+end
diff --git a/apps/ruby-sdk/test/firecrawl/client_test.rb b/apps/ruby-sdk/test/firecrawl/client_test.rb
index a35717c72..dca97e9ed 100644
--- a/apps/ruby-sdk/test/firecrawl/client_test.rb
+++ b/apps/ruby-sdk/test/firecrawl/client_test.rb
@@ -725,6 +725,55 @@ class ClientTest < Minitest::Test
assert_equal "<html>snapshot</html>", snapshot.snapshot
end
+ def test_list_agents
+ stub_request(:get, "#{BASE_URL}/v2/agent")
+ .to_return(
+ status: 200,
+ body: JSON.generate(
+ success: true,
+ agents: [
+ {
+ id: "agent-123",
+ createdAt: "2026-08-31T12:00:00.000Z",
+ targetHint: "https://example.com",
+ origin: "api",
+ settings: { hidden: false, starred: true, label: "prod" },
+ status: "completed",
+ options: { urls: ["https://example.com"], prompt: "find pricing", model: "spark-1-pro" }
+ }
+ ]
+ ),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ response = @client.list_agents
+ assert_instance_of Firecrawl::Models::AgentListResponse, response
+ assert_equal true, response.success
+ assert_nil response.next
+ assert_equal 1, response.agents.size
+ assert_equal "agent-123", response.agents.first["id"]
+ assert_equal "completed", response.agents.first["status"]
+ assert_equal true, response.agents.first["settings"]["starred"]
+ end
+
+ def test_list_agents_with_before
+ stub_request(:get, "#{BASE_URL}/v2/agent")
+ .with(query: { before: "1756600000000" })
+ .to_return(
+ status: 200,
+ body: JSON.generate(
+ success: true,
+ agents: [],
+ next: "https://api.firecrawl.dev/v2/agent?before=1756600000000"
+ ),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ response = @client.list_agents(before: 1756600000000)
+ assert_equal true, response.success
+ assert_equal "https://api.firecrawl.dev/v2/agent?before=1756600000000", response.next
+ end
+
# ================================================================
# USAGE & METRICS
# ================================================================
diff --git a/apps/rust-sdk/src/agent.rs b/apps/rust-sdk/src/agent.rs
index c283a61d3..44965f942 100644
--- a/apps/rust-sdk/src/agent.rs
+++ b/apps/rust-sdk/src/agent.rs
@@ -106,6 +106,74 @@ pub struct AgentStatusResponse {
pub credits_used: Option<u32>,
}
+/// Per-session settings attached to an agent run.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListItemSettings {
+ /// Whether the run is hidden.
+ pub hidden: bool,
+ /// Whether the run is starred.
+ pub starred: bool,
+ /// User-assigned label for the run.
+ pub label: Option<String>,
+}
+
+/// Options an agent run was started with.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListItemOptions {
+ /// URLs the agent was constrained to.
+ pub urls: Option<Vec<String>>,
+ /// The prompt describing what the agent should accomplish.
+ pub prompt: String,
+ /// JSON schema for the expected output structure.
+ pub schema: Option<Value>,
+ /// Agent model the run used.
+ pub model: Option<AgentModel>,
+ /// Reasoning effort the run used, if one was requested.
+ pub effort: Option<AgentEffort>,
+}
+
+/// A single agent run as returned by the agent list endpoint.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListItem {
+ /// The agent task ID.
+ pub id: String,
+ /// When the run was created (ISO 8601).
+ pub created_at: String,
+ /// Short hint describing the run's target.
+ pub target_hint: String,
+ /// Origin of the run (e.g. "api").
+ pub origin: String,
+ /// Integration identifier, if any.
+ pub integration: Option<String>,
+ /// Per-session settings for the run.
+ pub settings: AgentListItemSettings,
+ /// Current status of the run.
+ pub status: AgentStatus,
+ /// Options the run was started with.
+ pub options: Option<AgentListItemOptions>,
+}
+
+/// Response from listing agent runs.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentListResponse {
+ /// Whether the request was successful.
+ pub success: bool,
+ /// The agent runs, most recent first.
+ pub agents: Option<Vec<AgentListItem>>,
+ /// Absolute URL of the next page; only present when more pages exist.
+ pub next: Option<String>,
+ /// Error message if the request failed.
+ pub error: Option<String>,
+}
+
// Agent trace types (GET /v2/agent/:id/trace). These mirror the agent
// service's canonical event schema (schemaVersion 1): usage.recorded events
// are withheld server-side and agent.started carries no model name.
@@ -488,6 +556,58 @@ impl Client {
.await
}
+ /// Lists agent runs, most recent first.
+ ///
+ /// Pages are fixed at 20 runs. To fetch the next page, pass the `before`
+ /// value from the previous page's `next` URL. This method does not
+ /// auto-paginate.
+ ///
+ /// # Arguments
+ ///
+ /// * `before` - Only return agent runs created before this unix
+ /// millisecond timestamp.
+ ///
+ /// # Returns
+ ///
+ /// The list of agent runs and an optional next page URL.
+ ///
+ /// # Example
+ ///
+ /// ```no_run
+ /// use firecrawl::Client;
+ ///
+ /// #[tokio::main]
+ /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ /// let client = Client::new("your-api-key")?;
+ ///
+ /// let page = client.list_agents(None).await?;
+ /// for run in page.agents.unwrap_or_default() {
+ /// println!("{}: {:?}", run.id, run.status);
+ /// }
+ ///
+ /// Ok(())
+ /// }
+ /// ```
+ pub async fn list_agents(
+ &self,
+ before: Option<u64>,
+ ) -> Result<AgentListResponse, FirecrawlError> {
+ let path = match before {
+ Some(before) => format!("/agent?before={}", before),
+ None => "/agent".to_string(),
+ };
+
+ let response = self
+ .client
+ .get(self.url(&path))
+ .headers(self.prepare_headers(None))
+ .send()
+ .await
+ .map_err(|e| FirecrawlError::HttpError("Listing agents".to_string(), e))?;
+
+ self.handle_response(response, "list agents").await
+ }
+
/// Gets the execution trace of an agent task (spark-2 runs only).
///
/// # Arguments
@@ -1143,6 +1263,82 @@ mod tests {
mock.assert();
}
+ #[tokio::test]
+ async fn test_list_agents_with_mock() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock("GET", "/v2/agent")
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(
+ json!({
+ "success": true,
+ "agents": [{
+ "id": "agent-123",
+ "createdAt": "2026-08-31T12:00:00.000Z",
+ "targetHint": "https://example.com",
+ "origin": "api",
+ "settings": {"hidden": false, "starred": true, "label": "prod"},
+ "status": "completed",
+ "options": {
+ "urls": ["https://example.com"],
+ "prompt": "find pricing",
+ "model": "spark-1-pro"
+ }
+ }]
+ })
+ .to_string(),
+ )
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let page = client.list_agents(None).await.unwrap();
+
+ assert!(page.success);
+ assert!(page.next.is_none());
+ let agents = page.agents.unwrap();
+ assert_eq!(agents.len(), 1);
+ assert_eq!(agents[0].id, "agent-123");
+ assert_eq!(agents[0].status, AgentStatus::Completed);
+ assert!(agents[0].settings.starred);
+ assert_eq!(agents[0].settings.label.as_deref(), Some("prod"));
+ let options = agents[0].options.as_ref().unwrap();
+ assert_eq!(options.prompt, "find pricing");
+ assert_eq!(options.model, Some(AgentModel::Spark1Pro));
+ mock.assert();
+ }
+
+ #[tokio::test]
+ async fn test_list_agents_with_before() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock("GET", "/v2/agent")
+ .match_query(Matcher::UrlEncoded("before".into(), "1756600000000".into()))
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(
+ json!({
+ "success": true,
+ "agents": [],
+ "next": "https://api.firecrawl.dev/v2/agent?before=1756600000000"
+ })
+ .to_string(),
+ )
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let page = client.list_agents(Some(1756600000000)).await.unwrap();
+
+ assert!(page.success);
+ assert_eq!(
+ page.next.as_deref(),
+ Some("https://api.firecrawl.dev/v2/agent?before=1756600000000")
+ );
+ mock.assert();
+ }
+
#[tokio::test]
async fn test_agent_sync_with_mock() {
let mut server = mockito::Server::new_async().await;