apoc 0.7.4

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, ExecutionProjection};
use serde_json::{Value, json};

use crate::daemon::DaemonClient;

/// 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> {
        // `code.start` answers with an execution *summary*, which is the shape
        // apoc's own CLI prints. The Code Mode lifecycle is specified in terms
        // of the full state, so the identifier is read back through `code.get`
        // rather than reconstructing a partial state here.
        let started = DaemonClient
            .call::<Value>(
                "code.start",
                json!({
                    "code": code,
                    "purpose": "Code Mode execution requested over MCP.",
                }),
            )
            .await?;
        let id = started
            .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);
    CodeModeMcpServer::new(service)
        .with_identity("apoc", env!("CARGO_PKG_VERSION"))
        // A program's intermediate results stay inside the execution; only what
        // it returns crosses back. That projection is the reason one program
        // beats a dozen tool calls.
        .with_projection(ExecutionProjection::Reduced)
        .serve(rmcp::transport::io::stdio())
        .await?
        .waiting()
        .await?;
    Ok(())
}