Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Add MCP ingestion examples to existing use case notebooks

KaifAhmad1750fc1f9329c
diff --git a/cookbook/use_cases/biomedical/Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/Drug_Discovery_Pipeline.ipynb
index 28ab2822..41d8e4dc 100644
--- a/cookbook/use_cases/biomedical/Drug_Discovery_Pipeline.ipynb
+++ b/cookbook/use_cases/biomedical/Drug_Discovery_Pipeline.ipynb
@@ -12,8 +12,8 @@
"\n",
"### Modules Used (20+)\n",
"\n",
- "- **Ingestion**: WebIngestor, DBIngestor, FeedIngestor, FileIngestor\n",
- "- **Parsing**: JSONParser, StructuredDataParser, DocumentParser\n",
+ "- **Ingestion**: WebIngestor, DBIngestor, FeedIngestor, FileIngestor, MCPIngestor\n",
+ "- **Parsing**: JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",
@@ -26,7 +26,7 @@
"\n",
"### Pipeline\n",
"\n",
- "**Drug/Protein Data Sources → Parse → Extract Entities (compounds, targets, interactions) → Build Drug-Target KG → Generate Embeddings → Similarity Search → Predict Interactions → Target Identification → Generate Reports → Visualize**\n",
+ "**Drug/Protein Data Sources (APIs, DB, Feeds, MCP) → Parse → Extract Entities (compounds, targets, interactions) → Build Drug-Target KG → Generate Embeddings → Similarity Search → Predict Interactions → Target Identification → Generate Reports → Visualize**\n",
"\n",
"---\n",
"\n",
@@ -41,8 +41,8 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor\n",
- "from semantica.parse import JSONParser, StructuredDataParser, DocumentParser\n",
+ "from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor, MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",
"from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",
@@ -61,10 +61,12 @@
"db_ingestor = DBIngestor()\n",
"feed_ingestor = FeedIngestor()\n",
"file_ingestor = FileIngestor()\n",
+ "mcp_ingestor = MCPIngestor()\n",
"\n",
"json_parser = JSONParser()\n",
"structured_parser = StructuredDataParser()\n",
"document_parser = DocumentParser()\n",
+ "mcp_parser = MCPParser()\n",
"\n",
"# Real drug APIs\n",
"drug_apis = [\n",
@@ -179,11 +181,66 @@
" print(f\"⚠ Database connection (example pattern): Configure with real credentials\")\n",
" db_data = {\"data\": drug_data}\n",
"\n",
+ "# Optional: Ingest from MCP server\n",
+ "# Users can bring their own drug/protein database MCP server via URL\n",
+ "mcp_drug_data = []\n",
+ "try:\n",
+ " # Connect to biomedical database MCP server via URL\n",
+ " # Example: http://localhost:8000/mcp or https://api.example.com/biomedical-mcp\n",
+ " biomedical_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",
+ " \n",
+ " mcp_ingestor.connect(\n",
+ " \"biomedical_mcp_server\",\n",
+ " url=biomedical_mcp_url,\n",
+ " headers={\n",
+ " \"Authorization\": \"Bearer your_token\",\n",
+ " \"X-API-Key\": \"your_api_key\"\n",
+ " } if \"api.example.com\" in biomedical_mcp_url else {}\n",
+ " )\n",
+ " \n",
+ " # Ingest drug-target interactions from MCP server\n",
+ " mcp_data = mcp_ingestor.ingest_resources(\n",
+ " \"biomedical_mcp_server\",\n",
+ " resource_uris=[\"resource://drugs/interactions\", \"resource://proteins/targets\"]\n",
+ " )\n",
+ " mcp_drug_data.extend(mcp_data)\n",
+ " \n",
+ " # Or use tool-based ingestion to query drug interactions\n",
+ " tool_data = mcp_ingestor.ingest_tool_output(\n",
+ " \"biomedical_mcp_server\",\n",
+ " tool_name=\"query_drug_interactions\",\n",
+ " arguments={\n",
+ " \"compound_id\": \"CID2244\",\n",
+ " \"target_protein\": \"PTGS1\"\n",
+ " }\n",
+ " )\n",
+ " if tool_data:\n",
+ " mcp_drug_data.append(tool_data)\n",
+ " \n",
+ " # Parse MCP responses and merge with existing drug data\n",
+ " for mcp_item in mcp_drug_data:\n",
+ " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",
+ " if isinstance(parsed_mcp, dict):\n",
+ " if \"drug_targets\" in parsed_mcp or \"interactions\" in parsed_mcp:\n",
+ " # Merge drug-target interactions from MCP\n",
+ " mcp_interactions = parsed_mcp.get(\"drug_targets\", parsed_mcp.get(\"interactions\", []))\n",
+ " drug_data.extend(mcp_interactions)\n",
+ " elif \"compound_id\" in parsed_mcp:\n",
+ " # Single drug-target interaction\n",
+ " drug_data.append(parsed_mcp)\n",
+ " \n",
+ " print(f\"✓ Ingested {len(mcp_drug_data)} items from MCP server\")\n",
+ " mcp_ingestor.disconnect(\"biomedical_mcp_server\")\n",
+ "except Exception as e:\n",
+ " print(f\"⚠ MCP ingestion skipped: {e}\")\n",
+ " print(\" Note: MCP ingestion is optional. You can bring your own MCP server via URL.\")\n",
+ "\n",
"print(f\"\\n📊 Ingestion Summary:\")\n",
"print(f\" Local drug-target interactions: {len(drug_data)}\")\n",
"print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",
"print(f\" Drug APIs: {len(drug_apis)}\")\n",
- "print(f\" Protein APIs: {len(protein_apis)}\")\n"
+ "print(f\" Protein APIs: {len(protein_apis)}\")\n",
+ "print(f\" MCP server sources: {len(mcp_drug_data)}\")\n"
]
},
{
diff --git a/cookbook/use_cases/cybersecurity/Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/Threat_Intelligence_Hybrid_RAG.ipynb
index 6225cdda..36b14a6b 100644
--- a/cookbook/use_cases/cybersecurity/Threat_Intelligence_Hybrid_RAG.ipynb
+++ b/cookbook/use_cases/cybersecurity/Threat_Intelligence_Hybrid_RAG.ipynb
@@ -12,8 +12,8 @@
"\n",
"### Modules Used (20+)\n",
"\n",
- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, DBIngestor\n",
- "- **Parsing**: JSONParser, XMLParser, HTMLParser, DocumentParser\n",
+ "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor\n",
+ "- **Parsing**: JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
@@ -25,7 +25,7 @@
"\n",
"### Pipeline\n",
"\n",
- "**Multi-Source Threat Intel → Parse → Extract Entities → Build KG → Generate Embeddings → Vector Store → Hybrid RAG Setup → Query Threats → Generate Reports → Visualize**\n",
+ "**Multi-Source Threat Intel (Files, Web, Feeds, MCP) → Parse → Extract Entities → Build KG → Generate Embeddings → Vector Store → Hybrid RAG Setup → Query Threats → Generate Reports → Visualize**\n",
"\n",
"---\n",
"\n",
@@ -40,8 +40,8 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, DBIngestor\n",
- "from semantica.parse import JSONParser, XMLParser, HTMLParser, DocumentParser\n",
+ "from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",
"from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
@@ -59,11 +59,13 @@
"web_ingestor = WebIngestor()\n",
"feed_ingestor = FeedIngestor()\n",
"db_ingestor = DBIngestor()\n",
+ "mcp_ingestor = MCPIngestor()\n",
"\n",
"json_parser = JSONParser()\n",
"xml_parser = XMLParser()\n",
"html_parser = HTMLParser()\n",
"document_parser = DocumentParser()\n",
+ "mcp_parser = MCPParser()\n",
"\n",
"temp_dir = tempfile.mkdtemp()\n",
"\n",
@@ -170,10 +172,73 @@
" except Exception as e:\n",
" print(f\"⚠ Web ingestion for {web_url}: {str(e)[:100]}\")\n",
"\n",
+ "# Optional: Ingest from MCP server\n",
+ "# Users can bring their own threat intelligence MCP server via URL\n",
+ "mcp_threat_data = []\n",
+ "try:\n",
+ " # Connect to threat intelligence MCP server via URL\n",
+ " # Example: http://localhost:8000/mcp or https://api.example.com/threat-mcp\n",
+ " threat_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",
+ " \n",
+ " mcp_ingestor.connect(\n",
+ " \"threat_mcp_server\",\n",
+ " url=threat_mcp_url,\n",
+ " headers={\n",
+ " \"Authorization\": \"Bearer your_token\",\n",
+ " \"X-API-Key\": \"your_api_key\"\n",
+ " } if \"api.example.com\" in threat_mcp_url else {}\n",
+ " )\n",
+ " \n",
+ " # Ingest threat indicators from MCP server\n",
+ " mcp_data = mcp_ingestor.ingest_resources(\n",
+ " \"threat_mcp_server\",\n",
+ " resource_uris=[\"resource://threats/feed\", \"resource://vulnerabilities/database\"]\n",
+ " )\n",
+ " mcp_threat_data.extend(mcp_data)\n",
+ " \n",
+ " # Or use tool-based ingestion to query threat indicators\n",
+ " tool_data = mcp_ingestor.ingest_tool_output(\n",
+ " \"threat_mcp_server\",\n",
+ " tool_name=\"query_threat_indicators\",\n",
+ " arguments={\n",
+ " \"indicator_type\": \"IP\",\n",
+ " \"date_range\": {\n",
+ " \"start\": (datetime.now() - timedelta(days=7)).isoformat(),\n",
+ " \"end\": datetime.now().isoformat()\n",
+ " }\n",
+ " }\n",
+ " )\n",
+ " if tool_data:\n",
+ " mcp_threat_data.append(tool_data)\n",
+ " \n",
+ " # Parse MCP responses and merge with existing threat data\n",
+ " for mcp_item in mcp_threat_data:\n",
+ " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",
+ " if isinstance(parsed_mcp, dict):\n",
+ " if \"threat_indicators\" in parsed_mcp:\n",
+ " # Merge threat indicators from MCP\n",
+ " if parsed_json and parsed_json.data:\n",
+ " parsed_json.data.extend(parsed_mcp.get(\"threat_indicators\", []))\n",
+ " else:\n",
+ " parsed_json.data = parsed_mcp.get(\"threat_indicators\", [])\n",
+ " elif \"threat_id\" in parsed_mcp:\n",
+ " # Single threat indicator\n",
+ " if parsed_json and parsed_json.data:\n",
+ " parsed_json.data.append(parsed_mcp)\n",
+ " else:\n",
+ " parsed_json.data = [parsed_mcp]\n",
+ " \n",
+ " print(f\"✓ Ingested {len(mcp_threat_data)} items from MCP server\")\n",
+ " mcp_ingestor.disconnect(\"threat_mcp_server\")\n",
+ "except Exception as e:\n",
+ " print(f\"⚠ MCP ingestion skipped: {e}\")\n",
+ " print(\" Note: MCP ingestion is optional. You can bring your own MCP server via URL.\")\n",
+ "\n",
"print(f\"Ingested {len([file_objects_json]) if file_objects_json else 0} JSON threat intelligence files\")\n",
"print(f\"Ingested {len([file_objects_xml]) if file_objects_xml else 0} XML threat intelligence files\")\n",
"print(f\"Parsed {len(parsed_json.data) if parsed_json and parsed_json.data else 0} JSON threat entries\")\n",
- "print(f\"Parsed {len(parsed_xml.elements) if parsed_xml else 0} XML indicator elements\")\n"
+ "print(f\"Parsed {len(parsed_xml.elements) if parsed_xml else 0} XML indicator elements\")\n",
+ "print(f\"MCP server sources: {len(mcp_threat_data)}\")\n"
]
},
{
diff --git a/cookbook/use_cases/cybersecurity/Threat_Intelligence_Integration.ipynb b/cookbook/use_cases/cybersecurity/Threat_Intelligence_Integration.ipynb
new file mode 100644
index 00000000..b4e9055d
--- /dev/null
+++ b/cookbook/use_cases/cybersecurity/Threat_Intelligence_Integration.ipynb
@@ -0,0 +1,575 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Threat Intelligence Integration Pipeline\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for threat intelligence ingestion. Connect to threat intelligence MCP servers via URL, ingest threat feeds, vulnerability data, and security events, then build a threat intelligence 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",
+ "### Modules Used (20+)\n",
+ "\n",
+ "- **Ingestion**: MCPIngestor, ingest_mcp, WebIngestor, FeedIngestor\n",
+ "- **Parsing**: MCPParser, JSONParser, XMLParser, StructuredDataParser\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
+ "- **Vector Store**: VectorStore, HybridSearch\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",
+ "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "\n",
+ "### Pipeline\n",
+ "\n",
+ "**Connect to Threat Intel MCP Server → Ingest Threat Data via MCP → Parse MCP Responses → Extract Threat Entities → Build Threat KG → Generate Embeddings → Hybrid RAG → Analyze Threats → Generate Reports → Visualize**\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Step 1: Connect to Threat Intelligence MCP Server\n",
+ "\n",
+ "Connect to a Python/FastMCP MCP server that provides threat intelligence data via URL. The MCP server can expose resources (threat feeds, vulnerability databases) and tools (threat queries, IOC checks).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import MCPParser, JSONParser, XMLParser, StructuredDataParser\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",
+ "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "# Initialize MCP ingestor\n",
+ "mcp_ingestor = MCPIngestor()\n",
+ "\n",
+ "# Connect to threat intelligence MCP server via URL\n",
+ "# Replace with your actual MCP server URL\n",
+ "# Example: http://localhost:8000/mcp or https://api.example.com/threat-mcp\n",
+ "threat_mcp_url = \"http://localhost:8000/mcp\"\n",
+ "\n",
+ "try:\n",
+ " # Connect to MCP server with authentication (if required)\n",
+ " mcp_ingestor.connect(\n",
+ " \"threat_server\",\n",
+ " url=threat_mcp_url,\n",
+ " headers={\n",
+ " \"Authorization\": \"Bearer your_token\",\n",
+ " \"X-API-Key\": \"your_api_key\"\n",
+ " } if \"api.example.com\" in threat_mcp_url else {}\n",
+ " )\n",
+ " print(f\"✓ Connected to threat intelligence MCP server at {threat_mcp_url}\")\n",
+ " \n",
+ " # List available resources (threat feeds, vulnerability databases)\n",
+ " resources = mcp_ingestor.list_available_resources(\"threat_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 (threat queries, IOC checks)\n",
+ " tools = mcp_ingestor.list_available_tools(\"threat_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",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Connection failed: {e}\")\n",
+ " print(\"Note: This example uses a placeholder URL. Replace with your actual MCP server URL.\")\n",
+ " print(\"For testing, you can use a mock MCP server or skip connection and use sample data below.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Threat Intelligence Data from MCP Server\n",
+ "\n",
+ "Ingest threat feeds, vulnerability data, and security events 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",
+ "xml_parser = XMLParser()\n",
+ "structured_parser = StructuredDataParser()\n",
+ "\n",
+ "threat_data = []\n",
+ "\n",
+ "# Method 1: Resource-based ingestion\n",
+ "# Ingest from MCP resources (threat feeds, vulnerability databases)\n",
+ "try:\n",
+ " # Example: Ingest threat feed resource\n",
+ " threat_feeds = mcp_ingestor.ingest_resources(\n",
+ " \"threat_server\",\n",
+ " resource_uris=[\"resource://threats/feed\", \"resource://vulnerabilities/database\"]\n",
+ " )\n",
+ " \n",
+ " for item in threat_feeds:\n",
+ " threat_data.append(item)\n",
+ " print(f\"✓ Ingested resource: {item.resource_uri}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Resource ingestion: {e}\")\n",
+ "\n",
+ "# Method 2: Tool-based ingestion\n",
+ "# Call MCP tools to retrieve data dynamically\n",
+ "try:\n",
+ " # Example: Query threat indicators\n",
+ " threat_indicators = mcp_ingestor.ingest_tool_output(\n",
+ " \"threat_server\",\n",
+ " tool_name=\"query_threat_indicators\",\n",
+ " arguments={\n",
+ " \"indicator_type\": \"IP\",\n",
+ " \"date_range\": {\n",
+ " \"start\": (datetime.now() - timedelta(days=7)).isoformat(),\n",
+ " \"end\": datetime.now().isoformat()\n",
+ " }\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if threat_indicators:\n",
+ " threat_data.append(threat_indicators)\n",
+ " print(f\"✓ Retrieved threat indicators via tool\")\n",
+ " \n",
+ " # Example: Check IOC (Indicators of Compromise)\n",
+ " ioc_check = mcp_ingestor.ingest_tool_output(\n",
+ " \"threat_server\",\n",
+ " tool_name=\"check_ioc\",\n",
+ " arguments={\n",
+ " \"ioc_type\": \"hash\",\n",
+ " \"ioc_value\": \"abc123def456\"\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if ioc_check:\n",
+ " threat_data.append(ioc_check)\n",
+ " print(f\"✓ Retrieved IOC check results via tool\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Tool-based ingestion: {e}\")\n",
+ " print(\"Note: Using sample data for demonstration\")\n",
+ "\n",
+ "# Sample threat intelligence data (if MCP server is not available)\n",
+ "if not threat_data:\n",
+ " print(\"\\n📝 Using sample threat intelligence data for demonstration:\")\n",
+ " sample_data = {\n",
+ " \"threat_indicators\": [\n",
+ " {\n",
+ " \"indicator_id\": \"TI001\",\n",
+ " \"indicator_type\": \"IP\",\n",
+ " \"indicator_value\": \"192.168.1.100\",\n",
+ " \"threat_type\": \"malware\",\n",
+ " \"severity\": \"high\",\n",
+ " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat(),\n",
+ " \"source\": \"ThreatFeed1\"\n",
+ " },\n",
+ " {\n",
+ " \"indicator_id\": \"TI002\",\n",
+ " \"indicator_type\": \"domain\",\n",
+ " \"indicator_value\": \"malicious.example.com\",\n",
+ " \"threat_type\": \"phishing\",\n",
+ " \"severity\": \"medium\",\n",
+ " \"timestamp\": (datetime.now() - timedelta(hours=12)).isoformat(),\n",
+ " \"source\": \"ThreatFeed2\"\n",
+ " },\n",
+ " {\n",
+ " \"indicator_id\": \"TI003\",\n",
+ " \"indicator_type\": \"hash\",\n",
+ " \"indicator_value\": \"abc123def456\",\n",
+ " \"threat_type\": \"ransomware\",\n",
+ " \"severity\": \"critical\",\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"source\": \"ThreatFeed1\"\n",
+ " }\n",
+ " ],\n",
+ " \"vulnerabilities\": [\n",
+ " {\n",
+ " \"cve_id\": \"CVE-2024-0001\",\n",
+ " \"description\": \"Remote code execution vulnerability\",\n",
+ " \"severity\": \"critical\",\n",
+ " \"affected_products\": [\"Product A\", \"Product B\"],\n",
+ " \"published_date\": (datetime.now() - timedelta(days=5)).isoformat()\n",
+ " }\n",
+ " ]\n",
+ " }\n",
+ " threat_data.append(sample_data)\n",
+ " print(f\" Loaded {len(sample_data['threat_indicators'])} threat indicators\")\n",
+ " print(f\" Loaded {len(sample_data['vulnerabilities'])} vulnerabilities\")\n",
+ "\n",
+ "print(f\"\\n📊 Total threat intelligence data items ingested: {len(threat_data)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse Threat Intelligence Data\n",
+ "\n",
+ "Parse the threat intelligence data received from MCP server responses.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "parsed_threat_data = []\n",
+ "\n",
+ "# Parse MCP responses\n",
+ "for data_item in threat_data:\n",
+ " try:\n",
+ " # Parse MCP response (handles JSON, XML, 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_threat_data.append(parsed_item)\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\"⚠ Parsing error: {e}\")\n",
+ "\n",
+ "# Extract threat indicators and vulnerabilities\n",
+ "threat_indicators = []\n",
+ "vulnerabilities = []\n",
+ "\n",
+ "for item in parsed_threat_data:\n",
+ " if isinstance(item, dict):\n",
+ " if \"threat_indicators\" in item:\n",
+ " threat_indicators.extend(item[\"threat_indicators\"])\n",
+ " elif \"indicator_id\" in item:\n",
+ " threat_indicators.append(item)\n",
+ " elif \"vulnerabilities\" in item:\n",
+ " vulnerabilities.extend(item[\"vulnerabilities\"])\n",
+ " elif \"cve_id\" in item:\n",
+ " vulnerabilities.append(item)\n",
+ "\n",
+ "print(f\"✓ Parsed {len(parsed_threat_data)} data items\")\n",
+ "print(f\"✓ Extracted {len(threat_indicators)} threat indicators\")\n",
+ "print(f\"✓ Extracted {len(vulnerabilities)} vulnerabilities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Threat Entities and Relationships\n",
+ "\n",
+ "Extract threat entities (indicators, vulnerabilities, threat actors) and relationships from MCP data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "triple_extractor = TripleExtractor()\n",
+ "\n",
+ "threat_entities = []\n",
+ "threat_relationships = []\n",
+ "\n",
+ "# Extract from threat indicators\n",
+ "for indicator in threat_indicators:\n",
+ " if isinstance(indicator, dict):\n",
+ " indicator_id = indicator.get(\"indicator_id\", \"\")\n",
+ " indicator_type = indicator.get(\"indicator_type\", \"\")\n",
+ " threat_type = indicator.get(\"threat_type\", \"\")\n",
+ " source = indicator.get(\"source\", \"\")\n",
+ " \n",
+ " # Threat Indicator entity\n",
+ " threat_entities.append({\n",
+ " \"id\": indicator_id,\n",
+ " \"type\": \"ThreatIndicator\",\n",
+ " \"name\": indicator_id,\n",
+ " \"properties\": {\n",
+ " \"indicator_type\": indicator_type,\n",
+ " \"indicator_value\": indicator.get(\"indicator_value\", \"\"),\n",
+ " \"threat_type\": threat_type,\n",
+ " \"severity\": indicator.get(\"severity\", \"\"),\n",
+ " \"timestamp\": indicator.get(\"timestamp\", \"\"),\n",
+ " \"source\": source\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Threat Type entity\n",
+ " if threat_type:\n",
+ " threat_entities.append({\n",
+ " \"id\": threat_type,\n",
+ " \"type\": \"ThreatType\",\n",
+ " \"name\": threat_type,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " threat_relationships.append({\n",
+ " \"source\": indicator_id,\n",
+ " \"target\": threat_type,\n",
+ " \"type\": \"classified_as\",\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # Source entity\n",
+ " if source:\n",
+ " threat_entities.append({\n",
+ " \"id\": source,\n",
+ " \"type\": \"ThreatSource\",\n",
+ " \"name\": source,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " threat_relationships.append({\n",
+ " \"source\": indicator_id,\n",
+ " \"target\": source,\n",
+ " \"type\": \"reported_by\",\n",
+ " \"properties\": {}\n",
+ " })\n",
+ "\n",
+ "# Extract from vulnerabilities\n",
+ "for vuln in vulnerabilities:\n",
+ " if isinstance(vuln, dict):\n",
+ " cve_id = vuln.get(\"cve_id\", \"\")\n",
+ " \n",
+ " # Vulnerability entity\n",
+ " threat_entities.append({\n",
+ " \"id\": cve_id,\n",
+ " \"type\": \"Vulnerability\",\n",
+ " \"name\": cve_id,\n",
+ " \"properties\": {\n",
+ " \"description\": vuln.get(\"description\", \"\"),\n",
+ " \"severity\": vuln.get(\"severity\", \"\"),\n",
+ " \"published_date\": vuln.get(\"published_date\", \"\")\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Affected products\n",
+ " for product in vuln.get(\"affected_products\", []):\n",
+ " threat_entities.append({\n",
+ " \"id\": product,\n",
+ " \"type\": \"Product\",\n",
+ " \"name\": product,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " threat_relationships.append({\n",
+ " \"source\": cve_id,\n",
+ " \"target\": product,\n",
+ " \"type\": \"affects\",\n",
+ " \"properties\": {}\n",
+ " })\n",
+ "\n",
+ "# Remove duplicates\n",
+ "seen_entities = set()\n",
+ "unique_entities = []\n",
+ "for entity in threat_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",
+ "threat_entities = unique_entities\n",
+ "\n",
+ "print(f\"✓ Extracted {len(threat_entities)} threat entities\")\n",
+ "print(f\" - Threat Indicators: {len([e for e in threat_entities if e['type'] == 'ThreatIndicator'])}\")\n",
+ "print(f\" - Vulnerabilities: {len([e for e in threat_entities if e['type'] == 'Vulnerability'])}\")\n",
+ "print(f\" - Threat Types: {len([e for e in threat_entities if e['type'] == 'ThreatType'])}\")\n",
+ "print(f\" - Sources: {len([e for e in threat_entities if e['type'] == 'ThreatSource'])}\")\n",
+ "print(f\"✓ Extracted {len(threat_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Threat Intelligence Knowledge Graph\n",
+ "\n",
+ "Build a temporal knowledge graph from the extracted threat entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "builder = GraphBuilder()\n",
+ "temporal_query = TemporalGraphQuery()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "connectivity_analyzer = ConnectivityAnalyzer()\n",
+ "\n",
+ "# Build knowledge graph\n",
+ "threat_kg = builder.build(threat_entities, threat_relationships)\n",
+ "\n",
+ "# Analyze graph structure\n",
+ "metrics = graph_analyzer.compute_metrics(threat_kg)\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(threat_kg)\n",
+ "\n",
+ "print(f\"✓ Built threat intelligence knowledge graph\")\n",
+ "print(f\" Entities: {len(threat_kg.get('entities', []))}\")\n",
+ "print(f\" Relationships: {len(threat_kg.get('relationships', []))}\")\n",
+ "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",
+ "print(f\" Connectivity: {connectivity.get('connected_components', 0)} components\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Generate Embeddings and Set Up Hybrid RAG\n",
+ "\n",
+ "Generate embeddings for threat intelligence data and set up hybrid search (vector + temporal KG).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate embeddings\n",
+ "embedding_generator = EmbeddingGenerator()\n",
+ "text_embedder = TextEmbedder()\n",
+ "\n",
+ "# Generate embeddings for threat entities\n",
+ "threat_texts = []\n",
+ "for entity in threat_entities:\n",
+ " if entity.get(\"type\") == \"ThreatIndicator\":\n",
+ " text = f\"{entity.get('properties', {}).get('indicator_value', '')} {entity.get('properties', {}).get('threat_type', '')} {entity.get('properties', {}).get('description', '')}\"\n",
+ " threat_texts.append(text)\n",
+ "\n",
+ "embeddings = embedding_generator.generate_embeddings(threat_texts)\n",
+ "\n",
+ "# Set up vector store\n",
+ "vector_store = VectorStore()\n",
+ "vector_store.add_embeddings(threat_texts, embeddings)\n",
+ "\n",
+ "# Set up hybrid search (vector + temporal KG)\n",
+ "hybrid_search = HybridSearch()\n",
+ "hybrid_search.setup(vector_store, threat_kg)\n",
+ "\n",
+ "print(f\"✓ Generated embeddings for {len(threat_texts)} threat indicators\")\n",
+ "print(f\"✓ Set up vector store with {len(embeddings)} embeddings\")\n",
+ "print(f\"✓ Configured hybrid search (vector + temporal KG)\")\n",
+ "\n",
+ "# Inference engine for threat analysis\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Threat analysis rules\n",
+ "inference_engine.add_rule(\"IF severity(critical) AND threat_type(ransomware) THEN immediate_response_required\")\n",
+ "inference_engine.add_rule(\"IF severity(high) AND indicator_type(IP) THEN block_ip\")\n",
+ "\n",
+ "# Add facts from threat data\n",
+ "for indicator in threat_indicators:\n",
+ " if isinstance(indicator, dict):\n",
+ " inference_engine.add_fact({\n",
+ " \"indicator_id\": indicator.get(\"indicator_id\", \"\"),\n",
+ " \"severity\": indicator.get(\"severity\", \"\"),\n",
+ " \"threat_type\": indicator.get(\"threat_type\", \"\"),\n",
+ " \"indicator_type\": indicator.get(\"indicator_type\", \"\")\n",
+ " })\n",
+ "\n",
+ "# Generate threat insights\n",
+ "threat_insights = inference_engine.forward_chain()\n",
+ "\n",
+ "print(f\"✓ Threat analysis completed\")\n",
+ "print(f\" Threat insights: {len(threat_insights)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Export and Visualize\n",
+ "\n",
+ "Export the threat intelligence 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",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Export knowledge graph\n",
+ "json_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.json\"))\n",
+ "rdf_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.rdf\"))\n",
+ "\n",
+ "# Generate report\n",
+ "report_data = {\n",
+ " \"summary\": f\"Threat intelligence integration from MCP server identified {len(threat_insights)} insights\",\n",
+ " \"threat_indicators\": len([e for e in threat_entities if e['type'] == 'ThreatIndicator']),\n",
+ " \"vulnerabilities\": len([e for e in threat_entities if e['type'] == 'Vulnerability']),\n",
+ " \"threat_types\": len([e for e in threat_entities if e['type'] == 'ThreatType']),\n",
+ " \"insights\": len(threat_insights)\n",
+ "}\n",
+ "\n",
+ "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
+ "\n",
+ "print(\"✓ Exported threat intelligence knowledge graph\")\n",
+ "print(f\" JSON: {os.path.join(temp_dir, 'threat_kg.json')}\")\n",
+ "print(f\" RDF: {os.path.join(temp_dir, 'threat_kg.rdf')}\")\n",
+ "print(f\"✓ Generated report ({len(report)} characters)\")\n",
+ "\n",
+ "# Visualize\n",
+ "kg_visualizer = KGVisualizer()\n",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "analytics_visualizer = AnalyticsVisualizer()\n",
+ "\n",
+ "kg_viz = kg_visualizer.visualize_network(threat_kg, output=\"interactive\")\n",
+ "temporal_viz = temporal_visualizer.visualize_timeline(threat_kg, output=\"interactive\")\n",
+ "analytics_viz = analytics_visualizer.visualize_analytics(threat_kg, output=\"interactive\")\n",
+ "\n",
+ "print(\"✓ Generated visualizations for threat intelligence knowledge graph\")\n",
+ "\n",
+ "# Cleanup: Disconnect from MCP server\n",
+ "try:\n",
+ " mcp_ingestor.disconnect(\"threat_server\")\n",
+ " print(\"\\n✓ Disconnected from MCP server\")\n",
+ "except:\n",
+ " pass\n",
+ "\n",
+ "print(f\"\\n✅ Pipeline complete: MCP Server → Ingest → Parse → Extract → Build KG → Embeddings → Hybrid RAG → Analyze → Export → Visualize\")\n",
+ "print(f\"📊 Total modules used: 20+\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/finance/Financial_Data_Integration.ipynb b/cookbook/use_cases/finance/Financial_Data_Integration.ipynb
new file mode 100644
index 00000000..d3836cce
--- /dev/null
+++ b/cookbook/use_cases/finance/Financial_Data_Integration.ipynb
@@ -0,0 +1,538 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Financial Data Integration Pipeline\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for financial data ingestion. Connect to financial data MCP servers via URL, ingest market data, stock prices, and financial metrics, then build a knowledge graph for financial analysis.\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",
+ "### Modules Used (20+)\n",
+ "\n",
+ "- **Ingestion**: MCPIngestor, ingest_mcp, WebIngestor, FileIngestor\n",
+ "- **Parsing**: MCPParser, JSONParser, StructuredDataParser\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer\n",
+ "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "\n",
+ "### Pipeline\n",
+ "\n",
+ "**Connect to Financial MCP Server → Ingest Market Data via MCP → Parse MCP Responses → Extract Financial Entities → Build Financial KG → Analyze Trends → Generate Reports → Visualize**\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Step 1: Connect to Financial Data MCP Server\n",
+ "\n",
+ "Connect to a Python/FastMCP MCP server that provides financial data via URL. The MCP server can expose resources (datasets, market data) and tools (queries, calculations).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import MCPParser, JSONParser, StructuredDataParser\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer\n",
+ "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "# Initialize MCP ingestor\n",
+ "mcp_ingestor = MCPIngestor()\n",
+ "\n",
+ "# Connect to financial data MCP server via URL\n",
+ "# Replace with your actual MCP server URL\n",
+ "# Example: http://localhost:8000/mcp or https://api.example.com/financial-mcp\n",
+ "financial_mcp_url = \"http://localhost:8000/mcp\"\n",
+ "\n",
+ "try:\n",
+ " # Connect to MCP server\n",
+ " mcp_ingestor.connect(\n",
+ " \"financial_server\",\n",
+ " url=financial_mcp_url,\n",
+ " headers={\"Authorization\": \"Bearer your_token\"} if \"api.example.com\" in financial_mcp_url else {}\n",
+ " )\n",
+ " print(f\"✓ Connected to financial MCP server at {financial_mcp_url}\")\n",
+ " \n",
+ " # List available resources (datasets, market data feeds)\n",
+ " resources = mcp_ingestor.list_available_resources(\"financial_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, calculations)\n",
+ " tools = mcp_ingestor.list_available_tools(\"financial_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",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Connection failed: {e}\")\n",
+ " print(\"Note: This example uses a placeholder URL. Replace with your actual MCP server URL.\")\n",
+ " print(\"For testing, you can use a mock MCP server or skip connection and use sample data below.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Financial Data from MCP Server\n",
+ "\n",
+ "Ingest financial data using both resource-based and tool-based methods from the MCP server.\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",
+ "financial_data = []\n",
+ "\n",
+ "# Method 1: Resource-based ingestion\n",
+ "# Ingest from MCP resources (pre-defined datasets)\n",
+ "try:\n",
+ " # Example: Ingest market data resource\n",
+ " resource_data = mcp_ingestor.ingest_resources(\n",
+ " \"financial_server\",\n",
+ " resource_uris=[\"resource://market_data/daily\", \"resource://market_data/stocks\"]\n",
+ " )\n",
+ " \n",
+ " for item in resource_data:\n",
+ " financial_data.append(item)\n",
+ " print(f\"✓ Ingested resource: {item.resource_uri}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Resource ingestion: {e}\")\n",
+ "\n",
+ "# Method 2: Tool-based ingestion\n",
+ "# Call MCP tools to retrieve data dynamically\n",
+ "try:\n",
+ " # Example: Get stock prices for specific symbols\n",
+ " stock_prices = mcp_ingestor.ingest_tool_output(\n",
+ " \"financial_server\",\n",
+ " tool_name=\"get_stock_prices\",\n",
+ " arguments={\n",
+ " \"symbols\": [\"AAPL\", \"MSFT\", \"GOOGL\", \"TSLA\"],\n",
+ " \"date\": datetime.now().isoformat()\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if stock_prices:\n",
+ " financial_data.append(stock_prices)\n",
+ " print(f\"✓ Retrieved stock prices via tool\")\n",
+ " \n",
+ " # Example: Get market metrics\n",
+ " market_metrics = mcp_ingestor.ingest_tool_output(\n",
+ " \"financial_server\",\n",
+ " tool_name=\"get_market_metrics\",\n",
+ " arguments={\"sector\": \"Technology\"}\n",
+ " )\n",
+ " \n",
+ " if market_metrics:\n",
+ " financial_data.append(market_metrics)\n",
+ " print(f\"✓ Retrieved market metrics via tool\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Tool-based ingestion: {e}\")\n",
+ " print(\"Note: Using sample data for demonstration\")\n",
+ "\n",
+ "# Sample financial data (if MCP server is not available)\n",
+ "if not financial_data:\n",
+ " print(\"\\n📝 Using sample financial data for demonstration:\")\n",
+ " sample_data = {\n",
+ " \"stock_prices\": [\n",
+ " {\n",
+ " \"symbol\": \"AAPL\",\n",
+ " \"company\": \"Apple Inc.\",\n",
+ " \"price\": 175.50,\n",
+ " \"change\": 2.30,\n",
+ " \"change_percent\": 1.33,\n",
+ " \"volume\": 45000000,\n",
+ " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",
+ " \"sector\": \"Technology\"\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"MSFT\",\n",
+ " \"company\": \"Microsoft Corporation\",\n",
+ " \"price\": 380.25,\n",
+ " \"change\": -1.50,\n",
+ " \"change_percent\": -0.39,\n",
+ " \"volume\": 28000000,\n",
+ " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",
+ " \"sector\": \"Technology\"\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"GOOGL\",\n",
+ " \"company\": \"Alphabet Inc.\",\n",
+ " \"price\": 142.80,\n",
+ " \"change\": 3.20,\n",
+ " \"change_percent\": 2.29,\n",
+ " \"volume\": 32000000,\n",
+ " \"timestamp\": (datetime.now() - timedelta(minutes=30)).isoformat(),\n",
+ " \"sector\": \"Technology\"\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"TSLA\",\n",
+ " \"company\": \"Tesla Inc.\",\n",
+ " \"price\": 245.60,\n",
+ " \"change\": 5.40,\n",
+ " \"change_percent\": 2.25,\n",
+ " \"volume\": 55000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"sector\": \"Automotive\"\n",
+ " }\n",
+ " ],\n",
+ " \"market_metrics\": {\n",
+ " \"total_volume\": 150000000,\n",
+ " \"market_cap\": 15000000000000,\n",
+ " \"sectors\": [\"Technology\", \"Automotive\"]\n",
+ " }\n",
+ " }\n",
+ " financial_data.append(sample_data)\n",
+ " print(f\" Loaded {len(sample_data['stock_prices'])} stock prices\")\n",
+ "\n",
+ "print(f\"\\n📊 Total financial data items ingested: {len(financial_data)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse MCP Data\n",
+ "\n",
+ "Parse the data received from MCP server responses (JSON, structured data).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "parsed_financial_data = []\n",
+ "\n",
+ "# Parse MCP responses\n",
+ "for data_item in financial_data:\n",
+ " try:\n",
+ " # Parse MCP response (handles JSON, text, binary)\n",
+ " if isinstance(data_item, dict):\n",
+ " # If it's already structured, use it directly\n",
+ " parsed_item = data_item\n",
+ " else:\n",
+ " # Parse using MCP parser\n",
+ " parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",
+ " \n",
+ " parsed_financial_data.append(parsed_item)\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\"⚠ Parsing error: {e}\")\n",
+ "\n",
+ "# Extract stock prices from parsed data\n",
+ "stock_prices = []\n",
+ "for item in parsed_financial_data:\n",
+ " if isinstance(item, dict):\n",
+ " if \"stock_prices\" in item:\n",
+ " stock_prices.extend(item[\"stock_prices\"])\n",
+ " elif \"symbol\" in item:\n",
+ " stock_prices.append(item)\n",
+ "\n",
+ "print(f\"✓ Parsed {len(parsed_financial_data)} data items\")\n",
+ "print(f\"✓ Extracted {len(stock_prices)} stock price records\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Financial Entities and Relationships\n",
+ "\n",
+ "Extract financial entities (companies, stocks, sectors) and relationships from MCP data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "semantic_analyzer = SemanticAnalyzer()\n",
+ "\n",
+ "financial_entities = []\n",
+ "financial_relationships = []\n",
+ "\n",
+ "# Extract entities and relationships from stock prices\n",
+ "for stock in stock_prices:\n",
+ " if isinstance(stock, dict):\n",
+ " symbol = stock.get(\"symbol\", \"\")\n",
+ " company = stock.get(\"company\", \"\")\n",
+ " sector = stock.get(\"sector\", \"\")\n",
+ " \n",
+ " # Stock entity\n",
+ " financial_entities.append({\n",
+ " \"id\": symbol,\n",
+ " \"type\": \"Stock\",\n",
+ " \"name\": symbol,\n",
+ " \"properties\": {\n",
+ " \"price\": stock.get(\"price\", 0),\n",
+ " \"change\": stock.get(\"change\", 0),\n",
+ " \"change_percent\": stock.get(\"change_percent\", 0),\n",
+ " \"volume\": stock.get(\"volume\", 0),\n",
+ " \"timestamp\": stock.get(\"timestamp\", \"\")\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Company entity\n",
+ " if company:\n",
+ " financial_entities.append({\n",
+ " \"id\": company,\n",
+ " \"type\": \"Company\",\n",
+ " \"name\": company,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # Stock-Company relationship\n",
+ " financial_relationships.append({\n",
+ " \"source\": symbol,\n",
+ " \"target\": company,\n",
+ " \"type\": \"ticker_for\",\n",
+ " \"properties\": {\"timestamp\": stock.get(\"timestamp\", \"\")}\n",
+ " })\n",
+ " \n",
+ " # Sector entity\n",
+ " if sector:\n",
+ " financial_entities.append({\n",
+ " \"id\": sector,\n",
+ " \"type\": \"Sector\",\n",
+ " \"name\": sector,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # Company-Sector relationship\n",
+ " if company:\n",
+ " financial_relationships.append({\n",
+ " \"source\": company,\n",
+ " \"target\": sector,\n",
+ " \"type\": \"belongs_to\",\n",
+ " \"properties\": {}\n",
+ " })\n",
+ "\n",
+ "# Remove duplicates\n",
+ "seen_entities = set()\n",
+ "unique_entities = []\n",
+ "for entity in financial_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",
+ "financial_entities = unique_entities\n",
+ "\n",
+ "print(f\"✓ Extracted {len(financial_entities)} financial entities\")\n",
+ "print(f\" - Stocks: {len([e for e in financial_entities if e['type'] == 'Stock'])}\")\n",
+ "print(f\" - Companies: {len([e for e in financial_entities if e['type'] == 'Company'])}\")\n",
+ "print(f\" - Sectors: {len([e for e in financial_entities if e['type'] == 'Sector'])}\")\n",
+ "print(f\"✓ Extracted {len(financial_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Financial Knowledge Graph\n",
+ "\n",
+ "Build a knowledge graph from the extracted financial entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "builder = GraphBuilder()\n",
+ "temporal_query = TemporalGraphQuery()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "\n",
+ "# Build knowledge graph\n",
+ "financial_kg = builder.build(financial_entities, financial_relationships)\n",
+ "\n",
+ "# Analyze graph structure\n",
+ "metrics = graph_analyzer.compute_metrics(financial_kg)\n",
+ "centrality_calculator = CentralityCalculator()\n",
+ "community_detector = CommunityDetector()\n",
+ "connectivity_analyzer = ConnectivityAnalyzer()\n",
+ "\n",
+ "# Calculate graph metrics\n",
+ "centrality_scores = centrality_calculator.calculate_centrality(financial_kg, measure=\"degree\")\n",
+ "communities = community_detector.detect_communities(financial_kg)\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(financial_kg)\n",
+ "\n",
+ "print(f\"✓ Built financial knowledge graph\")\n",
+ "print(f\" Entities: {len(financial_kg.get('entities', []))}\")\n",
+ "print(f\" Relationships: {len(financial_kg.get('relationships', []))}\")\n",
+ "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",
+ "print(f\" Communities detected: {len(communities)}\")\n",
+ "print(f\" Central entities: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Analyze Financial Trends\n",
+ "\n",
+ "Analyze financial trends using temporal queries and pattern detection.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Temporal analysis\n",
+ "start_time = (datetime.now() - timedelta(days=7)).isoformat()\n",
+ "end_time = datetime.now().isoformat()\n",
+ "\n",
+ "temporal_results = temporal_query.query_time_range(\n",
+ " graph=financial_kg,\n",
+ " query=\"Find stock price movements\",\n",
+ " start_time=start_time,\n",
+ " end_time=end_time\n",
+ ")\n",
+ "\n",
+ "# Inference engine for financial rules\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Financial analysis rules\n",
+ "inference_engine.add_rule(\"IF change_percent > 2 AND volume > 40000000 THEN strong_momentum\")\n",
+ "inference_engine.add_rule(\"IF change_percent < -1 AND volume > 50000000 THEN selling_pressure\")\n",
+ "inference_engine.add_rule(\"IF change_percent > 0 AND sector == 'Technology' THEN tech_growth\")\n",
+ "\n",
+ "# Add facts from stock data\n",
+ "for stock in stock_prices:\n",
+ " if isinstance(stock, dict):\n",
+ " inference_engine.add_fact({\n",
+ " \"symbol\": stock.get(\"symbol\", \"\"),\n",
+ " \"change_percent\": stock.get(\"change_percent\", 0),\n",
+ " \"volume\": stock.get(\"volume\", 0),\n",
+ " \"sector\": stock.get(\"sector\", \"\")\n",
+ " })\n",
+ "\n",
+ "# Generate insights\n",
+ "financial_insights = inference_engine.forward_chain()\n",
+ "\n",
+ "print(f\"✓ Temporal analysis completed\")\n",
+ "print(f\" Temporal entities: {len(temporal_results.get('entities', []))}\")\n",
+ "print(f\" Financial insights: {len(financial_insights)}\")\n",
+ "\n",
+ "# Display insights\n",
+ "for insight in financial_insights[:3]:\n",
+ " print(f\" - {insight}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Export and Visualize\n",
+ "\n",
+ "Export the financial 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",
+ "csv_exporter = CSVExporter()\n",
+ "rdf_exporter = RDFExporter()\n",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Export knowledge graph\n",
+ "json_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.json\"))\n",
+ "csv_exporter.export_entities(financial_entities, os.path.join(temp_dir, \"financial_entities.csv\"))\n",
+ "rdf_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.rdf\"))\n",
+ "\n",
+ "# Generate report\n",
+ "report_data = {\n",
+ " \"summary\": f\"Financial data integration from MCP server identified {len(financial_insights)} insights\",\n",
+ " \"stocks_analyzed\": len([e for e in financial_entities if e['type'] == 'Stock']),\n",
+ " \"companies\": len([e for e in financial_entities if e['type'] == 'Company']),\n",
+ " \"sectors\": len([e for e in financial_entities if e['type'] == 'Sector']),\n",
+ " \"insights\": len(financial_insights)\n",
+ "}\n",
+ "\n",
+ "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
+ "\n",
+ "print(\"✓ Exported financial knowledge graph\")\n",
+ "print(f\" JSON: {os.path.join(temp_dir, 'financial_kg.json')}\")\n",
+ "print(f\" CSV: {os.path.join(temp_dir, 'financial_entities.csv')}\")\n",
+ "print(f\" RDF: {os.path.join(temp_dir, 'financial_kg.rdf')}\")\n",
+ "print(f\"✓ Generated report ({len(report)} characters)\")\n",
+ "\n",
+ "# Visualize\n",
+ "kg_visualizer = KGVisualizer()\n",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "analytics_visualizer = AnalyticsVisualizer()\n",
+ "\n",
+ "kg_viz = kg_visualizer.visualize_network(financial_kg, output=\"interactive\")\n",
+ "temporal_viz = temporal_visualizer.visualize_timeline(financial_kg, output=\"interactive\")\n",
+ "analytics_viz = analytics_visualizer.visualize_analytics(financial_kg, output=\"interactive\")\n",
+ "\n",
+ "print(\"✓ Generated visualizations for financial knowledge graph\")\n",
+ "\n",
+ "# Cleanup: Disconnect from MCP server\n",
+ "try:\n",
+ " mcp_ingestor.disconnect(\"financial_server\")\n",
+ " print(\"\\n✓ Disconnected from MCP server\")\n",
+ "except:\n",
+ " pass\n",
+ "\n",
+ "print(f\"\\n✅ Pipeline complete: MCP Server → Ingest → Parse → Extract → Build KG → Analyze → Export → Visualize\")\n",
+ "print(f\"📊 Total modules used: 20+\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/finance/Market_Intelligence.ipynb b/cookbook/use_cases/finance/Market_Intelligence.ipynb
index 68e67650..08fa7049 100644
--- a/cookbook/use_cases/finance/Market_Intelligence.ipynb
+++ b/cookbook/use_cases/finance/Market_Intelligence.ipynb
@@ -12,8 +12,8 @@
"\n",
"### Modules Used (20+)\n",
"\n",
- "- **Ingestion**: WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",
- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser, HTMLParser\n",
+ "- **Ingestion**: WebIngestor, FeedIngestor, DBIngestor, FileIngestor, MCPIngestor\n",
+ "- **Parsing**: JSONParser, CSVParser, StructuredDataParser, HTMLParser, MCPParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
@@ -23,7 +23,7 @@
"\n",
"### Pipeline\n",
"\n",
- "**Multiple Market Sources → Parse Data → Extract Market Entities → Build Temporal KG → Analyze Trends → Generate Insights → Export → Visualize**\n",
+ "**Multiple Market Sources (Web, Feeds, DB, Files, MCP) → Parse Data → Extract Market Entities → Build Temporal KG → Analyze Trends → Generate Insights → Export → Visualize**\n",
"\n",
"---\n",
"\n",
@@ -63,8 +63,8 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",
- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser, HTMLParser\n",
+ "from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor, MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import JSONParser, CSVParser, StructuredDataParser, HTMLParser, MCPParser\n",
"from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
"from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
@@ -80,11 +80,13 @@
"feed_ingestor = FeedIngestor()\n",
"db_ingestor = DBIngestor()\n",
"file_ingestor = FileIngestor()\n",
+ "mcp_ingestor = MCPIngestor()\n",
"\n",
"json_parser = JSONParser()\n",
"csv_parser = CSVParser()\n",
"structured_parser = StructuredDataParser()\n",
"html_parser = HTMLParser()\n",
+ "mcp_parser = MCPParser()\n",
"\n",
"temp_dir = tempfile.mkdtemp()\n",
"\n",
@@ -185,6 +187,49 @@
"db_connection_string = \"postgresql://user:password@localhost:5432/market_data_db\"\n",
"db_query = \"SELECT symbol, price, volume, timestamp FROM market_data WHERE timestamp > NOW() - INTERVAL '1 day' ORDER BY timestamp DESC\"\n",
"\n",
+ "# Optional: Ingest from MCP server\n",
+ "# Users can bring their own financial data MCP server via URL\n",
+ "mcp_market_data = []\n",
+ "try:\n",
+ " # Connect to financial data MCP server via URL\n",
+ " # Example: http://localhost:8000/mcp or https://api.example.com/financial-mcp\n",
+ " financial_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",
+ " \n",
+ " mcp_ingestor.connect(\n",
+ " \"market_mcp_server\",\n",
+ " url=financial_mcp_url,\n",
+ " headers={\"Authorization\": \"Bearer your_token\"} if \"api.example.com\" in financial_mcp_url else {}\n",
+ " )\n",
+ " \n",
+ " # Ingest market data from MCP server resources or tools\n",
+ " mcp_data = mcp_ingestor.ingest_resources(\n",
+ " \"market_mcp_server\",\n",
+ " resource_uris=[\"resource://market_data/daily\"]\n",
+ " )\n",
+ " mcp_market_data.extend(mcp_data)\n",
+ " \n",
+ " # Or use tool-based ingestion\n",
+ " tool_data = mcp_ingestor.ingest_tool_output(\n",
+ " \"market_mcp_server\",\n",
+ " tool_name=\"get_stock_prices\",\n",
+ " arguments={\"symbols\": [\"AAPL\", \"MSFT\", \"GOOGL\"], \"date\": datetime.now().isoformat()}\n",
+ " )\n",
+ " if tool_data:\n",
+ " mcp_market_data.append(tool_data)\n",
+ " \n",
+ " # Parse MCP responses\n",
+ " for mcp_item in mcp_market_data:\n",
+ " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",
+ " if isinstance(parsed_mcp, dict) and \"stock_prices\" in parsed_mcp:\n",
+ " # Merge MCP data with existing market data\n",
+ " market_data.extend(parsed_mcp.get(\"stock_prices\", []))\n",
+ " \n",
+ " print(f\"✓ Ingested {len(mcp_market_data)} items from MCP server\")\n",
+ " mcp_ingestor.disconnect(\"market_mcp_server\")\n",
+ "except Exception as e:\n",
+ " print(f\"⚠ MCP ingestion skipped: {e}\")\n",
+ " print(\" Note: MCP ingestion is optional. You can bring your own MCP server via URL.\")\n",
+ "\n",
"print(f\"Ingested {len([file_objects_json]) if file_objects_json else 0} JSON market data files\")\n",
"print(f\"Ingested {len([file_objects_csv]) if file_objects_csv else 0} CSV market data files\")\n",
"print(f\"Parsed {len(parsed_json.data) if parsed_json and parsed_json.data else 0} JSON market entries\")\n",
diff --git a/cookbook/use_cases/healthcare/Clinical_Reports_Processing.ipynb b/cookbook/use_cases/healthcare/Clinical_Reports_Processing.ipynb
index 3494e58a..4582d85d 100644
--- a/cookbook/use_cases/healthcare/Clinical_Reports_Processing.ipynb
+++ b/cookbook/use_cases/healthcare/Clinical_Reports_Processing.ipynb
@@ -12,8 +12,8 @@
"\n",
"### Modules Used (20+)\n",
"\n",
- "- **Ingestion**: FileIngestor, DBIngestor, StreamIngestor, WebIngestor\n",
- "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, CSVParser\n",
+ "- **Ingestion**: FileIngestor, DBIngestor, StreamIngestor, WebIngestor, MCPIngestor\n",
+ "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",
"- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",
@@ -24,7 +24,7 @@
"\n",
"### Pipeline\n",
"\n",
- "**Clinical Documents → Parse → Extract Medical Entities → Build Medical KG → Store in Triple Store → Query Patient Data → Generate Reports → Visualize**\n",
+ "**Clinical Documents (Files, APIs, DB, MCP) → Parse → Extract Medical Entities → Build Medical KG → Store in Triple Store → Query Patient Data → Generate Reports → Visualize**\n",
"\n",
"---\n",
"\n",
@@ -39,8 +39,8 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, WebIngestor\n",
- "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, CSVParser\n",
+ "from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, WebIngestor, MCPIngestor, ingest_mcp\n",
+ "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",
"from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",
"from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
@@ -57,11 +57,13 @@
"db_ingestor = DBIngestor()\n",
"stream_ingestor = StreamIngestor()\n",
"web_ingestor = WebIngestor()\n",
+ "mcp_ingestor = MCPIngestor()\n",
"\n",
"document_parser = DocumentParser()\n",
"pdf_parser = PDFParser()\n",
"structured_parser = StructuredDataParser()\n",
"csv_parser = CSVParser()\n",
+ "mcp_parser = MCPParser()\n",
"\n",
"# Real healthcare data sources\n",
"healthcare_apis = [\n",
@@ -110,10 +112,67 @@
" except Exception as e:\n",
" print(f\"⚠ FHIR API ingestion for {api_url}: {str(e)[:100]}\")\n",
"\n",
+ "# Optional: Ingest from MCP server\n",
+ "# Users can bring their own medical database MCP server via URL\n",
+ "mcp_clinical_data = []\n",
+ "try:\n",
+ " # Connect to medical database MCP server via URL\n",
+ " # Example: http://localhost:8000/mcp or https://api.example.com/medical-mcp\n",
+ " medical_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",
+ " \n",
+ " mcp_ingestor.connect(\n",
+ " \"clinical_mcp_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",
+ " # Ingest patient records from MCP server\n",
+ " mcp_data = mcp_ingestor.ingest_resources(\n",
+ " \"clinical_mcp_server\",\n",
+ " resource_uris=[\"resource://patients/records\"]\n",
+ " )\n",
+ " mcp_clinical_data.extend(mcp_data)\n",
+ " \n",
+ " # Or use tool-based ingestion to query patient records\n",
+ " tool_data = mcp_ingestor.ingest_tool_output(\n",
+ " \"clinical_mcp_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",
+ " if tool_data:\n",
+ " mcp_clinical_data.append(tool_data)\n",
+ " \n",
+ " # Parse MCP responses and merge with existing clinical data\n",
+ " for mcp_item in mcp_clinical_data:\n",
+ " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",
+ " if isinstance(parsed_mcp, dict):\n",
+ " if \"patient_records\" in parsed_mcp:\n",
+ " # Merge patient records from MCP\n",
+ " if isinstance(parsed_data.data, list):\n",
+ " parsed_data.data.extend(parsed_mcp.get(\"patient_records\", []))\n",
+ " elif isinstance(parsed_data.data, dict):\n",
+ " parsed_data.data = [parsed_data.data] + parsed_mcp.get(\"patient_records\", [])\n",
+ " \n",
+ " print(f\"✓ Ingested {len(mcp_clinical_data)} items from MCP server\")\n",
+ " mcp_ingestor.disconnect(\"clinical_mcp_server\")\n",
+ "except Exception as e:\n",
+ " print(f\"⚠ MCP ingestion skipped: {e}\")\n",
+ " print(\" Note: MCP ingestion is optional. You can bring your own MCP server via URL.\")\n",
+ "\n",
"print(f\"\\n📊 Ingestion Summary:\")\n",
"print(f\" Clinical reports: {len([file_objects]) if file_objects else 0}\")\n",
"print(f\" FHIR API sources: {len(fhir_content_list)}\")\n",
- "print(f\" Database sources: 1\")\n"
+ "print(f\" Database sources: 1\")\n",
+ "print(f\" MCP server sources: {len(mcp_clinical_data)}\")\n"
]
},
{
diff --git a/cookbook/use_cases/healthcare/Medical_Database_Integration.ipynb b/cookbook/use_cases/healthcare/Medical_Database_Integration.ipynb
new file mode 100644
index 00000000..89aa6d91
--- /dev/null
+++ b/cookbook/use_cases/healthcare/Medical_Database_Integration.ipynb
@@ -0,0 +1,601 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 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",
+ "### 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",
+ "---\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.kg_qa import KGQualityAssessor, ValidationEngine\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",
+ "try:\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",
+ " print(f\"✓ Connected to medical MCP server at {medical_mcp_url}\")\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",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Connection failed: {e}\")\n",
+ " print(\"Note: This example uses a placeholder URL. Replace with your actual MCP server URL.\")\n",
+ " print(\"For testing, you can use a mock MCP server or skip connection and use sample data below.\")\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",
+ "try:\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.resource_uri}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Resource ingestion: {e}\")\n",
+ "\n",
+ "# Method 2: Tool-based ingestion\n",
+ "# Call MCP tools to retrieve data dynamically\n",
+ "try:\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 via tool\")\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 via tool\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Tool-based ingestion: {e}\")\n",
+ " print(\"Note: Using sample data for demonstration\")\n",
+ "\n",
+ "# Sample medical data (if MCP server is not available)\n",
+ "if not medical_data:\n",
+ " print(\"\\n📝 Using sample medical data for demonstration:\")\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",
+ " try:\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",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\"⚠ Parsing error: {e}\")\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",
+ "\n",
+ "print(f\"✓ Parsed {len(parsed_medical_data)} data items\")\n",
+ "print(f\"✓ Extracted {len(patient_records)} patient records\")\n",
+ "print(f\"✓ Extracted {len(drug_interactions)} drug interactions\")\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\"✓ Extracted {len(medical_entities)} medical entities\")\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",
+ "print(f\"✓ Extracted {len(medical_relationships)} relationships\")\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\"✓ Built healthcare knowledge graph\")\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",
+ "print(f\"✓ Stored in triple store\")\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\"✓ Queried healthcare knowledge graph\")\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 assessment completed\")\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",
+ "owl_exporter.export_knowledge_graph(resolved_kg, os.path.join(temp_dir, \"medical_kg.owl\"))\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(\"✓ Exported healthcare knowledge graph\")\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",
+ "print(f\" OWL: {os.path.join(temp_dir, 'medical_kg.owl')}\")\n",
+ "print(f\"✓ Generated report ({len(report)} characters)\")\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",
+ "print(\"✓ Generated visualizations for healthcare knowledge graph\")\n",
+ "\n",
+ "# Cleanup: Disconnect from MCP server\n",
+ "try:\n",
+ " mcp_ingestor.disconnect(\"medical_server\")\n",
+ " print(\"\\n✓ Disconnected from MCP server\")\n",
+ "except:\n",
+ " pass\n",
+ "\n",
+ "print(f\"\\n✅ Pipeline complete: MCP Server → Ingest → Parse → Extract → Build KG → Query → Export → Visualize\")\n",
+ "print(f\"📊 Total modules used: 20+\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/supply_chain/Supply_Chain_Data_Integration.ipynb b/cookbook/use_cases/supply_chain/Supply_Chain_Data_Integration.ipynb
new file mode 100644
index 00000000..8c4e855a
--- /dev/null
+++ b/cookbook/use_cases/supply_chain/Supply_Chain_Data_Integration.ipynb
@@ -0,0 +1,589 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Supply Chain Data Integration Pipeline\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for supply chain data ingestion. Connect to supply chain database MCP servers via URL, ingest logistics data, inventory, and shipment information, then build a supply chain 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",
+ "### Modules Used (20+)\n",
+ "\n",
+ "- **Ingestion**: MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",
+ "- **Parsing**: MCPParser, JSONParser, StructuredDataParser, CSVParser\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "\n",
+ "### Pipeline\n",
+ "\n",
+ "**Connect to Supply Chain MCP Server → Ingest Logistics Data via MCP → Parse MCP Responses → Extract Supply Chain Entities → Build Supply Chain KG → Analyze Supply Chain → Generate Reports → Visualize**\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Step 1: Connect to Supply Chain Database MCP Server\n",
+ "\n",
+ "Connect to a Python/FastMCP MCP server that provides supply chain data via URL. The MCP server can expose resources (inventory databases, shipment records) and tools (logistics queries, inventory checks).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",
+ "from semantica.parse import MCPParser, JSONParser, StructuredDataParser, CSVParser\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.kg import CentralityCalculator, CommunityDetector\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "# Initialize MCP ingestor\n",
+ "mcp_ingestor = MCPIngestor()\n",
+ "\n",
+ "# Connect to supply chain database MCP server via URL\n",
+ "# Replace with your actual MCP server URL\n",
+ "# Example: http://localhost:8000/mcp or https://api.example.com/supplychain-mcp\n",
+ "supply_chain_mcp_url = \"http://localhost:8000/mcp\"\n",
+ "\n",
+ "try:\n",
+ " # Connect to MCP server with authentication (if required)\n",
+ " mcp_ingestor.connect(\n",
+ " \"supply_chain_server\",\n",
+ " url=supply_chain_mcp_url,\n",
+ " headers={\n",
+ " \"Authorization\": \"Bearer your_token\",\n",
+ " \"X-API-Key\": \"your_api_key\"\n",
+ " } if \"api.example.com\" in supply_chain_mcp_url else {}\n",
+ " )\n",
+ " print(f\"✓ Connected to supply chain MCP server at {supply_chain_mcp_url}\")\n",
+ " \n",
+ " # List available resources (inventory databases, shipment records)\n",
+ " resources = mcp_ingestor.list_available_resources(\"supply_chain_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 (logistics queries, inventory checks)\n",
+ " tools = mcp_ingestor.list_available_tools(\"supply_chain_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",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Connection failed: {e}\")\n",
+ " print(\"Note: This example uses a placeholder URL. Replace with your actual MCP server URL.\")\n",
+ " print(\"For testing, you can use a mock MCP server or skip connection and use sample data below.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Supply Chain Data from MCP Server\n",
+ "\n",
+ "Ingest logistics data, inventory, and shipment information 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",
+ "csv_parser = CSVParser()\n",
+ "\n",
+ "supply_chain_data = []\n",
+ "\n",
+ "# Method 1: Resource-based ingestion\n",
+ "# Ingest from MCP resources (inventory databases, shipment records)\n",
+ "try:\n",
+ " # Example: Ingest inventory resource\n",
+ " inventory_data = mcp_ingestor.ingest_resources(\n",
+ " \"supply_chain_server\",\n",
+ " resource_uris=[\"resource://inventory/database\", \"resource://shipments/records\"]\n",
+ " )\n",
+ " \n",
+ " for item in inventory_data:\n",
+ " supply_chain_data.append(item)\n",
+ " print(f\"✓ Ingested resource: {item.resource_uri}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Resource ingestion: {e}\")\n",
+ "\n",
+ "# Method 2: Tool-based ingestion\n",
+ "# Call MCP tools to retrieve data dynamically\n",
+ "try:\n",
+ " # Example: Query inventory levels\n",
+ " inventory_levels = mcp_ingestor.ingest_tool_output(\n",
+ " \"supply_chain_server\",\n",
+ " tool_name=\"query_inventory\",\n",
+ " arguments={\n",
+ " \"warehouse_id\": \"WH001\",\n",
+ " \"product_category\": \"Electronics\"\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if inventory_levels:\n",
+ " supply_chain_data.append(inventory_levels)\n",
+ " print(f\"✓ Retrieved inventory levels via tool\")\n",
+ " \n",
+ " # Example: Get shipment status\n",
+ " shipment_status = mcp_ingestor.ingest_tool_output(\n",
+ " \"supply_chain_server\",\n",
+ " tool_name=\"get_shipment_status\",\n",
+ " arguments={\n",
+ " \"shipment_id\": \"SH001\",\n",
+ " \"include_tracking\": True\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if shipment_status:\n",
+ " supply_chain_data.append(shipment_status)\n",
+ " print(f\"✓ Retrieved shipment status via tool\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Tool-based ingestion: {e}\")\n",
+ " print(\"Note: Using sample data for demonstration\")\n",
+ "\n",
+ "# Sample supply chain data (if MCP server is not available)\n",
+ "if not supply_chain_data:\n",
+ " print(\"\\n📝 Using sample supply chain data for demonstration:\")\n",
+ " sample_data = {\n",
+ " \"inventory\": [\n",
+ " {\n",
+ " \"warehouse_id\": \"WH001\",\n",
+ " \"product_id\": \"P001\",\n",
+ " \"product_name\": \"Laptop\",\n",
+ " \"quantity\": 150,\n",
+ " \"location\": \"Aisle 3, Shelf 2\",\n",
+ " \"last_updated\": (datetime.now() - timedelta(days=1)).isoformat()\n",
+ " },\n",
+ " {\n",
+ " \"warehouse_id\": \"WH001\",\n",
+ " \"product_id\": \"P002\",\n",
+ " \"product_name\": \"Mouse\",\n",
+ " \"quantity\": 500,\n",
+ " \"location\": \"Aisle 1, Shelf 5\",\n",
+ " \"last_updated\": (datetime.now() - timedelta(hours=12)).isoformat()\n",
+ " },\n",
+ " {\n",
+ " \"warehouse_id\": \"WH002\",\n",
+ " \"product_id\": \"P001\",\n",
+ " \"product_name\": \"Laptop\",\n",
+ " \"quantity\": 200,\n",
+ " \"location\": \"Aisle 2, Shelf 1\",\n",
+ " \"last_updated\": datetime.now().isoformat()\n",
+ " }\n",
+ " ],\n",
+ " \"shipments\": [\n",
+ " {\n",
+ " \"shipment_id\": \"SH001\",\n",
+ " \"origin\": \"WH001\",\n",
+ " \"destination\": \"WH002\",\n",
+ " \"product_id\": \"P001\",\n",
+ " \"quantity\": 50,\n",
+ " \"status\": \"in_transit\",\n",
+ " \"estimated_arrival\": (datetime.now() + timedelta(days=2)).isoformat(),\n",
+ " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",
+ " },\n",
+ " {\n",
+ " \"shipment_id\": \"SH002\",\n",
+ " \"origin\": \"WH002\",\n",
+ " \"destination\": \"Customer A\",\n",
+ " \"product_id\": \"P002\",\n",
+ " \"quantity\": 100,\n",
+ " \"status\": \"delivered\",\n",
+ " \"estimated_arrival\": (datetime.now() - timedelta(days=1)).isoformat(),\n",
+ " \"timestamp\": (datetime.now() - timedelta(days=3)).isoformat()\n",
+ " }\n",
+ " ]\n",
+ " }\n",
+ " supply_chain_data.append(sample_data)\n",
+ " print(f\" Loaded {len(sample_data['inventory'])} inventory records\")\n",
+ " print(f\" Loaded {len(sample_data['shipments'])} shipment records\")\n",
+ "\n",
+ "print(f\"\\n📊 Total supply chain data items ingested: {len(supply_chain_data)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse Supply Chain Data\n",
+ "\n",
+ "Parse the supply chain data received from MCP server responses.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "parsed_supply_chain_data = []\n",
+ "\n",
+ "# Parse MCP responses\n",
+ "for data_item in supply_chain_data:\n",
+ " try:\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_supply_chain_data.append(parsed_item)\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\"⚠ Parsing error: {e}\")\n",
+ "\n",
+ "# Extract inventory and shipments\n",
+ "inventory_records = []\n",
+ "shipment_records = []\n",
+ "\n",
+ "for item in parsed_supply_chain_data:\n",
+ " if isinstance(item, dict):\n",
+ " if \"inventory\" in item:\n",
+ " inventory_records.extend(item[\"inventory\"])\n",
+ " elif \"warehouse_id\" in item and \"product_id\" in item:\n",
+ " inventory_records.append(item)\n",
+ " elif \"shipments\" in item:\n",
+ " shipment_records.extend(item[\"shipments\"])\n",
+ " elif \"shipment_id\" in item:\n",
+ " shipment_records.append(item)\n",
+ "\n",
+ "print(f\"✓ Parsed {len(parsed_supply_chain_data)} data items\")\n",
+ "print(f\"✓ Extracted {len(inventory_records)} inventory records\")\n",
+ "print(f\"✓ Extracted {len(shipment_records)} shipment records\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Supply Chain Entities and Relationships\n",
+ "\n",
+ "Extract supply chain entities (warehouses, products, shipments, locations) and relationships from MCP data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "triple_extractor = TripleExtractor()\n",
+ "\n",
+ "supply_chain_entities = []\n",
+ "supply_chain_relationships = []\n",
+ "\n",
+ "# Extract from inventory records\n",
+ "for inventory in inventory_records:\n",
+ " if isinstance(inventory, dict):\n",
+ " warehouse_id = inventory.get(\"warehouse_id\", \"\")\n",
+ " product_id = inventory.get(\"product_id\", \"\")\n",
+ " product_name = inventory.get(\"product_name\", \"\")\n",
+ " location = inventory.get(\"location\", \"\")\n",
+ " \n",
+ " # Warehouse entity\n",
+ " supply_chain_entities.append({\n",
+ " \"id\": warehouse_id,\n",
+ " \"type\": \"Warehouse\",\n",
+ " \"name\": warehouse_id,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # Product entity\n",
+ " supply_chain_entities.append({\n",
+ " \"id\": product_id,\n",
+ " \"type\": \"Product\",\n",
+ " \"name\": product_name or product_id,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # Warehouse-Product relationship (inventory)\n",
+ " supply_chain_relationships.append({\n",
+ " \"source\": warehouse_id,\n",
+ " \"target\": product_id,\n",
+ " \"type\": \"stocks\",\n",
+ " \"properties\": {\n",
+ " \"quantity\": inventory.get(\"quantity\", 0),\n",
+ " \"location\": location,\n",
+ " \"last_updated\": inventory.get(\"last_updated\", \"\")\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "# Extract from shipment records\n",
+ "for shipment in shipment_records:\n",
+ " if isinstance(shipment, dict):\n",
+ " shipment_id = shipment.get(\"shipment_id\", \"\")\n",
+ " origin = shipment.get(\"origin\", \"\")\n",
+ " destination = shipment.get(\"destination\", \"\")\n",
+ " product_id = shipment.get(\"product_id\", \"\")\n",
+ " \n",
+ " # Shipment entity\n",
+ " supply_chain_entities.append({\n",
+ " \"id\": shipment_id,\n",
+ " \"type\": \"Shipment\",\n",
+ " \"name\": shipment_id,\n",
+ " \"properties\": {\n",
+ " \"status\": shipment.get(\"status\", \"\"),\n",
+ " \"quantity\": shipment.get(\"quantity\", 0),\n",
+ " \"estimated_arrival\": shipment.get(\"estimated_arrival\", \"\"),\n",
+ " \"timestamp\": shipment.get(\"timestamp\", \"\")\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Origin-Destination relationships\n",
+ " if origin:\n",
+ " supply_chain_relationships.append({\n",
+ " \"source\": origin,\n",
+ " \"target\": shipment_id,\n",
+ " \"type\": \"ships_from\",\n",
+ " \"properties\": {\"timestamp\": shipment.get(\"timestamp\", \"\")}\n",
+ " })\n",
+ " \n",
+ " if destination:\n",
+ " supply_chain_relationships.append({\n",
+ " \"source\": shipment_id,\n",
+ " \"target\": destination,\n",
+ " \"type\": \"ships_to\",\n",
+ " \"properties\": {\"timestamp\": shipment.get(\"timestamp\", \"\")}\n",
+ " })\n",
+ " \n",
+ " # Shipment-Product relationship\n",
+ " if product_id:\n",
+ " supply_chain_relationships.append({\n",
+ " \"source\": shipment_id,\n",
+ " \"target\": product_id,\n",
+ " \"type\": \"contains\",\n",
+ " \"properties\": {\"quantity\": shipment.get(\"quantity\", 0)}\n",
+ " })\n",
+ "\n",
+ "# Remove duplicates\n",
+ "seen_entities = set()\n",
+ "unique_entities = []\n",
+ "for entity in supply_chain_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",
+ "supply_chain_entities = unique_entities\n",
+ "\n",
+ "print(f\"✓ Extracted {len(supply_chain_entities)} supply chain entities\")\n",
+ "print(f\" - Warehouses: {len([e for e in supply_chain_entities if e['type'] == 'Warehouse'])}\")\n",
+ "print(f\" - Products: {len([e for e in supply_chain_entities if e['type'] == 'Product'])}\")\n",
+ "print(f\" - Shipments: {len([e for e in supply_chain_entities if e['type'] == 'Shipment'])}\")\n",
+ "print(f\"✓ Extracted {len(supply_chain_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Supply Chain Knowledge Graph\n",
+ "\n",
+ "Build a knowledge graph from the extracted supply chain entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "builder = GraphBuilder()\n",
+ "temporal_query = TemporalGraphQuery()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "connectivity_analyzer = ConnectivityAnalyzer()\n",
+ "\n",
+ "# Build knowledge graph\n",
+ "supply_chain_kg = builder.build(supply_chain_entities, supply_chain_relationships)\n",
+ "\n",
+ "# Analyze graph structure\n",
+ "metrics = graph_analyzer.compute_metrics(supply_chain_kg)\n",
+ "centrality_calculator = CentralityCalculator()\n",
+ "community_detector = CommunityDetector()\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(supply_chain_kg)\n",
+ "\n",
+ "# Calculate graph metrics\n",
+ "centrality_scores = centrality_calculator.calculate_centrality(supply_chain_kg, measure=\"degree\")\n",
+ "communities = community_detector.detect_communities(supply_chain_kg)\n",
+ "\n",
+ "print(f\"✓ Built supply chain knowledge graph\")\n",
+ "print(f\" Entities: {len(supply_chain_kg.get('entities', []))}\")\n",
+ "print(f\" Relationships: {len(supply_chain_kg.get('relationships', []))}\")\n",
+ "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",
+ "print(f\" Communities detected: {len(communities)}\")\n",
+ "print(f\" Connected components: {connectivity.get('connected_components', 0)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Analyze Supply Chain\n",
+ "\n",
+ "Analyze supply chain patterns using temporal queries and inference rules.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Temporal analysis\n",
+ "start_time = (datetime.now() - timedelta(days=30)).isoformat()\n",
+ "end_time = datetime.now().isoformat()\n",
+ "\n",
+ "temporal_results = temporal_query.query_time_range(\n",
+ " graph=supply_chain_kg,\n",
+ " query=\"Find shipments in the last 30 days\",\n",
+ " start_time=start_time,\n",
+ " end_time=end_time\n",
+ ")\n",
+ "\n",
+ "# Inference engine for supply chain rules\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Supply chain analysis rules\n",
+ "inference_engine.add_rule(\"IF quantity < 100 AND product_type(Electronics) THEN low_stock_alert\")\n",
+ "inference_engine.add_rule(\"IF status(in_transit) AND days_since_shipment > 5 THEN delayed_shipment\")\n",
+ "inference_engine.add_rule(\"IF stocks(Warehouse, Product) AND quantity > 500 THEN high_inventory\")\n",
+ "\n",
+ "# Add facts from supply chain data\n",
+ "for inventory in inventory_records:\n",
+ " if isinstance(inventory, dict):\n",
+ " inference_engine.add_fact({\n",
+ " \"warehouse\": inventory.get(\"warehouse_id\", \"\"),\n",
+ " \"product\": inventory.get(\"product_id\", \"\"),\n",
+ " \"quantity\": inventory.get(\"quantity\", 0),\n",
+ " \"product_name\": inventory.get(\"product_name\", \"\")\n",
+ " })\n",
+ "\n",
+ "for shipment in shipment_records:\n",
+ " if isinstance(shipment, dict):\n",
+ " days_since = (datetime.now() - datetime.fromisoformat(shipment.get(\"timestamp\", datetime.now().isoformat()))).days\n",
+ " inference_engine.add_fact({\n",
+ " \"shipment_id\": shipment.get(\"shipment_id\", \"\"),\n",
+ " \"status\": shipment.get(\"status\", \"\"),\n",
+ " \"days_since_shipment\": days_since\n",
+ " })\n",
+ "\n",
+ "# Generate supply chain insights\n",
+ "supply_chain_insights = inference_engine.forward_chain()\n",
+ "\n",
+ "print(f\"✓ Temporal analysis completed\")\n",
+ "print(f\" Temporal entities: {len(temporal_results.get('entities', []))}\")\n",
+ "print(f\" Supply chain insights: {len(supply_chain_insights)}\")\n",
+ "\n",
+ "# Display insights\n",
+ "for insight in supply_chain_insights[:3]:\n",
+ " print(f\" - {insight}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Export and Visualize\n",
+ "\n",
+ "Export the supply chain 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",
+ "csv_exporter = CSVExporter()\n",
+ "rdf_exporter = RDFExporter()\n",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Export knowledge graph\n",
+ "json_exporter.export_knowledge_graph(supply_chain_kg, os.path.join(temp_dir, \"supply_chain_kg.json\"))\n",
+ "csv_exporter.export_entities(supply_chain_entities, os.path.join(temp_dir, \"supply_chain_entities.csv\"))\n",
+ "rdf_exporter.export_knowledge_graph(supply_chain_kg, os.path.join(temp_dir, \"supply_chain_kg.rdf\"))\n",
+ "\n",
+ "# Generate report\n",
+ "report_data = {\n",
+ " \"summary\": f\"Supply chain data integration from MCP server identified {len(supply_chain_insights)} insights\",\n",
+ " \"warehouses\": len([e for e in supply_chain_entities if e['type'] == 'Warehouse']),\n",
+ " \"products\": len([e for e in supply_chain_entities if e['type'] == 'Product']),\n",
+ " \"shipments\": len([e for e in supply_chain_entities if e['type'] == 'Shipment']),\n",
+ " \"inventory_records\": len(inventory_records),\n",
+ " \"insights\": len(supply_chain_insights)\n",
+ "}\n",
+ "\n",
+ "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
+ "\n",
+ "print(\"✓ Exported supply chain knowledge graph\")\n",
+ "print(f\" JSON: {os.path.join(temp_dir, 'supply_chain_kg.json')}\")\n",
+ "print(f\" CSV: {os.path.join(temp_dir, 'supply_chain_entities.csv')}\")\n",
+ "print(f\" RDF: {os.path.join(temp_dir, 'supply_chain_kg.rdf')}\")\n",
+ "print(f\"✓ Generated report ({len(report)} characters)\")\n",
+ "\n",
+ "# Visualize\n",
+ "kg_visualizer = KGVisualizer()\n",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "analytics_visualizer = AnalyticsVisualizer()\n",
+ "\n",
+ "kg_viz = kg_visualizer.visualize_network(supply_chain_kg, output=\"interactive\")\n",
+ "temporal_viz = temporal_visualizer.visualize_timeline(supply_chain_kg, output=\"interactive\")\n",
+ "analytics_viz = analytics_visualizer.visualize_analytics(supply_chain_kg, output=\"interactive\")\n",
+ "\n",
+ "print(\"✓ Generated visualizations for supply chain knowledge graph\")\n",
+ "\n",
+ "# Cleanup: Disconnect from MCP server\n",
+ "try:\n",
+ " mcp_ingestor.disconnect(\"supply_chain_server\")\n",
+ " print(\"\\n✓ Disconnected from MCP server\")\n",
+ "except:\n",
+ " pass\n",
+ "\n",
+ "print(f\"\\n✅ Pipeline complete: MCP Server → Ingest → Parse → Extract → Build KG → Analyze → Export → Visualize\")\n",
+ "print(f\"📊 Total modules used: 20+\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/trading/Real_Time_Market_Data.ipynb b/cookbook/use_cases/trading/Real_Time_Market_Data.ipynb
new file mode 100644
index 00000000..b83938ae
--- /dev/null
+++ b/cookbook/use_cases/trading/Real_Time_Market_Data.ipynb
@@ -0,0 +1,566 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Real-Time Market Data Integration Pipeline\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for real-time market data ingestion. Connect to real-time market data MCP servers via URL, ingest live market data, and build a temporal trading 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",
+ "### Modules Used (20+)\n",
+ "\n",
+ "- **Ingestion**: MCPIngestor, ingest_mcp, StreamIngestor\n",
+ "- **Parsing**: MCPParser, JSONParser, StructuredDataParser\n",
+ "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
+ "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "\n",
+ "### Pipeline\n",
+ "\n",
+ "**Connect to Real-Time Market MCP Server → Ingest Live Market Data via MCP → Parse MCP Responses → Extract Trading Entities → Build Temporal Trading KG → Analyze Market Patterns → Generate Reports → Visualize**\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Step 1: Connect to Real-Time Market Data MCP Server\n",
+ "\n",
+ "Connect to a Python/FastMCP MCP server that provides real-time market data via URL. The MCP server can expose resources (market feeds) and tools (real-time price queries, market data streams).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, ingest_mcp, StreamIngestor\n",
+ "from semantica.parse import MCPParser, JSONParser, StructuredDataParser\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",
+ "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",
+ "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "# Initialize MCP ingestor\n",
+ "mcp_ingestor = MCPIngestor()\n",
+ "\n",
+ "# Connect to real-time market data MCP server via URL\n",
+ "# Replace with your actual MCP server URL\n",
+ "# Example: http://localhost:8000/mcp or https://api.example.com/market-mcp\n",
+ "market_mcp_url = \"http://localhost:8000/mcp\"\n",
+ "\n",
+ "try:\n",
+ " # Connect to MCP server with authentication (if required)\n",
+ " mcp_ingestor.connect(\n",
+ " \"market_server\",\n",
+ " url=market_mcp_url,\n",
+ " headers={\n",
+ " \"Authorization\": \"Bearer your_token\",\n",
+ " \"X-API-Key\": \"your_api_key\"\n",
+ " } if \"api.example.com\" in market_mcp_url else {}\n",
+ " )\n",
+ " print(f\"✓ Connected to real-time market data MCP server at {market_mcp_url}\")\n",
+ " \n",
+ " # List available resources (market feeds, price streams)\n",
+ " resources = mcp_ingestor.list_available_resources(\"market_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 (real-time queries, market data streams)\n",
+ " tools = mcp_ingestor.list_available_tools(\"market_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",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Connection failed: {e}\")\n",
+ " print(\"Note: This example uses a placeholder URL. Replace with your actual MCP server URL.\")\n",
+ " print(\"For testing, you can use a mock MCP server or skip connection and use sample data below.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Real-Time Market Data from MCP Server\n",
+ "\n",
+ "Ingest live market data using both resource-based and tool-based methods, including streaming data.\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",
+ "market_data = []\n",
+ "\n",
+ "# Method 1: Resource-based ingestion\n",
+ "# Ingest from MCP resources (market feeds)\n",
+ "try:\n",
+ " # Example: Ingest real-time market feed resource\n",
+ " market_feeds = mcp_ingestor.ingest_resources(\n",
+ " \"market_server\",\n",
+ " resource_uris=[\"resource://market/real_time\", \"resource://market/stream\"]\n",
+ " )\n",
+ " \n",
+ " for item in market_feeds:\n",
+ " market_data.append(item)\n",
+ " print(f\"✓ Ingested resource: {item.resource_uri}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Resource ingestion: {e}\")\n",
+ "\n",
+ "# Method 2: Tool-based ingestion\n",
+ "# Call MCP tools to retrieve real-time data dynamically\n",
+ "try:\n",
+ " # Example: Get real-time stock prices\n",
+ " real_time_prices = mcp_ingestor.ingest_tool_output(\n",
+ " \"market_server\",\n",
+ " tool_name=\"get_real_time_prices\",\n",
+ " arguments={\n",
+ " \"symbols\": [\"AAPL\", \"MSFT\", \"GOOGL\", \"TSLA\", \"AMZN\"],\n",
+ " \"interval\": \"1min\"\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if real_time_prices:\n",
+ " market_data.append(real_time_prices)\n",
+ " print(f\"✓ Retrieved real-time prices via tool\")\n",
+ " \n",
+ " # Example: Get market depth data\n",
+ " market_depth = mcp_ingestor.ingest_tool_output(\n",
+ " \"market_server\",\n",
+ " tool_name=\"get_market_depth\",\n",
+ " arguments={\n",
+ " \"symbol\": \"AAPL\",\n",
+ " \"levels\": 5\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " if market_depth:\n",
+ " market_data.append(market_depth)\n",
+ " print(f\"✓ Retrieved market depth via tool\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"⚠ Tool-based ingestion: {e}\")\n",
+ " print(\"Note: Using sample data for demonstration\")\n",
+ "\n",
+ "# Sample real-time market data (if MCP server is not available)\n",
+ "if not market_data:\n",
+ " print(\"\\n📝 Using sample real-time market data for demonstration:\")\n",
+ " sample_data = {\n",
+ " \"real_time_prices\": [\n",
+ " {\n",
+ " \"symbol\": \"AAPL\",\n",
+ " \"price\": 175.50,\n",
+ " \"change\": 2.30,\n",
+ " \"change_percent\": 1.33,\n",
+ " \"volume\": 45000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"bid\": 175.48,\n",
+ " \"ask\": 175.52,\n",
+ " \"spread\": 0.04\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"MSFT\",\n",
+ " \"price\": 380.25,\n",
+ " \"change\": -1.50,\n",
+ " \"change_percent\": -0.39,\n",
+ " \"volume\": 28000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"bid\": 380.20,\n",
+ " \"ask\": 380.30,\n",
+ " \"spread\": 0.10\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"GOOGL\",\n",
+ " \"price\": 142.80,\n",
+ " \"change\": 3.20,\n",
+ " \"change_percent\": 2.29,\n",
+ " \"volume\": 32000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"bid\": 142.75,\n",
+ " \"ask\": 142.85,\n",
+ " \"spread\": 0.10\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"TSLA\",\n",
+ " \"price\": 245.60,\n",
+ " \"change\": 5.40,\n",
+ " \"change_percent\": 2.25,\n",
+ " \"volume\": 55000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"bid\": 245.55,\n",
+ " \"ask\": 245.65,\n",
+ " \"spread\": 0.10\n",
+ " },\n",
+ " {\n",
+ " \"symbol\": \"AMZN\",\n",
+ " \"price\": 155.30,\n",
+ " \"change\": 1.20,\n",
+ " \"change_percent\": 0.78,\n",
+ " \"volume\": 42000000,\n",
+ " \"timestamp\": datetime.now().isoformat(),\n",
+ " \"bid\": 155.25,\n",
+ " \"ask\": 155.35,\n",
+ " \"spread\": 0.10\n",
+ " }\n",
+ " ]\n",
+ " }\n",
+ " market_data.append(sample_data)\n",
+ " print(f\" Loaded {len(sample_data['real_time_prices'])} real-time price records\")\n",
+ "\n",
+ "print(f\"\\n📊 Total market data items ingested: {len(market_data)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse Real-Time Market Data\n",
+ "\n",
+ "Parse the real-time market data received from MCP server responses.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "parsed_market_data = []\n",
+ "\n",
+ "# Parse MCP responses\n",
+ "for data_item in market_data:\n",
+ " try:\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_market_data.append(parsed_item)\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\"⚠ Parsing error: {e}\")\n",
+ "\n",
+ "# Extract real-time prices\n",
+ "real_time_prices = []\n",
+ "\n",
+ "for item in parsed_market_data:\n",
+ " if isinstance(item, dict):\n",
+ " if \"real_time_prices\" in item:\n",
+ " real_time_prices.extend(item[\"real_time_prices\"])\n",
+ " elif \"symbol\" in item and \"price\" in item:\n",
+ " real_time_prices.append(item)\n",
+ "\n",
+ "print(f\"✓ Parsed {len(parsed_market_data)} data items\")\n",
+ "print(f\"✓ Extracted {len(real_time_prices)} real-time price records\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Trading Entities and Relationships\n",
+ "\n",
+ "Extract trading entities (stocks, prices, market events) and relationships from real-time MCP data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "semantic_analyzer = SemanticAnalyzer()\n",
+ "\n",
+ "trading_entities = []\n",
+ "trading_relationships = []\n",
+ "\n",
+ "# Extract from real-time prices\n",
+ "for price_data in real_time_prices:\n",
+ " if isinstance(price_data, dict):\n",
+ " symbol = price_data.get(\"symbol\", \"\")\n",
+ " timestamp = price_data.get(\"timestamp\", \"\")\n",
+ " \n",
+ " # Stock entity with real-time price\n",
+ " trading_entities.append({\n",
+ " \"id\": f\"{symbol}_{timestamp}\",\n",
+ " \"type\": \"PricePoint\",\n",
+ " \"name\": f\"{symbol} @ {timestamp}\",\n",
+ " \"properties\": {\n",
+ " \"symbol\": symbol,\n",
+ " \"price\": price_data.get(\"price\", 0),\n",
+ " \"change\": price_data.get(\"change\", 0),\n",
+ " \"change_percent\": price_data.get(\"change_percent\", 0),\n",
+ " \"volume\": price_data.get(\"volume\", 0),\n",
+ " \"bid\": price_data.get(\"bid\", 0),\n",
+ " \"ask\": price_data.get(\"ask\", 0),\n",
+ " \"spread\": price_data.get(\"spread\", 0),\n",
+ " \"timestamp\": timestamp\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Stock entity\n",
+ " trading_entities.append({\n",
+ " \"id\": symbol,\n",
+ " \"type\": \"Stock\",\n",
+ " \"name\": symbol,\n",
+ " \"properties\": {}\n",
+ " })\n",
+ " \n",
+ " # PricePoint-Stock relationship\n",
+ " trading_relationships.append({\n",
+ " \"source\": f\"{symbol}_{timestamp}\",\n",
+ " \"target\": symbol,\n",
+ " \"type\": \"price_for\",\n",
+ " \"properties\": {\"timestamp\": timestamp}\n",
+ " })\n",
+ " \n",
+ " # Market event detection\n",
+ " if price_data.get(\"change_percent\", 0) > 2:\n",
+ " event_id = f\"event_{symbol}_{timestamp}\"\n",
+ " trading_entities.append({\n",
+ " \"id\": event_id,\n",
+ " \"type\": \"MarketEvent\",\n",
+ " \"name\": \"Price Surge\",\n",
+ " \"properties\": {\n",
+ " \"event_type\": \"surge\",\n",
+ " \"magnitude\": price_data.get(\"change_percent\", 0),\n",
+ " \"timestamp\": timestamp\n",
+ " }\n",
+ " })\n",
+ " trading_relationships.append({\n",
+ " \"source\": event_id,\n",
+ " \"target\": symbol,\n",
+ " \"type\": \"affects\",\n",
+ " \"properties\": {\"timestamp\": timestamp}\n",
+ " })\n",
+ "\n",
+ "# Remove duplicates\n",
+ "seen_entities = set()\n",
+ "unique_entities = []\n",
+ "for entity in trading_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",
+ "trading_entities = unique_entities\n",
+ "\n",
+ "print(f\"✓ Extracted {len(trading_entities)} trading entities\")\n",
+ "print(f\" - Price Points: {len([e for e in trading_entities if e['type'] == 'PricePoint'])}\")\n",
+ "print(f\" - Stocks: {len([e for e in trading_entities if e['type'] == 'Stock'])}\")\n",
+ "print(f\" - Market Events: {len([e for e in trading_entities if e['type'] == 'MarketEvent'])}\")\n",
+ "print(f\"✓ Extracted {len(trading_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Temporal Trading Knowledge Graph\n",
+ "\n",
+ "Build a temporal knowledge graph from the extracted trading entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "builder = GraphBuilder()\n",
+ "temporal_query = TemporalGraphQuery()\n",
+ "temporal_pattern_detector = TemporalPatternDetector()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "\n",
+ "# Build temporal knowledge graph\n",
+ "trading_kg = builder.build(trading_entities, trading_relationships)\n",
+ "\n",
+ "# Analyze graph structure\n",
+ "metrics = graph_analyzer.compute_metrics(trading_kg)\n",
+ "centrality_calculator = CentralityCalculator()\n",
+ "community_detector = CommunityDetector()\n",
+ "connectivity_analyzer = ConnectivityAnalyzer()\n",
+ "\n",
+ "# Calculate graph metrics\n",
+ "centrality_scores = centrality_calculator.calculate_centrality(trading_kg, measure=\"degree\")\n",
+ "communities = community_detector.detect_communities(trading_kg)\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(trading_kg)\n",
+ "\n",
+ "# Detect temporal patterns\n",
+ "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",
+ " trading_kg,\n",
+ " pattern_type=\"trend\",\n",
+ " min_frequency=1\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Built temporal trading knowledge graph\")\n",
+ "print(f\" Entities: {len(trading_kg.get('entities', []))}\")\n",
+ "print(f\" Relationships: {len(trading_kg.get('relationships', []))}\")\n",
+ "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",
+ "print(f\" Communities detected: {len(communities)}\")\n",
+ "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Analyze Market Patterns\n",
+ "\n",
+ "Analyze real-time market patterns using temporal queries and pattern detection.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Temporal analysis\n",
+ "start_time = (datetime.now() - timedelta(hours=1)).isoformat()\n",
+ "end_time = datetime.now().isoformat()\n",
+ "\n",
+ "temporal_results = temporal_query.query_time_range(\n",
+ " graph=trading_kg,\n",
+ " query=\"Find price movements in the last hour\",\n",
+ " start_time=start_time,\n",
+ " end_time=end_time\n",
+ ")\n",
+ "\n",
+ "# Inference engine for trading rules\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Trading analysis rules\n",
+ "inference_engine.add_rule(\"IF change_percent > 2 AND volume > 40000000 THEN strong_momentum\")\n",
+ "inference_engine.add_rule(\"IF change_percent < -1 AND volume > 50000000 THEN selling_pressure\")\n",
+ "inference_engine.add_rule(\"IF spread < 0.05 AND volume > 30000000 THEN high_liquidity\")\n",
+ "\n",
+ "# Add facts from real-time price data\n",
+ "for price_data in real_time_prices:\n",
+ " if isinstance(price_data, dict):\n",
+ " inference_engine.add_fact({\n",
+ " \"symbol\": price_data.get(\"symbol\", \"\"),\n",
+ " \"change_percent\": price_data.get(\"change_percent\", 0),\n",
+ " \"volume\": price_data.get(\"volume\", 0),\n",
+ " \"spread\": price_data.get(\"spread\", 0)\n",
+ " })\n",
+ "\n",
+ "# Generate trading insights\n",
+ "trading_insights = inference_engine.forward_chain()\n",
+ "\n",
+ "print(f\"✓ Temporal analysis completed\")\n",
+ "print(f\" Temporal entities: {len(temporal_results.get('entities', []))}\")\n",
+ "print(f\" Trading insights: {len(trading_insights)}\")\n",
+ "\n",
+ "# Display insights\n",
+ "for insight in trading_insights[:3]:\n",
+ " print(f\" - {insight}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Export and Visualize\n",
+ "\n",
+ "Export the trading 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",
+ "csv_exporter = CSVExporter()\n",
+ "rdf_exporter = RDFExporter()\n",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Export knowledge graph\n",
+ "json_exporter.export_knowledge_graph(trading_kg, os.path.join(temp_dir, \"trading_kg.json\"))\n",
+ "csv_exporter.export_entities(trading_entities, os.path.join(temp_dir, \"trading_entities.csv\"))\n",
+ "rdf_exporter.export_knowledge_graph(trading_kg, os.path.join(temp_dir, \"trading_kg.rdf\"))\n",
+ "\n",
+ "# Generate report\n",
+ "report_data = {\n",
+ " \"summary\": f\"Real-time market data integration from MCP server identified {len(trading_insights)} insights\",\n",
+ " \"price_points\": len([e for e in trading_entities if e['type'] == 'PricePoint']),\n",
+ " \"stocks\": len([e for e in trading_entities if e['type'] == 'Stock']),\n",
+ " \"market_events\": len([e for e in trading_entities if e['type'] == 'MarketEvent']),\n",
+ " \"temporal_patterns\": len(temporal_patterns),\n",
+ " \"insights\": len(trading_insights)\n",
+ "}\n",
+ "\n",
+ "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
+ "\n",
+ "print(\"✓ Exported trading knowledge graph\")\n",
+ "print(f\" JSON: {os.path.join(temp_dir, 'trading_kg.json')}\")\n",
+ "print(f\" CSV: {os.path.join(temp_dir, 'trading_entities.csv')}\")\n",
+ "print(f\" RDF: {os.path.join(temp_dir, 'trading_kg.rdf')}\")\n",
+ "print(f\"✓ Generated report ({len(report)} characters)\")\n",
+ "\n",
+ "# Visualize\n",
+ "kg_visualizer = KGVisualizer()\n",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "analytics_visualizer = AnalyticsVisualizer()\n",
+ "\n",
+ "kg_viz = kg_visualizer.visualize_network(trading_kg, output=\"interactive\")\n",
+ "temporal_viz = temporal_visualizer.visualize_timeline(trading_kg, output=\"interactive\")\n",
+ "analytics_viz = analytics_visualizer.visualize_analytics(trading_kg, output=\"interactive\")\n",
+ "\n",
+ "print(\"✓ Generated visualizations for trading knowledge graph\")\n",
+ "\n",
+ "# Cleanup: Disconnect from MCP server\n",
+ "try:\n",
+ " mcp_ingestor.disconnect(\"market_server\")\n",
+ " print(\"\\n✓ Disconnected from MCP server\")\n",
+ "except:\n",
+ " pass\n",
+ "\n",
+ "print(f\"\\n✅ Pipeline complete: MCP Server → Ingest Real-Time Data → Parse → Extract → Build Temporal KG → Analyze Patterns → Export → Visualize\")\n",
+ "print(f\"📊 Total modules used: 20+\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/semantica/ingest/config.py b/semantica/ingest/config.py
index 6cc0c4b5..a21f0ace 100644
--- a/semantica/ingest/config.py
+++ b/semantica/ingest/config.py
@@ -95,11 +95,10 @@ class IngestConfig:
"INGEST_RESPECT_ROBOTS": ("respect_robots", bool),
"INGEST_BATCH_SIZE": ("batch_size", int),
"INGEST_TIMEOUT": ("timeout", float),
- # MCP server configuration
+ # MCP server configuration (URL-based, Python/FastMCP only)
+ # Note: MCP servers are connected via URL (http://, https://, mcp://)
+ # Command/args are not supported in public API
"MCP_SERVER_URL": ("mcp_server_url", str),
- "MCP_SERVER_TRANSPORT": ("mcp_server_transport", str),
- "MCP_SERVER_COMMAND": ("mcp_server_command", str),
- "MCP_SERVER_ARGS": ("mcp_server_args", str),
"MCP_SERVER_TIMEOUT": ("mcp_server_timeout", float),
}
@@ -130,10 +129,6 @@ class IngestConfig:
except ValueError:
self._configs[config_key] = value
- # Parse MCP_SERVER_ARGS if it's a comma-separated string
- if "mcp_server_args" in self._configs and isinstance(self._configs["mcp_server_args"], str):
- self._configs["mcp_server_args"] = [arg.strip() for arg in self._configs["mcp_server_args"].split(",") if arg.strip()]
-
# Also check for MCP_ prefixed variables
mcp_prefix = "MCP_"
for key, value in os.environ.items():
diff --git a/semantica/ingest/ingest_usage.md b/semantica/ingest/ingest_usage.md
index 7772de7c..9ef5ce19 100644
--- a/semantica/ingest/ingest_usage.md
+++ b/semantica/ingest/ingest_usage.md
@@ -12,11 +12,12 @@ This guide demonstrates how to use the ingest module for ingesting data from var
6. [Repository Ingestion](#repository-ingestion)
7. [Email Ingestion](#email-ingestion)
8. [Database Ingestion](#database-ingestion)
-9. [Unified Ingestion](#unified-ingestion)
-10. [Using Methods](#using-methods)
-11. [Using Registry](#using-registry)
-12. [Configuration](#configuration)
-13. [Advanced Examples](#advanced-examples)
+9. [MCP Server Ingestion](#mcp-server-ingestion)
+10. [Unified Ingestion](#unified-ingestion)
+11. [Using Methods](#using-methods)
+12. [Using Registry](#using-registry)
+13. [Configuration](#configuration)
+14. [Advanced Examples](#advanced-examples)
## Basic Usage
@@ -591,9 +592,317 @@ engine = connector.connect("postgresql://user:password@localhost/dbname")
# Get schema information
schema = connector.get_schema(engine)
-print(f"Tables: {schema['tables']}")
-for table_name, columns in schema['columns'].items():
- print(f" {table_name}: {[col['name'] for col in columns]}")
+ print(f"Tables: {schema['tables']}")
+ for table_name, columns in schema['columns'].items():
+ print(f" {table_name}: {[col['name'] for col in columns]}")
+```
+
+## MCP Server Ingestion
+
+**IMPORTANT**: This implementation supports **ONLY Python-based MCP servers and FastMCP servers**. Users can bring their own Python or FastMCP MCP servers via URL connections. JavaScript, TypeScript, C#, Java, and other language implementations are **NOT supported**.
+
+The MCP (Model Context Protocol) server ingestion allows you to connect to Python/FastMCP MCP servers via URL and ingest data from their resources and tools. The implementation is generic and works with Python/FastMCP MCP servers across diverse domains.
+
+### Basic MCP Server Connection
+
+```python
+from semantica.ingest import ingest_mcp, MCPIngestor
+
+# Using convenience function - connect via URL and ingest resources
+data = ingest_mcp(
+ "http://localhost:8000/mcp", # MCP server URL
+ method="resources"
+)
+
+print(f"Ingested {len(data)} resources")
+```
+
+### Using MCPIngestor Class
+
+```python
+from semantica.ingest import MCPIngestor
+
+# Create ingestor
+ingestor = MCPIngestor()
+
+# Connect to MCP server via URL (primary method)
+ingestor.connect(
+ "db_server",
+ url="http://localhost:8000/mcp" # MCP server URL
+)
+
+# List available resources
+resources = ingestor.list_available_resources("db_server")
+print(f"Available resources: {[r.uri for r in resources]}")
+
+# List available tools
+tools = ingestor.list_available_tools("db_server")
+print(f"Available tools: {[t.name for t in tools]}")
+```
+
+### Resource-Based Ingestion
+
+```python
+from semantica.ingest import ingest_mcp, MCPIngestor
+
+# Ingest specific resources
+ingestor = MCPIngestor()
+ingestor.connect("file_server", url="http://localhost:8000/mcp")
+
+# Ingest specific resource URIs
+data = ingestor.ingest_resources(
+ "file_server",
+ resource_uris=["resource://file/documents", "resource://file/reports"]
+)
+
+for item in data:
+ print(f"Resource: {item.resource_uri}")
+ print(f"Content type: {item.data_type}")
+ print(f"Metadata: {item.metadata}")
+```
+
+### Ingest All Resources
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+ingestor.connect("db_server", url="http://localhost:8000/mcp")
+
+# Ingest all available resources
+all_data = ingestor.ingest_all_resources("db_server")
+
+print(f"Ingested {len(all_data)} resources")
+```
+
+### Tool-Based Ingestion
+
+```python
+from semantica.ingest import ingest_mcp, MCPIngestor
+
+# Using convenience function
+result = ingest_mcp(
+ "db_server", # Server name (must be already connected)
+ method="tools",
+ tool_name="query_database",
+ tool_arguments={"query": "SELECT * FROM users LIMIT 10"}
+)
+
+# Using class directly
+ingestor = MCPIngestor()
+ingestor.connect("db_server", url="http://localhost:8000/mcp")
+
+result = ingestor.ingest_tool_output(
+ "db_server",
+ tool_name="query_database",
+ arguments={"query": "SELECT * FROM users LIMIT 10"}
+)
+
+print(f"Tool result: {result.content}")
+```
+
+### Multiple MCP Servers
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+
+# Connect multiple MCP servers via URLs
+ingestor.connect(
+ "db_server",
+ url="http://localhost:8001/mcp"
+)
+
+ingestor.connect(
+ "file_server",
+ url="https://api.example.com/mcp",
+ headers={"Authorization": "Bearer token"}
+)
+
+ingestor.connect(
+ "api_server",
+ url="http://localhost:8002/mcp"
+)
+
+# Ingest from different servers
+db_data = ingestor.ingest_resources("db_server", resource_uris=["resource://database/tables"])
+file_data = ingestor.ingest_all_resources("file_server")
+api_result = ingestor.ingest_tool_output("api_server", tool_name="fetch_data", arguments={})
+
+# List all connected servers
+servers = ingestor.get_connected_servers()
+print(f"Connected servers: {servers}")
+```
+
+### HTTPS Transport with Authentication
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+
+# Connect via HTTPS with authentication (transport auto-detected from URL)
+ingestor.connect(
+ "remote_server",
+ url="https://api.example.com/mcp",
+ headers={
+ "Authorization": "Bearer your_token",
+ "Content-Type": "application/json"
+ }
+)
+
+# Ingest resources
+data = ingestor.ingest_resources("remote_server")
+```
+
+### Resource Filtering
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+ingestor.connect("file_server", url="http://localhost:8000/mcp")
+
+# Filter resources by custom function
+def filter_pdf_resources(resource):
+ return resource.uri.endswith(".pdf") or "pdf" in resource.mime_type
+
+pdf_resources = ingestor.ingest_resources(
+ "file_server",
+ filter_func=filter_pdf_resources
+)
+
+print(f"Found {len(pdf_resources)} PDF resources")
+```
+
+### Reading Individual Resources
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+ingestor.connect("db_server", url="http://localhost:8000/mcp")
+
+# Read a specific resource
+resource_data = ingestor.read_resource("db_server", "resource://database/users")
+
+print(f"Resource data: {resource_data}")
+```
+
+### Calling Individual Tools
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+ingestor.connect("api_server", url="http://localhost:8000/mcp")
+
+# Call a tool directly
+result = ingestor.call_tool(
+ "api_server",
+ tool_name="get_user_data",
+ arguments={"user_id": 123}
+)
+
+print(f"Tool result: {result}")
+```
+
+### Disconnecting Servers
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+ingestor.connect("server1", url="http://localhost:8001/mcp")
+ingestor.connect("server2", url="http://localhost:8002/mcp")
+
+# Disconnect specific server
+ingestor.disconnect("server1")
+
+# Disconnect all servers
+ingestor.disconnect()
+```
+
+### Supported MCP Server Domains
+
+**IMPORTANT**: Only Python MCP servers and FastMCP servers are supported. Users can bring their own Python/FastMCP MCP servers via URL.
+
+The implementation works generically with Python and FastMCP MCP servers, including:
+
+- **Database Connectors**: SQLite, PostgreSQL, MySQL, Firebase, Google Drive
+- **File Systems**: Local filesystem, cloud storage (S3, GCS, Azure)
+- **Code Execution**: Pydantic AI MCP, MCP-Run-Python, SonarQube, VSCode
+- **Communication**: Telegram, Microsoft Teams, Mac Messages, ntfy
+- **Calendar & Tasks**: Google Calendar, Google Tasks
+- **CRM**: HubSpot
+- **Financial Data**: Alphavantage
+- **News & Media**: Google News
+- **Authentication**: Keycloak
+- **System Admin**: iTerm
+- **Document Processing**: PDF, Markdown, HTML parsers
+- **Custom Domains**: Any user-created Python MCP server
+
+### Configuration via Environment Variables
+
+```bash
+# MCP server configuration (URL-based)
+export MCP_SERVER_URL="http://localhost:8000/mcp"
+export MCP_SERVER_TIMEOUT=30.0
+```
+
+### Example: Database MCP Server
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+
+# Connect to database MCP server via URL
+ingestor.connect(
+ "postgres_mcp",
+ url="http://localhost:8000/mcp"
+)
+
+# List available resources (tables, views, etc.)
+resources = ingestor.list_available_resources("postgres_mcp")
+print(f"Database resources: {[r.uri for r in resources]}")
+
+# Ingest table data via resource
+table_data = ingestor.ingest_resources(
+ "postgres_mcp",
+ resource_uris=["resource://database/users"]
+)
+
+# Or use a tool to query
+query_result = ingestor.ingest_tool_output(
+ "postgres_mcp",
+ tool_name="execute_query",
+ arguments={"sql": "SELECT * FROM users WHERE age > 18"}
+)
+```
+
+### Example: File System MCP Server
+
+```python
+from semantica.ingest import MCPIngestor
+
+ingestor = MCPIngestor()
+
+# Connect to filesystem MCP server via URL
+ingestor.connect(
+ "fs_mcp",
+ url="http://localhost:8000/mcp"
+)
+
+# Ingest all file resources
+files = ingestor.ingest_all_resources("fs_mcp")
+
+# Filter for specific file types
+pdf_files = ingestor.ingest_resources(
+ "fs_mcp",
+ filter_func=lambda r: r.uri.endswith(".pdf")
+)
```
## Unified Ingestion
@@ -608,6 +917,7 @@ result = ingest("document.pdf") # Auto-detects file
result = ingest("https://example.com") # Auto-detects web
result = ingest("https://example.com/feed.xml") # Auto-detects feed
result = ingest("postgresql://user:pass@localhost/db") # Auto-detects database
+result = ingest("http://localhost:8000/mcp", source_type="mcp") # MCP server ingestion via URL
```
### Explicit Source Type
@@ -649,7 +959,8 @@ from semantica.ingest.methods import (
ingest_stream,
ingest_repository,
ingest_email,
- ingest_database
+ ingest_database,
+ ingest_mcp
)
# File ingestion
@@ -672,6 +983,9 @@ emails = ingest_email({"host": "imap.example.com", "username": "user", "password
# Database ingestion
data = ingest_database("postgresql://user:pass@localhost/db", table="users")
+
+# MCP server ingestion via URL
+data = ingest_mcp("http://localhost:8000/mcp", method="resources")
```
## Using Registry
@@ -733,6 +1047,10 @@ export INGEST_RATE_LIMIT_DELAY=1.0
export INGEST_RESPECT_ROBOTS="true"
export INGEST_BATCH_SIZE=100
export INGEST_TIMEOUT=30.0
+
+# MCP server configuration (URL-based, Python/FastMCP only)
+export MCP_SERVER_URL="http://localhost:8000/mcp"
+export MCP_SERVER_TIMEOUT=30.0
```
### Programmatic Configuration
@@ -778,6 +1096,9 @@ ingest_methods:
timeout: 30.0
stream:
batch_size: 1000
+ mcp:
+ timeout: 30.0
+ # URL is provided when connecting, not in config file
```
```python
@@ -897,6 +1218,7 @@ for source_type, source_list in sources.items():
- Repositories: Git repositories
- Emails: IMAP, POP3 email servers
- Databases: SQL databases
+ - MCP Servers: Any Python-based MCP server (databases, file systems, APIs, etc.)
2. **Rate Limiting**: Always use rate limiting for web ingestion
```python
@@ -970,6 +1292,15 @@ for source_type, source_list in sources.items():
# Reuse engine for multiple queries
```
+6. **MCP Server Connection Reuse**: Reuse MCP server connections for multiple operations
+ ```python
+ ingestor = MCPIngestor()
+ ingestor.connect("server1", transport="stdio", command="python", args=["-m", "mcp_server"])
+ # Reuse connection for multiple operations
+ data1 = ingestor.ingest_resources("server1")
+ data2 = ingestor.ingest_tool_output("server1", tool_name="get_data", arguments={})
+ ```
+
5. **Memory Management**: Process large datasets in batches
```python
# Process in batches to avoid memory issues
diff --git a/semantica/ingest/mcp_client.py b/semantica/ingest/mcp_client.py
index 8d7bf8d7..0909cee1 100644
--- a/semantica/ingest/mcp_client.py
+++ b/semantica/ingest/mcp_client.py
@@ -2,21 +2,26 @@
MCP Client Module
This module provides a generic MCP (Model Context Protocol) client implementation
-for communicating with ANY Python-based MCP server across diverse domains.
+for communicating with Python-based MCP servers and FastMCP servers via URL connections.
+
+**IMPORTANT**: This implementation supports ONLY Python MCP servers and FastMCP servers.
+JavaScript, TypeScript, C#, Java, and other language implementations are NOT supported.
Key Features:
- - Generic JSON-RPC communication with any MCP server
- - Support for stdio, HTTP, and SSE transports
+ - URL-based connection (primary interface)
+ - Generic JSON-RPC communication with Python/FastMCP servers
+ - Support for HTTP, HTTPS, and SSE transports (auto-detected from URL)
- Dynamic discovery of server capabilities
- Authentication support (API keys, OAuth, custom headers)
- Error handling and connection management
Main Classes:
- - MCPClient: Generic MCP client for any Python MCP server
+ - MCPClient: Generic MCP client for Python/FastMCP MCP servers
Example Usage:
>>> from semantica.ingest import MCPClient
- >>> client = MCPClient(transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> # Connect via URL (primary method)
+ >>> client = MCPClient(url="http://localhost:8000/mcp")
>>> client.connect()
>>> resources = client.list_resources()
>>> tools = client.list_tools()
@@ -61,78 +66,115 @@ class MCPTool:
class MCPClient:
"""
- Generic MCP client for communicating with any Python MCP server.
+ Generic MCP client for communicating with Python MCP servers and FastMCP servers.
+
+ **IMPORTANT**: This client supports ONLY Python-based MCP servers and FastMCP servers.
+ JavaScript, TypeScript, C#, Java, and other language implementations are NOT supported.
This class provides a domain-agnostic implementation that works with
- any Python-based MCP server following the MCP protocol specification.
- It supports multiple transport methods and dynamically discovers server
+ any Python or FastMCP server following the MCP protocol specification.
+ It supports URL-based connections and dynamically discovers server
capabilities without requiring domain-specific code.
- Supported Transports:
- - stdio: Standard input/output (for local MCP servers)
- - http: HTTP/HTTPS transport
- - sse: Server-Sent Events transport
+ Supported URL Schemes:
+ - http://, https://: HTTP/HTTPS transport (auto-detected)
+ - mcp://: MCP protocol URL (auto-detected as HTTP)
+ - sse://: Server-Sent Events transport (auto-detected)
Example Usage:
- >>> client = MCPClient(transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> # Connect via URL (primary method)
+ >>> client = MCPClient(url="http://localhost:8000/mcp")
>>> client.connect()
>>> resources = client.list_resources()
>>> data = client.read_resource("resource://example")
+
+ >>> # With authentication
+ >>> client = MCPClient(
+ ... url="https://api.example.com/mcp",
+ ... headers={"Authorization": "Bearer token"}
+ ... )
"""
def __init__(
self,
- transport: str = "stdio",
- command: Optional[str] = None,
- args: Optional[List[str]] = None,
url: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
+ transport: Optional[str] = None,
**config
):
"""
Initialize MCP client.
+ **IMPORTANT**: Supports only Python MCP servers and FastMCP servers.
+
Args:
- transport: Transport method ("stdio", "http", "sse")
- command: Command to run for stdio transport (e.g., "python")
- args: Arguments for command (e.g., ["-m", "mcp_server"])
- url: URL for HTTP/SSE transport
- headers: Custom headers for HTTP/SSE transport
- **config: Additional configuration options
+ url: MCP server URL (primary parameter)
+ - http://localhost:8000/mcp
+ - https://api.example.com/mcp
+ - mcp://server-name
+ headers: Custom headers for authentication (e.g., {"Authorization": "Bearer token"})
+ transport: Optional transport override (auto-detected from URL if not provided)
+ - "http": HTTP/HTTPS transport
+ - "sse": Server-Sent Events transport
+ **config: Additional configuration options (timeout, etc.)
+
+ Raises:
+ ValidationError: If URL is invalid or transport cannot be determined
"""
self.logger = get_logger("mcp_client")
- self.transport = transport.lower()
- self.command = command
- self.args = args or []
self.url = url
self.headers = headers or {}
self.config = config
- # Connection state
- self._process: Optional[subprocess.Popen] = None
- self._connected: bool = False
- self._initialized: bool = False
- self._server_info: Optional[Dict[str, Any]] = None
- self._request_id: int = 0
+ # Auto-detect transport from URL if not provided
+ if url:
+ parsed_url = url.lower()
+ if parsed_url.startswith(("http://", "https://", "mcp://")):
+ self.transport = "http"
+ elif parsed_url.startswith("sse://"):
+ self.transport = "sse"
+ else:
+ # Default to HTTP if scheme not recognized
+ self.transport = "http"
+ self.logger.warning(f"Unknown URL scheme, defaulting to HTTP: {url}")
+ elif transport:
+ self.transport = transport.lower()
+ else:
+ raise ValidationError(
+ "Either 'url' or 'transport' parameter is required. "
+ "URL-based connection is the primary method."
+ )
# Validate transport
- if self.transport not in ("stdio", "http", "sse"):
+ if self.transport not in ("http", "sse"):
raise ValidationError(
f"Unsupported transport: {self.transport}. "
- f"Supported: stdio, http, sse"
+ f"Supported: http, sse. "
+ f"Note: stdio transport is not supported in public API."
)
- # Validate transport-specific requirements
- if self.transport == "stdio" and not self.command:
- raise ValidationError("stdio transport requires 'command' parameter")
+ # Validate URL for HTTP/SSE transports
if self.transport in ("http", "sse") and not self.url:
raise ValidationError(f"{self.transport} transport requires 'url' parameter")
- self.logger.debug(f"MCP client initialized: transport={transport}")
+ # Internal stdio support (not exposed in public API)
+ self._command: Optional[str] = None
+ self._args: Optional[List[str]] = None
+
+ # Connection state
+ self._process: Optional[subprocess.Popen] = None
+ self._connected: bool = False
+ self._initialized: bool = False
+ self._server_info: Optional[Dict[str, Any]] = None
+ self._request_id: int = 0
+
+ self.logger.debug(f"MCP client initialized: url={url}, transport={self.transport}")
def connect(self) -> bool:
"""
- Connect to MCP server.
+ Connect to MCP server via URL.
+
+ **IMPORTANT**: Supports only Python MCP servers and FastMCP servers.
Returns:
bool: True if connection successful
@@ -141,9 +183,7 @@ class MCPClient:
ProcessingError: If connection fails
"""
try:
- if self.transport == "stdio":
- return self._connect_stdio()
- elif self.transport == "http":
+ if self.transport == "http":
return self._connect_http()
elif self.transport == "sse":
return self._connect_sse()
diff --git a/semantica/ingest/mcp_ingestor.py b/semantica/ingest/mcp_ingestor.py
index 0f4a142a..41fcbaa3 100644
--- a/semantica/ingest/mcp_ingestor.py
+++ b/semantica/ingest/mcp_ingestor.py
@@ -2,11 +2,15 @@
MCP Ingestion Module
This module provides comprehensive MCP (Model Context Protocol) server ingestion
-capabilities, allowing users to ingest data from any Python-based MCP server
-across diverse domains.
+capabilities, allowing users to ingest data from Python MCP servers and FastMCP servers
+via URL connections.
+
+**IMPORTANT**: This implementation supports ONLY Python-based MCP servers and FastMCP servers.
+JavaScript, TypeScript, C#, Java, and other language implementations are NOT supported.
Key Features:
- - Generic implementation that works with ANY Python MCP server
+ - URL-based connection (primary interface)
+ - Generic implementation that works with Python/FastMCP MCP servers
- Dynamic discovery of resources and tools
- Resource-based and tool-based ingestion
- Multiple MCP server support
@@ -19,7 +23,8 @@ Main Classes:
Example Usage:
>>> from semantica.ingest import MCPIngestor
>>> ingestor = MCPIngestor()
- >>> ingestor.connect("server1", transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> # Connect via URL (primary method)
+ >>> ingestor.connect("server1", url="http://localhost:8000/mcp")
>>> resources = ingestor.list_available_resources("server1")
>>> data = ingestor.ingest_resources("server1", resource_uris=["resource://example"])
>>> result = ingestor.ingest_tool_output("server1", tool_name="get_data", arguments={})
@@ -54,15 +59,20 @@ class MCPData:
class MCPIngestor:
"""
- Generic MCP server ingestion handler.
+ Generic MCP server ingestion handler for Python and FastMCP servers.
+
+ **IMPORTANT**: This class supports ONLY Python-based MCP servers and FastMCP servers.
+ Users can bring their own Python or FastMCP MCP servers via URL connections.
+ JavaScript, TypeScript, and other language implementations are NOT supported.
This class provides comprehensive MCP server ingestion capabilities,
- working generically with ANY Python-based MCP server. It dynamically
+ working generically with Python and FastMCP servers. It dynamically
discovers resources and tools from connected servers without requiring
domain-specific code.
Features:
- - Generic implementation for any Python MCP server
+ - URL-based connection (primary interface)
+ - Generic implementation for Python/FastMCP MCP servers
- Multiple MCP server support
- Dynamic resource and tool discovery
- Resource-based and tool-based ingestion
@@ -71,8 +81,9 @@ class MCPIngestor:
Example Usage:
>>> ingestor = MCPIngestor()
- >>> ingestor.connect("db_server", transport="stdio", command="python", args=["-m", "mcp_db"])
- >>> ingestor.connect("file_server", transport="http", url="http://localhost:8000/mcp")
+ >>> # Connect via URL (primary method)
+ >>> ingestor.connect("db_server", url="http://localhost:8000/mcp")
+ >>> ingestor.connect("file_server", url="https://api.example.com/mcp", headers={"Authorization": "Bearer token"})
>>> resources = ingestor.list_available_resources("db_server")
>>> data = ingestor.ingest_resources("db_server", resource_uris=["resource://database/tables"])
"""
@@ -105,30 +116,36 @@ class MCPIngestor:
def connect(
self,
server_name: str,
- transport: str = "stdio",
- command: Optional[str] = None,
- args: Optional[List[str]] = None,
url: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
**config
) -> bool:
"""
- Connect to an MCP server.
+ Connect to an MCP server via URL.
+
+ **IMPORTANT**: Supports only Python MCP servers and FastMCP servers.
+ Users can bring their own Python/FastMCP MCP servers via URL.
Args:
server_name: Unique name for this MCP server connection
- transport: Transport method ("stdio", "http", "sse")
- command: Command for stdio transport (e.g., "python")
- args: Arguments for command (e.g., ["-m", "mcp_server"])
- url: URL for HTTP/SSE transport
- headers: Custom headers for HTTP/SSE transport
- **config: Additional configuration options
+ url: MCP server URL (primary parameter)
+ - http://localhost:8000/mcp
+ - https://api.example.com/mcp
+ - mcp://server-name
+ headers: Custom headers for authentication (e.g., {"Authorization": "Bearer token"})
+ **config: Additional configuration options (timeout, etc.)
Returns:
bool: True if connection successful
Raises:
ProcessingError: If connection fails
+ ValidationError: If URL is not provided or invalid
+
+ Example:
+ >>> ingestor = MCPIngestor()
+ >>> ingestor.connect("db_server", url="http://localhost:8000/mcp")
+ >>> ingestor.connect("api_server", url="https://api.example.com/mcp", headers={"Authorization": "Bearer token"})
"""
try:
# Check if already connected
@@ -136,11 +153,15 @@ class MCPIngestor:
self.logger.warning(f"Server {server_name} already connected, reconnecting...")
self.disconnect(server_name)
- # Create and connect client
+ # Validate URL
+ if not url:
+ raise ValidationError(
+ f"URL is required for MCP server connection. "
+ f"Provide MCP server URL: http://, https://, or mcp://"
+ )
+
+ # Create and connect client (transport auto-detected from URL)
client = MCPClient(
- transport=transport,
- command=command,
- args=args,
url=url,
headers=headers,
**config
@@ -148,7 +169,7 @@ class MCPIngestor:
if client.connect():
self._clients[server_name] = client
- self.logger.info(f"Connected to MCP server: {server_name}")
+ self.logger.info(f"Connected to MCP server: {server_name} at {url}")
return True
else:
raise ProcessingError(f"Failed to connect to MCP server: {server_name}")
diff --git a/semantica/ingest/methods.py b/semantica/ingest/methods.py
index d6f7d97b..9984ae8f 100644
--- a/semantica/ingest/methods.py
+++ b/semantica/ingest/methods.py
@@ -610,22 +610,23 @@ def ingest_mcp(
"""
Ingest data from MCP server (convenience function).
+ **IMPORTANT**: Supports only Python MCP servers and FastMCP servers.
+ Users can bring their own Python/FastMCP MCP servers via URL.
+
This is a user-friendly wrapper that ingests data from MCP servers using
- the specified method. Works with any Python-based MCP server.
+ the specified method. Works with Python and FastMCP MCP servers.
Args:
- source: MCP server configuration (dict) or server name (str) if already connected
+ source: MCP server URL (str) or configuration dict with "url" key, or server name (str) if already connected
+ - URL string: "http://localhost:8000/mcp"
+ - Dict: {"url": "http://localhost:8000/mcp", "headers": {...}}
method: Ingestion method (default: "resources")
- "resources": Ingest from MCP server resources
- "tools": Ingest by calling MCP tools
- "all": Ingest all resources
server_name: Name for MCP server connection (auto-generated if not provided)
**kwargs: Additional options:
- - transport: Transport method ("stdio", "http", "sse")
- - command: Command for stdio transport
- - args: Arguments for command
- - url: URL for HTTP/SSE transport
- - headers: Custom headers
+ - headers: Custom headers for authentication
- resource_uris: List of resource URIs to ingest
- tool_name: Tool name to call
- tool_arguments: Tool arguments
@@ -635,10 +636,12 @@ def ingest_mcp(
Examples:
>>> from semantica.ingest.methods import ingest_mcp
- >>> # Connect and ingest resources
+ >>> # Connect via URL and ingest resources
+ >>> data = ingest_mcp("http://localhost:8000/mcp", method="resources")
+ >>> # Connect via URL dict and ingest all resources
>>> data = ingest_mcp(
- ... {"transport": "stdio", "command": "python", "args": ["-m", "mcp_server"]},
- ... method="resources"
+ ... {"url": "https://api.example.com/mcp", "headers": {"Authorization": "Bearer token"}},
+ ... method="all"
... )
>>> # Ingest from already connected server
>>> data = ingest_mcp("server1", method="resources", resource_uris=["resource://example"])
@@ -660,27 +663,46 @@ def ingest_mcp(
ingestor = MCPIngestor(**config)
- # If source is a string, assume it's a server name (already connected)
+ # If source is a string, check if it's a URL or server name
if isinstance(source, str):
- server_name = source
- if not ingestor.is_connected(server_name):
- raise ProcessingError(f"MCP server '{server_name}' not connected. Provide connection config.")
+ # Check if it looks like a URL
+ if source.startswith(("http://", "https://", "mcp://", "sse://")):
+ # It's a URL, connect to it
+ if not server_name:
+ server_name = f"mcp_server_{len(ingestor.get_connected_servers())}"
+ ingestor.connect(server_name=server_name, url=source, headers=kwargs.get("headers"))
+ else:
+ # Assume it's a server name (already connected)
+ server_name = source
+ if not ingestor.is_connected(server_name):
+ raise ProcessingError(
+ f"MCP server '{server_name}' not connected. "
+ f"Provide MCP server URL: http://, https://, or mcp://"
+ )
elif isinstance(source, dict):
# Connect to MCP server
if not server_name:
server_name = source.get("server_name", f"mcp_server_{len(ingestor.get_connected_servers())}")
+ # Extract URL (required)
+ url = source.get("url")
+ if not url:
+ raise ProcessingError(
+ "MCP server URL is required. Provide 'url' in configuration dict: "
+ "http://, https://, or mcp://"
+ )
+
ingestor.connect(
server_name=server_name,
- transport=source.get("transport", "stdio"),
- command=source.get("command"),
- args=source.get("args"),
- url=source.get("url"),
+ url=url,
headers=source.get("headers"),
- **{k: v for k, v in source.items() if k not in ("transport", "command", "args", "url", "headers", "server_name")}
+ **{k: v for k, v in source.items() if k not in ("url", "headers", "server_name")}
)
else:
- raise ProcessingError("Source must be server name (str) or configuration (dict)")
+ raise ProcessingError(
+ "Source must be MCP server URL (str), configuration dict with 'url' key, "
+ "or server name (str) if already connected"
+ )
# Ingest based on method
if method == "resources" or method == "all":