mirror of
https://github.com/jmagar/unraid-mcp.git
synced 2026-03-01 16:04:24 -08:00
lintfree
This commit is contained in:
@@ -1 +1 @@
|
||||
"""MCP tools organized by functional domain."""
|
||||
"""MCP tools organized by functional domain."""
|
||||
|
||||
@@ -65,7 +65,7 @@ def get_available_container_names(containers: list[dict[str, Any]]) -> list[str]
|
||||
return names
|
||||
|
||||
|
||||
def register_docker_tools(mcp: FastMCP):
|
||||
def register_docker_tools(mcp: FastMCP) -> None:
|
||||
"""Register all Docker tools with the FastMCP instance.
|
||||
|
||||
Args:
|
||||
@@ -97,11 +97,12 @@ def register_docker_tools(mcp: FastMCP):
|
||||
logger.info("Executing list_docker_containers tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
if response_data.get("docker"):
|
||||
return response_data["docker"].get("containers", [])
|
||||
containers = response_data["docker"].get("containers", [])
|
||||
return list(containers) if isinstance(containers, list) else []
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Error in list_docker_containers: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to list Docker containers: {str(e)}")
|
||||
raise ToolError(f"Failed to list Docker containers: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def manage_docker_container(container_id: str, action: str) -> dict[str, Any]:
|
||||
@@ -161,7 +162,7 @@ def register_docker_tools(mcp: FastMCP):
|
||||
containers = list_response["docker"].get("containers", [])
|
||||
resolved_container = find_container_by_identifier(container_id, containers)
|
||||
if resolved_container:
|
||||
actual_container_id = resolved_container.get("id")
|
||||
actual_container_id = str(resolved_container.get("id", ""))
|
||||
logger.info(f"Resolved '{container_id}' to container ID: {actual_container_id}")
|
||||
else:
|
||||
available_names = get_available_container_names(containers)
|
||||
@@ -309,7 +310,7 @@ def register_docker_tools(mcp: FastMCP):
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in manage_docker_container ({action}): {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to {action} Docker container: {str(e)}")
|
||||
raise ToolError(f"Failed to {action} Docker container: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_docker_container_details(container_identifier: str) -> dict[str, Any]:
|
||||
@@ -382,6 +383,6 @@ def register_docker_tools(mcp: FastMCP):
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_docker_container_details: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve Docker container details: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve Docker container details: {str(e)}") from e
|
||||
|
||||
logger.info("Docker tools registered successfully")
|
||||
|
||||
@@ -7,30 +7,29 @@ notifications, Docker services, and API responsiveness.
|
||||
|
||||
import datetime
|
||||
import time
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
from ..config.logging import logger
|
||||
from ..config.settings import UNRAID_API_URL, UNRAID_MCP_HOST, UNRAID_MCP_PORT, UNRAID_MCP_TRANSPORT
|
||||
from ..core.client import make_graphql_request
|
||||
from ..core.exceptions import ToolError
|
||||
|
||||
|
||||
def register_health_tools(mcp: FastMCP):
|
||||
def register_health_tools(mcp: FastMCP) -> None:
|
||||
"""Register all health tools with the FastMCP instance.
|
||||
|
||||
|
||||
Args:
|
||||
mcp: FastMCP instance to register tools with
|
||||
"""
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def health_check() -> Dict[str, Any]:
|
||||
async def health_check() -> dict[str, Any]:
|
||||
"""Returns comprehensive health status of the Unraid MCP server and system for monitoring purposes."""
|
||||
start_time = time.time()
|
||||
health_status = "healthy"
|
||||
issues = []
|
||||
|
||||
|
||||
try:
|
||||
# Enhanced health check with multiple system components
|
||||
comprehensive_query = """
|
||||
@@ -58,10 +57,10 @@ def register_health_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
response_data = await make_graphql_request(comprehensive_query)
|
||||
api_latency = round((time.time() - start_time) * 1000, 2) # ms
|
||||
|
||||
|
||||
# Base health info
|
||||
health_info = {
|
||||
"status": health_status,
|
||||
@@ -76,14 +75,14 @@ def register_health_tools(mcp: FastMCP):
|
||||
"process_uptime_seconds": time.time() - start_time # Rough estimate
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if not response_data:
|
||||
health_status = "unhealthy"
|
||||
issues.append("No response from Unraid API")
|
||||
health_info["status"] = health_status
|
||||
health_info["issues"] = issues
|
||||
return health_info
|
||||
|
||||
|
||||
# System info analysis
|
||||
info = response_data.get("info", {})
|
||||
if info:
|
||||
@@ -98,7 +97,7 @@ def register_health_tools(mcp: FastMCP):
|
||||
else:
|
||||
health_status = "degraded"
|
||||
issues.append("Unable to retrieve system info")
|
||||
|
||||
|
||||
# Array health analysis
|
||||
array_info = response_data.get("array", {})
|
||||
if array_info:
|
||||
@@ -113,7 +112,7 @@ def register_health_tools(mcp: FastMCP):
|
||||
else:
|
||||
health_status = "warning"
|
||||
issues.append("Unable to retrieve array status")
|
||||
|
||||
|
||||
# Notifications analysis
|
||||
notifications = response_data.get("notifications", {})
|
||||
if notifications and notifications.get("overview"):
|
||||
@@ -121,32 +120,32 @@ def register_health_tools(mcp: FastMCP):
|
||||
alert_count = unread.get("alert", 0)
|
||||
warning_count = unread.get("warning", 0)
|
||||
total_unread = unread.get("total", 0)
|
||||
|
||||
|
||||
health_info["notifications"] = {
|
||||
"unread_total": total_unread,
|
||||
"unread_alerts": alert_count,
|
||||
"unread_warnings": warning_count,
|
||||
"has_critical_notifications": alert_count > 0
|
||||
}
|
||||
|
||||
|
||||
if alert_count > 0:
|
||||
health_status = "warning"
|
||||
issues.append(f"{alert_count} unread alert notification(s)")
|
||||
|
||||
# Docker services analysis
|
||||
|
||||
# Docker services analysis
|
||||
docker_info = response_data.get("docker", {})
|
||||
if docker_info and docker_info.get("containers"):
|
||||
containers = docker_info["containers"]
|
||||
running_containers = [c for c in containers if c.get("state") == "running"]
|
||||
stopped_containers = [c for c in containers if c.get("state") == "exited"]
|
||||
|
||||
|
||||
health_info["docker_services"] = {
|
||||
"total_containers": len(containers),
|
||||
"running_containers": len(running_containers),
|
||||
"stopped_containers": len(stopped_containers),
|
||||
"containers_healthy": len([c for c in containers if c.get("status", "").startswith("Up")])
|
||||
}
|
||||
|
||||
|
||||
# API performance assessment
|
||||
if api_latency > 5000: # > 5 seconds
|
||||
health_status = "warning"
|
||||
@@ -154,20 +153,20 @@ def register_health_tools(mcp: FastMCP):
|
||||
elif api_latency > 10000: # > 10 seconds
|
||||
health_status = "degraded"
|
||||
issues.append(f"Very high API latency: {api_latency}ms")
|
||||
|
||||
|
||||
# Final status determination
|
||||
health_info["status"] = health_status
|
||||
if issues:
|
||||
health_info["issues"] = issues
|
||||
|
||||
|
||||
# Add performance metrics
|
||||
health_info["performance"] = {
|
||||
"api_response_time_ms": api_latency,
|
||||
"health_check_duration_ms": round((time.time() - start_time) * 1000, 2)
|
||||
}
|
||||
|
||||
|
||||
return health_info
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Health check failed: {e}")
|
||||
return {
|
||||
@@ -184,4 +183,4 @@ def register_health_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Health tools registered successfully")
|
||||
logger.info("Health tools registered successfully")
|
||||
|
||||
@@ -5,7 +5,7 @@ remotes, getting configuration forms, creating new remotes, and deleting remotes
|
||||
for various cloud storage providers (S3, Google Drive, Dropbox, FTP, etc.).
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
@@ -14,15 +14,15 @@ from ..core.client import make_graphql_request
|
||||
from ..core.exceptions import ToolError
|
||||
|
||||
|
||||
def register_rclone_tools(mcp: FastMCP):
|
||||
def register_rclone_tools(mcp: FastMCP) -> None:
|
||||
"""Register all RClone tools with the FastMCP instance.
|
||||
|
||||
|
||||
Args:
|
||||
mcp: FastMCP instance to register tools with
|
||||
"""
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def list_rclone_remotes() -> List[Dict[str, Any]]:
|
||||
async def list_rclone_remotes() -> list[dict[str, Any]]:
|
||||
"""Retrieves all configured RClone remotes with their configuration details."""
|
||||
try:
|
||||
query = """
|
||||
@@ -37,25 +37,25 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
response_data = await make_graphql_request(query)
|
||||
|
||||
|
||||
if "rclone" in response_data and "remotes" in response_data["rclone"]:
|
||||
remotes = response_data["rclone"]["remotes"]
|
||||
logger.info(f"Retrieved {len(remotes)} RClone remotes")
|
||||
return remotes
|
||||
|
||||
return list(remotes) if isinstance(remotes, list) else []
|
||||
|
||||
return []
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to list RClone remotes: {str(e)}")
|
||||
raise ToolError(f"Failed to list RClone remotes: {str(e)}")
|
||||
raise ToolError(f"Failed to list RClone remotes: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_rclone_config_form(provider_type: Optional[str] = None) -> Dict[str, Any]:
|
||||
async def get_rclone_config_form(provider_type: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
Get RClone configuration form schema for setting up new remotes.
|
||||
|
||||
|
||||
Args:
|
||||
provider_type: Optional provider type to get specific form (e.g., 's3', 'drive', 'dropbox')
|
||||
"""
|
||||
@@ -71,29 +71,29 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
variables = {}
|
||||
if provider_type:
|
||||
variables["formOptions"] = {"providerType": provider_type}
|
||||
|
||||
|
||||
response_data = await make_graphql_request(query, variables)
|
||||
|
||||
|
||||
if "rclone" in response_data and "configForm" in response_data["rclone"]:
|
||||
form_data = response_data["rclone"]["configForm"]
|
||||
logger.info(f"Retrieved RClone config form for {provider_type or 'general'}")
|
||||
return form_data
|
||||
|
||||
return dict(form_data) if isinstance(form_data, dict) else {}
|
||||
|
||||
raise ToolError("No RClone config form data received")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get RClone config form: {str(e)}")
|
||||
raise ToolError(f"Failed to get RClone config form: {str(e)}")
|
||||
raise ToolError(f"Failed to get RClone config form: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def create_rclone_remote(name: str, provider_type: str, config_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
async def create_rclone_remote(name: str, provider_type: str, config_data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Create a new RClone remote with the specified configuration.
|
||||
|
||||
|
||||
Args:
|
||||
name: Name for the new remote
|
||||
provider_type: Type of provider (e.g., 's3', 'drive', 'dropbox', 'ftp')
|
||||
@@ -111,7 +111,7 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
variables = {
|
||||
"input": {
|
||||
"name": name,
|
||||
@@ -119,9 +119,9 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
"config": config_data
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
response_data = await make_graphql_request(mutation, variables)
|
||||
|
||||
|
||||
if "rclone" in response_data and "createRCloneRemote" in response_data["rclone"]:
|
||||
remote_info = response_data["rclone"]["createRCloneRemote"]
|
||||
logger.info(f"Successfully created RClone remote: {name}")
|
||||
@@ -130,18 +130,18 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
"message": f"RClone remote '{name}' created successfully",
|
||||
"remote": remote_info
|
||||
}
|
||||
|
||||
|
||||
raise ToolError("Failed to create RClone remote")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create RClone remote {name}: {str(e)}")
|
||||
raise ToolError(f"Failed to create RClone remote {name}: {str(e)}")
|
||||
raise ToolError(f"Failed to create RClone remote {name}: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def delete_rclone_remote(name: str) -> Dict[str, Any]:
|
||||
async def delete_rclone_remote(name: str) -> dict[str, Any]:
|
||||
"""
|
||||
Delete an existing RClone remote by name.
|
||||
|
||||
|
||||
Args:
|
||||
name: Name of the remote to delete
|
||||
"""
|
||||
@@ -153,26 +153,26 @@ def register_rclone_tools(mcp: FastMCP):
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
variables = {
|
||||
"input": {
|
||||
"name": name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
response_data = await make_graphql_request(mutation, variables)
|
||||
|
||||
|
||||
if "rclone" in response_data and response_data["rclone"]["deleteRCloneRemote"]:
|
||||
logger.info(f"Successfully deleted RClone remote: {name}")
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"RClone remote '{name}' deleted successfully"
|
||||
}
|
||||
|
||||
|
||||
raise ToolError(f"Failed to delete RClone remote '{name}'")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete RClone remote {name}: {str(e)}")
|
||||
raise ToolError(f"Failed to delete RClone remote {name}: {str(e)}")
|
||||
raise ToolError(f"Failed to delete RClone remote {name}: {str(e)}") from e
|
||||
|
||||
logger.info("RClone tools registered successfully")
|
||||
logger.info("RClone tools registered successfully")
|
||||
|
||||
@@ -5,7 +5,7 @@ log files, physical disks with SMART data, and system storage operations
|
||||
with custom timeout configurations for disk-intensive operations.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastmcp import FastMCP
|
||||
@@ -15,15 +15,15 @@ from ..core.client import make_graphql_request
|
||||
from ..core.exceptions import ToolError
|
||||
|
||||
|
||||
def register_storage_tools(mcp: FastMCP):
|
||||
def register_storage_tools(mcp: FastMCP) -> None:
|
||||
"""Register all storage tools with the FastMCP instance.
|
||||
|
||||
|
||||
Args:
|
||||
mcp: FastMCP instance to register tools with
|
||||
"""
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def get_shares_info() -> List[Dict[str, Any]]:
|
||||
async def get_shares_info() -> list[dict[str, Any]]:
|
||||
"""Retrieves information about user shares."""
|
||||
query = """
|
||||
query GetSharesInfo {
|
||||
@@ -50,13 +50,14 @@ def register_storage_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing get_shares_info tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
return response_data.get("shares", [])
|
||||
shares = response_data.get("shares", [])
|
||||
return list(shares) if isinstance(shares, list) else []
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_shares_info: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve shares information: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve shares information: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_notifications_overview() -> Dict[str, Any]:
|
||||
async def get_notifications_overview() -> dict[str, Any]:
|
||||
"""Retrieves an overview of system notifications (unread and archive counts by severity)."""
|
||||
query = """
|
||||
query GetNotificationsOverview {
|
||||
@@ -72,19 +73,20 @@ def register_storage_tools(mcp: FastMCP):
|
||||
logger.info("Executing get_notifications_overview tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
if response_data.get("notifications"):
|
||||
return response_data["notifications"].get("overview", {})
|
||||
overview = response_data["notifications"].get("overview", {})
|
||||
return dict(overview) if isinstance(overview, dict) else {}
|
||||
return {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_notifications_overview: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve notifications overview: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve notifications overview: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def list_notifications(
|
||||
type: str,
|
||||
offset: int,
|
||||
limit: int,
|
||||
importance: Optional[str] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
type: str,
|
||||
offset: int,
|
||||
limit: int,
|
||||
importance: str | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Lists notifications with filtering. Type: UNREAD/ARCHIVE. Importance: INFO/WARNING/ALERT."""
|
||||
query = """
|
||||
query ListNotifications($filter: NotificationFilter!) {
|
||||
@@ -114,19 +116,20 @@ def register_storage_tools(mcp: FastMCP):
|
||||
# Remove null importance from variables if not provided, as GraphQL might be strict
|
||||
if not importance:
|
||||
del variables["filter"]["importance"]
|
||||
|
||||
|
||||
try:
|
||||
logger.info(f"Executing list_notifications: type={type}, offset={offset}, limit={limit}, importance={importance}")
|
||||
response_data = await make_graphql_request(query, variables)
|
||||
if response_data.get("notifications"):
|
||||
return response_data["notifications"].get("list", [])
|
||||
notifications_list = response_data["notifications"].get("list", [])
|
||||
return list(notifications_list) if isinstance(notifications_list, list) else []
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Error in list_notifications: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to list notifications: {str(e)}")
|
||||
raise ToolError(f"Failed to list notifications: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def list_available_log_files() -> List[Dict[str, Any]]:
|
||||
async def list_available_log_files() -> list[dict[str, Any]]:
|
||||
"""Lists all available log files that can be queried."""
|
||||
query = """
|
||||
query ListLogFiles {
|
||||
@@ -141,13 +144,14 @@ def register_storage_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing list_available_log_files tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
return response_data.get("logFiles", [])
|
||||
log_files = response_data.get("logFiles", [])
|
||||
return list(log_files) if isinstance(log_files, list) else []
|
||||
except Exception as e:
|
||||
logger.error(f"Error in list_available_log_files: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to list available log files: {str(e)}")
|
||||
raise ToolError(f"Failed to list available log files: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_logs(log_file_path: str, tail_lines: int = 100) -> Dict[str, Any]:
|
||||
async def get_logs(log_file_path: str, tail_lines: int = 100) -> dict[str, Any]:
|
||||
"""Retrieves content from a specific log file, defaulting to the last 100 lines."""
|
||||
# The Unraid GraphQL API Query.logFile takes 'lines' and 'startLine'.
|
||||
# To implement 'tail_lines', we would ideally need to know the total lines first,
|
||||
@@ -158,7 +162,7 @@ def register_storage_tools(mcp: FastMCP):
|
||||
# If not, this tool might need to be smarter or the API might not directly support 'tail' easily.
|
||||
# The SDL for LogFileContent implies it returns startLine, so it seems aware of ranges.
|
||||
|
||||
# Let's try fetching with just 'lines' to see if it acts as a tail,
|
||||
# Let's try fetching with just 'lines' to see if it acts as a tail,
|
||||
# or if we need Query.logFiles first to get totalLines for calculation.
|
||||
# For robust tailing, one might need to fetch totalLines first, then calculate start_line for the tail.
|
||||
# Simplified: query for the last 'tail_lines'. If the API doesn't support tailing this way, we may need adjustment.
|
||||
@@ -178,16 +182,17 @@ def register_storage_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info(f"Executing get_logs for {log_file_path}, tail_lines={tail_lines}")
|
||||
response_data = await make_graphql_request(query, variables)
|
||||
return response_data.get("logFile", {})
|
||||
log_file = response_data.get("logFile", {})
|
||||
return dict(log_file) if isinstance(log_file, dict) else {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_logs for {log_file_path}: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve logs from {log_file_path}: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve logs from {log_file_path}: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def list_physical_disks() -> List[Dict[str, Any]]:
|
||||
async def list_physical_disks() -> list[dict[str, Any]]:
|
||||
"""Lists all physical disks recognized by the Unraid system."""
|
||||
# Querying an extremely minimal set of fields for diagnostics
|
||||
query = """
|
||||
query = """
|
||||
query ListPhysicalDisksMinimal {
|
||||
disks {
|
||||
id
|
||||
@@ -199,15 +204,16 @@ def register_storage_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing list_physical_disks tool with minimal query and increased timeout")
|
||||
# Increased read timeout for this potentially slow query
|
||||
long_timeout = httpx.Timeout(10.0, read=90.0, connect=5.0)
|
||||
long_timeout = httpx.Timeout(10.0, read=90.0, connect=5.0)
|
||||
response_data = await make_graphql_request(query, custom_timeout=long_timeout)
|
||||
return response_data.get("disks", [])
|
||||
disks = response_data.get("disks", [])
|
||||
return list(disks) if isinstance(disks, list) else []
|
||||
except Exception as e:
|
||||
logger.error(f"Error in list_physical_disks: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to list physical disks: {str(e)}")
|
||||
raise ToolError(f"Failed to list physical disks: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_disk_details(disk_id: str) -> Dict[str, Any]:
|
||||
async def get_disk_details(disk_id: str) -> dict[str, Any]:
|
||||
"""Retrieves detailed SMART information and partition data for a specific physical disk."""
|
||||
# Enhanced query with more comprehensive disk information
|
||||
query = """
|
||||
@@ -227,19 +233,20 @@ def register_storage_tools(mcp: FastMCP):
|
||||
logger.info(f"Executing get_disk_details for disk: {disk_id}")
|
||||
response_data = await make_graphql_request(query, variables)
|
||||
raw_disk = response_data.get("disk", {})
|
||||
|
||||
|
||||
if not raw_disk:
|
||||
raise ToolError(f"Disk '{disk_id}' not found")
|
||||
|
||||
|
||||
# Process disk information for human-readable output
|
||||
def format_bytes(bytes_value):
|
||||
if bytes_value is None: return "N/A"
|
||||
bytes_value = int(bytes_value)
|
||||
def format_bytes(bytes_value: int | None) -> str:
|
||||
if bytes_value is None:
|
||||
return "N/A"
|
||||
value = float(int(bytes_value))
|
||||
for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
|
||||
if bytes_value < 1024.0:
|
||||
return f"{bytes_value:.2f} {unit}"
|
||||
bytes_value /= 1024.0
|
||||
return f"{bytes_value:.2f} EB"
|
||||
if value < 1024.0:
|
||||
return f"{value:.2f} {unit}"
|
||||
value /= 1024.0
|
||||
return f"{value:.2f} EB"
|
||||
|
||||
summary = {
|
||||
'disk_id': raw_disk.get('id'),
|
||||
@@ -256,15 +263,15 @@ def register_storage_tools(mcp: FastMCP):
|
||||
'partition_count': len(raw_disk.get('partitions', [])),
|
||||
'total_partition_size': format_bytes(sum(p.get('size', 0) for p in raw_disk.get('partitions', []) if p.get('size')))
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
'summary': summary,
|
||||
'partitions': raw_disk.get('partitions', []),
|
||||
'details': raw_disk
|
||||
}
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_disk_details for {disk_id}: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve disk details for {disk_id}: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve disk details for {disk_id}: {str(e)}") from e
|
||||
|
||||
logger.info("Storage tools registered successfully")
|
||||
logger.info("Storage tools registered successfully")
|
||||
|
||||
@@ -5,7 +5,7 @@ array status with health analysis, network configuration, registration info,
|
||||
and system variables.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
@@ -15,7 +15,7 @@ from ..core.exceptions import ToolError
|
||||
|
||||
|
||||
# Standalone functions for use by subscription resources
|
||||
async def _get_system_info() -> Dict[str, Any]:
|
||||
async def _get_system_info() -> dict[str, Any]:
|
||||
"""Standalone function to get system info - used by subscriptions and tools."""
|
||||
query = """
|
||||
query GetSystemInfo {
|
||||
@@ -44,20 +44,20 @@ async def _get_system_info() -> Dict[str, Any]:
|
||||
raise ToolError("No system info returned from Unraid API")
|
||||
|
||||
# Process for human-readable output
|
||||
summary = {}
|
||||
summary: dict[str, Any] = {}
|
||||
if raw_info.get('os'):
|
||||
os_info = raw_info['os']
|
||||
summary['os'] = f"{os_info.get('distro', '')} {os_info.get('release', '')} ({os_info.get('platform', '')}, {os_info.get('arch', '')})"
|
||||
summary['hostname'] = os_info.get('hostname')
|
||||
summary['uptime'] = os_info.get('uptime')
|
||||
|
||||
summary['uptime'] = os_info.get('uptime')
|
||||
|
||||
if raw_info.get('cpu'):
|
||||
cpu_info = raw_info['cpu']
|
||||
summary['cpu'] = f"{cpu_info.get('manufacturer', '')} {cpu_info.get('brand', '')} ({cpu_info.get('cores')} cores, {cpu_info.get('threads')} threads)"
|
||||
|
||||
|
||||
if raw_info.get('memory') and raw_info['memory'].get('layout'):
|
||||
mem_layout = raw_info['memory']['layout']
|
||||
summary['memory_layout_details'] = [] # Renamed for clarity
|
||||
summary['memory_layout_details'] = [] # Renamed for clarity
|
||||
# The API is not returning 'size' for individual sticks in the layout, even if queried.
|
||||
# So, we cannot calculate total from layout currently.
|
||||
for stick in mem_layout:
|
||||
@@ -74,10 +74,10 @@ async def _get_system_info() -> Dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_system_info: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve system information: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve system information: {str(e)}") from e
|
||||
|
||||
|
||||
async def _get_array_status() -> Dict[str, Any]:
|
||||
async def _get_array_status() -> dict[str, Any]:
|
||||
"""Standalone function to get array status - used by subscriptions and tools."""
|
||||
query = """
|
||||
query GetArrayStatus {
|
||||
@@ -102,34 +102,38 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
if not raw_array_info:
|
||||
raise ToolError("No array information returned from Unraid API")
|
||||
|
||||
summary = {}
|
||||
summary: dict[str, Any] = {}
|
||||
summary['state'] = raw_array_info.get('state')
|
||||
|
||||
if raw_array_info.get('capacity') and raw_array_info['capacity'].get('kilobytes'):
|
||||
kb_cap = raw_array_info['capacity']['kilobytes']
|
||||
# Helper to format KB into TB/GB/MB
|
||||
def format_kb(k):
|
||||
if k is None: return "N/A"
|
||||
def format_kb(k: Any) -> str:
|
||||
if k is None:
|
||||
return "N/A"
|
||||
k = int(k) # Values are strings in SDL for PrefixedID containing types like capacity
|
||||
if k >= 1024*1024*1024: return f"{k / (1024*1024*1024):.2f} TB"
|
||||
if k >= 1024*1024: return f"{k / (1024*1024):.2f} GB"
|
||||
if k >= 1024: return f"{k / 1024:.2f} MB"
|
||||
if k >= 1024*1024*1024:
|
||||
return f"{k / (1024*1024*1024):.2f} TB"
|
||||
if k >= 1024*1024:
|
||||
return f"{k / (1024*1024):.2f} GB"
|
||||
if k >= 1024:
|
||||
return f"{k / 1024:.2f} MB"
|
||||
return f"{k} KB"
|
||||
|
||||
summary['capacity_total'] = format_kb(kb_cap.get('total'))
|
||||
summary['capacity_used'] = format_kb(kb_cap.get('used'))
|
||||
summary['capacity_free'] = format_kb(kb_cap.get('free'))
|
||||
|
||||
|
||||
summary['num_parity_disks'] = len(raw_array_info.get('parities', []))
|
||||
summary['num_data_disks'] = len(raw_array_info.get('disks', []))
|
||||
summary['num_cache_pools'] = len(raw_array_info.get('caches', [])) # Note: caches are pools, not individual cache disks
|
||||
|
||||
# Enhanced: Add disk health summary
|
||||
def analyze_disk_health(disks, disk_type):
|
||||
def analyze_disk_health(disks: list[dict[str, Any]], disk_type: str) -> dict[str, int]:
|
||||
"""Analyze health status of disk arrays"""
|
||||
if not disks:
|
||||
return {}
|
||||
|
||||
|
||||
health_counts = {
|
||||
'healthy': 0,
|
||||
'failed': 0,
|
||||
@@ -138,12 +142,12 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
'warning': 0,
|
||||
'unknown': 0
|
||||
}
|
||||
|
||||
|
||||
for disk in disks:
|
||||
status = disk.get('status', '').upper()
|
||||
warning = disk.get('warning')
|
||||
critical = disk.get('critical')
|
||||
|
||||
|
||||
if status == 'DISK_OK':
|
||||
if warning or critical:
|
||||
health_counts['warning'] += 1
|
||||
@@ -157,7 +161,7 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
health_counts['new'] += 1
|
||||
else:
|
||||
health_counts['unknown'] += 1
|
||||
|
||||
|
||||
return health_counts
|
||||
|
||||
# Analyze health for each disk type
|
||||
@@ -168,12 +172,12 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
health_summary['data_health'] = analyze_disk_health(raw_array_info['disks'], 'data')
|
||||
if raw_array_info.get('caches'):
|
||||
health_summary['cache_health'] = analyze_disk_health(raw_array_info['caches'], 'cache')
|
||||
|
||||
|
||||
# Overall array health assessment
|
||||
total_failed = sum(h.get('failed', 0) for h in health_summary.values())
|
||||
total_missing = sum(h.get('missing', 0) for h in health_summary.values())
|
||||
total_warning = sum(h.get('warning', 0) for h in health_summary.values())
|
||||
|
||||
|
||||
if total_failed > 0:
|
||||
overall_health = "CRITICAL"
|
||||
elif total_missing > 0:
|
||||
@@ -182,7 +186,7 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
overall_health = "WARNING"
|
||||
else:
|
||||
overall_health = "HEALTHY"
|
||||
|
||||
|
||||
summary['overall_health'] = overall_health
|
||||
summary['health_summary'] = health_summary
|
||||
|
||||
@@ -190,28 +194,28 @@ async def _get_array_status() -> Dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_array_status: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve array status: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve array status: {str(e)}") from e
|
||||
|
||||
|
||||
def register_system_tools(mcp: FastMCP):
|
||||
def register_system_tools(mcp: FastMCP) -> None:
|
||||
"""Register all system tools with the FastMCP instance.
|
||||
|
||||
|
||||
Args:
|
||||
mcp: FastMCP instance to register tools with
|
||||
"""
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def get_system_info() -> Dict[str, Any]:
|
||||
async def get_system_info() -> dict[str, Any]:
|
||||
"""Retrieves comprehensive information about the Unraid system, OS, CPU, memory, and baseboard."""
|
||||
return await _get_system_info()
|
||||
|
||||
@mcp.tool()
|
||||
async def get_array_status() -> Dict[str, Any]:
|
||||
async def get_array_status() -> dict[str, Any]:
|
||||
"""Retrieves the current status of the Unraid storage array, including its state, capacity, and details of all disks."""
|
||||
return await _get_array_status()
|
||||
|
||||
@mcp.tool()
|
||||
async def get_network_config() -> Dict[str, Any]:
|
||||
async def get_network_config() -> dict[str, Any]:
|
||||
"""Retrieves network configuration details, including access URLs."""
|
||||
query = """
|
||||
query GetNetworkConfig {
|
||||
@@ -224,13 +228,14 @@ def register_system_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing get_network_config tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
return response_data.get("network", {})
|
||||
network = response_data.get("network", {})
|
||||
return dict(network) if isinstance(network, dict) else {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_network_config: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve network configuration: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve network configuration: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_registration_info() -> Dict[str, Any]:
|
||||
async def get_registration_info() -> dict[str, Any]:
|
||||
"""Retrieves Unraid registration details."""
|
||||
query = """
|
||||
query GetRegistrationInfo {
|
||||
@@ -247,13 +252,14 @@ def register_system_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing get_registration_info tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
return response_data.get("registration", {})
|
||||
registration = response_data.get("registration", {})
|
||||
return dict(registration) if isinstance(registration, dict) else {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_registration_info: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve registration information: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve registration information: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_connect_settings() -> Dict[str, Any]:
|
||||
async def get_connect_settings() -> dict[str, Any]:
|
||||
"""Retrieves settings related to Unraid Connect."""
|
||||
# Based on actual schema: settings.unified.values contains the JSON settings
|
||||
query = """
|
||||
@@ -268,7 +274,7 @@ def register_system_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing get_connect_settings tool")
|
||||
response_data = await make_graphql_request(query)
|
||||
|
||||
|
||||
# Navigate down to the unified settings values
|
||||
if response_data.get("settings") and response_data["settings"].get("unified"):
|
||||
values = response_data["settings"]["unified"].get("values", {})
|
||||
@@ -280,15 +286,15 @@ def register_system_tools(mcp: FastMCP):
|
||||
if 'connect' in key.lower() or key in ['accessType', 'forwardType', 'port']:
|
||||
connect_settings[key] = value
|
||||
return connect_settings if connect_settings else values
|
||||
return values
|
||||
return dict(values) if isinstance(values, dict) else {}
|
||||
return {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_connect_settings: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve Unraid Connect settings: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve Unraid Connect settings: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_unraid_variables() -> Dict[str, Any]:
|
||||
"""Retrieves a selection of Unraid system variables and settings.
|
||||
async def get_unraid_variables() -> dict[str, Any]:
|
||||
"""Retrieves a selection of Unraid system variables and settings.
|
||||
Note: Many variables are omitted due to API type issues (Int overflow/NaN).
|
||||
"""
|
||||
# Querying a smaller, curated set of fields to avoid Int overflow and NaN issues
|
||||
@@ -377,9 +383,10 @@ def register_system_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info("Executing get_unraid_variables tool with a selective query")
|
||||
response_data = await make_graphql_request(query)
|
||||
return response_data.get("vars", {})
|
||||
vars_data = response_data.get("vars", {})
|
||||
return dict(vars_data) if isinstance(vars_data, dict) else {}
|
||||
except Exception as e:
|
||||
logger.error(f"Error in get_unraid_variables: {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to retrieve Unraid variables: {str(e)}")
|
||||
raise ToolError(f"Failed to retrieve Unraid variables: {str(e)}") from e
|
||||
|
||||
logger.info("System tools registered successfully")
|
||||
logger.info("System tools registered successfully")
|
||||
|
||||
@@ -5,7 +5,7 @@ including listing VMs, VM operations (start/stop/pause/reboot/etc),
|
||||
and detailed VM information retrieval.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from typing import Any
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
@@ -14,17 +14,17 @@ from ..core.client import make_graphql_request
|
||||
from ..core.exceptions import ToolError
|
||||
|
||||
|
||||
def register_vm_tools(mcp: FastMCP):
|
||||
def register_vm_tools(mcp: FastMCP) -> None:
|
||||
"""Register all VM tools with the FastMCP instance.
|
||||
|
||||
|
||||
Args:
|
||||
mcp: FastMCP instance to register tools with
|
||||
"""
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def list_vms() -> List[Dict[str, Any]]:
|
||||
async def list_vms() -> list[dict[str, Any]]:
|
||||
"""Lists all Virtual Machines (VMs) on the Unraid system and their current state.
|
||||
|
||||
|
||||
Returns:
|
||||
List of VM information dictionaries with UUID, name, and state
|
||||
"""
|
||||
@@ -48,7 +48,7 @@ def register_vm_tools(mcp: FastMCP):
|
||||
if response_data.get("vms") and response_data["vms"].get("domains"):
|
||||
vms = response_data["vms"]["domains"]
|
||||
logger.info(f"Found {len(vms)} VMs")
|
||||
return vms
|
||||
return list(vms) if isinstance(vms, list) else []
|
||||
else:
|
||||
logger.info("No VMs found in domains field")
|
||||
return []
|
||||
@@ -56,18 +56,18 @@ def register_vm_tools(mcp: FastMCP):
|
||||
logger.error(f"Error in list_vms: {e}", exc_info=True)
|
||||
error_msg = str(e)
|
||||
if "VMs are not available" in error_msg:
|
||||
raise ToolError("VMs are not available on this Unraid server. This could mean: 1) VM support is not enabled, 2) VM service is not running, or 3) no VMs are configured. Check Unraid VM settings.")
|
||||
raise ToolError("VMs are not available on this Unraid server. This could mean: 1) VM support is not enabled, 2) VM service is not running, or 3) no VMs are configured. Check Unraid VM settings.") from e
|
||||
else:
|
||||
raise ToolError(f"Failed to list virtual machines: {error_msg}")
|
||||
raise ToolError(f"Failed to list virtual machines: {error_msg}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def manage_vm(vm_uuid: str, action: str) -> Dict[str, Any]:
|
||||
async def manage_vm(vm_uuid: str, action: str) -> dict[str, Any]:
|
||||
"""Manages a VM: start, stop, pause, resume, force_stop, reboot, reset. Uses VM UUID.
|
||||
|
||||
|
||||
Args:
|
||||
vm_uuid: UUID of the VM to manage
|
||||
action: Action to perform - one of: start, stop, pause, resume, forceStop, reboot, reset
|
||||
|
||||
|
||||
Returns:
|
||||
Dict containing operation success status and details
|
||||
"""
|
||||
@@ -95,15 +95,15 @@ def register_vm_tools(mcp: FastMCP):
|
||||
raise ToolError(f"Failed to {action} VM or unexpected response structure.")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in manage_vm ({action}): {e}", exc_info=True)
|
||||
raise ToolError(f"Failed to {action} virtual machine: {str(e)}")
|
||||
raise ToolError(f"Failed to {action} virtual machine: {str(e)}") from e
|
||||
|
||||
@mcp.tool()
|
||||
async def get_vm_details(vm_identifier: str) -> Dict[str, Any]:
|
||||
async def get_vm_details(vm_identifier: str) -> dict[str, Any]:
|
||||
"""Retrieves detailed information for a specific VM by its UUID or name.
|
||||
|
||||
|
||||
Args:
|
||||
vm_identifier: VM UUID or name to retrieve details for
|
||||
|
||||
|
||||
Returns:
|
||||
Dict containing detailed VM information
|
||||
"""
|
||||
@@ -129,20 +129,20 @@ def register_vm_tools(mcp: FastMCP):
|
||||
try:
|
||||
logger.info(f"Executing get_vm_details for identifier: {vm_identifier}")
|
||||
response_data = await make_graphql_request(query)
|
||||
|
||||
|
||||
if response_data.get("vms"):
|
||||
vms_data = response_data["vms"]
|
||||
# Try to get VMs from either domains or domain field
|
||||
vms = vms_data.get("domains") or vms_data.get("domain") or []
|
||||
|
||||
|
||||
if vms:
|
||||
for vm_data in vms:
|
||||
if (vm_data.get("uuid") == vm_identifier or
|
||||
vm_data.get("id") == vm_identifier or
|
||||
if (vm_data.get("uuid") == vm_identifier or
|
||||
vm_data.get("id") == vm_identifier or
|
||||
vm_data.get("name") == vm_identifier):
|
||||
logger.info(f"Found VM {vm_identifier}")
|
||||
return vm_data
|
||||
|
||||
return dict(vm_data) if isinstance(vm_data, dict) else {}
|
||||
|
||||
logger.warning(f"VM with identifier '{vm_identifier}' not found.")
|
||||
available_vms = [f"{vm.get('name')} (UUID: {vm.get('uuid')}, ID: {vm.get('id')})" for vm in vms]
|
||||
raise ToolError(f"VM '{vm_identifier}' not found. Available VMs: {', '.join(available_vms)}")
|
||||
@@ -155,8 +155,8 @@ def register_vm_tools(mcp: FastMCP):
|
||||
logger.error(f"Error in get_vm_details: {e}", exc_info=True)
|
||||
error_msg = str(e)
|
||||
if "VMs are not available" in error_msg:
|
||||
raise ToolError("VMs are not available on this Unraid server. This could mean: 1) VM support is not enabled, 2) VM service is not running, or 3) no VMs are configured. Check Unraid VM settings.")
|
||||
raise ToolError("VMs are not available on this Unraid server. This could mean: 1) VM support is not enabled, 2) VM service is not running, or 3) no VMs are configured. Check Unraid VM settings.") from e
|
||||
else:
|
||||
raise ToolError(f"Failed to retrieve VM details: {error_msg}")
|
||||
raise ToolError(f"Failed to retrieve VM details: {error_msg}") from e
|
||||
|
||||
logger.info("VM tools registered successfully")
|
||||
logger.info("VM tools registered successfully")
|
||||
|
||||
Reference in New Issue
Block a user