✅ COMPREHENSIVE SAFETY FRAMEWORK: • Package-level safety notices with SACRED TRUST language • Server-level LLM safety protocols with specific refusal scenarios • Class-level safety reminders for AI assistants • Tool-level destructive operation warnings (🔴 DESTRUCTIVE markers) • Visual safety system: 🔴🛡️🚨 markers throughout codebase • Emergency logging infrastructure with proper escalation • Default-safe operations (dry_run=True for destructive tools) 🔒 DESTRUCTIVE OPERATION PROTECTIONS: • bulk_rename: LLM safety instructions + dry_run default • search_and_replace_batch: Comprehensive safety warnings • All destructive tools require preview before execution • Clear REFUSE scenarios for AI assistants 📚 COMPREHENSIVE DOCUMENTATION: • SACRED_TRUST_SAFETY.md: Complete safety philosophy & implementation guide • IMPLEMENTATION_COMPLETE.md: Project completion status • EMERGENCY_LOGGING_COMPLETE.md: Logging infrastructure details • UV_BUILD_GUIDE.md: Modern Python project setup • Multiple implementation guides and status docs 🔧 PROJECT MODERNIZATION: • Migrated from setup.py/requirements.txt to pyproject.toml + uv • Updated dependency management with uv.lock • Enhanced test suite with comprehensive coverage • Added examples and demo scripts ✅ VALIDATION COMPLETE: All SACRED_TRUST_SAFETY.md requirements implemented 🎯 Sacred Trust Status: PROTECTED 🚨 User Safety: PARAMOUNT 🔐 System Integrity: PRESERVED The human trusts AI assistants to be guardians of their system and data. This framework ensures that trust is honored through comprehensive safety measures.
160 lines
4.3 KiB
Python
160 lines
4.3 KiB
Python
"""
|
|
Base module with common imports and utilities for Enhanced MCP Tools
|
|
"""
|
|
|
|
# Standard library imports
|
|
import ast
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from collections import defaultdict
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from typing import Any, Dict, List, Literal, Optional, Union
|
|
|
|
# Third-party imports with fallbacks
|
|
try:
|
|
import aiofiles
|
|
except ImportError:
|
|
aiofiles = None
|
|
|
|
try:
|
|
import psutil
|
|
except ImportError:
|
|
psutil = None
|
|
|
|
try:
|
|
import requests
|
|
except ImportError:
|
|
requests = None
|
|
|
|
try:
|
|
from fastmcp import Context, FastMCP
|
|
from fastmcp.contrib.mcp_mixin import MCPMixin, mcp_prompt, mcp_resource, mcp_tool
|
|
except ImportError:
|
|
# Fallback for when FastMCP is not available
|
|
Context = None
|
|
FastMCP = None
|
|
MCPMixin = object
|
|
mcp_tool = lambda **kwargs: lambda func: func
|
|
mcp_resource = lambda **kwargs: lambda func: func
|
|
mcp_prompt = lambda **kwargs: lambda func: func
|
|
|
|
|
|
# Common utility functions that multiple modules will use
|
|
class MCPBase:
|
|
"""Base class with common functionality for all MCP tool classes"""
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
async def log_info(self, message: str, ctx: Optional[Context] = None):
|
|
"""Helper to log info messages"""
|
|
if ctx:
|
|
await ctx.info(message)
|
|
else:
|
|
print(f"INFO: {message}")
|
|
|
|
async def log_warning(self, message: str, ctx: Optional[Context] = None):
|
|
"""Helper to log warning messages"""
|
|
if ctx:
|
|
await ctx.warning(message)
|
|
else:
|
|
print(f"WARNING: {message}")
|
|
|
|
async def log_error(self, message: str, ctx: Optional[Context] = None):
|
|
"""Helper to log error messages"""
|
|
if ctx:
|
|
await ctx.error(message)
|
|
else:
|
|
print(f"ERROR: {message}")
|
|
|
|
async def log_critical_error(self, message: str, exception: Exception = None, ctx: Optional[Context] = None):
|
|
"""Helper to log critical error messages with enhanced detail
|
|
|
|
For critical tool failures that prevent completion but don't corrupt data.
|
|
Uses ctx.error() as the highest severity in current FastMCP.
|
|
"""
|
|
if exception:
|
|
error_detail = f"CRITICAL: {message} | Exception: {type(exception).__name__}: {str(exception)}"
|
|
else:
|
|
error_detail = f"CRITICAL: {message}"
|
|
|
|
if ctx:
|
|
await ctx.error(error_detail)
|
|
else:
|
|
print(f"CRITICAL ERROR: {error_detail}")
|
|
|
|
async def log_emergency(self, message: str, exception: Exception = None, ctx: Optional[Context] = None):
|
|
"""Helper to log emergency-level errors
|
|
|
|
RESERVED FOR TRUE EMERGENCIES: data corruption, security breaches, system instability.
|
|
Currently uses ctx.error() with EMERGENCY prefix since FastMCP doesn't have emergency().
|
|
If FastMCP adds emergency() method in future, this will be updated.
|
|
"""
|
|
if exception:
|
|
error_detail = f"EMERGENCY: {message} | Exception: {type(exception).__name__}: {str(exception)}"
|
|
else:
|
|
error_detail = f"EMERGENCY: {message}"
|
|
|
|
if ctx:
|
|
# Check if emergency method exists (future-proofing)
|
|
if hasattr(ctx, 'emergency'):
|
|
await ctx.emergency(error_detail)
|
|
else:
|
|
# Fallback to error with EMERGENCY prefix
|
|
await ctx.error(error_detail)
|
|
else:
|
|
print(f"🚨 EMERGENCY: {error_detail}")
|
|
|
|
# Could also implement additional emergency actions here:
|
|
# - Write to emergency log file
|
|
# - Send alerts
|
|
# - Trigger backup/recovery procedures
|
|
|
|
|
|
# Export common dependencies for use by other modules
|
|
__all__ = [
|
|
# Standard library
|
|
"os",
|
|
"sys",
|
|
"re",
|
|
"ast",
|
|
"json",
|
|
"time",
|
|
"uuid",
|
|
"shutil",
|
|
"asyncio",
|
|
"subprocess",
|
|
# Typing
|
|
"Optional",
|
|
"Any",
|
|
"Union",
|
|
"Literal",
|
|
"Dict",
|
|
"List",
|
|
# Path and datetime
|
|
"Path",
|
|
"datetime",
|
|
"defaultdict",
|
|
# Third-party
|
|
"aiofiles",
|
|
"psutil",
|
|
"requests",
|
|
# FastMCP
|
|
"MCPMixin",
|
|
"mcp_tool",
|
|
"mcp_resource",
|
|
"mcp_prompt",
|
|
"FastMCP",
|
|
"Context",
|
|
# Base class
|
|
"MCPBase",
|
|
]
|