PRD v4: MCP-first, no in-stack LLM, mechanical extraction only

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
User 2026-07-05 21:57:46 -07:00
parent 6d7e401188
commit 55317f3f75

225
PRD.md
View file

@ -1,6 +1,6 @@
# PRD — Local Web Search Stack (LWSS) # PRD — Local Web Search Stack (LWSS)
**Status:** Draft v2 (MVP-scoped) **Status:** Draft v4 (MVP-scoped, MCP-first, no in-stack LLM)
**Owner:** Neil **Owner:** Neil
**Last updated:** 2026-07-05 **Last updated:** 2026-07-05
@ -12,6 +12,17 @@ A containerized, self-hosted stack that provides the capabilities of Serper
(search), Tavily (LLM-optimized retrieval), and Firecrawl (render + extract + (search), Tavily (LLM-optimized retrieval), and Firecrawl (render + extract +
clean) **fully locally and privately**, purpose-built to feed a local LLM. 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 The stack is decomposed into single-responsibility Docker services so each layer
is independently deployable, testable, and debuggable. No third-party SaaS sits is independently deployable, testable, and debuggable. No third-party SaaS sits
in the request hot path. in the request hot path.
@ -21,28 +32,23 @@ in the request hot path.
The end goal is **private + free + reliable + high-quality**. The **MVP The end goal is **private + free + reliable + high-quality**. The **MVP
deliberately sequences reliability and quality first**, deferring the deliberately sequences reliability and quality first**, deferring the
privacy/cost-distribution work (SearXNG rotation, VPS obfuscation, config UI). privacy/cost-distribution work (SearXNG rotation, VPS obfuscation, config UI).
The MVP runs **entirely on one local machine** and must be **usable as a drop-in The MVP runs **entirely on one local machine** and must be **usable as a
replacement for Tavily API calls** — that is the acceptance bar. functional Tavily replacement via MCP** — that is the acceptance bar.
Quality is raised by an **LLM stage** (reranking candidate results before render,
and cleaning extracted content after), which is the only stage that needs the
good (single) GPU machine. Inference targets a **configurable OpenAI-compatible
endpoint**, so future remote deployments of the stack point *just that portion*
at the GPU machine (exposed via Tailscale/Cloudflared) while everything else runs
on modest hardware.
## 2. Goals ## 2. Goals
- Provide a Serper/Tavily/Firecrawl-equivalent API backed only by - Provide a Serper/Tavily/Firecrawl-equivalent capability, exposed as an **MCP
self-hostable/free components. server**, backed only by self-hostable/free components.
- **Reliability (MVP priority):** the pipeline doesn't fall over — retries, - **Reliability (MVP priority):** the pipeline doesn't fall over — retries,
timeouts, health checks, graceful partial results, caching. No single stage timeouts, health checks, graceful partial results, caching. No single stage is
(including the LLM endpoint) is a hard dependency; degrade instead of fail. a hard dependency where degradation is possible.
- **Quality (MVP priority):** results return meaningful content, not render - **Quality (MVP priority):** results return meaningful content, not render
failures or boilerplate. LLM reranking filters junk before render; LLM cleaning failures or boilerplate. Mechanical extraction (Trafilatura + friends) strips
guarantees high-quality markdown after extraction. HTML/CSS/JS/nav/ads and returns clean text/data.
- **Modularity:** core layers (`searcher`, `renderer`, `extractor`, `llm`, - **Deterministic pipeline:** no inference in-stack; every stage is mechanical,
`formatter`) as separate containers, each curl-able in isolation. 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 - **Debuggability:** structured logging, `/health` on every service, per-stage
timing/trace in orchestrator responses. timing/trace in orchestrator responses.
- **Privacy (end goal, deferred past MVP):** no commercial SaaS sees queries or - **Privacy (end goal, deferred past MVP):** no commercial SaaS sees queries or
@ -55,10 +61,12 @@ on modest hardware.
## 3. Non-Goals (MVP) ## 3. Non-Goals (MVP)
- Answer synthesis / RAG generation — that is the downstream local LLM's job. - **Any in-stack LLM usage** — no reranking, no LLM cleaning, no summarization,
- **LLM-powered _structured/schema_ extraction** (Firecrawl `/extract` structured no structured/schema extraction. The calling LLM does all of that with the
mode). Note: LLM **reranking** and **content cleaning** ARE in scope (see §6.6); clean text this stack returns.
only structured-schema output is deferred. - 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. - 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. - Anti-bot/CAPTCHA defeat, residential proxy pools. Partial coverage is accepted.
- Multi-tenant auth / user accounts. - Multi-tenant auth / user accounts.
@ -69,7 +77,7 @@ on modest hardware.
- **Boundary:** "no SaaS logs my queries/content against my identity," **not** - **Boundary:** "no SaaS logs my queries/content against my identity," **not**
"airgapped." Queries still reach public search engines via SearXNG upstreams. "airgapped." Queries still reach public search engines via SearXNG upstreams.
- **MVP:** a **single local self-hosted SearXNG** instance (now a **required** - **MVP:** a **single local self-hosted SearXNG** instance (a **required**
container). No rotation, fan-out, or obfuscation yet — but the searcher keeps 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 the **file-based instance-list abstraction** (§6.2) so rotation drops in later
with no refactor. with no refactor.
@ -81,61 +89,66 @@ on modest hardware.
## 5. Architecture ## 5. Architecture
``` ```
client / local LLM MCP client (agent / local LLM host)
│ │ MCP (streamable HTTP; stdio optional)
▼ ▼
┌───────────────┐ public API (only exposed port) ┌────────────────────────┐
│ ORCHESTRATOR │ search → LLM rerank → render → extract → LLM clean → format │ ORCHESTRATOR + MCP │ pipeline: search → render → extract/clean
└─┬──┬──┬──┬──┬─┘ │ (REST also exposed) │
│ │ │ │ └──────────────────────────────────────┐ └──┬────────┬────────┬───┘
▼ │ │ │ ▼ ▼ │ │
┌────────┐│ │ │ ┌───────────┐ ┌────────┐ ▼ ▼
│SEARCHER││ │ │ │ FORMATTER │ │SEARCHER│ ┌─────────┐ ┌───────────┐
└───┬────┘│ │ │ │ md+chunk │ └───┬────┘ │RENDERER │ │ EXTRACTOR │
│ ▼ │ ▼ └───────────┘ │ │Playwright│ │Trafilatura│ mechanical clean: strip HTML/CSS/JS/
SearXNG ┌─────────┐ ┌───────────┐ SearXNG └─────────┘ │ + friends │ nav/ads/boilerplate → pure text/data
(local) │RENDERER │ │ EXTRACTOR │ ┌──────────────────────────┐ (local) ▲ └───────────┘
│Playwright│ │Trafilatura│ │ LLM │ │
└─────────┘ └───────────┘ │ /rerank + /clean │ ┌─────────┐
▲ │ OpenAI-compatible client │ │ REDIS │ shared cache (search + rendered HTML + extracted text)
│ │ (configurable endpoint) │
┌─────────┐ └──────────────────────────┘
│ REDIS │ shared cache (search + rendered HTML)
└─────────┘ └─────────┘
``` ```
**Containers (8):** orchestrator, searcher, **searxng (required, local)**, **Containers (6):** orchestrator (REST + MCP), searcher, **searxng (required,
renderer, extractor, **llm**, formatter, redis. local)**, renderer, extractor, redis.
**Invariants:** **Invariants:**
- Workers are stateless and independently testable. - 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 - Only shared state: Redis (cache + ephemeral health) and the searcher's
instance-list file. instance-list file.
- Orchestrator is the only externally exposed service. - Orchestrator is the only externally exposed service (MCP + REST).
- **The LLM is the only inference-heavy stage; its endpoint is independently
repointable** (env-configured OpenAI-compatible base URL), and the pipeline
degrades gracefully if it is unreachable.
## 6. Service Specifications ## 6. Service Specifications
### 6.1 Orchestrator (API Gateway) ### 6.1 Orchestrator (MCP server + API gateway)
- **Runtime:** Python / FastAPI. - **Runtime:** Python / FastAPI + MCP SDK (single container; MCP tools call the
- **Responsibility:** expose the public API, run the pipeline, aggregate same internal pipeline functions as the REST routes).
per-stage traces, handle errors/partial results. - **Responsibility:** expose the MCP tools and REST API, run the pipeline,
- **Endpoints:** 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}` → - `POST /search` — results only (Serper-like): `{query, options}` →
`{results: [{url,title,snippet,rank,source_instance}], trace}`. `{results: [{url,title,snippet,rank,source_instance}], trace}`.
- `POST /search/contents` — **(MVP primary)** full flow (Tavily-like): search → - `POST /search/contents` — full flow (Tavily-like): search → render → extract
**LLM rerank** → render → extract → **LLM clean** → format for top-N results → for top-N results → `{results:[{...,content}], trace}`.
`{results:[{...,markdown,chunks}], trace}`. - `POST /scrape` — per-URL: render → extract.
- `POST /scrape` — per-URL: render → extract → format for a given URL.
- `GET /health`. - `GET /health`.
- Every response includes a `trace` with per-stage timing and cache hit/miss. - 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 ### 6.2 Searcher
- **Runtime:** Python / FastAPI (or Node — TBD at impl; Python default). - **Runtime:** Python / FastAPI.
- **Responsibility:** query the SearXNG instance pool, normalize + dedup results, - **Responsibility:** query the SearXNG instance pool, normalize + dedup results,
track instance health, serve the config UI. track instance health.
- **Rotation (configurable):** - **Rotation (configurable):**
- `failover` (default, **MVP: only mode**): one healthy instance per query, fail - `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 over on error. MVP points at a single local SearXNG, so this is effectively a
@ -147,8 +160,9 @@ renderer, extractor, **llm**, formatter, redis.
in Redis; used for weighted selection and surfaced in the UI. in Redis; used for weighted selection and surfaced in the UI.
- **Instance list persistence (MVP):** mounted YAML/JSON file (git-friendly, - **Instance list persistence (MVP):** mounted YAML/JSON file (git-friendly,
hand-editable, survives rebuilds). Kept even in the single-instance MVP. hand-editable, survives rebuilds). Kept even in the single-instance MVP.
- **Config UI (post-MVP):** CRUD instance list + live health/status table - **SearXNG config note:** the local instance must enable JSON output
(last check, success rate, latency). Per-instance engine config / auth later still. (`formats: [html, json]` in `settings.yml`) and disable the built-in limiter
for internal use.
- **Output contract:** `{url, title, snippet, rank, source_instance}`. - **Output contract:** `{url, title, snippet, rank, source_instance}`.
### 6.3 Renderer ### 6.3 Renderer
@ -161,42 +175,19 @@ renderer, extractor, **llm**, formatter, redis.
- **Caching:** rendered HTML cached in Redis keyed by URL with TTL. - **Caching:** rendered HTML cached in Redis keyed by URL with TTL.
- **Contract:** `url` → `{html, status, final_url, rendered_at}`. - **Contract:** `url` → `{html, status, final_url, rendered_at}`.
### 6.4 Extractor ### 6.4 Extractor (mechanical clean)
- **Runtime:** Python / Trafilatura. - **Runtime:** Python / Trafilatura as primary, with library fallbacks
- **Responsibility:** HTML → main content + metadata (boilerplate removal). (e.g. readability-lxml) when Trafilatura returns empty/thin content.
- **Contract:** `{html, url}` → `{title, text, main_html, metadata}`. - **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 Formatter ### 6.5 Redis
- **Runtime:** Python. - Shared cache: search results (short TTL), rendered HTML (medium TTL),
- **Responsibility:** clean content → LLM-ready Markdown + chunks. extracted text (medium TTL).
- **Chunking:** token-based, configurable size, with overlap; tuned for local LLM
context windows. Returns **both** full markdown and chunks.
- **Contract:** `{title, text, main_html, metadata}` →
`{markdown, chunks: [{text, index, tokens}]}`.
### 6.6 LLM service
- **Runtime:** Python / FastAPI, thin **OpenAI-compatible client** (works with
Ollama, llama.cpp, vLLM, LM Studio, etc.).
- **Responsibility:** the only inference-heavy stage; owns all prompt templates,
endpoint config, retry/timeout behavior. Two jobs:
- `POST /rerank` — `{query, candidates:[{url,title,snippet,rank}]}` →
`{ranked:[{url,relevance,keep}]}`. Filters junk / off-topic results **before**
render so renders aren't wasted. Runs after search, before render.
- `POST /clean` — `{title, text, main_html, metadata, query?}` →
`{clean_text}`. Polishes/repairs extracted content into high-quality,
boilerplate-free text. Runs after extract, before format.
- **Config (env-driven):** `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `LLM_MODEL`,
per-endpoint timeout + max retries. MVP defaults to `localhost`; remote stack
deployments override `OPENAI_BASE_URL` to reach the GPU machine via
Tailscale/Cloudflared. **This is the only container a remote deployment repoints.**
- **Graceful degradation (reliability):** if the endpoint is unreachable or times
out, `/rerank` falls back to the original SearXNG rank (keep all) and `/clean`
falls back to the Trafilatura text unchanged. The pipeline never hard-fails on
the LLM.
- `GET /health` reports endpoint reachability + model.
### 6.7 Redis
- Shared cache: search results (short TTL), rendered HTML (medium TTL).
- Ephemeral instance-health stats. - Ephemeral instance-health stats.
## 7. Inter-Service Contract ## 7. Inter-Service Contract
@ -210,13 +201,13 @@ renderer, extractor, **llm**, formatter, redis.
- **Logging:** structured JSON on every service. - **Logging:** structured JSON on every service.
- **Health:** `GET /health` on every service; orchestrator aggregates. - **Health:** `GET /health` on every service; orchestrator aggregates.
- **Tracing:** per-stage timings + cache hit/miss returned to caller. - **Tracing:** per-stage timings + cache hit/miss + degraded-stage list returned
- **Config:** env-driven; instance list via mounted file. The LLM inference to caller.
endpoint (`OPENAI_BASE_URL` / `LLM_MODEL`) is independently repointable so the - **Config:** env-driven; instance list via mounted file.
inference-heavy stage can live on separate hardware from the rest of the stack.
- **Resource limits:** per-container CPU/RAM limits in compose; renderer - **Resource limits:** per-container CPU/RAM limits in compose; renderer
concurrency cap enforced. concurrency cap enforced.
- **Politeness:** per-domain rate limiting; caching to reduce upstream load/bans. - **Politeness:** per-domain rate limiting (Redis token bucket, enforced at the
renderer); caching to reduce upstream load/bans.
## 9. Limitations (accepted) ## 9. Limitations (accepted)
@ -225,7 +216,11 @@ renderer, extractor, **llm**, formatter, redis.
- "Always render" imposes a RAM/CPU/latency tax; mitigated by concurrency caps - "Always render" imposes a RAM/CPU/latency tax; mitigated by concurrency caps
+ Redis cache. + Redis cache.
- Public SearXNG instances are flaky (rate limits, downtime, degraded results); - Public SearXNG instances are flaky (rate limits, downtime, degraded results);
handled by health tracking + rotation. 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). - No answer synthesis in-stack (by design).
## 10. Open Questions / Future (post-MVP) ## 10. Open Questions / Future (post-MVP)
@ -235,22 +230,24 @@ renderer, extractor, **llm**, formatter, redis.
and cost distribution across VPSs / friends' hardware. and cost distribution across VPSs / friends' hardware.
- **Config UI:** instance CRUD + live health table; per-instance engine config + - **Config UI:** instance CRUD + live health table; per-instance engine config +
authenticated private instances. authenticated private instances.
- Optional chunking of returned content if small-context consumers appear.
- Optional message queue for batch crawl jobs. - Optional message queue for batch crawl jobs.
- LLM-powered **structured/schema** extraction endpoint.
- Conditional rendering (fetch-first escalation) as an optimization if always-render - Conditional rendering (fetch-first escalation) as an optimization if always-render
proves too heavy. proves too heavy.
- Local private-corpus index (hybrid open-web + private). - Local private-corpus index (hybrid open-web + private).
## 11. Milestones (MVP: reliability + quality first) ## 11. Milestones (MVP: reliability + quality first)
1. **M1 — Scrape spine:** compose up; `/scrape` (render → extract → format for one 1. **M1 — Scrape spine:** compose up; `/scrape` (render → extract) for one URL;
URL); `/health` everywhere; Redis render cache. Proves the quality path. `/health` everywhere; Redis render cache. Proves the quality path.
2. **M2 — LLM clean:** add LLM service `/clean`; wire into `/scrape`; configurable 2. **M2 — Extraction quality:** fallback extractors, empty/thin-content
OpenAI-compatible endpoint; graceful fallback to Trafilatura-only. detection, metadata capture; extracted-text caching.
3. **M3 — Search + rerank:** single local SearXNG + searcher (file-based, failover); 3. **M3 — Search:** single local SearXNG + searcher (file-based, failover);
LLM `/rerank`; `/search` working. `/search` working.
4. **M4 — Tavily parity:** `/search/contents` wiring all stages end-to-end with 4. **M4 — Tavily parity + MCP:** `/search/contents` wiring all stages end-to-end
per-stage traces + caching. **MVP acceptance: usable as a Tavily drop-in.** (parallel per-URL) with traces + caching; MCP server exposing `web_search` +
5. **M5 — Hardening:** retries, per-domain rate limiting, resource limits, timeouts, `fetch_url`. **MVP acceptance: usable as a functional Tavily replacement
docs. 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). 6. **Post-MVP:** rotation/fan-out, VPS obfuscation, config UI (see §10).