use std::sync::Arc;
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
}
}
}
}
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());
}
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
}
}
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 observed = DaemonClient
.call::<Value>(
"code.run",
json!({
"code": code,
"timeout_ms": 500,
"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
}
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);
VerbosityMcpServer(
CodeModeMcpServer::new(service).with_identity("apoc", env!("CARGO_PKG_VERSION")),
)
.serve(rmcp::transport::io::stdio())
.await?
.waiting()
.await?;
Ok(())
}