Skip to content

Testing

Pummelchen edited this page Sep 12, 2026 · 32 revisions

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


Running the suite

swift test
Property Value
Tests 368 (6 of them opt-in live tests, skipped without SEARCH_LIVE_TESTS and a usable key)
Runtime seconds; the default suite makes no external network calls
External network not required for the default suite
Warnings none, from a clean build

Local development on a synced folder

The commands above are correct for a normal checkout and are exactly what CI runs on a clean macos-26 runner. On a machine where the repository lives inside Dropbox, a plain swift build can still stall even after the evicted .build state has been cleared: swift-frontend blocks in pread at 0% CPU while fileproviderd saturates a core. Building to a scratch path outside the synced folder is the verified workaround:

swift build --build-tests --scratch-path ~/Library/Caches/MCPSearch/scratch
swift build -c release     --scratch-path ~/Library/Caches/MCPSearch/scratch
swift test                 --scratch-path ~/Library/Caches/MCPSearch/scratch
python3 scripts/mcp_smoke.py \
  "$(swift build -c release --scratch-path ~/Library/Caches/MCPSearch/scratch --show-bin-path)/SwiftWebSearchMCP"

.build is marked with the com.dropbox.ignored extended attribute so Dropbox leaves it alone and there are no dataless files under it. This is a local-environment workaround, not a repository requirement.


Hermeticity

End-to-end tests launch the real executable with a scrubbed environment: PATH plus their own explicit overrides, with every documented provider variable removed.

Without that scrub, an exported TAVILY_API_KEY — exactly what the installation guide tells a user to set — would make the stub-provider test contact the live vendor and fail. This was a real defect, so it is now verified rather than assumed. The same list covers DEEPSEEK_API_KEY and the other synthesis variables: the test asserting that web_answer degrades to results_only when unconfigured would otherwise make a live, billed request on any machine where the developer had exported a key. The suite is run with fake credentials present to prove it:

TAVILY_API_KEY=tvly-fake BRAVE_SEARCH_API_KEY=brave-fake swift test

CI runs the whole suite a second time with credentials present for the same reason.


Layout

File Covers
CoreUnitTests URL canonicalization, configuration parsing, durations, logging
FusionAndReliabilityTests RRF fusion, deduplication, diversity capping, per-result engine attribution, circuit breaker, rate limiter, cache
URLPolicyTests SSRF: schemes, loopback/private/metadata literals, embedded-IPv4 unwrapping, DNS resolution, IP classification
HTMLExtractorTests Readable-text extraction, boilerplate removal, scraper parsing, challenge detection
FetchBehaviorTests web_open's direct fetch path against a real socket: non-2xx is fetchFailed (not a provider network failure), a missing page keeps its own error, a success yields readable text, and a body already opening with the title is detected
FetchFallbackTests The fetch fallback chain above it: thin native text triggers the Jina Reader, the flag disables it, a blocked URL is never laundered through the reader, and the reader's own 429 / 401 / 403 / empty-body cases (11 tests)
HTTPClientTests Retry, Retry-After, idempotency, size limits, cancellation, Latin-1 fallback
HTTPTransportTests Drives the built executable on an ephemeral loopback port (7 tests) because HTTPMCPHost is internal to the executable target: /health body, initialize session, tools/list over SSE, missing-session and cross-origin refusals, oversized-body framing, unknown paths
ProviderContractTests Per-adapter contract and the shared failure taxonomy, now applied to every adapter rather than Tavily alone (27 → 51 tests)
AnswerSynthesizerTests Grounding rules, citation validation and renumbering, refusal handling, thinking-mode request shape, credential placement
SearchOrchestratorTests Selection, fan-out, refill, failover, timeouts, caching, domain filtering
StdioServerTests Real MCP handshake, tool schemas, tool calls, stdout purity, protocol-revision negotiation, the web_answer end-to-end path
SchemaCompatibilityTests Every advertised schema against the strictest client rules
TransportConfigurationTests CLI flag parsing, defaults and rejection of bad arguments, the transport-flag conflict
ErrorReportingTests Error attribution, explicit-provider fallback, post-error liveness, curated transport text that never echoes a request URL
ProbeTests NodeProbe (up/degraded/down, engine reporting, unresponsive_engines) and ProviderProbe (success, taxonomy, setup hints, cancellation) — 15 tests
MonitorTests Terminal layout, renderer output, model accumulation, probe-query rotation
MonitorOptionsTests mcps-mon CLI parsing, the probe interval floor and its explicit override
LiveProviderTests Opt-in. Real API calls; skipped unless SEARCH_LIVE_TESTS is set and a usable key exists

Transport tests use a real socket

LoopbackServer binds 127.0.0.1 and speaks HTTP/1.1, so retry, Retry-After, idempotency, size limits and cancellation are verified against real socket behaviour rather than against a mock that would encode the same assumptions as the client.


Provider contract

Every covered adapter must satisfy the same contract:

Expectation Assertion
Happy path Normalized results with valid URLs and ranks
401 / 403 Classified as authentication
429 Classified as rate_limited, with Retry-After parsed
5xx Classified as transient
Malformed body Clean malformed_response failure, never junk results
Cancellation Stops in-flight work
Credentials Never appear in logs or diagnostics

Every adapter now runs the shared taxonomy: Tavily, Brave, Mojeek, Exa, SearXNG, DuckDuckGo, Startpage, Open Web Search and Parallel Search MCP; the Jina Reader fetch fallback is covered separately in FetchFallbackTests. The only remaining gap is live coverage: LiveProviderTests still exercises Tavily alone, because it is the only key available, so the others are verified against stubs and the API notes rather than live. That gap is recorded under Known limitations on the Project Tracker.


Determinism

CircuitBreaker, RateLimiter and SearchCache take an injectable Clock, so cooldown and expiry tests advance a TestClock instead of sleeping. Timeout tests use short budgets rather than real waits. Fusion ordering is fully deterministic, so ranking assertions are stable.


End-to-end smoke test

python3 scripts/mcp_smoke.py

A dependency-free client that drives the built binary through a real handshake and asserts that:

  1. initialize succeeds and reports the expected server identity;
  2. tools/list advertises the four documented tools with usable object schemas. This is a presence check, not an exact-inventory assertion: the exact set is asserted in Swift by StdioServerTests, and SchemaCompatibilityTests lints every schema. The script prints — but does not fail on — any extra tool, so adding a tool cannot require editing two languages in lockstep. An extra tool is visible in the log. web_answer must expose no model-selection argument;
  3. web_search with no provider configured fails as an actionable tool error;
  4. every line written to stdout is valid JSON-RPC;
  5. diagnostics appear on stderr, never stdout.

Keeping a second exhaustive tool list in the script is exactly what let a fourth tool ship while it still demanded three, which turned CI red for an otherwise-correct release.

It keeps stdin open until all replies have been read, which is what the stdio transport contract requires.


CI

.github/workflows/ci.yml runs on macos-26 (Xcode 26.x, Swift 6.3) for every push and pull request to main:

  1. swift build --build-tests
  2. swift test
  3. swift build -c release
  4. python3 scripts/mcp_smoke.py — stdio handshake and stdout purity
  5. python3 scripts/mcp_smoke.py --http — starts the HTTP transport, waits for /health, drives a full stateful session over SSE, and checks that requests without a session, without SSE in Accept, and from a cross-origin page are refused
  6. swift test again with provider credentials present, proving hermeticity

The toolchain version is asserted before anything else, because a swift-tools-version: 6.3 manifest cannot even be parsed by an older Swift. Actions are pinned by commit SHA and the SwiftPM dependency graph is cached, so a run is reproducible and fits the runner budget. The end-to-end harnesses fail rather than skip when the server binary is missing, so a green run cannot mean the smoke tests never ran.


What CI has caught

Automation is not ceremony here: it found three defects that local builds had hidden.

  1. macos-14 ships Swift 5.10, which cannot parse the manifest.
  2. Package.swift declared a resource bundle for a directory git does not track, so a clean checkout failed to build while local builds passed.
  3. A trailing-defer warning that only a from-scratch build surfaced.

Live provider tests

SEARCH_LIVE_TESTS=1 swift test --filter LiveProviderTests

These call real APIs, so they are opt-in and skipped by default. They run only when SEARCH_LIVE_TESTS is set and a usable TAVILY_API_KEY is available, either in the environment or in a git-ignored config.env at the package root. A key alone is deliberately not enough: on a machine where one is routinely exported, that would make a plain swift test spend real credits. testLiveTestsRequireAnExplicitOptIn guards the rule, and testPlaceholderCredentialsAreNotTreatedAsUsable keeps CI's fake keys inert.

They are written to be frugal with a metered free tier: fast mode, small result counts, and most assertions made against a single live response. The authentication path is covered with a deliberately invalid key, which costs no credits. Coverage:

Test What it proves Cost
Invalid key A rejected credential is classified as authentication, not transient free
Search Live results normalize correctly, with scores and sequential ranks 1 credit
Recency A recency filter returns dated results, so the filter is verifiable 1 credit
Orchestration Full path with fusion and a cache hit on the repeat query 1 credit
Thorough mode The advanced-depth mapping reaches the live service 2 credits
Status A live key reports ready and the payload never contains the key free

This suite exists because it found a defect the stub tests could not: Tavily's published_date silently decoded to nil, since the DTO maps keys explicitly while the adapter had been applying .convertFromSnakeCase, which rewrites the key before those mappings are consulted.

Cross-client schema rules

SchemaCompatibilityTests walks every advertised input and output schema, via a real tools/list over stdio, and fails on any construct a mainstream client rejects: a missing additionalProperties: false, a property that is not also required, a banned keyword (format, default, oneOf, allOf, not), an object without properties, an array without items, a non-object root, or an over-long tool or property name. It also asserts that defaults are documented in descriptions rather than declared, and that every required-but-optional property is nullable so a strict client can omit it.

See Compatibility for why each rule exists.

Volume soak

python3 scripts/soak.py --queries 50 --mode balanced

Runs a list of realistic coding-agent queries through the real binary and reports per-query outcome, provider participation, failure categories and end-of-run provider health. It exists because quota and rate-limit behaviour only appears over a sustained run: a single-query test cannot show that an anonymous tier allows exactly 20 calls, or that a scraper's throttle turns into one error per query once it is exhausted.

It is opt-in, spends real credits, and is not part of CI. The measured limits are recorded on the Project Tracker.

Not covered here

Live provider behaviour is non-deterministic and free tiers are metered. A scheduled live smoke test on CI is still open work on the Project Tracker.


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

Clone this wiki locally