Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Add generic MCP server support for ingestion and parsing

KaifAhmad1d86d5d83e600
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.py
index 9bc4a515..85d3c8d5 100644
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@ -129,6 +129,8 @@ from .stream_ingestor import (
from .repo_ingestor import RepoIngestor, CodeFile, CommitInfo, CodeExtractor, GitAnalyzer
from .email_ingestor import EmailIngestor, EmailData, AttachmentProcessor, EmailParser as EmailIngestorParser
from .db_ingestor import DBIngestor, TableData, DatabaseConnector, DataExporter
+from .mcp_ingestor import MCPIngestor, MCPData
+from .mcp_client import MCPClient, MCPResource, MCPTool
from .registry import MethodRegistry, method_registry
from .methods import (
ingest,
@@ -139,6 +141,7 @@ from .methods import (
ingest_repository,
ingest_email,
ingest_database,
+ ingest_mcp,
get_ingest_method,
list_available_methods,
)
@@ -188,6 +191,12 @@ __all__ = [
"TableData",
"DatabaseConnector",
"DataExporter",
+ # MCP ingestion
+ "MCPIngestor",
+ "MCPData",
+ "MCPClient",
+ "MCPResource",
+ "MCPTool",
# Registry and Methods
"MethodRegistry",
"method_registry",
@@ -199,6 +208,7 @@ __all__ = [
"ingest_repository",
"ingest_email",
"ingest_database",
+ "ingest_mcp",
"get_ingest_method",
"list_available_methods",
# Configuration
diff --git a/semantica/ingest/config.py b/semantica/ingest/config.py
index 17196bc0..6cc0c4b5 100644
--- a/semantica/ingest/config.py
+++ b/semantica/ingest/config.py
@@ -95,6 +95,12 @@ class IngestConfig:
"INGEST_RESPECT_ROBOTS": ("respect_robots", bool),
"INGEST_BATCH_SIZE": ("batch_size", int),
"INGEST_TIMEOUT": ("timeout", float),
+ # MCP server configuration
+ "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),
}
for env_key, (config_key, type_func) in env_mappings.items():
@@ -123,6 +129,26 @@ class IngestConfig:
self._configs[config_key] = float(value)
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():
+ if key.startswith(mcp_prefix) and key not in env_mappings:
+ config_key = key[len(mcp_prefix):].lower()
+ # Try to convert to appropriate type
+ if value.lower() in ('true', 'false'):
+ self._configs[f"mcp_{config_key}"] = value.lower() == 'true'
+ elif value.isdigit():
+ self._configs[f"mcp_{config_key}"] = int(value)
+ else:
+ try:
+ self._configs[f"mcp_{config_key}"] = float(value)
+ except ValueError:
+ self._configs[f"mcp_{config_key}"] = value
def set(self, key: str, value: Any):
"""Set configuration value programmatically."""
diff --git a/semantica/ingest/mcp_client.py b/semantica/ingest/mcp_client.py
new file mode 100644
index 00000000..8d7bf8d7
--- /dev/null
+++ b/semantica/ingest/mcp_client.py
@@ -0,0 +1,496 @@
+"""
+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.
+
+Key Features:
+ - Generic JSON-RPC communication with any MCP server
+ - Support for stdio, HTTP, and SSE transports
+ - 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
+
+Example Usage:
+ >>> from semantica.ingest import MCPClient
+ >>> client = MCPClient(transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> client.connect()
+ >>> resources = client.list_resources()
+ >>> tools = client.list_tools()
+ >>> data = client.read_resource("resource://example")
+ >>> result = client.call_tool("tool_name", {"param": "value"})
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import json
+import subprocess
+import sys
+from typing import Any, Dict, List, Optional, Union
+from dataclasses import dataclass, field
+from datetime import datetime
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class MCPResource:
+ """MCP resource representation."""
+
+ uri: str
+ name: str
+ description: Optional[str] = None
+ mime_type: Optional[str] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class MCPTool:
+ """MCP tool representation."""
+
+ name: str
+ description: Optional[str] = None
+ input_schema: Dict[str, Any] = field(default_factory=dict)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class MCPClient:
+ """
+ Generic MCP client for communicating with any Python MCP server.
+
+ 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
+ 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
+
+ Example Usage:
+ >>> client = MCPClient(transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> client.connect()
+ >>> resources = client.list_resources()
+ >>> data = client.read_resource("resource://example")
+ """
+
+ 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,
+ **config
+ ):
+ """
+ Initialize MCP client.
+
+ 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
+ """
+ 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
+
+ # Validate transport
+ if self.transport not in ("stdio", "http", "sse"):
+ raise ValidationError(
+ f"Unsupported transport: {self.transport}. "
+ f"Supported: stdio, http, sse"
+ )
+
+ # Validate transport-specific requirements
+ if self.transport == "stdio" and not self.command:
+ raise ValidationError("stdio transport requires 'command' parameter")
+ 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}")
+
+ def connect(self) -> bool:
+ """
+ Connect to MCP server.
+
+ Returns:
+ bool: True if connection successful
+
+ Raises:
+ ProcessingError: If connection fails
+ """
+ try:
+ if self.transport == "stdio":
+ return self._connect_stdio()
+ elif self.transport == "http":
+ return self._connect_http()
+ elif self.transport == "sse":
+ return self._connect_sse()
+ else:
+ raise ValidationError(f"Unsupported transport: {self.transport}")
+ except Exception as e:
+ self.logger.error(f"Failed to connect to MCP server: {e}")
+ raise ProcessingError(f"Failed to connect to MCP server: {e}") from e
+
+ def _connect_stdio(self) -> bool:
+ """Connect via stdio transport."""
+ try:
+ cmd = [self.command] + self.args
+ self._process = subprocess.Popen(
+ cmd,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=0
+ )
+ self._connected = True
+ self.logger.info("Connected to MCP server via stdio")
+
+ # Initialize protocol
+ return self._initialize()
+ except Exception as e:
+ self.logger.error(f"Failed to connect via stdio: {e}")
+ raise
+
+ def _connect_http(self) -> bool:
+ """Connect via HTTP transport."""
+ try:
+ # HTTP transport will be implemented with requests/httpx
+ # For now, mark as connected and initialize
+ self._connected = True
+ self.logger.info(f"Connected to MCP server via HTTP: {self.url}")
+ return self._initialize()
+ except Exception as e:
+ self.logger.error(f"Failed to connect via HTTP: {e}")
+ raise
+
+ def _connect_sse(self) -> bool:
+ """Connect via SSE transport."""
+ try:
+ # SSE transport will be implemented
+ # For now, mark as connected and initialize
+ self._connected = True
+ self.logger.info(f"Connected to MCP server via SSE: {self.url}")
+ return self._initialize()
+ except Exception as e:
+ self.logger.error(f"Failed to connect via SSE: {e}")
+ raise
+
+ def _initialize(self) -> bool:
+ """Initialize MCP protocol."""
+ try:
+ request = {
+ "jsonrpc": "2.0",
+ "id": self._get_request_id(),
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {
+ "roots": {
+ "listChanged": True
+ }
+ },
+ "clientInfo": {
+ "name": "semantica",
+ "version": "1.0.0"
+ }
+ }
+ }
+
+ response = self._send_request(request)
+
+ if response and "result" in response:
+ self._server_info = response["result"]
+ self._initialized = True
+ self.logger.info("MCP protocol initialized")
+ return True
+ else:
+ error = response.get("error", {}) if response else {}
+ raise ProcessingError(f"Failed to initialize MCP: {error.get('message', 'Unknown error')}")
+ except Exception as e:
+ self.logger.error(f"Failed to initialize MCP protocol: {e}")
+ raise
+
+ def disconnect(self):
+ """Disconnect from MCP server."""
+ if self._process:
+ try:
+ self._process.terminate()
+ self._process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self._process.kill()
+ except Exception as e:
+ self.logger.warning(f"Error disconnecting: {e}")
+ finally:
+ self._process = None
+
+ self._connected = False
+ self._initialized = False
+ self.logger.info("Disconnected from MCP server")
+
+ def _get_request_id(self) -> int:
+ """Get next request ID."""
+ self._request_id += 1
+ return self._request_id
+
+ def _send_request(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """
+ Send JSON-RPC request to MCP server.
+
+ Args:
+ request: JSON-RPC request dictionary
+
+ Returns:
+ Response dictionary or None
+ """
+ if not self._connected:
+ raise ProcessingError("Not connected to MCP server")
+
+ try:
+ if self.transport == "stdio":
+ return self._send_request_stdio(request)
+ elif self.transport == "http":
+ return self._send_request_http(request)
+ elif self.transport == "sse":
+ return self._send_request_sse(request)
+ else:
+ raise ValidationError(f"Unsupported transport: {self.transport}")
+ except Exception as e:
+ self.logger.error(f"Failed to send request: {e}")
+ raise ProcessingError(f"Failed to send request: {e}") from e
+
+ def _send_request_stdio(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Send request via stdio."""
+ if not self._process:
+ raise ProcessingError("Process not running")
+
+ try:
+ # Send request
+ request_json = json.dumps(request) + "\n"
+ self._process.stdin.write(request_json)
+ self._process.stdin.flush()
+
+ # Read response
+ response_line = self._process.stdout.readline()
+ if response_line:
+ return json.loads(response_line.strip())
+ return None
+ except Exception as e:
+ self.logger.error(f"Failed to send stdio request: {e}")
+ raise
+
+ def _send_request_http(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Send request via HTTP."""
+ try:
+ import httpx
+
+ response = httpx.post(
+ self.url,
+ json=request,
+ headers=self.headers,
+ timeout=self.config.get("timeout", 30.0)
+ )
+ response.raise_for_status()
+ return response.json()
+ except ImportError:
+ # Fallback to requests if httpx not available
+ try:
+ import requests
+ response = requests.post(
+ self.url,
+ json=request,
+ headers=self.headers,
+ timeout=self.config.get("timeout", 30.0)
+ )
+ response.raise_for_status()
+ return response.json()
+ except ImportError:
+ raise ProcessingError(
+ "HTTP transport requires 'httpx' or 'requests' package. "
+ "Install with: pip install httpx or pip install requests"
+ )
+ except Exception as e:
+ self.logger.error(f"Failed to send HTTP request: {e}")
+ raise
+
+ def _send_request_sse(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Send request via SSE."""
+ # SSE implementation would go here
+ # For now, raise not implemented
+ raise ProcessingError("SSE transport not yet implemented")
+
+ def list_resources(self) -> List[MCPResource]:
+ """
+ List resources available from MCP server.
+
+ Returns:
+ List of MCPResource objects
+ """
+ if not self._initialized:
+ raise ProcessingError("MCP protocol not initialized")
+
+ try:
+ request = {
+ "jsonrpc": "2.0",
+ "id": self._get_request_id(),
+ "method": "resources/list"
+ }
+
+ response = self._send_request(request)
+
+ if response and "result" in response:
+ resources_data = response["result"].get("resources", [])
+ return [
+ MCPResource(
+ uri=r.get("uri", ""),
+ name=r.get("name", ""),
+ description=r.get("description"),
+ mime_type=r.get("mimeType"),
+ metadata=r.get("metadata", {})
+ )
+ for r in resources_data
+ ]
+ else:
+ error = response.get("error", {}) if response else {}
+ raise ProcessingError(f"Failed to list resources: {error.get('message', 'Unknown error')}")
+ except Exception as e:
+ self.logger.error(f"Failed to list resources: {e}")
+ raise
+
+ def list_tools(self) -> List[MCPTool]:
+ """
+ List tools available from MCP server.
+
+ Returns:
+ List of MCPTool objects
+ """
+ if not self._initialized:
+ raise ProcessingError("MCP protocol not initialized")
+
+ try:
+ request = {
+ "jsonrpc": "2.0",
+ "id": self._get_request_id(),
+ "method": "tools/list"
+ }
+
+ response = self._send_request(request)
+
+ if response and "result" in response:
+ tools_data = response["result"].get("tools", [])
+ return [
+ MCPTool(
+ name=t.get("name", ""),
+ description=t.get("description"),
+ input_schema=t.get("inputSchema", {}),
+ metadata=t.get("metadata", {})
+ )
+ for t in tools_data
+ ]
+ else:
+ error = response.get("error", {}) if response else {}
+ raise ProcessingError(f"Failed to list tools: {error.get('message', 'Unknown error')}")
+ except Exception as e:
+ self.logger.error(f"Failed to list tools: {e}")
+ raise
+
+ def read_resource(self, uri: str) -> Dict[str, Any]:
+ """
+ Read a resource from MCP server.
+
+ Args:
+ uri: Resource URI
+
+ Returns:
+ Resource data dictionary
+ """
+ if not self._initialized:
+ raise ProcessingError("MCP protocol not initialized")
+
+ try:
+ request = {
+ "jsonrpc": "2.0",
+ "id": self._get_request_id(),
+ "method": "resources/read",
+ "params": {
+ "uri": uri
+ }
+ }
+
+ response = self._send_request(request)
+
+ if response and "result" in response:
+ return response["result"]
+ else:
+ error = response.get("error", {}) if response else {}
+ raise ProcessingError(f"Failed to read resource: {error.get('message', 'Unknown error')}")
+ except Exception as e:
+ self.logger.error(f"Failed to read resource {uri}: {e}")
+ raise
+
+ def call_tool(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ """
+ Call a tool on MCP server.
+
+ Args:
+ name: Tool name
+ arguments: Tool arguments
+
+ Returns:
+ Tool result dictionary
+ """
+ if not self._initialized:
+ raise ProcessingError("MCP protocol not initialized")
+
+ try:
+ request = {
+ "jsonrpc": "2.0",
+ "id": self._get_request_id(),
+ "method": "tools/call",
+ "params": {
+ "name": name,
+ "arguments": arguments or {}
+ }
+ }
+
+ response = self._send_request(request)
+
+ if response and "result" in response:
+ return response["result"]
+ else:
+ error = response.get("error", {}) if response else {}
+ raise ProcessingError(f"Failed to call tool {name}: {error.get('message', 'Unknown error')}")
+ except Exception as e:
+ self.logger.error(f"Failed to call tool {name}: {e}")
+ raise
+
+ def is_connected(self) -> bool:
+ """Check if connected to MCP server."""
+ return self._connected and self._initialized
+
+ def get_server_info(self) -> Optional[Dict[str, Any]]:
+ """Get server information from initialization."""
+ return self._server_info
+
diff --git a/semantica/ingest/mcp_ingestor.py b/semantica/ingest/mcp_ingestor.py
new file mode 100644
index 00000000..0f4a142a
--- /dev/null
+++ b/semantica/ingest/mcp_ingestor.py
@@ -0,0 +1,434 @@
+"""
+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.
+
+Key Features:
+ - Generic implementation that works with ANY Python MCP server
+ - Dynamic discovery of resources and tools
+ - Resource-based and tool-based ingestion
+ - Multiple MCP server support
+ - Connection management integrated into ingestor
+ - Progress tracking
+
+Main Classes:
+ - MCPIngestor: Main MCP ingestion class
+
+Example Usage:
+ >>> from semantica.ingest import MCPIngestor
+ >>> ingestor = MCPIngestor()
+ >>> ingestor.connect("server1", transport="stdio", command="python", args=["-m", "mcp_server"])
+ >>> 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={})
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
+from .mcp_client import MCPClient, MCPResource, MCPTool
+
+
+@dataclass
+class MCPData:
+ """MCP data representation."""
+
+ source: str
+ server_name: str
+ data_type: str # "resource" or "tool_output"
+ content: Any
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ ingested_at: datetime = field(default_factory=datetime.now)
+ resource_uri: Optional[str] = None
+ tool_name: Optional[str] = None
+
+
+class MCPIngestor:
+ """
+ Generic MCP server ingestion handler.
+
+ This class provides comprehensive MCP server ingestion capabilities,
+ working generically with ANY Python-based MCP server. It dynamically
+ discovers resources and tools from connected servers without requiring
+ domain-specific code.
+
+ Features:
+ - Generic implementation for any Python MCP server
+ - Multiple MCP server support
+ - Dynamic resource and tool discovery
+ - Resource-based and tool-based ingestion
+ - Connection management
+ - Progress tracking
+
+ 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")
+ >>> resources = ingestor.list_available_resources("db_server")
+ >>> data = ingestor.ingest_resources("db_server", resource_uris=["resource://database/tables"])
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize MCP ingestor.
+
+ Sets up the ingestor with configuration. MCP servers are connected
+ on-demand using the connect() method.
+
+ Args:
+ config: Ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
+ """
+ self.logger = get_logger("mcp_ingestor")
+
+ # Merge configuration
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # MCP server connections (keyed by server name)
+ self._clients: Dict[str, MCPClient] = {}
+
+ # Initialize progress tracker
+ self.progress_tracker = get_progress_tracker()
+
+ self.logger.info("MCP ingestor initialized")
+
+ 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.
+
+ 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
+
+ Returns:
+ bool: True if connection successful
+
+ Raises:
+ ProcessingError: If connection fails
+ """
+ try:
+ # Check if already connected
+ if server_name in self._clients:
+ self.logger.warning(f"Server {server_name} already connected, reconnecting...")
+ self.disconnect(server_name)
+
+ # Create and connect client
+ client = MCPClient(
+ transport=transport,
+ command=command,
+ args=args,
+ url=url,
+ headers=headers,
+ **config
+ )
+
+ if client.connect():
+ self._clients[server_name] = client
+ self.logger.info(f"Connected to MCP server: {server_name}")
+ return True
+ else:
+ raise ProcessingError(f"Failed to connect to MCP server: {server_name}")
+ except Exception as e:
+ self.logger.error(f"Failed to connect to MCP server {server_name}: {e}")
+ raise ProcessingError(f"Failed to connect to MCP server {server_name}: {e}") from e
+
+ def disconnect(self, server_name: Optional[str] = None):
+ """
+ Disconnect from an MCP server or all servers.
+
+ Args:
+ server_name: Server name to disconnect (None to disconnect all)
+ """
+ if server_name:
+ if server_name in self._clients:
+ self._clients[server_name].disconnect()
+ del self._clients[server_name]
+ self.logger.info(f"Disconnected from MCP server: {server_name}")
+ else:
+ self.logger.warning(f"Server {server_name} not connected")
+ else:
+ # Disconnect all
+ for name, client in list(self._clients.items()):
+ client.disconnect()
+ del self._clients[name]
+ self.logger.info("Disconnected from all MCP servers")
+
+ def _get_client(self, server_name: str) -> MCPClient:
+ """Get MCP client for server name."""
+ if server_name not in self._clients:
+ raise ValidationError(f"MCP server '{server_name}' not connected. Call connect() first.")
+ return self._clients[server_name]
+
+ def list_available_resources(self, server_name: str) -> List[MCPResource]:
+ """
+ List resources available from an MCP server.
+
+ Args:
+ server_name: Name of connected MCP server
+
+ Returns:
+ List of MCPResource objects
+ """
+ client = self._get_client(server_name)
+ return client.list_resources()
+
+ def list_available_tools(self, server_name: str) -> List[MCPTool]:
+ """
+ List tools available from an MCP server.
+
+ Args:
+ server_name: Name of connected MCP server
+
+ Returns:
+ List of MCPTool objects
+ """
+ client = self._get_client(server_name)
+ return client.list_tools()
+
+ def read_resource(self, server_name: str, uri: str) -> Dict[str, Any]:
+ """
+ Read a resource from an MCP server.
+
+ Args:
+ server_name: Name of connected MCP server
+ uri: Resource URI
+
+ Returns:
+ Resource data dictionary
+ """
+ client = self._get_client(server_name)
+ return client.read_resource(uri)
+
+ def call_tool(
+ self,
+ server_name: str,
+ tool_name: str,
+ arguments: Optional[Dict[str, Any]] = None
+ ) -> Dict[str, Any]:
+ """
+ Call a tool on an MCP server.
+
+ Args:
+ server_name: Name of connected MCP server
+ tool_name: Tool name
+ arguments: Tool arguments
+
+ Returns:
+ Tool result dictionary
+ """
+ client = self._get_client(server_name)
+ return client.call_tool(tool_name, arguments or {})
+
+ def ingest_resources(
+ self,
+ server_name: str,
+ resource_uris: Optional[List[str]] = None,
+ filter_func: Optional[callable] = None,
+ **options
+ ) -> List[MCPData]:
+ """
+ Ingest data from MCP server resources.
+
+ Args:
+ server_name: Name of connected MCP server
+ resource_uris: List of resource URIs to ingest (None for all)
+ filter_func: Optional function to filter resources
+ **options: Additional ingestion options
+
+ Returns:
+ List of MCPData objects
+ """
+ client = self._get_client(server_name)
+
+ try:
+ # Get tracking ID
+ tracking_id = self.progress_tracker.start_task(
+ task_type="mcp_ingest_resources",
+ description=f"Ingesting resources from {server_name}"
+ )
+
+ # List available resources
+ all_resources = client.list_resources()
+
+ # Filter resources if needed
+ if resource_uris:
+ resources = [r for r in all_resources if r.uri in resource_uris]
+ elif filter_func:
+ resources = [r for r in all_resources if filter_func(r)]
+ else:
+ resources = all_resources
+
+ if not resources:
+ self.logger.warning(f"No resources found for server {server_name}")
+ self.progress_tracker.update_task(tracking_id, status="completed", message="No resources found")
+ return []
+
+ # Ingest each resource
+ ingested_data = []
+ total = len(resources)
+
+ for idx, resource in enumerate(resources):
+ try:
+ self.progress_tracker.update_task(
+ tracking_id,
+ status="in_progress",
+ progress=(idx / total) * 100,
+ message=f"Reading resource: {resource.uri}"
+ )
+
+ # Read resource
+ resource_data = client.read_resource(resource.uri)
+
+ # Create MCPData object
+ mcp_data = MCPData(
+ source=resource.uri,
+ server_name=server_name,
+ data_type="resource",
+ content=resource_data,
+ metadata={
+ "resource_name": resource.name,
+ "resource_description": resource.description,
+ "mime_type": resource.mime_type,
+ **resource.metadata
+ },
+ resource_uri=resource.uri
+ )
+
+ ingested_data.append(mcp_data)
+
+ except Exception as e:
+ self.logger.error(f"Failed to ingest resource {resource.uri}: {e}")
+ self.progress_tracker.update_task(
+ tracking_id,
+ status="warning",
+ message=f"Failed to ingest resource {resource.uri}: {e}"
+ )
+ continue
+
+ self.progress_tracker.update_task(
+ tracking_id,
+ status="completed",
+ progress=100,
+ message=f"Successfully ingested {len(ingested_data)} resources"
+ )
+
+ self.logger.info(f"Ingested {len(ingested_data)} resources from {server_name}")
+ return ingested_data
+
+ except Exception as e:
+ self.logger.error(f"Failed to ingest resources from {server_name}: {e}")
+ raise ProcessingError(f"Failed to ingest resources: {e}") from e
+
+ def ingest_tool_output(
+ self,
+ server_name: str,
+ tool_name: str,
+ arguments: Optional[Dict[str, Any]] = None,
+ **options
+ ) -> MCPData:
+ """
+ Ingest data by calling an MCP tool.
+
+ Args:
+ server_name: Name of connected MCP server
+ tool_name: Tool name to call
+ arguments: Tool arguments
+ **options: Additional ingestion options
+
+ Returns:
+ MCPData object with tool output
+ """
+ client = self._get_client(server_name)
+
+ try:
+ # Get tracking ID
+ tracking_id = self.progress_tracker.start_task(
+ task_type="mcp_ingest_tool",
+ description=f"Calling tool {tool_name} on {server_name}"
+ )
+
+ self.progress_tracker.update_task(
+ tracking_id,
+ status="in_progress",
+ message=f"Calling tool: {tool_name}"
+ )
+
+ # Call tool
+ tool_result = client.call_tool(tool_name, arguments or {})
+
+ # Create MCPData object
+ mcp_data = MCPData(
+ source=tool_name,
+ server_name=server_name,
+ data_type="tool_output",
+ content=tool_result,
+ metadata={
+ "tool_name": tool_name,
+ "arguments": arguments or {}
+ },
+ tool_name=tool_name
+ )
+
+ self.progress_tracker.update_task(
+ tracking_id,
+ status="completed",
+ progress=100,
+ message=f"Successfully called tool {tool_name}"
+ )
+
+ self.logger.info(f"Ingested data from tool {tool_name} on {server_name}")
+ return mcp_data
+
+ except Exception as e:
+ self.logger.error(f"Failed to ingest tool output from {server_name}: {e}")
+ raise ProcessingError(f"Failed to ingest tool output: {e}") from e
+
+ def ingest_all_resources(
+ self,
+ server_name: str,
+ **options
+ ) -> List[MCPData]:
+ """
+ Ingest all resources from an MCP server.
+
+ Args:
+ server_name: Name of connected MCP server
+ **options: Additional ingestion options
+
+ Returns:
+ List of MCPData objects
+ """
+ return self.ingest_resources(server_name, resource_uris=None, **options)
+
+ def get_connected_servers(self) -> List[str]:
+ """Get list of connected server names."""
+ return list(self._clients.keys())
+
+ def is_connected(self, server_name: str) -> bool:
+ """Check if a server is connected."""
+ return server_name in self._clients and self._clients[server_name].is_connected()
+
diff --git a/semantica/ingest/methods.py b/semantica/ingest/methods.py
index c59c1493..d6f7d97b 100644
--- a/semantica/ingest/methods.py
+++ b/semantica/ingest/methods.py
@@ -151,6 +151,7 @@ from .stream_ingestor import StreamIngestor, StreamProcessor
from .repo_ingestor import RepoIngestor
from .email_ingestor import EmailIngestor, EmailData
from .db_ingestor import DBIngestor, TableData
+from .mcp_ingestor import MCPIngestor, MCPData
from .registry import method_registry
from .config import ingest_config
@@ -600,6 +601,108 @@ def ingest_database(
raise
+def ingest_mcp(
+ source: Union[str, Dict[str, Any]],
+ method: str = "resources",
+ server_name: Optional[str] = None,
+ **kwargs
+) -> Union[MCPData, List[MCPData], Dict[str, Any]]:
+ """
+ Ingest data from MCP server (convenience function).
+
+ This is a user-friendly wrapper that ingests data from MCP servers using
+ the specified method. Works with any Python-based MCP server.
+
+ Args:
+ source: MCP server configuration (dict) or server name (str) if already connected
+ 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
+ - resource_uris: List of resource URIs to ingest
+ - tool_name: Tool name to call
+ - tool_arguments: Tool arguments
+
+ Returns:
+ MCPData, List[MCPData], or Dict with ingestion results
+
+ Examples:
+ >>> from semantica.ingest.methods import ingest_mcp
+ >>> # Connect and ingest resources
+ >>> data = ingest_mcp(
+ ... {"transport": "stdio", "command": "python", "args": ["-m", "mcp_server"]},
+ ... method="resources"
+ ... )
+ >>> # Ingest from already connected server
+ >>> data = ingest_mcp("server1", method="resources", resource_uris=["resource://example"])
+ >>> # Call tool
+ >>> result = ingest_mcp("server1", method="tools", tool_name="get_data", tool_arguments={})
+ """
+ # Check for custom method in registry
+ custom_method = method_registry.get("mcp", method)
+ if custom_method:
+ try:
+ return custom_method(source, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ # Get config
+ config = ingest_config.get_method_config("mcp")
+ config.update(kwargs)
+
+ ingestor = MCPIngestor(**config)
+
+ # If source is a string, assume it's a server name (already connected)
+ 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.")
+ 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())}")
+
+ ingestor.connect(
+ server_name=server_name,
+ transport=source.get("transport", "stdio"),
+ command=source.get("command"),
+ args=source.get("args"),
+ url=source.get("url"),
+ headers=source.get("headers"),
+ **{k: v for k, v in source.items() if k not in ("transport", "command", "args", "url", "headers", "server_name")}
+ )
+ else:
+ raise ProcessingError("Source must be server name (str) or configuration (dict)")
+
+ # Ingest based on method
+ if method == "resources" or method == "all":
+ resource_uris = kwargs.get("resource_uris")
+ if method == "all":
+ return ingestor.ingest_all_resources(server_name, **kwargs)
+ else:
+ return ingestor.ingest_resources(server_name, resource_uris=resource_uris, **kwargs)
+ elif method == "tools":
+ tool_name = kwargs.get("tool_name")
+ if not tool_name:
+ raise ProcessingError("tool_name required for tools method")
+ tool_arguments = kwargs.get("tool_arguments", {})
+ return ingestor.ingest_tool_output(server_name, tool_name, tool_arguments, **kwargs)
+ else:
+ raise ProcessingError(f"Unknown MCP method: {method}")
+
+ except Exception as e:
+ logger.error(f"Failed to ingest MCP: {e}")
+ raise
+
+
def ingest(
sources: Union[List[Union[str, Path]], str, Path],
source_type: Optional[str] = None,
@@ -677,6 +780,9 @@ def ingest(
raise ProcessingError("Email ingestion requires configuration dictionary")
elif source_type == "db":
return {"data": ingest_database(sources, method=method, **kwargs)}
+ else:
+ elif source_type == "mcp":
+ return {"data": ingest_mcp(sources, method=method or "resources", **kwargs)}
else:
raise ProcessingError(f"Unknown source type: {source_type}")
@@ -686,7 +792,7 @@ def get_ingest_method(task: str, name: str) -> Optional[Callable]:
Get a registered ingestion method.
Args:
- task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")
+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "mcp", "ingest")
name: Method name
Returns:
@@ -750,6 +856,10 @@ method_registry.register("db", "mysql", ingest_database)
method_registry.register("db", "sqlite", ingest_database)
method_registry.register("db", "oracle", ingest_database)
method_registry.register("db", "mssql", ingest_database)
+method_registry.register("mcp", "default", ingest_mcp)
+method_registry.register("mcp", "resources", ingest_mcp)
+method_registry.register("mcp", "tools", ingest_mcp)
+method_registry.register("mcp", "all", ingest_mcp)
method_registry.register("ingest", "default", ingest)
method_registry.register("ingest", "unified", ingest)
diff --git a/semantica/ingest/registry.py b/semantica/ingest/registry.py
index 4b94f347..5910169d 100644
--- a/semantica/ingest/registry.py
+++ b/semantica/ingest/registry.py
@@ -55,6 +55,7 @@ class MethodRegistry:
"repo": {},
"email": {},
"db": {},
+ "mcp": {},
"ingest": {},
}
@@ -64,7 +65,7 @@ class MethodRegistry:
Register a custom ingestion method.
Args:
- task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")
+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "mcp", "ingest")
name: Method name
method_func: Method function
"""
@@ -78,7 +79,7 @@ class MethodRegistry:
Get method by task and name.
Args:
- task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")
+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "mcp", "ingest")
name: Method name
Returns:
@@ -107,7 +108,7 @@ class MethodRegistry:
Unregister a method.
Args:
- task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")
+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "mcp", "ingest")
name: Method name
"""
if task in cls._methods and name in cls._methods[task]:
diff --git a/semantica/parse/__init__.py b/semantica/parse/__init__.py
index 136e5e82..ce61abec 100644
--- a/semantica/parse/__init__.py
+++ b/semantica/parse/__init__.py
@@ -135,6 +135,7 @@ from .json_parser import JSONParser, JSONData
from .csv_parser import CSVParser, CSVData
from .xml_parser import XMLParser, XMLElement, XMLData
from .image_parser import ImageParser, ImageMetadata, OCRResult
+from .mcp_parser import MCPParser
from .methods import (
parse_document,
parse_web_content,
@@ -200,6 +201,8 @@ __all__ = [
"ImageParser",
"ImageMetadata",
"OCRResult",
+ # MCP parsing
+ "MCPParser",
# Registry and config
"MethodRegistry",
"method_registry",
diff --git a/semantica/parse/mcp_parser.py b/semantica/parse/mcp_parser.py
new file mode 100644
index 00000000..6c7c4277
--- /dev/null
+++ b/semantica/parse/mcp_parser.py
@@ -0,0 +1,301 @@
+"""
+MCP Parser Module
+
+This module provides parsing capabilities for MCP (Model Context Protocol) server
+responses and tool outputs, handling various response formats from any Python MCP server.
+
+Key Features:
+ - Generic parsing for any Python MCP server responses
+ - Support for JSON, text, and binary formats
+ - Structured data extraction from tool outputs
+ - Integration with existing parsers
+
+Main Classes:
+ - MCPParser: Main MCP response parser
+
+Example Usage:
+ >>> from semantica.parse import MCPParser
+ >>> parser = MCPParser()
+ >>> parsed = parser.parse_resource_response(resource_data)
+ >>> parsed = parser.parse_tool_output(tool_result)
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import json
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .structured_data_parser import StructuredDataParser
+from .document_parser import DocumentParser
+
+
+class MCPParser:
+ """
+ Generic parser for MCP server responses and tool outputs.
+
+ This class provides parsing capabilities for responses from any Python MCP server,
+ handling various formats (JSON, text, binary) and extracting structured data.
+
+ Features:
+ - Generic parsing for any MCP server domain
+ - Support for multiple response formats
+ - Structured data extraction
+ - Integration with existing parsers
+
+ Example Usage:
+ >>> parser = MCPParser()
+ >>> parsed = parser.parse_resource_response(resource_data)
+ >>> parsed = parser.parse_tool_output(tool_result)
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize MCP parser.
+
+ Args:
+ config: Parser configuration dictionary
+ **kwargs: Additional configuration parameters
+ """
+ self.logger = get_logger("mcp_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize helper parsers
+ self.structured_parser = StructuredDataParser(**self.config)
+ self.document_parser = DocumentParser(**self.config)
+
+ self.logger.debug("MCP parser initialized")
+
+ def parse_resource_response(
+ self,
+ resource_data: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Parse a resource response from an MCP server.
+
+ Args:
+ resource_data: Resource data dictionary from MCP server
+ **options: Additional parsing options
+
+ Returns:
+ Parsed resource data dictionary
+ """
+ try:
+ result = {
+ "type": "resource",
+ "raw": resource_data,
+ "content": None,
+ "metadata": {},
+ "parsed_content": None
+ }
+
+ # Extract content
+ content = resource_data.get("contents", [])
+ if content:
+ # Handle multiple contents (MCP allows multiple)
+ parsed_contents = []
+ for item in content:
+ parsed_item = self._parse_content_item(item)
+ if parsed_item:
+ parsed_contents.append(parsed_item)
+
+ result["content"] = parsed_contents
+ result["parsed_content"] = parsed_contents[0] if len(parsed_contents) == 1 else parsed_contents
+
+ # Extract metadata
+ result["metadata"] = resource_data.get("metadata", {})
+ result["uri"] = resource_data.get("uri")
+ result["mimeType"] = resource_data.get("mimeType")
+
+ return result
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse resource response: {e}")
+ raise ProcessingError(f"Failed to parse resource response: {e}") from e
+
+ def parse_tool_output(
+ self,
+ tool_result: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Parse a tool output from an MCP server.
+
+ Args:
+ tool_result: Tool result dictionary from MCP server
+ **options: Additional parsing options
+
+ Returns:
+ Parsed tool output dictionary
+ """
+ try:
+ result = {
+ "type": "tool_output",
+ "raw": tool_result,
+ "content": None,
+ "metadata": {},
+ "parsed_content": None
+ }
+
+ # Extract content
+ content = tool_result.get("content", [])
+ if content:
+ # Handle multiple contents
+ parsed_contents = []
+ for item in content:
+ parsed_item = self._parse_content_item(item)
+ if parsed_item:
+ parsed_contents.append(parsed_item)
+
+ result["content"] = parsed_contents
+ result["parsed_content"] = parsed_contents[0] if len(parsed_contents) == 1 else parsed_contents
+
+ # Extract metadata
+ result["metadata"] = tool_result.get("metadata", {})
+ result["isError"] = tool_result.get("isError", False)
+
+ return result
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse tool output: {e}")
+ raise ProcessingError(f"Failed to parse tool output: {e}") from e
+
+ def _parse_content_item(self, item: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """
+ Parse a single content item from MCP response.
+
+ Args:
+ item: Content item dictionary
+
+ Returns:
+ Parsed content dictionary or None
+ """
+ try:
+ content_type = item.get("type", "text")
+ text = item.get("text", "")
+ data = item.get("data")
+ mime_type = item.get("mimeType")
+
+ parsed = {
+ "type": content_type,
+ "mimeType": mime_type,
+ "raw": item
+ }
+
+ if content_type == "text":
+ parsed["text"] = text
+ # Try to parse as structured data if it looks like JSON
+ if text.strip().startswith(("{", "[")):
+ try:
+ parsed["structured"] = json.loads(text)
+ except json.JSONDecodeError:
+ pass
+ elif content_type == "resource":
+ parsed["resource"] = item.get("resource")
+ elif content_type == "image" and data:
+ parsed["image_data"] = data
+ parsed["image_format"] = mime_type
+ else:
+ parsed["data"] = data
+
+ # If we have text and it looks like structured data, try parsing
+ if "text" in parsed and not "structured" in parsed:
+ text_content = parsed["text"]
+ # Try JSON
+ if text_content.strip().startswith(("{", "[")):
+ try:
+ parsed["structured"] = json.loads(text_content)
+ except json.JSONDecodeError:
+ pass
+ # Try CSV-like
+ elif "\t" in text_content or "," in text_content:
+ try:
+ lines = text_content.strip().split("\n")
+ if len(lines) > 1:
+ parsed["structured"] = self._parse_csv_like(text_content)
+ except Exception:
+ pass
+
+ return parsed
+
+ except Exception as e:
+ self.logger.warning(f"Failed to parse content item: {e}")
+ return None
+
+ def _parse_csv_like(self, text: str) -> List[Dict[str, Any]]:
+ """
+ Parse CSV-like text data.
+
+ Args:
+ text: CSV-like text
+
+ Returns:
+ List of dictionaries
+ """
+ lines = text.strip().split("\n")
+ if not lines:
+ return []
+
+ # Detect delimiter
+ delimiter = "\t" if "\t" in lines[0] else ","
+
+ # Parse header
+ header = [h.strip() for h in lines[0].split(delimiter)]
+
+ # Parse rows
+ rows = []
+ for line in lines[1:]:
+ if not line.strip():
+ continue
+ values = [v.strip() for v in line.split(delimiter)]
+ if len(values) == len(header):
+ rows.append(dict(zip(header, values)))
+
+ return rows
+
+ def parse_mcp_data(
+ self,
+ mcp_data: Any,
+ data_type: Optional[str] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Parse MCP data (generic method that auto-detects type).
+
+ Args:
+ mcp_data: MCP data to parse (can be resource or tool output)
+ data_type: Optional data type hint ("resource" or "tool_output")
+ **options: Additional parsing options
+
+ Returns:
+ Parsed data dictionary
+ """
+ try:
+ # Auto-detect type if not provided
+ if not data_type:
+ if isinstance(mcp_data, dict):
+ if "contents" in mcp_data:
+ data_type = "resource"
+ elif "content" in mcp_data:
+ data_type = "tool_output"
+ else:
+ # Default to tool_output
+ data_type = "tool_output"
+ else:
+ raise ProcessingError("Cannot determine MCP data type")
+
+ if data_type == "resource":
+ return self.parse_resource_response(mcp_data, **options)
+ elif data_type == "tool_output":
+ return self.parse_tool_output(mcp_data, **options)
+ else:
+ raise ProcessingError(f"Unknown MCP data type: {data_type}")
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse MCP data: {e}")
+ raise ProcessingError(f"Failed to parse MCP data: {e}") from e
+
diff --git a/semantica/parse/registry.py b/semantica/parse/registry.py
index ecaafada..729aabd7 100644
--- a/semantica/parse/registry.py
+++ b/semantica/parse/registry.py
@@ -52,6 +52,7 @@ class MethodRegistry:
"email": {},
"code": {},
"media": {},
+ "mcp": {},
}
@classmethod
@@ -60,7 +61,7 @@ class MethodRegistry:
Register a custom parsing method.
Args:
- task: Task type ("document", "web", "structured", "email", "code", "media")
+ task: Task type ("document", "web", "structured", "email", "code", "media", "mcp")
name: Method name
method_func: Method function
"""
@@ -74,7 +75,7 @@ class MethodRegistry:
Get method by task and name.
Args:
- task: Task type ("document", "web", "structured", "email", "code", "media")
+ task: Task type ("document", "web", "structured", "email", "code", "media", "mcp")
name: Method name
Returns:
@@ -103,7 +104,7 @@ class MethodRegistry:
Unregister a method.
Args:
- task: Task type ("document", "web", "structured", "email", "code", "media")
+ task: Task type ("document", "web", "structured", "email", "code", "media", "mcp")
name: Method name
"""
if task in cls._methods and name in cls._methods[task]: