//! Request-owned SDK completion handler; the domain future remains in its caller. use std::sync::Arc; use crank_core::{CorrelationContext, ExecutionLocale}; use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext}; use serde_json::{Map, Value}; use super::AppState; use crate::{ auth::VerifiedMachineCredential, protocol::{self, CompletionCommand, CompletionOutcome, CompletionReference, ServiceContext}, }; #[derive(Clone)] struct Scope { workspace: String, agent: String, credential: VerifiedMachineCredential, correlation: CorrelationContext, continuation: protocol::ContinuationSupport, locale: ExecutionLocale, revision: String, context: Option>, } impl Scope { fn service(&self) -> ServiceContext<'_> { ServiceContext { workspace_slug: &self.workspace, agent_slug: &self.agent, credential: &self.credential, correlation: &self.correlation, continuation: self.continuation, locale: self.locale, } } } #[derive(Clone)] struct CompletionHandler { state: Arc, #[cfg(test)] domain: Option>, } fn internal() -> ErrorData { ErrorData::internal_error("completion handler unavailable", None) } impl CompletionHandler { async fn domain(&self, scope: &Scope, command: CompletionCommand) -> CompletionOutcome { #[cfg(test)] if let Some(domain) = &self.domain { return domain.complete(command).await; } protocol::handle_completion_command(&self.state, scope.service(), &scope.revision, command) .await } fn scope(context: &RequestContext) -> Result { context .extensions .get::() .cloned() .ok_or_else(internal) } async fn execute( &self, scope: &Scope, params: CompleteRequestParams, ) -> Result { let reference = match params.r#ref { Reference::Prompt(prompt) => CompletionReference::Prompt { name: prompt.name }, Reference::Resource(resource) => CompletionReference::Resource { uri: resource.uri }, _ => { return Err(ErrorData::invalid_params( "invalid completion/complete parameters", None, )); } }; // SDK context only accepts strings; retain the original JSON for domain validation. let context = scope .context .clone() .map(|arguments| serde_json::from_value(serde_json::json!({"arguments": arguments}))) .transpose() .map_err(|_| internal())?; let command = CompletionCommand { reference, argument: crate::protocol::CompletionArgument { name: params.argument.name, value: params.argument.value, }, context, }; match self.domain(scope, command).await { CompletionOutcome::Completed { values, total, has_more, } => { let mut info = CompletionInfo::new(values).map_err(|_| internal())?; info.total = total.and_then(|v| u32::try_from(v).ok()); info.has_more = Some(has_more); Ok(CompleteResult::new(info)) } CompletionOutcome::InvalidParams(detail) => { Err(ErrorData::invalid_params(detail, None)) } CompletionOutcome::NotAvailable => Err(ErrorData::invalid_params( "the completion reference is not available", None, )), CompletionOutcome::CatalogUnavailable => Err(internal()), } } } impl ServerHandler for CompletionHandler { async fn complete( &self, request: CompleteRequestParams, context: RequestContext, ) -> Result { let scope = Self::scope(&context)?; let result = self.execute(&scope, request).await; #[cfg(test)] super::dispatch_observer::sdk_completion_handler_completed(); result } } async fn request_context( handler: &CompletionHandler, scope: Scope, ) -> Result, ErrorData> { let ping = serde_json::from_value(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"ping"})) .map_err(|_| internal())?; let (transport, receiver) = rmcp::transport::OneshotTransport::::new(ping); let revision = serde_json::from_value(Value::String(scope.revision.clone())).map_err(|_| internal())?; let info = InitializeRequestParams::new( ClientCapabilities::default(), Implementation::new("crank-completion-context", "1"), ) .with_protocol_version(revision); let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info)); let peer = running.peer().clone(); running.close().await.map_err(|_| internal())?; drop(receiver); let mut context = RequestContext::new(RequestId::Number(1), peer); context.extensions.insert(scope); Ok(context) } pub(super) async fn handle( state: &Arc, context: ServiceContext<'_>, revision: &str, command: CompletionCommand, ) -> CompletionOutcome { let (reference, context_args) = match command.reference { CompletionReference::Prompt { name } => ( Reference::for_prompt(name), command.context.and_then(|c| c.arguments), ), CompletionReference::Resource { uri } => ( Reference::for_resource(uri), command.context.and_then(|c| c.arguments), ), }; let scope = Scope { workspace: context.workspace_slug.to_owned(), agent: context.agent_slug.to_owned(), credential: context.credential.clone(), correlation: context.correlation.clone(), continuation: context.continuation, locale: context.locale, revision: revision.to_owned(), context: context_args, }; let handler = CompletionHandler { state: state.clone(), #[cfg(test)] domain: None, }; let sdk_context = match request_context(&handler, scope).await { Ok(context) => context, Err(_) => return CompletionOutcome::CatalogUnavailable, }; #[cfg(test)] super::dispatch_observer::sdk_completion_dispatch_enter(); let params = CompleteRequestParams::new( reference, ArgumentInfo::new(command.argument.name, command.argument.value), ); let result = ServerHandler::complete(&handler, params, sdk_context).await; restore(result) } fn restore(result: Result) -> CompletionOutcome { let outcome = match result { Ok(result) => CompletionOutcome::Completed { values: result.completion.values, total: result.completion.total.map(|v| v as usize), has_more: result.completion.has_more.unwrap_or(false), }, Err(error) if error.message == "the completion reference is not available" => { CompletionOutcome::NotAvailable } Err(error) if error.code == ErrorCode::INVALID_PARAMS => { CompletionOutcome::InvalidParams("invalid completion/complete parameters") } Err(_) => CompletionOutcome::CatalogUnavailable, }; #[cfg(test)] super::dispatch_observer::sdk_completion_handler_consumed(); outcome } #[cfg(test)] #[path = "../rmcp_completion_handler_tests.rs"] mod tests;