Skip to main content
Glama
README.md
# typst-docs-neo4j

A deterministic **Knowledge Graph** for the **Typst 0.15.1 Documentation**, packaged for **Neo4j** (`LOAD CSV` + Bolt auto-loader) alongside a zero-setup **SQLite FTS5 mirror** and a **Model Context Protocol (MCP) server** for AI coding assistants.

---

## Why a Graph Instead of Plain Vector RAG?

Chunk-based vector search frequently breaks Typst's tightly interconnected semantics across pages—such as `set`/`show` rules, element parameters, type unions (`color | gradient | tiling`), and method signatures.

By parsing the official Typst documentation PDF deterministically (no LLM extraction hallucinations) using its Table of Contents tree, coordinate-filtered layout blocks, and **8,699 internal PDF hyperlinks**, this repository preserves exact multi-hop relationships:

- Traverse `Element -> Parameter -> Type` to find every component that accepts `gradient` or every parameter configurable via `#set`.
- Combine **Full-Text Search** entry points with **1–2 hop graph traversal** (`REFERENCES`, `ACCEPTS_TYPE`, `RETURNS_TYPE`, `HAS_METHOD`, `DEFINES`) to feed AI assistants compact, accurate API context.

---

## Graph Schema

```mermaid
flowchart LR
    Chapter["Chapter / Category / Module"] -->|HAS_CHILD / DEFINES| Symbol["Element / Function / Type"]
    Symbol -->|HAS_PARAMETER| Param["Parameter"]
    Symbol -->|HAS_METHOD| Method["Method"]
    Param -->|ACCEPTS_TYPE| TypeNode["Type"]
    Symbol -->|RETURNS_TYPE| TypeNode
    Method -->|RETURNS_TYPE| TypeNode
    Symbol -->|REFERENCES| Symbol
```

### Dataset Stats (Typst 0.15.1 — 692 Pages)

| Metric | Count | Breakdown |
| :--- | ---: | :--- |
| **Nodes (`:DocNode`)** | **2,732** | `116` Element, `37` Type, `237` Function, `156` Method, `473` Parameter (`99.8%` typed), `8` Module, `11` Category, `4` LanguageSection, `5` Tutorial, `4` Guide, `21` ChangelogVersion, `5` Chapter, `1,655` Section |
| **Relationships** | **11,454** | `6,153` `REFERENCES` (`8,699/8,699` PDF links resolved), `2,727` `HAS_CHILD`, `979` `ACCEPTS_TYPE`, `572` `RETURNS_TYPE`, `473` `HAS_PARAMETER`, `394` `DEFINES`, `156` `HAS_METHOD` |

---

## Quickstart

### Prerequisites
- Python 3.10+ and [`uv`](https://docs.astral.sh/uv/)
- Neo4j 5+ (via **Neo4j Desktop 2** or **Docker Compose**) — *optional if you only want the local SQLite-backed MCP server*

```bash
git clone https://github.com/<your-username>/typst-docs-neo4j.git
cd typst-docs-neo4j
uv sync
```

---

### Option 1: Load into Neo4j Desktop 2

1. Open **Neo4j Desktop 2** and start your DBMS (default Bolt URI: `bolt://localhost:7687`).
2. Run the Bolt auto-loader (reads directly from the included `data/typst_graph.db`, zero APOC plugins required):

```bash
uv run typst-load-neo4j --password "YOUR_NEO4J_PASSWORD" --clear
```

<details>
<summary>Alternative: Manual Import via Neo4j Browser (LOAD CSV)</summary>

1. In Neo4j Desktop 2, open your DBMS **`import`** folder (`...` → *Open folder* → *Import*).
2. Copy `data/neo4j/nodes.csv` and `data/neo4j/edges.csv` into that `import` folder.
3. Open **Neo4j Browser** and run [`data/neo4j/schema.cypher`](data/neo4j/schema.cypher).
4. Then run [`data/neo4j/import_csv.cypher`](data/neo4j/import_csv.cypher).

</details>

---

### Option 2: Spin Up Neo4j via Docker Compose

```bash
cp .env.example .env   # edit NEO4J_PASSWORD if desired
docker compose up -d
uv run typst-load-neo4j --password typstgraph123 --clear
```

Neo4j Browser will be available at `http://localhost:7474`.

---

### Option 3: Connect the MCP Server (`typst-mcp`) to Your AI Client

The MCP server runs in `auto` mode:
- When `NEO4J_PASSWORD` is configured and Neo4j is reachable, queries run against **Neo4j** (Full-Text Index + Cypher).
- When Neo4j is stopped or unconfigured, it seamlessly falls back to the bundled **SQLite FTS5 mirror** (`data/typst_graph.db`) with identical tool outputs.

Add this to your `mcp_config.json` (Antigravity / Claude Desktop / Cursor):

```json
{
  "mcpServers": {
    "typst-docs-neo4j": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/typst-docs-neo4j",
        "run",
        "typst-mcp"
      ],
      "env": {
        "NEO4J_URI": "bolt://localhost:7687",
        "NEO4J_USER": "neo4j",
        "NEO4J_PASSWORD": "YOUR_NEO4J_PASSWORD"
      }
    }
  }
}
```

*(To use SQLite-only mode with zero database setup, omit the `env` block or set `"TYPST_GRAPH_BACKEND": "sqlite"`.)*

#### Available MCP Tools
1. `search_typst_docs(query, kind?, limit?)` — Full-text search with exact symbol name boosting
2. `get_symbol_context(symbol, include_content?, max_refs?)` — Full node details, parameters, defaults, methods, return types, and incoming/outgoing cross-references
3. `find_by_type(type_name, role?, limit?)` — Find all symbols accepting or returning a given type
4. `find_settable_params(element_name)` — List all `#set`-able parameters of an element
5. `traverse_related(node_id_or_symbol, hops?, limit?)` — Multi-hop graph traversal (`1..3` hops)
6. `get_section_content(section_num_or_id)` — Fetch verbatim documentation text and child sections
7. `graph_stats()` — Active backend and node/relationship counts

---

## Example Cypher Queries

See [`queries/examples.cypher`](queries/examples.cypher) for more ready-to-run Neo4j Browser queries.

```cypher
// 1. Visualize `heading` parameters, accepted types, and cross-references
MATCH (h:Element {symbol_name: 'heading'})-[r1:HAS_PARAMETER]->(p:Parameter)
OPTIONAL MATCH (p)-[r2:ACCEPTS_TYPE]->(t:Type)
OPTIONAL MATCH (h)-[r3:REFERENCES]->(ref:DocNode)
RETURN h, r1, p, r2, t, r3, ref
LIMIT 80;

// 2. Hybrid Full-Text Search + 1-hop context expansion
CALL db.index.fulltext.queryNodes('typst_doc_fulltext', 'show rule numbering') YIELD node, score
WITH node, score LIMIT 5
OPTIONAL MATCH (node)-[:HAS_PARAMETER|HAS_METHOD|DEFINES|REFERENCES]-(neighbor:DocNode)
RETURN node.id AS id, node.kind AS kind, node.title AS title,
       round(score, 2) AS relevance,
       collect(DISTINCT coalesce(neighbor.qualified_name, neighbor.title))[0..10] AS connected_concepts;
```

---

## Re-extracting from a Newer Typst Documentation PDF

```bash
uv run typst-extract --pdf path/to/typst-documentation.pdf
```

This regenerates `data/typst_graph.db` and `data/neo4j/*` (`nodes.csv`, `edges.csv`, `schema.cypher`, `import_csv.cypher`).

---

## Running Tests

```bash
uv run pytest -v
```

---

## License & Attribution

- Repository code and extraction pipeline: [Apache License 2.0](LICENSE).
- Extracted documentation content: derived from the official **Typst Documentation (0.15.1)** by Laurenz Mädje, Martin Haug, and The Typst Project Developers (Typst GmbH), licensed under **Apache License 2.0** (`https://github.com/typst/typst`).