Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b39e4a3470 | ||
|
|
3b30aad28e | ||
|
|
5611e81579 | ||
|
|
b769a2ed2e |
No files matched your search
@@ -34,6 +34,7 @@ pub(crate) mod lifecycle;
|
||||
mod metrics;
|
||||
mod request;
|
||||
mod response;
|
||||
mod rmcp_completion;
|
||||
mod rmcp_dispatch;
|
||||
#[cfg(test)]
|
||||
mod rmcp_http;
|
||||
@@ -49,6 +50,8 @@ mod rmcp_resources_projection;
|
||||
mod rmcp_session_tests;
|
||||
#[cfg(test)]
|
||||
mod rmcp_tools;
|
||||
mod rmcp_tools_projection;
|
||||
mod rmcp_tools_runtime;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_tools_tests.rs"]
|
||||
mod rmcp_tools_tests;
|
||||
|
||||
@@ -17,8 +17,8 @@ use crate::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
declared_mcp_method, discover_result, validate_modern_request_name,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, declared_mcp_method,
|
||||
discover_result, validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
@@ -38,7 +38,7 @@ use time::OffsetDateTime;
|
||||
use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, tools_list_result,
|
||||
resource_templates_list_result, resources_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
use crate::protocol::ResourceTemplatesListError;
|
||||
@@ -170,36 +170,7 @@ pub(super) async fn handle_modern_request(
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||
}
|
||||
// A list command never produces a call outcome; it is answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||
message,
|
||||
"unexpected shared tools outcome for a tools/list",
|
||||
),
|
||||
}
|
||||
super::response::sdk_tools_response(message, response_mode, version, outcome)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
|
||||
@@ -54,6 +54,10 @@ pub(crate) struct CounterSet {
|
||||
sdk_tools_dispatch: AtomicUsize,
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
sdk_tools_list_handler_completed: AtomicUsize,
|
||||
sdk_tools_list_handler_consumed: AtomicUsize,
|
||||
sdk_tools_call_handler_completed: AtomicUsize,
|
||||
sdk_tools_call_handler_consumed: AtomicUsize,
|
||||
sdk_resources_dispatch: AtomicUsize,
|
||||
sdk_resources_list_handler_completed: AtomicUsize,
|
||||
sdk_resources_read_handler_completed: AtomicUsize,
|
||||
@@ -73,6 +77,8 @@ pub(crate) struct CounterSet {
|
||||
sdk_prompts_get_result: AtomicUsize,
|
||||
sdk_completion_dispatch: AtomicUsize,
|
||||
sdk_completion_result: AtomicUsize,
|
||||
sdk_completion_handler_completed: AtomicUsize,
|
||||
sdk_completion_handler_consumed: AtomicUsize,
|
||||
sdk_logging_dispatch: AtomicUsize,
|
||||
sdk_logging_level: AtomicUsize,
|
||||
sdk_logging_notification: AtomicUsize,
|
||||
@@ -99,6 +105,18 @@ pub(crate) struct CounterSet {
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_tools_list_handler_completed(&self) -> usize {
|
||||
self.sdk_tools_list_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_tools_list_handler_consumed(&self) -> usize {
|
||||
self.sdk_tools_list_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_tools_call_handler_completed(&self) -> usize {
|
||||
self.sdk_tools_call_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_tools_call_handler_consumed(&self) -> usize {
|
||||
self.sdk_tools_call_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_list_handler_completed(&self) -> usize {
|
||||
self.sdk_prompts_list_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
@@ -219,6 +237,12 @@ impl CounterSet {
|
||||
pub(crate) fn sdk_completion_result(&self) -> usize {
|
||||
self.sdk_completion_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_completion_handler_completed(&self) -> usize {
|
||||
self.sdk_completion_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_completion_handler_consumed(&self) -> usize {
|
||||
self.sdk_completion_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_dispatch(&self) -> usize {
|
||||
self.sdk_prompts_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -358,6 +382,23 @@ pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
/// Mark after the SDK Tools handler awaits the domain operation and builds its typed result.
|
||||
pub(crate) fn sdk_tools_list_handler_completed() {
|
||||
increment(|counters| &counters.sdk_tools_list_handler_completed);
|
||||
}
|
||||
/// Mark only after the caller consumes the actual SDK handler result.
|
||||
pub(crate) fn sdk_tools_list_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_tools_list_handler_consumed);
|
||||
}
|
||||
/// Mark after the SDK Tools handler awaits the domain operation and builds its typed result.
|
||||
pub(crate) fn sdk_tools_call_handler_completed() {
|
||||
increment(|counters| &counters.sdk_tools_call_handler_completed);
|
||||
}
|
||||
/// Mark only after the caller consumes the actual SDK handler result.
|
||||
pub(crate) fn sdk_tools_call_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_tools_call_handler_consumed);
|
||||
}
|
||||
|
||||
/// Mark inside the ServerHandler override after domain await and typed result/error construction.
|
||||
pub(crate) fn sdk_resources_list_handler_completed() {
|
||||
increment(|c| &c.sdk_resources_list_handler_completed);
|
||||
@@ -459,10 +500,24 @@ pub(crate) fn sdk_completion_result_serialized() {
|
||||
increment(|counters| &counters.sdk_completion_result);
|
||||
}
|
||||
|
||||
/// Mark inside the ServerHandler override after domain await and typed Result construction.
|
||||
pub(crate) fn sdk_completion_handler_completed() {
|
||||
increment(|counters| &counters.sdk_completion_handler_completed);
|
||||
}
|
||||
|
||||
/// Mark in the caller only after matching and consuming the actual trait Result.
|
||||
pub(crate) fn sdk_completion_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_completion_handler_consumed);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_runtime_tests.rs"]
|
||||
mod rmcp_completion_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_handler_runtime_tests.rs"]
|
||||
mod rmcp_completion_handler_runtime_tests;
|
||||
|
||||
/// Mark only after constructing the real SDK typed legacy logging request.
|
||||
pub(crate) fn sdk_logging_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_logging_dispatch);
|
||||
|
||||
@@ -22,7 +22,6 @@ use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
@@ -36,7 +35,7 @@ use crate::{
|
||||
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_logging_command,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, handle_logging_command,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -159,36 +158,12 @@ pub(super) async fn handle_legacy_request(
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, &session.protocol_version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||
}
|
||||
// A list command never produces a call outcome; it is answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||
message,
|
||||
"unexpected shared tools outcome for a tools/list",
|
||||
),
|
||||
}
|
||||
super::response::sdk_tools_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
outcome,
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
|
||||
@@ -41,11 +41,11 @@ use tokio::sync::{mpsc, watch};
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
use super::{
|
||||
AppState,
|
||||
response::{ToolCommandPayload, tool_command_payload, tool_command_response},
|
||||
response::{ToolCommandPayload, sdk_tools_payload, sdk_tools_response},
|
||||
};
|
||||
use crate::{
|
||||
jsonrpc::request_id,
|
||||
protocol::{ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsOutcome},
|
||||
protocol::{ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand},
|
||||
transport::{ResponseMode, sse_response},
|
||||
};
|
||||
|
||||
@@ -393,7 +393,7 @@ pub(crate) async fn run_tool_call(
|
||||
});
|
||||
|
||||
let message = wire.message.clone();
|
||||
let correlation = request.correlation.clone();
|
||||
|
||||
let protocol_version = wire.protocol_version.clone();
|
||||
let response_mode = wire.response_mode;
|
||||
|
||||
@@ -411,13 +411,7 @@ pub(crate) async fn run_tool_call(
|
||||
outcome = &mut call => outcome,
|
||||
_ = lifecycle.cancelled() => return cancelled_response(),
|
||||
};
|
||||
return tool_command_response(
|
||||
&message,
|
||||
response_mode,
|
||||
&protocol_version,
|
||||
&correlation,
|
||||
outcome,
|
||||
);
|
||||
return sdk_tools_response(&message, response_mode, &protocol_version, outcome);
|
||||
};
|
||||
|
||||
debug_assert!(matches!(response_mode, ResponseMode::Sse));
|
||||
@@ -430,7 +424,6 @@ pub(crate) async fn run_tool_call(
|
||||
token,
|
||||
message,
|
||||
protocol_version: protocol_version.clone(),
|
||||
correlation,
|
||||
pending: VecDeque::new(),
|
||||
finished: false,
|
||||
logging: crate::protocol::carry_scope(),
|
||||
@@ -451,7 +444,7 @@ async fn call_future(
|
||||
request: ToolCallRequest,
|
||||
lifecycle: ToolCallLifecycle,
|
||||
command: ToolCallCommand,
|
||||
) -> ToolsOutcome {
|
||||
) -> super::rmcp_tools_runtime::Outcome {
|
||||
handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
@@ -478,13 +471,12 @@ fn cancelled_response() -> Response {
|
||||
}
|
||||
|
||||
struct CallStream {
|
||||
call: Pin<Box<dyn Future<Output = ToolsOutcome> + Send>>,
|
||||
call: Pin<Box<dyn Future<Output = super::rmcp_tools_runtime::Outcome> + Send>>,
|
||||
events: mpsc::Receiver<ProgressEvent>,
|
||||
cancel: CancelSignal,
|
||||
token: ProgressToken,
|
||||
message: Value,
|
||||
protocol_version: String,
|
||||
correlation: CorrelationContext,
|
||||
pending: VecDeque<Event>,
|
||||
finished: bool,
|
||||
/// The request's logging context, so the terminal event of the stream is projected exactly as the
|
||||
@@ -496,7 +488,7 @@ struct CallStream {
|
||||
|
||||
enum Step {
|
||||
Progress(ProgressEvent),
|
||||
Outcome(ToolsOutcome),
|
||||
Outcome(super::rmcp_tools_runtime::Outcome),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
@@ -541,12 +533,7 @@ async fn next_event_in_scope(
|
||||
}
|
||||
Step::Outcome(outcome) => {
|
||||
call.finished = true;
|
||||
let payload = match tool_command_payload(
|
||||
&call.message,
|
||||
&call.protocol_version,
|
||||
&call.correlation,
|
||||
outcome,
|
||||
) {
|
||||
let payload = match sdk_tools_payload(&call.message, &call.protocol_version, outcome) {
|
||||
ToolCommandPayload::Ok(payload) => payload,
|
||||
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use rmcp::model::{CacheScope, CallToolResult, ContentBlock, ListToolsResult, ResultType, Tool};
|
||||
#[cfg(test)]
|
||||
use rmcp::model::{CacheScope, ListToolsResult, Tool};
|
||||
use rmcp::model::{CallToolResult, ContentBlock, ResultType};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
@@ -9,8 +11,11 @@ use crate::{
|
||||
};
|
||||
|
||||
use crate::jsonrpc::jsonrpc_error;
|
||||
#[cfg(test)]
|
||||
use crate::protocol::{ToolCallOutcome, ToolsOutcome};
|
||||
#[cfg(test)]
|
||||
use crate::tool_error::{control_tool_error_contract, execution_locale};
|
||||
#[cfg(test)]
|
||||
use crank_core::CorrelationContext;
|
||||
|
||||
pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
||||
@@ -25,6 +30,7 @@ pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
||||
|
||||
/// The era-neutral success payload of one `tools/call` (Story 3.4: the streamed response needs the
|
||||
/// payload itself, because the terminal response is the last event of the request's stream).
|
||||
#[cfg(test)]
|
||||
pub(super) fn success_tool_payload(
|
||||
message: &Value,
|
||||
protocol_version: &str,
|
||||
@@ -49,6 +55,7 @@ pub(crate) fn tool_error_response(
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn tool_error_payload(
|
||||
message: &Value,
|
||||
protocol_version: &str,
|
||||
@@ -79,6 +86,7 @@ fn call_result_payload(message: &Value, version: &str, mut result: CallToolResul
|
||||
jsonrpc_result(request_id(message), result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn sdk_tools_list_result(
|
||||
tools: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
@@ -95,6 +103,7 @@ pub(super) fn sdk_tools_list_result(
|
||||
}
|
||||
|
||||
/// Serialize the SDK model, preserving catalog extensions that pinned Tool serde cannot represent.
|
||||
#[cfg(test)]
|
||||
pub(super) fn tools_list_result(
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
@@ -256,6 +265,7 @@ pub(super) enum ToolCommandPayload {
|
||||
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
|
||||
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
|
||||
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
|
||||
#[cfg(test)]
|
||||
pub(super) fn tool_command_payload(
|
||||
message: &Value,
|
||||
protocol_version: &str,
|
||||
@@ -300,22 +310,53 @@ pub(super) fn tool_command_payload(
|
||||
}
|
||||
}
|
||||
|
||||
/// The single-response form of [`tool_command_payload`].
|
||||
pub(super) fn tool_command_response(
|
||||
pub(super) fn sdk_tools_payload(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
correlation: &CorrelationContext,
|
||||
outcome: ToolsOutcome,
|
||||
version: &str,
|
||||
outcome: super::rmcp_tools_runtime::Outcome,
|
||||
) -> ToolCommandPayload {
|
||||
use super::rmcp_tools_runtime::Outcome;
|
||||
let payload = match outcome {
|
||||
Outcome::List { result, extras } => {
|
||||
match super::rmcp_tools_projection::serialize_list(result, extras, version) {
|
||||
Ok(result) => jsonrpc_result(request_id(message), result),
|
||||
Err(_) => return ToolCommandPayload::Internal("invalid tool catalog"),
|
||||
}
|
||||
}
|
||||
Outcome::Call(result) => call_result_payload(message, version, result),
|
||||
Outcome::Error(error) => sdk_tools_error_payload(message, error),
|
||||
};
|
||||
ToolCommandPayload::Ok(payload)
|
||||
}
|
||||
pub(super) fn sdk_tools_error_payload(message: &Value, error: rmcp::ErrorData) -> Value {
|
||||
let mut payload = jsonrpc_error(
|
||||
request_id(message),
|
||||
i64::from(error.code.0),
|
||||
error.message.to_string(),
|
||||
);
|
||||
if let Some(data) = error.data {
|
||||
payload["error"]["data"] = data;
|
||||
}
|
||||
payload
|
||||
}
|
||||
pub(super) fn sdk_tools_response(
|
||||
message: &Value,
|
||||
mode: ResponseMode,
|
||||
version: &str,
|
||||
outcome: super::rmcp_tools_runtime::Outcome,
|
||||
) -> Response {
|
||||
match tool_command_payload(message, protocol_version, correlation, outcome) {
|
||||
ToolCommandPayload::Ok(payload) => transport_response(
|
||||
StatusCode::OK,
|
||||
let internal = matches!(&outcome, super::rmcp_tools_runtime::Outcome::Error(error) if error.code == rmcp::model::ErrorCode::INTERNAL_ERROR);
|
||||
match sdk_tools_payload(message, version, outcome) {
|
||||
ToolCommandPayload::Ok(payload) if internal => transport_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
payload,
|
||||
response_mode,
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
),
|
||||
ToolCommandPayload::Ok(payload) => {
|
||||
transport_response(StatusCode::OK, payload, mode, None, Some(version))
|
||||
}
|
||||
ToolCommandPayload::Internal(detail) => internal_jsonrpc_error(message, detail),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! 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<Map<String, Value>>,
|
||||
}
|
||||
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<AppState>,
|
||||
#[cfg(test)]
|
||||
domain: Option<Arc<tests::Domain>>,
|
||||
}
|
||||
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<RoleServer>) -> Result<Scope, ErrorData> {
|
||||
context
|
||||
.extensions
|
||||
.get::<Scope>()
|
||||
.cloned()
|
||||
.ok_or_else(internal)
|
||||
}
|
||||
async fn execute(
|
||||
&self,
|
||||
scope: &Scope,
|
||||
params: CompleteRequestParams,
|
||||
) -> Result<CompleteResult, ErrorData> {
|
||||
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<RoleServer>,
|
||||
) -> Result<CompleteResult, ErrorData> {
|
||||
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<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-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<AppState>,
|
||||
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<CompleteResult, ErrorData>) -> 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;
|
||||
@@ -2,68 +2,18 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle};
|
||||
use crate::protocol::{
|
||||
ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
};
|
||||
|
||||
// Crank extensions are not SDK fields and must survive the typed request boundary unchanged.
|
||||
enum SdkToolsCommand {
|
||||
List {
|
||||
params: PaginatedRequestParams,
|
||||
limit: Option<usize>,
|
||||
},
|
||||
Call {
|
||||
params: CallToolRequestParams,
|
||||
confirmation_token: Option<String>,
|
||||
},
|
||||
}
|
||||
use crate::protocol::{ServiceContext, ToolsCommand};
|
||||
|
||||
pub(super) async fn handle_tools_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
command: ToolsCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> ToolsOutcome {
|
||||
let request = match command {
|
||||
ToolsCommand::List(list) => SdkToolsCommand::List {
|
||||
params: PaginatedRequestParams::default().with_cursor(list.cursor),
|
||||
limit: list.limit,
|
||||
},
|
||||
ToolsCommand::Call(call) => {
|
||||
let Value::Object(arguments) = call.arguments else {
|
||||
return ToolsOutcome::Call(ToolCallOutcome::InvalidParams(
|
||||
"tool arguments must be an object".to_owned(),
|
||||
));
|
||||
};
|
||||
SdkToolsCommand::Call {
|
||||
params: CallToolRequestParams::new(call.tool_name).with_arguments(arguments),
|
||||
confirmation_token: call.confirmation_token,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_dispatch_enter();
|
||||
|
||||
let command = match request {
|
||||
SdkToolsCommand::List { params, limit } => ToolsCommand::List(ToolsListCommand {
|
||||
cursor: params.cursor,
|
||||
limit,
|
||||
}),
|
||||
SdkToolsCommand::Call {
|
||||
params,
|
||||
confirmation_token,
|
||||
} => ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: params.name.into_owned(),
|
||||
arguments: Value::Object(params.arguments.unwrap_or_default()),
|
||||
confirmation_token,
|
||||
}),
|
||||
};
|
||||
crate::protocol::handle_tools_command(state, context, command, lifecycle).await
|
||||
) -> super::rmcp_tools_runtime::Outcome {
|
||||
super::rmcp_tools_runtime::handle(state, context, command, lifecycle).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_prompts_command(
|
||||
@@ -99,37 +49,5 @@ pub(super) async fn handle_completion_command(
|
||||
revision: &str,
|
||||
command: crate::protocol::CompletionCommand,
|
||||
) -> crate::protocol::CompletionOutcome {
|
||||
use crate::protocol::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
};
|
||||
use rmcp::model::{ArgumentInfo, CompleteRequestParams, Reference};
|
||||
|
||||
let reference = match command.reference {
|
||||
CompletionReference::Prompt { name } => Reference::for_prompt(name),
|
||||
CompletionReference::Resource { uri } => Reference::for_resource(uri),
|
||||
};
|
||||
let params = CompleteRequestParams::new(
|
||||
reference,
|
||||
ArgumentInfo::new(command.argument.name, command.argument.value),
|
||||
);
|
||||
// SDK context only supports strings; retain arbitrary JSON unchanged for domain validation.
|
||||
let context_arguments = command.context;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_dispatch_enter();
|
||||
let reference = match params.r#ref {
|
||||
Reference::Prompt(reference) => CompletionReference::Prompt {
|
||||
name: reference.name,
|
||||
},
|
||||
Reference::Resource(reference) => CompletionReference::Resource { uri: reference.uri },
|
||||
_ => return CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
|
||||
};
|
||||
let command = CompletionCommand {
|
||||
reference,
|
||||
argument: CompletionArgument {
|
||||
name: params.argument.name,
|
||||
value: params.argument.value,
|
||||
},
|
||||
context: context_arguments,
|
||||
};
|
||||
crate::protocol::handle_completion_command(state, context, revision, command).await
|
||||
super::rmcp_completion::handle(state, context, revision, command).await
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Lossless catalog extras only; represented SDK fields remain authoritative.
|
||||
use rmcp::{ErrorData, model::*};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) type Extras = Vec<Map<String, Value>>;
|
||||
pub(super) enum Outcome {
|
||||
List {
|
||||
result: ListToolsResult,
|
||||
extras: Extras,
|
||||
},
|
||||
Call(CallToolResult),
|
||||
Error(ErrorData),
|
||||
}
|
||||
pub(super) fn internal() -> ErrorData {
|
||||
ErrorData::internal_error("internal server error", None)
|
||||
}
|
||||
pub(super) fn list(
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<(ListToolsResult, Extras), ErrorData> {
|
||||
let mut extras = Vec::with_capacity(tools.len());
|
||||
let mut typed = Vec::with_capacity(tools.len());
|
||||
for tool in tools {
|
||||
let mut raw = tool.as_object().cloned().ok_or_else(internal)?;
|
||||
let mut extra = Map::new();
|
||||
for key in raw.keys().cloned().collect::<Vec<_>>() {
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"name" | "title" | "description" | "inputSchema" | "outputSchema" | "_meta"
|
||||
) || raw[&key].is_null()
|
||||
{
|
||||
extra.insert(key.clone(), raw.remove(&key).expect("existing field"));
|
||||
}
|
||||
}
|
||||
typed.push(serde_json::from_value(Value::Object(raw)).map_err(|_| internal())?);
|
||||
extras.push(extra);
|
||||
}
|
||||
Ok((
|
||||
ListToolsResult {
|
||||
tools: typed,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
},
|
||||
extras,
|
||||
))
|
||||
}
|
||||
pub(super) fn consume_list(result: Result<ListToolsResult, ErrorData>, extras: Extras) -> Outcome {
|
||||
match result {
|
||||
Ok(result) => Outcome::List { result, extras },
|
||||
Err(error) => Outcome::Error(error),
|
||||
}
|
||||
}
|
||||
pub(super) fn serialize_list(
|
||||
mut result: ListToolsResult,
|
||||
extras: Extras,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
result.result_type = modern.then_some(ResultType::COMPLETE);
|
||||
result.ttl_ms = modern.then_some(0);
|
||||
result.cache_scope = modern.then_some(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
for (tool, extras) in result["tools"]
|
||||
.as_array_mut()
|
||||
.expect("SDK tools array")
|
||||
.iter_mut()
|
||||
.zip(extras)
|
||||
{
|
||||
let tool = tool.as_object_mut().expect("SDK Tool object");
|
||||
for (key, value) in extras {
|
||||
tool.entry(key).or_insert(value);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_list_result_serialized();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn consume_call(result: Result<CallToolResponse, ErrorData>) -> Outcome {
|
||||
match result {
|
||||
Ok(CallToolResponse::Complete(result)) => Outcome::Call(result),
|
||||
Ok(_) => Outcome::Error(internal()),
|
||||
Err(error) => Outcome::Error(error),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Request-owned Tools trait execution. The caller retains admission and lifecycle ownership.
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle, rmcp_tools_projection as projection};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
protocol::{self, *},
|
||||
};
|
||||
use crank_core::{CorrelationContext, ExecutionLocale};
|
||||
pub(super) use projection::Outcome;
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use serde_json::Value;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Scope {
|
||||
workspace: String,
|
||||
agent: String,
|
||||
credential: VerifiedMachineCredential,
|
||||
correlation: CorrelationContext,
|
||||
continuation: ContinuationSupport,
|
||||
locale: ExecutionLocale,
|
||||
limit: Option<usize>,
|
||||
confirmation: Option<String>,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
}
|
||||
impl Scope {
|
||||
fn context(&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 Handler {
|
||||
state: Arc<AppState>,
|
||||
extras: Arc<Mutex<projection::Extras>>,
|
||||
#[cfg(test)]
|
||||
domain: Option<Arc<tests::Domain>>,
|
||||
}
|
||||
impl Handler {
|
||||
fn new(state: &Arc<AppState>) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
extras: Arc::new(Mutex::new(Vec::new())),
|
||||
#[cfg(test)]
|
||||
domain: None,
|
||||
}
|
||||
}
|
||||
async fn execute(&self, scope: &Scope, command: ToolsCommand) -> ToolsOutcome {
|
||||
#[cfg(test)]
|
||||
if let Some(domain) = &self.domain {
|
||||
return domain.execute(scope, command).await;
|
||||
}
|
||||
protocol::handle_tools_command(
|
||||
&self.state,
|
||||
scope.context(),
|
||||
command,
|
||||
scope.lifecycle.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
fn scope(context: &RequestContext<RoleServer>) -> Result<Scope, ErrorData> {
|
||||
context
|
||||
.extensions
|
||||
.get::<Scope>()
|
||||
.cloned()
|
||||
.ok_or_else(projection::internal)
|
||||
}
|
||||
fn take_extras(&self) -> projection::Extras {
|
||||
self.extras
|
||||
.lock()
|
||||
.expect("request-local extras")
|
||||
.drain(..)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
impl ServerHandler for Handler {
|
||||
async fn list_tools(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<ListToolsResult, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let outcome = self
|
||||
.execute(
|
||||
&scope,
|
||||
ToolsCommand::List(ToolsListCommand {
|
||||
cursor: request.unwrap_or_default().cursor,
|
||||
limit: scope.limit,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let result = match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => projection::list(tools, next_cursor)
|
||||
.and_then(|(result, extras)| {
|
||||
*self.extras.lock().map_err(|_| projection::internal())? = extras;
|
||||
Ok(result)
|
||||
}),
|
||||
ToolsOutcome::InvalidParams(detail) => Err(ErrorData::invalid_params(detail, None)),
|
||||
_ => Err(projection::internal()),
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_list_handler_completed();
|
||||
result
|
||||
}
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResponse, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let outcome = self
|
||||
.execute(
|
||||
&scope,
|
||||
ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: request.name.into_owned(),
|
||||
arguments: Value::Object(request.arguments.unwrap_or_default()),
|
||||
confirmation_token: scope.confirmation.clone(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let result = match outcome {
|
||||
ToolsOutcome::Call(
|
||||
ToolCallOutcome::Completed(output) | ToolCallOutcome::ApprovalPending(output),
|
||||
) => Ok(super::response::sdk_success_tool_result(output).into()),
|
||||
ToolsOutcome::Call(ToolCallOutcome::Error(error)) => {
|
||||
Ok(super::response::sdk_error_tool_result(error).into())
|
||||
}
|
||||
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(error)) => {
|
||||
Ok(super::response::sdk_error_tool_result(
|
||||
crate::tool_error::control_tool_error_contract(
|
||||
error,
|
||||
scope.correlation.request_id().as_str(),
|
||||
scope.correlation.trace_id().as_str(),
|
||||
scope.locale,
|
||||
),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail))
|
||||
| ToolsOutcome::InvalidParams(detail) => Err(ErrorData::invalid_params(detail, None)),
|
||||
_ => Err(projection::internal()),
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_call_handler_completed();
|
||||
result
|
||||
}
|
||||
}
|
||||
// Context seed only: close the inert transport before running domain code. No Peer callbacks.
|
||||
async fn request_context(
|
||||
handler: &Handler,
|
||||
scope: Scope,
|
||||
) -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping = serde_json::from_value(serde_json::json!({"jsonrpc":"2.0","id":1,"method":"ping"}))
|
||||
.map_err(|_| projection::internal())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-tools-context", "1"),
|
||||
)
|
||||
.with_protocol_version(ProtocolVersion::V_2025_11_25);
|
||||
let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running.close().await.map_err(|_| projection::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<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
command: ToolsCommand,
|
||||
lifecycle: Option<ToolCallLifecycle>,
|
||||
) -> Outcome {
|
||||
let (limit, confirmation) = match &command {
|
||||
ToolsCommand::List(list) => (list.limit, None),
|
||||
ToolsCommand::Call(call) => (None, call.confirmation_token.clone()),
|
||||
};
|
||||
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,
|
||||
limit,
|
||||
confirmation,
|
||||
lifecycle,
|
||||
};
|
||||
let handler = Handler::new(state);
|
||||
let context = match request_context(&handler, scope).await {
|
||||
Ok(context) => context,
|
||||
Err(error) => return Outcome::Error(error),
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_dispatch_enter();
|
||||
match command {
|
||||
ToolsCommand::List(list) => {
|
||||
let result = ServerHandler::list_tools(
|
||||
&handler,
|
||||
Some(PaginatedRequestParams::default().with_cursor(list.cursor)),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = projection::consume_list(result, handler.take_extras());
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_list_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
ToolsCommand::Call(call) => {
|
||||
let Value::Object(arguments) = call.arguments else {
|
||||
return Outcome::Error(ErrorData::invalid_params(
|
||||
"tool arguments must be an object",
|
||||
None,
|
||||
));
|
||||
};
|
||||
let result = ServerHandler::call_tool(
|
||||
&handler,
|
||||
CallToolRequestParams::new(call.tool_name).with_arguments(arguments),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = projection::consume_call(result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_call_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_tools_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Completion actual ServerHandler execution/consumption observer oracle.
|
||||
use super::{CounterSet, observe};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[
|
||||
c.sdk_completion_handler_completed(),
|
||||
c.sdk_completion_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn delta(c: &CounterSet, before: [usize; 2]) -> ([usize; 2], [usize; 2]) {
|
||||
let after = counts(c);
|
||||
(std::array::from_fn(|i| after[i] - before[i]), [1, 1])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_handler_observer_positive_control() {
|
||||
use super::{sdk_completion_handler_completed, sdk_completion_handler_consumed};
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
sdk_completion_handler_completed();
|
||||
sdk_completion_handler_consumed();
|
||||
assert_eq!(counts(&counters), [0, 0], "out-of-scope markers are no-ops");
|
||||
observe(counters.clone(), async {
|
||||
sdk_completion_handler_completed();
|
||||
sdk_completion_handler_consumed();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&counters), [1, 1]);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Real trait execution, lossless request context, typed result consumption and drop ownership.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Domain {
|
||||
outcome: Mutex<Option<CompletionOutcome>>,
|
||||
calls: AtomicUsize,
|
||||
pending: bool,
|
||||
dropped: AtomicBool,
|
||||
finished: AtomicBool,
|
||||
}
|
||||
struct DropWitness<'a>(&'a AtomicBool);
|
||||
impl Drop for DropWitness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Domain {
|
||||
pub(super) async fn complete(&self, command: CompletionCommand) -> CompletionOutcome {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
assert!(
|
||||
matches!(command.reference, CompletionReference::Resource { uri } if uri == "crank://bound/{region}")
|
||||
);
|
||||
assert_eq!(command.argument.name, "region");
|
||||
assert_eq!(command.argument.value, "e");
|
||||
assert_eq!(command.context.unwrap().arguments.unwrap(), args());
|
||||
let _guard = DropWitness(&self.dropped);
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
self.finished.store(true, SeqCst);
|
||||
self.outcome
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("single domain execution")
|
||||
}
|
||||
}
|
||||
fn args() -> Map<String, Value> {
|
||||
json!({"number":42,"bool":true,"null":null,"array":["x"],"object":{"a":1}})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
fn scope(revision: &str) -> Scope {
|
||||
Scope {
|
||||
workspace: "workspace".into(),
|
||||
agent: "agent".into(),
|
||||
credential: VerifiedMachineCredential {
|
||||
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
scopes: vec![crank_core::PlatformApiKeyScope::Read],
|
||||
platform_api_key_id: Some("key".into()),
|
||||
},
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: protocol::ContinuationSupport::from_supported(false),
|
||||
locale: ExecutionLocale::En,
|
||||
revision: revision.into(),
|
||||
context: Some(args()),
|
||||
}
|
||||
}
|
||||
fn params() -> CompleteRequestParams {
|
||||
CompleteRequestParams::new(
|
||||
Reference::for_resource("crank://bound/{region}"),
|
||||
ArgumentInfo::new("region", "e"),
|
||||
)
|
||||
}
|
||||
async fn state() -> Arc<AppState> {
|
||||
crank_test_support::postgres_schema_url_for_task("completion_handler_local", "t_7458fe3b")
|
||||
.await;
|
||||
super::super::rmcp_tools_tests::test_state().await
|
||||
}
|
||||
fn handler(state: &Arc<AppState>, outcome: CompletionOutcome, pending: bool) -> CompletionHandler {
|
||||
CompletionHandler {
|
||||
state: state.clone(),
|
||||
domain: Some(Arc::new(Domain {
|
||||
outcome: Mutex::new(Some(outcome)),
|
||||
pending,
|
||||
..Default::default()
|
||||
})),
|
||||
}
|
||||
}
|
||||
async fn context(h: &CompletionHandler, revision: &str) -> RequestContext<RoleServer> {
|
||||
let c = request_context(h, scope(revision)).await.unwrap();
|
||||
assert!(c.peer.is_transport_closed());
|
||||
assert_eq!(
|
||||
h.domain.as_ref().unwrap().calls.load(SeqCst),
|
||||
0,
|
||||
"bootstrap must not execute domain"
|
||||
);
|
||||
let s = CompletionHandler::scope(&c).unwrap();
|
||||
assert_eq!(s.workspace, "workspace");
|
||||
assert_eq!(s.agent, "agent");
|
||||
assert_eq!(s.revision, revision);
|
||||
assert_eq!(s.credential.platform_api_key_id.unwrap().as_str(), "key");
|
||||
c
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_trait_result_is_consumed_and_domain_runs_once() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let h = handler(
|
||||
&state,
|
||||
CompletionOutcome::Completed {
|
||||
values: vec!["eu".into()],
|
||||
total: Some(1),
|
||||
has_more: false,
|
||||
},
|
||||
false,
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let mut result = ServerHandler::complete(&h, params(), c).await.unwrap();
|
||||
assert_eq!(result.completion.values, ["eu"]);
|
||||
result.completion.values = vec!["typed".into()];
|
||||
result.completion.total = None;
|
||||
result.completion.has_more = Some(true);
|
||||
match restore(Ok(result)) {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => {
|
||||
assert_eq!(values, ["typed"]);
|
||||
assert_eq!(total, None);
|
||||
assert!(has_more);
|
||||
}
|
||||
_ => panic!("typed result not consumed"),
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let h = handler(
|
||||
&state,
|
||||
CompletionOutcome::Completed {
|
||||
values: vec![],
|
||||
total: None,
|
||||
has_more: false,
|
||||
},
|
||||
false,
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let result = ServerHandler::complete(&h, params(), c).await.unwrap();
|
||||
assert!(result.completion.values.is_empty());
|
||||
assert_eq!(result.completion.total, None);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_dropping_trait_future_drops_pending_domain() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let h = handler(&state, CompletionOutcome::CatalogUnavailable, true);
|
||||
let c = context(&h, revision).await;
|
||||
let domain = h.domain.as_ref().unwrap();
|
||||
let mut future = Box::pin(ServerHandler::complete(&h, params(), c));
|
||||
assert!(futures_util::poll!(&mut future).is_pending());
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
assert!(!domain.dropped.load(SeqCst));
|
||||
drop(future);
|
||||
assert!(domain.dropped.load(SeqCst));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!domain.finished.load(SeqCst));
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_trait_errors_remain_safe() {
|
||||
let state = state().await;
|
||||
for outcome in [
|
||||
CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
|
||||
CompletionOutcome::NotAvailable,
|
||||
CompletionOutcome::CatalogUnavailable,
|
||||
] {
|
||||
let h = handler(&state, outcome, false);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::complete(&h, params(), c).await;
|
||||
assert!(result.is_err());
|
||||
let error = result.as_ref().unwrap_err();
|
||||
assert!(!error.to_string().contains("crank://bound"));
|
||||
match error.code {
|
||||
ErrorCode::INVALID_PARAMS => assert!(matches!(
|
||||
restore(result),
|
||||
CompletionOutcome::InvalidParams(_) | CompletionOutcome::NotAvailable
|
||||
)),
|
||||
ErrorCode::INTERNAL_ERROR => assert!(matches!(
|
||||
restore(result),
|
||||
CompletionOutcome::CatalogUnavailable
|
||||
)),
|
||||
_ => panic!("unexpected error"),
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_completion_test_support.rs"]
|
||||
mod fixtures;
|
||||
use super::rmcp_completion_handler_runtime_tests as handler;
|
||||
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
@@ -89,8 +90,10 @@ async fn success(
|
||||
session: Option<&str>,
|
||||
p: Value,
|
||||
sse: bool,
|
||||
require_handler: bool,
|
||||
) -> (Value, [usize; 2]) {
|
||||
let before = counts(&h.counters);
|
||||
let handler_before = handler::counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
@@ -107,12 +110,19 @@ async fn success(
|
||||
assert!(result.get(key).is_none(), "{body}");
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
let handler_delta = handler::delta(&h.counters, handler_before);
|
||||
if require_handler {
|
||||
assert_eq!(
|
||||
handler_delta.0, handler_delta.1,
|
||||
"actual completion handler execution/consumption: {handler_delta:?}"
|
||||
);
|
||||
}
|
||||
(
|
||||
result["completion"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
async fn control(revision: &str, require_handler: bool) -> Vec<[usize; 2]> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
@@ -149,7 +159,7 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
] {
|
||||
let (completion, delta) = success(&h, revision, session, p, sse).await;
|
||||
let (completion, delta) = success(&h, revision, session, p, sse, require_handler).await;
|
||||
assert_eq!(completion, expected);
|
||||
deltas.push(delta);
|
||||
}
|
||||
@@ -160,6 +170,7 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
session,
|
||||
params(resource(uri), "region", "item"),
|
||||
sse,
|
||||
require_handler,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
@@ -179,7 +190,8 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
}
|
||||
let mut with_context = params(prompt("greeting"), "tone", "w");
|
||||
with_context["context"] = json!({"arguments":{"name":"Ada","tone":"dry"}});
|
||||
let (completion, delta) = success(&h, revision, session, with_context, sse).await;
|
||||
let (completion, delta) =
|
||||
success(&h, revision, session, with_context, sse, require_handler).await;
|
||||
assert_eq!(completion, json!({"values":["warm"],"total":1}));
|
||||
deltas.push(delta);
|
||||
let mut unavailable = None;
|
||||
@@ -284,15 +296,15 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
control(LEGACY_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
control(MODERN_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
let deltas = control(LEGACY_REVISION, true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
@@ -300,7 +312,7 @@ async fn rmcp_completion_sdk_legacy() {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
let deltas = control(MODERN_REVISION, true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
|
||||
@@ -365,6 +365,45 @@ async fn rmcp_runtime_sdk_dispatch_legacy() {
|
||||
);
|
||||
}
|
||||
|
||||
async fn handler_execution_control(revision: &str) {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
h.list(revision, session, TOOL_NAME).await;
|
||||
h.call(
|
||||
revision,
|
||||
session,
|
||||
TOOL_NAME,
|
||||
&format!("{revision}@handler.test"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
h.calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"one domain call expected"
|
||||
);
|
||||
assert_eq!(
|
||||
[
|
||||
h.counters.sdk_tools_list_handler_completed(),
|
||||
h.counters.sdk_tools_list_handler_consumed(),
|
||||
h.counters.sdk_tools_call_handler_completed(),
|
||||
h.counters.sdk_tools_call_handler_consumed(),
|
||||
],
|
||||
[1, 1, 1, 1],
|
||||
"real build_app HTTP tools/list and tools/call must execute and consume SDK handler results ({revision})"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_http_modern() {
|
||||
handler_execution_control(MODERN_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_http_legacy() {
|
||||
handler_execution_control(LEGACY_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_runtime_observer_is_request_scoped() {
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Real trait-result consumption controls and request-owned cancellation.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Domain {
|
||||
outcome: Mutex<Option<ToolsOutcome>>,
|
||||
calls: AtomicUsize,
|
||||
pending: bool,
|
||||
started: tokio::sync::Notify,
|
||||
dropped: AtomicBool,
|
||||
}
|
||||
struct Witness<'a>(&'a AtomicBool);
|
||||
impl Drop for Witness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Domain {
|
||||
pub(super) async fn execute(&self, scope: &Scope, command: ToolsCommand) -> ToolsOutcome {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
assert_eq!(scope.workspace, "workspace");
|
||||
assert_eq!(scope.agent, "agent");
|
||||
assert_eq!(
|
||||
scope
|
||||
.credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"key"
|
||||
);
|
||||
assert_eq!(scope.locale, ExecutionLocale::En);
|
||||
match command {
|
||||
ToolsCommand::List(list) => {
|
||||
assert_eq!(list.cursor.as_deref(), Some("cursor"));
|
||||
assert_eq!(list.limit, Some(7));
|
||||
}
|
||||
ToolsCommand::Call(call) => {
|
||||
assert_eq!(call.tool_name, "bound");
|
||||
assert_eq!(call.arguments, json!({"number":42,"nested":[null]}));
|
||||
assert_eq!(call.confirmation_token.as_deref(), Some("confirmation"));
|
||||
assert!(scope.lifecycle.is_some());
|
||||
}
|
||||
}
|
||||
let _witness = Witness(&self.dropped);
|
||||
self.started.notify_one();
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
self.outcome
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("one domain call")
|
||||
}
|
||||
}
|
||||
fn scope() -> Scope {
|
||||
Scope {
|
||||
workspace: "workspace".into(),
|
||||
agent: "agent".into(),
|
||||
credential: VerifiedMachineCredential {
|
||||
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
scopes: vec![crank_core::PlatformApiKeyScope::Read],
|
||||
platform_api_key_id: Some("key".into()),
|
||||
},
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: ContinuationSupport::ElicitationUnsupported,
|
||||
locale: ExecutionLocale::En,
|
||||
limit: Some(7),
|
||||
confirmation: Some("confirmation".into()),
|
||||
lifecycle: Some(ToolCallLifecycle::new(None).0),
|
||||
}
|
||||
}
|
||||
async fn state() -> Arc<AppState> {
|
||||
crank_test_support::postgres_schema_url_for_task("tools_handler_local", "t_75a3342f").await;
|
||||
super::super::rmcp_tools_tests::test_state().await
|
||||
}
|
||||
fn handler(state: &Arc<AppState>, outcome: ToolsOutcome) -> Handler {
|
||||
let mut h = Handler::new(state);
|
||||
h.domain = Some(Arc::new(Domain {
|
||||
outcome: Mutex::new(Some(outcome)),
|
||||
..Default::default()
|
||||
}));
|
||||
h
|
||||
}
|
||||
async fn context(h: &Handler) -> RequestContext<RoleServer> {
|
||||
let context = request_context(h, scope()).await.unwrap();
|
||||
assert!(context.peer.is_transport_closed());
|
||||
assert_eq!(Arc::strong_count(&h.extras), 1);
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
||||
context
|
||||
}
|
||||
fn call() -> CallToolRequestParams {
|
||||
CallToolRequestParams::new("bound").with_arguments(
|
||||
json!({"number":42,"nested":[null]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
fn payload(outcome: Outcome, version: &str) -> Value {
|
||||
match super::super::response::sdk_tools_payload(&json!({"id":17}), version, outcome) {
|
||||
super::super::response::ToolCommandPayload::Ok(value) => value,
|
||||
_ => panic!("expected wire payload"),
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_list_typed_mutation_and_lossless_catalog() {
|
||||
let state = state().await;
|
||||
for version in ["2025-11-25", "2026-07-28"] {
|
||||
let raw = json!({"name":"original","inputSchema":{"type":"object"},"description":null,
|
||||
"annotations":{"readOnlyHint":true,"x-extra":[null]},"icons":null,"x-tool":{}});
|
||||
let h = handler(
|
||||
&state,
|
||||
ToolsOutcome::List {
|
||||
tools: vec![raw.clone()],
|
||||
next_cursor: Some("next".into()),
|
||||
},
|
||||
);
|
||||
let mut result = ServerHandler::list_tools(
|
||||
&h,
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
|
||||
context(&h).await,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
result.tools[0].name = "mutated".into();
|
||||
result.tools[0].description = Some("typed description".into());
|
||||
result.next_cursor = Some("changed".into());
|
||||
let wire = payload(
|
||||
projection::consume_list(Ok(result), h.take_extras()),
|
||||
version,
|
||||
);
|
||||
let mut expected = raw;
|
||||
expected["name"] = json!("mutated");
|
||||
expected["description"] = json!("typed description");
|
||||
assert_eq!(wire["result"]["tools"], json!([expected]));
|
||||
assert_eq!(wire["result"]["nextCursor"], "changed");
|
||||
assert_eq!(
|
||||
wire["result"].get("resultType").is_some(),
|
||||
version == "2026-07-28"
|
||||
);
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_call_typed_content_structured_and_is_error_mutations() {
|
||||
let state = state().await;
|
||||
for version in ["2025-11-25", "2026-07-28"] {
|
||||
for original in [
|
||||
ToolCallOutcome::Completed(Value::Null),
|
||||
ToolCallOutcome::ApprovalPending(json!({"approval":true})),
|
||||
] {
|
||||
let h = handler(&state, ToolsOutcome::Call(original));
|
||||
let result = ServerHandler::call_tool(&h, call(), context(&h).await)
|
||||
.await
|
||||
.unwrap();
|
||||
let CallToolResponse::Complete(mut result) = result else {
|
||||
panic!("complete result");
|
||||
};
|
||||
result.content = vec![ContentBlock::text("typed content")];
|
||||
result.structured_content = Some(json!({"typed":42}));
|
||||
result.is_error = Some(true);
|
||||
let wire = payload(projection::consume_call(Ok(result.into())), version);
|
||||
assert_eq!(
|
||||
wire["result"]["content"],
|
||||
json!([{"type":"text","text":"typed content"}])
|
||||
);
|
||||
assert_eq!(wire["result"]["structuredContent"], json!({"typed":42}));
|
||||
assert_eq!(wire["result"]["isError"], true);
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_typed_list_and_call_errors_are_consumed() {
|
||||
let state = state().await;
|
||||
for version in ["2025-11-25", "2026-07-28"] {
|
||||
let h = handler(&state, ToolsOutcome::InvalidParams("original list".into()));
|
||||
let result = ServerHandler::list_tools(
|
||||
&h,
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
|
||||
context(&h).await,
|
||||
)
|
||||
.await;
|
||||
let mut error = result.unwrap_err();
|
||||
error.message = "mutated list".into();
|
||||
error.data = Some(json!({"typed":true}));
|
||||
let wire = payload(
|
||||
projection::consume_list(Err(error), h.take_extras()),
|
||||
version,
|
||||
);
|
||||
assert_eq!(wire["error"]["message"], "mutated list");
|
||||
assert_eq!(wire["error"]["data"], json!({"typed":true}));
|
||||
let h = handler(
|
||||
&state,
|
||||
ToolsOutcome::Call(ToolCallOutcome::InvalidParams("original call".into())),
|
||||
);
|
||||
let mut error = ServerHandler::call_tool(&h, call(), context(&h).await)
|
||||
.await
|
||||
.unwrap_err();
|
||||
error.code = ErrorCode(-32001);
|
||||
error.message = "mutated call".into();
|
||||
error.data = Some(json!({"typed":42}));
|
||||
let wire = payload(projection::consume_call(Err(error)), version);
|
||||
assert_eq!(wire["error"]["code"], -32001);
|
||||
assert_eq!(wire["error"]["message"], "mutated call");
|
||||
assert_eq!(wire["error"]["data"], json!({"typed":42}));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_domain_outcomes_keep_wire_semantics() {
|
||||
use crate::tool_error::{McpControlError, control_tool_error_contract};
|
||||
let state = state().await;
|
||||
for version in ["2025-11-25", "2026-07-28"] {
|
||||
for kind in 0..6 {
|
||||
let outcome = || match kind {
|
||||
0 => ToolCallOutcome::Completed(Value::Null),
|
||||
1 => ToolCallOutcome::ApprovalPending(json!({"approval":"pending"})),
|
||||
2 => ToolCallOutcome::ApprovalUnavailable(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
),
|
||||
3 => ToolCallOutcome::Error(control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
"request",
|
||||
"trace",
|
||||
ExecutionLocale::En,
|
||||
)),
|
||||
4 => ToolCallOutcome::InvalidParams("invalid argument".into()),
|
||||
_ => ToolCallOutcome::InternalFailure,
|
||||
};
|
||||
let h = handler(&state, ToolsOutcome::Call(outcome()));
|
||||
let ctx = context(&h).await;
|
||||
let correlation = Handler::scope(&ctx).unwrap().correlation;
|
||||
let result = ServerHandler::call_tool(&h, call(), ctx).await;
|
||||
let actual = payload(projection::consume_call(result), version);
|
||||
let expected = super::super::response::tool_command_payload(
|
||||
&json!({"id":17}),
|
||||
version,
|
||||
&correlation,
|
||||
ToolsOutcome::Call(outcome()),
|
||||
);
|
||||
match expected {
|
||||
super::super::response::ToolCommandPayload::Ok(expected) => {
|
||||
assert_eq!(actual, expected)
|
||||
}
|
||||
super::super::response::ToolCommandPayload::Internal(_) => {
|
||||
assert_eq!(actual["error"]["code"], -32603);
|
||||
assert_eq!(actual["error"]["message"], "internal server error");
|
||||
}
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
for raw in [
|
||||
json!({"name":"tool","inputSchema":{},"description":null,"_meta":null,"annotations":{},"icons":[]}),
|
||||
json!({"name":"tool","inputSchema":{},"annotations":{"x-annotation":null},"icons":null,"x-tool":[null,{}]}),
|
||||
] {
|
||||
let h = handler(
|
||||
&state,
|
||||
ToolsOutcome::List {
|
||||
tools: vec![raw.clone()],
|
||||
next_cursor: Some(String::new()),
|
||||
},
|
||||
);
|
||||
let result = ServerHandler::list_tools(
|
||||
&h,
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
|
||||
context(&h).await,
|
||||
)
|
||||
.await;
|
||||
let wire = payload(projection::consume_list(result, h.take_extras()), version);
|
||||
assert_eq!(wire["result"]["tools"], json!([raw]));
|
||||
assert_eq!(wire["result"]["nextCursor"], "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_tools_handler_pending_domain_dropped_with_parent_and_identity_is_local() {
|
||||
let state = state().await;
|
||||
for list in [false, true] {
|
||||
let mut h = Handler::new(&state);
|
||||
h.domain = Some(Arc::new(Domain {
|
||||
pending: true,
|
||||
..Default::default()
|
||||
}));
|
||||
let ctx = context(&h).await;
|
||||
let other = request_context(
|
||||
&h,
|
||||
Scope {
|
||||
agent: "other-agent".into(),
|
||||
..scope()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(Handler::scope(&ctx).unwrap().agent, "agent");
|
||||
assert_eq!(Handler::scope(&other).unwrap().agent, "other-agent");
|
||||
let parent = async {
|
||||
if list {
|
||||
let _ = ServerHandler::list_tools(
|
||||
&h,
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
|
||||
ctx,
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
let _ = ServerHandler::call_tool(&h, call(), ctx).await;
|
||||
}
|
||||
};
|
||||
let domain = h.domain.as_ref().unwrap();
|
||||
{
|
||||
let parent = parent;
|
||||
tokio::pin!(parent);
|
||||
tokio::select! { _ = domain.started.notified() => {}, _ = &mut parent => panic!("pending domain completed") }
|
||||
assert!(!domain.dropped.load(SeqCst));
|
||||
}
|
||||
assert!(domain.dropped.load(SeqCst));
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,10 @@ Inbound-response-срез #107 на базе rc.31/rmcp3.9.0 подключае
|
||||
|
||||
Prompts handler-срез #107 на базе rc.33 заменяет прежний DTO-only shim настоящими `ServerHandler::list_prompts/get_prompt` в `app/rmcp_prompts.rs`. Уже подключённый потребитель — `build_app` → обе HTTP dispatch-ветки → `rmcp_dispatch::handle_prompts_command`. Overrides напрямую await-ят прежний domain service ровно один раз; caller потребляет actual typed SDK Result, а request-local projection восстанавливает только непредставимые поля/omissions. Инертный ping-bootstrap закрывается до domain execution; domain future остаётся в parent HTTP future и отменяется при drop. Closed Peer не поддерживает callbacks. HTTP handler completed/consumed ATDD обеих revisions и trait-result mutation/drop regressions подтверждают реальное исполнение, прежние wire/access/error boundaries и lossless content; affected Prompts integration проверяет pinned static/dynamic Resource composition и dependency errors. Domain/auth/storage/session/transport не меняются. Это не завершение #107, feature qualification или разрешение #108/4.7/production.
|
||||
|
||||
Completion handler-срез #107 на базе rc.34 заменяет DTO-only completion shim настоящим `ServerHandler::complete` в `app/rmcp_completion.rs`. Подключённый потребитель — обе штатные HTTP dispatch-ветки через `rmcp_dispatch::handle_completion_command`. Override напрямую await-ит прежний domain service один раз; caller потребляет возвращённый SDK `CompleteResult`/`ErrorData`, сохраняя прежнюю JSON/SSE проекцию. Исходный JSON context передаётся request-local без сужения до SDK string map. Инертный ping-bootstrap закрывается до domain execution; drop parent future отменяет незавершённый domain future, закрытый Peer не поддерживает callbacks. Отдельные HTTP handler-completed/caller-consumed oracles и trait mutation/drop/error regressions проверяют этот переход, а wire controls сохраняют refs, published/archive binding, bounded/empty/omitted totals, safe errors и revocation. Domain/auth/storage/session/transport/capabilities не меняются. Полный #107, нагрузочная квалификация, #108/4.7 и production не завершены и не запускаются.
|
||||
|
||||
Tools handler-срез #107 на базе rc.35 заменяет DTO-only Tools shim настоящими `ServerHandler::list_tools/call_tool` в `app/rmcp_tools_runtime.rs`. Подключённый потребитель — `build_app` → modern/legacy list dispatch и `lifecycle::call_future` → `rmcp_dispatch::handle_tools_command`. Overrides напрямую await-ят прежний shared service один раз; HTTP JSON/SSE consumers сериализуют actual SDK `ListToolsResult`/`CallToolResult`/`ErrorData`, сохраняя локально только непредставимые catalog extras. Request-local context переносит identity/locale/limit/confirmation и существующий lifecycle без повторной in-flight регистрации. Инертный ping-bootstrap закрыт до domain execution, closed Peer не используется для callbacks; progress/cancel/deadline остаются у прежнего lifecycle, drop parent отменяет domain future. HTTP handler-completed/caller-consumed oracles обеих revisions и typed mutation/error/single-call/drop controls отделены от existing wire GREEN. Affected проверки сохраняют pagination, Search/proxy binding, published catalog, access/revocation и approval semantics. Domain/auth/storage/session/transport/capabilities не меняются. Это не завершение #107, не нагрузочная/feature qualification и не разрешение #108/4.7/production.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user