webfetch

io.github.firish由 GitHub 帳號 firish 發布v0.1.3更新於 Oct 25, 2026

Self-hosted web search for LLM agents: search -> fetch -> rank pipeline with semantic caching

概覽

AI 產生的概覽

供 LLM 代理使用的自架網頁搜尋:多引擎檢索、本機抓取與擷取、重排序、壓縮以及語意快取。

可以做什麼
透過本機流程搜尋網頁,融合 DuckDuckGo、Brave、Serper 與 Tavily 的結果,支援新鮮度提示與略過快取的強制刷新,並可完整抓取單一引用頁面,已快取時立即回傳。把模型從其他來源取得的發現存入快取,並標記為未經驗證。查看執行狀態,包括哪些引擎與選用功能已啟用,並查看節省報告,依本次工作階段與累計統計已服務搜尋次數與估算省下的託管搜尋費用。
適用情境
適合代理需要近期網頁事實、但希望避免託管搜尋費用與大量檢索內容 token 成本的情境,並願意以較慢的首次搜尋換取本機快取與壓縮。也適合重複或改寫過的查詢,可由語意快取直接回傳。
執行需求
以 Python 套件形式在本機執行,可用 uvx 或 pip 安裝;完整安裝會引入 torch、Playwright、PDF 與表格擷取,精簡安裝則以降級模式執行。需要 Python,且在全新虛擬環境中要求 pip 24 或更新版本。需要存取搜尋引擎與網頁的網路。選用金鑰 BRAVE_API_KEY、SERPER_API_KEY 與 TAVILY_API_KEY 可增加引擎;DuckDuckGo 無需金鑰。WEBFETCH_PROVIDER 與 WEBFETCH_CACHE_DB 用於設定搜尋策略與快取位置。
安裝前請注意
選用金鑰 BRAVE_API_KEY、SERPER_API_KEY 與 TAVILY_API_KEY 從環境變數或工作目錄下的 .env 檔案讀取,各引擎免費額度是真實配額,可能用盡。快取為單一程序,每台機器只應執行一個伺服器。除非關閉,伺服器每個程序會向 pypi.org 發出一次更新檢查請求。save_finding 會存入模型提供的內容並標記為未經驗證。首次搜尋耗時 10-40 秒。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 webfetch,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

webfetch

Web search for LLM agents that you run yourself - up to 8x fewer input tokens and 3x lower cost than hosted web_search, at the same accuracy.

Hosted web-search tools charge $10 per thousand searches and then bill you again for every token of retrieved content they push into your context window. webfetch replaces them with a local pipeline - multi-engine search, page fetching and extraction, semantic reranking, sentence-level compression - exposed as a web_search tool your model calls like any other. And unlike every hosted tool and search API we surveyed, repeated and paraphrased queries are served from a semantic cache for free.

(Install with pip install webfetch-llm; the import name is webfetch.)

Jump to: The headline · What you get · Getting started · Check your setup · Full benchmark results · Claude Code · Agent loop · Savings report · How it works · Caveats

Same accuracy. A third of the cost. An eighth of the tokens.

One agent loop, one model, one judge, 50 SimpleQA questions. The only thing that changes between rows is the search tool:

search toolaccuracyinput tok/querycost/query
Anthropic hosted web_search96%17,408$0.108
webfetch (4-engine fusion)92%3,467$0.035
webfetch (DDG only, $0 in fees)84%3,623$0.026

Swap Opus for gpt-5.6-sol and the same webfetch tool hits 96% - hosted parity - at $0.040/query and 2,156 tokens: an eighth of what the hosted tool pushes into your context. Full results cover every arm we ran.

These numbers are the WORST case for webfetch - measured on an empty cache. In real use the gap widens on its own: repeats and rewords serve from cache for free, and the token advantage is paid again on every later turn that keeps search results in context. It adds up to receipts like this one, from an ordinary Claude Code session:

[savings report rendered in Claude Code]

Every claim in this README is generated by an eval harness that ships in this repo - the question sets, per-question records, judging protocol, and the negative results are all in evals/, and every table can be regenerated with one command. Don't take our word for the grading: evals/results/README.md maps every table row to the raw result file that produced it, down to per-question judge verdicts.

What you get

A search pipeline you own (4-engine RRF fusion, local extraction, sentence-level compression). Results come from reciprocal-rank fusion across DuckDuckGo, Brave, Serper, and Tavily - whichever of them you have keys for. DDG needs no key, so the tool works at literally zero cost out of the box; every key you add joins the fusion automatically. Pages are fetched and extracted locally (trafilatura, readability, newspaper4k, Playwright rendering for JS pages and 403 walls), chunked, ranked by a hybrid BM25 + bi-encoder cascade with a cross-encoder on top, then compressed to the sentences that answer the query - measured 50% fewer tokens at zero recall loss.

Caching nobody else has (exact + semantic matching, volatility-aware TTLs). Two layers in one sqlite file: page text by URL, ranked results by query. Identical queries hit an exact cache. Paraphrased queries hit a semantic cache - an embedding shortlist verified by an NLI cross-encoder, tuned eval-first for precision (zero wrong-target matches across every live run we have done). Cache lifetimes adapt to the query: prices and scores expire in 15 minutes, current-ish topics in 7 days, release notes and specs in 90 - classified by the calling model's hint or a local classifier. The model sees provenance on every cached result ([cache: semantic match to "...", 2h old, recent]) and can send force_fresh when it disagrees. No hosted tool or search API we surveyed offers any client-visible caching at all.

The model can maintain its own cache (save_finding, labeled UNVERIFIED, kill switch included). If a search comes up empty and the model answers from some other source (a hosted search fallback, say), it can call save_finding to store what it learned - marked model-contributed, served with an explicit UNVERIFIED warning and a force_fresh escape hatch, and aged out on the normal TTL rules. A kill switch (SAVE_FINDING_ENABLED = False) exists for deployments that never want unverified content cached.

Levers where models actually need them (full_results, fetch_url, freshness, force_fresh). full_results returns uncompressed excerpts for list and ranking queries (compression trims parallel list items - we measured it). fetch_url pulls one cited page in full, instantly if the pipeline has ever fetched it. freshness hints control cache lifetime; force_fresh bypasses it.

Receipts (session and lifetime, exact counters). Usage counters persist in the cache file; webfetch-savings (or the savings_report tool) shows what you did not pay hosted-search pricing for, split by this session and lifetime. Sample below.

Getting started

The one-liner (uv installs the package on first launch, @latest picks up new releases automatically):

claude mcp add webfetch -- uvx --from webfetch-llm@latest webfetch-mcp

Or manage the install yourself, two commands:

pip install "webfetch-llm[all]"claude mcp add webfetch -- webfetch-mcp

The slim install (webfetch-llm without extras) starts in seconds and runs degraded: BM25 ranking, exact-only cache, lexical compression. [all] pulls the semantic stack (torch - a few minutes once) plus Playwright, PDF, and table extraction; it is the configuration every benchmark number in this README was measured on. Needs pip >= 24 in fresh venvs (python -m pip install -U pip - older pips crash on a duplicated extra in our dependency tree). If you install into a venv, register the absolute path to webfetch-mcp or keep the venv active.

Keys are optional (DDG works with none) but improve recall - all the engines have free tiers:

cp .env.example .env    # fill in what you have

The console scripts and the MCP server pick up a .env from the directory they run in; exported env vars and --env flags on claude mcp add always take precedence. import webfetch as a library never reads .env - your process env is yours.

Check your setup

webfetch-status (or asking the model to call the status tool) answers "is my key being picked up, and what am I actually running?":

webfetch 0.1.3
search engines:  ddg      ready (no key needed)  brave    ready (BRAVE_API_KEY is set)  serper   off   (SERPER_API_KEY not set)  tavily   ready (TAVILY_API_KEY is set)
active provider: multi(ddg+brave+tavily) (RRF fusion)
optional features:  semantic ranking/cache/compression: on  JS-page rendering (playwright):     on  PDF extraction (pdfplumber):        OFF (pip install 'webfetch-llm[pdf]')  HTML tables (pandas+tabulate):      on  result compression:                 on (crossencoder)
cache: /Users/you/.webfetch/cache.db  5.4 MB, 70 lifetime searches (webfetch-savings for the receipt)

Key names only - values are never printed. Configuration is environment variables, read at server start:

variableeffect
BRAVE_API_KEY, SERPER_API_KEY, TAVILY_API_KEYeach key adds an engine to the fusion
WEBFETCH_PROVIDERmulti (default: fuse everything keyed), fallback (DDG serves, keyed engines catch its blocks), or a single engine name
WEBFETCH_CACHE_DBrelocate the cache file (default ~/.webfetch/cache.db)

With zero keys the default resolves to plain DDG; the status output says so honestly rather than calling it fusion. Library users can skip env entirely: Pipeline(search=get_search_adapter("fallback"), cache=...).

Full benchmark results

Every arm, same 50 SimpleQA questions, same judge, one same-day run (2026-07-14). Agent-loop arms share an identical loop; only the search tool differs. Costs include model tokens plus each provider's published per-search fees; ours include estimated engine fees.

search toolmodelaccuracyinput tok/qcost/q
OpenAI hosted web_searchgpt-5.6-sol100%10,027$0.066
webfetch (4-engine fusion)gpt-5.6-sol96%2,156$0.040
Anthropic hosted web_searchOpus 4.796%17,408$0.108
webfetch (4-engine fusion)Opus 4.792%3,467$0.035
Exa (search + contents)Opus 4.790%5,496$0.053
TavilyOpus 4.788%6,387$0.047
webfetch (DDG only)Opus 4.784%3,623$0.026
webfetch (4-engine fusion)Haiku 4.576%*3,021$0.031

* Haiku's failures were mostly re-searching past the turn cap, and its last few questions ran on a degraded engine set after we exhausted a free tier mid-benchmark. Treat it as a floor.

Notice the token column: webfetch results cost half the input tokens of the snippet APIs and a fifth to an eighth of the hosted tools - which is why our cost stays lowest even where per-search fees are similar.

On a second dataset of 27 questions about events from the two weeks before the run (hand-written, never published, so no vendor could have tuned on them), webfetch scored 100% with fusion and 100% with DDG alone; the hosted tools also scored 100%. Fresh events are not the hard part - the date-injection trap is.

Reproduce: python evals/run_e2e_eval.py --arms ours-multi,hosted - the harness, datasets, and per-question records are in evals/. The table above comes from e2e_eval_20260714_005531.json (plus the Haiku run and the fresh-events set - the full claim-to-file map is in evals/results/README.md). The questions are a seeded sample (seed 42) of OpenAI's public SimpleQA set, so build_datasets.py regenerates the identical 50 on your machine. One honest caveat: the live web moves between runs, and at n=50 the 96-vs-92 accuracy gap is 48-vs-46 correct - parity within noise. The token and cost columns are the mechanically stable result.

Using it in Claude Code / Claude Desktop

Fastest route in Claude Code - install it as a plugin, two slash commands (runs the same uv one-liner under the hood):

/plugin marketplace add firish/webfetch/plugin install webfetch@webfetch

Or register the MCP server yourself. Either way, a new session shows webfetch under /mcp with five tools: web_search, fetch_url, save_finding, status, and savings_report. Ask anything recent and watch the tool calls; ask the same thing reworded and the result comes back with a [cache: semantic match ...] header instead of a fresh search. First call in a session is slow (encoder warm-up plus real page fetches, 10-40s); cached calls are instant.

Toggle the server off per-session in /mcp; remove it with /plugin uninstall webfetch or claude mcp remove webfetch, matching how you installed it. Your cache and its receipt history live in ~/.webfetch/ and survive reinstalls. Run one server per machine - the semantic cache assumes a single process owns its file.

Update notice: the server makes one request to pypi.org per process to check for a newer release, surfaced as one line in savings_report output. UPDATE_CHECK_ENABLED = False in webfetch/config.py disables it; nothing else is ever sent anywhere.

Use it in your own agent loop

python
import timeimport anthropicfrom webfetch import WEB_SEARCH_TOOL, handle_web_search
client = anthropic.Anthropic()messages = [{"role": "user", "content": "What did the FOMC decide this week?"}]system = (f"Today's date is {time.strftime('%Y-%m-%d')}. "          "Use web_search for recent facts.")
while True:    response = client.messages.create(        model="claude-opus-4-7", max_tokens=2000, system=system,        tools=[WEB_SEARCH_TOOL], messages=messages,    )    if response.stop_reason != "tool_use":        break    messages.append({"role": "assistant", "content": response.content})    results = [{"type": "tool_result", "tool_use_id": b.id,                "content": handle_web_search(b.input)}               for b in response.content if b.type == "tool_use"]    messages.append({"role": "user", "content": results})

A complete version with prompt caching and adaptive thinking is in examples/agent_loop.py. The tool schema is provider-agnostic in spirit - OpenAI function calling needs only a mechanical reshape of the dict.

Put today's date in your system prompt. This is not optional. Models refuse to search for events they believe have not happened yet: on our fresh-events dataset, loops without the date declined to even call the tool on up to 10 of 27 questions ("Wimbledon 2026 hasn't taken place yet"). One line fixes it. Hosted search tools do this server-side, which is part of why nobody notices until they run their own tool.

handle_web_search never raises. Engine failures, empty results, and malformed input come back as readable strings the model can react to, because an exception mid-conversation kills the whole agent loop.

The savings report

Counters accumulate in the cache file as you search. Ask the model to run the report, or run webfetch-savings yourself. The MCP tool splits this session from lifetime, so you can see what one conversation saved:

[session vs lifetime savings]

That one-liner unpacked - a 30-search session on this machine:

this sessionlifetime
searches served3076
served from cache17 (57%) - 10 exact, 7 semantic-
search fees avoided~$0.30
content-token cost avoided~$2.56
estimated total avoided~$2.86~$7.21

Counters are exact; the dollar lines are estimates with the assumptions (hosted per-search fee, hosted tokens per call - both measured - and your model's token price) exposed as arguments to webfetch.savings_report().

How it works

query -> multi-engine search (RRF fusion, circuit breakers)      -> semantic query cache? serve with provenance header      -> fetch pages concurrently (page cache by URL)      -> extract (trafilatura -> readability -> newspaper4k -> playwright)      -> chunk (400 chars) -> BM25 + bi-encoder fusion -> cross-encoder top 5      -> compress to query-relevant sentences -> source-labeled result

Everything heavy is optional: without [rerank] you get BM25 ranking, exact-match caching, and lexical compression, with a logged warning instead of an ImportError. DDG deserves a special note: it fingerprint-blocks automated clients with silent empty responses. webfetch detects that (empty-with-peers in fusion, any empty in the fallback chain), benches the engine on a circuit breaker, and routes around it; the TLS side is handled by the ddgs dependency.

Design decisions and their measurements are documented as they happened in docs/architecture.md and docs/ROADMAP.md - including the negative results.

Caveats, honestly

  • Latency. A fresh search takes 10-40 seconds - real pages get fetched and ranked locally. Hosted search returns in ~10s, snippet APIs in ~6s. Cache hits are instant. If you need sub-second search and do not care about cost, this is not your tool.
  • The cache is single-process. One agent loop, one MCP server, or one notebook at a time; a shared team cache backend is on the roadmap.
  • Engine free tiers are real quotas. We exhausted Brave's monthly tier during benchmarking. The resilience layer degrades gracefully, but your recall degrades with it. Engine fees in the tables are estimates from published prices.
  • Answer quality depends on the model driving the tool - weak models formulate worse queries and re-search instead of reading (see the Haiku row).
  • Semantic-cache recall on cross-form rewords ("what did X add" vs "X new features") is partial: measured 6/10 on real pairs after tuning, because some paraphrase forms defeat every available verifier. Misses cost a re-search, never a wrong answer.

Benchmarks and data

Three eval layers, all in evals/: an offline matcher eval that picks the semantic-cache thresholds, a live retrieval eval (recall, tokens, cache diagnostics), and the end-to-end answer eval quoted above (SimpleQA protocol: normalized exact match, then an LLM judge). Datasets are built deterministically from SimpleQA (MIT), QQP/GLUE, and FreshQA (CC-BY-SA), with provenance sidecars next to each file. The fresh-events set was hand-written against verified news sources days before the benchmark ran, specifically so no model or vendor pipeline could have seen it.

License

MIT.

來源:README.md,提交 3399799

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.1.3最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分