Skip to content

Building AI agents, atomically

Address review: drop origin field, split tool logic, validate responses, redact key

Juampi04921b1f9309
diff --git a/atomic-forge/tools/firecrawl_search/README.md b/atomic-forge/tools/firecrawl_search/README.md
index 74b1782..1fbacb9 100644
--- a/atomic-forge/tools/firecrawl_search/README.md
+++ b/atomic-forge/tools/firecrawl_search/README.md
@@ -15,7 +15,7 @@ Searches the web or recent news through the [Firecrawl Search](https://www.firec
2. Or copy the `tool/` folder directly into your project.
## Configuration
-- `api_key` (str): Firecrawl API key. Falls back to the `FIRECRAWL_API_KEY` environment variable when empty.
+- `api_key` (str): Firecrawl API key. Falls back to the `FIRECRAWL_API_KEY` environment variable when empty. Stored as a secret and kept out of reprs, raised errors, and logs.
- `base_url` (str): API base URL (default `https://api.firecrawl.dev/v2`).
- `location` (str, optional): location to localise results, e.g. `Germany`.
- `time_range` (str, optional): `day`, `week`, `month`, or `year`. Only applies to web results.
diff --git a/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py b/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py
index 2c78168..f61e2a7 100644
--- a/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py
+++ b/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py
@@ -1,9 +1,13 @@
+import logging
import os
import sys
+from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestServer
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -41,6 +45,33 @@ CONTENT_HIT = {
}
+DUMMY_KEY = "fc-dummy-secret-0123456789"
+
+
+@asynccontextmanager
+async def fake_firecrawl(respond):
+ """Serve POST /v2/search on a local aiohttp server; `respond(body)` builds each response."""
+ seen = []
+
+ async def handler(request):
+ body = await request.json()
+ seen.append({"headers": dict(request.headers), "body": body})
+ return respond(body)
+
+ app = web.Application()
+ app.router.add_post("/v2/search", handler)
+ server = TestServer(app)
+ await server.start_server()
+ try:
+ yield str(server.make_url("/v2")), seen
+ finally:
+ await server.close()
+
+
+def _http_tool(base_url: str, **config) -> FirecrawlSearchTool:
+ return FirecrawlSearchTool(config=FirecrawlSearchToolConfig(api_key=DUMMY_KEY, base_url=base_url, **config))
+
+
def _mock_session(status: int, payload: dict, reason: str = "OK") -> MagicMock:
session = MagicMock()
response = SimpleNamespace(status=status, reason=reason, json=AsyncMock(return_value=payload))
@@ -89,7 +120,7 @@ def test_to_item_falls_back_to_url_for_title():
def test_build_body_defaults(tool):
body = tool._build_body("python", FirecrawlSearchToolInputSchema(queries=["python"]))
- assert body == {"query": "python", "limit": 5, "sources": ["web"], "origin": "atomic-agents"}
+ assert body == {"query": "python", "limit": 5, "sources": ["web"]}
def test_build_body_with_options():
@@ -244,24 +275,70 @@ async def test_run_async_raises_when_every_query_fails(tool):
@pytest.mark.asyncio
-async def test_run_async_end_to_end_with_mocked_session(tool):
- session = _mock_session(200, {"success": True, "data": {"web": [WEB_HIT]}})
+async def test_http_round_trip():
+ def respond(body):
+ return web.json_response(
+ {"success": True, "data": {"web": [{**CONTENT_HIT, "url": f"https://example.com/{body['query']}"}]}}
+ )
- class FakeSession:
- def __init__(self, headers=None, timeout=None):
- self.headers = headers
+ async with fake_firecrawl(respond) as (base_url, seen):
+ out = await _http_tool(base_url).run_async(FirecrawlSearchToolInputSchema(queries=["agents"], include_content=True))
- async def __aenter__(self):
- return session
+ assert [r.url for r in out.results] == ["https://example.com/agents"]
+ assert out.results[0].content.startswith("# Agent guide")
+ assert seen[0]["headers"]["Authorization"] == f"Bearer {DUMMY_KEY}"
+ assert seen[0]["body"]["scrapeOptions"] == {"formats": ["markdown"], "onlyMainContent": True}
- async def __aexit__(self, *args):
- return False
- with patch("tool.firecrawl_search.aiohttp.ClientSession", FakeSession):
- out = await tool.run_async(FirecrawlSearchToolInputSchema(queries=["python"], include_content=True))
+ "payload",
+ [
+ {"success": True, "data": None},
+ {"success": True},
+ {"success": True, "data": {"web": {"url": "https://example.com/not-a-list"}}},
+ {"success": True, "data": {"web": None}},
+ {"success": True, "data": [WEB_HIT]},
+ ],
+)
+async def test_http_malformed_success_response_raises(payload):
+ """A 200 with success=true but no usable result list is an error, not an empty result."""
+ async with fake_firecrawl(lambda body: web.json_response(payload)) as (base_url, _):
+ with pytest.raises(Exception, match="unexpected response shape for 'web' results"):
+ await _http_tool(base_url).run_async(FirecrawlSearchToolInputSchema(queries=["q"]))
+
+
+async def test_http_non_json_error_page_reports_status():
+ def respond(body):
+ return web.Response(status=502, text="<html>Bad Gateway</html>", content_type="text/html")
+
+ async with fake_firecrawl(respond) as (base_url, _):
+ with pytest.raises(Exception, match="Firecrawl search failed for 'q': 502 Bad Gateway"):
+ await _http_tool(base_url).run_async(FirecrawlSearchToolInputSchema(queries=["q"]))
+
+
+async def test_http_dummy_key_kept_out_of_repr_errors_and_logs(caplog):
+ """Even when the provider echoes the key back, it never reaches repr, raised errors, or logs."""
+
+ def respond(body):
+ if body["query"] == "bad":
+ return web.json_response({"success": False, "error": f"Invalid token {DUMMY_KEY}"}, status=401)
+ return web.json_response({"success": True, "data": {"web": [WEB_HIT]}})
+
+ async with fake_firecrawl(respond) as (base_url, _):
+ tool = _http_tool(base_url)
+ with caplog.at_level(logging.WARNING, logger="tool.firecrawl_search"):
+ out = await tool.run_async(FirecrawlSearchToolInputSchema(queries=["bad", "good"]))
+ with pytest.raises(Exception) as raised:
+ await tool.run_async(FirecrawlSearchToolInputSchema(queries=["bad"]))
- assert [r.url for r in out.results] == ["https://www.python.org/"]
- assert session.post.call_args[1]["json"]["scrapeOptions"]["formats"] == ["markdown"]
+ assert [r.query for r in out.results] == ["good"]
+ assert "401 Invalid token [redacted]" in caplog.text
+ assert "401 Invalid token [redacted]" in str(raised.value)
+ for text in (caplog.text, str(raised.value), repr(raised.value), repr(tool), repr(tool.config), str(tool.config)):
+ assert DUMMY_KEY not in text
@pytest.mark.asyncio
@@ -303,7 +380,7 @@ async def test_run_async_requires_api_key(monkeypatch):
def test_api_key_falls_back_to_environment(monkeypatch):
monkeypatch.setenv("FIRECRAWL_API_KEY", "env-key")
tool = FirecrawlSearchTool(config=FirecrawlSearchToolConfig())
- assert tool.api_key == "env-key"
+ assert tool._api_key == "env-key"
def test_run_invokes_run_async(tool):
diff --git a/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py b/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py
index 4ee7a66..11683d1 100644
--- a/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py
+++ b/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py
@@ -5,7 +5,7 @@ from concurrent.futures import ThreadPoolExecutor
from typing import List, Literal, Optional
import aiohttp
-from pydantic import Field
+from pydantic import Field, SecretStr
from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig
@@ -65,8 +65,9 @@ class FirecrawlSearchToolOutputSchema(BaseIOSchema):
class FirecrawlSearchToolConfig(BaseToolConfig):
"""Configuration for the FirecrawlSearchTool."""
- api_key: str = Field(
- default="", description="Firecrawl API key. Falls back to the FIRECRAWL_API_KEY environment variable."
+ api_key: SecretStr = Field(
+ default=SecretStr(""),
+ description="Firecrawl API key. Falls back to the FIRECRAWL_API_KEY environment variable. Hidden in repr.",
)
base_url: str = Field(default="https://api.firecrawl.dev/v2", description="Firecrawl API base URL.")
location: Optional[str] = Field(
@@ -91,27 +92,30 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear
def __init__(self, config: FirecrawlSearchToolConfig = FirecrawlSearchToolConfig()):
super().__init__(config)
- self.api_key = config.api_key or os.getenv("FIRECRAWL_API_KEY", "")
+ self._api_key = config.api_key.get_secret_value() or os.getenv("FIRECRAWL_API_KEY", "")
self.base_url = config.base_url.rstrip("/")
self.location = config.location
self.time_range = config.time_range
self.max_content_chars = config.max_content_chars
self.timeout = config.timeout
+ @staticmethod
+ def _first(*values):
+ return next((value for value in values if value), None)
+
@classmethod
def _to_item(cls, hit: dict, query: str, max_content_chars: Optional[int] = None) -> FirecrawlSearchResultItem:
- metadata = hit.get("metadata") if isinstance(hit.get("metadata"), dict) else {}
+ metadata = hit.get("metadata")
+ metadata = metadata if isinstance(metadata, dict) else {}
content = hit.get("markdown")
- if content and max_content_chars:
- content = content[:max_content_chars]
return FirecrawlSearchResultItem(
query=query,
- title=hit.get("title") or metadata.get("title") or hit["url"],
+ title=cls._first(hit.get("title"), metadata.get("title"), hit["url"]),
url=hit["url"],
- description=hit.get("description") or hit.get("snippet") or metadata.get("description"),
+ description=cls._first(hit.get("description"), hit.get("snippet"), metadata.get("description")),
position=hit.get("position"),
published=hit.get("date"),
- content=content,
+ content=content[:max_content_chars] if content else None,
)
def _build_body(self, query: str, params: FirecrawlSearchToolInputSchema) -> dict:
@@ -119,7 +123,6 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear
"query": query,
"limit": params.max_results_per_query,
"sources": [params.search_type],
- "origin": "atomic-agents",
}
if self.location:
body["location"] = self.location
@@ -129,6 +132,32 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear
body["scrapeOptions"] = {"formats": ["markdown"], "onlyMainContent": True}
return body
+ def _redact(self, text: str) -> str:
+ return text.replace(self._api_key, "[redacted]") if self._api_key else text
+
+ def _error(self, query: str, status: int, detail: str) -> Exception:
+ return Exception(self._redact(f"Firecrawl search failed for '{query}': {status} {detail}"))
+
+ @staticmethod
+ async def _read_json(resp: aiohttp.ClientResponse):
+ try:
+ return await resp.json(content_type=None)
+ except ValueError:
+ return None
+
+ def _check_success(self, query: str, status: int, reason: Optional[str], data) -> None:
+ payload = data if isinstance(data, dict) else {}
+ if status != 200 or not payload.get("success"):
+ raise self._error(query, status, payload.get("error") or reason)
+
+ def _extract_hits(self, query: str, data: dict, search_type: str) -> list:
+ # The key for the requested source is absent when there are no results.
+ groups = data.get("data")
+ hits = groups.get(search_type, []) if isinstance(groups, dict) else None
+ if not isinstance(hits, list):
+ raise self._error(query, 200, f"unexpected response shape for '{search_type}' results")
+ return hits
+
async def _fetch(
self,
session: aiohttp.ClientSession,
@@ -136,45 +165,45 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear
params: FirecrawlSearchToolInputSchema,
) -> List[FirecrawlSearchResultItem]:
async with session.post(f"{self.base_url}/search", json=self._build_body(query, params)) as resp:
- try:
- data = await resp.json(content_type=None)
- except ValueError:
- data = None
- if resp.status != 200 or not isinstance(data, dict) or not data.get("success"):
- error = data.get("error") if isinstance(data, dict) else None
- raise Exception(f"Firecrawl search failed for '{query}': {resp.status} {error or resp.reason}")
+ data = await self._read_json(resp)
+ self._check_success(query, resp.status, resp.reason, data)
- # The key for the requested source is absent when there are no results.
- groups = data.get("data") if isinstance(data.get("data"), dict) else {}
- hits = groups.get(params.search_type) or []
+ hits = self._extract_hits(query, data, params.search_type)
items = [self._to_item(hit, query, self.max_content_chars) for hit in hits if isinstance(hit, dict) and hit.get("url")]
return items[: params.max_results_per_query]
+ def _log_failure(self, query: str, error: BaseException) -> None:
+ logger.warning("Firecrawl query '%s' failed: %s", query, self._redact(str(error) or repr(error)))
+
+ def _collect(self, queries: List[str], grouped: list) -> List[FirecrawlSearchResultItem]:
+ results: List[FirecrawlSearchResultItem] = []
+ errors = []
+ for query, group in zip(queries, grouped):
+ if isinstance(group, BaseException):
+ errors.append(group)
+ self._log_failure(query, group)
+ continue
+ results.extend(group)
+
+ # A bad key or exhausted credits fails every query; raise instead of returning an empty list.
+ if errors and len(errors) == len(grouped):
+ raise errors[0]
+ return results
+
async def run_async(self, params: FirecrawlSearchToolInputSchema) -> FirecrawlSearchToolOutputSchema:
- if not self.api_key:
+ if not self._api_key:
raise ValueError(
"Firecrawl API key is missing. Set FirecrawlSearchToolConfig.api_key or the FIRECRAWL_API_KEY "
"environment variable."
)
- headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
+ headers = {"Authorization": f"Bearer {self._api_key}", "Content-Type": "application/json"}
timeout = aiohttp.ClientTimeout(total=self.timeout)
async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:
tasks = [self._fetch(session, q, params) for q in params.queries]
grouped = await asyncio.gather(*tasks, return_exceptions=True)
- # A bad key or exhausted credits fails every query; raise instead of returning an empty list.
- failures = [group for group in grouped if isinstance(group, Exception)]
- if failures and len(failures) == len(grouped):
- raise failures[0]
-
- results: List[FirecrawlSearchResultItem] = []
- for query, group in zip(params.queries, grouped):
- if isinstance(group, Exception):
- logger.warning("Firecrawl query '%s' failed: %s", query, str(group) or repr(group))
- continue
- results.extend(group)
- return FirecrawlSearchToolOutputSchema(results=results)
+ return FirecrawlSearchToolOutputSchema(results=self._collect(params.queries, grouped))
def run(self, params: FirecrawlSearchToolInputSchema) -> FirecrawlSearchToolOutputSchema:
with ThreadPoolExecutor() as executor: