dpartin/neo4j_mcp
If you are the rightful owner of neo4j_mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
A modular, context-aware server implementing a Model Context Protocol (MCP) with Neo4j support for graph operations and Retrieval-Augmented Generation (RAG).
MCP Server with Neo4j Support
A modular, context-aware server that implements a Model Context Protocol (MCP) to orchestrate AI agents and provide graph creation, modification, and augmentation via Neo4j for Retrieval-Augmented Generation (RAG).
Overview
This project implements a Model Context Protocol (MCP) server that provides direct access to Neo4j graph database operations through stdio communication. It includes comprehensive graph analysis tools, path finding algorithms, and graph augmentation capabilities for Retrieval-Augmented Generation (RAG) workflows.
Architecture
Core Modules
Module | Description |
---|---|
MCP Server | Main server implementing Model Context Protocol via stdio communication |
Neo4j Client | Wraps Neo4j operations (CRUD, Cypher queries) with proper serialization |
Advanced Cypher | Graph analysis operations (path finding, PageRank, community detection) |
Augmentation Engine | Transforms graph data into embeddings and RAG-ready content |
Tech Stack
Layer | Tools/Technologies |
---|---|
Backend | Python, MCP Protocol |
Messaging | JSON-RPC over stdio |
Graph Database | Neo4j with neo4j-driver |
Containerization | Docker, Docker Compose |
Testing | pytest |
Quick Start
Prerequisites
- Python 3.11+
- Docker and Docker Compose
- Neo4j database (see setup options below)
Easy CLI Interface
The project now includes user-friendly CLI tools that don't require complex echo
commands:
Command-Line Interface
# List all nodes
python neo4j_cli.py list
# List with limit
python neo4j_cli.py list --limit 5
# List by label
python neo4j_cli.py list --labels Person
# Create a node
python neo4j_cli.py create --labels Person --properties name="John",age=30
# Run custom query
python neo4j_cli.py query "MATCH (n) RETURN count(n) as total"
# Analyze graph
python neo4j_cli.py analyze
# Find paths
python neo4j_cli.py paths 1 10
# Detect communities
python neo4j_cli.py communities
# Calculate PageRank
python neo4j_cli.py pagerank --labels Person
Interactive Mode
# Start interactive session
python neo4j_interactive.py
Then use commands like:
neo4j> list
neo4j> list --limit 5
neo4j> analyze
neo4j> help
neo4j> exit
Neo4j Setup Options
Option 1: Local Neo4j Installation
- Install Neo4j Desktop or Neo4j Community Edition
- Start Neo4j on your local machine
- Default connection:
bolt://localhost:7687
Option 2: Neo4j AuraDB (SaaS)
- Create a free account at Neo4j AuraDB
- Get your connection string (format:
bolt+s://<instance-id>.neo4j.io:7687
) - Update your
.env
file with the connection details
Option 3: Self-hosted Neo4j
- Deploy Neo4j on your preferred platform (AWS, GCP, Azure, etc.)
- Configure network access to allow connections from your MCP server
- Update your
.env
file with the connection details
Installation
-
Clone the repository:
git clone <repository-url> cd neo4j_mcp
-
Generate secure credentials:
python scripts/generate_secrets.py
-
Configure Neo4j connection:
Edit the
.env
file and update the Neo4j connection details:# For local Neo4j NEO4J_URI=bolt://localhost:7687 # For Neo4j AuraDB NEO4J_URI=bolt+s://<your-instance-id>.neo4j.io:7687 # For self-hosted Neo4j NEO4J_URI=bolt://<your-neo4j-host>:7687
-
Start the MCP server:
# Build and test the Docker image ./scripts/setup_mcp_docker.sh # Or manually docker build -t neo4j_mcp .
-
Or run locally:
pip install -r requirements.txt python mcp_server.py
Cursor MCP Integration
This project includes a proper MCP server implementation that communicates via stdio, making it compatible with Cursor's MCP integration.
Docker Setup (Recommended)
The easiest way to use the MCP server is with Docker:
-
Build the Docker image:
# On Linux/Mac ./scripts/setup_mcp_docker.sh # On Windows scripts\setup_mcp_docker.bat
-
Or manually:
docker build -f Dockerfile.mcp -t neo4j_mcp_server .
-
Test the Docker MCP server:
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | docker run --rm -i neo4j_mcp_server
Local Setup
If you prefer to run the MCP server locally without Docker:
-
Ensure the MCP server is working:
# Test the MCP server echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | python mcp_server.py
-
Available Tools:
neo4j_create_node
- Create nodes with labels and propertiesneo4j_run_cypher_query
- Execute Cypher queriesneo4j_create_relationship
- Create relationships between nodesgraph_find_shortest_path
- Find shortest paths between nodesgraph_find_all_paths
- Find all paths up to a maximum lengthgraph_calculate_pagerank
- Calculate PageRank for nodesgraph_detect_communities
- Detect communities using algorithmsgraph_analyze_structure
- Analyze overall graph structureaugmentation_augment_for_rag
- Augment graph data for RAG
-
Environment Variables: Make sure your Neo4j connection details are set in your environment:
export NEO4J_URI=bolt://localhost:7687 export NEO4J_USER=neo4j export NEO4J_PASSWORD=your_password export NEO4J_DATABASE=neo4j
MCP Configuration
The mcp.json
file includes two server configurations:
neo4j-mcp
: Uses Docker (recommended)neo4j-mcp-local
: Runs locally with Python
To switch between them, edit your mcp.json
file or use different server names in Cursor's MCP settings.
Troubleshooting
If Cursor doesn't show available tools:
-
Check the MCP server is running correctly:
python mcp_server.py
-
Verify the mcp.json configuration:
- Ensure the
command
andargs
point to the correct Python executable and script - Check that the
cwd
path is correct for your workspace
- Ensure the
-
Check Neo4j connection:
- The MCP server will show warnings if Neo4j is not available
- Tools will return error messages if Neo4j is not connected
-
Restart Cursor:
- Sometimes Cursor needs to be restarted to pick up MCP configuration changes
MCP Tools
The server provides the following tools via MCP, all with enhanced formatting for better readability:
neo4j_create_node
- Create nodes with labels and propertiesneo4j_run_cypher_query
- Execute Cypher queries with formatted resultsneo4j_create_relationship
- Create relationships between nodesgraph_find_shortest_path
- Find shortest paths between nodesgraph_find_all_paths
- Find all paths up to a maximum lengthgraph_calculate_pagerank
- Calculate PageRank for nodesgraph_detect_communities
- Detect communities using algorithmsgraph_analyze_structure
- Analyze overall graph structureaugmentation_augment_for_rag
- Augment graph data for RAG
Enhanced Output Formatting
All tools now provide enhanced, human-readable output formatting:
- Node Display:
Node 1 (Person) - name: John Doe, age: 30, email: john@example.com
- Relationship Display:
Relationship 5 (WORKS_FOR) - since: 2020, role: Engineer
- Query Results: Structured display with record numbers and formatted data
- Graph Statistics: Summary counts and breakdowns by node labels and relationship types
- Path Analysis: Clear path visualization with node and relationship details
- Community Detection: Grouped communities with size information
- RAG Augmentation: Structured subgraph information with similarity scores
MCP Protocol
This server implements the Model Context Protocol (MCP) using JSON-RPC over stdio communication. It provides tools for Neo4j graph operations and graph analysis.
Supported Tools
The server exposes the following tools via MCP:
Basic Neo4j Operations
Tool Name | Arguments | Description |
---|---|---|
neo4j_create_node | {"labels": [], "properties": {}} | Create a new node |
neo4j_run_cypher_query | {"query": "", "parameters": {}} | Execute Cypher query |
neo4j_create_relationship | {"from_node_id": 1, "to_node_id": 2, "rel_type": "", "properties": {}} | Create relationship |
Advanced Graph Operations
Tool Name | Arguments | Description |
---|---|---|
graph_find_shortest_path | {"start_node_id": 1, "end_node_id": 2, "relationship_types": []} | Find shortest path |
graph_find_all_paths | {"start_node_id": 1, "end_node_id": 2, "max_length": 5} | Find all paths up to length |
graph_calculate_pagerank | {"node_labels": ["Person", "Company"]} | Calculate PageRank centrality |
graph_detect_communities | {"algorithm": "louvain"} | Detect communities in graph |
graph_analyze_structure | {} | Analyze graph structure |
Graph Augmentation
Tool Name | Arguments | Description |
---|---|---|
augmentation_augment_for_rag | {"query": "", "node_ids": [1, 2, 3]} | Transform subgraphs for RAG |
Example Usage
Create a Person Node
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "neo4j_create_node", "arguments": {"labels": ["Person"], "properties": {"name": "John Doe", "age": 30, "email": "john@example.com"}}}]}}' | python mcp_server.py
Execute Cypher Query
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "neo4j_run_cypher_query", "arguments": {"query": "MATCH (p:Person) RETURN p.name, p.age LIMIT 5"}}]}}' | python mcp_server.py
Formatted Output:
--- Record 1 ---
p.name: John Doe
p.age: 30
--- Record 2 ---
p.name: John Doe
p.age: 30
Total records: 2
Nodes by label:
Person: 2
Find Shortest Path
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "graph_find_shortest_path", "arguments": {"start_node_id": 1, "end_node_id": 10, "relationship_types": ["WORKS_FOR", "KNOWS"]}}]}}' | python mcp_server.py
Calculate PageRank
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "graph_calculate_pagerank", "arguments": {"node_labels": ["Person", "Company"]}}]}}' | python mcp_server.py
Analyze Graph Structure
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "graph_analyze_structure", "arguments": {"random_string": "test"}}]}}' | python mcp_server.py
Formatted Output:
Graph Statistics:
Total Nodes: 15
Total Relationships: 0
Node Labels: 8
Relationship Types: 0
Top Nodes by Degree:
1. Node 1 (Person): degree 0
2. Node 2 (Person): degree 0
3. Node 4 (TestNode): degree 0
RAG Augmentation
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"calls": [{"name": "augmentation_augment_for_rag", "arguments": {"query": "Find people working in tech companies", "node_ids": [1, 2, 3, 4, 5]}}]}}' | python mcp_server.py
Development
Running Tests
# Test the MCP server directly
python test_mcp.py
# Test with quick start script
python quick_start.py
Code Structure
neo4j_mcp/
โโโ mcp_server.py # MCP server entry point (stdio communication)
โโโ config.py # Configuration management
โโโ requirements.txt # Python dependencies
โโโ Dockerfile # Container configuration
โโโ docker-compose.yml # Development environment
โโโ mcp.json # Cursor MCP configuration
โโโ mcp/
โ โโโ __init__.py
โ โโโ neo4j_client.py # Neo4j operations with proper serialization
โ โโโ advanced_cypher.py # Graph analysis operations
โ โโโ augmentation_engine.py # Graph augmentation for RAG
โโโ scripts/
โ โโโ generate_secrets.py # Utility for generating secure credentials
โโโ examples/
โ โโโ cursor_integration.py # Example client implementation
โโโ tests/
โ โโโ __init__.py # Test framework (tests removed during cleanup)
โโโ README.md
Configuration
Environment variables can be set in a .env
file. For security, never commit the .env
file to version control.
Security Setup
-
Generate secure credentials:
python scripts/generate_secrets.py
-
Manual configuration:
cp env.example .env # Edit .env with your secure credentials
Environment Variables
# Neo4j Configuration
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=your-secure-password-here
NEO4J_DATABASE=neo4j
# Server Configuration
HOST=0.0.0.0
PORT=8000
DEBUG=false
# Logging
LOG_LEVEL=INFO
# Security
SECRET_KEY=your-secret-key-here-change-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=30
Security Best Practices
- โ
Never commit
.env
files to version control - โ Use different credentials for each environment (dev, staging, prod)
- โ Generate secure passwords using the provided script
- โ Rotate credentials regularly in production
- โ Use environment-specific configurations for Docker deployments
Project Status
โ Completed Features
- MCP Server: Full Model Context Protocol implementation via stdio
- Neo4j Integration: Complete CRUD operations with proper serialization
- Graph Analysis: Path finding, PageRank, community detection
- Graph Augmentation: RAG-ready content transformation
- Cursor Integration: Ready-to-use MCP configuration
- Code Cleanup: Removed all unused code and modules
๐งน Recent Cleanup (Latest Update)
The project has been streamlined by removing unused code:
Removed Modules:
mcp/router.py
- FastAPI router (unused)mcp/auth.py
- JWT authentication (unused)mcp/validator.py
- Message validation (unused)mcp/schema.py
- JSON schema definitions (unused)tests/test_router.py
- Router tests (unused)tests/test_phase2.py
- Phase 2 tests (unused)
Removed Functions:
find_node()
,close()
,neo4j_client()
from neo4j_client.pyfind_cycles()
,calculate_centrality()
,find_triangles()
from advanced_cypher.pyPathAlgorithm
,GraphAlgorithm
enums from advanced_cypher.pyAugmentationType
enum from augmentation_engine.py
Result: ~50% code reduction while maintaining all core functionality
๐ Current Focus
- Stability: Ensuring robust error handling and connection management
- Documentation: Comprehensive examples and usage guides
- Testing: Automated testing for all MCP tools
๐ Future Enhancements
- Performance: Connection pooling and caching optimizations
- Monitoring: Metrics and observability improvements
- Advanced Features: Additional graph algorithms and analysis tools
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
This project is licensed under the MIT License - see the file for details.