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;
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),
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
}
}
}
}
const CODE_MODE_WAIT_DEFAULT: Duration = Duration::from_secs(45);
const CODE_MODE_WAIT_CEILING: Duration = Duration::from_secs(120);
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)
}
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
}
}
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 {
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> {
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
}
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
}
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
}
}
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));
}
}