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;
struct DaemonCodeMode;
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 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
}
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);
CodeModeMcpServer::new(service)
.with_identity("apoc", env!("CARGO_PKG_VERSION"))
.with_projection(ExecutionProjection::Reduced)
.serve(rmcp::transport::io::stdio())
.await?
.waiting()
.await?;
Ok(())
}