neo4j_mcp

dpartin/neo4j_mcp

3.1

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

ModuleDescription
MCP ServerMain server implementing Model Context Protocol via stdio communication
Neo4j ClientWraps Neo4j operations (CRUD, Cypher queries) with proper serialization
Advanced CypherGraph analysis operations (path finding, PageRank, community detection)
Augmentation EngineTransforms graph data into embeddings and RAG-ready content

Tech Stack

LayerTools/Technologies
BackendPython, MCP Protocol
MessagingJSON-RPC over stdio
Graph DatabaseNeo4j with neo4j-driver
ContainerizationDocker, Docker Compose
Testingpytest

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
  1. Install Neo4j Desktop or Neo4j Community Edition
  2. Start Neo4j on your local machine
  3. Default connection: bolt://localhost:7687
Option 2: Neo4j AuraDB (SaaS)
  1. Create a free account at Neo4j AuraDB
  2. Get your connection string (format: bolt+s://<instance-id>.neo4j.io:7687)
  3. Update your .env file with the connection details
Option 3: Self-hosted Neo4j
  1. Deploy Neo4j on your preferred platform (AWS, GCP, Azure, etc.)
  2. Configure network access to allow connections from your MCP server
  3. Update your .env file with the connection details

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd neo4j_mcp
    
  2. Generate secure credentials:

    python scripts/generate_secrets.py
    
  3. 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
    
  4. Start the MCP server:

    # Build and test the Docker image
    ./scripts/setup_mcp_docker.sh
    
    # Or manually
    docker build -t neo4j_mcp .
    
  5. 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:

  1. Build the Docker image:

    # On Linux/Mac
    ./scripts/setup_mcp_docker.sh
    
    # On Windows
    scripts\setup_mcp_docker.bat
    
  2. Or manually:

    docker build -f Dockerfile.mcp -t neo4j_mcp_server .
    
  3. 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:

  1. 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
    
  2. Available Tools:

    • neo4j_create_node - Create nodes with labels and properties
    • neo4j_run_cypher_query - Execute Cypher queries
    • neo4j_create_relationship - Create relationships between nodes
    • graph_find_shortest_path - Find shortest paths between nodes
    • graph_find_all_paths - Find all paths up to a maximum length
    • graph_calculate_pagerank - Calculate PageRank for nodes
    • graph_detect_communities - Detect communities using algorithms
    • graph_analyze_structure - Analyze overall graph structure
    • augmentation_augment_for_rag - Augment graph data for RAG
  3. 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:

  1. Check the MCP server is running correctly:

    python mcp_server.py
    
  2. Verify the mcp.json configuration:

    • Ensure the command and args point to the correct Python executable and script
    • Check that the cwd path is correct for your workspace
  3. Check Neo4j connection:

    • The MCP server will show warnings if Neo4j is not available
    • Tools will return error messages if Neo4j is not connected
  4. 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 properties
  • neo4j_run_cypher_query - Execute Cypher queries with formatted results
  • neo4j_create_relationship - Create relationships between nodes
  • graph_find_shortest_path - Find shortest paths between nodes
  • graph_find_all_paths - Find all paths up to a maximum length
  • graph_calculate_pagerank - Calculate PageRank for nodes
  • graph_detect_communities - Detect communities using algorithms
  • graph_analyze_structure - Analyze overall graph structure
  • augmentation_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 NameArgumentsDescription
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 NameArgumentsDescription
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 NameArgumentsDescription
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

  1. Generate secure credentials:

    python scripts/generate_secrets.py
    
  2. 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.py
  • find_cycles(), calculate_centrality(), find_triangles() from advanced_cypher.py
  • PathAlgorithm, GraphAlgorithm enums from advanced_cypher.py
  • AugmentationType 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

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

This project is licensed under the MIT License - see the file for details.