apoc 0.9.1

Agentic process control for LLMs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! 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.
///
/// Holding reduces model round trips while staying inside common MCP client
/// deadlines. Cache reuse is controlled by the model provider, not this wait.
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,
    }
}

tokio::task_local! {
    static EXECUTION_METADATA: (Option<String>, Option<String>);
}

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 tool.name == "codemode_execute" {
                properties.insert(
                    "purpose".into(),
                    json!({
                        "type": "string",
                        "description": "Purpose inherited by nested apoc calls when omitted."
                    }),
                );
                properties.insert(
                    "idempotency_key".into(),
                    json!({
                        "type": "string",
                        "description": "Stable request key used to derive nested mutation keys."
                    }),
                );
            }
        }
        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 metadata = (
                execution_metadata(&arguments, "purpose")?,
                execution_metadata(&arguments, "idempotency_key")?,
            );
            let response = EXECUTION_METADATA
                .scope(
                    metadata,
                    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;

fn execution_metadata(
    arguments: &serde_json::Map<String, Value>,
    name: &str,
) -> Result<Option<String>, ErrorData> {
    let Some(value) = arguments.get(name) else {
        return Ok(None);
    };
    let value = value
        .as_str()
        .filter(|value| !value.trim().is_empty() && !value.chars().any(char::is_control))
        .ok_or_else(|| {
            ErrorData::invalid_params(
                format!("{name} must be a nonempty string without control characters"),
                None,
            )
        })?;
    Ok(Some(value.trim().to_string()))
}

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 (purpose, key) = EXECUTION_METADATA
            .try_with(Clone::clone)
            .unwrap_or_default();
        let observed = DaemonClient
            .call::<Value>(
                "code.run",
                json!({
                    "code": code,
                    "timeout_ms": code_mode_wait_ms(),
                    "purpose": purpose.unwrap_or_else(|| "Code Mode execution requested over MCP.".to_string()),
                    "idempotency_key": key,
                }),
            )
            .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));
    }
}