Web Search & Page Fetching
How web_search and url_fetch work, how to configure the search provider, and the safety rules both enforce.
Both are general tools in svc-ai/app/tools/ — auto-injected into every agent, and used directly by the __external_retrieval__ and __tool_retrieval__ graph nodes (see Agent Graph).
Finding sources for knowledge is the one consumer outside an agent run (October 2026, svc-ai/app/knowledge/discovery.py, Website knowledge): generative knowledge setup, the agent wizard's proposed sources, and Find sources on an empty source. It runs a model's planned searches through the same provider chain and domain policy (search.permitted_ranked, which the tool uses too), merges them a result at a time, and allows 3 per host rather than the tool's 2, since a regulator's site often holds several of the pages a source needs. A search the plan marked as looking for documents gets filetype:pdf appended by the server: Brave documents the operator, ddgs honours it only partly. Each search is a web_search tool invocation on svc-ai's trace. What they find is then probed with UrlFetcher.probe (the first 64 KB only: status, type, title), under the same SSRF and robots.txt rules as url_fetch.
Provider
web_search runs on the Brave Search API (official, keyed, independent index) with the keyless DuckDuckGo scraper (ddgs) as a fallback.
| Provider | When it is used | Notes |
|---|---|---|
duckduckgo | No key, or the primary provider failed or answered with nothing | ddgs scrapes public engines (by default DuckDuckGo, Brave, Mojeek, Wikipedia — see below). No SLA, results vary run to run, aggressively rate-limited from datacentre IPs, and every scraped engine sees the query |
Get a key at <https://api-dashboard.search.brave.com/app/keys> and set BRAVE_SEARCH_API_KEY. Without it the service logs a warning once at startup and degrades to DuckDuckGo.
Data sovereignty: every engine
ddgsscrapes receives the user's query, soWEB_SEARCH_DDGS_BACKENDdefaults to a narrow list —duckduckgo,brave,mojeek,wikipedia(privacy-oriented or independent indexes; Mojeek is UK-based). Google, Bing, Yahoo, Yandex and Grokipedia are excluded;autoopts back in to all of them. SetWEB_SEARCH_FALLBACK_ENABLED=falsewhere queries must never leave the contracted provider.The backend list is resolved per result category before each call, because
ddgsresponds to an unknown backend name by silently reverting toauto— i.e. re-enabling the excluded engines. Onlyduckduckgooffers news, image and video results, so those categories resolve to it; a list with no usable engine for a category fails the call rather than widening it.
Pipeline
WebSearchInput ──► SearchRequest site: scoping from `domains`, over-fetch
──► TTL cache identical queries across parallel nodes hit once
──► provider chain primary → fallback on error, unsupported type or an empty answer
──► (news, nothing) once more as a web search, same freshness
──► DomainPolicy safety, the tool's config, the workspace's rules, the call's domains
──► rank relevance-preserving, de-duplicated, host-diverse
──► formatted text Title/URL/Source/Published/Snippet blocks
When a search finds nothing, or fails (October 2026)
On 25 October 2026 CHAINR Bot answered "whats in the news" with "my searches did not return any results that matched the safety and domain criteria", and the person read it as a trust rule blocking news. No rule was in force. Brave had run out of credit, the ddgs fallback's news search found nothing, and the tool's empty-result text always said "matched the domain and safety criteria", whatever had happened. It also dropped the provider failure. The bot repeats tool output exactly, so it passed the claim on. Now:
The chain falls through on an empty answer, not only on an error (
WebSearchService.search). The one exception is the extra search scoped to trusted sources (empty_falls_through=False), because the first page has already answered. Each provider asked is recorded on the response (SearchResponse.attempts):answered,empty,failedwith aFailureReason(quota,rate_limited,auth,refused,timeout,network,unsupported,error; Brave's 402, and a 429 naming quota or credit, arequota), orskippedonce the call's time budget (WEB_SEARCH_CALL_BUDGET_S, 25 s) has passed. Fallback still needsWEB_SEARCH_FALLBACK_ENABLED.An empty answer is never cached. An engine out of credit would otherwise answer nothing for the whole TTL.
A news search that finds nothing is tried once more as a web search with the same freshness. Far more is indexed as pages than as news, and the fallback offers more engines for text than for news. It does not count against
max_calls. On that retry only, with a day or week window, a full calendar date is taken out of the query (search.without_date: "25 October 2026", "20-25 Oct 2026", "2026-10-25"), because the window already says when. The results say so in aNote:.The model is told to set
freshnessrather than write today's date into the query (thequeryfield, andNODE_EXTERNAL_RETRIEVAL). Both had said "include the year".Why each result was removed (
DomainPolicy.verdict):safety(scheme or HTTPS, shorteners, disposable TLDs),tool_config,rules_blocked,rules_not_allowedornot_requested.is_permittedis exactly apermittedverdict.The text says what happened. It is rendered from
_FAILURE_WORDS/_REMOVED_WORDS/_REMOVED_HINT, each checked against its enum at import, and never names an engine:nothing came back: what each engine said, then either "no workspace rule limits web search here", "the rules were in force but nothing came back for them to remove", or that the search was limited to the rules', the tool's or the call's domains and nothing there matched;
results came back but none could be used: how many each check removed, naming the rules' allowed list or the hosts they ruled out, and a hint only for a check the model can act on;
every engine failed:
Tool error: web search is unavailable — … No workspace rule was involved.A provider's own error text goes to the log, never to the model;results found: a note of how many the rules left out (never which).
Operators see each provider in
/health(web_search:configured,chain,brave_key(presence only), and per providerlast_answer_at,last_empty_at,last_failure {reason, at},failures_in_a_row). The record is per process (app/tools/web/health.py). Each attempt is also logged[web_search] provider=… type=… outcome=… reason=…, never with the query.
What each search did, kept as a report (October 2026)
The text above is what the model reads. Nothing else could read it back: no record said what a search returned, what was removed and why, or which engine failed, so the incident above could not be checked against anything. Now every call keeps a report beside its text (app/util/web_search_report.py, carried byte for byte by svc-ai and svc-core, tools/test_shared_modules.py):
What it holds: the search type asked (and
searched_aswhen an empty news search was tried as a web search), freshness, the call'soutcome(found,empty,unavailable,closed,refused,call_limit,misconfigured), every engine asked (primary/fallback, never its name, with its outcome andFailureReason), results returned and kept, what each check removed (removed, by verdict), what passed but did not fit, the hosts the workspace's Tools rules left out (left_out, with which way) and put first (put_first), at most ten each, whether the query was limited to the rules', the tool's or the call's domains (scoped_to), whether the extra trusted-sources search ran, the date taken out, and whether it came from the cache. Never a result's text or URL.The model never sees it. The tool returns
content_and_artifact(report.build): the report is the tool message's artifact, which no provider is sent. A call with plain arguments still gets the text alone.Where it travels: the stream's
tool_callframe (report), the batch response'scontext.web_searches, and the stored call (tool_invocations.report, svc-ai migration 32), served byGET /stats/turns/{id}. Under a withhold rule the stored call keeps no host (SearchReport.without_hosts), as it keeps no arguments or result.svc-core reads it from the raw stream before any frame is held back (
ai_client.UsageCapture.web_searches) and from the batch context, and makes of a turn's reports (services/web_search_summary.py):meta.web_searchon the answer (also the chat'sresponseframe andPromptResponse.web_search): the turn's outcome, strongest first —closed(no source left),limited(a rule narrowed a search),found,unavailable(no engine could answer),empty— the engines' failures by reason, what each check removed, and per Tools rule what it did (the hosts it left out or put first, counts only for a turn whose answer may yet be withheld);settled Tools rules: see
governance.md#the-tools-layer-where-an-agent-may-look-things-up;the decision record's "Web sources" section: each search (its query, what came back, what each engine said) and what each rule did.
fe-core draws it on the chat trace's tool row: "No results", "Unavailable", "2 left out by rules", and on opening the row what was kept and removed and what each engine said, with the tool's output preview (
util/webSearchReport.ts), and under the answer as one line (ChatPanel/WebSourcesNote.tsx,util/webSearchNotice.ts) when a Tools rule narrowed a search — naming the rule, its sites and what it left out, with Edit rule pre-filled for whoever may change it — or when nothing came back for no rule's reason ("No trust rule limited this search. The search engine was unavailable (its usage quota is used up).", with Ask again). A search that found what it looked for, or a rule that only put its sources first, shows nothing. Seegovernance.md#the-tools-layer-where-an-agent-may-look-things-up.
Ranking. The provider's own relevance order is the primary signal. Each result scores 1/(10 + rank) plus a small authority bonus (0.004 × tier, tiers in policy.py), so an authoritative domain can break a near-tie but never drag an irrelevant result to the top. Results are de-duplicated by canonical URL (tracking params and www. ignored) and capped at 2 per host, so a single site cannot crowd out independent corroboration.
Citations. Within a run each result block starts Cite as: [S#] — the id the answer cites it by, from the run's source registry (app/util/source_registry.py; a search hit and its later url_fetch share one) — then Title: and URL:. extract_citations parses those into the citation list, with the id, scored by domain tier (domain_quality_score / 4). Outside a run there is no id line. Changing that block format breaks citations and the web-search domain stats. See docs/guides/retrieval.md#every-source-has-an-id-and-chain-r-writes-the-sources-block-19-october-2026.
CHAINR Bot's preferred sources (October 2026)
The built-in agent's requests carry platform_sources (svc-core system_resources/web_sources.py: two wire services, seven public-service broadcaster domains and the ONS). svc-ai puts them in the run's config (app/tools/web/platform_sources.py, never a tool's config) and DomainPolicy.preferred() falls back to them when the workspace's Tools rules put no source first and allow every source; less what the tool or the rules block, nothing when the rules leave no source. They prefer, never restrict: ranked first on every search, one more site:-scoped search only on a news search whose first page had none (the clause for all ten fits Brave's 400 characters with a 200-character query), the request context's <web_sources set_by="platform"> line, and sources_set_by: platform on each report (SourcesSetBy). No other agent's request carries them. See chainr-bot.md.
An image search asks Wikimedia Commons first (29 October 2026)
The document tool and the prompts ask for open-licence images, Wikimedia Commons first, and refuse stock-photo previews. The engines' image verticals rarely return Commons: in scenario run 7, seven image searches (some naming "Wikimedia Commons") returned an Etsy listing, abc-people.com and a Guardian photo, and two of five images would not embed. So web_search with search_type: images also asks Commons' own search (app/tools/web/commons.py), beside the engines and at the same time:
What is asked: the query without what aimed an engine at Commons (
site:clauses, "Wikimedia Commons"), pictures only (filetype:bitmap|drawing, the keywordImageSource.find_missinguses), through the run's hardened fetcher and web policy, 8 s at most. A workspace whose Tools rules leave Commons out, or a call whosedomainsdo, never asks it (asks_commons).What comes back: each file's page (its author and licence), an
Image:link the document tool embeds (Special:FilePathat the document width), its size, and a snippet of its description, licence and author. Commons' files come first (pictures_first), then the engines' results that do not repeat one, tomax_results, with a note saying to link a picture by its Image address. When the engines cannot answer, Commons' files are the answer.The report counts them as returned and kept; it names no engine, and Commons is none.
Pinned by tests/tools/test_commons_images.py.
Configuration
Service-wide (env, svc-ai/app/common/settings.py):
| Variable | Default | Purpose | ||
|---|---|---|---|---|
WEB_SEARCH_PROVIDER | auto | auto \ | brave \ | duckduckgo |
WEB_SEARCH_FALLBACK_ENABLED | true | Retry on DuckDuckGo when the primary fails or answers with nothing | ||
WEB_SEARCH_DDGS_BACKEND | duckduckgo,brave,mojeek,wikipedia | Engines the fallback may scrape (auto = all) | ||
WEB_SEARCH_COUNTRY / WEB_SEARCH_LANGUAGE | GB / en | Result locale | ||
WEB_SEARCH_SAFESEARCH | moderate | off \ | moderate \ | strict |
WEB_SEARCH_TIMEOUT_S | 10 | Per-provider request timeout | ||
WEB_SEARCH_CALL_BUDGET_S | 25 | How long one search may spend across the chain before the providers not yet asked are skipped | ||
WEB_SEARCH_CACHE_TTL_S / WEB_SEARCH_CACHE_SIZE | 600 / 512 | In-process result cache (0 disables) | ||
URL_FETCH_MAX_BYTES | 10485760 | Download cap for url_fetch | ||
URL_FETCH_USER_AGENT | Mozilla/5.0 (compatible; CHAINR-Agent/1.0; +https://datachainr.com/bot) | Sent by url_fetch; point the URL at your own bot page |
Per-agent tool config (ToolConfig.config for builtin:web_search):
| Key | Default | Purpose |
|---|---|---|
max_calls | 5 | Calls per agent run / graph node |
allowed_domains | [] | Operator allowlist — results and url_fetch are confined to these domains and their subdomains |
blocked_domains | [] | Extra blocks on top of the built-ins |
require_https | true | Drop http:// results |
provider / fallback | env | Per-agent provider override |
country / language / safesearch | env | Per-agent locale override. country must be a two-letter code and language an ISO 639 code with an optional subtag (en, pt-br); anything else falls back to the deployment's value with a warning, because ddgs builds a host name from the language (https://{lang}.wikipedia.org). SearchRequest refuses any other value |
{
"tools": [
{"name": "web_search", "type": "builtin",
"config": {"max_results": 8, "allowed_domains": ["gov.uk", "legislation.gov.uk"]}}
]
}
An allowed_domains list does two things: the query is rewritten with a site: clause so the engine finds results on those domains (rather than filtering a generic result page down to nothing), and any result outside the list is dropped afterwards. url_fetch inherits the same allowlist, so the restriction cannot be bypassed by fetching a URL directly.
The workspace's Tools rules sit on top (governance.md#the-tools-layer-where-an-agent-may-look-things-up). Every web tool builds its policy with DomainPolicy.for_run, which reads the turn's policy (X-Web-Policy) at each check: a rule's "only these" narrows the allowlist further, its blocked sources join the blocklist, and its trusted sources are ranked above every other result. When the first page holds none of them, one more search scoped to them with site: runs, so a trusted source the engine ranked low is still found.
Deployment (SSM)
On deployed environments these live in SSM Parameter Store, declared in infra/terraform/envs/dev/app-secrets.tf under the ai group and hydrated by the Deploy stage into modules/dotenv/prod/ai.env (svc-ai's env_file).
Terraform creates each parameter with a CHANGE_ME placeholder and never writes real values; the deploy aborts while any parameter still holds that placeholder, so set all of them before the next deploy:
P=/chainr/dev/ai; R=eu-west-2
put() { aws ssm put-parameter --overwrite --region "$R" --type "$1" --name "$P/$2" --value "$3"; }
put SecureString BRAVE_SEARCH_API_KEY 'BSA...' # from the Brave API dashboard
put String WEB_SEARCH_PROVIDER 'auto'
put String WEB_SEARCH_FALLBACK_ENABLED 'true'
put String WEB_SEARCH_DDGS_BACKEND 'duckduckgo,brave,mojeek,wikipedia'
put String WEB_SEARCH_COUNTRY 'GB'
put String WEB_SEARCH_LANGUAGE 'en'
put String WEB_SEARCH_SAFESEARCH 'moderate'
put String URL_FETCH_USER_AGENT 'Mozilla/5.0 (compatible; CHAINR-Agent/1.0; +https://datachainr.com/bot)'
The values above are the code defaults; set them verbatim to keep current behaviour. There is no "unset" in this scheme — every declared parameter needs a value — so to run without Brave, set WEB_SEARCH_PROVIDER=duckduckgo and give the key a throwaway value rather than leaving it blank.
Tool parameters (what the model sees)
web_search(query, search_type, freshness, max_results, domains)
search_type—text(default),news,images,videos. Usenewsfor current events; results carry publish dates.freshness—day\|week\|month\|year. Provider codes and phrasings (pw,w,past_week) are accepted and normalised rather than rejected.domains— scopes the search, subject to the operator allowlist.
url_fetch(url, max_chars) returns the page's main content as Markdown — trafilatura strips navigation, cookie banners and comment rails, keeping headings, lists and tables, and recovers the title and publication date. PDFs and Office documents are converted via docling. Non-document types (images, archives) are refused with a clear message.
Safety
url_fetch treats every URL as attacker-influenced (search results and fetched pages can carry prompt injection). Each hop — including every redirect — must be https on port 443, carry no embedded credentials, pass the domain policy, and resolve exclusively to globally routable IPs. Docker service names (qdrant), localhost, *.local, private/loopback/link-local ranges and IPv4-mapped IPv6 forms are all refused, so a redirect cannot pull svc-ai into its own private networks. Responses are streamed against a byte cap. The check runs twice: before each hop, to say why a URL was refused, and as the connection opens (PublicOnlyTransport), which resolves the host once, checks every address and connects to a checked one by IP — so a DNS answer that changes in between (rebinding) never reaches a socket, and TLS still verifies the certificate against the host name. Both resolve the host as httpx encodes it (IDNA 2008), and NAT64 addresses are judged by the IPv4 they carry. Webhook tools are held to the same rule and never follow a redirect.
Both tools label their output as untrusted third-party content, and the research prompts instruct agents to extract facts from it without following instructions inside it.
url_fetch identifies itself honestly (CHAINR-Agent, with a contact URL) rather than impersonating Chrome, so site operators can recognise, contact or block it. Some publishers refuse self-declared bots and those fetches will fail — that is their call to make; the agent is told to move on to the next source.
Built-in blocklists (svc-ai/app/tools/web/policy.py) cover URL shorteners (which hide their destination) and disposable TLDs commonly used for malware. search_type="books" was removed: the underlying ddgs backend scraped Anna's Archive, a shadow library.
Extending
Add a provider by subclassing SearchProvider (svc-ai/app/tools/web/providers.py), normalising its payload into SearchResult, and registering it in build_provider_chain. Filtering, ranking, caching and formatting are provider-agnostic and need no changes.