Skip to main content
Glama
connectimtiazh

Bi-Temporal Knowledge Graph MCP Server

README.md
# Bi-Temporal Knowledge Graph MCP Server

A production-ready MCP (Model Context Protocol) server that combines a sophisticated bi-temporal knowledge graph with dynamic automation tool generation. Save facts with full temporal tracking, extract entities using AI, and generate custom automation tools on-the-fly from database configurations.

**๐ŸŽฏ Build intelligent AI agents with persistent memory that understands time and context**

## Architecture

This server uses a modular architecture:

- **main.py** - The main orchestrator that initializes FastMCP, registers core memory tools, and manages the complete server lifecycle
- **memory.py** - Bi-temporal Graphiti memory implementation with FalkorDB for knowledge graph storage
- **tools.py** - Container for automation tools with webhook execution utilities

---

## โญ Star This Repo

If you find this project useful, please give it a star! It helps others discover the project and motivates continued development.

![How to star this repo](./assets/star-repo.png)

---

## ๐Ÿ”— Links

- ๐ŸŽ **[Get Started](#-quick-start)** - Ready in 5 minutes
- ๐ŸŽฅ **[Video Tutorial](YOUR_YOUTUBE_VIDEO_LINK)** - Watch how to set it up
- โ“ **[FAQs](#-frequently-asked-questions)** - Common questions answered
- ๐Ÿ› **[Report Bugs](https://github.com/YOUR_USERNAME/bitemporal-mcp-server/issues)** - Found an issue?
- ๐Ÿ†• **[Request Features](https://github.com/YOUR_USERNAME/bitemporal-mcp-server/issues)** - Have an idea?

### Resources

- ๐Ÿ’ฌ **[Community](https://www.skool.com/knowledge-engineering-hub-9993)** - High Ticket AI Builders community
- ๐Ÿ“š **[Full Documentation](./README.md)** - Complete guide
- ๐Ÿš€ **[Deployment Guide](./DEPLOYMENT.md)** - Deploy anywhere
- ๐Ÿงช **[Examples](./examples.py)** - Interactive scenarios

---

## ๐Ÿ“‘ Table of Contents

- [Features](#-features)
- [How It Works](#-how-it-works)
- [Screenshots](#-screenshots)
- [Video Tutorial](#-video-tutorial)
- [Quick Start](#-quick-start)
- [Creating Automation Tools](#-creating-automation-tools)
- [Use Cases](#-use-cases)
- [FAQ](#-frequently-asked-questions)
- [Changelog](#-changelog)
- [Support](#-support)
- [License](#-license)

---

## โœจ Features

### ๐Ÿง  Bi-Temporal Knowledge Graph
- **Smart Memory**: Automatically tracks when facts were created AND when they became true in reality
- **Conflict Resolution**: When you move locations or change jobs, old facts are automatically invalidated
- **Time Travel Queries**: Ask "Where did John live in March 2024?" and get accurate historical answers
- **Session Tracking**: Maintains context across conversations with automatic cleanup

### ๐Ÿค– AI-Powered Entity Extraction
- **Natural Language Understanding**: Just tell it in plain English - "Alice moved to San Francisco and started working at Google"
- **Automatic Relationship Discovery**: AI extracts entities and relationships without manual input
- **OpenAI Integration**: Uses GPT-4 for intelligent entity extraction
- **Graceful Degradation**: Works without AI - just add facts manually

### ๐Ÿ› ๏ธ Dynamic Tool Generator
- **Flexible Configuration**: Define webhook configurations easily
- **Auto-Generate Code**: Automatically creates Python functions from your configs
- **Single & Multi-Webhook**: Execute one webhook or fire multiple in parallel
- **Hot Reload**: New tools available instantly without restarting

### ๐Ÿš€ Production Ready
- **Docker Support**: Complete docker-compose setup included
- **Replit Optimized**: Built specifically for Replit Autoscale environments
- **Resource Management**: Automatic session cleanup and connection pooling
- **Health Checks**: Built-in monitoring and status endpoints
- **100% Privacy-Friendly**: Your data stays in your database

---

## ๐ŸŽฌ How It Works

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  1. Natural Language Input                              โ”‚
โ”‚  "Bob moved to NYC and joined Google as a PM"          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  2. AI Entity Extraction (OpenAI)                       โ”‚
โ”‚  โ€ข Bob -> lives in -> NYC                               โ”‚
โ”‚  โ€ข Bob -> works at -> Google                            โ”‚
โ”‚  โ€ข Bob -> has role -> PM                                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  3. Bi-Temporal Storage (FalkorDB)                      โ”‚
โ”‚  โ€ข Fact: Bob works at Google                            โ”‚
โ”‚  โ€ข created_at: 2024-12-19T10:00:00Z                     โ”‚
โ”‚  โ€ข valid_at: 2024-12-19T10:00:00Z                       โ”‚
โ”‚  โ€ข invalid_at: null (still true)                        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  4. Query Anytime                                       โ”‚
โ”‚  โ€ข "Where does Bob work now?" โ†’ Google                  โ”‚
โ”‚  โ€ข "What was Bob's job history?" โ†’ All past jobs        โ”‚
โ”‚  โ€ข "Where did Bob live in 2023?" โ†’ Historical data      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

---

## ๐Ÿ“ธ Screenshots

### Memory in Action
![Knowledge Graph Example](./assets/screenshot-graph.png)

### AI Entity Extraction
![Entity Extraction Demo](./assets/screenshot-extraction.png)

### Dynamic Tool Generation
![Tool Generator Interface](./assets/screenshot-tools.png)

### Temporal Queries
![Time-Travel Query Results](./assets/screenshot-temporal.png)

---

## ๐ŸŽฅ Video Tutorial

**Watch the complete setup and usage guide:**

[![Bi-Temporal MCP Server Tutorial](./assets/video-thumbnail.png)](YOUR_YOUTUBE_VIDEO_LINK)

**Topics covered:**
- Installation & setup (0:00)
- Adding your first facts (2:30)
- Using AI entity extraction (5:15)
- Creating automation tools (8:45)
- Temporal queries (12:20)
- Deployment to production (15:00)

---

## ๐Ÿš€ Quick Start

### Option 1: Docker Compose (Recommended)

```bash
# 1. Download and extract
wget https://github.com/YOUR_USERNAME/bitemporal-mcp-server/archive/main.zip
unzip main.zip
cd bitemporal-mcp-server-main

# 2. Configure
echo "OPENAI_API_KEY=sk-your-key" > .env

# 3. Start everything (FalkorDB + MCP Server)
docker-compose up -d

# 4. Verify it's running
curl http://localhost:8080/health
```

**That's it! ๐ŸŽ‰** Your server is now running at `http://localhost:8080/sse`

### Option 2: Python (Local Development)

```bash
# 1. Install dependencies
pip install -r requirements.txt

# 2. Configure
cp .env.example .env
# Edit .env with your settings

# 3. Start FalkorDB (Docker)
docker run -d -p 6379:6379 falkordb/falkordb:latest

# 4. Run the server
python main.py
```

### Option 3: One-Click Deploy

[![Deploy to Replit](https://replit.com/badge/github/YOUR_USERNAME/bitemporal-mcp-server)](https://replit.com/github/YOUR_USERNAME/bitemporal-mcp-server)

---

## ๐Ÿ› ๏ธ Creating Automation Tools

### Overview

The tool generator reads webhook configurations and automatically creates MCP tools. Here's how:

### Step 1: Define Your Webhook in Automation Engine OS

![Automation Engine Interface](./assets/automation-engine-setup.png)

1. Go to [Automation Engine OS](YOUR_AUTOMATION_ENGINE_LINK)
2. Create a new webhook configuration
3. Define fields and parameters
4. Save your configuration

### Step 2: Generate the MCP Tool

```python
# Via MCP protocol or directly in Python
await generate_tool_from_db(
    user_id="your_user_id",
    item_name="Slack Notification",
    item_type="single"  # or "multi" for multiple webhooks
)
```

### Step 3: Use Your New Tool

```python
# Your tool is now available!
await slack_notification(
    message="Deployment completed!",
    channel="#devops"
)
```

### Example: Single Webhook Tool

**Database Configuration:**
```json
{
  "name": "Send Email",
  "url": "https://api.example.com/send-email",
  "template_fields": {
    "to": {"type": "str", "required": true},
    "subject": {"type": "str", "required": true},
    "body": {"type": "str", "required": true}
  }
}
```

**Generated Tool:**
```python
@mcp.tool()
async def send_email(to: str, subject: str, body: str):
    """Send an email via webhook."""
    # Automatically generated code
```

### Example: Multi-Webhook Tool (Parallel Execution)

**Database Configuration:**
```json
{
  "name": "Broadcast Alert",
  "webhooks": [
    {"url": "https://hooks.slack.com/...", "data": {"message": "..."}},
    {"url": "https://discord.com/api/webhooks/...", "data": {"content": "..."}},
    {"url": "https://api.email.com/send", "data": {"subject": "..."}}
  ]
}
```

**Result:** All three webhooks fire simultaneously using `asyncio.gather`!

---

## ๐Ÿ’ก Use Cases

### Personal Knowledge Management
Track your life events, relationships, and locations with full history:
```python
await add_message(
    "I met Sarah at the tech conference. She works at OpenAI.",
    session_id="my_life"
)
# Later: "Where did I meet Sarah?" โ†’ "At the tech conference"
```

### Customer Relationship Management
Monitor customer interactions with automatic conflict resolution:
```python
await add_fact("CustomerA", "status", "premium")
# Automatically invalidates previous "status" facts
# Query history: "What was CustomerA's status in January?"
```

### AI Agent Memory
Give your AI agents persistent, queryable memory:
```python
# Agent learns from conversation
await add_message(
    "User prefers morning meetings and uses Slack",
    session_id="agent_123"
)
# Agent recalls later: "What are the user's preferences?"
```

### Workflow Automation
Combine knowledge with actions:
```python
# When fact changes, trigger automation
if customer_upgraded_to_premium:
    await notify_sales_team(customer_name=name)
    await update_crm(customer_id=id, tier="premium")
```

---

## โ“ Frequently Asked Questions

### Q: Does this require OpenAI?
**A:** No! OpenAI is optional for AI entity extraction. You can add facts manually without it.

### Q: Can I use this with Claude Desktop?
**A:** Yes! Add the server URL to your `claude_desktop_config.json`:
```json
{
  "mcpServers": {
    "knowledge-graph": {
      "url": "http://localhost:8080/sse"
    }
  }
}
```

### Q: How do I query historical data?
**A:** Use the `query_at_time` tool:
```python
await query_at_time(
    timestamp="2024-01-15T00:00:00Z",
    entity_name="John"
)
```

### Q: Can I deploy this to production?
**A:** Absolutely! See [DEPLOYMENT.md](./DEPLOYMENT.md) for guides on:
- Replit Autoscale
- Railway
- Render
- Fly.io
- Docker
- VPS

### Q: How does fact invalidation work?
**A:** When you add a fact about location or employment, the system automatically finds previous facts of the same type and marks them as `invalid_at: current_time`. Your query results only show current facts unless you specifically request historical data.

### Q: Can I create bulk download tools?
**A:** Yes! Create a multi-webhook template with multiple endpoints, and the tool generator will create a function that fires all webhooks in parallel.

### Q: Is my data secure?
**A:** Yes! Everything runs in your infrastructure. No data is sent anywhere except:
- OpenAI (only if you use entity extraction)
- Your configured webhooks (only when you call them)

### Q: How much does it cost to run?
**A:** Free for self-hosting! Only costs:
- FalkorDB hosting (free tier available)
- OpenAI API usage (optional, ~$0.001 per extraction)

---

## ๐Ÿ“‹ Changelog

### [1.0.0] - 2024-12-19

#### Added
- โœ… Full bi-temporal tracking (created_at, valid_at, invalid_at, expired_at)
- โœ… Smart conflict resolution for location and employment changes
- โœ… Session-aware episodic memory with 30-minute TTL
- โœ… OpenAI-powered entity extraction from natural language
- โœ… Dynamic tool generator for automation workflows
- โœ… Single webhook tool template
- โœ… Multi-webhook parallel execution template
- โœ… Docker and Docker Compose support
- โœ… Replit Autoscale optimization
- โœ… Background cleanup manager
- โœ… Comprehensive documentation and examples

#### Supported Features
| Feature | Status | Notes |
|---------|--------|-------|
| Bi-Temporal Tracking | โœ… | Full implementation |
| AI Entity Extraction | โœ… | OpenAI GPT-4 |
| Smart Invalidation | โœ… | Location, employment, relationships |
| Session Management | โœ… | Auto-cleanup after 30 min |
| Dynamic Tools | โœ… | Single & multi-webhook |
| Parallel Webhooks | โœ… | asyncio.gather |
| Docker Support | โœ… | Complete stack included |
| Health Checks | โœ… | Built-in monitoring |

---

## ๐Ÿ†˜ Support

### Need Help?

1. **Check Documentation**: Start with [QUICKSTART.md](./QUICKSTART.md)
2. **Join Community**: [High Ticket AI Builders](https://www.skool.com/knowledge-engineering-hub-9993) - Free access!
3. **Watch Tutorial**: [Video Guide](YOUR_YOUTUBE_VIDEO_LINK)
4. **Report Bugs**: [GitHub Issues](https://github.com/YOUR_USERNAME/bitemporal-mcp-server/issues)

### Creating Tools in Automation Engine OS

![Automation Engine Setup Guide](./assets/automation-engine-guide.png)

**Need help setting up automation tools?** Join our community for:
- ๐Ÿ“น Video tutorials
- ๐Ÿค 1-on-1 support
- ๐Ÿ’ก Example configurations
- ๐ŸŽ“ Best practices

**๐Ÿ‘‰ [Access the tool and community for free](https://www.skool.com/knowledge-engineering-hub-9993)**

---

## ๐Ÿค Contributing

Contributions are welcome! Areas for improvement:

- ๐Ÿ” Additional temporal query operators
- ๐Ÿง  Enhanced entity extraction prompts
- ๐Ÿ”ง More webhook authentication methods
- ๐Ÿ“Š Performance optimizations
- ๐ŸŒ Additional deployment platforms
- ๐Ÿ“– More examples and tutorials

**To contribute:**
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

---

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

**TL;DR:** You can use this commercially, modify it, distribute it. Just keep the license notice.

---

## ๐Ÿ™ Acknowledgments

- Built with [FastMCP](https://github.com/jlowin/fastmcp)
- Powered by [FalkorDB](https://www.falkordb.com/)
- AI features via [OpenAI](https://openai.com/)
- Inspired by the High Ticket AI Builders community

---

## โญ Star History

[![Star History Chart](https://api.star-history.com/svg?repos=YOUR_USERNAME/bitemporal-mcp-server&type=Date)](https://star-history.com/#YOUR_USERNAME/bitemporal-mcp-server&Date)

---

## ๐Ÿ“ž Connect

- ๐Ÿ’ฌ **Community**: [High Ticket AI Builders](https://www.skool.com/knowledge-engineering-hub-9993)
- ๐Ÿ“… **Want this implemented for your business?** [Book a Meeting](https://calendly.com/aiagentready/meeting)

---

<div align="center">

**Built with โค๏ธ for the High Ticket AI Builders ecosystem**

If this project helps you, please consider giving it a โญ!

[โฌ† Back to Top](#bi-temporal-knowledge-graph-mcp-server)

</div>