Skip to main content
Glama
pdfctx

pdfctx

by StanislavV01
README.md
<div align="center">

# ๐Ÿ“‘ pdfctx

**PDF retrieval for AI agents. On FinanceBench it finds the evidence page in the top 10 for 67% of questions, against 51% for page-level search, and returns 11ร— fewer tokens.**

pdfctx turns PDFs into a section tree of paragraphs and tables with page + bounding box on every block, and
gives agents (Claude, Cursor, any MCP client) tools to navigate, search, cite and pack context. It reads
borderless SEC-style tables row by row, and it logs every read.

![Python](https://img.shields.io/badge/python-3.11+-3776AB?style=flat&logo=python&logoColor=white)
![MCP](https://img.shields.io/badge/MCP-SDK_2.3-6366F1?style=flat)
![FastAPI](https://img.shields.io/badge/FastAPI-REST-009688?style=flat&logo=fastapi&logoColor=white)
![Local-first](https://img.shields.io/badge/local--first-no_API_keys-22C55E?style=flat)
[![CI](https://github.com/StanislavV01/pdfctx/actions/workflows/ci.yml/badge.svg)](https://github.com/StanislavV01/pdfctx/actions)

</div>

![pdfctx web demo: a search over 3M's 2018 10-K. The table row with 2018 capex ($1,577M) is the selected hit, and its table is boxed on page 49.](docs/demo.png)

<sub>The web demo (`web/`) on a real 10-K. The question is "purchases of property, plant and equipment 2018". The
right panel lists the hits and what `context_pack` hands the agent. Each hit is boxed on the page it came from.
The image is regenerated by CI.</sub>

---

## Results: FinanceBench

[FinanceBench](https://github.com/patronus-ai/financebench) (open set) has 150 questions about 84 SEC filings
(10-K, 10-Q, 8-K, earnings releases), and each question is labeled with its evidence pages. Below, each system
retrieves 10 passages from the question's filing, and we measure whether an evidence page is among them. No LLM
is involved and nothing is graded by a model.

| system (single-document scope) | R@1 | R@3 | R@5 | R@10 | MRR@10 | tokens for top-5 |
|---|---|---|---|---|---|---|
| page-level BM25 (what most "chat with PDF" tools do) | 0.147 | 0.233 | 0.360 | 0.507 | 0.230 | 4,615 |
| pdfctx: structure | 0.160 | 0.267 | 0.333 | 0.453 | 0.237 | 586 |
| pdfctx: + section context | 0.160 | 0.267 | 0.353 | 0.500 | 0.242 | 572 |
| pdfctx: + table rows | 0.167 | 0.313 | 0.393 | 0.567 | 0.269 | 458 |
| **pdfctx: + finance glossary (default)** | **0.200** | **0.407** | **0.500** | **0.673** | **0.332** | **419** |
| pdfctx: + dense vectors + cross-encoder rerank (no glossary) | 0.267 | 0.447 | 0.540 | 0.713 | 0.389 | 505 |
| [`jztan/pdf-mcp`](https://github.com/jztan/pdf-mcp) `pdf_search`, mode auto | 0.247 | 0.427 | 0.553 | 0.693 | 0.368 | 940 |

**The default finds the evidence page in the top 10 for 67% of questions, against 51% for page search,
and hands the agent 11ร— fewer tokens.** The paired bootstrap (`python3 -m bench.compare`, 10,000 resamples)
puts the gain over page search clear of noise at every cutoff from R@3 to R@10:

| vs page-level BM25 | R@1 | R@3 | R@5 | R@10 |
|---|---|---|---|---|
| difference | +0.053 | +0.173 | +0.140 | +0.167 |
| 95% CI | [โˆ’0.007, +0.113] | [+0.093, +0.253] | [+0.047, +0.233] | [+0.087, +0.247] |
| questions won / lost | 15 / 7 | 35 / 9 | 37 / 16 | 34 / 9 |

What moved the number is vocabulary. Questions say *"FY2018 capital expenditure"* or *"quick ratio"*;
the filing says *"Purchases of property, plant and equipment"* and *"Total current assets"*. The glossary
([`src/pdfctx/glossary.py`](src/pdfctx/glossary.py), 29 entries) adds a statement's own line-item words to the
query when a question uses a finance term. Table rows already carry their headers and years, so the
expanded query lands on the exact row. By FinanceBench question type, R@10 rises from 0.64 to 0.78 on
metric questions and from 0.40 to 0.56 on domain questions. Novel questions stay flat (0.66 โ†’ 0.68).

**How far to trust this:**
- **No held-out split.** Every change was kept or reverted on the same 150 questions reported here.
  The glossary entries are textbook definitions, but I wrote them knowing what kinds of questions
  FinanceBench asks. Treat the numbers as optimistic.
- **Tokens** count passage text only (len/4), not the JSON fields around it.
- **Full log.** [`bench/results/CHANGELOG.md`](bench/results/CHANGELOG.md) records every choice, including
  what did not work: summed page boosts lost to boilerplate, and document routing hurt corpus search.
- **Compared with pdf-mcp and the reranker, it is a tie.** Both score higher than the lexical default,
  but within noise. Against the default, pdf-mcp gets R@10 +0.020 with 95% CI [โˆ’0.073, +0.107], and the
  reranker +0.040 [โˆ’0.033, +0.113]. Rank-1 leans their way (+0.047 and +0.067), and the CIs still cross
  zero. By question type the rankings differ: on human-written "novel" questions both reach 0.82โ€“0.84
  R@10 against 0.68, while on domain questions the glossary leads (0.56 against 0.52 and 0.46).
- **The difference is cost.** Median latency per question was 45 ms for the default, 8.5 s for the
  reranker (CPU) and 20 s for pdf-mcp, which re-reads the filing for each query. pdf-mcp also returns
  2.2ร— the tokens. The latencies come from different machines (default measured locally, the other two on
  CI runners), so compare orders of magnitude only.
- **Dense vectors alone** (`pdfctx-hybrid`) did not finish within the 5-hour CI limit. Embedding every
  block and table row of 84 filings on a 4-core runner is too slow, so dense search stays opt-in
  (`pdfctx[embed]`).

Corpus scope (search all 84 filings at once) stays hard: R@10 0.213 with the glossary vs 0.187 for the baseline
at 13ร— fewer tokens, but rank-1 is lower (0.073 vs 0.093). Finding the right filing among 84 similar ones
is the open problem
([details](bench/results/CHANGELOG.md#corpus-scope)).

## Why it works

- **Structure, not chunks.** PDFium (via pypdfium2) gives every character a box. pdfctx rebuilds words, lines,
  columns and paragraphs, and drops running headers, footers and page numbers, including the ones HTML-to-PDF
  converters print mid-page. Headings and bookmarks become a section tree.
- **Tables without borders.** SEC filings draw tables with whitespace only, and ruling-line detectors find
  nothing in them. pdfctx finds tables from text alignment: a label plus right-aligned numeric cells, with year
  and caption lines above. Each **row** is indexed with its headers and caption:
  `Consolidated Statement of Cash Flows ยท (Millions) โ€บ Purchases of PP&E | 2018: (1,577) | 2017: (1,373)`.
- **Page-aware ranking.** One result per page, a bounded boost for pages with several matches, and the most
  specific match (a row rather than the whole table). This is how small units beat whole pages on recall while
  staying cheap.
- **Everything local by default.** BM25 lives in SQLite FTS5 and the whole index is one file. Dense vectors
  and reranking are optional, either local (fastembed, ONNX on CPU) or through OpenAI / Voyage / Cohere keys.

## Tools for agents

| Tool | What it returns |
|---|---|
| `list_documents` | indexed PDFs with status (`ok`, `no_text`, `encrypted`, `failed`) |
| `outline(doc_id)` | the section tree with ids and pages |
| `read_section(section_id, max_tokens)` | a whole section, sub-sections included, in reading order |
| `search(query, doc_ids, k)` | paragraphs, tables or single table rows, with page, bbox and section path |
| `get_table(table_id, format)` | a full table as markdown or CSV, with its caption |
| `cite(block_id)` | file, page, bounding box and the verbatim text, so the user can verify |
| `context_pack(query, budget_tokens)` | the best evidence within a token budget, deduplicated and in document order |

All tools are read-only (`readOnlyHint`). Errors come back as readable tool errors. Every call is appended to an
audit log: which client, which tool, which blocks it received.

```text
$ pdfctx audit --db 10k/.pdfctx/index.db
2026-11-27T01:18:23.062+00:00  claude     search     {"doc_ids": null, "k": 3, "query": "purchases of property plant and equipment 2018"}  โ†’ 3 block(s)
2026-11-27T01:18:23.063+00:00  claude     get_table  {"format": "markdown", "table_id": "d34948841326:b797"}  โ†’ 1 block(s)
```

## Quick start

```bash
pip install "git+https://github.com/StanislavV01/pdfctx"     # PyPI release coming
pdfctx index ~/Documents/contracts
pdfctx search "termination notice period" --db ~/Documents/contracts/.pdfctx/index.db
```

**Claude Code**

```bash
claude mcp add pdfctx -- uvx --from git+https://github.com/StanislavV01/pdfctx pdfctx serve ~/Documents/contracts
```

**Claude Desktop / Cursor**

```json
{
  "mcpServers": {
    "pdfctx": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/StanislavV01/pdfctx", "pdfctx", "serve", "/Users/me/Documents/contracts"]
    }
  }
}
```

The folder is indexed on start, and files that are added, changed or deleted are re-indexed on the next tool
call.

**Try the web demo locally** (Python 3.11+, Node 20+). One command installs everything, indexes a real 10-K
(or your folder) and opens the UI on http://localhost:3000:

```bash
./scripts/demo.sh                    # or: ./scripts/demo.sh ~/Documents/reports
```

`./scripts/cloud-demo.sh` runs pdfctx Cloud the same way, with landing, sign-in, metrics table and API keys.
The sign-in link is printed in the terminal. Deploying it is described in [docs/DEPLOY.md](docs/DEPLOY.md).

**HTTP (REST + remote MCP)**

```bash
pdfctx serve-http ~/Documents/contracts --port 8000 --uploads ./uploads
curl "localhost:8000/v1/search?q=termination%20notice"
curl -X POST localhost:8000/v1/context -H 'content-type: application/json' \
     -d '{"query": "revenue by region 2024", "budget_tokens": 1500}'
# MCP clients connect to http://localhost:8000/mcp
```

Every route checks the `Host` and `Origin` headers, which blocks DNS-rebinding and cross-site requests. By
default only localhost is allowed. Binding to another address (`--host 0.0.0.0`) refuses to start until
`PDFCTX_ALLOWED_HOSTS` lists the public host names. Set `PDFCTX_WEB_ORIGIN` to allow a separate web UI.

Uploads (`POST /v1/documents`, raw PDF body with `content-type: application/pdf`) are off unless `--uploads` is set, and are limited to 20 MB and
300 pages. `GET /v1/documents/{id}/pages/{n}.png` renders a page so a UI can draw cited boxes on it.

**Better recall with local models** (first run downloads ~200 MB of ONNX models):

```bash
pip install "pdfctx[embed] @ git+https://github.com/StanislavV01/pdfctx"
pdfctx serve ~/Documents/contracts --embed fastembed --rerank fastembed
```

## Limits

- Text-layer PDFs only. Scanned pages are reported as `no_text`, and there is no OCR yet
  (pdf-mcp has it).
- Tables are detected from alignment. Unusual layouts can split or merge rows, and `get_table` always
  returns what was parsed, so it can be checked.
- Token counts are estimates (`len / 4`).
- Some HTML-to-PDF converters letter-space words in the text layer itself (`Busines s`). pdfctx keeps what
  the PDF says.

## Development

```bash
pip install -e ".[dev]" && pytest
python -m bench.financebench --systems baseline,pdfctx-tables --scope doc   # downloads FinanceBench (~160 MB)
```

The repository uses its own quality gate,
[seaworthy](https://github.com/StanislavV01/seaworthy): ruff and pytest must pass before every commit, and
test tampering is flagged.

## License

MIT. FinanceBench data (CC BY-NC 4.0) is downloaded at run time and not redistributed.