Building AI agents, atomically
Report failure reasons, wrap invalid URLs, require http(s) result URLs, dedupe queries
Juampi1589b24b8bd5
diff --git a/atomic-forge/tools/firecrawl_search/README.md b/atomic-forge/tools/firecrawl_search/README.mdindex af7120b..674cf91 100644--- a/atomic-forge/tools/firecrawl_search/README.md+++ b/atomic-forge/tools/firecrawl_search/README.md@@ -25,14 +25,14 @@ Searches the web or recent news through the [Firecrawl Search](https://www.firec## Input & Output Structure### Input Schema-- `queries` (list[str], at least one): search queries to run. Operators such as `site:`, `"exact phrase"`, `-term`, and `filetype:pdf` are supported.+- `queries` (list[str], at least one): search queries to run. Duplicates are sent once. Operators such as `site:`, `"exact phrase"`, `-term`, and `filetype:pdf` are supported.- `search_type` (str): `web` or `news`. Default `web`.- `max_results_per_query` (int): 1-100 (default 5, kept low because each result can carry a full page with `include_content`).- `include_content` (bool): also return each result page as Markdown (default `False`).### Output Schema-- `results`: a list of `FirecrawlSearchResultItem` items. Each has `query`, `title`, `url`, and optional `description` (a query-relevant excerpt or snippet), `position`, `published` (news), and `content` (Markdown, when `include_content` is set). Results without a usable URL are skipped, and badly typed optional fields are left empty.-- `failed_queries`: queries that failed while others returned results. The reason for each is logged as a warning.+- `results`: a list of `FirecrawlSearchResultItem` items. Each has `query`, `title`, `url`, and optional `description` (a query-relevant excerpt or snippet), `position`, `published` (news), and `content` (Markdown, when `include_content` is set). Results without an http(s) URL are skipped, and badly typed optional fields are left empty.+- `failures`: queries that failed while others returned results, each with `query` and `error` (the HTTP status and the API's error message, with any key redacted). They are also logged as warnings.## UsageIf no query returns results and at least one failed (for example a wrong API key, no credits, or a malformed response), `run` raises the first error instead of returning an empty list. Redirects are not followed; they are reported as errors.diff --git a/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py b/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.pyindex b7fae4f..801866b 100644--- a/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py+++ b/atomic-forge/tools/firecrawl_search/tests/test_firecrawl_search.py@@ -16,6 +16,7 @@ from pydantic import ValidationErrorsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))from tool.firecrawl_search import ( # noqa: E402+ FirecrawlSearchFailure,FirecrawlSearchResultItem,FirecrawlSearchTool,FirecrawlSearchToolConfig,@@ -25,6 +26,7 @@ from tool.firecrawl_search import ( # noqa: E402DUMMY_KEY = "fc-dummy0secret0key0123456789"+OTHER_KEY = "fc-0123456789abcdef0123456789abcdef"WEB_HIT = {"url": "https://www.python.org/",@@ -138,6 +140,7 @@ def test_to_item_content_and_truncation():("position", 1.5, "position", None),("position", True, "position", None),("position", -3, "position", None),+ ("position", 0, "position", None),("date", 20250101, "published", None),("markdown", 42, "content", None),("markdown", {}, "content", None),@@ -149,7 +152,22 @@ def test_to_item_drops_badly_typed_fields(field, value, attribute, expected):assert getattr(item, attribute) == expected[email protected]("hit", [1, "s", None, [], {"title": "no url"}, {"url": ""}, {"url": 123}])+ "hit",+ [+ 1,+ "s",+ None,+ [],+ {"title": "no url"},+ {"url": ""},+ {"url": 123},+ {"url": ["https://example.com"]},+ {"url": " https://example.com"},+ {"url": "javascript:alert(1)"},+ {"url": "ftp://example.com/file"},+ ],+)def test_to_item_without_usable_url_is_none(hit):assert FirecrawlSearchTool._to_item(hit, "q") is None@@ -221,7 +239,7 @@ async def test_news_round_trip_reads_news_key_only():async def test_missing_source_key_is_an_empty_search():"""The API omits the source key when there are no results; that is a real empty result."""out, _ = await search(lambda body: web.json_response({"success": True, "data": {}}))- assert out == FirecrawlSearchToolOutputSchema(results=[], failed_queries=[])+ assert out == FirecrawlSearchToolOutputSchema(results=[], failures=[])@pytest.mark.asyncio@@ -244,6 +262,13 @@ async def test_all_hits_invalid_raises():assert str(error) == "Firecrawl search failed for 'q': 200 none of the 4 'web' results had a usable url"+async def test_duplicate_queries_sent_once():+ out, seen = await search(lambda body: ok("web", [WEB_HIT]), queries=["q", "q"])+ assert len(seen) == 1+ assert [r.query for r in out.results] == ["q"]++######################## Response validation ########################@@ -267,7 +292,7 @@ async def test_malformed_success_response_raises(payload):@pytest.mark.parametrize("payload", [{"success": "false"}, {"success": "true"}, {"success": 1}, {}])async def test_success_must_be_literally_true(payload):error = await search_error(lambda body: web.json_response({**payload, "data": {"web": [WEB_HIT]}}))- assert str(error) == "Firecrawl search failed for 'q': 200 OK"+ assert str(error) == "Firecrawl search failed for 'q': 200 response did not report success"@pytest.mark.asyncio@@ -291,7 +316,7 @@ async def test_provider_error_message_is_reported():"response, expected",[(lambda: web.Response(status=502, text="<html>Bad Gateway</html>", content_type="text/html"), "502 Bad Gateway"),- (lambda: web.Response(status=200, text=""), "200 OK"),+ (lambda: web.Response(status=200, text=""), "200 response did not report success"),(lambda: web.Response(status=204), "204 No Content"),],)@@ -323,9 +348,10 @@ async def test_partial_failure_reports_failed_queries(caplog):with caplog.at_level(logging.WARNING, logger="tool.firecrawl_search"):out, _ = await search(respond, queries=["bad", "good"])+ reason = "Firecrawl search failed for 'bad': 429 Rate limit exceeded"assert [r.query for r in out.results] == ["good"]- assert out.failed_queries == ["bad"]- assert "Firecrawl query 'bad' failed: Firecrawl search failed for 'bad': 429 Rate limit exceeded" in caplog.text+ assert out.failures == [FirecrawlSearchFailure(query="bad", error=reason)]+ assert f"Firecrawl query 'bad' failed: {reason}" in caplog.text@pytest.mark.asyncio@@ -385,9 +411,30 @@ async def test_timeout_is_wrapped_with_query():with pytest.raises(Exception) as raised:await tool.run_async(FirecrawlSearchToolInputSchema(queries=["q"]))+ assert str(raised.value) == "Firecrawl search failed for 'q': request failed: TimeoutError after 0.05s"+ assert raised.value.__context__ is None+++ "base_url",+ [+ "http://exa\nmple.com/v2",+ f"http://{'a' * 70}.example.com/v2",+ f"{DUMMY_KEY}/v2", # aiohttp's InvalidUrlClientError echoes the URL, so its text must be redacted too+ ],+)+async def test_invalid_base_url_is_wrapped_and_no_frame_holds_the_key(base_url):+ """aiohttp raises ValueError/UnicodeError for such URLs from a frame whose locals hold the request headers."""+ with pytest.raises(Exception) as raised:+ await http_tool(base_url).run_async(FirecrawlSearchToolInputSchema(queries=["q"]))+assert str(raised.value).startswith("Firecrawl search failed for 'q': request failed: ")- assert "Timeout" in str(raised.value)assert raised.value.__context__ is None+ stack = traceback.TracebackException.from_exception(raised.value, capture_locals=True).stack+ non_test_frames = [repr(frame.locals) for frame in stack if frame.filename != __file__]+ assert non_test_frames+ assert DUMMY_KEY not in str(raised.value) + repr(raised.value) + "".join(non_test_frames)################@@ -396,7 +443,7 @@ async def test_timeout_is_wrapped_with_query():@pytest.mark.asyncio@pytest.mark.parametrize("echo",- [DUMMY_KEY, f"Bearer {DUMMY_KEY}", DUMMY_KEY.upper(), {"token": DUMMY_KEY}, "fc-someotherkey12345"],+ [DUMMY_KEY, f"Bearer {DUMMY_KEY}", DUMMY_KEY.upper(), {"token": DUMMY_KEY}, OTHER_KEY, OTHER_KEY.upper()],)async def test_echoed_key_kept_out_of_errors_and_logs(caplog, echo):"""Even when the provider echoes a key back, it never reaches raised errors, tracebacks or logs."""@@ -410,10 +457,10 @@ async def test_echoed_key_kept_out_of_errors_and_logs(caplog, echo):out, _ = await search(respond, queries=["bad", "good"])error = await search_error(respond, queries=["bad"])- assert out.failed_queries == ["bad"]- assert "[redacted]" in str(error) and "[redacted]" in caplog.text- for text in (caplog.text, leak_surfaces(error)):- assert DUMMY_KEY not in text and DUMMY_KEY.upper() not in text and "fc-someotherkey12345" not in text+ assert [failure.query for failure in out.failures] == ["bad"]+ assert "[redacted]" in str(error) and "[redacted]" in caplog.text and "[redacted]" in out.failures[0].error+ for text in (caplog.text, leak_surfaces(error), repr(out)):+ assert all(key not in text for key in (DUMMY_KEY, DUMMY_KEY.upper(), OTHER_KEY, OTHER_KEY.upper()))def test_key_kept_out_of_tool_and_config_state():@@ -424,9 +471,11 @@ def test_key_kept_out_of_tool_and_config_state():assert tool._api_key.get_secret_value() == DUMMY_KEY-def test_short_key_does_not_mangle_messages():+def test_redaction_does_not_mangle_ordinary_text():+ """A one-letter key is not redacted (it would hit every 'a'), and fc- words that are not keys are left alone."""tool = FirecrawlSearchTool(config=FirecrawlSearchToolConfig(api_key="a"))- assert tool._redact("Firecrawl search failed") == "Firecrawl search failed"+ text = "Firecrawl search failed for 'fc-barcelona-2024'"+ assert tool._redact(text) == text@pytest.mark.asynciodiff --git a/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py b/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.pyindex c91e57c..4a5de9e 100644--- a/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py+++ b/atomic-forge/tools/firecrawl_search/tool/firecrawl_search.py@@ -3,7 +3,7 @@ import loggingimport osimport refrom concurrent.futures import ThreadPoolExecutor-from typing import Any, List, Literal, Optional+from typing import Any, List, Literal, Optional, Tupleimport aiohttpfrom pydantic import Field, SecretStr, field_validator@@ -61,12 +61,19 @@ class FirecrawlSearchResultItem(BaseIOSchema):return value if type(value) is int and value > 0 else None+class FirecrawlSearchFailure(BaseIOSchema):+ """A query that failed while other queries returned results."""++ query: str = Field(..., description="The query that failed.")+ error: str = Field(..., description="Why it failed, e.g. an HTTP status and the API's error message.")++class FirecrawlSearchToolOutputSchema(BaseIOSchema):"""Output of the Firecrawl search tool."""results: List[FirecrawlSearchResultItem] = Field(..., description="Matching results across all queries.")- failed_queries: List[str] = Field(- default_factory=list, description="Queries that failed while others succeeded. Details are logged."+ failures: List[FirecrawlSearchFailure] = Field(+ default_factory=list, description="Queries that failed while others returned results, with the reason.")@@ -100,9 +107,9 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear"""Tool for searching the web and news via the Firecrawl Search API."""TIME_RANGES = {"day": "qdr:d", "week": "qdr:w", "month": "qdr:m", "year": "qdr:y"}- # Anything shaped like a Firecrawl key is redacted from error and log text, plus the configured key itself+ # Anything in the Firecrawl key format is redacted from error and log text, plus the configured key itself# when it is long enough that replacing it cannot mangle ordinary words.- KEY_PATTERN = re.compile(r"fc-[A-Za-z0-9]{8,}")+ KEY_PATTERN = re.compile(r"\bfc-[0-9a-f]{32}\b", re.IGNORECASE)MIN_REDACTED_KEY_LENGTH = 8def __init__(self, config: FirecrawlSearchToolConfig = FirecrawlSearchToolConfig()):@@ -121,9 +128,9 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear@classmethoddef _to_item(cls, hit: Any, query: str, max_content_chars: Optional[int] = None) -> Optional[FirecrawlSearchResultItem]:- """Normalise one result, or return None when it has no usable URL."""- url = cls._first_text(hit.get("url")) if isinstance(hit, dict) else None- if url is None:+ """Normalise one result, or return None when it has no http(s) URL."""+ url = hit.get("url") if isinstance(hit, dict) else None+ if not str(url).startswith(("http://", "https://")):return Nonecontent = cls._first_text(hit.get("markdown"))return FirecrawlSearchResultItem(@@ -152,8 +159,9 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSeartext = re.sub(re.escape(key), "[redacted]", text, flags=re.IGNORECASE)return self.KEY_PATTERN.sub("[redacted]", text)- def _error(self, query: str, detail: str) -> Exception:- return Exception(self._redact(f"Firecrawl search failed for '{query}': {detail}"))+ @staticmethod+ def _error(query: str, detail: str) -> Exception:+ return Exception(f"Firecrawl search failed for '{query}': {detail}")@staticmethodasync def _read_json(resp: aiohttp.ClientResponse) -> Any:@@ -164,26 +172,36 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSeardef _failure(self, status: int, reason: Optional[str], data: Any) -> Optional[str]:"""Return why a response is not a successful search (only a 200 whose body says success is true is),- or None when it is."""+ or None when it is. Provider text is redacted here, where it enters the tool."""payload = data if isinstance(data, dict) else {}if status == 200 and payload.get("success") is True:return Nonereturn self._redact(f"{status} {payload.get('error') or reason}")- async def _post(self, session: aiohttp.ClientSession, query: str, params: FirecrawlSearchToolInputSchema) -> dict:- """Send one search request and return the successful response body.+ async def _exchange(+ self, session: aiohttp.ClientSession, query: str, params: FirecrawlSearchToolInputSchema+ ) -> Tuple[Any, Optional[str]]:+ """Send one search request and return the parsed body plus why it failed (None on success).- Errors are raised outside the except block, so the original aiohttp error (whose repr carries the request- headers) is not attached as context, and the provider body is dropped first, so a traceback that captures- locals cannot show a key the provider echoed back."""+ Transport errors, timeouts and invalid URLs are turned into a failure reason here instead of propagating,+ because aiohttp's own frames and errors hold the request headers, Authorization included."""try:async with session.post(f"{self.base_url}/search", json=self._build_body(query, params), allow_redirects=False) as resp:payload = await self._read_json(resp)- failure = self._failure(resp.status, resp.reason, payload)- except (aiohttp.ClientError, asyncio.TimeoutError) as error:- payload, failure = None, f"request failed: {type(error).__name__} {error}"+ reason = resp.reason if resp.status != 200 else "response did not report success"+ return payload, self._failure(resp.status, reason, payload)+ except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as error:+ return None, self._redact(f"request failed: {type(error).__name__} {str(error) or f'after {self.timeout:g}s'}")++ async def _post(self, session: aiohttp.ClientSession, query: str, params: FirecrawlSearchToolInputSchema) -> dict:+ """Return the body of a successful search response, or raise.++ The raise happens in this frame, which holds neither the response nor an aiohttp error, and the body of a+ failed response is dropped first, so a traceback that captures locals cannot show a key echoed back in an+ error response."""+ payload, failure = await self._exchange(session, query, params)if failure:payload = Noneraise self._error(query, failure)@@ -214,19 +232,19 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear"""Merge per-query results. Raise when no query produced results and at least one failed, so a bad key,exhausted credits or a malformed response never looks like an empty search."""results: List[FirecrawlSearchResultItem] = []- failed_queries: List[str] = []+ failures: List[FirecrawlSearchFailure] = []errors: List[Exception] = []for query, group in zip(queries, grouped):if isinstance(group, Exception):- failed_queries.append(query)errors.append(group)- logger.warning("Firecrawl query '%s' failed: %s", query, self._redact(str(group)))+ failures.append(FirecrawlSearchFailure(query=query, error=str(group)))+ logger.warning("Firecrawl query '%s' failed: %s", query, failures[-1].error)continueresults.extend(group)if errors and not results:raise errors[0]- return FirecrawlSearchToolOutputSchema(results=results, failed_queries=failed_queries)+ return FirecrawlSearchToolOutputSchema(results=results, failures=failures)async def run_async(self, params: FirecrawlSearchToolInputSchema) -> FirecrawlSearchToolOutputSchema:if not self._api_key.get_secret_value():@@ -235,14 +253,16 @@ class FirecrawlSearchTool(BaseTool[FirecrawlSearchToolInputSchema, FirecrawlSear"environment variable.")+ # Duplicate queries would be billed twice and return the same results.+ queries = list(dict.fromkeys(params.queries))# The Authorization header is built inline so no local variable holds the key.async with aiohttp.ClientSession(headers={"Authorization": f"Bearer {self._api_key.get_secret_value()}", "Content-Type": "application/json"},timeout=aiohttp.ClientTimeout(total=self.timeout),) as session:- grouped = await asyncio.gather(*(self._fetch(session, q, params) for q in params.queries), return_exceptions=True)+ grouped = await asyncio.gather(*(self._fetch(session, q, params) for q in queries), return_exceptions=True)- return self._collect(params.queries, grouped)+ return self._collect(queries, grouped)def run(self, params: FirecrawlSearchToolInputSchema) -> FirecrawlSearchToolOutputSchema:with ThreadPoolExecutor() as executor: