Skip to main content
Glama
README.md
# pf2e-mcp

[![CI](https://github.com/Viroide/pf2e-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/Viroide/pf2e-mcp/actions/workflows/ci.yml)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)

An MCP server for **Pathfinder 2e** rules content from
[Archives of Nethys](https://2e.aonprd.com). It reads the public AoN
Elasticsearch index directly, so results include full rules text, not scraped
fragments.

The design follows [jhheider/wayfinder](https://github.com/jhheider/wayfinder) —
an excellent Rust AoN server — and fixes the edge cases found while evaluating
it. This is an independent Python implementation, not a fork.

## What it does

- **Search** 30,000+ current entries by text, category, traits, level, source,
  rarity, and arbitrary indexed fields.
- **Read** a full entry by name, AoN URL, or stable document id.
- **Disambiguate** same-named entries (spell vs. feat vs. action) and list the
  alternatives.
- **Follow the Remaster**: replaced legacy entries are hidden in favour of their
  remastered versions. Pass `legacy=true` for the pre-remaster version.
- **Hides reprints** using AoN's own `exclude_from_search` flag. This is why
  `get_content(name="Interact")` resolves to the real action instead of one of
  743 near-duplicates.
- **Deduplicates** sub-documents that render as the same row (`Staff of Fire`).
- **Works offline** via a local 24-hour response cache.

Content is read-only. The server never writes to Archives of Nethys.

## Tools

| Tool | Purpose |
| --- | --- |
| `search_content` | Search with text and filters. Returns names, levels, traits, summaries, and URLs. |
| `get_content` | Fetch one entry's full rules text by `name`, `url`, or `doc_id`. |
| `get_creature` | Convenience lookup for a creature or NPC statblock. |
| `get_creature_stats` | A creature's numeric statblock as structured data, plus a compact text summary. |
| `list_categories` | Every category and its entry count. |
| `list_sources` | Source books by entry count. |
| `list_traits` | Traits by entry count. |

### `search_content`

```text
search_content(
  query: str | None,            # free text over names, summaries, rules text
  category: str | None,         # spell, feat, creature, equipment, ...
  traits: list[str] | None,     # requires ALL of them, case-insensitive
  filters: dict[str, str|int] | None,  # exact extra fields
  min_level: int | None,
  max_level: int | None,
  source: str | None,           # phrase match; "Player Core" also matches "Player Core 2"
  rarity: str | None,           # common | uncommon | rare | unique
  legacy: bool = false,         # pre-remaster versions
  sort: str = "relevance",      # relevance | level | name
  limit: int = 10,              # capped at 50
  offset: int = 0,
  cursor: str | None = None     # resume from a previous next_cursor
)
```

Examples:

```text
search_content(query="fireball", category="spell")
search_content(category="creature", filters={"size": "Small"}, min_level=1, max_level=3)
search_content(category="feat", traits=["fighter"], source="Player Core", limit=20)
search_content(category="spell", filters={"actions_number": 4}, min_level=3, max_level=3)
```

Useful `filters` fields that are actually indexed: `size`, `pfs`, `alignment`,
`actions_number`, `ac`, `hp`, `primary_source`, `trait_raw`, `url`, `type`.
(`trait_group` is stored but not indexed by AoN, so filter on `traits` instead.)

Elasticsearch only allows `from + size` up to 10,000. For deeper paging, every
page that has more results ends with a stateless `next_cursor`. Pass it back as
`cursor`; the cursor carries the original query and page size, so every other
search argument is ignored. Cursors are compressed, self-contained, and survive
a server restart.

```text
search_content(query="dragon", limit=20)
# ... result ends with: Next page cursor (pass to search_content as cursor): ...
search_content(cursor="<the returned cursor>")
```

### `get_content`

```text
get_content(
  name: str | None,
  category: str | None,
  url: str | None,       # full or relative, e.g. "/Spells.aspx?ID=1530"
  doc_id: str | None,    # stable id, e.g. "spell-119" or "creature-3024"
  legacy: bool = false
)
```

Examples:

```text
get_content(name="Interact", category="action")
get_content(name="Fireball", category="spell")
get_content(name="Fireball", category="spell", legacy=true)
get_content(doc_id="creature-3024")
get_content(url="/Spells.aspx?ID=1530")
```

### `get_creature_stats`

```text
get_creature_stats(name="Goblin Warrior", legacy=false)
```

Returns both a compact text statblock and MCP `structuredContent` with `ac`,
`hp`, `perception`, `saves`, `abilities`, `skills`, `senses`, `languages`,
`speed`, `weaknesses`, `resistances`, `items`, and `spells`. This is the tool to
use when a client needs numbers it can compare or calculate with; use
`get_creature` when it needs the full prose statblock.

```text
get_creature_stats(name="Lich")
# structuredContent:
# {"ac": 31, "hp": 190, "saves": {"fortitude": 17, "reflex": 21, "will": 23}, ...}
```

## Install

Requires Python 3.11+.

```bash
git clone https://github.com/Viroide/pf2e-mcp.git
cd pf2e-mcp
uv venv --python 3.13
uv pip install -e ".[http]"     # omit [http] for stdio only
```

Without `uv`:

```bash
python -m venv .venv
.venv/bin/pip install -e ".[http]"
```

This installs two commands:

- `pf2e-mcp` — the MCP server (stdio by default)
- `pf2e` — a CLI harness for poking at the same data

## Connect an MCP client

Point the client at the absolute path of the `pf2e-mcp` executable:

```json
{
  "mcpServers": {
    "pf2e": {
      "command": "/absolute/path/to/pf2e-mcp/.venv/bin/pf2e-mcp",
      "env": {
        "PF2E_CACHE": "/Users/you/.cache/pf2e-mcp/responses.sqlite3"
      }
    }
  }
}
```

Use `which pf2e-mcp` after installation if you are unsure of the path. The
server speaks MCP over stdio and logs only to stderr, so it is safe inside a
client that owns stdout.

## HTTP transport (optional)

MCP itself is not a REST API. The server uses the official Python SDK for the
protocol. If you want to run it over the network, a FastAPI wrapper is included:

```bash
.venv/bin/uvicorn pf2e_mcp.http_app:app --host 127.0.0.1 --port 8000
```

The MCP endpoint is `http://127.0.0.1:8000/mcp`; `GET /health` is a liveness
probe. DNS-rebinding protection is on by default, which is why the endpoint must
be reached through `127.0.0.1:8000` or `localhost:8000` (with a port).

Alternatively, `PF2E_TRANSPORT=http pf2e-mcp` runs the SDK's built-in
streamable-HTTP server without FastAPI.

### Docker

The included image runs the FastAPI wrapper as a non-root user and keeps the
SQLite cache on a volume:

```bash
docker build -t pf2e-mcp .
docker run --rm -p 8000:8000 -v pf2e-cache:/data pf2e-mcp
```

The MCP endpoint is `http://localhost:8000/mcp`; `GET /health` is the health
probe. The image is built and smoke-tested by CI.

## CLI

The CLI talks to the same service layer, which makes debugging a query easy:

```bash
pf2e search spell/fireball
pf2e search "fireball" -c spell -l 5
pf2e search -c creature -f size=Small --min-level 1 --max-level 3
pf2e search -c feat -t fighter --source "Player Core"
pf2e get Interact -c action
pf2e get Fireball -c spell --legacy
pf2e get --id creature-3024
pf2e get --url '/Spells.aspx?ID=1530'
pf2e stats "Lich"
pf2e search dragon -l 20
pf2e search --cursor 'v1...'          # resume a deep page
pf2e categories
pf2e sources -l 20
pf2e traits -l 30
pf2e cache status
```

Add `--json` for the underlying records instead of the LLM-facing text. The
`category/name` shorthand mirrors wayfinder and is handy for disambiguation.

## Configuration

All settings are environment variables.

| Variable | Default | Meaning |
| --- | --- | --- |
| `PF2E_AON_ENDPOINT` | `https://elasticsearch.aonprd.com/aon/_search` | Search endpoint. |
| `PF2E_AON_BASE` | `https://2e.aonprd.com` | Base for relative URLs. |
| `PF2E_USER_AGENT` | `pf2e-mcp/0.1.0 (...)` | Identifying User-Agent. |
| `PF2E_CACHE` | `~/.cache/pf2e-mcp/responses.sqlite3` | Cache path, or `off` to disable. |
| `PF2E_CACHE_TTL` | `86400` | Cache lifetime in seconds. |
| `PF2E_TIMEOUT` | `30` | HTTP timeout in seconds. |
| `PF2E_MAX_RETRIES` | `3` | Attempts for 429/5xx and transport errors. |
| `PF2E_TRANSPORT` | `stdio` | `stdio` or `http`. |
| `PF2E_HOST` | `127.0.0.1` | HTTP bind host. |
| `PF2E_PORT` | `8000` | HTTP bind port. |

The cache stores successful raw responses in SQLite, with WAL enabled. Errors
are never cached. `pf2e cache clear` empties it; `pf2e cache purge` removes only
expired rows.

## Design notes

### Data source

AoN exposes an anonymous Elasticsearch endpoint:

```text
POST https://elasticsearch.aonprd.com/aon/_search
```

`aon` is a rotating alias (currently pointing at a dated index). Never pin the
dated name. Documents have a stable `id`, a `url`, `markdown` with the full
statblock, a flat `text` field, and relationship fields such as `remaster_id`
and `legacy_id`.

### Query strategy

- Free text uses `multi_match` with `operator: "and"` and boosts on
  `name^10`, `legacy_name^5`, and `summary^3`. Scoping by category is the most
  effective way to cut noise.
- Every search filters `exclude_from_search: false`. AoN uses this for reprints
  and joke entries; ignoring it is the source of the `Interact` bug.
- Remaster selection is `must_not exists remaster_id` (or `legacy_id` for
  `legacy=true`). An id lookup deliberately ignores the edition switch.
- Lookups rank exact current name, then legacy name, then category priority.
  Ties go to higher level and newer release date.
- `source` is matched as a phrase on purpose, so `Player Core` also finds
  `Player Core 2`. Use `filters={"primary_source": ...}` for exact book identity.

### Rendering

AoN's `markdown` mixes Markdown with XML-ish tags: `<title>`, `<traits>`,
`<trait>`, `<actions>`, `<row>`, `<column>`, `<table>`, `<aside>`, and more.
The normalizer turns those into plain GFM:

- titles become headings with level/type annotations,
- traits become a `**Traits**` line,
- row/column wrappers become paragraph breaks,
- HTML tables become pipe tables,
- links are flattened to their text (the canonical URL is in the header),
- unknown tags are stripped.

This keeps statblocks readable for an LLM without shipping raw markup.

### Limits

- Search results are capped at 50 per call (the query layer allows 100).
- Elasticsearch's `from + size` window is 10,000. Larger offsets are rejected
  with a clear error; use the cursor (`search_after`) for deeper paging.
- Cursor queries are self-contained and stateless, and request one extra row to
  know whether another page exists.
- Responses larger than 24,000 characters are truncated in `get_content`.
- No bulk export and no crawling. The server issues one query per request and
  caches the result.

## Development

```bash
uv venv --python 3.13
uv pip install -e ".[dev,http]"
.venv/bin/python -m pytest
.venv/bin/ruff check src tests scripts
.venv/bin/ruff format --check src tests scripts
```

The offline suite uses recorded responses in `tests/fixtures/` and never
touches the network. To refresh them:

```bash
.venv/bin/python scripts/fetch_fixtures.py
```

Live canary tests are opt-in:

```bash
PF2E_LIVE=1 .venv/bin/python -m pytest tests/test_live.py
```

They check that the index is populated, `Fireball` still has a statblock,
`Interact` still resolves to `action-2297`, the remaster/legacy pair still
exists, and cursor pagination returns distinct pages. Run them before a release
or on a schedule.

## Publishing

Build and check the distributions locally:

```bash
python -m build
twine check dist/*
```

Publish to PyPI with trusted publishing (preferred) or a token:

```bash
twine upload dist/*
```

For the official MCP Registry, copy `server.json.example` to `server.json`,
replace `<owner>` with the GitHub owner, keep the version in sync with
`pyproject.toml`, then publish with `mcp-publisher`. CI builds and checks the
wheel, sdist, and Docker image on every push.

### Layout

```text
src/pf2e_mcp/
  aon/
    client.py      # HTTP, retry/backoff, User-Agent
    cursor.py      # compressed search_after cursors
    models.py      # tolerant Document model
    query.py       # Elasticsearch request builders
    normalize.py   # AoN markup -> GFM
  cache.py         # SQLite response cache
  categories.py    # category resolution and priority
  creature.py      # structured creature statblocks
  service.py       # search, lookup, facets, variant collapsing
  format.py        # text shown to the model
  server.py        # MCP tools (stdio / streamable HTTP)
  http_app.py      # optional FastAPI wrapper
  cli.py           # `pf2e` command
tests/             # offline fixtures + live canaries
scripts/           # fixture refresh
Dockerfile         # HTTP deployment image
server.json.example # MCP registry manifest template
```

## Attribution and licensing

The **code** in this repository is MIT licensed (see `LICENSE`).

The **game content** is not. Pathfinder and Archives of Nethys content is
published by Paizo Inc. under the
[Community Use Policy](https://paizo.com/community/communityuse) and the
OGL/ORC licenses. This project:

- does not charge for access to AoN content,
- does not claim endorsement by Paizo or Archives of Nethys,
- does not mirror or redistribute the dataset,
- fetches pages live from AoN and caches them locally for a day.

If you deploy this, keep it non-commercial and keep the identifying
User-Agent. Read the current Paizo and AoN policies before redistributing
anything.

Wayfinder is MIT licensed and was used as a behavioural reference. Thanks to
its author and to the Archives of Nethys maintainers.

TDQS

A3.7/5.0

Scored across 7 tools

Disambiguation3/5

get_creature is effectively a special case of get_content, and get_creature vs get_creature_stats target the same entity, so boundaries overlap. Descriptions do clarify the split (full text vs structured numeric data), but an agent must read carefully to pick correctly.

Naming Consistency5/5

Clean verb_noun convention throughout: search_content, get_content, get_creature, get_creature_stats, list_categories, list_sources, list_traits. Verbs map predictably to operation type (search/get/list).

Tool Count5/5

Seven tools is well-scoped for a read-only rules-reference server. Each tool has a clear role: retrieval, structured statblocks, and three facet-listing helpers for filters.

Completeness4/5

Coverage is strong for a lookup server: search, full text retrieval, structured creature stats, and discoverable filter facets. Minor gaps exist around bulk/browse operations (e.g. paging long result sets or level-range queries), but core reference workflows are covered.