mcp-neo4j-query-optimizer
Extracts structured operator data from Neo4j query plans and provides rich context for MCP clients to deliver intelligent optimization recommendations.
README
π 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
π 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-optimizer -
Install 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 10 - Get 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 10
Structured 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 |
|---|---|---|
optimize-neo4j-query |
Analyze and optimize a Neo4j query with before/after comparison | query (required), database (optional) |
analyze-query-plan |
Get detailed structured analysis of a query execution plan | query (required), database (optional) |
π 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.json - Windows:
%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_URI |
Neo4j database URI | No* | bolt://localhost:7687 |
NEO4J_USER |
Neo4j username | No* | neo4j |
NEO4J_PASSWORD |
Neo4j password | No* | password |
*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.pyfile - Verify 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-dotenv - Ensure 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.py
You 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"
- "Can you optimize this Cypher query:
π― 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 documentation - MCP 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! π
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.