Skip to content

Architecture

Pummelchen edited this page Sep 16, 2026 · 10 revisions

Home · Installation · Compatibility · Tools Reference · Architecture · Providers · Configuration · Reliability · Security · Self-Hosting · Monitor · Testing · Troubleshooting · Project Tracker


Overview

MCPSearch is layered so that no vendor detail can reach the protocol surface and no protocol detail can reach a provider.

MCP layer — Sources/SwiftWebSearchMCP
  main.swift          boot: configuration -> pipeline -> server -> stdio
  MCPServer.swift     Server construction, ListTools, CallTool routing
  ToolHandlers.swift  web_search / web_open / web_answer / web_search_status
  ToolSchemas.swift   JSON Schemas, argument parsing, result formatting
        |
        |  knows MCP; knows nothing about any vendor
        v
Core — Sources/WebSearchCore
  Search/     orchestrator, registry, fusion, cache, breakers, health, errors,
              AnswerSynthesizer (grounded generation, not a provider)
  Providers/  one adapter per vendor, all behind SearchProvider
  Fetch/      URL policy, HTTP fetcher, SwiftSoup extraction, Jina fallback
  Support/    HTTP client, retry policy, configuration, logging, clocks, JSON coding

The dependency arrow points one way. WebSearchCore does not import MCP, and no provider knows MCP exists. Adding or removing a vendor therefore touches one adapter file plus the factory.

All MCP coupling lives in the executable because the SDK's Value type is required to build tool results. Keeping it out of the core means the core is testable without a transport.

Source layout

Path Responsibility
Sources/SwiftWebSearchMCP/main.swift Configuration, composition, stdio boot
Sources/SwiftWebSearchMCP/MCPServer.swift Tool registration
Sources/SwiftWebSearchMCP/ToolHandlers.swift Argument validation, error mapping
Sources/WebSearchCore/Search/SearchOrchestrator.swift Fan-out, failover, deadlines
Sources/WebSearchCore/Search/ProviderRegistry.swift Eligibility and selection
Sources/WebSearchCore/Search/RankFusion.swift Deduplication and scoring
Sources/WebSearchCore/Search/AnswerSynthesizer.swift Grounded generation over fetched results
Sources/WebSearchCore/Providers/ One file per vendor
Sources/WebSearchCore/Fetch/ web_open pipeline and SSRF policy

Where synthesis sits, and why it is not a provider

web_answer composes two phases in ToolHandlers:

search phase   pipeline.orchestrator.search(...)   -> SearchResponse (real results)
                        |
                        v
answer phase   pipeline.synthesizer.synthesize(...) -> SynthesizedAnswer (citations)

The ordering is the safety property. The model is invoked only after results exist, and receives only those results, so it has nothing to answer from except fetched documents. That is what makes a model with no web access safe to put in the path.

It is deliberately not a SearchProvider:

  • It never appears in ProviderRegistry, so it cannot be selected, rate limited by the provider limiters, counted in fusion, or fused into results.
  • Its credentials are read by AppConfiguration but never influence provider order or the enabled set — asserted by a test.
  • It gets its own wall-clock budget, because generative traffic is a different traffic class from a search request and would otherwise be clipped by the 10 s default.

A synthesis failure is contained: the tool returns the search results with the reason in warnings and a status of results_only, rather than discarding documents because a summary could not be produced.


Lifecycle of a search

  1. Validate. ToolHandlers.webSearch turns arguments into a SearchRequest, clamping rather than rejecting where that is more useful.
  2. Select. ProviderRegistry.select chooses candidates. An explicit provider= takes the explicit path and fails loudly if that provider is unusable. Otherwise providers are chosen by tier — independent indexes, other direct providers, aggregators, then the scrapers — bounded by the mode (1 / 2 / 3).
  3. Check the cache. Keyed on query, filters, mode and provider set.
  4. Fan out concurrently under one wall-clock budget per mode. Each provider is gated first by its circuit breaker, then its rate limiter.
  5. Contain failures. Errors become ProviderFailure records instead of being thrown, so one bad provider cannot abort the fan-out.
  6. Optional extra coverage. In thorough mode only, if the fused set is thin, one aggregator that has not already been attempted may be called.
  7. Recover thin results. A provider skipped locally (open breaker or empty token bucket) does not waste its slot: the orchestrator refills from the next candidate in the same preference order. An upstream failure is never replaced. If the whole search comes back empty and a local throttle was the only cause, one last-resort pass waits out an affordable throttle (at most 6 s and half the remaining budget).
  8. Fuse. RankFusion deduplicates by canonical URL and scores with weighted RRF.
  9. Return compact text and structured content together.

Rank fusion

Provider relevance scores are not comparable across vendors, so fusion is rank-based:

score(result) = Σ  (providerWeight × familyWeight) / (k + rank)        k = 60

Every provider contributes with weight 1.0, and an aggregator is discounted (× 0.7) only when it demonstrably resells an index that another provider in the same run already owns. That is detected from the upstream engines the adapter reports: a SearXNG instance that internally queried Brave is discounted when Brave was also queried directly, while one covering engines nobody else covers is not.

Why there is no blanket provider weighting. The score is weight / (k + rank), so once a weight ratio exceeds the reachable rank ratio (k + maxRank) / (k + 1) — about 1.07 for five results at k = 60 — one provider's entire result list outranks another's regardless of relevance, and fusion degenerates into provider preference. This was measured live: with the previous per-provider weights (1.1 vs 0.8, a 1.375 ratio) Tavily's sixth result outranked Parallel's first by 1.82×, and the fused output was 100% Tavily even though Parallel ranked better on the query. Collapsing the registry weights to 1.0 made the same query interleave both providers and return on-topic results throughout.

Provider quality is instead expressed through signals that cannot override rank: corroboration (a URL reported by two providers outranks a single vote) and the per-domain diversity cap.

Final ordering is fully deterministic: score, then corroboration, then best rank, then canonical URL. That determinism is what makes fusion testable.

Deduplication

URLCanonicalizer produces the deduplication key: hostname lower-cased, fragment dropped, credentials stripped, default ports removed, tracking parameters (utm_*, gclid, fbclid, mc_cid, …) removed, trailing slash normalized and percent-encoding case-folded. Query parameters that identify a resource are preserved — the canonicalizer never sorts or deletes arbitrary parameters.

Diversity

A per-domain cap stops one host from filling the result set. The backfill pass that tops the list back up is subject to the same cap, so the cap cannot be defeated.

Per-result engine attribution and resold-provenance folding. SearchResult can carry the upstream engines a provider reports for that specific result, and both SearXNG and Open Web Search populate it. A resold page is then attributed to the index it came from: a URL returned by both Brave and an instance that queried Brave is folded into the Brave family and discounted, so it is one source rather than two independent confirmations. Folding requires per-result engines. An adapter that reports only a response-level engine list cannot be folded, and its whole response receives the aggregator discount instead. Either way the discount applies to the resold contribution, not to a provider's results in general — one instance can serve one page from Brave and another from an engine nobody else covers, and only the resold one is affected.


Concurrency model

Swift 6 strict concurrency throughout, with no @preconcurrency escape hatches in the core.

State Isolation
Orchestrator, health, breakers, limiters, cache, fetcher actor
Requests, responses, results, failures Sendable value types
URLSession-backed clients immutable, @unchecked Sendable

HTTP clients are deliberately not actors. URLSession is internally thread-safe, so wrapping it in an actor would serialize concurrent provider calls and defeat the fan-out.

Cancellation propagates: a cancelled tool call cancels its URLSession tasks, so an abandoned search does not keep sockets open.


Extension points

To change… Touch
Add or remove a provider one file in Providers/ plus SearchPipelineFactory
Change scoring RankFusion.Configuration
Change timeouts or retry policy AppConfiguration / HTTPPolicy
Add a tool ToolSchemas, ToolHandlers, MCPServerFactory
Change the answering model DEEPSEEK_MODEL; the prompt lives in AnswerSynthesizer.systemPrompt

See Providers for the adapter contract.


Home · Installation · Compatibility · Tools Reference · Architecture · Providers · Configuration · Reliability · Security · Testing · Troubleshooting · Project Tracker

Clone this wiki locally