logcut 0.3.1

Local-first stacktrace, runtime log & compiler error slicing for AI coding agents and terminal pipelines
Documentation
//! MCP stdio server: JSON-RPC on stdout, diagnostics only on stderr.

use std::path::Path;

use rmcp::{
    Json, ServerHandler, ServiceExt,
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{Implementation, ServerCapabilities, ServerConfig},
    tool, tool_handler, tool_router,
};

use crate::core::{
    self,
    models::{
        LastCrashRequest, SliceBuildArgs, SliceBuildReport, SliceContainerRequest, SliceLogRequest,
        SliceReport, SliceServiceRequest, SliceTestArgs, SliceTestReport,
    },
};

/// Message returned by tools that need the host machine when served without it.
pub const HOST_ONLY_TOOL_ERROR: &str = "requires a local logcut install; this tool needs host access and is unavailable in the hosted server";

/// Tool handler shared by every MCP session.
#[derive(Debug, Clone)]
pub struct LogcutServer {
    tool_router: ToolRouter<Self>,
    host_tools: bool,
}

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

impl LogcutServer {
    pub fn new() -> Self {
        Self::with_host_tools(true)
    }

    pub fn for_hosted() -> Self {
        Self::with_host_tools(false)
    }

    pub fn with_host_tools(host_tools: bool) -> Self {
        Self {
            tool_router: Self::tool_router(),
            host_tools,
        }
    }
}

#[tool_router]
impl LogcutServer {
    #[tool(
        name = "slice_log",
        description = "Redact, deduplicate and slice a log file, piped text, or raw log string"
    )]
    async fn slice_log(
        &self,
        Parameters(request): Parameters<SliceLogRequest>,
    ) -> Result<Json<SliceReport>, String> {
        core::slice_log(request)
            .map(Json)
            .map_err(|error| error.to_string())
    }

    #[tool(
        name = "slice_test",
        description = "Strip passing test lines and slice failing tests with source context"
    )]
    async fn slice_test(
        &self,
        Parameters(request): Parameters<SliceTestArgs>,
    ) -> Result<Json<SliceTestReport>, String> {
        core::slice_test(request)
            .map(Json)
            .map_err(|error| error.to_string())
    }

    #[tool(
        name = "get_last_crash",
        description = "Read the last crash report saved by `logcut watch`"
    )]
    async fn get_last_crash(
        &self,
        Parameters(request): Parameters<LastCrashRequest>,
    ) -> Result<Json<String>, String> {
        if !self.host_tools {
            return Err(HOST_ONLY_TOOL_ERROR.to_string());
        }
        let root = request.workspace_root.as_deref().unwrap_or(".");
        core::watch::read_last_crash(Path::new(root))
            .map(Json)
            .map_err(|error| error.to_string())
    }

    #[tool(
        name = "slice_build",
        description = "Collapse compiler error cascades into root causes with source context"
    )]
    async fn slice_build(
        &self,
        Parameters(request): Parameters<SliceBuildArgs>,
    ) -> Result<Json<SliceBuildReport>, String> {
        core::slice_build(request)
            .map(Json)
            .map_err(|error| error.to_string())
    }

    #[tool(
        name = "slice_container",
        description = "Slice Docker container logs with the logcut engine"
    )]
    async fn slice_container(
        &self,
        Parameters(request): Parameters<SliceContainerRequest>,
    ) -> Result<Json<SliceReport>, String> {
        if !self.host_tools {
            return Err(HOST_ONLY_TOOL_ERROR.to_string());
        }
        core::slice_container(request)
            .await
            .map(Json)
            .map_err(|error| error.to_string())
    }

    #[tool(
        name = "slice_service",
        description = "Slice a systemd unit's journal with the logcut engine"
    )]
    async fn slice_service(
        &self,
        Parameters(request): Parameters<SliceServiceRequest>,
    ) -> Result<Json<SliceReport>, String> {
        if !self.host_tools {
            return Err(HOST_ONLY_TOOL_ERROR.to_string());
        }
        core::slice_service(request)
            .await
            .map(Json)
            .map_err(|error| error.to_string())
    }
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for LogcutServer {
    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("logcut", env!("CARGO_PKG_VERSION")))
            .with_instructions(
                "Slice noisy logs, stacktraces and error bursts down to diagnostic signal.",
            )
    }
}

/// Serve until the MCP client closes stdio. No writes to stdout except JSON-RPC.
pub async fn serve() -> anyhow::Result<()> {
    let service = LogcutServer::new()
        .serve(rmcp::transport::stdio())
        .await
        .map_err(|error| anyhow::anyhow!("MCP initialize failed: {error}"))?;
    service
        .waiting()
        .await
        .map_err(|error| anyhow::anyhow!("MCP session ended: {error}"))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::models::{LastCrashRequest, SliceContainerRequest, SliceServiceRequest};

    #[tokio::test]
    async fn stdio_tools_keep_host_access() {
        let err = LogcutServer::new()
            .slice_container(Parameters(SliceContainerRequest {
                container: "logcut-no-such-container".into(),
                tail_lines: Some(10),
                since: None,
                workspace_root: Some(".".into()),
                max_chars: Some(1000),
            }))
            .await
            .err()
            .expect("missing docker must produce an error");
        assert!(!err.contains(HOST_ONLY_TOOL_ERROR), "{err}");
    }

    #[tokio::test]
    async fn hosted_container_tool_requires_local_install() {
        let err = LogcutServer::for_hosted()
            .slice_container(Parameters(SliceContainerRequest {
                container: "anything".into(),
                tail_lines: Some(10),
                since: None,
                workspace_root: Some(".".into()),
                max_chars: Some(1000),
            }))
            .await
            .err()
            .expect("hosted container tool must refuse");
        assert!(err.contains(HOST_ONLY_TOOL_ERROR), "{err}");
    }

    #[tokio::test]
    async fn hosted_service_tool_requires_local_install() {
        let err = LogcutServer::for_hosted()
            .slice_service(Parameters(SliceServiceRequest {
                unit: "anything.service".into(),
                lines: Some(10),
                workspace_root: Some(".".into()),
                max_chars: Some(1000),
            }))
            .await
            .err()
            .expect("hosted service tool must refuse");
        assert!(err.contains(HOST_ONLY_TOOL_ERROR), "{err}");
    }

    #[tokio::test]
    async fn hosted_last_crash_tool_requires_local_install() {
        let err = LogcutServer::for_hosted()
            .get_last_crash(Parameters(LastCrashRequest {
                workspace_root: Some(".".into()),
            }))
            .await
            .err()
            .expect("hosted last-crash tool must refuse");
        assert!(err.contains(HOST_ONLY_TOOL_ERROR), "{err}");
    }
}