kgraph-mcp
v1.0.0
Published
MCP-powered Knowledge Graph system for dynamically constructing, querying, and updating graph databases with Neo4j/Memgraph
Maintainers
Readme
🌐 KnowledgeGraphMCP - Model Context Protocol Knowledge Graph System
A complete Model Context Protocol (MCP)-based system that enables LLMs to dynamically construct, query, and update knowledge graphs using Neo4j or Memgraph as the backend. Build complex knowledge graphs through natural language without hardcoding entities or relationships.
🔍 Overview
KnowledgeGraphMCP allows AI assistants to interact with graph databases in real-time, enabling:
- Dynamic Entity Management: Add entities (nodes) on-the-fly with custom types and metadata
- Relationship Creation: Connect entities with typed relationships
- Natural Language Querying: Convert natural language to Cypher queries automatically
- Graph Analytics: Get insights, statistics, and find patterns in your knowledge graph
- External Data Integration: Fetch and integrate data from external APIs
- Real-time Updates: Modify graph structure based on LLM interactions
✨ Features
- 🔄 Dynamic Graph Construction - No hardcoded schemas, create entities and relationships on demand
- 🧠 Natural Language Interface - Query graphs using plain English
- 📊 Built-in Analytics - Graph statistics, top connections, distribution analysis
- 🔗 External Data Integration - Pull data from APIs and automatically create graph structures
- 🔒 Security First - Input sanitization and safe query validation
- 🚀 Production Ready - Connection pooling, error handling, and graceful shutdowns
- 📚 Multiple Graph DBs - Supports both Neo4j and Memgraph
- 🎯 Domain Agnostic - Works for legal aid, startups, research, and any domain
🏗️ Architecture
┌─────────────────────────────────────────────────────────────┐
│ LLM Client │
│ (Issues natural language commands) │
└────────────────┬────────────────────────────────────────────┘
│
│ MCP Protocol (JSON-RPC over stdio)
│
┌────────────────┴────────────────────────────────────────────┐
│ Knowledge Graph MCP Server │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Tools: addEntity, addRelationship, queryGraph, │ │
│ │ searchEntities, graphAnalytics, etc. │ │
│ └────────────────────┬─────────────────────────────────┘ │
│ │ │
│ ┌────────────────────▼─────────────────────────────────┐ │
│ │ Database Connection Manager │ │
│ │ (Neo4j Driver / Memgraph) │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────┬────────────────────────────────────────────┘
│
│ Bolt Protocol
│
┌────────────────▼────────────────────────────────────────────┐
│ Neo4j / Memgraph Database │
│ (Graph storage with Cypher query language) │
└─────────────────────────────────────────────────────────────┘📋 Prerequisites
- Node.js 18+
- Neo4j or Memgraph database (local or cloud)
- An MCP-compatible client (Claude Desktop, Cline, etc.)
🚀 Installation
Quick Start with npx (Recommended)
Configure your MCP client:
{
"mcpServers": {
"knowledge-graph": {
"command": "npx",
"args": ["-y", "kgraph-mcp"],
"env": {
"NEO4J_URI": "bolt://localhost:7687",
"NEO4J_USERNAME": "neo4j",
"NEO4J_PASSWORD": "your_password"
}
}
}
}That's it! The server will auto-connect to your graph database.
Local Development
For contributing or modifying the code:
git clone https://github.com/gyash1512/KnowledgeGraphMCP.git
cd KnowledgeGraphMCP
npm install
npm run buildDatabase Setup
Using Neo4j Desktop (Easiest)
- Download Neo4j Desktop
- Create a new project and database
- Start the database (default:
bolt://localhost:7687) - Note your username and password
Using Docker
# Neo4j
docker run -d \
--name neo4j \
-p 7474:7474 -p 7687:7687 \
-e NEO4J_AUTH=neo4j/your_password \
neo4j:latest
# Or Memgraph
docker run -d \
--name memgraph \
-p 7687:7687 \
memgraph/memgraph:latest🎮 Usage
MCP Configuration
For Claude Desktop:
Edit your Claude Desktop config file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"knowledge-graph": {
"command": "npx",
"args": ["-y", "kgraph-mcp"],
"env": {
"NEO4J_URI": "bolt://localhost:7687",
"NEO4J_USERNAME": "neo4j",
"NEO4J_PASSWORD": "your_password"
}
}
}
}For local development:
{
"mcpServers": {
"knowledge-graph": {
"command": "node",
"args": ["./dist/server.js"],
"cwd": "/absolute/path/to/KnowledgeGraphMCP",
"env": {
"NEO4J_URI": "bolt://localhost:7687",
"NEO4J_USERNAME": "neo4j",
"NEO4J_PASSWORD": "your_password"
}
}
}
}📚 Available Tools
1. addEntity
Add a new entity (node) to the knowledge graph.
Parameters:
name(string, required): Unique entity nametype(string, required): Entity type/categorymetadata(object, optional): Additional properties
Example:
{
"name": "NutriGuide AI",
"type": "Startup",
"metadata": {
"founded": "2024",
"founder": "Yash Gupta",
"location": "Delhi",
"industry": "HealthTech"
}
}2. addRelationship
Create a relationship between two existing entities.
Parameters:
source(string, required): Source entity nametarget(string, required): Target entity nametype(string, required): Relationship typemetadata(object, optional): Relationship properties
Example:
{
"source": "NutriGuide AI",
"target": "Yash Gupta",
"type": "FOUNDED_BY",
"metadata": {
"date": "2024-01-15",
"role": "CEO"
}
}3. queryGraph
Query the graph using natural language or Cypher.
Parameters:
query(string, required): Natural language or Cypher queryuseNaturalLanguage(boolean, optional): Auto-convert to Cypher (default: true)
Examples:
// Natural language
{
"query": "Show all startups founded by Yash Gupta"
}
// Cypher query
{
"query": "MATCH (s:Startup)-[:FOUNDED_BY]->(p:Person {name: 'Yash Gupta'}) RETURN s",
"useNaturalLanguage": false
}4. searchEntities
Search for entities by name or type.
Parameters:
searchTerm(string, required): Search termentityType(string, optional): Filter by type
5. graphAnalytics
Get comprehensive graph statistics.
Parameters:
nodeType(string, optional): Filter by node typerelationshipType(string, optional): Filter by relationship type
Returns:
- Node and relationship counts
- Type distributions
- Top connected entities
- Graph density and average degree
6. externalData
Fetch data from external APIs and integrate into graph.
Parameters:
source(string, required): API source namequery(string, required): Query parametersendpoint(string, optional): Custom API endpointapiKey(string, optional): API authentication
7. deleteEntity
Remove an entity and its relationships.
Parameters:
name(string, required): Entity name to delete
8. getSubgraph
Get a subgraph starting from a specific entity.
Parameters:
entityName(string, required): Starting entitymaxDepth(number, optional): Max traversal depth (default: 2)relationshipTypes(array, optional): Filter relationship types
💡 Example Queries
Example 1: Building a Startup Ecosystem
Natural language commands:
1. "Add entity: Startup 'NutriGuide AI' with founder 'Yash Gupta'"
2. "Add entity: Investor 'Sequoia Capital' with metadata type 'VC Firm'"
3. "Add relationship: 'Sequoia Capital' invested in 'NutriGuide AI' with amount '1M USD'"
4. "Show all startups and their investors"Expected workflow:
- Creates Startup node
- Creates Investor node
- Creates INVESTED_IN relationship
- Returns graph showing connections
Example 2: Legal Aid System
Natural language commands:
1. "Add entity: Prisoner 'John Doe' in 'Tihar Jail'"
2. "Add entity: Volunteer 'Jane Smith' specializing in 'criminal law'"
3. "Add relationship: 'Jane Smith' assigned to 'John Doe'"
4. "Show all prisoners connected to volunteers in Delhi"Example 3: Knowledge Graph Analytics
Query:
"Get analytics for all Person entities"Returns:
{
"nodeCount": 150,
"relationshipCount": 320,
"nodeTypeDistribution": {
"Person": 150
},
"topConnectedNodes": [
{
"name": "Yash Gupta",
"type": "Person",
"connectionCount": 25
}
],
"averageDegree": 4.27,
"graphDensity": 0.0143
}🔧 API Response Schemas
Entity Object
{
id: string; // Database-generated ID
name: string; // Entity name
type: string; // Entity type
metadata: object; // Custom properties
createdAt: string; // ISO timestamp
updatedAt: string; // ISO timestamp
}Relationship Object
{
id: string; // Database-generated ID
source: string; // Source entity name
target: string; // Target entity name
type: string; // Relationship type
metadata: object; // Custom properties
createdAt: string; // ISO timestamp
}Query Result
{
nodes: Entity[]; // Matching nodes
relationships: Relationship[]; // Matching relationships
metadata: {
executionTime: number; // Query time in ms
query: string; // Executed query
resultCount: number; // Number of results
}
}🎯 Use Cases
Startup/Investment Tracking
- Map startup founders, investors, and funding rounds
- Track connections between companies
- Analyze investment patterns
Legal Aid Management
- Connect prisoners with legal volunteers
- Track case assignments and progress
- Map legal case relationships
Research Networks
- Build academic collaboration graphs
- Track paper citations and co-authorships
- Find research communities
Social Networks
- Map person-to-person relationships
- Analyze influence and connections
- Build organizational hierarchies
Knowledge Management
- Create interconnected knowledge bases
- Map concepts and relationships
- Build decision trees
🛠️ Development
Project Structure
KnowledgeGraphMCP/
├── src/
│ ├── server.ts # Main MCP server
│ ├── database.ts # Graph DB connection
│ ├── types.ts # TypeScript types
│ ├── utils.ts # Utility functions
│ └── cli.ts # CLI entry point
├── dist/ # Compiled output
├── package.json
├── tsconfig.json
└── README.mdBuilding
npm run build # Compile TypeScript
npm run watch # Watch mode for development
npm run clean # Clean dist folderTesting
# Start the server locally
npm run start
# Or with development build
npm run dev🔒 Security
- Input Sanitization: All user inputs are sanitized
- Query Validation: Dangerous Cypher operations are blocked
- Connection Security: Supports encrypted connections
- Environment Variables: Credentials stored securely in .env
🐛 Troubleshooting
Database Connection Failed
- Verify Neo4j/Memgraph is running:
http://localhost:7474 - Check credentials in config
- Ensure bolt port (7687) is accessible
Entity Already Exists
- Entity names must be unique
- Search for existing entity first
- Update metadata instead of recreating
Query Returns Empty
- Verify entities exist: use
searchEntities - Check relationship types match
- Try simpler query first
📞 Support
For issues, questions, or contributions:
- Open an issue on GitHub
- Check Neo4j Documentation
- Review MCP Specification
🤝 Contributing
Contributions welcome! Please read CONTRIBUTING.md for guidelines.
📄 License
MIT License - see LICENSE for details.
🙏 Acknowledgments
- Built with Model Context Protocol SDK
- Uses Neo4j graph database
- Compatible with Memgraph
- Inspired by the research at ResearchMCP
Built with ❤️ using TypeScript, MCP, and Graph Databases
