apoc 0.9.0

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 std::time::Duration;

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
            }
        }
    }
}

/// How long one Code Mode lifecycle call may hold its caller.
///
/// Every MCP round trip makes the model reread its whole conversation, so an
/// answer of "still running" costs a full turn and tells the caller nothing.
/// A call therefore holds until the program finishes and answers the moment it
/// does. The default stays inside common MCP client tool deadlines, and the
/// ceiling stays far inside prompt-cache lifetimes, so a wait never expires the
/// conversation it exists to save.
const CODE_MODE_WAIT_DEFAULT: Duration = Duration::from_secs(45);
const CODE_MODE_WAIT_CEILING: Duration = Duration::from_secs(120);

/// Resolves the wait from `APOC_CODE_MODE_WAIT_MS`, capped at the ceiling.
fn code_mode_wait(configured: Option<&str>) -> Duration {
    configured
        .and_then(|value| value.trim().parse::<u64>().ok())
        .map(Duration::from_millis)
        .map_or(CODE_MODE_WAIT_DEFAULT, |wait| {
            wait.min(CODE_MODE_WAIT_CEILING)
        })
}

fn code_mode_wait_ms() -> u64 {
    let wait = code_mode_wait(std::env::var("APOC_CODE_MODE_WAIT_MS").ok().as_deref());
    u64::try_from(wait.as_millis()).unwrap_or(u64::MAX)
}

/// Tells the model, where it chooses its next call, that a call already waits.
fn waiting_note(tool: &str) -> Option<&'static str> {
    match tool {
        "codemode_execute" => Some(
            "Holds until the program finishes and returns its result at once, waiting at most the Code Mode wait ceiling (45 s by default). A running answer means the program outlived the ceiling.",
        ),
        "codemode_execution" => Some(
            "On a running execution, holds until it finishes or the Code Mode wait ceiling passes, so one call replaces a polling loop. Never call it repeatedly to wait.",
        ),
        _ => None,
    }
}

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());
        }
        if let Some(note) = waiting_note(&tool.name) {
            let description = match tool.description.as_deref() {
                Some(base) if !base.is_empty() => format!("{base} {note}"),
                _ => note.to_string(),
            };
            tool.description = Some(description.into());
        }
        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> {
        // Hold until the program finishes, up to the wait ceiling; 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": code_mode_wait_ms(),
                    "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
    }

    /// A finished execution answers at once; a running one is waited on.
    async fn execution(&self, execution_id: String) -> Result<ExecutionState, String> {
        Self::state(
            "code.wait",
            json!({ "id": execution_id, "timeout_ms": code_mode_wait_ms() }),
        )
        .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(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn code_mode_wait_defaults_and_never_exceeds_its_ceiling() {
        assert_eq!(code_mode_wait(None), Duration::from_secs(45));
        assert_eq!(
            code_mode_wait(Some("not-a-number")),
            Duration::from_secs(45)
        );
        assert_eq!(code_mode_wait(Some("250")), Duration::from_millis(250));
        assert_eq!(code_mode_wait(Some("0")), Duration::ZERO);
        assert_eq!(code_mode_wait(Some("600000")), Duration::from_secs(120));
    }
}