Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
c90a0a4
Validate Wikipedia edition codes before building URLs
Afloat16 Nov 13, 2026
7966624
fix(weather): preserve forecasts when current temperature is missing
Afloat16 Nov 13, 2026
2ceb1bb
Preserve Hacker News query failures in tool results
Afloat16 Nov 14, 2026
62d01d3
Preserve arXiv metadata and submission-date queries
Afloat16 Nov 14, 2026
84b529c
Reject nonexistent local datetime inputs
Afloat16 Nov 14, 2026
11e13ff
Resolve scraped links against the final page URL
Afloat16 Nov 14, 2026
a38b0b4
Honor HTML encodings in webpage scraping
Afloat16 Nov 14, 2026
86d283f
Preserve article headings and attribution during webpage extraction
Afloat16 Nov 16, 2026
cb1e029
Map social_media to the SearXNG social media category
Afloat16 Nov 16, 2026
bb05ac6
Skip empty main-content candidates while preserving media
Afloat16 Nov 16, 2026
f98d638
Keep authenticated Serply requests at their configured endpoint
Afloat16 Nov 17, 2026
65c3f80
Send BoCha per-call limits to the search API
Afloat16 Nov 17, 2026
8732c5b
Merge #418: Honor HTML encodings in webpage scraping
Nov 17, 2026
33567f2
Merge #442: Preserve article headings and attribution during webpage …
Nov 17, 2026
69da4b2
Merge #458: Skip empty main-content candidates while preserving media
Nov 17, 2026
0c0f17b
Merge #453: Map social_media to the SearXNG social media category
Nov 17, 2026
50596bf
Merge #400: Preserve Hacker News query failures in tool results
Nov 17, 2026
d8403fe
Merge #379: Validate Wikipedia edition codes before building URLs
Nov 17, 2026
ee0a0d3
Merge #397: fix(weather): preserve forecasts when current temperature…
Nov 17, 2026
27e2680
Merge #402: Preserve arXiv metadata and submission-date queries
Nov 17, 2026
f3a6345
Merge #406: Reject nonexistent local datetime inputs
Nov 17, 2026
289dada
Merge #462: Keep authenticated Serply requests at their configured en…
Nov 17, 2026
547383f
Merge #464: Send BoCha per-call limits to the search API
Nov 17, 2026
74ba844
Merge #412: Resolve scraped links against the final page URL
Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,9 @@ async def run_async(
ValueError: If the base URL is not provided.
Exception: If the request to SearXNG fails.
"""
category = "social media" if params.category == "social_media" else params.category
async with aiohttp.ClientSession() as session:
tasks = [self._fetch_search_results(session, query, params.category) for query in params.queries]
tasks = [self._fetch_search_results(session, query, category) for query in params.queries]
results = await asyncio.gather(*tasks)

all_results = [item for sublist in results for item in sublist]
Expand All @@ -152,8 +153,8 @@ async def run_async(
seen_urls.add(result["url"])

# Filter results to include only those with the correct category if it is set
if params.category:
filtered_results = [result for result in unique_results if result.get("category") == params.category]
if category:
filtered_results = [result for result in unique_results if result.get("category") == category]
else:
filtered_results = unique_results

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from email.message import Message
from typing import Optional, Dict
import re
import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup, UnicodeDammit
from markdownify import markdownify
from pydantic import Field, HttpUrl
from readability import Document
Expand Down Expand Up @@ -102,22 +103,49 @@ def __init__(self, config: WebpageScraperToolConfig = WebpageScraperToolConfig()
self.min_text_length = config.min_text_length
self.use_trafilatura = config.use_trafilatura

def _fetch_webpage(self, url: str) -> str:
def _fetch_webpage(self, url: str) -> tuple[str, str]:
"""
Fetches the webpage content with custom headers.

Args:
url (str): The URL to fetch.

Returns:
str: The HTML content of the webpage.
tuple[str, str]: The HTML content and final response URL.
"""
response = requests.get(url, headers=self.headers, timeout=self.timeout)

if len(response.content) > self.config.max_content_length:
raise ValueError(f"Content length exceeds maximum of {self.config.max_content_length} bytes")

return response.text
content_type = Message()
content_type["Content-Type"] = response.headers.get("Content-Type", "")
charset = content_type.get_content_charset()
# Decode HTML from its bytes: a BOM, an explicit HTTP charset, and an
# HTML declaration take precedence over heuristic encoding detection.
decoded = UnicodeDammit(response.content, is_html=True, user_encodings=[charset] if charset else []).unicode_markup
return (decoded if decoded is not None else response.text), response.url

@staticmethod
def _resolve_content_urls(soup: BeautifulSoup, document_url: str) -> None:
"""Keep links and images usable when the Markdown leaves its source document."""
base_url = document_url
base = soup.find("base", href=True)
if base:
try:
candidate = urljoin(document_url, base["href"].strip())
if urlparse(candidate).scheme not in {"data", "javascript"}:
base_url = candidate
except ValueError:
pass

for tag, attribute in (("a", "href"), ("img", "src")):
for element in soup.find_all(tag, attrs={attribute: True}):
try:
element[attribute] = urljoin(base_url, element[attribute].strip())
except ValueError:
# One malformed URL must not discard the rest of the page.
pass

def _extract_metadata(self, soup: BeautifulSoup, doc: Document, url: str) -> WebpageMetadata:
"""
Expand Down Expand Up @@ -185,18 +213,36 @@ def _extract_main_content(self, soup: BeautifulSoup) -> str:
str: Main content HTML.
"""
# Remove unwanted elements
for element in soup.find_all(["script", "style", "nav", "header", "footer"]):
for element in soup.find_all(["script", "style", "nav"]):
element.decompose()

# Section headers and footers contain headings, authors, and attribution.
# Unwrap them so their IDs/classes cannot become the main-content candidate.
for element in soup.find_all(["header", "footer"]):
if element.find_parent(["main", "article", "section"]) is not None:
element.unwrap()
else:
element.decompose()

# Try to find main content container
content_candidates = [
soup.find("main"),
soup.find(id=re.compile(r"content|main", re.I)),
soup.find(class_=re.compile(r"content|main", re.I)),
soup.find("article"),
*soup.find_all("main"),
*soup.find_all(id=re.compile(r"content|main", re.I)),
*soup.find_all(class_=re.compile(r"content|main", re.I)),
*soup.find_all("article"),
]

main_content = next((candidate for candidate in content_candidates if candidate), None)
# Empty skip targets and placeholders are not article containers.
# Media-only containers still carry content even without text.
media_tags = {"img", "audio", "video", "iframe", "object", "embed", "svg", "canvas"}
main_content = next(
(
candidate
for candidate in content_candidates
if candidate.get_text(strip=True) or candidate.name in media_tags or candidate.find(media_tags)
),
None,
)

if not main_content:
main_content = soup.find("body")
Expand All @@ -216,10 +262,11 @@ def run(self, params: WebpageScraperToolInputSchema) -> WebpageScraperToolOutput

try:
# Fetch webpage content
html_content = self._fetch_webpage(str(params.url))
html_content, document_url = self._fetch_webpage(str(params.url))

# Parse HTML with BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")
self._resolve_content_urls(soup, document_url)

# Extract main content using custom extraction
main_content = self._extract_main_content(soup)
Expand All @@ -241,7 +288,7 @@ def run(self, params: WebpageScraperToolInputSchema) -> WebpageScraperToolOutput
markdown_content = self._clean_markdown(markdown_content)

# Extract metadata
metadata = self._extract_metadata(soup, Document(html_content), str(params.url))
metadata = self._extract_metadata(soup, Document(html_content), document_url)

return WebpageScraperToolOutputSchema(
content=markdown_content,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,9 @@ async def run_async(
ValueError: If the base URL is not provided.
Exception: If the request to SearXNG fails.
"""
category = "social media" if params.category == "social_media" else params.category
async with aiohttp.ClientSession() as session:
tasks = [self._fetch_search_results(session, query, params.category) for query in params.queries]
tasks = [self._fetch_search_results(session, query, category) for query in params.queries]
results = await asyncio.gather(*tasks)

all_results = [item for sublist in results for item in sublist]
Expand All @@ -155,8 +156,8 @@ async def run_async(
seen_urls.add(result["url"])

# Filter results to include only those with the correct category if it is set
if params.category:
filtered_results = [result for result in unique_results if result.get("category") == params.category]
if category:
filtered_results = [result for result in unique_results if result.get("category") == category]
else:
filtered_results = unique_results

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,9 @@ async def run_async(
ValueError: If the base URL is not provided.
Exception: If the request to SearXNG fails.
"""
category = "social media" if params.category == "social_media" else params.category
async with aiohttp.ClientSession() as session:
tasks = [self._fetch_search_results(session, query, params.category) for query in params.queries]
tasks = [self._fetch_search_results(session, query, category) for query in params.queries]
results = await asyncio.gather(*tasks)

all_results = [item for sublist in results for item in sublist]
Expand All @@ -153,8 +154,8 @@ async def run_async(
seen_urls.add(result["url"])

# Filter results to include only those with the correct category if it is set
if params.category:
filtered_results = [result for result in unique_results if result.get("category") == params.category]
if category:
filtered_results = [result for result in unique_results if result.get("category") == category]
else:
filtered_results = unique_results

Expand Down
4 changes: 3 additions & 1 deletion atomic-forge/tools/arxiv_search/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ Searches arXiv for academic papers via the free public API and returns each pape
## Input & Output Structure

### Input Schema
- `queries` (list[str]): plain keywords or arXiv field-prefixed expressions (`ti:`, `au:`, `abs:`, `cat:`, `id:`, `all:`).
- `queries` (list[str]): plain keywords or arXiv field-prefixed expressions (`ti:`, `au:`, `abs:`, `co:`, `jr:`, `cat:`, `rn:`, `id:`, `all:`), including `submittedDate:` date ranges.
- `max_results_per_query` (int): 1–50 (default 5).
- `sort_by` (str): `relevance`, `lastUpdatedDate`, or `submittedDate` (default `relevance`).
- `sort_order` (str): `ascending` or `descending` (default `descending`).
- `category` (str, optional): arXiv category filter (e.g. `cs.AI`).

For example, `jr:Nature` searches journal references and `submittedDate:[202401010000 TO 202412312359]` selects submissions in a date range. These expressions are passed through as written, with the optional category filter applied to the whole expression. See the [arXiv query construction reference](https://info.arxiv.org/help/api/user-manual.html#query_details) for the supported fields and date format.

### Output Schema
A list of `ArxivPaper` items. Each has `arxiv_id`, `title`, `summary`, `authors`, `published`, `updated`, `categories`, `primary_category`, `pdf_url`, `abs_url`, optional `comment` and `journal_ref`.

Expand Down
32 changes: 32 additions & 0 deletions atomic-forge/tools/arxiv_search/tests/test_arxiv_search.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from unittest.mock import AsyncMock, patch

import pytest
from aiohttp import web
from aiohttp.test_utils import TestServer

from tool.arxiv_search import (
ArxivPaper,
Expand Down Expand Up @@ -73,6 +75,36 @@ def test_build_search_query_field_prefix_and_category(tool):
assert tool._build_search_query("ti:RAG", "cs.AI") == "(ti:RAG) AND cat:cs.AI"


@pytest.mark.asyncio
@pytest.mark.parametrize("category", [None, "cs.AI"])
@pytest.mark.parametrize(
"query",
[
'co:"Accepted at NeurIPS"',
"jr:Nature",
"rn:CERN-TH",
"submittedDate:[202401010000 TO 202412312359]",
],
)
async def test_metadata_and_date_queries_reach_http_endpoint_unchanged(query, category):
received = []

async def search(request):
received.append(request.query["search_query"])
return web.Response(text=SAMPLE_FEED, content_type="application/atom+xml")

app = web.Application()
app.router.add_get("/query", search)
async with TestServer(app) as server:
tool = ArxivSearchTool(ArxivSearchToolConfig(base_url=str(server.make_url("/query"))))
output = await tool.run_async(ArxivSearchToolInputSchema(queries=[query], category=category))

expected = f"({query}) AND cat:{category}" if category else query
assert received == [expected]
assert len(output.results) == 2
assert all(paper.query == query for paper in output.results)


def test_extract_id_strips_version_and_url(tool):
assert tool._extract_id("http://arxiv.org/abs/2401.12345v2") == "2401.12345"
assert tool._extract_id("http://arxiv.org/abs/2401.12345") == "2401.12345"
Expand Down
3 changes: 2 additions & 1 deletion atomic-forge/tools/arxiv_search/tool/arxiv_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ def __init__(self, config: ArxivSearchToolConfig = ArxivSearchToolConfig()):
@staticmethod
def _build_search_query(query: str, category: Optional[str]) -> str:
# If the user already used field prefixes, leave them alone; otherwise wrap as `all:`
if any(prefix in query for prefix in ("ti:", "au:", "abs:", "cat:", "all:", "id:")):
field_prefixes = ("ti:", "au:", "abs:", "co:", "jr:", "cat:", "rn:", "id:", "all:", "submittedDate:")
if any(prefix in query for prefix in field_prefixes):
base = query
else:
base = f"all:{query}"
Expand Down
85 changes: 85 additions & 0 deletions atomic-forge/tools/bocha_search/tests/test_count_override.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Verify per-call result limits through real HTTP requests."""

import asyncio
import json
import os
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import aiohttp
import pytest

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from tool.bocha_search import BoChaSearchTool, BoChaSearchToolConfig, BoChaSearchToolInputSchema # noqa: E402


@pytest.fixture
def request_counts(monkeypatch):
requests = []

class Handler(BaseHTTPRequestHandler):
def do_POST(self):
request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
requests.append((request["query"], request["count"]))
hits = [
{"name": str(index), "url": f"https://example.test/{index}", "snippet": "excerpt"}
for index in range(request["count"])
]
encoded = json.dumps({"data": {"webPages": {"value": hits}}}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)

def log_message(self, *args):
pass

server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
original_post = aiohttp.ClientSession.post

def local_post(self, url, **kwargs):
assert url == "https://api.bochaai.com/v1/web-search"
return original_post(self, f"http://127.0.0.1:{server.server_port}/search", **kwargs)

monkeypatch.setattr(aiohttp.ClientSession, "post", local_post)
try:
yield requests
finally:
server.shutdown()
server.server_close()
worker.join()


@pytest.mark.parametrize("mode", ["sync", "async"])
@pytest.mark.parametrize("count", [None, 1, 5])
def test_result_limit_is_sent_to_the_provider_for_each_query(request_counts, mode, count):
tool = BoChaSearchTool(BoChaSearchToolConfig(api_key="test", count=3))
params = BoChaSearchToolInputSchema(queries=["first", "second"])

result = tool.run(params, count=count) if mode == "sync" else asyncio.run(tool.run_async(params, count=count))

expected = 3 if count is None else count
assert sorted(request_counts) == [("first", expected), ("second", expected)]
assert [item.query for item in result.results] == ["first"] * expected + ["second"] * expected
assert tool.count == 3


def test_concurrent_overrides_do_not_change_the_default_or_each_other(request_counts):
tool = BoChaSearchTool(BoChaSearchToolConfig(api_key="test", count=3))

async def search():
return await asyncio.gather(
tool.run_async(BoChaSearchToolInputSchema(queries=["small"]), count=1),
tool.run_async(BoChaSearchToolInputSchema(queries=["large"]), count=5),
)

small, large = asyncio.run(search())
default = tool.run(BoChaSearchToolInputSchema(queries=["default"]))

assert sorted(request_counts) == [("default", 3), ("large", 5), ("small", 1)]
assert [len(result.results) for result in (small, large, default)] == [1, 5, 3]
6 changes: 3 additions & 3 deletions atomic-forge/tools/bocha_search/tool/bocha_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,15 @@ def __init__(self, config: BoChaSearchToolConfig = BoChaSearchToolConfig()):
self.include = config.include
self.exclude = config.exclude

async def _fetch_search_results(self, session: aiohttp.ClientSession, query: str) -> dict:
async def _fetch_search_results(self, session: aiohttp.ClientSession, query: str, count: Optional[int] = None) -> dict:
headers = {
"content-type": "application/json",
"Authorization": f"Bearer {self.api_key}",
}

json_data = {
"query": query,
"count": self.count,
"count": count or self.count,
"freshness": self.freshness,
}
if self.include is not None:
Expand Down Expand Up @@ -118,7 +118,7 @@ async def _fetch_search_results(self, session: aiohttp.ClientSession, query: str
async def run_async(self, params: BoChaSearchToolInputSchema, count: Optional[int] = None) -> BoChaSearchToolOutputSchema:
async with aiohttp.ClientSession() as session:
# Fetch results for all queries
tasks = [self._fetch_search_results(session, query) for query in params.queries]
tasks = [self._fetch_search_results(session, query, count) for query in params.queries]
raw_responses = await asyncio.gather(*tasks, return_exceptions=True)

# Process results for each query
Expand Down
8 changes: 8 additions & 0 deletions atomic-forge/tools/datetime_tool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ It uses the standard library only (`datetime`, `zoneinfo`) plus `tzdata` so the
- `diff_seconds`, `diff_human`: populated for `diff`.
- `error` (str, optional): set when something went wrong.

An input without an explicit UTC offset is interpreted in `timezone`. A local
time skipped by an offset change, such as `2026-03-08T02:30:00` in
`America/New_York`, returns an error instead of a timestamp for a different local
time. This check applies to both inputs of `diff` as well as `parse`, `convert`
and `shift`. An ambiguous time during a backward clock change keeps the first
occurrence (`fold=0`); include an explicit offset to select the other occurrence.
An explicit offset always defines the input instant independently of `timezone`.

## Usage

```python
Expand Down
Loading
Loading