//! Request-owned Prompts trait adapter; domain execution stays in the parent HTTP future. use std::sync::{Arc, Mutex}; use crank_core::{CorrelationContext, ExecutionLocale}; use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext}; use serde_json::Value; use super::{AppState, rmcp_prompts_projection as projection}; use crate::{ auth::VerifiedMachineCredential, protocol::{ self, ContinuationSupport, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, ServiceContext, }, }; #[derive(Clone)] struct PromptScope { workspace_slug: String, agent_slug: String, credential: VerifiedMachineCredential, correlation: CorrelationContext, continuation: ContinuationSupport, locale: ExecutionLocale, revision: String, limit: Option, } impl PromptScope { fn new(context: ServiceContext<'_>, revision: &str, limit: Option) -> Self { Self { workspace_slug: context.workspace_slug.to_owned(), agent_slug: context.agent_slug.to_owned(), credential: context.credential.clone(), correlation: context.correlation.clone(), continuation: context.continuation, locale: context.locale, revision: revision.to_owned(), limit, } } fn context(&self) -> ServiceContext<'_> { ServiceContext { workspace_slug: &self.workspace_slug, agent_slug: &self.agent_slug, credential: &self.credential, correlation: &self.correlation, continuation: self.continuation, locale: self.locale, } } } enum ReplyExtras { List(projection::Projection), Get(projection::Projection), DomainError(PromptsOutcome), } #[derive(Clone)] struct PromptHandler { state: Arc, reply: Arc>>, #[cfg(test)] domain: Option>, } fn internal() -> ErrorData { ErrorData::internal_error("prompt handler unavailable", None) } impl PromptHandler { fn new(state: &Arc) -> Self { Self { state: state.clone(), reply: Arc::new(Mutex::new(None)), #[cfg(test)] domain: None, } } async fn execute(&self, scope: &PromptScope, command: PromptsCommand) -> PromptsOutcome { #[cfg(test)] if let Some(domain) = &self.domain { return domain.prompts(command).await; } protocol::handle_prompts_command(&self.state, scope.context(), &scope.revision, command) .await } fn save(&self, extras: ReplyExtras) -> Result<(), ErrorData> { let mut slot = self.reply.lock().map_err(|_| internal())?; if slot.is_some() { return Err(internal()); } *slot = Some(extras); Ok(()) } fn take(&self) -> Option { self.reply.lock().ok()?.take() } fn scope(context: &RequestContext) -> Result { context .extensions .get::() .cloned() .ok_or_else(internal) } fn domain_error(&self, outcome: PromptsOutcome) -> ErrorData { let error = match &outcome { PromptsOutcome::Listed { .. } | PromptsOutcome::Got { .. } => return internal(), PromptsOutcome::InvalidParams(detail) => { ErrorData::invalid_params(detail.clone(), None) } PromptsOutcome::NotAvailable => { ErrorData::invalid_params("the requested prompt is not available", None) } PromptsOutcome::ArgumentsRejected { .. } => { ErrorData::invalid_params("the prompt arguments were rejected", None) } _ => internal(), }; if self.save(ReplyExtras::DomainError(outcome)).is_err() { return internal(); } error } fn project_list(&self, outcome: PromptsOutcome) -> Result { match outcome { PromptsOutcome::Listed { prompts, next_cursor, } => { let (result, extras) = projection::list(&prompts, next_cursor).map_err(|_| internal())?; self.save(ReplyExtras::List(extras))?; Ok(result) } other => Err(self.domain_error(other)), } } fn project_get(&self, outcome: PromptsOutcome) -> Result { match outcome { PromptsOutcome::Got { description, messages, } => { let (result, extras) = projection::get(description, &messages).map_err(|_| internal())?; self.save(ReplyExtras::Get(extras))?; Ok(result) } other => Err(self.domain_error(other)), } } } impl ServerHandler for PromptHandler { async fn list_prompts( &self, request: Option, context: RequestContext, ) -> Result { let scope = Self::scope(&context)?; let command = PromptsCommand::List(PromptsListCommand { cursor: request.unwrap_or_default().cursor, limit: scope.limit, }); let outcome = self.execute(&scope, command).await; let result = self.project_list(outcome); #[cfg(test)] super::dispatch_observer::sdk_prompts_list_handler_completed(); result } async fn get_prompt( &self, request: GetPromptRequestParams, context: RequestContext, ) -> Result { let scope = Self::scope(&context)?; let command = PromptsCommand::Get(PromptGetCommand { name: request.name, arguments: request.arguments, }); let outcome = self.execute(&scope, command).await; let result = self.project_get(outcome).map(Into::into); #[cfg(test)] super::dispatch_observer::sdk_prompts_get_handler_completed(); result } } /// Public SDK context seed only; close the inert service before any domain execution. /// shortcut: the closed Peer cannot send callbacks, revisit if Prompts need peer messaging. async fn request_context( handler: &PromptHandler, scope: PromptScope, ) -> 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-prompt-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) } fn restore_list( handler: &PromptHandler, result: Result, ) -> PromptsOutcome { match (result, handler.take()) { (Ok(result), Some(ReplyExtras::List(extras))) => { let cursor = result.next_cursor.clone(); match projection::serialize(result, extras, "prompts") { Ok(mut result) => match result["prompts"].take() { Value::Array(prompts) => PromptsOutcome::Listed { prompts, next_cursor: cursor, }, _ => PromptsOutcome::CatalogUnavailable, }, Err(_) => PromptsOutcome::CatalogUnavailable, } } (Err(_), Some(ReplyExtras::DomainError(error))) => error, _ => PromptsOutcome::CatalogUnavailable, } } fn restore_get( handler: &PromptHandler, result: Result, ) -> PromptsOutcome { match (result, handler.take()) { (Ok(GetPromptResponse::Complete(result)), Some(ReplyExtras::Get(extras))) => { let description = result.description.clone(); match projection::serialize(result, extras, "messages") { Ok(mut result) => match result["messages"].take() { Value::Array(messages) => PromptsOutcome::Got { description, messages, }, _ => PromptsOutcome::CatalogUnavailable, }, Err(_) => PromptsOutcome::CatalogUnavailable, } } (Err(_), Some(ReplyExtras::DomainError(error))) => error, _ => PromptsOutcome::CatalogUnavailable, } } pub(super) async fn handle( state: &Arc, context: ServiceContext<'_>, revision: &str, command: PromptsCommand, ) -> PromptsOutcome { let limit = match &command { PromptsCommand::List(list) => list.limit, _ => None, }; let handler = PromptHandler::new(state); let context = match request_context(&handler, PromptScope::new(context, revision, limit)).await { Ok(context) => context, Err(_) => return PromptsOutcome::CatalogUnavailable, }; #[cfg(test)] super::dispatch_observer::sdk_prompts_dispatch_enter(); match command { PromptsCommand::List(list) => { let result = ServerHandler::list_prompts( &handler, Some(PaginatedRequestParams::default().with_cursor(list.cursor)), context, ) .await; let outcome = restore_list(&handler, result); #[cfg(test)] super::dispatch_observer::sdk_prompts_list_handler_consumed(); outcome } PromptsCommand::Get(get) => { let mut request = GetPromptRequestParams::new(get.name); request.arguments = get.arguments; let result = ServerHandler::get_prompt(&handler, request, context).await; let outcome = restore_get(&handler, result); #[cfg(test)] super::dispatch_observer::sdk_prompts_get_handler_consumed(); outcome } } } #[cfg(test)] #[path = "../rmcp_prompts_handler_tests.rs"] mod tests;