local-web-search/PRD.md

259 lines
13 KiB
Markdown

# PRD — Local Web Search Stack (LWSS)
**Status:** Draft v4 (MVP-scoped, MCP-first, no in-stack LLM)
**Owner:** the maintainer
**Last updated:** 2026-07-05
---
## 1. Summary
A containerized, self-hosted stack that provides the capabilities of Serper
(search), Tavily (LLM-optimized retrieval), and Firecrawl (render + extract +
clean) **fully locally and privately**, purpose-built to feed a local LLM.
**The primary deliverable is an MCP server** exposing two tools: **web search**
and **URL fetch/render**. "Tavily drop-in" means **functional equivalence** — an
agent that would call Tavily's search tool gets the same capability from this
MCP server — not wire-level API compatibility with Tavily's REST schema.
**There is no LLM anywhere in the stack.** The consumer of the MCP server *is*
an LLM; any judgment calls (reranking results, deciding relevance, summarizing)
belong to that calling model. In-stack content cleaning is **purely mechanical**:
existing libraries strip HTML/CSS/JS/boilerplate from rendered pages and return
pure text/data. This keeps every layer deterministic, fast, and testable.
The stack is decomposed into single-responsibility Docker services so each layer
is independently deployable, testable, and debuggable. No third-party SaaS sits
in the request hot path.
### MVP framing
The end goal is **private + free + reliable + high-quality**. The **MVP
deliberately sequences reliability and quality first**, deferring the
privacy/cost-distribution work (SearXNG rotation, VPS obfuscation, config UI).
The MVP runs **entirely on one local machine** and must be **usable as a
functional Tavily replacement via MCP** — that is the acceptance bar.
## 2. Goals
- Provide a Serper/Tavily/Firecrawl-equivalent capability, exposed as an **MCP
server**, backed only by self-hostable/free components.
- **Reliability (MVP priority):** the pipeline doesn't fall over — retries,
timeouts, health checks, graceful partial results, caching. No single stage is
a hard dependency where degradation is possible.
- **Quality (MVP priority):** results return meaningful content, not render
failures or boilerplate. Mechanical extraction (Trafilatura + friends) strips
HTML/CSS/JS/nav/ads and returns clean text/data.
- **Deterministic pipeline:** no inference in-stack; every stage is mechanical,
reproducible, and cheap to run on modest hardware.
- **Modularity:** core layers (`searcher`, `renderer`, `extractor`) as separate
containers, each curl-able in isolation.
- **Debuggability:** structured logging, `/health` on every service, per-stage
timing/trace in orchestrator responses.
- **Privacy (end goal, deferred past MVP):** no commercial SaaS sees queries or
scraped content; query origin obfuscated by rotating across public +
self-hosted SearXNG instances on rotating VPSs. MVP runs a single local
instance (see §4).
- **Cost (end goal):** zero recurring SaaS cost; minimal external dependencies.
The one paid resource is compute (VPS subscription or self-owned hardware),
never per-call API fees.
## 3. Non-Goals (MVP)
- **Any in-stack LLM usage** — no reranking, no LLM cleaning, no summarization,
no structured/schema extraction. The calling LLM does all of that with the
clean text this stack returns.
- Answer synthesis / RAG generation — the calling LLM's job.
- Chunking — the consumer is an MCP client with a large-context model; full
cleaned text is returned as-is.
- Truly airgapped search or a self-built web index — search is open-web only.
- Anti-bot/CAPTCHA defeat, residential proxy pools. Partial coverage is accepted.
- Multi-tenant auth / user accounts. (A single shared bearer token gating the
orchestrator IS provided for exposed deployments — see §8 — but there are no
per-user accounts, scopes, or quotas.)
- SearXNG instance rotation / fan-out / VPS obfuscation and the config UI —
deferred past MVP (see §4, §10). MVP uses a single local instance.
## 4. Privacy & Threat Model
- **Boundary:** "no SaaS logs my queries/content against my identity," **not**
"airgapped." Queries still reach public search engines via SearXNG upstreams.
- **MVP:** a **single local self-hosted SearXNG** instance (a **required**
container). No rotation, fan-out, or obfuscation yet — but the searcher keeps
the **file-based instance-list abstraction** (§6.2) so rotation drops in later
with no refactor.
- **End goal (deferred, see §10):** searcher rotates across a configurable pool of
SearXNG instances (public + private self-hosted on rotating VPSs) to spread and
obscure query origin. Self-hosted instances are then treated as **external**
clients on VPSs.
## 5. Architecture
```
MCP client (agent / local LLM host)
│ MCP (streamable HTTP; stdio optional)
▼
┌────────────────────────┐
│ ORCHESTRATOR + MCP │ pipeline: search → render → extract/clean
│ (REST also exposed) │
└──┬────────┬────────┬───┘
▼ │ │
┌────────┐ ▼ ▼
│SEARCHER│ ┌─────────┐ ┌───────────┐
└───┬────┘ │RENDERER │ │ EXTRACTOR │
│ │Playwright│ │Trafilatura│ mechanical clean: strip HTML/CSS/JS/
SearXNG └─────────┘ │ + friends │ nav/ads/boilerplate → pure text/data
(local) ▲ └───────────┘
│
┌─────────┐
│ REDIS │ shared cache (search + rendered HTML + extracted text)
└─────────┘
```
**Containers (6):** orchestrator (REST + MCP), searcher, **searxng (required,
local)**, renderer, extractor, redis.
**Invariants:**
- Workers are stateless and independently testable.
- No inference anywhere in the stack; every stage is deterministic.
- Only shared state: Redis (cache + ephemeral health) and the searcher's
instance-list file.
- Orchestrator is the only externally exposed service (MCP + REST).
## 6. Service Specifications
### 6.1 Orchestrator (MCP server + API gateway)
- **Runtime:** Python / FastAPI + MCP SDK (single container; MCP tools call the
same internal pipeline functions as the REST routes).
- **Responsibility:** expose the MCP tools and REST API, run the pipeline,
aggregate per-stage traces, handle errors/partial results.
- **MCP tools (MVP primary interface):**
- `web_search` — Tavily-equivalent: `{query, max_results, include_content}` →
ranked results, each with `{url, title, snippet}` and (when
`include_content`) cleaned full text. Ranking is SearXNG's; the calling LLM
reranks/filters as it sees fit.
- `fetch_url` — `{url}` → render → extract → cleaned full text + metadata for
one page.
- **REST endpoints (same pipeline, for curl/debug and non-MCP clients):**
- `POST /search` — results only (Serper-like): `{query, options}` →
`{results: [{url,title,snippet,rank,source_instance}], trace}`.
- `POST /search/contents` — full flow (Tavily-like): search → render → extract
for top-N results → `{results:[{...,content}], trace}`.
- `POST /scrape` — per-URL: render → extract.
- `GET /health`.
- Every REST response includes a `trace` with per-stage timing, cache hit/miss,
and a `degraded` list naming any stage that fell back or partially failed.
MCP tool results carry a compact version of the same.
- Renders/extracts for the top-N results run **in parallel across URLs**.
### 6.2 Searcher
- **Runtime:** Python / FastAPI.
- **Responsibility:** query the SearXNG instance pool, normalize + dedup results,
track instance health.
- **Rotation (configurable):**
- `failover` (default, **MVP: only mode**): one healthy instance per query, fail
over on error. MVP points at a single local SearXNG, so this is effectively a
single-instance path — but the code reads the instance list from the file so
fan-out drops in later without refactor.
- `fanout` (**post-MVP**): query N instances in parallel, dedup by URL,
merge/reconcile rank. Fan-out width is a setting.
- **Health tracking (post-MVP):** per-instance success rate, latency, last-failure,
in Redis; used for weighted selection and surfaced in the UI.
- **Instance list persistence (MVP):** mounted YAML/JSON file (git-friendly,
hand-editable, survives rebuilds). Kept even in the single-instance MVP.
- **SearXNG config note:** the local instance must enable JSON output
(`formats: [html, json]` in `settings.yml`) and disable the built-in limiter
for internal use.
- **Output contract:** `{url, title, snippet, rank, source_instance}`.
### 6.3 Renderer
- **Runtime:** Node / raw Playwright (no external browser service).
- **Responsibility:** URL → fully-rendered HTML. Always renders.
- **Concurrency control:** single browser, pooled contexts, hard concurrency cap
+ request queue.
- **Wait policy:** configurable (`networkidle` / fixed delay / selector) with a
hard per-page timeout.
- **Caching:** rendered HTML cached in Redis keyed by URL with TTL.
- **Contract:** `url` → `{html, status, final_url, rendered_at}`.
### 6.4 Extractor (mechanical clean)
- **Runtime:** Python / Trafilatura as primary, with library fallbacks
(e.g. readability-lxml) when Trafilatura returns empty/thin content.
- **Responsibility:** rendered HTML → pure text/data. Strips all markup, CSS,
JS, nav, footers, cookie banners, ads, related-links boilerplate. Preserves
real content verbatim — including tables/lists/code as text — plus page
metadata (title, author, date where available). **No inference, no
summarization — deterministic library-based extraction only.**
- **Contract:** `{html, url}` → `{title, text, metadata, extractor_used}`.
### 6.5 Redis
- Shared cache: search results (short TTL), rendered HTML (medium TTL),
extracted text (medium TTL).
- Ephemeral instance-health stats.
## 7. Inter-Service Contract
- Transport: synchronous HTTP/REST between services (simplest to debug). Queue
deferred to a later version if batch crawling is needed.
- Each stage's output schema (Section 6) is the contract; the orchestrator owns
sequencing and error handling.
## 8. Cross-Cutting Requirements
- **Logging:** structured JSON on every service.
- **Health:** `GET /health` on every service; orchestrator aggregates.
- **Tracing:** per-stage timings + cache hit/miss + degraded-stage list returned
to caller.
- **Auth (exposed deployments):** optional single bearer token (`LWSS_API_KEY`)
required on all orchestrator MCP + REST requests; `/health` exempt. Empty key
disables auth (trusted/LAN only). Bind address configurable so the endpoint
can stay localhost-only behind a private tunnel (Tailscale/WireGuard/Cloudflared).
- **Config:** env-driven; instance list via mounted file.
- **Resource limits:** per-container CPU/RAM limits in compose; renderer
concurrency cap enforced.
- **Politeness:** per-domain rate limiting (Redis token bucket, enforced at the
renderer); caching to reduce upstream load/bans.
## 9. Limitations (accepted)
- Anti-bot walls (Cloudflare/DataDome/CAPTCHA) will block some pages → partial
coverage.
- "Always render" imposes a RAM/CPU/latency tax; mitigated by concurrency caps
+ Redis cache.
- Public SearXNG instances are flaky (rate limits, downtime, degraded results);
handled by health tracking + rotation (post-MVP).
- Mechanical extraction is imperfect: some boilerplate survives, some content
is lost on unusual layouts. Accepted — the calling LLM is robust to residual
noise, and library fallbacks cover the worst cases.
- No reranking in-stack: result order is SearXNG's; the calling LLM filters.
- No answer synthesis in-stack (by design).
## 10. Open Questions / Future (post-MVP)
- **Privacy/cost end goal:** multi-instance rotation, fan-out search, weighted
health-based selection, public + VPS instance pool, query-origin obfuscation,
and cost distribution across VPSs / friends' hardware.
- **Config UI:** instance CRUD + live health table; per-instance engine config +
authenticated private instances.
- Optional chunking of returned content if small-context consumers appear.
- Optional message queue for batch crawl jobs.
- Conditional rendering (fetch-first escalation) as an optimization if always-render
proves too heavy.
- Local private-corpus index (hybrid open-web + private).
## 11. Milestones (MVP: reliability + quality first)
1. **M1 — Scrape spine:** compose up; `/scrape` (render → extract) for one URL;
`/health` everywhere; Redis render cache. Proves the quality path.
2. **M2 — Extraction quality:** fallback extractors, empty/thin-content
detection, metadata capture; extracted-text caching.
3. **M3 — Search:** single local SearXNG + searcher (file-based, failover);
`/search` working.
4. **M4 — Tavily parity + MCP:** `/search/contents` wiring all stages end-to-end
(parallel per-URL) with traces + caching; MCP server exposing `web_search` +
`fetch_url`. **MVP acceptance: usable as a functional Tavily replacement
from an MCP client.**
5. **M5 — Hardening:** retries, per-domain rate limiting, resource limits,
timeouts, docs.
6. **Post-MVP:** rotation/fan-out, VPS obfuscation, config UI (see §10).