feat(mcp): execute Prompts through request-scoped SDK handlers
CI / UI Checks (pull_request) Successful in 14s
CI / Rust Checks (pull_request) Successful in 37m47s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-11-13 07:30:32 +00:00
1 parent 5b0af84d5a
commit 5cce1b09df
11 files changed
+1070 -108

No files matched your search

@@ -64,6 +64,10 @@ pub(crate) struct CounterSet {
sdk_resources_list_result: AtomicUsize,
sdk_resources_read_result: AtomicUsize,
sdk_resource_templates_list_result: AtomicUsize,
sdk_prompts_list_handler_completed: AtomicUsize,
sdk_prompts_get_handler_completed: AtomicUsize,
sdk_prompts_list_handler_consumed: AtomicUsize,
sdk_prompts_get_handler_consumed: AtomicUsize,
sdk_prompts_dispatch: AtomicUsize,
sdk_prompts_list_result: AtomicUsize,
sdk_prompts_get_result: AtomicUsize,
@@ -95,6 +99,21 @@ pub(crate) struct CounterSet {
}
impl CounterSet {
pub(crate) fn sdk_prompts_list_handler_completed(&self) -> usize {
self.sdk_prompts_list_handler_completed
.load(Ordering::SeqCst)
}
pub(crate) fn sdk_prompts_get_handler_completed(&self) -> usize {
self.sdk_prompts_get_handler_completed
.load(Ordering::SeqCst)
}
pub(crate) fn sdk_prompts_list_handler_consumed(&self) -> usize {
self.sdk_prompts_list_handler_consumed
.load(Ordering::SeqCst)
}
pub(crate) fn sdk_prompts_get_handler_consumed(&self) -> usize {
self.sdk_prompts_get_handler_consumed.load(Ordering::SeqCst)
}
pub(crate) fn sdk_resources_list_handler_completed(&self) -> usize {
self.sdk_resources_list_handler_completed
.load(Ordering::SeqCst)
@@ -391,6 +410,26 @@ mod rmcp_resources_runtime_tests;
#[path = "../rmcp_resources_handler_runtime_tests.rs"]
mod rmcp_resources_handler_runtime_tests;
#[path = "../rmcp_prompts_handler_runtime_tests.rs"]
mod rmcp_prompts_handler_runtime_tests;
/// Mark inside the override after domain await and typed Result construction.
pub(crate) fn sdk_prompts_list_handler_completed() {
increment(|c| &c.sdk_prompts_list_handler_completed);
}
/// Mark inside the override after domain await and typed Result construction.
pub(crate) fn sdk_prompts_get_handler_completed() {
increment(|c| &c.sdk_prompts_get_handler_completed);
}
/// Mark after matching/restoring the actual trait Result in the caller.
pub(crate) fn sdk_prompts_list_handler_consumed() {
increment(|c| &c.sdk_prompts_list_handler_consumed);
}
/// Mark after matching/restoring the actual trait Result in the caller.
pub(crate) fn sdk_prompts_get_handler_consumed() {
increment(|c| &c.sdk_prompts_get_handler_consumed);
}
/// Mark only after converting a Prompts request through the real SDK typed path.
pub(crate) fn sdk_prompts_dispatch_enter() {
increment(|counters| &counters.sdk_prompts_dispatch);
+4 -80
View File
@@ -166,57 +166,13 @@ pub(super) fn resource_templates_list_result(
Ok(result)
}
// Pinned SDK serde drops unknown fields and optional nulls, including Crank template parameters.
// Treat annotations/icons as opaque too: their nested extensions are not represented by the SDK.
fn preserve_resource_fields(raw: &[Value], serialized: &mut Value, sdk_fields: &[&str]) {
for (raw, serialized) in raw
.iter()
.zip(serialized.as_array_mut().expect("SDK array"))
{
let serialized = serialized.as_object_mut().expect("SDK object");
for (key, value) in raw.as_object().expect("validated resource object") {
if !sdk_fields.contains(&key.as_str()) || value.is_null() {
serialized.insert(key.clone(), value.clone());
}
}
}
}
/// SDK pagination with lossless Crank argument schemas/defaults and optional nulls.
pub(super) fn prompts_list_result(
prompts: Vec<Value>,
next_cursor: Option<String>,
) -> Result<Value, serde_json::Error> {
let result = rmcp::model::ListPromptsResult {
prompts: prompts
.iter()
.cloned()
.map(serde_json::from_value)
.collect::<Result<Vec<rmcp::model::Prompt>, _>>()?,
next_cursor,
result_type: None,
ttl_ms: None,
cache_scope: None,
meta: None,
};
let mut result = serde_json::to_value(result)?;
preserve_resource_fields(
&prompts,
&mut result["prompts"],
&["name", "title", "description", "arguments", "_meta"],
);
for (raw, serialized) in prompts
.iter()
.zip(result["prompts"].as_array_mut().expect("SDK prompts"))
{
if let Some(arguments) = raw["arguments"].as_array() {
preserve_resource_fields(
arguments,
&mut serialized["arguments"],
&["name", "title", "description", "required"],
);
}
}
let (result, extras) = super::rmcp_prompts_projection::list(&prompts, next_cursor)?;
let result = super::rmcp_prompts_projection::serialize(result, extras, "prompts")?;
#[cfg(test)]
super::dispatch_observer::sdk_prompts_list_result_serialized();
Ok(result)
@@ -227,40 +183,8 @@ pub(super) fn prompt_get_result(
description: Option<String>,
messages: Vec<Value>,
) -> Result<Value, serde_json::Error> {
let sdk_messages = messages
.iter()
.cloned()
.map(|mut message| {
if message["role"] == "system" {
message["role"] = json!("user");
}
serde_json::from_value::<rmcp::model::PromptMessage>(message)
})
.collect::<Result<Vec<_>, _>>()?;
let mut result = rmcp::model::GetPromptResult::new(sdk_messages);
result.description = description;
// Era-specific resultType/cache projection remains at the existing dispatch boundary.
result.result_type = None;
let mut result = serde_json::to_value(result)?;
preserve_resource_fields(&messages, &mut result["messages"], &["role", "content"]);
for (raw, serialized) in messages
.iter()
.zip(result["messages"].as_array_mut().expect("SDK messages"))
{
if raw["role"] == "system" {
serialized["role"] = raw["role"].clone();
}
// Content extensions/optional nulls are opaque to the pinned SDK.
let content = serialized["content"].as_object_mut().expect("SDK content");
for (key, value) in raw["content"].as_object().expect("validated content") {
if !content.contains_key(key)
|| value.is_null()
|| matches!(key.as_str(), "annotations" | "resource")
{
content.insert(key.clone(), value.clone());
}
}
}
let (result, extras) = super::rmcp_prompts_projection::get(description, &messages)?;
let result = super::rmcp_prompts_projection::serialize(result, extras, "messages")?;
#[cfg(test)]
super::dispatch_observer::sdk_prompts_get_result_serialized();
Ok(result)
@@ -72,27 +72,7 @@ pub(super) async fn handle_prompts_command(
revision: &str,
command: crate::protocol::PromptsCommand,
) -> crate::protocol::PromptsOutcome {
use crate::protocol::{PromptGetCommand, PromptsCommand, PromptsListCommand};
let command = match command {
PromptsCommand::List(list) => {
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
PromptsCommand::List(PromptsListCommand {
cursor: params.cursor,
limit: list.limit,
})
}
PromptsCommand::Get(get) => {
let mut params = rmcp::model::GetPromptRequestParams::new(get.name);
params.arguments = get.arguments;
PromptsCommand::Get(PromptGetCommand {
name: params.name,
arguments: params.arguments,
})
}
};
#[cfg(test)]
super::dispatch_observer::sdk_prompts_dispatch_enter();
crate::protocol::handle_prompts_command(state, context, revision, command).await
super::rmcp_prompts::handle(state, context, revision, command).await
}
pub(super) async fn handle_resources_command(
@@ -0,0 +1,302 @@
//! 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<usize>,
}
impl PromptScope {
fn new(context: ServiceContext<'_>, revision: &str, limit: Option<usize>) -> 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<AppState>,
reply: Arc<Mutex<Option<ReplyExtras>>>,
#[cfg(test)]
domain: Option<Arc<tests::Domain>>,
}
fn internal() -> ErrorData {
ErrorData::internal_error("prompt handler unavailable", None)
}
impl PromptHandler {
fn new(state: &Arc<AppState>) -> 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<ReplyExtras> {
self.reply.lock().ok()?.take()
}
fn scope(context: &RequestContext<RoleServer>) -> Result<PromptScope, ErrorData> {
context
.extensions
.get::<PromptScope>()
.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<ListPromptsResult, ErrorData> {
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<GetPromptResult, ErrorData> {
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<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListPromptsResult, ErrorData> {
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<RoleServer>,
) -> Result<GetPromptResponse, ErrorData> {
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<RequestContext<RoleServer>, 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::<RoleServer>::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<ListPromptsResult, ErrorData>,
) -> 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<GetPromptResponse, ErrorData>,
) -> 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<AppState>,
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;
@@ -0,0 +1,194 @@
//! Prompt-only lossless projection: SDK fields remain sourced from the actual trait result.
use rmcp::model::{GetPromptResult, ListPromptsResult};
use serde::Serialize;
use serde_json::{Map, Value};
pub(super) fn invalid() -> serde_json::Error {
<serde_json::Error as serde::de::Error>::custom("invalid prompt projection")
}
// Store only differences from SDK serialization, not an alternate successful response.
pub(super) enum Projection {
Same,
Opaque(Value),
Object {
extras: Map<String, Value>,
absent: Vec<String>,
children: Vec<(String, Projection)>,
identity: Map<String, Value>,
},
Array(Vec<Projection>),
}
impl Projection {
fn between(raw: &Value, sdk: &Value) -> Self {
match (raw, sdk) {
(Value::Object(raw), Value::Object(sdk)) => {
let extras = raw
.iter()
.filter(|(k, _)| !sdk.contains_key(*k))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let absent = sdk
.keys()
.filter(|k| !raw.contains_key(*k))
.cloned()
.collect();
let children = raw
.iter()
.filter_map(|(k, v)| sdk.get(k).map(|s| (k.clone(), Self::between(v, s))))
.collect();
let identity = sdk
.iter()
.filter(|(k, _)| matches!(k.as_str(), "name" | "role" | "type" | "uri"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
Self::Object {
extras,
absent,
children,
identity,
}
}
(Value::Array(raw), Value::Array(sdk)) => Self::Array(
raw.iter()
.zip(sdk)
.map(|(r, s)| Self::between(r, s))
.collect(),
),
_ if raw == sdk => Self::Same,
_ => Self::Opaque(raw.clone()),
}
}
fn restore(self, sdk: &mut Value) -> Result<(), serde_json::Error> {
match self {
Self::Same => {}
Self::Opaque(value) => *sdk = value,
Self::Object {
extras,
absent,
children,
identity,
} => {
let object = sdk.as_object_mut().ok_or_else(invalid)?;
if identity.iter().any(|(k, v)| object.get(k) != Some(v)) {
return Err(invalid());
}
for (key, projection) in children {
projection.restore(object.get_mut(&key).ok_or_else(invalid)?)?;
}
for key in absent {
object.remove(&key);
}
object.extend(extras);
}
Self::Array(children) => {
let array = sdk.as_array_mut().ok_or_else(invalid)?;
if array.len() != children.len() {
return Err(invalid());
}
for (projection, item) in children.into_iter().zip(array) {
projection.restore(item)?;
}
}
}
Ok(())
}
}
fn visible(raw: &Value, fields: &[&str]) -> Result<Value, serde_json::Error> {
let raw = raw.as_object().ok_or_else(invalid)?;
Ok(Value::Object(
raw.iter()
.filter(|(key, _)| fields.contains(&key.as_str()))
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
))
}
pub(super) fn list(
prompts: &[Value],
next_cursor: Option<String>,
) -> Result<(ListPromptsResult, Projection), serde_json::Error> {
let mut typed = Vec::with_capacity(prompts.len());
for prompt in prompts {
let mut prompt = visible(
prompt,
&["name", "title", "description", "arguments", "_meta"],
)?;
if let Some(Value::Array(arguments)) = prompt.get_mut("arguments") {
for argument in arguments {
*argument = visible(argument, &["name", "title", "description", "required"])?;
}
}
typed.push(serde_json::from_value(prompt)?);
}
let result = ListPromptsResult {
prompts: typed,
next_cursor,
result_type: None,
ttl_ms: None,
cache_scope: None,
meta: None,
};
let extras = Projection::between(
&Value::Array(prompts.to_vec()),
&serde_json::to_value(&result)?["prompts"],
);
Ok((result, extras))
}
pub(super) fn get(
description: Option<String>,
messages: &[Value],
) -> Result<(GetPromptResult, Projection), serde_json::Error> {
let mut typed = Vec::with_capacity(messages.len());
for message in messages {
let mut message = visible(message, &["role", "content"])?;
if message["role"] == "system" {
message["role"] = Value::String("user".into());
}
let content = message.get_mut("content").ok_or_else(invalid)?;
// Opaque annotations and newly known SDK extensions must not add validation to Crank.
let fields: &[&str] = match content["type"].as_str() {
Some("text") => &["type", "text", "_meta"],
Some("image" | "audio") => &["type", "data", "mimeType", "_meta"],
Some("resource") => &["type", "resource", "_meta"],
Some("resource_link") => &[
"type",
"uri",
"name",
"title",
"description",
"mimeType",
"size",
"_meta",
],
_ => return Err(invalid()),
};
*content = visible(content, fields)?;
if let Some(resource) = content.get_mut("resource") {
*resource = visible(resource, &["uri", "mimeType", "text", "blob", "_meta"])?;
}
typed.push(serde_json::from_value(message)?);
}
let mut result = GetPromptResult::new(typed);
result.description = description;
result.result_type = None;
let extras = Projection::between(
&Value::Array(messages.to_vec()),
&serde_json::to_value(&result)?["messages"],
);
Ok((result, extras))
}
pub(super) fn serialize(
result: impl Serialize,
extras: Projection,
field: &str,
) -> Result<Value, serde_json::Error> {
let mut result = serde_json::to_value(result)?;
extras.restore(result.get_mut(field).ok_or_else(invalid)?)?;
Ok(result)
}