neo4j-kg-mcp
by happy-momo
README.md
# neo4j-kg-mcp
**Neo4j Knowledge Graph MCP Server for AI Agents** — zero-LLM-config tool server that turns PDFs, Word, Excel and plain text into a Neo4j knowledge graph.
<p align="center">
<strong>No internal LLM. No API keys. Your agent is the extraction engine.</strong><br/>
A <a href="https://modelcontextprotocol.io">Model Context Protocol (MCP)</a> server that lets Claude Code, Cursor, WorkBuddy and any MCP-enabled agent<br/>
extract entities & relationships from documents and write them straight into <a href="https://neo4j.com">Neo4j</a> via idempotent <code>MERGE</code>.
</p>
<p align="center">
<img src="https://img.shields.io/badge/Python-3.10+-3776AB?style=flat-square&logo=python" alt="Python 3.10+"/>
<img src="https://img.shields.io/badge/Neo4j-5.x-4581C3?style=flat-square&logo=neo4j" alt="Neo4j 5.x"/>
<img src="https://img.shields.io/badge/MCP-server-F9AB00?style=flat-square" alt="MCP Server"/>
<img src="https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square" alt="MIT"/>
</p>
---
## Why this exists
Most MCP knowledge-graph servers embed private LLM calls and ask you to configure yet another API key.
**neo4j-kg-mcp** flips that: the host platform's LLM — Claude, GPT, Gemini, DeepSeek inside your agent —
performs entity-relationship extraction in a conversational chunk loop, while the server handles the
graph-write layer: document parsing, **ontology validation**, **parameterized Cypher generation**,
and auditable Neo4j writes.
It is the missing **graph construction** block for the MCP ecosystem:
- **Zero LLM configuration** — the server ships with no LLM dependency. Configure one Neo4j connection and you're done.
- **Schema-driven & interactive** — define your ontology in YAML, validate it conversationally with the agent, iterate until it passes.
- **Long-task friendly** — work proceeds chunk-by-chunk in the conversation, survives server restarts, and never duplicates nodes.
---
## Features
| Feature | Description |
|---------|-------------|
| 🔌 **MCP native** | 8 clean tools; works over stdio (Claude Code, Cursor) or Streamable HTTP (WorkBuddy, Dify, n8n, custom agents) |
| 🤖 **Agent = engine** | No embedded LLM, no API keys — extraction quality follows your platform's model |
| 📚 **Multi-format documents** | PDF, DOCX/DOC, XLSX/XLS, TXT — single file, folder batch, or inline text |
| 📝 **Ontology (Schema) management** | Preset templates + YAML; `validate_schema` returns structured errors the agent can fix iteratively |
| 🧱 **Enforced constraints** | Entity types, relation types and endpoints are validated against your ontology before writing |
| 🛡️ **Secure by design** | Parameterized Cypher (injection-safe), sanitized identifiers, read-only query whitelist |
| ⏸️ **Resumable** | Progress persists to disk per job; resume after a crash or server restart |
| ♻️ **Idempotent writes** | `MERGE` semantics — resuming or re-submitting a chunk never creates duplicate nodes |
---
## Quick demo
```
User: Ingest docs/product-report.pdf using this schema
1. Agent drafts a Schema → validate_schema → fixes per error list → passes
2. start_extraction(document={path|text}, schema=final)
← {job_id, total_chunks, chunk_text, instructions}
3. Agent reads the chunk, produces triples → submit_triples
← {accepted, rejected:[{triple, reason}], next_chunk}
4. …loop until done…
5. get_job_status → summary; query_graph → verify in Neo4j
```
You can interrupt at any block and redirect the agent ("normalize company names"), effective from the next chunk.
---
## Install & configure
### Prerequisites
- Python 3.10+
- A running Neo4j 5.x instance
### 1. Install
```bash
pip install -e neo4j-kg-mcp
# or
pip install -r requirements.txt
```
### 2. Claude Code / Cursor (stdio)
Add this to your `.mcp.json`:
```json
{
"mcpServers": {
"neo4j-kg-mcp": {
"command": "python",
"args": ["-m", "kg_mcp.server"],
"env": {
"NEO4J_URI": "bolt://localhost:7687",
"NEO4J_USER": "neo4j",
"NEO4J_PASSWORD": "your_password"
}
}
}
}
```
No `NEO4J_*` env vars? Still fine — call `configure_neo4j` in the conversation and pass credentials there.
### 3. WorkBuddy / Dify / n8n (Streamable HTTP)
```bash
python -m kg_mcp.server --http --host 0.0.0.0 --port 8765
```
Point your platform at: `http://<host>:8765/mcp`
### Environment variables
| Variable | Default | Description |
|----------|---------|-------------|
| `NEO4J_URI` | `bolt://localhost:7687` | Neo4j Bolt address |
| `NEO4J_USER` | `neo4j` | Username |
| `NEO4J_PASSWORD` | — | Password (optional if calling `configure_neo4j`) |
Job progress lives in `.data/jobs/<job_id>/`; delete the folder to reset.
---
## Tools (8)
| Tool | Purpose |
|------|---------|
| `configure_neo4j` | Set & test the Neo4j connection |
| `list_schema_templates` | List built-in ontology templates (full YAML) |
| `validate_schema` | Validate ontology YAML; return structured errors for agent iteration |
| `start_extraction` | Parse the document, chunk it, return chunk 0 + instructions |
| `submit_triples` | Validate & write a chunk's triples; return the next chunk |
| `get_job_status` | Query job progress |
| `resume_extraction` | Resume a job from its first unfinished chunk |
| `query_graph` | Read-only Cypher query (whitelist: MATCH/RETURN/WITH/ORDER BY/LIMIT) |
### Sample schema (ontology) YAML
```yaml
entities:
- name: Person
properties: [name, role]
- name: Company
properties: [name, industry]
relationships:
- {head: Person, relation: worksAt, tail: Company}
- {head: Person, relation: develops, tail: Product}
```
---
## Architecture
```
┌─────────────────────────────┐
│ Claude Code / WorkBuddy │
│ (platform LLM = engine) │
│ read chunk → triples │◄── MCP tool calls
└──────────┬──────────────────┘
▼
┌─────────────────────────────┐
│ neo4j-kg-mcp (no LLM) │
│ doc_loader · schema_mgr │
│ triple validation · cypher │
│ graph_store · job_store │
└──────────┬──────────────────┘
▼
┌──────┐
│Neo4j │
└──────┘
```
**Design decisions**
| Decision | Rationale |
|----------|-----------|
| No embedded LLM | Install-and-run (configure Neo4j only); quality follows your platform's model; cost stays on your existing subscription |
| Chunked conversational loop | No context overflow on big docs; ~2000-char chunks keep extraction precise; per-chunk persistence enables resume |
| Reject + explain, not silent filter | Rejected triples return their reason to the agent so it can fix and resubmit — no invisible data loss |
| `MERGE` writes | Idempotent: resume / re-submit never duplicates nodes or edges |
---
## Development
```bash
pytest tests/ -v # unit + simulated end-to-end
```
Unit tests cover schema validation, triple validation (rejection reasons), injection-safe Cypher,
job persistence and resume. An end-to-end script exercises the full MCP flow against a real Neo4j.
---
## License
[MIT](LICENSE)
---
<p align="center">
<strong>If this helps you, give it a ⭐</strong><br/>
<a href="https://github.com/happy-momo/neo4j-kg-mcp">GitHub Repository</a>
</p>This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues