apoc 0.8.2

Agentic process control for LLMs
Documentation
//! Serving Code Mode as apoc's MCP surface.
//!
//! An MCP client gets the five Code Mode lifecycle tools rather than the tool
//! router `incurs` serves by default. That router was never an apoc design
//! choice — apoc simply never called `Cli::mcp(..)`, so it inherited
//! `McpDiscovery::Progressive`. Code Mode is what AGENTS.md already calls "the
//! only workflow language", and it is the surface that lets one program span
//! apoc's own commands and every MCP server configured on this machine without
//! returning to the model in between.
//!
//! Every call proxies to the daemon, exactly as the CLI does. The daemon owns
//! the actor pool, the durable store, and the discovered connectors; a second
//! pool inside the MCP process would contend with it for both.

use std::sync::Arc;

use async_trait::async_trait;
use incurs_codemode::{CodeModeRunOptions, CodeModeService, ExecutionState, SearchOutput};
use incurs_codemode_mcp::CodeModeMcpServer;
use rmcp::model::{
    CallToolRequestParams, CallToolResponse, CallToolResult, InitializeRequestParams,
    InitializeResult, JsonObject, ListPromptsResult, ListResourceTemplatesResult,
    ListResourcesResult, ListToolsResult, PaginatedRequestParams, ProtocolVersion, ServerInfo,
    Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData, RoleServer, ServerHandler};
use serde_json::{Map, Value, json};

use crate::daemon::DaemonClient;
use crate::model::Verbosity;

/// Shapes every lifecycle answer with the same ladder the CLI uses.
///
/// An explicit `verbosity` argument wins, then `APOC_VERBOSITY`, then the
/// `error` default. Without this the library's fixed projection returned the
/// name of every discovered connector and a summary of every call on every
/// answer, whatever level the caller asked for.
struct VerbosityProjector;

impl VerbosityProjector {
    fn level(arguments: &JsonObject) -> Result<Verbosity, String> {
        if let Some(requested) = arguments.get("verbosity") {
            return requested
                .as_str()
                .ok_or_else(|| "verbosity must be a string".to_string())
                .and_then(Verbosity::parse);
        }
        Verbosity::from_env().unwrap_or(Ok(Verbosity::DEFAULT))
    }
}

impl VerbosityProjector {
    fn arguments(&self) -> Map<String, Value> {
        let mut properties = Map::new();
        properties.insert(
            "verbosity".to_string(),
            json!({
                "type": "string",
                "enum": ["off", "error", "warn", "info", "debug", "trace"],
                "description": "Response detail. Defaults to APOC_VERBOSITY, otherwise error."
            }),
        );
        properties
    }

    fn project(&self, _tool: &str, arguments: &JsonObject, execution: Value) -> Value {
        let Ok(state) = serde_json::from_value::<ExecutionState>(execution.clone()) else {
            return execution;
        };
        match Self::level(arguments) {
            Ok(level) => crate::code::project_execution(state, level),
            // The execution already exists, so its identity must still come
            // back; the rejected level is the anomaly worth reporting.
            Err(error) => {
                let mut answer = crate::code::project_execution(state, Verbosity::DEFAULT);
                if let Some(object) = answer.as_object_mut() {
                    object.insert("verbosity_error".to_string(), json!(error));
                }
                answer
            }
        }
    }
}

struct VerbosityMcpServer(CodeModeMcpServer);

impl VerbosityMcpServer {
    fn tool(mut tool: Tool) -> Tool {
        let schema = Arc::make_mut(&mut tool.input_schema);
        if let Some(Value::Object(properties)) = schema.get_mut("properties") {
            properties.extend(VerbosityProjector.arguments());
        }
        tool
    }
}

impl ServerHandler for VerbosityMcpServer {
    fn get_info(&self) -> ServerInfo {
        self.0.get_info()
    }

    fn supported_protocol_versions(&self) -> std::borrow::Cow<'static, [ProtocolVersion]> {
        self.0.supported_protocol_versions()
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, ErrorData> {
        self.0.initialize(request, context).await
    }

    async fn list_tools(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        let mut result = self.0.list_tools(request, context).await?;
        result.tools = result.tools.into_iter().map(Self::tool).collect();
        Ok(result)
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.0.get_tool(name).map(Self::tool)
    }

    async fn list_prompts(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, ErrorData> {
        self.0.list_prompts(request, context).await
    }

    async fn list_resources(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        self.0.list_resources(request, context).await
    }

    async fn list_resource_templates(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        self.0.list_resource_templates(request, context).await
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        let operation = match request.name.as_ref() {
            "codemode_search" => "codemode_search",
            "codemode_execute" => "codemode_execute",
            "codemode_execution" => "codemode_execution",
            "codemode_decide" => "codemode_decide",
            "codemode_cancel" => "codemode_cancel",
            _ => "unknown",
        };
        let result: Result<CallToolResponse, ErrorData> = async {
            let arguments = request.arguments.clone().unwrap_or_default();
            let level = VerbosityProjector::level(&arguments)
                .map_err(|error| ErrorData::invalid_params(error, None))?;
            let execution = matches!(
                request.name.as_ref(),
                "codemode_execute" | "codemode_decide" | "codemode_cancel"
            ) || (request.name == "codemode_execution"
                && arguments.get("artifact_id").is_none_or(Value::is_null));
            let response = crate::process::with_request_verbosity(
                level.as_str().to_string(),
                self.0.call_tool(request, context),
            )
            .await?;
            if execution && let CallToolResponse::Complete(mut result) = response {
                if let Some(value) = result.structured_content.take() {
                    let projected = CallToolResult::structured(
                        VerbosityProjector.project("", &arguments, value),
                    );
                    result.content = projected.content;
                    result.structured_content = projected.structured_content;
                }
                return Ok(result.into());
            }
            Ok(response)
        }
        .await;
        if let Err(error) = &result {
            crate::error_telemetry::record(
                "mcp",
                operation,
                "MCP_TOOL_ERROR",
                None,
                None,
                &error.to_string(),
            );
        }
        result
    }
}

/// A [`CodeModeService`] backed by the apoc daemon.
struct DaemonCodeMode;

impl DaemonCodeMode {
    /// Calls one daemon method and decodes its execution state.
    async fn state(method: &str, params: Value) -> Result<ExecutionState, String> {
        DaemonClient
            .call::<Value>(method, params)
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|error| error.to_string()))
    }
}

#[async_trait]
impl CodeModeService for DaemonCodeMode {
    async fn search(&self, query: String) -> Result<SearchOutput, String> {
        DaemonClient
            .call::<Value>("code.search", json!({ "query": query }))
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|error| error.to_string()))
    }

    async fn execute(
        &self,
        code: String,
        _options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        // Wait briefly for fast results; the deadline leaves longer executions running.
        // `code.run` returns a summary, so read its ID back for the full MCP state.
        let observed = DaemonClient
            .call::<Value>(
                "code.run",
                json!({
                    "code": code,
                    "timeout_ms": 500,
                    "purpose": "Code Mode execution requested over MCP.",
                }),
            )
            .await?;
        let id = observed
            .get("id")
            .and_then(Value::as_str)
            .ok_or("the daemon started an execution without naming it")?;
        Self::state("code.get", json!({ "id": id })).await
    }

    async fn execution(&self, execution_id: String) -> Result<ExecutionState, String> {
        Self::state("code.get", json!({ "id": execution_id })).await
    }

    async fn artifact(&self, execution_id: String, artifact_id: String) -> Result<Value, String> {
        DaemonClient
            .call::<Value>(
                "code.artifact",
                json!({ "id": execution_id, "artifact_id": artifact_id }),
            )
            .await
    }

    /// Approval is not reachable: apoc never pauses.
    ///
    /// Every connector is resolved through `UnrestrictedPolicy`, which sets
    /// `requires_approval: false`, and `UnrestrictedConnector::describe` re-stamps
    /// it over any resolver a connector ships. The tool exists because the Code
    /// Mode lifecycle is a fixed five; saying so plainly is better than a silent
    /// no-op that leaves a caller waiting for a pause that cannot happen.
    async fn approve(
        &self,
        _execution_id: String,
        _seq: u64,
        _options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        Err("apoc runs every tool without pausing, so there is nothing to approve".to_string())
    }

    async fn reject(&self, _execution_id: String, _seq: u64) -> Result<ExecutionState, String> {
        Err("apoc runs every tool without pausing, so there is nothing to reject".to_string())
    }

    async fn cancel(&self, execution_id: String) -> Result<ExecutionState, String> {
        Self::state("code.cancel", json!({ "id": execution_id })).await
    }
}

/// Serves the Code Mode lifecycle over stdio until the client disconnects.
///
/// # Errors
/// Returns an error when the transport fails to start.
pub async fn serve_stdio() -> Result<(), Box<dyn std::error::Error>> {
    use rmcp::ServiceExt;

    let service: Arc<dyn CodeModeService> = Arc::new(DaemonCodeMode);
    VerbosityMcpServer(
        CodeModeMcpServer::new(service).with_identity("apoc", env!("CARGO_PKG_VERSION")),
    )
    .serve(rmcp::transport::io::stdio())
    .await?
    .waiting()
    .await?;
    Ok(())
}