# Architecture

The codebase is deliberately small. The catalog is 246 recipes; that fits in memory, so the project
has no database, no build step and no cache invalidation problem.

## Module map

```text
src/alhorno_mcp/
├── __init__.py        version and package metadata
├── __main__.py        python -m alhorno_mcp
├── cli.py             serve / sync commands and exit codes
├── constants.py       every product constant in one place
├── snapshot.py        fetch, validate, load and write recipes.json
├── models.py          pydantic models for upstream data and tool responses
├── records.py         immutable, indexed view of a recipe
├── dataset.py         the in-memory catalog: lookup, tags, relations
├── settings.py        environment variables and command line overrides
├── tools.py           the six tools, the Toolbox and the log decorator
├── server.py          MCP server wiring, transports and /health
├── urls.py            website URLs with URLSearchParams-compatible encoding
├── data/recipes.json  the packaged snapshot
└── search/
    ├── bitap.py       Fuse.js Bitap port, int32 masks, UTF-16 units
    ├── fuse.py        keys, weights, field norms and the search index
    ├── tokens.py      tokenization, stopwords and per-token thresholds
    ├── normalize.py   accent folding and normalized containment
    ├── ingredients.py the website's "Qué cocino" ranking
    └── service.py     the pipeline: filters, strategies, ordering, excerpts
```

`tools.py` is the only module that talks to MCP. `search/` is a port of the website's algorithm
with no MCP knowledge, which keeps it testable against the JavaScript goldens.

## Request flow

```text
MCP host
  │  JSON-RPC over stdio or Streamable HTTP
  ▼
MCPServer (server.py)
  │  tool dispatch, validated arguments
  ▼
Toolbox method (tools.py)
  │  validates tag/ingredients, builds links
  ▼
RecipeDataset (dataset.py) ──▶ RecipeSearch (search/service.py)
  │
  └─ pydantic response model ──▶ JSON-RPC result
```

Startup does the expensive work once:

```text
Settings.from_env()
  → load_recipes()      read 1 file, validate 246 recipes
  → RecipeDataset       index by slug and id, count tags, build the search index
  → MCPServer(...)      register six tools and /health
```

No per-request file reads, no locks, no connection pool.

## Design decisions

**In-memory catalog, no database.** A previous iteration built an SQLite catalog with FTS5. It was
removed: it needed a build step, a schema, a resolver, migrations and 20 files of plumbing to serve
246 rows. A tuple of records plus the Fuse port is faster to start, simpler to test and impossible
to get out of sync with the snapshot.

**One dependency for MCP.** `mcp==2.3.0` provides `MCPServer`, tool registration, schema
generation from type hints, transports and the rebinding protection. The project adds no web
framework of its own.

**Tools are methods on a frozen dataclass.** `Toolbox(dataset, base_url)` holds exactly the two
things a tool needs. Each tool is a plain method with type-annotated arguments, so the MCP schema is
generated from the signature and the docstring stays honest. `TOOL_SPECS` stores the name, title and
description in one table; `register_tools` only replays it.

**No functions defined inside functions.** Registration is a loop over `TOOL_SPECS`, not a nest of
closures. The one exception is the logging decorator, where the wrapper is the point.

**Constants in one place.** `constants.py` owns the product values: site base URL, page size, the
`Todas` sentinel, featured tags, snapshot limits, server name and instructions, transport
defaults, `MAX_RELATED` and the read-only annotations. Algorithm numbers — Bitap masks, Fuse
weights, token thresholds — stay beside the algorithm they belong to, because moving them away
would make that code harder to read.

**Read-only by contract.** Every tool carries `readOnlyHint: true` and `openWorldHint: false`. The
server never writes, never reaches the network at runtime, and holds no credentials.

**Links, not prose.** The server returns data and `site_url`/`site_search_url` values. Writing the
answer is the host model's job, and the recipe always links back to the author's site.

**Errors teach.** A missing recipe, an unknown tag or an unknown ingredient raises a tool error
with close matches (`Did you mean: ...?`), so the model can correct itself instead of reporting an
empty catalog.

## Validation strategy

The suite is end-to-end on purpose: five files, ~35 tests, and no unit test per helper.

| File | What it proves |
| --- | --- |
| `test_site_parity.py` | 100 recorded search cases and 12 ingredient cases return the same recipes as the website's own JavaScript. |
| `test_server.py` | The six tools answer through a real MCP client: paging, filters, errors, relations, random seeds. |
| `test_http.py` | The HTTP transport: handshake, tool call, `/health`, and a `421` for a foreign `Host`. |
| `test_data.py` | Snapshot validation: duplicates, missing fields, size limits, hidden recipes. |
| `test_cli.py` | `serve`/`sync` flags, exit codes and `--check`. |

Goldens are recorded, not hand-written: `tools/goldens.mjs` imports the website's
`src/utils/index.js` and `src/utils/queCocino.js` and writes the outputs together with hashes of
the dataset, the two scripts and the site commit. A website change is therefore a reviewable diff,
not a guess.

Coverage is gated at 80 % in CI. The remaining lines are mostly transport error paths and Bitap
fallbacks that an end-to-end suite cannot reach without duplicating the algorithm in a test.

## What this project is not

- Not a scraper: it reads a public JSON file, manually, with `sync`.
- Not a model: no prompts, no embeddings, no API keys.
- Not a database service: one process, one immutable snapshot, no persistence.
- Not the website: it exposes the catalog through MCP and links back for everything visual.
