Skip to main content
Glama
kgraph-mcp

kgraph-mcp

by gyash1512
README.md
# 🌐 KnowledgeGraphMCP - Model Context Protocol Knowledge Graph System

[![npm version](https://img.shields.io/npm/v/kgraph-mcp.svg)](https://www.npmjs.com/package/kgraph-mcp)
[![GitHub](https://img.shields.io/badge/GitHub-gyash1512%2FKnowledgeGraphMCP-blue)](https://github.com/gyash1512/KnowledgeGraphMCP)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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:**

```json
{
  "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:

```bash
git clone https://github.com/gyash1512/KnowledgeGraphMCP.git
cd KnowledgeGraphMCP
npm install
npm run build
```

### Database Setup

#### Using Neo4j Desktop (Easiest)
1. Download [Neo4j Desktop](https://neo4j.com/download/)
2. Create a new project and database
3. Start the database (default: `bolt://localhost:7687`)
4. Note your username and password

#### Using Docker
```bash
# 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`

```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:**

```json
{
  "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 name
- `type` (string, required): Entity type/category
- `metadata` (object, optional): Additional properties

**Example:**
```json
{
  "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 name
- `target` (string, required): Target entity name
- `type` (string, required): Relationship type
- `metadata` (object, optional): Relationship properties

**Example:**
```json
{
  "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 query
- `useNaturalLanguage` (boolean, optional): Auto-convert to Cypher (default: true)

**Examples:**
```json
// 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 term
- `entityType` (string, optional): Filter by type

### 5. `graphAnalytics`
Get comprehensive graph statistics.

**Parameters:**
- `nodeType` (string, optional): Filter by node type
- `relationshipType` (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 name
- `query` (string, required): Query parameters
- `endpoint` (string, optional): Custom API endpoint
- `apiKey` (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 entity
- `maxDepth` (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:**
1. Creates Startup node
2. Creates Investor node
3. Creates INVESTED_IN relationship
4. 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:**
```json
{
  "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
```typescript
{
  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
```typescript
{
  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
```typescript
{
  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.md
```

### Building
```bash
npm run build        # Compile TypeScript
npm run watch        # Watch mode for development
npm run clean        # Clean dist folder
```

### Testing
```bash
# 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](https://github.com/gyash1512/KnowledgeGraphMCP/issues)
- Check [Neo4j Documentation](https://neo4j.com/docs/)
- Review [MCP Specification](https://modelcontextprotocol.io/)

## šŸ¤ Contributing

Contributions welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## šŸ“„ License

MIT License - see [LICENSE](LICENSE) for details.

## šŸ™ Acknowledgments

- Built with [Model Context Protocol SDK](https://github.com/modelcontextprotocol/sdk)
- Uses [Neo4j](https://neo4j.com/) graph database
- Compatible with [Memgraph](https://memgraph.com/)
- Inspired by the research at [ResearchMCP](https://github.com/gyash1512/ResearchMCP)

---

**Built with ā¤ļø using TypeScript, MCP, and Graph Databases**