pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
use crate::mcp_pmcp::analyze_handlers::{
    AnalyzeBigOTool, AnalyzeComplexityTool, AnalyzeDagTool, AnalyzeDeadCodeTool,
    AnalyzeDeepContextTool, AnalyzeSatdTool, AnalyzeTdgCompareTool, AnalyzeTdgTool,
};
use crate::mcp_pmcp::context_handlers::{GenerateContextTool, GitTool, ScaffoldProjectTool};
use crate::mcp_pmcp::handlers::{
    RefactorGetStateTool, RefactorNextIterationTool, RefactorStartTool, RefactorStopTool,
};
use crate::mcp_pmcp::prompt_handlers::GenerateDefectAwarePromptTool;
use crate::mcp_pmcp::quality_handlers::QualityGateTool;
use crate::mcp_pmcp::quality_proxy_handler::QualityProxyTool;
use crate::mcp_pmcp::tdg_handlers::{
    TdgAnalyzeWithStorageTool, TdgConfigureStorageTool, TdgHealthCheckTool,
    TdgPerformanceMetricsTool, TdgStorageManagementTool, TdgSystemDiagnosticsTool,
};
use crate::mcp_server::state_manager::StateManager;
use pmcp::{Server, ServerCapabilities, ToolCapabilities};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::info;

/// High-performance MCP server implementation using the pmcp SDK.
///
/// Provides a complete MCP implementation with all PMAT tools, offering
/// significant performance improvements over the standard implementation.
/// Supports 24 tools across analysis, refactoring, quality, TDG system,
/// and context generation categories.
///
/// # Architecture
///
/// Uses pmcp's type-safe tool handler system where each tool implements
/// the `ToolHandler` trait, providing:
/// - Compile-time validation of tool interfaces
/// - Automatic JSON-RPC request/response handling
/// - Built-in error propagation and logging
///
/// # Examples
///
/// ```rust,no_run
/// use pmat::mcp_pmcp::PmcpServer;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let server = PmcpServer::new();
///     server.run().await?;
///     Ok(())
/// }
/// ```
pub struct PmcpServer {
    state_manager: Arc<Mutex<StateManager>>,
}

impl PmcpServer {
    /// Creates a new MCP server instance using pmcp SDK.
    ///
    /// Initializes the server with a fresh state manager for handling
    /// refactoring sessions. The state manager is thread-safe and can be
    /// shared across multiple tool handlers.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "pmcp-mcp")]
    /// # {
    /// use pmat::mcp_pmcp::PmcpServer;
    ///
    /// let server = PmcpServer::new();
    /// // Server is ready to be run with server.run().await
    /// # }
    /// ```
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn new() -> Self {
        Self {
            state_manager: Arc::new(Mutex::new(StateManager::new())),
        }
    }

    /// Runs the MCP server with stdio transport.
    ///
    /// Creates a pmcp Server instance configured with PMAT's refactoring
    /// tools and runs it using the stdio transport, handling JSON-RPC
    /// communication over stdin/stdout.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Server ran successfully and shut down cleanly
    /// * `Err(Box<dyn std::error::Error>)` - Server initialization or runtime error
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use pmat::mcp_pmcp::server::PmcpServer;
    ///
    /// # tokio_test::block_on(async {
    /// let server = PmcpServer::new();
    /// server.run().await.unwrap();
    /// # });
    /// ```
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        info!("Starting PMAT MCP server using pmcp SDK");

        let server = Server::builder()
            .name("paiml-mcp-agent-toolkit")
            .version(env!("CARGO_PKG_VERSION"))
            .capabilities(ServerCapabilities {
                tools: Some(ToolCapabilities { list_changed: None }),
                ..Default::default()
            })
            // Analysis tools
            .tool("analyze_complexity", AnalyzeComplexityTool)
            .tool("analyze_satd", AnalyzeSatdTool)
            .tool("analyze_dead_code", AnalyzeDeadCodeTool)
            .tool("analyze_dag", AnalyzeDagTool)
            .tool("analyze_deep_context", AnalyzeDeepContextTool)
            .tool("analyze_big_o", AnalyzeBigOTool)
            .tool("analyze_tdg", AnalyzeTdgTool)
            .tool("analyze_tdg_compare", AnalyzeTdgCompareTool)
            // Refactoring tools
            .tool(
                "refactor.start",
                RefactorStartTool::new(self.state_manager.clone()),
            )
            .tool(
                "refactor.nextIteration",
                RefactorNextIterationTool::new(self.state_manager.clone()),
            )
            .tool(
                "refactor.getState",
                RefactorGetStateTool::new(self.state_manager.clone()),
            )
            .tool(
                "refactor.stop",
                RefactorStopTool::new(self.state_manager.clone()),
            )
            // Quality tools
            .tool("quality_gate", QualityGateTool)
            .tool("quality_proxy", QualityProxyTool)
            // Git tools
            .tool("git_operation", GitTool)
            // Context tools
            .tool("generate_context", GenerateContextTool)
            .tool("scaffold_project", ScaffoldProjectTool)
            // TDG System tools (Sprint 31)
            .tool("tdg_system_diagnostics", TdgSystemDiagnosticsTool)
            .tool("tdg_storage_management", TdgStorageManagementTool)
            .tool("tdg_analyze_with_storage", TdgAnalyzeWithStorageTool)
            .tool("tdg_performance_metrics", TdgPerformanceMetricsTool)
            .tool("tdg_configure_storage", TdgConfigureStorageTool)
            .tool("tdg_health_check", TdgHealthCheckTool)
            // Organizational Intelligence tools (Phase 4)
            .tool(
                "generate_defect_aware_prompt",
                GenerateDefectAwarePromptTool,
            )
            .build()?;

        info!(
            "PMAT MCP server ready with {} tools, listening on stdio",
            25
        );

        server.run_stdio().await?;

        info!("PMAT MCP server shutting down");
        Ok(())
    }
}

impl Default for PmcpServer {
    fn default() -> Self {
        Self::new()
    }
}

include!("server_tests.rs");