{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Notice**: The `semantica.kg_qa` module is temporarily unavailable and will be reintroduced in a future release. Any quality assessment examples in this notebook are disabled."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb)\n",
    "\n",
    "# Medical Database Integration Pipeline\n",
    "\n",
    "## Overview\n",
    "\n",
    "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for medical database ingestion. Connect to medical database MCP servers via URL, ingest patient records, drug interactions, and clinical data, then build a healthcare knowledge graph.\n",
    "\n",
    "**IMPORTANT**: This implementation supports ONLY Python-based MCP servers and FastMCP servers. Users can bring their own Python/FastMCP MCP servers via URL connections.\n",
    "\n",
    "\n",
    "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",
    "\n",
    "### Modules Used (20+)\n",
    "\n",
    "- **Ingestion**: MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",
    "- **Parsing**: MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
    "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
    "- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
    "- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",
    "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
    "- **Quality**: KGQualityAssessor, ValidationEngine\n",
    "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
    "- **Visualization**: KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
    "\n",
    "### Pipeline\n",
    "\n",
    "**Connect to Medical MCP Server → Ingest Patient/Drug Data via MCP → Parse MCP Responses → Extract Medical Entities → Build Healthcare KG → Query & Analyze → Generate Reports → Visualize**\n",
    "\n",
    "## Installation\n",
    "\n",
    "Install Semantica from PyPI:\n",
    "\n",
    "```bash\n",
    "pip install semantica\n",
    "# Or with all optional dependencies:\n",
    "pip install semantica[all]\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## Step 1: Connect to Medical Database MCP Server\n",
    "\n",
    "Connect to a Python/FastMCP MCP server that provides medical database access via URL. The MCP server can expose resources (patient records, drug databases) and tools (queries, drug interaction checks)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantica.ingest import MCPIngestor, ingest_mcp\n",
    "from semantica.parse import MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
    "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
    "from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
    "from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
    "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
    
    "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
    "from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
    "import json\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "# Initialize MCP ingestor\n",
    "mcp_ingestor = MCPIngestor()\n",
    "\n",
    "# Connect to medical database MCP server via URL\n",
    "# Replace with your actual MCP server URL\n",
    "# Example: http://localhost:8000/mcp or https://api.example.com/medical-mcp\n",
    "medical_mcp_url = \"http://localhost:8000/mcp\"\n",
    "\n",
    "# Connect to MCP server with authentication (if required)\n",
    "mcp_ingestor.connect(\n",
    "    \"medical_server\",\n",
    "    url=medical_mcp_url,\n",
    "    headers={\n",
    "        \"Authorization\": \"Bearer your_token\",\n",
    "        \"X-API-Key\": \"your_api_key\"\n",
    "    } if \"api.example.com\" in medical_mcp_url else {}\n",
    ")\n",
    "\n",
    "# List available resources (patient records, drug databases)\n",
    "resources = mcp_ingestor.list_available_resources(\"medical_server\")\n",
    "print(f\"\\n📊 Available Resources ({len(resources)}):\")\n",
    "for resource in resources[:5]:  # Show first 5\n",
    "    print(f\"  - {resource.uri}: {resource.name}\")\n",
    "    if resource.description:\n",
    "        print(f\"    {resource.description[:80]}...\")\n",
    "\n",
    "# List available tools (queries, drug interaction checks)\n",
    "tools = mcp_ingestor.list_available_tools(\"medical_server\")\n",
    "print(f\"\\n🔧 Available Tools ({len(tools)}):\")\n",
    "for tool in tools[:5]:  # Show first 5\n",
    "    print(f\"  - {tool.name}: {tool.description or 'No description'}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Ingest Medical Data from MCP Server\n",
    "\n",
    "Ingest patient records, drug interactions, and clinical data using both resource-based and tool-based methods.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize parsers\n",
    "mcp_parser = MCPParser()\n",
    "json_parser = JSONParser()\n",
    "structured_parser = StructuredDataParser()\n",
    "\n",
    "medical_data = []\n",
    "\n",
    "# Method 1: Resource-based ingestion\n",
    "# Ingest from MCP resources (patient records, drug databases)\n",
    "# Example: Ingest patient records resource\n",
    "patient_data = mcp_ingestor.ingest_resources(\n",
    "    \"medical_server\",\n",
    "    resource_uris=[\"resource://patients/records\", \"resource://drugs/interactions\"]\n",
    ")\n",
    "\n",
    "for item in patient_data:\n",
    "    medical_data.append(item)\n",
    "    print(f\"  Ingested resource: {item}\")\n",
    "\n",
    "# Method 2: Tool-based ingestion\n",
    "# Call MCP tools to retrieve data dynamically\n",
    "# Example: Query patient records\n",
    "patient_records = mcp_ingestor.ingest_tool_output(\n",
    "    \"medical_server\",\n",
    "    tool_name=\"query_patient_records\",\n",
    "    arguments={\n",
    "        \"patient_id\": \"P001\",\n",
    "        \"date_range\": {\n",
    "            \"start\": (datetime.now() - timedelta(days=365)).isoformat(),\n",
    "            \"end\": datetime.now().isoformat()\n",
    "        }\n",
    "    }\n",
    ")\n",
    "\n",
    "if patient_records:\n",
    "    medical_data.append(patient_records)\n",
    "    print(f\"  Retrieved patient records\")\n",
    "\n",
    "# Example: Check drug interactions\n",
    "drug_interactions = mcp_ingestor.ingest_tool_output(\n",
    "    \"medical_server\",\n",
    "    tool_name=\"check_drug_interactions\",\n",
    "    arguments={\n",
    "        \"medications\": [\"Lisinopril\", \"Metformin\", \"Aspirin\"]\n",
    "    }\n",
    ")\n",
    "\n",
    "if drug_interactions:\n",
    "    medical_data.append(drug_interactions)\n",
    "    print(f\"  Retrieved drug interactions\")\n",
    "\n",
    "# Sample medical data (if MCP server is not available)\n",
    "if not medical_data:\n",
    "    sample_data = {\n",
    "        \"patient_records\": [\n",
    "            {\n",
    "                \"patient_id\": \"P001\",\n",
    "                \"visit_date\": (datetime.now() - timedelta(days=30)).isoformat(),\n",
    "                \"diagnosis\": [\"Hypertension\", \"Type 2 Diabetes\"],\n",
    "                \"medications\": [\"Lisinopril 10mg\", \"Metformin 500mg\"],\n",
    "                \"procedures\": [\"Blood Pressure Check\", \"HbA1c Test\"],\n",
    "                \"doctor\": \"Dr. Smith\",\n",
    "                \"notes\": \"Patient shows improvement in blood pressure control.\"\n",
    "            },\n",
    "            {\n",
    "                \"patient_id\": \"P002\",\n",
    "                \"visit_date\": (datetime.now() - timedelta(days=15)).isoformat(),\n",
    "                \"diagnosis\": [\"Asthma\"],\n",
    "                \"medications\": [\"Albuterol Inhaler\"],\n",
    "                \"procedures\": [\"Spirometry\"],\n",
    "                \"doctor\": \"Dr. Johnson\",\n",
    "                \"notes\": \"Asthma well controlled with current medication.\"\n",
    "            }\n",
    "        ],\n",
    "        \"drug_interactions\": [\n",
    "            {\n",
    "                \"drug1\": \"Lisinopril\",\n",
    "                \"drug2\": \"Aspirin\",\n",
    "                \"interaction_type\": \"moderate\",\n",
    "                \"description\": \"May increase risk of kidney problems\"\n",
    "            },\n",
    "            {\n",
    "                \"drug1\": \"Metformin\",\n",
    "                \"drug2\": \"Alcohol\",\n",
    "                \"interaction_type\": \"severe\",\n",
    "                \"description\": \"May cause lactic acidosis\"\n",
    "            }\n",
    "        ]\n",
    "    }\n",
    "    medical_data.append(sample_data)\n",
    "    print(f\"  Loaded {len(sample_data['patient_records'])} patient records\")\n",
    "    print(f\"  Loaded {len(sample_data['drug_interactions'])} drug interactions\")\n",
    "\n",
    "print(f\"\\n📊 Total medical data items ingested: {len(medical_data)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Parse MCP Medical Data\n",
    "\n",
    "Parse the medical data received from MCP server responses.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parsed_medical_data = []\n",
    "\n",
    "# Parse MCP responses\n",
    "for data_item in medical_data:\n",
    "    # Parse MCP response (handles JSON, text, binary)\n",
    "    if isinstance(data_item, dict):\n",
    "        parsed_item = data_item\n",
    "    else:\n",
    "        parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",
    "    \n",
    "    parsed_medical_data.append(parsed_item)\n",
    "    print(f\"  Parsed data item\")\n",
    "\n",
    "# Extract patient records and drug interactions\n",
    "patient_records = []\n",
    "drug_interactions = []\n",
    "\n",
    "for item in parsed_medical_data:\n",
    "    if isinstance(item, dict):\n",
    "        if \"patient_records\" in item:\n",
    "            patient_records.extend(item[\"patient_records\"])\n",
    "        elif \"patient_id\" in item:\n",
    "            patient_records.append(item)\n",
    "        elif \"drug_interactions\" in item:\n",
    "            drug_interactions.extend(item[\"drug_interactions\"])\n",
    "        elif \"drug1\" in item:\n",
    "            drug_interactions.append(item)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Extract Medical Entities and Relationships\n",
    "\n",
    "Extract medical entities (patients, diagnoses, medications, procedures, doctors) and relationships from MCP data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ner_extractor = NERExtractor()\n",
    "relation_extractor = RelationExtractor()\n",
    "triple_extractor = TripleExtractor()\n",
    "semantic_analyzer = SemanticAnalyzer()\n",
    "\n",
    "medical_entities = []\n",
    "medical_relationships = []\n",
    "\n",
    "# Extract from patient records\n",
    "for record in patient_records:\n",
    "    if isinstance(record, dict):\n",
    "        patient_id = record.get(\"patient_id\", \"\")\n",
    "        \n",
    "        # Patient entity\n",
    "        medical_entities.append({\n",
    "            \"id\": patient_id,\n",
    "            \"type\": \"Patient\",\n",
    "            \"name\": patient_id,\n",
    "            \"properties\": {\"visit_date\": record.get(\"visit_date\", \"\")}\n",
    "        })\n",
    "        \n",
    "        # Diagnoses\n",
    "        for diagnosis in record.get(\"diagnosis\", []):\n",
    "            medical_entities.append({\n",
    "                \"id\": diagnosis,\n",
    "                \"type\": \"Diagnosis\",\n",
    "                \"name\": diagnosis,\n",
    "                \"properties\": {}\n",
    "            })\n",
    "            medical_relationships.append({\n",
    "                \"source\": patient_id,\n",
    "                \"target\": diagnosis,\n",
    "                \"type\": \"has_diagnosis\",\n",
    "                \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",
    "            })\n",
    "        \n",
    "        # Medications\n",
    "        for medication in record.get(\"medications\", []):\n",
    "            medical_entities.append({\n",
    "                \"id\": medication,\n",
    "                \"type\": \"Medication\",\n",
    "                \"name\": medication,\n",
    "                \"properties\": {}\n",
    "            })\n",
    "            medical_relationships.append({\n",
    "                \"source\": patient_id,\n",
    "                \"target\": medication,\n",
    "                \"type\": \"prescribed\",\n",
    "                \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",
    "            })\n",
    "        \n",
    "        # Procedures\n",
    "        for procedure in record.get(\"procedures\", []):\n",
    "            medical_entities.append({\n",
    "                \"id\": procedure,\n",
    "                \"type\": \"Procedure\",\n",
    "                \"name\": procedure,\n",
    "                \"properties\": {}\n",
    "            })\n",
    "            medical_relationships.append({\n",
    "                \"source\": patient_id,\n",
    "                \"target\": procedure,\n",
    "                \"type\": \"underwent\",\n",
    "                \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",
    "            })\n",
    "        \n",
    "        # Doctor\n",
    "        doctor = record.get(\"doctor\", \"\")\n",
    "        if doctor:\n",
    "            medical_entities.append({\n",
    "                \"id\": doctor,\n",
    "                \"type\": \"Doctor\",\n",
    "                \"name\": doctor,\n",
    "                \"properties\": {}\n",
    "            })\n",
    "            medical_relationships.append({\n",
    "                \"source\": doctor,\n",
    "                \"target\": patient_id,\n",
    "                \"type\": \"treats\",\n",
    "                \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",
    "            })\n",
    "\n",
    "# Extract from drug interactions\n",
    "for interaction in drug_interactions:\n",
    "    if isinstance(interaction, dict):\n",
    "        drug1 = interaction.get(\"drug1\", \"\")\n",
    "        drug2 = interaction.get(\"drug2\", \"\")\n",
    "        interaction_type = interaction.get(\"interaction_type\", \"\")\n",
    "        \n",
    "        if drug1 and drug2:\n",
    "            medical_relationships.append({\n",
    "                \"source\": drug1,\n",
    "                \"target\": drug2,\n",
    "                \"type\": \"interacts_with\",\n",
    "                \"properties\": {\n",
    "                    \"interaction_type\": interaction_type,\n",
    "                    \"description\": interaction.get(\"description\", \"\")\n",
    "                }\n",
    "            })\n",
    "\n",
    "# Remove duplicates\n",
    "seen_entities = set()\n",
    "unique_entities = []\n",
    "for entity in medical_entities:\n",
    "    entity_key = (entity[\"id\"], entity[\"type\"])\n",
    "    if entity_key not in seen_entities:\n",
    "        seen_entities.add(entity_key)\n",
    "        unique_entities.append(entity)\n",
    "\n",
    "medical_entities = unique_entities\n",
    "\n",
    "print(f\"  - Patients: {len([e for e in medical_entities if e['type'] == 'Patient'])}\")\n",
    "print(f\"  - Diagnoses: {len([e for e in medical_entities if e['type'] == 'Diagnosis'])}\")\n",
    "print(f\"  - Medications: {len([e for e in medical_entities if e['type'] == 'Medication'])}\")\n",
    "print(f\"  - Procedures: {len([e for e in medical_entities if e['type'] == 'Procedure'])}\")\n",
    "print(f\"  - Doctors: {len([e for e in medical_entities if e['type'] == 'Doctor'])}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Build Healthcare Knowledge Graph\n",
    "\n",
    "Build a knowledge graph from the extracted medical entities and relationships, then store in triple store.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "builder = GraphBuilder()\n",
    "graph_validator = GraphValidator()\n",
    "entity_resolver = EntityResolver()\n",
    "graph_analyzer = GraphAnalyzer()\n",
    "\n",
    "# Build knowledge graph\n",
    "medical_kg = builder.build(medical_entities, medical_relationships)\n",
    "\n",
    "# Validate and resolve entities\n",
    "validated_kg = graph_validator.validate(medical_kg)\n",
    "resolved_kg = entity_resolver.resolve_entities(validated_kg)\n",
    "\n",
    "# Analyze graph structure\n",
    "metrics = graph_analyzer.compute_metrics(resolved_kg)\n",
    "\n",
    "# Store in triple store\n",
    "triple_store = TripleStore()\n",
    "triple_manager = TripleManager()\n",
    "query_engine = QueryEngine()\n",
    "\n",
    "triple_store.add_knowledge_graph(resolved_kg)\n",
    "triple_manager.manage_triples(resolved_kg)\n",
    "\n",
    "print(f\"  Entities: {len(resolved_kg.get('entities', []))}\")\n",
    "print(f\"  Relationships: {len(resolved_kg.get('relationships', []))}\")\n",
    "print(f\"  Graph density: {metrics.get('density', 0):.3f}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Query and Analyze Medical Data\n",
    "\n",
    "Query the healthcare knowledge graph and analyze medical patterns.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Query patient data\n",
    "patient_query = query_engine.query(\n",
    "    \"SELECT ?patient ?diagnosis WHERE { ?patient has_diagnosis ?diagnosis }\"\n",
    ")\n",
    "\n",
    "# Query drug interactions\n",
    "interaction_query = query_engine.query(\n",
    "    \"SELECT ?drug1 ?drug2 ?type WHERE { ?drug1 interacts_with ?drug2 }\"\n",
    ")\n",
    "\n",
    "# Inference engine for medical rules\n",
    "inference_engine = InferenceEngine()\n",
    "rule_manager = RuleManager()\n",
    "explanation_generator = ExplanationGenerator()\n",
    "\n",
    "# Medical analysis rules\n",
    "inference_engine.add_rule(\"IF has_diagnosis(Diabetes) AND prescribed(Metformin) THEN diabetes_treatment\")\n",
    "inference_engine.add_rule(\"IF interacts_with(Drug1, Drug2) AND interaction_type(severe) THEN contraindication\")\n",
    "\n",
    "# Add facts from medical data\n",
    "for record in patient_records:\n",
    "    if isinstance(record, dict):\n",
    "        for diagnosis in record.get(\"diagnosis\", []):\n",
    "            inference_engine.add_fact({\n",
    "                \"patient\": record.get(\"patient_id\", \"\"),\n",
    "                \"diagnosis\": diagnosis\n",
    "            })\n",
    "        for medication in record.get(\"medications\", []):\n",
    "            inference_engine.add_fact({\n",
    "                \"patient\": record.get(\"patient_id\", \"\"),\n",
    "                \"medication\": medication\n",
    "            })\n",
    "\n",
    "for interaction in drug_interactions:\n",
    "    if isinstance(interaction, dict):\n",
    "        inference_engine.add_fact({\n",
    "            \"drug1\": interaction.get(\"drug1\", \"\"),\n",
    "            \"drug2\": interaction.get(\"drug2\", \"\"),\n",
    "            \"interaction_type\": interaction.get(\"interaction_type\", \"\")\n",
    "        })\n",
    "\n",
    "# Generate medical insights\n",
    "medical_insights = inference_engine.forward_chain()\n",
    "\n",
    "print(f\"  Patient-diagnosis relationships: {len(patient_query.get('results', []))}\")\n",
    "print(f\"  Drug interactions: {len(interaction_query.get('results', []))}\")\n",
    "print(f\"  Medical insights: {len(medical_insights)}\")\n",
    "\n",
    "# Quality assessment\n",
    "quality_assessor = KGQualityAssessor()\n",
    "validation_engine = ValidationEngine()\n",
    "\n",
    "quality_metrics = quality_assessor.assess_quality(resolved_kg)\n",
    "validation_results = validation_engine.validate(resolved_kg)\n",
    "\n",
    "print(f\"  Quality score: {quality_metrics.get('overall_score', 0):.2f}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 7: Export and Visualize\n",
    "\n",
    "Export the healthcare knowledge graph and generate visualizations.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tempfile\n",
    "import os\n",
    "\n",
    "temp_dir = tempfile.mkdtemp()\n",
    "\n",
    "json_exporter = JSONExporter()\n",
    "rdf_exporter = RDFExporter()\n",
    "owl_exporter = OWLExporter()\n",
    "report_generator = ReportGenerator()\n",
    "\n",
    "# Export knowledge graph\n",
    "json_exporter.export_knowledge_graph(resolved_kg, os.path.join(temp_dir, \"medical_kg.json\"))\n",
    "rdf_exporter.export_knowledge_graph(resolved_kg, os.path.join(temp_dir, \"medical_kg.rdf\"))\n",
    "# Note: OWLExporter expects an ontology structure, not a knowledge graph\n",
    "# To export as OWL, first generate an ontology from the KG using OntologyGenerator\n",
    "\n",
    "# Generate report\n",
    "report_data = {\n",
    "    \"summary\": f\"Medical database integration from MCP server identified {len(medical_insights)} insights\",\n",
    "    \"patients\": len([e for e in medical_entities if e['type'] == 'Patient']),\n",
    "    \"diagnoses\": len([e for e in medical_entities if e['type'] == 'Diagnosis']),\n",
    "    \"medications\": len([e for e in medical_entities if e['type'] == 'Medication']),\n",
    "    \"drug_interactions\": len(drug_interactions),\n",
    "    \"insights\": len(medical_insights)\n",
    "}\n",
    "\n",
    "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
    "\n",
    "print(f\"  JSON: {os.path.join(temp_dir, 'medical_kg.json')}\")\n",
    "print(f\"  RDF: {os.path.join(temp_dir, 'medical_kg.rdf')}\")\n",
    "\n",
    "# Visualize\n",
    "kg_visualizer = KGVisualizer()\n",
    "ontology_visualizer = OntologyVisualizer()\n",
    "temporal_visualizer = TemporalVisualizer()\n",
    "\n",
    "kg_viz = kg_visualizer.visualize_network(resolved_kg, output=\"interactive\")\n",
    "ontology_viz = ontology_visualizer.visualize_ontology(resolved_kg, output=\"interactive\")\n",
    "temporal_viz = temporal_visualizer.visualize_timeline(resolved_kg, output=\"interactive\")\n",
    "\n",
    "\n",
    "# Cleanup: Disconnect from MCP server\n",
    "mcp_ingestor.disconnect(\"medical_server\")\n",
    "print(\"  Disconnected from MCP server\")\n",
    "\n",
    "print(f\"📊 Total modules used: 20+\")\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
