ontology-mcp-self-healing

ontology-mcp-self-healing

Self-healing MCP server that monitors database schema changes, detects differences, and automatically updates ontology mappings using AI to ensure agents continue working without manual intervention.

Category
访问服务器

README

Self-Healing Ontology MCP Agent System

Python 3.10+ License: MIT MCP Tests

A production-ready self-healing multi-agent system that uses ontologies and MCP (Model Context Protocol) to automatically adapt when database schemas change.

Overview

This system solves a critical problem in modern AI agent deployments: when database schemas change, agent queries break. Instead of manually updating every agent and query, this system:

  1. Monitors database schemas continuously
  2. Detects schema changes automatically
  3. Analyzes changes using Claude AI
  4. Heals ontology mappings automatically
  5. Reloads MCP tools without downtime

The result: agents continue working seamlessly even when databases evolve.

Architecture

┌─────────────┐      ┌──────────────┐      ┌─────────────┐
│   Agents    │─────▶│ MCP Server   │─────▶│  Database   │
│ (Analytics, │      │ (Ontology)   │      │  (SQLite,   │
│  Support)   │      │              │      │  PostgreSQL)│
└─────────────┘      └──────┬───────┘      └─────────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │ Schema Monitor  │
                   │ (SHA-256 Hash)  │
                   └────────┬────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │  Diff Engine    │
                   │ (Change Detect) │
                   └────────┬────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │ Ontology Remap  │
                   │ (Claude AI)     │
                   └─────────────────┘

Features

  • Automatic Schema Change Detection - SHA-256 hash-based monitoring
  • Intelligent Diff Analysis - Detects renames, additions, deletions
  • AI-Powered Healing - Uses Claude to update ontology mappings
  • MCP Protocol Support - Native Model Context Protocol integration
  • Multi-Agent Support - Shared semantic understanding across agents
  • Hot Reload - MCP server reloads without downtime
  • Audit Logging - Complete JSON audit trail
  • Alert Integration - Slack/Teams webhook support
  • Production Ready - Docker, tests, error handling

Quickstart (< 5 minutes)

1. Install Dependencies

pip install -r requirements.txt

2. Set Up Environment

# Create .env file
echo "ANTHROPIC_API_KEY=your_api_key_here" > .env

3. Initialize Database and Ontology

# Create sample database
python scripts/init_db.py

# Generate initial ontology
python scripts/setup_ontology.py

4. Run Quickstart Example

python examples/quickstart.py

You should see:

  • ✓ MCP Server initialized
  • ✓ Tools generated from ontology
  • ✓ Schema monitoring active
  • ✓ Agent system ready

5. Test Schema Change Healing

# In another terminal, modify the database schema
sqlite3 test_database.db "ALTER TABLE customers ADD COLUMN phone TEXT;"

# Watch the system automatically detect and heal
python examples/full_system.py

Installation

From Source

git clone https://github.com/yourusername/ontology-mcp-self-healing.git
cd ontology-mcp-self-healing
pip install -r requirements.txt
pip install -e .

Using Docker

# Build and run
docker-compose up -d

# View logs
docker-compose logs -f

Configuration

Configuration is managed via config/config.yaml:

# Database Configuration
database:
  type: sqlite  # sqlite, postgresql, mysql
  connection_string: sqlite:///./test_database.db

# Ontology Configuration
ontology:
  main_file: ontologies/business_domain.owl
  auto_reload: true

# Schema Monitoring
monitoring:
  enabled: true
  check_interval: 60  # seconds
  detect_renames: true

# Auto-Healing
healing:
  enabled: true
  auto_approve: false  # Set to true for automatic healing
  claude_model: claude-3-5-sonnet-20241022
  validation_enabled: true

# Alerts
alerts:
  enabled: true
  webhook_url: ${ALERT_WEBHOOK_URL}  # Optional

Usage Examples

Basic MCP Server

from src.mcp_server.server import OntologyMCPServer

# Initialize server
server = OntologyMCPServer()

# Get available tools
tools = server.get_tools()

# Execute query
result = await server.execute_tool(
    "query_order",
    {"query": "all orders", "limit": 10}
)

Create an Agent

from src.mcp_server.server import OntologyMCPServer
from src.agents.examples.analytics_agent import AnalyticsAgent

# Initialize MCP server
mcp_server = OntologyMCPServer()

# Create agent
agent = AnalyticsAgent(mcp_server, claude_api_key="your_key")

# Query using natural language
response = await agent.query("What are the total sales for last month?")

Full Self-Healing System

from src.system.self_healing import SelfHealingAgentSystem

# Initialize system
system = SelfHealingAgentSystem()

# Start monitoring and healing
system.start()

# System runs forever, auto-healing on schema changes

Architecture Details

MCP Server

The MCP server loads OWL ontologies and generates tools dynamically:

  • Extracts class → table mappings
  • Extracts property → column mappings
  • Translates semantic queries to SQL
  • Caches queries for performance

Schema Monitor

Continuous monitoring using:

  • SQLAlchemy inspector for schema capture
  • SHA-256 hashing for change detection
  • Configurable check intervals
  • Event callbacks on changes

Diff Engine

Intelligent diff computation:

  • Detects table/column additions/removals
  • Heuristic-based rename detection
  • Type change detection
  • Detailed diff reporting

Auto Remapper

AI-powered ontology healing:

  • Extracts current ontology mappings
  • Generates LLM prompts with schema changes
  • Validates proposed RDF triples
  • Applies updates to ontology files
  • Supports manual approval mode

Production Deployment

Docker Deployment

# Build image
docker build -t ontology-mcp-self-healing .

# Run container
docker run -d \
  -e ANTHROPIC_API_KEY=your_key \
  -v $(pwd)/ontologies:/app/ontologies \
  -v $(pwd)/logs:/app/logs \
  ontology-mcp-self-healing

Docker Compose

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f self-healing

# Stop services
docker-compose down

See docs/deployment.md for Kubernetes, Helm, and production best practices.

Testing

# Run all tests
pytest tests/ -v

# Run with coverage
pytest tests/ --cov=src --cov-report=html

# Run specific test
pytest tests/test_mcp_server.py -v

Documentation

Project Structure

ontology-mcp-self-healing/
├── README.md
├── requirements.txt
├── setup.py
├── docker-compose.yml
├── Dockerfile
├── config/
│   └── config.yaml
├── ontologies/
│   └── business_domain.owl
├── src/
│   ├── mcp_server/      # MCP server implementation
│   ├── monitoring/      # Schema monitoring
│   ├── healing/         # Auto-healing
│   ├── system/          # Orchestration
│   └── agents/         # Agent implementations
├── tests/              # Test suite
├── examples/           # Example scripts
├── scripts/            # Setup scripts
└── docs/               # Documentation

Getting Started

New to this project? Follow our comprehensive SETUP_GUIDE.md for step-by-step instructions on:

  • Cloning the repository
  • Setting up your environment
  • Running examples
  • Running tests
  • Troubleshooting common issues

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE file for details.

Publishing to GitHub

Want to publish this project? See GITHUB_SETUP.md for step-by-step instructions.

Acknowledgments

Related Articles


Made with ❤️ for the AI agent community

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选