mcp-neo4j-query-optimizer
Provides tools for analyzing and optimizing Cypher queries executed against a Neo4j database, including extracting structured operator data from query plans, identifying performance issues, and suggesting index improvements and query rewrites.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-neo4j-query-optimizeroptimize Cypher: MATCH (n) WHERE n.id=1 RETURN n"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
π Neo4j Query Optimizer MCP Server
β οΈ Work in Progress: This repository is actively being developed. Feel free to try it out and provide feedback, but expect some changes and improvements as we development continues.
A comprehensive MCP (Model Context Protocol) server that extracts structured operator data from Neo4j query plans and provides rich context for MCP clients to interpret and provide intelligent optimization recommendations. Perfect for integration with Claude Desktop and other MCP clients.
β¨ Features
π Structured Data Extraction: Extracts comprehensive operator data from Neo4j query plans
π Performance Analysis: Identifies performance indicators and characteristics
π― Operator Classification: Based on official Neo4j operators documentation
π§ MCP Client Intelligence: Provides rich context for intelligent recommendations
β‘ Query Optimization: Basic optimization with before/after comparisons
π§ͺ Comprehensive Testing: 38 unit tests ensuring reliability
π Universal Compatibility: Works with any MCP client (Claude Desktop, etc.)
π Rich Context: Structured data for intelligent conversations
π Fast & Reliable: No external API dependencies, works offline
Related MCP server: Neo4j GraphRAG MCP Server
π Quick Start
Prerequisites
Python 3.8+
Neo4j database (local or cloud)
Claude Desktop or other MCP client
Installation
Clone the repository:
git clone <repository-url> cd mcp-query-optimizerInstall dependencies:
pip install -e .Configure Neo4j connection: Set up your Neo4j credentials in your MCP client configuration (see Configuration section below)
Configure MCP client: Add the server to your Claude Desktop or other MCP client configuration
π― Usage
Available Tools
The MCP server provides two main tools:
optimize-neo4j-query: Full optimization workflow with before/after comparison and rich context for conversationsanalyze-query-plan: Single query plan analysis with rich context for discussions
Claude Desktop Integration
Configure the MCP server in Claude Desktop settings
Ask Claude to optimize queries:
Can you optimize this Cypher query: MATCH (n) WHERE n.name = 'test' RETURN n LIMIT 10Get detailed analysis:
What performance issues does this query have: MATCH (p:Product)-[:HAS_SKU]->(s:SKU) WHERE p.category = 'Electronics' RETURN p, s
Direct MCP Usage
Test the server directly:
# List available tools
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | python src/mcp_neo4j_optimizer/agent.py
# Optimize a query
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "optimize-neo4j-query", "arguments": {"query": "MATCH (n) RETURN n"}}}' | python src/mcp_neo4j_optimizer/agent.pyπ Analysis Output
The optimizer provides:
Performance Issues
Critical: Full database scans, Cartesian products
High: Missing indexes, inefficient scans
Medium: Late filters, sorting issues
Low: Well-optimized operations
Recommendations
Specific optimization strategies
Implementation guidance
Priority-based suggestions
Index Suggestions
Exact CREATE INDEX statements
Property-specific recommendations
Composite index suggestions
Query Rewrites
Before/after query examples
Improved query structures
Performance-focused alternatives
ποΈ Architecture
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β MCP Client β β MCP Server β β Neo4j β
β (Claude, etc.) βββββΊβ βββββΊβ Database β
β β β β β β
β β’ Interprets β β β’ Extracts β β β’ Query Plans β
β operators β β operator data β β β’ Execution β
β β’ Provides β β β’ Classifies β β Stats β
β recommendationsβ β operators β β β
β β’ Generates β β β’ Structures β β β
β optimizations β β data β β β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββπ― Proper MCP Architecture
MCP Server Responsibilities:
Extracts structured operator data from Neo4j query plans
Classifies operators based on official Neo4j documentation
Provides performance indicators and characteristics
Structures data for MCP client interpretation
MCP Client Responsibilities:
Interprets operator data using knowledge of Neo4j operators
Provides intelligent recommendations and optimizations
Generates educational content and best practices
Creates before/after comparisons and explanations
π Recent Refactoring (v2.0) - Proper MCP Architecture
Major Changes:
β Structured Data Extraction: MCP server extracts operator data, client provides intelligence
β Operator Classification: Based on Neo4j operators documentation
β Comprehensive Testing: Added 38 unit tests covering all functionality
Proper MCP Architecture:
π― MCP Server: Extracts structured operator data from Neo4j query plans
π§ MCP Client: Uses knowledge of Neo4j operators to provide intelligent recommendations
π Structured Data: Rich context with operator details, performance indicators, and metadata
π Official Reference: Links to Neo4j documentation for operator understanding
π Example Analysis
Input Query:
MATCH (n) WHERE n.name = 'test' RETURN n LIMIT 10Structured Data Output:
{
"query": "MATCH (n) WHERE n.name = 'test' RETURN n LIMIT 10",
"query_type": "read",
"complexity": "medium",
"query_patterns": ["node matching", "property filtering", "result limiting"],
"operators": [
{
"operator": "NodeByLabelScan",
"clean_operator": "NodeByLabelScan",
"estimated_rows": 1000,
"db_hits": 1000,
"is_leaf": true,
"is_updating": false,
"is_eager": false,
"performance_characteristics": {
"operator_type": "NodeByLabelScan",
"estimated_rows": 1000,
"db_hits": 1000,
"performance_indicators": ["high_row_count"]
}
}
],
"summary": {
"total_operators": 3,
"leaf_operators": 1,
"updating_operators": 0,
"eager_operators": 0,
"estimated_total_rows": 1000,
"estimated_db_hits": 1000
},
"performance_indicators": ["high_row_count"],
"query_metadata": {
"has_where_clause": true,
"has_order_by": false,
"has_limit": true,
"has_aggregation": false,
"has_relationships": false
}
}MCP Client Interpretation: Based on this structured data, the MCP client can provide:
Performance Analysis: High row count indicates potential performance issues
Optimization Suggestions: Create indexes on filtered properties
Index Recommendations:
CREATE INDEX FOR (n:Node) ON (n.name)Best Practices: Use labels in MATCH clauses for better performance
π οΈ MCP Tools
Tool | Description | Parameters |
| Analyze and optimize a Neo4j query with before/after comparison |
|
| Get detailed structured analysis of a query execution plan |
|
π Tool Outputs
Both tools provide:
Structured operator data with performance characteristics
Query metadata and patterns
Performance indicators for MCP client interpretation
Rich context for intelligent recommendations
References to official Neo4j documentation
π¨ MCP Agent Features
Structured Data Extraction: Extracts comprehensive operator data from Neo4j query plans
Operator Classification: Based on official Neo4j operators documentation
Performance Analysis: Identifies performance indicators and characteristics
Rich Context Generation: Provides structured data for MCP client interpretation
Universal Compatibility: Works with any MCP client (Claude Desktop, etc.)
Offline Operation: No external API dependencies, works completely offline
π§ Configuration
MCP Client Configuration
Add this to your Claude Desktop or other MCP client configuration:
For Claude Desktop (macOS):
{
"mcpServers": {
"neo4j-query-optimizer": {
"command": "python",
"args": ["/path/to/your/mcp-query-optimizer/src/mcp_neo4j_optimizer/agent.py"],
"env": {
"NEO4J_URI": "neo4j+s://your-db-id.databases.neo4j.io",
"NEO4J_USER": "neo4j",
"NEO4J_PASSWORD": "your-password"
}
}
}
}Configuration File Location:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Important Notes:
Replace the Python path with your actual Python executable path
Replace the project path with your actual project location
Environment Variables
Variable | Description | Required | Default |
| Neo4j database URI | No* |
|
| Neo4j username | No* |
|
| Neo4j password | No* |
|
*Required for live database analysis. The MCP server works in rule-based analysis mode without these credentials.
π§ Troubleshooting
Common Issues
1. MCP Server Not Loading
Check that the Python path in your configuration is correct
Ensure the script path points to the actual
agent.pyfileVerify the script is executable:
chmod +x src/mcp_neo4j_optimizer/agent.py
2. "No tools available" Error
Restart Claude Desktop completely after configuration changes
Check the configuration file syntax with a JSON validator
Ensure the MCP server name matches in your configuration
3. Neo4j Connection Issues
The MCP server works without Neo4j credentials (rule-based mode)
For live database analysis, verify your Neo4j credentials
Check that your Neo4j database is accessible from your machine
4. Python Dependencies
Install required dependencies:
pip install neo4j python-dotenvEnsure you're using the correct Python environment
Testing the MCP Server
Test the MCP server directly:
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' | python src/mcp_neo4j_optimizer/agent.pyYou should see a JSON response with available tools.
π€ Contributing
Fork the repository
Create a feature branch
Make your changes
Add tests if applicable
Submit a pull request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π€ Neo4j Query Optimizer Agent - MCP Server
This project provides an intelligent Neo4j query optimization agent that can be integrated directly into Claude Desktop! The agent analyzes your Cypher queries, generates optimized versions, and compares the execution plans to show you exactly how performance improves.
Quick Setup for Claude Desktop
Copy the configuration:
{ "mcpServers": { "neo4j-optimizer-agent": { "command": "/path/to/your/anaconda3/bin/python", "args": ["/path/to/your/neo4j_optimizer_agent.py"] } } }Add to Claude Desktop MCP settings
Use in Claude:
"Can you optimize this Cypher query:
MATCH (n) RETURN n LIMIT 5""Analyze the query plan for:
MATCH (p:Product)-[:HAS_SKU]->(s:SKU) WHERE p.category = 'Electronics' RETURN p, s""Compare the before and after performance of my query optimization"
π― What the Agent Does
Core Functionality:
π Analyzes Original Query: Gets the execution plan from your Neo4j database
β‘ Generates Optimized Version: Creates an improved query based on detected issues
π Compares Plans: Shows you exactly what improved and why
π‘ Provides Insights: Explains the performance differences and next steps
Available MCP Tools
optimize-neo4j-query: Complete optimization workflow - analyzes original query, creates optimized version, compares execution plansanalyze-query-plan: Deep dive into a single query's execution plan without optimization
Testing the Agent
# Test tools list
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | python neo4j_optimizer_agent.py
# Test query optimization
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "optimize-neo4j-query", "arguments": {"query": "MATCH (n) RETURN n"}}}' | python neo4j_optimizer_agent.pyπ Agent Features
π Real Query Plan Analysis: Connects to your actual Neo4j database
β‘ Smart Optimizations: Detects AllNodesScan, CartesianProduct, and other expensive operations
π Before/After Comparison: Shows operator changes, row estimates, and improvements
π‘ Actionable Insights: Suggests indexes, query rewrites, and performance tips
π― Production Ready: Uses your actual database for realistic analysis
π Support
Issues: Report bugs and feature requests via GitHub issues
Documentation: Check
docs/API_DOCS.mdfor detailed API documentationMCP Integration: Use directly in Claude Desktop with the MCP server
Testing: Test the server directly with the provided examples
π Troubleshooting
Common Issues
β "Neo4j credentials not found"
Ensure environment variables are set correctly
Check your MCP client configuration
β "Cannot resolve address"
Verify your Neo4j database is running
Check your database credentials
β "Connection timeout"
Check your network connection
Verify Neo4j database is accessible
Happy Query Optimizing! π
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/dhodapkarsoham/mcp-neo4j-query-optimizer'
If you have feedback or need assistance with the MCP directory API, please join our Discord server