Skip to main content
Glama
ryoureddy

Cardiology Knowledge Graph MCP

by ryoureddy
README.md
# Cardiology Knowledge Graph MCP Server

A Model Context Protocol (MCP) server that creates and queries a cardiology knowledge graph using Neo4j and LLM-powered entity extraction.

## Features

- 📚 **Document Ingestion**: Process PDF files or raw text to extract cardiology entities and relationships
- 🧠 **LLM-Powered Extraction**: Uses GPT-4 (or customizable models like BioGPT) for intelligent extraction
- 📊 **Knowledge Graph**: Stores data in Neo4j with proper relationships
- 🔍 **Natural Language Queries**: Query the graph using plain English
- ✏️ **Human-in-the-Loop**: Review and edit extractions before adding to graph
- 📈 **Graph Analytics**: Get statistics and insights about your knowledge graph

## Prerequisites

### 1. Neo4j Setup
- **Option A (Recommended)**: Download [Neo4j Desktop](https://neo4j.com/download/) for Mac
  - Create a new database with these credentials:
    - URI: `bolt://localhost:7687`
    - Username: `neo4j`
    - Password: `password` (or your choice)
  - Start the database

- **Option B**: Use [Neo4j Aura](https://neo4j.com/cloud/aura/) (free cloud instance)
  - Update connection details in your environment variables

### 2. API Key
- Get an OpenAI API key from [OpenAI Platform](https://platform.openai.com/api-keys)
- Or set up alternative models (see Configuration section)

## Installation

1. **Clone and setup**:
   ```bash
   git clone <your-repo>
   cd "Cardiology Knowledge Graph MCP"
   ```

2. **Install dependencies**:
   ```bash
   pip install -r requirements.txt
   ```

3. **Set up environment variables**:
   ```bash
   cp .env.example .env
   # Edit .env with your actual values
   ```

4. **Test the server**:
   ```bash
   python mcp_server.py
   ```

## Claude Desktop Configuration

1. **Find your Claude Desktop config**:
   - Mac: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - Create the file if it doesn't exist

2. **Add the MCP server configuration**:
   ```json
   {
     "mcpServers": {
       "cardiology-kg": {
         "command": "python",
         "args": ["/full/path/to/your/mcp_server.py"],
         "env": {
           "NEO4J_URI": "bolt://localhost:7687",
           "NEO4J_USERNAME": "neo4j",
           "NEO4J_PASSWORD": "your-password",
           "OPENAI_API_KEY": "your-openai-key"
         }
       }
     }
   }
   ```

3. **Restart Claude Desktop** and look for the 🔨 hammer icon to confirm the server is connected.

## Usage

### 1. Document Ingestion

**Process a PDF file**:
```
Ingest this cardiology document: /path/to/cardiology-textbook-chapter.pdf
```

**Process raw text**:
```
Ingest this cardiology note: "Patient presents with atrial fibrillation. Echocardiogram shows left ventricular hypertrophy. Prescribed metoprolol for rate control."
```

The system will:
- Extract entities (conditions, medications, procedures, anatomy)
- Identify relationships (causes, treats, affects, etc.)
- Return a draft JSON for your review

### 2. Review and Edit Extractions

After ingestion, you'll get a draft like:
```json
{
  "entities": [
    {"name": "atrial fibrillation", "label": "Condition", "properties": {}},
    {"name": "metoprolol", "label": "Medication", "properties": {"class": "beta-blocker"}}
  ],
  "relationships": [
    {"source": "metoprolol", "target": "atrial fibrillation", "type": "TREATS", "properties": {"purpose": "rate control"}}
  ]
}
```

Edit as needed, then add to graph:
```
Add this to my knowledge graph: [paste your edited JSON]
```

### 3. Query the Knowledge Graph

Ask natural language questions:
```
What medications treat atrial fibrillation?
How does left ventricular hypertrophy affect cardiac function?
Show me all conditions that cause heart failure.
What procedures are used to diagnose coronary artery disease?
```

### 4. Graph Management

**Get statistics**:
```
Show me statistics about my cardiology knowledge graph
```

**Clear the graph** (caution!):
```
Clear my knowledge graph
```

## Advanced Configuration

### Using Alternative LLMs

**BioGPT (specialized medical model)**:
```python
# Uncomment in mcp_server.py:
from langchain_huggingface import HuggingFaceHub
llm = HuggingFaceHub(repo_id="microsoft/BioGPT")
```

**Local Ollama model**:
```python
# Uncomment in mcp_server.py:
from langchain_community.llms import Ollama
llm = Ollama(model="llama2")  # or "biomedical-llm"
```

### Custom Entity Types and Relationships

Edit the extraction prompt in `mcp_server.py` to focus on specific:
- Anatomical structures
- Drug classes
- Diagnostic criteria
- Treatment protocols

### Integration with Neo4j Official MCP Servers

Install additional Neo4j MCP servers for enhanced capabilities:
```bash
pip install mcp-neo4j-cypher mcp-neo4j-memory
```

Add to Claude config:
```json
{
  "mcpServers": {
    "cardiology-kg": { /* your custom server */ },
    "neo4j-cypher": {
      "command": "mcp-neo4j-cypher",
      "args": ["--db-url", "bolt://localhost:7687", "--user", "neo4j", "--password", "password"]
    }
  }
}
```

## Example Workflow

1. **Start with a textbook chapter**:
   ```
   Ingest this PDF: /Users/you/Downloads/cardiac-physiology-chapter.pdf
   ```

2. **Review the extraction** - you might see entities like:
   - Anatomy: "left ventricle", "aortic valve"
   - Processes: "cardiac cycle", "systole", "diastole"
   - Relationships: "systole FOLLOWS atrial contraction"

3. **Edit and refine** the JSON to add missing details or correct relationships

4. **Add to graph**:
   ```
   Add this to my knowledge graph: [your refined JSON]
   ```

5. **Query for insights**:
   ```
   Explain the cardiac cycle based on my knowledge graph
   What anatomical structures are involved in systole?
   How do beta-blockers affect the cardiac cycle?
   ```

## Troubleshooting

### Common Issues

**"Connection refused" error**:
- Ensure Neo4j database is running
- Check connection details in environment variables

**"API key not found"**:
- Verify OPENAI_API_KEY is set correctly
- Check Claude Desktop config environment variables

**"Module not found" errors**:
- Run `pip install -r requirements.txt` again
- Check Python virtual environment

**MCP server not appearing in Claude**:
- Verify the full path to `mcp_server.py` in config
- Restart Claude Desktop completely
- Check logs in Claude Desktop (Help → Show Logs)

### Logs and Debugging

The server logs helpful information. To see detailed logs:
```bash
python mcp_server.py 2>&1 | tee server.log
```

## Contributing

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

## License

MIT License - see LICENSE file for details.

## Acknowledgments

- Built on the Model Context Protocol by Anthropic
- Uses Neo4j for graph database capabilities
- Powered by LangChain for LLM integration
- Inspired by medical informatics and knowledge representation research