Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d01bdf019c | ||
|
|
22637861c3 | ||
|
|
7aab666aaa | ||
|
|
fd76aaf676 | ||
|
|
986cd78b96 | ||
|
|
bcdf57074b | ||
|
|
b39e4a3470 | ||
|
|
3b30aad28e | ||
|
|
5611e81579 |
No files matched your search
@@ -41,6 +41,10 @@ mod rmcp_http;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
mod rmcp_logging;
|
||||
mod rmcp_negotiation;
|
||||
mod rmcp_notifications;
|
||||
#[cfg(test)]
|
||||
mod rmcp_progress_cancel;
|
||||
mod rmcp_prompts;
|
||||
mod rmcp_prompts_projection;
|
||||
@@ -50,6 +54,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,
|
||||
validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
@@ -38,12 +38,10 @@ 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;
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Serve a request of the modern stateless era.
|
||||
/// No session is created, read or required; identity comes from the per-request `_meta` metadata that
|
||||
@@ -111,32 +109,43 @@ pub(super) async fn handle_modern_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Discover,
|
||||
..
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
discover_result(version, SERVER_NAME, SERVER_VERSION),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
} => {
|
||||
let result = match super::rmcp_negotiation::discover(version).await {
|
||||
Ok(result) => result,
|
||||
Err(error) => return sdk_error_response(message, response_mode, version, error),
|
||||
};
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(version, result),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
crate::protocol::ping_result(&json!({"method": "ping"}), version),
|
||||
} => {
|
||||
if let Err(error) = super::rmcp_negotiation::ping().await {
|
||||
return sdk_error_response(message, response_mode, version, error);
|
||||
}
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
json!({"protocolVersion": version}),
|
||||
),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
@@ -170,36 +179,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,
|
||||
@@ -761,6 +741,19 @@ pub(super) async fn handle_modern_request(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sdk_error_response(
|
||||
message: &Value,
|
||||
mode: ResponseMode,
|
||||
revision: &str,
|
||||
error: rmcp::ErrorData,
|
||||
) -> Response {
|
||||
let mut envelope = jsonrpc_error(request_id(message), i64::from(error.code.0), error.message);
|
||||
if let Some(data) = error.data {
|
||||
envelope["error"]["data"] = data;
|
||||
}
|
||||
transport_response(StatusCode::OK, envelope, mode, None, Some(revision))
|
||||
}
|
||||
|
||||
/// The verified, era-neutral context of a Resource command: the same workspace/Agent/credential/
|
||||
/// correlation the Tools service receives.
|
||||
fn resource_service_context<'a>(
|
||||
@@ -820,6 +813,10 @@ pub(super) async fn handle_initialize(
|
||||
None,
|
||||
);
|
||||
};
|
||||
let initialize_result = match super::rmcp_negotiation::initialize(protocol_version).await {
|
||||
Ok(result) => result,
|
||||
Err(error) => return sdk_error_response(message, response_mode, protocol_version, error),
|
||||
};
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||
let supports_elicitation = raw_params
|
||||
@@ -845,10 +842,7 @@ pub(super) async fn handle_initialize(
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::initialize_result(protocol_version, SERVER_NAME, SERVER_VERSION),
|
||||
),
|
||||
jsonrpc_result(request_id(message), initialize_result),
|
||||
response_mode,
|
||||
Some(&session_id),
|
||||
Some(protocol_version),
|
||||
@@ -876,15 +870,9 @@ pub(super) async fn handle_initialized_notification(
|
||||
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
|
||||
#[cfg(not(test))]
|
||||
let _ = initialized;
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
super::rmcp_notifications::initialized(state, session_id)
|
||||
.await
|
||||
{
|
||||
Ok(true) => StatusCode::ACCEPTED.into_response(),
|
||||
Ok(false) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
.into_response()
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::NOT_FOUND.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
|
||||
@@ -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,
|
||||
@@ -78,6 +82,8 @@ pub(crate) struct CounterSet {
|
||||
sdk_logging_dispatch: AtomicUsize,
|
||||
sdk_logging_level: AtomicUsize,
|
||||
sdk_logging_notification: AtomicUsize,
|
||||
sdk_logging_handler_completed: AtomicUsize,
|
||||
sdk_logging_handler_consumed: AtomicUsize,
|
||||
sdk_progress_notification: AtomicUsize,
|
||||
sdk_cancelled_params: AtomicUsize,
|
||||
sdk_subscriptions_listen: AtomicUsize,
|
||||
@@ -85,8 +91,7 @@ pub(crate) struct CounterSet {
|
||||
sdk_signal_notification: AtomicUsize,
|
||||
sdk_jsonrpc_response: AtomicUsize,
|
||||
sdk_jsonrpc_error: AtomicUsize,
|
||||
sdk_ping_request: AtomicUsize,
|
||||
sdk_ping_result: AtomicUsize,
|
||||
|
||||
sdk_inbound_response_decoded: AtomicUsize,
|
||||
sdk_inbound_error_decoded: AtomicUsize,
|
||||
sdk_inbound_response_consumed: AtomicUsize,
|
||||
@@ -95,12 +100,33 @@ pub(crate) struct CounterSet {
|
||||
sdk_dispatch_consumed: AtomicUsize,
|
||||
sdk_initialized_decoded: AtomicUsize,
|
||||
sdk_initialized_consumed: AtomicUsize,
|
||||
sdk_initialized_handler_completed: AtomicUsize,
|
||||
sdk_initialized_handler_consumed: AtomicUsize,
|
||||
sdk_cancelled_handler_completed: AtomicUsize,
|
||||
sdk_cancelled_handler_consumed: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
|
||||
sdk_initialize_handler_completed: AtomicUsize,
|
||||
sdk_initialize_handler_consumed: AtomicUsize,
|
||||
sdk_discover_handler_completed: AtomicUsize,
|
||||
sdk_discover_handler_consumed: AtomicUsize,
|
||||
sdk_ping_handler_completed: AtomicUsize,
|
||||
sdk_ping_handler_consumed: AtomicUsize,
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -164,20 +190,42 @@ impl CounterSet {
|
||||
pub(crate) fn sdk_initialized_consumed(&self) -> usize {
|
||||
self.sdk_initialized_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_request(&self) -> usize {
|
||||
self.sdk_ping_request.load(Ordering::SeqCst)
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_completed(&self) -> usize {
|
||||
self.sdk_initialized_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_result(&self) -> usize {
|
||||
self.sdk_ping_result.load(Ordering::SeqCst)
|
||||
pub(crate) fn sdk_initialized_handler_consumed(&self) -> usize {
|
||||
self.sdk_initialized_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_cancelled_handler_completed(&self) -> usize {
|
||||
self.sdk_cancelled_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_cancelled_handler_consumed(&self) -> usize {
|
||||
self.sdk_cancelled_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialize_input(&self) -> usize {
|
||||
self.sdk_initialize_input.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialize_result(&self) -> usize {
|
||||
self.sdk_initialize_result.load(Ordering::SeqCst)
|
||||
|
||||
pub(crate) fn sdk_initialize_handler_completed(&self) -> usize {
|
||||
self.sdk_initialize_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_discover_result(&self) -> usize {
|
||||
self.sdk_discover_result.load(Ordering::SeqCst)
|
||||
pub(crate) fn sdk_initialize_handler_consumed(&self) -> usize {
|
||||
self.sdk_initialize_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_discover_handler_completed(&self) -> usize {
|
||||
self.sdk_discover_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_discover_handler_consumed(&self) -> usize {
|
||||
self.sdk_discover_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_handler_completed(&self) -> usize {
|
||||
self.sdk_ping_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_handler_consumed(&self) -> usize {
|
||||
self.sdk_ping_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_jsonrpc_response(&self) -> usize {
|
||||
self.sdk_jsonrpc_response.load(Ordering::SeqCst)
|
||||
@@ -214,6 +262,14 @@ impl CounterSet {
|
||||
self.sdk_logging_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_handler_completed(&self) -> usize {
|
||||
self.sdk_logging_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_handler_consumed(&self) -> usize {
|
||||
self.sdk_logging_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
|
||||
self.sdk_completion_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -366,6 +422,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);
|
||||
@@ -500,9 +573,23 @@ pub(crate) fn sdk_logging_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_logging_notification);
|
||||
}
|
||||
|
||||
/// Mark after the real logging handler has completed its awaited operation and built its result.
|
||||
pub(crate) fn sdk_logging_handler_completed() {
|
||||
increment(|counters| &counters.sdk_logging_handler_completed);
|
||||
}
|
||||
|
||||
/// Mark only after the caller consumes the actual SDK handler Result.
|
||||
pub(crate) fn sdk_logging_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_logging_handler_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_logging_runtime_tests.rs"]
|
||||
mod rmcp_logging_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_logging_handler_runtime_tests.rs"]
|
||||
mod rmcp_logging_handler_runtime_tests;
|
||||
|
||||
/// Mark only after successfully serializing real SDK ProgressNotificationParam params.
|
||||
pub(crate) fn sdk_progress_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_progress_notification);
|
||||
@@ -548,19 +635,32 @@ pub(crate) fn sdk_jsonrpc_error_serialized() {
|
||||
#[path = "../rmcp_envelopes_runtime_tests.rs"]
|
||||
mod rmcp_envelopes_runtime_tests;
|
||||
|
||||
/// Mark only after successfully serializing a real rmcp InitializeResult.
|
||||
pub(crate) fn sdk_initialize_result_serialized() {
|
||||
increment(|counters| &counters.sdk_initialize_result);
|
||||
pub(crate) fn sdk_initialize_handler_completed() {
|
||||
increment(|c| &c.sdk_initialize_handler_completed);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real rmcp DiscoverResult.
|
||||
pub(crate) fn sdk_discover_result_serialized() {
|
||||
increment(|counters| &counters.sdk_discover_result);
|
||||
pub(crate) fn sdk_initialize_handler_consumed() {
|
||||
increment(|c| &c.sdk_initialize_handler_consumed);
|
||||
}
|
||||
pub(crate) fn sdk_discover_handler_completed() {
|
||||
increment(|c| &c.sdk_discover_handler_completed);
|
||||
}
|
||||
pub(crate) fn sdk_discover_handler_consumed() {
|
||||
increment(|c| &c.sdk_discover_handler_consumed);
|
||||
}
|
||||
pub(crate) fn sdk_ping_handler_completed() {
|
||||
increment(|c| &c.sdk_ping_handler_completed);
|
||||
}
|
||||
pub(crate) fn sdk_ping_handler_consumed() {
|
||||
increment(|c| &c.sdk_ping_handler_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
|
||||
mod rmcp_lifecycle_negotiation_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_negotiation_handler_runtime_tests.rs"]
|
||||
mod rmcp_negotiation_handler_runtime_tests;
|
||||
|
||||
/// Mark only where SDK protocol_version is consumed by initialize negotiation, not at DTO creation.
|
||||
pub(crate) fn sdk_initialize_input_consumed(_params: &rmcp::model::InitializeRequestParams) {
|
||||
increment(|counters| &counters.sdk_initialize_input);
|
||||
@@ -569,16 +669,6 @@ pub(crate) fn sdk_initialize_input_consumed(_params: &rmcp::model::InitializeReq
|
||||
#[path = "../rmcp_initialize_input_runtime_tests.rs"]
|
||||
mod rmcp_initialize_input_runtime_tests;
|
||||
|
||||
/// Mark only where a real SDK PingRequest is consumed by the shared runtime ping seam.
|
||||
pub(crate) fn sdk_ping_request_consumed(_request: &rmcp::model::PingRequest) {
|
||||
increment(|counters| &counters.sdk_ping_request);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing the real SDK ping result.
|
||||
pub(crate) fn sdk_ping_result_serialized() {
|
||||
increment(|counters| &counters.sdk_ping_result);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_ping_runtime_tests.rs"]
|
||||
mod rmcp_ping_runtime_tests;
|
||||
|
||||
@@ -596,9 +686,29 @@ pub(crate) fn sdk_initialized_notification_consumed(
|
||||
increment(|counters| &counters.sdk_initialized_consumed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_completed() {
|
||||
increment(|c| &c.sdk_initialized_handler_completed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_consumed() {
|
||||
increment(|c| &c.sdk_initialized_handler_consumed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_cancelled_handler_completed() {
|
||||
increment(|c| &c.sdk_cancelled_handler_completed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_cancelled_handler_consumed() {
|
||||
increment(|c| &c.sdk_cancelled_handler_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialized_runtime_tests.rs"]
|
||||
mod rmcp_initialized_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_notification_handler_runtime_tests.rs"]
|
||||
mod rmcp_notification_handler_runtime_tests;
|
||||
|
||||
/// Mark after successful SDK envelope decode, independently of routing consumption.
|
||||
pub(crate) fn sdk_dispatch_envelope_decoded() {
|
||||
increment(|counters| &counters.sdk_dispatch_decoded);
|
||||
|
||||
@@ -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,
|
||||
@@ -32,11 +31,11 @@ use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{LEGACY_PROTOCOL_VERSION, jsonrpc_error, jsonrpc_result, params, request_id},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||
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,
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, INVALID_LEVEL,
|
||||
Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome,
|
||||
RequestIdentity, ResourceReadCommand, ResourcesCommand, ResourcesListCommand,
|
||||
ResourcesOutcome, ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand,
|
||||
ToolsListCommand,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -107,14 +106,20 @@ pub(super) async fn handle_legacy_request(
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
if let Err(error) = super::rmcp_negotiation::ping().await {
|
||||
return super::dispatch::sdk_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::ping_result(
|
||||
&json!({"method": "ping"}),
|
||||
&session.protocol_version,
|
||||
),
|
||||
json!({"protocolVersion": session.protocol_version}),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -159,36 +164,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,
|
||||
@@ -746,30 +727,23 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||
LoggingOutcome::Applied(level) => {
|
||||
crate::protocol::set_active_level(Some(level));
|
||||
crate::protocol::note(
|
||||
crate::protocol::LogLevel::Notice,
|
||||
EVENT_LEVEL_APPLIED,
|
||||
"applied",
|
||||
);
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), json!({})),
|
||||
let request = match command.validate() {
|
||||
Ok(request) => request,
|
||||
Err(detail) => {
|
||||
return super::dispatch::sdk_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
&session.protocol_version,
|
||||
rmcp::ErrorData::invalid_params(detail, None),
|
||||
);
|
||||
}
|
||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
}
|
||||
};
|
||||
super::rmcp_logging::response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
super::rmcp_logging::set_level(&state, &session.id, request).await,
|
||||
)
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
@@ -821,25 +795,19 @@ async fn handle_cancelled_notification(
|
||||
message: &Value,
|
||||
credential: &VerifiedMachineCredential,
|
||||
) -> Response {
|
||||
let request_id = super::rmcp_progress_cancel::decode_cancelled_request_id(¶ms(message));
|
||||
let Some((typed, raw_number)) = super::rmcp_notifications::cancelled_params(¶ms(message))
|
||||
else {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
};
|
||||
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned_by_session {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id,
|
||||
owner: in_flight_owner(credential),
|
||||
},
|
||||
&request_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
super::rmcp_notifications::cancelled(
|
||||
Arc::clone(state),
|
||||
path.clone(),
|
||||
credential.clone(),
|
||||
session_id,
|
||||
typed,
|
||||
raw_number,
|
||||
)
|
||||
.await;
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Request-owned SDK implementation of the legacy `logging/setLevel` handler.
|
||||
// The pinned legacy revision still requires this deprecated SDK method.
|
||||
#![allow(deprecated)]
|
||||
use super::AppState;
|
||||
use crate::protocol::{self, LogLevel};
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LoggingHandler {
|
||||
store: Arc<protocol::LogLevelStore>,
|
||||
session_id: String,
|
||||
}
|
||||
|
||||
impl ServerHandler for LoggingHandler {
|
||||
async fn set_level(
|
||||
&self,
|
||||
request: SetLevelRequestParams,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
#[allow(deprecated)]
|
||||
let level: LogLevel = request.level.into();
|
||||
self.store.set(&self.session_id, level);
|
||||
protocol::set_active_level(Some(level));
|
||||
protocol::note(LogLevel::Notice, protocol::EVENT_LEVEL_APPLIED, "applied");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_completed();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_context() -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping: ClientJsonRpcMessage = serde_json::from_value(serde_json::json!({
|
||||
"jsonrpc":"2.0", "id":1, "method":"ping"
|
||||
}))
|
||||
.map_err(|_| ErrorData::internal_error("logging handler unavailable", None))?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-logging-context", "1"),
|
||||
);
|
||||
#[derive(Clone)]
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
let mut running = rmcp::service::serve_directly(Bootstrap, transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running
|
||||
.close()
|
||||
.await
|
||||
.map_err(|_| ErrorData::internal_error("logging handler unavailable", None))?;
|
||||
drop(receiver);
|
||||
Ok(RequestContext::new(RequestId::Number(1), peer))
|
||||
}
|
||||
|
||||
pub(super) async fn set_level(
|
||||
state: &Arc<AppState>,
|
||||
session_id: &str,
|
||||
request: SetLevelRequestParams,
|
||||
) -> Result<(), ErrorData> {
|
||||
let handler = LoggingHandler {
|
||||
store: Arc::clone(&state.logging_levels),
|
||||
session_id: session_id.to_owned(),
|
||||
};
|
||||
let context = request_context().await?;
|
||||
invoke(&handler, request, context).await
|
||||
}
|
||||
|
||||
async fn invoke(
|
||||
handler: &impl ServerHandler,
|
||||
request: SetLevelRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
ServerHandler::set_level(handler, request, context).await
|
||||
}
|
||||
|
||||
pub(super) fn response(
|
||||
message: &serde_json::Value,
|
||||
mode: crate::transport::ResponseMode,
|
||||
revision: &str,
|
||||
result: Result<(), ErrorData>,
|
||||
) -> axum::response::Response {
|
||||
match result {
|
||||
Ok(()) => {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_consumed();
|
||||
crate::transport::transport_response(
|
||||
axum::http::StatusCode::OK,
|
||||
crate::jsonrpc::jsonrpc_result(
|
||||
crate::jsonrpc::request_id(message),
|
||||
serde_json::json!({}),
|
||||
),
|
||||
mode,
|
||||
None,
|
||||
Some(revision),
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_consumed();
|
||||
super::dispatch::sdk_error_response(message, mode, revision, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_logging_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Request-owned SDK handlers for the existing HTTP negotiation and ping routes.
|
||||
use std::borrow::Cow;
|
||||
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{jsonrpc::SUPPORTED_PROTOCOL_VERSIONS, protocol::advertised_server_capabilities};
|
||||
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
#[derive(Clone)]
|
||||
struct NegotiationHandler;
|
||||
|
||||
impl ServerHandler for NegotiationHandler {
|
||||
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
|
||||
Cow::Owned(
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|v| version(v))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn initialize(
|
||||
&self,
|
||||
request: InitializeRequestParams,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<InitializeResult, ErrorData> {
|
||||
let revision = request.protocol_version.as_str();
|
||||
if !SUPPORTED_PROTOCOL_VERSIONS.contains(&revision) {
|
||||
return Err(ErrorData::new(
|
||||
ErrorCode(-32602),
|
||||
format!("unsupported protocol version {revision}"),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let caps = capabilities(&advertised_server_capabilities(revision));
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialize_handler_completed();
|
||||
Ok(InitializeResult::new(caps)
|
||||
.with_protocol_version(version(revision))
|
||||
.with_server_info(Implementation::new(SERVER_NAME, SERVER_VERSION)))
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
&self,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<DiscoverResult, ErrorData> {
|
||||
let revision = context
|
||||
.extensions
|
||||
.get::<ProtocolVersion>()
|
||||
.ok_or_else(|| ErrorData::internal_error("discovery revision unavailable", None))?;
|
||||
let revision = revision.as_str();
|
||||
let result = DiscoverResult::new(
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|v| version(v))
|
||||
.collect(),
|
||||
capabilities(&advertised_server_capabilities(revision)),
|
||||
)
|
||||
.with_server_info(Implementation::new(SERVER_NAME, SERVER_VERSION))
|
||||
.with_ttl_ms(0)
|
||||
.with_cache_scope(CacheScope::Private);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_discover_handler_completed();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn ping(&self, _context: RequestContext<RoleServer>) -> Result<(), ErrorData> {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_ping_handler_completed();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn version(revision: &str) -> ProtocolVersion {
|
||||
serde_json::from_value(Value::String(revision.to_owned()))
|
||||
.expect("registered revisions are valid SDK versions")
|
||||
}
|
||||
|
||||
fn capabilities(value: &Value) -> ServerCapabilities {
|
||||
// Registry capabilities are the allowlist; the SDK must not supply defaults.
|
||||
serde_json::from_value(value.clone()).expect("registered capabilities match SDK shapes")
|
||||
}
|
||||
|
||||
async fn request_context() -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping: rmcp::model::ClientJsonRpcMessage =
|
||||
serde_json::from_value(json!({"jsonrpc":"2.0", "id":1, "method":"ping"}))
|
||||
.map_err(|_| ErrorData::internal_error("negotiation context unavailable", None))?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-negotiation-context", "1"),
|
||||
);
|
||||
// Bootstrap only obtains a closed Peer; it must never run the request handler.
|
||||
#[derive(Clone)]
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
let mut running = rmcp::service::serve_directly(Bootstrap, transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running
|
||||
.close()
|
||||
.await
|
||||
.map_err(|_| ErrorData::internal_error("negotiation handler unavailable", None))?;
|
||||
drop(receiver);
|
||||
Ok(RequestContext::new(RequestId::Number(1), peer))
|
||||
}
|
||||
|
||||
pub(super) async fn initialize(revision: &str) -> Result<Value, ErrorData> {
|
||||
initialize_with(&NegotiationHandler, revision).await
|
||||
}
|
||||
|
||||
async fn initialize_with(handler: &impl ServerHandler, revision: &str) -> Result<Value, ErrorData> {
|
||||
let context = request_context().await?;
|
||||
let params =
|
||||
InitializeRequestParams::new(ClientCapabilities::default(), Implementation::new("", ""))
|
||||
.with_protocol_version(version(revision));
|
||||
let result = ServerHandler::initialize(handler, params, context).await?;
|
||||
let mut value = serde_json::to_value(result)
|
||||
.map_err(|_| ErrorData::internal_error("initialize result unavailable", None))?;
|
||||
restore_capabilities(&mut value, revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialize_handler_consumed();
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) async fn discover(revision: &str) -> Result<Value, ErrorData> {
|
||||
discover_with(&NegotiationHandler, revision).await
|
||||
}
|
||||
|
||||
async fn discover_with(handler: &impl ServerHandler, revision: &str) -> Result<Value, ErrorData> {
|
||||
let mut context = request_context().await?;
|
||||
context.extensions.insert(version(revision));
|
||||
let result = ServerHandler::discover(handler, context).await?;
|
||||
let mut value = serde_json::to_value(result)
|
||||
.map_err(|_| ErrorData::internal_error("discover result unavailable", None))?;
|
||||
restore_capabilities(&mut value, revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_discover_handler_consumed();
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) async fn ping() -> Result<(), ErrorData> {
|
||||
ping_with(&NegotiationHandler).await
|
||||
}
|
||||
|
||||
async fn ping_with(handler: &impl ServerHandler) -> Result<(), ErrorData> {
|
||||
let context = request_context().await?;
|
||||
let result = ServerHandler::ping(handler, context).await;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_ping_handler_consumed();
|
||||
result
|
||||
}
|
||||
|
||||
fn restore_capabilities(result: &mut Value, revision: &str) {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let represented =
|
||||
serde_json::to_value(capabilities(&advertised)).expect("SDK capabilities serialize");
|
||||
let caps = result["capabilities"]
|
||||
.as_object_mut()
|
||||
.expect("SDK capabilities serialize as object");
|
||||
for (key, value) in advertised
|
||||
.as_object()
|
||||
.expect("registry capabilities are object")
|
||||
{
|
||||
// Restore only fields the SDK cannot represent, not removed typed capabilities.
|
||||
if represented.get(key).is_none() {
|
||||
caps.entry(key.clone()).or_insert_with(|| value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_negotiation_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Request-owned SDK execution for legacy notifications/initialized and notifications/cancelled.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use rmcp::{RoleServer, ServerHandler, model::*, service::NotificationContext};
|
||||
use serde_json::{Map, Value};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::auth::VerifiedMachineCredential;
|
||||
|
||||
struct OutcomeHandler {
|
||||
operation: Operation,
|
||||
outcome: Mutex<Option<StatusCode>>,
|
||||
}
|
||||
|
||||
enum Operation {
|
||||
Initialized {
|
||||
state: Arc<AppState>,
|
||||
session_id: String,
|
||||
},
|
||||
Cancelled {
|
||||
state: Arc<AppState>,
|
||||
path: AgentRoutePath,
|
||||
credential: VerifiedMachineCredential,
|
||||
session_id: Option<String>,
|
||||
request_id: Option<Value>,
|
||||
},
|
||||
}
|
||||
|
||||
impl OutcomeHandler {
|
||||
fn publish(&self, status: StatusCode) {
|
||||
if let Ok(mut outcome) = self.outcome.lock() {
|
||||
*outcome = Some(status);
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&self) -> Option<StatusCode> {
|
||||
self.outcome.lock().ok()?.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandler for OutcomeHandler {
|
||||
async fn on_initialized(&self, _context: NotificationContext<RoleServer>) {
|
||||
if let Operation::Initialized { state, session_id } = &self.operation {
|
||||
let status = match state
|
||||
.sessions
|
||||
.mark_initialized(session_id, time::OffsetDateTime::now_utc())
|
||||
.await
|
||||
{
|
||||
Ok(true) => StatusCode::ACCEPTED,
|
||||
Ok(false) => StatusCode::NOT_FOUND,
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
self.publish(status);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialized_handler_completed();
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_cancelled(
|
||||
&self,
|
||||
params: CancelledNotificationParam,
|
||||
_context: NotificationContext<RoleServer>,
|
||||
) {
|
||||
if let Operation::Cancelled {
|
||||
state,
|
||||
path,
|
||||
credential,
|
||||
session_id,
|
||||
request_id,
|
||||
} = &self.operation
|
||||
{
|
||||
let target = params.request_id.map(|id| {
|
||||
let typed = id.into_json_value();
|
||||
match (request_id, typed) {
|
||||
(Some(Value::Number(original)), Value::String(projected))
|
||||
if original.to_string() == projected =>
|
||||
{
|
||||
Value::Number(original.clone())
|
||||
}
|
||||
(_, typed) => typed,
|
||||
}
|
||||
});
|
||||
if let (Some(target), Some(session_id)) = (target, session_id.as_ref()) {
|
||||
let owned = match state.sessions.get(session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id: session_id.clone(),
|
||||
owner: credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map_or_else(String::new, |id| id.as_str().to_owned()),
|
||||
},
|
||||
&target,
|
||||
);
|
||||
}
|
||||
}
|
||||
self.publish(StatusCode::ACCEPTED);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_handler_completed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Capture(Mutex<Option<oneshot::Sender<NotificationContext<RoleServer>>>>);
|
||||
|
||||
impl ServerHandler for Capture {
|
||||
async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
|
||||
if let Ok(mut sender) = self.0.lock()
|
||||
&& let Some(sender) = sender.take()
|
||||
{
|
||||
let _ = sender.send(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn notification_context() -> Result<NotificationContext<RoleServer>, ()> {
|
||||
let message: ClientJsonRpcMessage = serde_json::from_value(serde_json::json!({
|
||||
"jsonrpc":"2.0", "method":"notifications/initialized"
|
||||
}))
|
||||
.map_err(|_| ())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(message);
|
||||
let (sender, captured) = oneshot::channel();
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-internal", "1"),
|
||||
);
|
||||
let mut running =
|
||||
rmcp::service::serve_directly(Capture(Mutex::new(Some(sender))), transport, Some(info));
|
||||
let context = captured.await;
|
||||
let closed = running.close().await.is_ok();
|
||||
drop(receiver);
|
||||
if !closed {
|
||||
return Err(());
|
||||
}
|
||||
context.map_err(|_| ())
|
||||
}
|
||||
|
||||
pub(super) async fn initialized(state: Arc<AppState>, session_id: String) -> StatusCode {
|
||||
let handler = OutcomeHandler {
|
||||
operation: Operation::Initialized { state, session_id },
|
||||
outcome: Mutex::new(None),
|
||||
};
|
||||
initialized_with(&handler, &handler, notification_context()).await
|
||||
}
|
||||
|
||||
async fn initialized_with(
|
||||
sdk: &impl ServerHandler,
|
||||
outcome: &OutcomeHandler,
|
||||
context: impl std::future::Future<Output = Result<NotificationContext<RoleServer>, ()>>,
|
||||
) -> StatusCode {
|
||||
let Ok(context) = context.await else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR;
|
||||
};
|
||||
ServerHandler::on_initialized(sdk, context).await;
|
||||
let status = outcome.take();
|
||||
#[cfg(test)]
|
||||
if status.is_some() {
|
||||
super::dispatch_observer::sdk_initialized_handler_consumed();
|
||||
}
|
||||
status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
// Retain the SDK's typed interpretation and the exact original number used by its safe projection.
|
||||
pub(super) fn cancelled_params(
|
||||
value: &Value,
|
||||
) -> Option<(CancelledNotificationParam, Option<Value>)> {
|
||||
let original = value.get("requestId");
|
||||
let mut projected = Map::new();
|
||||
if let Some(id) = original {
|
||||
let safe = match id {
|
||||
Value::Number(number) if number.as_i64().is_none() => Value::String(number.to_string()),
|
||||
_ => id.clone(),
|
||||
};
|
||||
projected.insert("requestId".to_owned(), safe);
|
||||
}
|
||||
let typed = serde_json::from_value(Value::Object(projected)).ok()?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_params_decoded();
|
||||
let raw_number = original.filter(|id| id.is_number()).cloned();
|
||||
Some((typed, raw_number))
|
||||
}
|
||||
|
||||
pub(super) async fn cancelled(
|
||||
state: Arc<AppState>,
|
||||
path: AgentRoutePath,
|
||||
credential: VerifiedMachineCredential,
|
||||
session_id: Option<String>,
|
||||
params: CancelledNotificationParam,
|
||||
raw_number: Option<Value>,
|
||||
) {
|
||||
let request_id = raw_number;
|
||||
let handler = OutcomeHandler {
|
||||
operation: Operation::Cancelled {
|
||||
state,
|
||||
path,
|
||||
credential,
|
||||
session_id,
|
||||
request_id,
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
};
|
||||
cancelled_with(&handler, &handler, params, notification_context()).await;
|
||||
}
|
||||
|
||||
async fn cancelled_with(
|
||||
sdk: &impl ServerHandler,
|
||||
outcome: &OutcomeHandler,
|
||||
params: CancelledNotificationParam,
|
||||
context: impl std::future::Future<Output = Result<NotificationContext<RoleServer>, ()>>,
|
||||
) {
|
||||
let Ok(context) = context.await else {
|
||||
return;
|
||||
};
|
||||
// Cancellation is intentionally opaque: no outcome or bootstrap details reach the client.
|
||||
ServerHandler::on_cancelled(sdk, params, context).await;
|
||||
let status = outcome.take();
|
||||
if status.is_none() {
|
||||
tracing::warn!(name: "mcp.cancelled_handler.missing_outcome", "SDK cancellation handler did not publish an outcome");
|
||||
}
|
||||
#[cfg(test)]
|
||||
if status.is_some() {
|
||||
super::dispatch_observer::sdk_cancelled_handler_consumed();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_notification_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,31 +1,11 @@
|
||||
//! Lossless projection of legacy cancellation targets through the pinned SDK.
|
||||
|
||||
use rmcp::model::CancelledNotificationParam;
|
||||
use serde_json::{Map, Value};
|
||||
//! Test compatibility entry for the production notification decoder.
|
||||
use serde_json::Value;
|
||||
|
||||
pub(super) fn decode_cancelled_request_id(params: &Value) -> Option<Value> {
|
||||
let mut projection = Map::new();
|
||||
let original_id = params.get("requestId");
|
||||
if let Some(id) = original_id {
|
||||
// SDK IDs use i64; the temporary string never reaches the in-flight lookup.
|
||||
let projected = match id {
|
||||
Value::Number(number) if number.as_i64().is_none() => Value::String(number.to_string()),
|
||||
_ => id.clone(),
|
||||
};
|
||||
projection.insert("requestId".to_owned(), projected);
|
||||
}
|
||||
// Only requestId names a target; reason, _meta and extensions retain their ignore semantics.
|
||||
let decoded =
|
||||
serde_json::from_value::<CancelledNotificationParam>(Value::Object(projection)).ok()?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_params_decoded();
|
||||
let id = decoded.request_id?;
|
||||
Some(match original_id {
|
||||
Some(Value::Number(number)) => Value::Number(number.clone()),
|
||||
_ => id.into_json_value(),
|
||||
})
|
||||
let (typed, raw_number) = super::rmcp_notifications::cancelled_params(params)?;
|
||||
let id = typed.request_id?;
|
||||
Some(raw_number.unwrap_or_else(|| id.into_json_value()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_progress_cancel_tests.rs"]
|
||||
mod tests;
|
||||
@@ -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;
|
||||
@@ -1,14 +1,10 @@
|
||||
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
||||
|
||||
use rmcp::model::{
|
||||
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
|
||||
PingRequest, ProtocolVersion, ServerCapabilities, ServerResult,
|
||||
};
|
||||
use rmcp::model::InitializeRequestParams;
|
||||
#[cfg(test)]
|
||||
use rmcp::model::{InitializeResult, ServerCapabilities};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::advertised_server_capabilities;
|
||||
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
|
||||
|
||||
pub(crate) fn initialize_params(
|
||||
params: &Value,
|
||||
) -> Result<InitializeRequestParams, serde_json::Error> {
|
||||
@@ -20,16 +16,13 @@ pub(crate) fn initialize_params(
|
||||
}))
|
||||
}
|
||||
|
||||
fn protocol_version(revision: &str) -> ProtocolVersion {
|
||||
serde_json::from_value(Value::String(revision.to_owned()))
|
||||
.expect("served protocol revisions are strings")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn capabilities(advertised: &Value) -> ServerCapabilities {
|
||||
serde_json::from_value(advertised.clone())
|
||||
.expect("registry capability fragments match SDK capability shapes")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn restore_registry_extensions(result: &mut Value, advertised: Value) {
|
||||
let capabilities = result["capabilities"]
|
||||
.as_object_mut()
|
||||
@@ -55,59 +48,6 @@ pub(crate) fn initialized_notification(message: &Value) -> rmcp::model::ClientNo
|
||||
notification.into()
|
||||
}
|
||||
|
||||
pub(crate) fn ping_result(message: &Value, revision: &str) -> Value {
|
||||
// Ping params were ignored after admission; do not add SDK constraints to extensions.
|
||||
let request: PingRequest = serde_json::from_value(serde_json::json!({
|
||||
"method": message["method"]
|
||||
}))
|
||||
.expect("registry dispatched a validated ping request");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_ping_request_consumed(&request);
|
||||
let result = match rmcp::model::ClientRequest::from(request) {
|
||||
rmcp::model::ClientRequest::PingRequest(_) => ServerResult::empty(()),
|
||||
_ => unreachable!("typed ping can only dispatch ping"),
|
||||
};
|
||||
let mut result = serde_json::to_value(result).expect("SDK ping result is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_ping_result_serialized();
|
||||
// Crank keeps the admitted/session revision in addition to the SDK's empty ping result.
|
||||
result["protocolVersion"] = Value::String(revision.to_owned());
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn initialize_result(revision: &str, name: &str, version: &str) -> Value {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let result = InitializeResult::new(capabilities(&advertised))
|
||||
.with_protocol_version(protocol_version(revision))
|
||||
.with_server_info(Implementation::new(name, version));
|
||||
let mut result = serde_json::to_value(result)
|
||||
.expect("SDK initialize result with registry capabilities is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_initialize_result_serialized();
|
||||
restore_registry_extensions(&mut result, advertised);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn discover_result(revision: &str, name: &str, version: &str) -> Value {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let result = DiscoverResult::new(
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|revision| protocol_version(revision))
|
||||
.collect(),
|
||||
capabilities(&advertised),
|
||||
)
|
||||
.with_server_info(Implementation::new(name, version))
|
||||
.with_ttl_ms(0)
|
||||
.with_cache_scope(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)
|
||||
.expect("SDK discovery result with registry capabilities is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_discover_result_serialized();
|
||||
restore_registry_extensions(&mut result, advertised);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -186,7 +186,8 @@ impl SetLevelCommand {
|
||||
}
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared `logging/setLevel` service.
|
||||
/// Compatibility outcome for the original protocol unit tests; runtime uses the SDK handler.
|
||||
#[cfg(test)]
|
||||
pub(crate) enum LoggingOutcome {
|
||||
/// The level of this client context was accepted.
|
||||
Applied(LogLevel),
|
||||
@@ -394,6 +395,7 @@ impl LogLevelStore {
|
||||
///
|
||||
/// The command has already been parsed from the wire form, so this function only validates and
|
||||
/// records; it never reads the registry, the catalog or any stored value.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn handle_logging_command(
|
||||
store: &LogLevelStore,
|
||||
session_id: &str,
|
||||
|
||||
@@ -45,14 +45,11 @@ pub(crate) use completion::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
handle_completion_command,
|
||||
};
|
||||
pub(crate) use lifecycle_sdk::{
|
||||
discover_result, initialize_params, initialize_result, initialized_notification, ping_result,
|
||||
};
|
||||
pub(crate) use lifecycle_sdk::{initialize_params, initialized_notification};
|
||||
pub(crate) use logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||
in_carried_scope, modern_request_level, note, scoped as logging_scope, set_active_level,
|
||||
set_sse_acceptable, take_notifications,
|
||||
LogLevel, LogLevelStore, SetLevelCommand, carry_scope, in_carried_scope, modern_request_level,
|
||||
note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications,
|
||||
};
|
||||
pub(crate) use prompts::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||
|
||||
@@ -395,7 +395,7 @@ async fn rmcp_initialize_input_observer_positive_control() {
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
assert_eq!(c.sdk_initialize_input(), 1);
|
||||
assert_eq!(
|
||||
c.sdk_initialize_result(),
|
||||
c.sdk_initialize_handler_consumed(),
|
||||
0,
|
||||
"input and output are independent"
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@ struct FaultStore {
|
||||
inner: PostgresTransportSessionStore,
|
||||
fail_get: AtomicBool,
|
||||
fail_mark: AtomicBool,
|
||||
delete_on_mark: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -44,6 +45,9 @@ impl TransportSessionStore for FaultStore {
|
||||
details: "test mark failure".into(),
|
||||
});
|
||||
}
|
||||
if self.delete_on_mark.load(Ordering::SeqCst) {
|
||||
self.inner.delete(id).await?;
|
||||
}
|
||||
self.inner.mark_initialized(id, now).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
@@ -68,6 +72,7 @@ async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
.unwrap(),
|
||||
fail_get: AtomicBool::new(false),
|
||||
fail_mark: AtomicBool::new(false),
|
||||
delete_on_mark: AtomicBool::new(false),
|
||||
});
|
||||
let h = Endpoint::started_with_store(Some(store.clone())).await;
|
||||
let response = post(&h, None, "application/json", legacy_initialize(80)).await;
|
||||
@@ -150,6 +155,26 @@ async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
store.fail_get.store(false, Ordering::SeqCst);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
|
||||
// Session can disappear after admission/scoped reads but before the durable UPDATE.
|
||||
store.delete_on_mark.store(true, Ordering::SeqCst);
|
||||
let completed = h.counters.sdk_initialized_handler_completed();
|
||||
let consumed = h.counters.sdk_initialized_handler_consumed();
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 404);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_completed(),
|
||||
completed + 1
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_consumed(), consumed + 1);
|
||||
assert!(restarted.get(&pending).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -7,7 +7,10 @@ use std::{sync::Arc, time::Duration};
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
|
||||
fn sdk_counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_initialize_result(), c.sdk_discover_result()]
|
||||
[
|
||||
c.sdk_initialize_handler_consumed(),
|
||||
c.sdk_discover_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
fn capabilities() -> Value {
|
||||
@@ -197,19 +200,19 @@ async fn rmcp_lifecycle_negotiation_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observe(c.clone(), async {
|
||||
super::admission_enter();
|
||||
super::sdk_initialize_result_serialized();
|
||||
super::sdk_initialize_handler_consumed();
|
||||
assert_eq!(
|
||||
sdk_counts(&c),
|
||||
[1, 0],
|
||||
"initialize and discovery are separate markers"
|
||||
);
|
||||
super::sdk_discover_result_serialized();
|
||||
super::sdk_discover_handler_consumed();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(sdk_counts(&c), [1, 1]);
|
||||
assert_eq!(c.snapshot(), super::Snapshot::new(1, 0, 0, 0));
|
||||
super::sdk_initialize_result_serialized();
|
||||
super::sdk_discover_result_serialized();
|
||||
super::sdk_initialize_handler_consumed();
|
||||
super::sdk_discover_handler_consumed();
|
||||
assert_eq!(sdk_counts(&c), [1, 1], "out-of-scope markers are no-ops");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Handler-specific acceptance oracle, distinct from existing wire-level GREEN controls.
|
||||
use super::rmcp_logging_runtime_tests;
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_logging_http_completes_and_consumes_the_sdk_handler() {
|
||||
// Existing real build_app HTTP control proves the JSON/SSE contract independently.
|
||||
assert_eq!(
|
||||
rmcp_logging_runtime_tests::control("2025-11-25").await,
|
||||
[1, 1, 1, 1, 1],
|
||||
"legacy wire succeeded but the awaited SDK handler was not completed/consumed"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
#![allow(deprecated)]
|
||||
use super::*;
|
||||
use crate::protocol::SetLevelCommand;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn request(level: &str) -> SetLevelRequestParams {
|
||||
serde_json::from_value(json!({"level": level})).expect("valid SDK logging level")
|
||||
}
|
||||
fn handler(store: &Arc<protocol::LogLevelStore>) -> LoggingHandler {
|
||||
LoggingHandler {
|
||||
store: store.clone(),
|
||||
session_id: "current".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn typed_sdk_level_is_the_applied_level_and_execution_is_single() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
store.set("other", LogLevel::Debug);
|
||||
let counters = Arc::new(super::super::dispatch_observer::CounterSet::default());
|
||||
let events = super::super::dispatch_observer::observe(
|
||||
counters.clone(),
|
||||
protocol::logging_scope(async {
|
||||
// Mutate the typed value after validation: no raw command may override it later.
|
||||
let mut typed = SetLevelCommand {
|
||||
level: "critical".into(),
|
||||
}
|
||||
.validate()
|
||||
.unwrap();
|
||||
typed.level = LoggingLevel::Info;
|
||||
let result = invoke(&handler(&store), typed, request_context().await.unwrap()).await;
|
||||
assert!(result.is_ok());
|
||||
protocol::set_sse_acceptable();
|
||||
let events = protocol::take_notifications();
|
||||
let response = response(
|
||||
&json!({"id":91}),
|
||||
crate::transport::ResponseMode::Json,
|
||||
crate::jsonrpc::LEGACY_PROTOCOL_VERSION,
|
||||
result,
|
||||
);
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(store.get("current"), Some(LogLevel::Info));
|
||||
assert_eq!(store.get("other"), Some(LogLevel::Debug));
|
||||
events
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(counters.sdk_logging_handler_completed(), 1);
|
||||
assert_eq!(counters.sdk_logging_handler_consumed(), 1);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(
|
||||
events[0]["params"]["data"],
|
||||
json!({
|
||||
"event": protocol::EVENT_LEVEL_APPLIED, "outcome": "applied"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
struct Controlled {
|
||||
inner: LoggingHandler,
|
||||
entered: AtomicUsize,
|
||||
error: Option<ErrorData>,
|
||||
pending: bool,
|
||||
}
|
||||
impl ServerHandler for Controlled {
|
||||
async fn set_level(
|
||||
&self,
|
||||
request: SetLevelRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
self.entered.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(error) = &self.error {
|
||||
return Err(error.clone());
|
||||
}
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
ServerHandler::set_level(&self.inner, request, context).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_trait_error_controls_the_http_response_without_store_effect() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
let error = ErrorData::invalid_params("controlled handler error", None);
|
||||
let controlled = Controlled {
|
||||
inner: handler(&store),
|
||||
entered: AtomicUsize::new(0),
|
||||
error: Some(error),
|
||||
pending: false,
|
||||
};
|
||||
for mode in [
|
||||
crate::transport::ResponseMode::Json,
|
||||
crate::transport::ResponseMode::Sse,
|
||||
] {
|
||||
let result = invoke(
|
||||
&controlled,
|
||||
request("notice"),
|
||||
request_context().await.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let reply = response(
|
||||
&json!({"id":"controlled"}),
|
||||
mode,
|
||||
crate::jsonrpc::LEGACY_PROTOCOL_VERSION,
|
||||
result,
|
||||
);
|
||||
assert_eq!(reply.status(), 200);
|
||||
let bytes = axum::body::to_bytes(reply.into_body(), 4096).await.unwrap();
|
||||
let raw = std::str::from_utf8(&bytes).unwrap();
|
||||
let raw = raw
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data:"))
|
||||
.unwrap_or(raw);
|
||||
let body: serde_json::Value = serde_json::from_str(raw).unwrap();
|
||||
assert_eq!(body["id"], "controlled");
|
||||
assert_eq!(body["error"]["code"], -32602);
|
||||
assert_eq!(body["error"]["message"], "controlled handler error");
|
||||
assert!(body.get("result").is_none());
|
||||
}
|
||||
assert_eq!(controlled.entered.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(store.get("current"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_pending_await_before_store_effect_does_not_detach_work() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
let controlled = Controlled {
|
||||
inner: handler(&store),
|
||||
entered: AtomicUsize::new(0),
|
||||
error: None,
|
||||
pending: true,
|
||||
};
|
||||
let context = request_context().await.unwrap();
|
||||
let mut future = Box::pin(invoke(&controlled, request("alert"), context));
|
||||
assert!(futures_util::poll!(future.as_mut()).is_pending());
|
||||
assert_eq!(controlled.entered.load(Ordering::SeqCst), 1);
|
||||
drop(future);
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(store.get("current"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_command_maps_to_safe_invalid_params_error_data() {
|
||||
let error = SetLevelCommand {
|
||||
level: "not-a-level".to_owned(),
|
||||
}
|
||||
.validate()
|
||||
.unwrap_err();
|
||||
assert_eq!(error, protocol::INVALID_LEVEL);
|
||||
let sdk_error = ErrorData::invalid_params(error, None);
|
||||
assert_eq!(sdk_error.code.0, -32602);
|
||||
assert_eq!(sdk_error.message, protocol::INVALID_LEVEL);
|
||||
}
|
||||
@@ -78,7 +78,7 @@ fn opted(level: Value) -> Value {
|
||||
meta[LEVEL] = level;
|
||||
json!({"_meta":meta})
|
||||
}
|
||||
async fn control(revision: &str) -> [usize; 3] {
|
||||
pub(super) async fn control(revision: &str) -> [usize; 5] {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
@@ -131,6 +131,11 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
assert_eq!(h.counters.sdk_logging_notification(), 0);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
handlers(&h.counters),
|
||||
[0, 0],
|
||||
"rejected input must not invoke the handler"
|
||||
);
|
||||
let before = counts(&h.counters);
|
||||
let (method, params, expected) = if revision == LEGACY_REVISION {
|
||||
(
|
||||
@@ -155,7 +160,7 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
assert_eq!(events, vec![expected]);
|
||||
assert!(raw.len() < 4096);
|
||||
let after = counts(&h.counters);
|
||||
let delta = std::array::from_fn(|i| after[i] - before[i]);
|
||||
let delta: [usize; 3] = std::array::from_fn(|i| after[i] - before[i]);
|
||||
// Legacy severity persists, modern opt-in does not leak into the next request.
|
||||
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
@@ -169,6 +174,7 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
.await
|
||||
.unwrap();
|
||||
let before = counts(&h.counters);
|
||||
let before_handlers = handlers(&h.counters);
|
||||
let era = h.counters.snapshot();
|
||||
let response = h
|
||||
.post(
|
||||
@@ -186,13 +192,20 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
let raw = response.text().await.unwrap();
|
||||
assert!(!raw.contains("notifications/message"));
|
||||
assert_eq!(counts(&h.counters), before);
|
||||
assert_eq!(handlers(&h.counters), before_handlers);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(after.era_modern, era.era_modern);
|
||||
assert_eq!(after.era_legacy, era.era_legacy);
|
||||
eprintln!(
|
||||
"existing GREEN logging HTTP {revision}: safe SSE, result, opt-in/invalid/era/auth controls passed; SDK positive delta={delta:?}"
|
||||
);
|
||||
delta
|
||||
[
|
||||
delta[0],
|
||||
delta[1],
|
||||
delta[2],
|
||||
h.counters.sdk_logging_handler_completed(),
|
||||
h.counters.sdk_logging_handler_consumed(),
|
||||
]
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_wire_legacy() {
|
||||
@@ -206,7 +219,7 @@ async fn rmcp_logging_wire_modern() {
|
||||
async fn rmcp_logging_sdk_legacy() {
|
||||
assert_eq!(
|
||||
control(LEGACY_REVISION).await,
|
||||
[1, 1, 1],
|
||||
[1, 1, 1, 1, 1],
|
||||
"missing SDK legacy request/level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
@@ -214,7 +227,7 @@ async fn rmcp_logging_sdk_legacy() {
|
||||
async fn rmcp_logging_sdk_modern() {
|
||||
assert_eq!(
|
||||
control(MODERN_REVISION).await,
|
||||
[0, 1, 1],
|
||||
[0, 1, 1, 0, 0],
|
||||
"missing SDK modern level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
@@ -256,3 +269,140 @@ async fn rmcp_logging_observer_scope_control() {
|
||||
assert_eq!(counts(&a), [1, 1, 1]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
}
|
||||
|
||||
fn handlers(c: &CounterSet) -> [usize; 2] {
|
||||
[
|
||||
c.sdk_logging_handler_completed(),
|
||||
c.sdk_logging_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_all_levels_json_sse_and_ignored_extensions() {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for level in [
|
||||
"debug",
|
||||
"info",
|
||||
"notice",
|
||||
"warning",
|
||||
"error",
|
||||
"critical",
|
||||
"alert",
|
||||
"emergency",
|
||||
] {
|
||||
let before = handlers(&h.counters);
|
||||
let response = h.post_with_accept(LEGACY_REVISION, Some(&session), "logging/setLevel",
|
||||
json!({"level":level,"extension":{"CANARY":"ignored"},"_meta":{"extension":true}}), accept).await;
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
assert_eq!(
|
||||
response.headers()["x-request-id"],
|
||||
"logging-handler-control"
|
||||
);
|
||||
let (body, events, raw) = reply(response).await;
|
||||
assert_eq!(body["result"], json!({}));
|
||||
assert!(!raw.contains("CANARY"));
|
||||
if accept == "application/json" || !["debug", "info", "notice"].contains(&level) {
|
||||
assert!(events.is_empty());
|
||||
} else {
|
||||
let mut expected = vec![notification(
|
||||
"notice",
|
||||
"mcp.logging.level_applied",
|
||||
"applied",
|
||||
)];
|
||||
if ["debug", "info"].contains(&level) {
|
||||
expected.push(notification("info", "mcp.request.served", "ok"));
|
||||
}
|
||||
assert_eq!(events, expected);
|
||||
}
|
||||
assert_eq!(handlers(&h.counters), before.map(|n| n + 1));
|
||||
}
|
||||
}
|
||||
let before = handlers(&h.counters);
|
||||
let response = h
|
||||
.post(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"logging/setLevel",
|
||||
json!({"level":"info","_meta":7}),
|
||||
)
|
||||
.await;
|
||||
assert!(response.status().is_client_error());
|
||||
assert!(!response.text().await.unwrap().contains("CANARY"));
|
||||
assert_eq!(handlers(&h.counters), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_session_guards_do_not_enter_the_handler() {
|
||||
use crate::session::TransportSessionStore;
|
||||
let h = Endpoint::started().await;
|
||||
let uninitialized = h
|
||||
.sessions
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
AGENT_SLUG,
|
||||
false,
|
||||
time::OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign = h
|
||||
.sessions
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
"another-agent",
|
||||
false,
|
||||
time::OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
h.sessions
|
||||
.mark_initialized(&foreign, time::OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
for session in [
|
||||
None,
|
||||
Some("unknown"),
|
||||
Some(uninitialized.as_str()),
|
||||
Some(foreign.as_str()),
|
||||
] {
|
||||
let response = h
|
||||
.post(
|
||||
LEGACY_REVISION,
|
||||
session,
|
||||
"logging/setLevel",
|
||||
json!({"level":"debug"}),
|
||||
)
|
||||
.await;
|
||||
let status = response.status();
|
||||
let raw = response.text().await.unwrap();
|
||||
if session == Some(uninitialized.as_str()) {
|
||||
assert_eq!(status, 200);
|
||||
let body: Value = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(body["error"]["code"], -32002);
|
||||
} else {
|
||||
assert_eq!(status.as_u16(), if session.is_none() { 400 } else { 404 });
|
||||
}
|
||||
assert!(!raw.contains("mcp.logging.level_applied"));
|
||||
assert_eq!(handlers(&h.counters), [0, 0]);
|
||||
assert_eq!(h.counters.sdk_logging_dispatch(), 0);
|
||||
}
|
||||
let session = h.session(LEGACY_REVISION).await;
|
||||
let (body, _, _) = reply(
|
||||
h.post(
|
||||
LEGACY_REVISION,
|
||||
session.as_deref(),
|
||||
"logging/setLevel",
|
||||
json!({"level":"notice"}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["result"], json!({}));
|
||||
assert_eq!(handlers(&h.counters), [1, 1]);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crank_runtime::{
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub sessions: Arc<crate::session::InMemorySessionStore>,
|
||||
key: String,
|
||||
url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
@@ -18,7 +19,7 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("logging_owner", "t_c28c3800").await;
|
||||
crank_test_support::postgres_schema_url_for_task("logging_handler", "t_dbf2bdff").await;
|
||||
let registry = test_registry().await;
|
||||
let operation = test_operation("http://127.0.0.1:9");
|
||||
registry
|
||||
@@ -38,6 +39,7 @@ impl Endpoint {
|
||||
publish_agent(®istry, &operation).await;
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let sessions = Arc::new(crate::session::InMemorySessionStore::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
@@ -49,7 +51,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
sessions.clone(),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
@@ -73,22 +75,41 @@ impl Endpoint {
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
sessions,
|
||||
key,
|
||||
url,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> reqwest::Response {
|
||||
self.post_with_accept(
|
||||
revision,
|
||||
session,
|
||||
method,
|
||||
params,
|
||||
"text/event-stream, application/json",
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub async fn post_with_accept(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
mut params: Value,
|
||||
accept: &str,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "text/event-stream, application/json")
|
||||
.header("Accept", accept)
|
||||
.header("x-request-id", "logging-handler-control")
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Behavioral RED for real negotiation/ping handler execution and result consumption.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
async fn request(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
payload: Value,
|
||||
accept: &str,
|
||||
session: Option<&str>,
|
||||
) -> reqwest::Response {
|
||||
h.request(revision, session, &h.key, accept, payload)
|
||||
.header("x-request-id", "negotiation-handler-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn terminal(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|line| serde_json::from_str(line.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "single terminal response frame");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn handler_counts(c: &CounterSet) -> [usize; 6] {
|
||||
[
|
||||
c.sdk_initialize_handler_completed(),
|
||||
c.sdk_initialize_handler_consumed(),
|
||||
c.sdk_discover_handler_completed(),
|
||||
c.sdk_discover_handler_consumed(),
|
||||
c.sdk_ping_handler_completed(),
|
||||
c.sdk_ping_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
fn delta(after: [usize; 6], before: [usize; 6]) -> [usize; 6] {
|
||||
std::array::from_fn(|index| after[index] - before[index])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_http_executes_and_consumes_initialize_discover_and_ping() {
|
||||
crank_test_support::postgres_schema_url_for_task("negotiation_handler_owner", "t_219756db")
|
||||
.await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await;
|
||||
let before_all = handler_counts(&h.counters);
|
||||
for (revision, method, session) in [
|
||||
(LEGACY_REVISION, "initialize", None),
|
||||
(MODERN_REVISION, "server/discover", None),
|
||||
] {
|
||||
let mut payload = if method == "initialize" {
|
||||
legacy_initialize(1)
|
||||
} else {
|
||||
json!({"jsonrpc":"2.0","id":1,"method":method,"params":{"_meta":modern_meta()}})
|
||||
};
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
if method == "initialize" {
|
||||
payload["id"] = json!(if accept.starts_with("text/event") {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
});
|
||||
}
|
||||
let response = request(&h, revision, payload.clone(), accept, session).await;
|
||||
let body = terminal(response, accept.starts_with("text/event")).await;
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
}
|
||||
}
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
let payload = json!({"jsonrpc":"2.0","id":"ping","method":"ping","params":{"_meta":if revision == MODERN_REVISION { modern_meta() } else { json!({"future":true}) }}});
|
||||
let response = request(
|
||||
&h,
|
||||
revision,
|
||||
payload,
|
||||
accept,
|
||||
if revision == LEGACY_REVISION {
|
||||
session.as_deref()
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let body = terminal(response, accept.starts_with("text/event")).await;
|
||||
assert_eq!(body["id"], "ping");
|
||||
assert!(body.get("error").is_none());
|
||||
if revision == LEGACY_REVISION {
|
||||
assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
}
|
||||
}
|
||||
}
|
||||
let after = handler_counts(&h.counters);
|
||||
assert_eq!(
|
||||
delta(after, before_all),
|
||||
[2, 2, 2, 2, 4, 4],
|
||||
"successful initialize/discover/ping HTTP responses must complete in and consume their SDK handler results"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observe(c.clone(), async {
|
||||
super::sdk_initialize_handler_completed();
|
||||
super::sdk_initialize_handler_consumed();
|
||||
super::sdk_discover_handler_completed();
|
||||
super::sdk_discover_handler_consumed();
|
||||
super::sdk_ping_handler_completed();
|
||||
super::sdk_ping_handler_consumed();
|
||||
assert_eq!(handler_counts(&c), [1; 6]);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(handler_counts(&c), [1; 6]);
|
||||
super::sdk_initialize_handler_completed();
|
||||
assert_eq!(
|
||||
handler_counts(&c),
|
||||
[1; 6],
|
||||
"markers outside observer scope are inert"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! The production adapters consume actual trait results and own their pending work.
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_qa_discover_uses_requested_revision_capabilities() {
|
||||
use crate::protocol::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityRegistry, METHOD_DESCRIPTORS,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut outcomes = Vec::new();
|
||||
for revisions in [&["2026-07-28"][..], &["2025-11-25"][..]] {
|
||||
let mut descriptors = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
descriptors
|
||||
.iter_mut()
|
||||
.find(|d| d.id == CapabilityId::Tools)
|
||||
.unwrap()
|
||||
.revisions = revisions;
|
||||
let registration =
|
||||
Arc::new(CapabilityRegistry::new(&descriptors, METHOD_DESCRIPTORS).unwrap());
|
||||
crate::app::dispatch_observer::observe_with_registration(registration, async {
|
||||
let expected = advertised_server_capabilities("2026-07-28");
|
||||
let actual = discover("2026-07-28").await.unwrap();
|
||||
outcomes.push((
|
||||
expected["tools"].clone(),
|
||||
actual["capabilities"]["tools"].clone(),
|
||||
));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
vec![
|
||||
(json!({"listChanged":true}), json!({"listChanged":true})),
|
||||
(Value::Null, Value::Null)
|
||||
],
|
||||
"modern-only tools must be advertised; legacy-only tools must not leak into modern discovery"
|
||||
);
|
||||
}
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Control {
|
||||
calls: AtomicUsize,
|
||||
dropped: AtomicBool,
|
||||
finished: AtomicBool,
|
||||
fail: bool,
|
||||
pending: bool,
|
||||
}
|
||||
struct Witness<'a>(&'a AtomicBool);
|
||||
impl Drop for Witness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
fn error() -> ErrorData {
|
||||
ErrorData::new(
|
||||
ErrorCode(-32042),
|
||||
"typed negotiation failure",
|
||||
Some(json!({"proof":42})),
|
||||
)
|
||||
}
|
||||
impl Control {
|
||||
async fn enter(&self, context: &RequestContext<RoleServer>) -> Result<(), ErrorData> {
|
||||
assert!(
|
||||
context.peer.is_transport_closed(),
|
||||
"bootstrap closes before handler"
|
||||
);
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
let _witness = Witness(&self.dropped);
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
self.finished.store(true, SeqCst);
|
||||
if self.fail { Err(error()) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
impl ServerHandler for Control {
|
||||
async fn initialize(
|
||||
&self,
|
||||
request: InitializeRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<InitializeResult, ErrorData> {
|
||||
self.enter(&context).await?;
|
||||
let mut result = ServerHandler::initialize(&NegotiationHandler, request, context).await?;
|
||||
result.server_info = Implementation::new("typed-initialize", "42");
|
||||
result.capabilities.tools = None;
|
||||
Ok(result)
|
||||
}
|
||||
async fn discover(
|
||||
&self,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<DiscoverResult, ErrorData> {
|
||||
self.enter(&context).await?;
|
||||
let mut result = ServerHandler::discover(&NegotiationHandler, context).await?;
|
||||
result = result.with_server_info(Implementation::new("typed-discover", "42"));
|
||||
result.capabilities.tools = None;
|
||||
Ok(result)
|
||||
}
|
||||
async fn ping(&self, context: RequestContext<RoleServer>) -> Result<(), ErrorData> {
|
||||
self.enter(&context).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_mutated_typed_success_is_consumed() {
|
||||
let h = Control::default();
|
||||
let init = initialize_with(&h, "2025-11-25").await.unwrap();
|
||||
assert_eq!(init["serverInfo"]["name"], "typed-initialize");
|
||||
assert!(init["capabilities"].get("tools").is_none());
|
||||
let discover = discover_with(&h, "2026-07-28").await.unwrap();
|
||||
assert_eq!(
|
||||
discover["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
|
||||
"typed-discover"
|
||||
);
|
||||
assert!(discover["capabilities"].get("tools").is_none());
|
||||
ping_with(&h).await.unwrap();
|
||||
assert_eq!(h.calls.load(SeqCst), 3, "no bootstrap invocation");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_typed_errors_are_not_success() {
|
||||
let h = Control {
|
||||
fail: true,
|
||||
..Default::default()
|
||||
};
|
||||
for actual in [
|
||||
initialize_with(&h, "2025-11-25").await.unwrap_err(),
|
||||
discover_with(&h, "2026-07-28").await.unwrap_err(),
|
||||
ping_with(&h).await.unwrap_err(),
|
||||
] {
|
||||
assert_eq!(actual, error());
|
||||
for mode in [
|
||||
crate::transport::ResponseMode::Json,
|
||||
crate::transport::ResponseMode::Sse,
|
||||
] {
|
||||
let response = super::super::dispatch::sdk_error_response(
|
||||
&json!({"id":"typed-error"}),
|
||||
mode,
|
||||
"2025-11-25",
|
||||
actual.clone(),
|
||||
);
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(response.headers().get("mcp-session-id").is_none());
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let raw = std::str::from_utf8(&bytes).unwrap();
|
||||
let body: Value = match mode {
|
||||
crate::transport::ResponseMode::Json => serde_json::from_str(raw).unwrap(),
|
||||
crate::transport::ResponseMode::Sse => serde_json::from_str(
|
||||
raw.lines()
|
||||
.find_map(|l| l.strip_prefix("data:"))
|
||||
.unwrap()
|
||||
.trim(),
|
||||
)
|
||||
.unwrap(),
|
||||
};
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({"jsonrpc":"2.0","id":"typed-error","error":{"code":-32042,"message":"typed negotiation failure","data":{"proof":42}}})
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(h.calls.load(SeqCst), 3);
|
||||
assert!(initialize("not-supported").await.is_err());
|
||||
assert_eq!(
|
||||
NegotiationHandler
|
||||
.supported_protocol_versions()
|
||||
.iter()
|
||||
.map(|v| v.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_negotiation_handler_drop_cancels_request_owned_work() {
|
||||
for method in 0..3 {
|
||||
let h = Control {
|
||||
pending: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut future = Box::pin(async {
|
||||
match method {
|
||||
0 => {
|
||||
initialize_with(&h, "2025-11-25").await?;
|
||||
}
|
||||
1 => {
|
||||
discover_with(&h, "2026-07-28").await?;
|
||||
}
|
||||
_ => {
|
||||
ping_with(&h).await?;
|
||||
}
|
||||
}
|
||||
Ok::<_, ErrorData>(())
|
||||
});
|
||||
tokio::select! {
|
||||
result = &mut future => panic!("pending handler completed: {result:?}"),
|
||||
_ = async { while h.calls.load(SeqCst) == 0 { tokio::task::yield_now().await; } } => {}
|
||||
}
|
||||
assert!(!h.dropped.load(SeqCst));
|
||||
drop(future);
|
||||
assert!(h.dropped.load(SeqCst));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!h.finished.load(SeqCst));
|
||||
assert_eq!(h.calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! #107 real HTTP contract for awaited legacy SDK notification handlers.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::support::*;
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Duration;
|
||||
|
||||
async fn legacy_session(h: &Endpoint) -> String {
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
None,
|
||||
&h.key,
|
||||
"application/json",
|
||||
legacy_initialize(801),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body: Value = json_body(response).await;
|
||||
assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
session
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_handler_executes_and_is_consumed_by_real_http_caller() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = legacy_session(&h).await;
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202, "legacy HTTP wire positive control");
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert!(h.sessions.retained(&session).await.unwrap().initialized);
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_completed(),
|
||||
1,
|
||||
"real awaited on_initialized must complete its durable operation"
|
||||
);
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_consumed(),
|
||||
1,
|
||||
"HTTP caller must consume the outcome of that same SDK handler"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_handler_executes_and_is_consumed_for_owned_active_call() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
let call = h.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(802),
|
||||
Some(json!("cancel")),
|
||||
"text/event-stream",
|
||||
);
|
||||
let active = tokio::spawn(async move { call.send().await.unwrap().text().await.unwrap() });
|
||||
h.wait_started(1).await;
|
||||
h.cancel(&h.key, &session, json!({"requestId":802})).await;
|
||||
tokio::time::timeout(Duration::from_secs(2), active)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
h.counters.sdk_cancelled_handler_completed(),
|
||||
1,
|
||||
"real awaited on_cancelled must cancel the owned call"
|
||||
);
|
||||
assert_eq!(
|
||||
h.counters.sdk_cancelled_handler_consumed(),
|
||||
1,
|
||||
"HTTP caller must consume the outcome of that same SDK handler"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_notifications_remain_ack_only_without_legacy_handlers() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let before = h.sessions.snapshot();
|
||||
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":modern_meta()}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":802,"_meta":modern_meta()}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_session_ops(
|
||||
"modern notification ACK",
|
||||
before,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_completed(), 0);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_consumed(), 0);
|
||||
assert_eq!(h.counters.sdk_cancelled_handler_completed(), 0);
|
||||
assert_eq!(h.counters.sdk_cancelled_handler_consumed(), 0);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//! Direct controls of the production awaited notification boundary.
|
||||
use super::*;
|
||||
use crate::session::{
|
||||
InMemorySessionStore, SessionState, SessionStoreError, TransportSessionStore,
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Store {
|
||||
inner: InMemorySessionStore,
|
||||
marks: AtomicUsize,
|
||||
reads: AtomicUsize,
|
||||
entered: AtomicBool,
|
||||
dropped: AtomicBool,
|
||||
pending: AtomicBool,
|
||||
fail_get: AtomicBool,
|
||||
gate: tokio::sync::Notify,
|
||||
}
|
||||
struct Witness<'a>(&'a AtomicBool);
|
||||
impl Drop for Witness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Store {
|
||||
async fn wait(&self) {
|
||||
if self.pending.load(SeqCst) {
|
||||
let _witness = Witness(&self.dropped);
|
||||
self.entered.store(true, SeqCst);
|
||||
self.gate.notified().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for Store {
|
||||
async fn create(
|
||||
&self,
|
||||
v: &str,
|
||||
w: &str,
|
||||
a: &str,
|
||||
e: bool,
|
||||
n: OffsetDateTime,
|
||||
x: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.inner.create(v, w, a, e, n, x).await
|
||||
}
|
||||
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
self.wait().await;
|
||||
self.reads.fetch_add(1, SeqCst);
|
||||
if self.fail_get.load(SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test read refusal".into(),
|
||||
});
|
||||
}
|
||||
self.inner.get(id).await
|
||||
}
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
id: &str,
|
||||
n: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
self.wait().await;
|
||||
self.marks.fetch_add(1, SeqCst);
|
||||
self.inner.mark_initialized(id, n).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(id).await
|
||||
}
|
||||
async fn cleanup_expired(&self, n: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(n).await
|
||||
}
|
||||
async fn active_count(&self, n: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(n).await
|
||||
}
|
||||
}
|
||||
async fn fixture() -> (Arc<AppState>, Arc<Store>, String) {
|
||||
let mut state = (*super::super::rmcp_tools_tests::test_state().await).clone();
|
||||
let store = Arc::new(Store::default());
|
||||
let id = store
|
||||
.create(
|
||||
"2025-11-25",
|
||||
"w",
|
||||
"a",
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state.sessions = store.clone();
|
||||
(Arc::new(state), store, id)
|
||||
}
|
||||
fn initialized_handler(state: Arc<AppState>, id: &str) -> OutcomeHandler {
|
||||
OutcomeHandler {
|
||||
operation: Operation::Initialized {
|
||||
state,
|
||||
session_id: id.to_owned(),
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
fn cancelled_handler(state: Arc<AppState>, id: &str, raw: Option<Value>) -> OutcomeHandler {
|
||||
OutcomeHandler {
|
||||
operation: Operation::Cancelled {
|
||||
state,
|
||||
path: AgentRoutePath {
|
||||
workspace_slug: "w".into(),
|
||||
agent_slug: "a".into(),
|
||||
},
|
||||
credential: VerifiedMachineCredential {
|
||||
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
scopes: vec![],
|
||||
platform_api_key_id: None,
|
||||
},
|
||||
session_id: Some(id.to_owned()),
|
||||
request_id: raw,
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
struct Noop;
|
||||
impl ServerHandler for Noop {}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_noop_and_bootstrap_failure_have_no_effect() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let init = initialized_handler(state.clone(), &id);
|
||||
assert_eq!(
|
||||
initialized_with(&Noop, &init, notification_context()).await,
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
initialized_with(&init, &init, async { Err(()) }).await,
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
let cancel = cancelled_handler(state.clone(), &id, None);
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(1))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":1})).unwrap();
|
||||
cancelled_with(&Noop, &cancel, params.clone(), notification_context()).await;
|
||||
cancelled_with(&cancel, &cancel, params, async { Err(()) }).await;
|
||||
assert!(cancel.take().is_none());
|
||||
assert_eq!(store.marks.load(SeqCst), 0);
|
||||
assert_eq!(store.reads.load(SeqCst), 0);
|
||||
assert!(!store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
// Positive control: exactly one durable operation, and the caller drains its outcome.
|
||||
assert_eq!(
|
||||
initialized_with(&init, &init, notification_context()).await,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
assert_eq!(store.marks.load(SeqCst), 1);
|
||||
assert!(init.take().is_none());
|
||||
assert!(store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
}
|
||||
|
||||
struct Mutate(Arc<OutcomeHandler>, NumberOrString);
|
||||
impl ServerHandler for Mutate {
|
||||
async fn on_cancelled(
|
||||
&self,
|
||||
mut p: CancelledNotificationParam,
|
||||
ctx: NotificationContext<RoleServer>,
|
||||
) {
|
||||
assert!(ctx.peer.is_transport_closed());
|
||||
p.request_id = Some(self.1.clone());
|
||||
ServerHandler::on_cancelled(self.0.as_ref(), p, ctx).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_typed_target_mutation_and_raw_number_separation() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
for raw in [
|
||||
serde_json::json!(18446744073709551615_u64),
|
||||
serde_json::json!(1.25),
|
||||
] {
|
||||
let numeric = state.in_flight.register(&scope, &raw).unwrap();
|
||||
let text = state
|
||||
.in_flight
|
||||
.register(&scope, &Value::String(raw.to_string()))
|
||||
.unwrap();
|
||||
let changed = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(42))
|
||||
.unwrap();
|
||||
let (params, original) = cancelled_params(&serde_json::json!({"requestId":raw})).unwrap();
|
||||
let h = Arc::new(cancelled_handler(state.clone(), &id, original));
|
||||
let mutation = Mutate(h.clone(), NumberOrString::Number(42));
|
||||
cancelled_with(
|
||||
&mutation,
|
||||
h.as_ref(),
|
||||
params.clone(),
|
||||
notification_context(),
|
||||
)
|
||||
.await;
|
||||
assert!(futures_util::poll!(Box::pin(changed.cancel_signal().cancelled())).is_ready());
|
||||
assert!(futures_util::poll!(Box::pin(numeric.cancel_signal().cancelled())).is_pending());
|
||||
assert!(futures_util::poll!(Box::pin(text.cancel_signal().cancelled())).is_pending());
|
||||
assert!(h.take().is_none());
|
||||
cancelled_with(h.as_ref(), h.as_ref(), params, notification_context()).await;
|
||||
assert!(futures_util::poll!(Box::pin(numeric.cancel_signal().cancelled())).is_ready());
|
||||
assert!(futures_util::poll!(Box::pin(text.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
assert_eq!(
|
||||
store.reads.load(SeqCst),
|
||||
4,
|
||||
"one lookup per real callback, no bootstrap effects"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_store_read_refusal_does_not_cancel() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(7))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":7})).unwrap();
|
||||
let h = cancelled_handler(state, &id, None);
|
||||
store.fail_get.store(true, SeqCst);
|
||||
ServerHandler::on_cancelled(&h, params, notification_context().await.unwrap()).await;
|
||||
assert_eq!(h.take(), Some(StatusCode::ACCEPTED));
|
||||
assert_eq!(store.reads.load(SeqCst), 1);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_pending_store_drop_stops_initialized_and_cancelled() {
|
||||
let (state, store, id) = fixture().await;
|
||||
for cancel in [false, true] {
|
||||
store.pending.store(true, SeqCst);
|
||||
store.entered.store(false, SeqCst);
|
||||
store.dropped.store(false, SeqCst);
|
||||
let h = if cancel {
|
||||
cancelled_handler(state.clone(), &id, None)
|
||||
} else {
|
||||
initialized_handler(state.clone(), &id)
|
||||
};
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(7))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":7})).unwrap();
|
||||
let mut future = Box::pin(async {
|
||||
if cancel {
|
||||
cancelled_with(&h, &h, params, notification_context()).await;
|
||||
} else {
|
||||
initialized_with(&h, &h, notification_context()).await;
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
tokio::select! {
|
||||
_ = &mut future => panic!("pending operation completed"),
|
||||
_ = async { while !store.entered.load(SeqCst) { tokio::task::yield_now().await; } } => {}
|
||||
}
|
||||
}).await.unwrap();
|
||||
assert!(!store.dropped.load(SeqCst));
|
||||
drop(future);
|
||||
assert!(
|
||||
store.dropped.load(SeqCst),
|
||||
"the actual store future belongs to this await"
|
||||
);
|
||||
store.gate.notify_waiters();
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(store.marks.load(SeqCst), 0);
|
||||
assert_eq!(store.reads.load(SeqCst), 0);
|
||||
assert!(h.take().is_none());
|
||||
assert!(!store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,10 @@ async fn success_control(revision: &str) -> Vec<(usize, usize)> {
|
||||
] {
|
||||
let counters = h.counters.snapshot();
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = (h.counters.sdk_ping_request(), h.counters.sdk_ping_result());
|
||||
let before = (
|
||||
h.counters.sdk_ping_handler_completed(),
|
||||
h.counters.sdk_ping_handler_consumed(),
|
||||
);
|
||||
let response = correlated(h.request(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
@@ -118,8 +121,8 @@ async fn success_control(revision: &str) -> Vec<(usize, usize)> {
|
||||
},
|
||||
);
|
||||
sdk.push((
|
||||
h.counters.sdk_ping_request() - before.0,
|
||||
h.counters.sdk_ping_result() - before.1,
|
||||
h.counters.sdk_ping_handler_completed() - before.0,
|
||||
h.counters.sdk_ping_handler_consumed() - before.1,
|
||||
));
|
||||
eprintln!(
|
||||
"existing GREEN ping revision={revision} accept={accept} extended={extended}; SDK delta={:?}",
|
||||
@@ -176,9 +179,20 @@ async fn ping_guards_never_enter_sdk() {
|
||||
assert!(wire.get("result").is_none());
|
||||
}
|
||||
assert_eq!(
|
||||
(h.counters.sdk_ping_request(), h.counters.sdk_ping_result()),
|
||||
(
|
||||
h.counters.sdk_ping_handler_completed(),
|
||||
h.counters.sdk_ping_handler_consumed()
|
||||
),
|
||||
(0, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
h.counters.sdk_ping_handler_completed(),
|
||||
h.counters.sdk_ping_handler_consumed()
|
||||
),
|
||||
(0, 0),
|
||||
"pre-handler guard rejection must not execute or consume the SDK ping handler"
|
||||
);
|
||||
eprintln!("existing GREEN pre-seam guard revision={revision}; SDK=(0,0)");
|
||||
}
|
||||
}
|
||||
@@ -186,24 +200,37 @@ async fn ping_guards_never_enter_sdk() {
|
||||
#[tokio::test]
|
||||
async fn ping_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
let request: rmcp::model::PingRequest =
|
||||
serde_json::from_value(json!({"method":"ping"})).unwrap();
|
||||
observe(c.clone(), async {
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 0));
|
||||
super::sdk_ping_result_serialized();
|
||||
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 1));
|
||||
super::sdk_ping_handler_completed();
|
||||
assert_eq!(
|
||||
(
|
||||
c.sdk_ping_handler_completed(),
|
||||
c.sdk_ping_handler_consumed()
|
||||
),
|
||||
(1, 0)
|
||||
);
|
||||
super::sdk_ping_handler_consumed();
|
||||
assert_eq!(
|
||||
(
|
||||
c.sdk_ping_handler_completed(),
|
||||
c.sdk_ping_handler_consumed()
|
||||
),
|
||||
(1, 1)
|
||||
);
|
||||
})
|
||||
.await;
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
super::sdk_ping_handler_completed();
|
||||
super::sdk_ping_handler_consumed();
|
||||
observe(Arc::new(CounterSet::default()), async {
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
super::sdk_ping_handler_completed();
|
||||
super::sdk_ping_handler_consumed();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(c.sdk_ping_request(), c.sdk_ping_result()),
|
||||
(
|
||||
c.sdk_ping_handler_completed(),
|
||||
c.sdk_ping_handler_consumed()
|
||||
),
|
||||
(1, 1),
|
||||
"scope isolation and out-of-scope no-op"
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,8 @@ Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `com
|
||||
|
||||
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
|
||||
|
||||
Logging-handler-срез #107 поверх rc.38/rmcp3.9.0 подключает legacy `LoggingSetLevel` в `app/legacy_dispatch.rs` к прямому request-owned await `ServerHandler::set_level` в `app/rmcp_logging.rs`. Override применяет именно typed level к прежнему session store, активирует request-local level и записывает safe event; actual Result/ErrorData определяет JSON/SSE ответ. Bounded command validation остаётся до инертного bootstrap, bootstrap закрыт до рабочего handler. DTO-only execution оставлен только для старых protocol unit tests. HTTP completion/consumption, восемь levels, ignored extensions/admission, session/revocation guards и modern rejection дополняются direct typed mutation/error/single-execution/pending-drop controls; logging matrix и streamed carried scope сохраняются. try_lock skip по-прежнему не подтверждается readback и не превращается в blocking write; drop до эффекта не обещает rollback выполненного store.set. SDK Peer callbacks/transport/SessionManager не подключены; #107 остаётся partial, full/load/external-client qualification и production не входят в срез.
|
||||
|
||||
Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает штатный SSE `lifecycle::progress_frame` обеих revisions к сериализации `ProgressNotificationParam`, а legacy `handle_cancelled_notification` — к декодированию `CancelledNotificationParam.request_id`. Локальная projection+restore сохраняет исходные JSON numbers токена/ID и целочисленный u64 progress, включая значения вне i64/exact-f64; message и omissions берутся из SDK. Decoder передаёт SDK только requestId, не валидируя reason/_meta/extensions. Session+credential ownership, bounded queues/slots, transport, auth и modern stream-close cancellation не меняются. Runtime ATDD подтверждает SDK seams отдельно от wire; unit regression проверяет точную числовую форму. Decoder ignore действует только после HTTP admission: `_meta:[]` сохраняет прежний HTTP400/-32020 до SDK decoder. Отдельная HTTP-регрессия проверяет отказ без отмены активного вызова, а допустимый `_meta:{}` с reason/extensions — успешную SDK-отмену. Это частичная миграция params, не завершение #107, feature qualification или production deployment.
|
||||
|
||||
Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены.
|
||||
@@ -51,8 +53,12 @@ Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет
|
||||
|
||||
Ping-срез #107 на базе rc.28/rmcp3.9.0 подключает обе штатные HTTP ветки к общему `protocol/lifecycle_sdk.rs::ping_result`: проекция уже допущенного метода декодируется в `PingRequest`, его SDK request variant выбирает `ServerResult::empty(())`, а сериализованный SDK результат поступает в прежний JSON/SSE terminal. Удалены два handwritten ping result builder; Crank добавляет прежний `protocolVersion` из legacy session либо modern identity, а modern result projection сохраняется. Игнорируемые params/extensions не получают новых SDK ограничений. Legacy initialized-session guard остаётся перед helper; modern ping не обращается к sessions. Runtime ATDD отдельно подтверждает SDK request/result execution и прежние wire/status/headers/id/correlation обеих revisions; affected regressions проверяют session/admission/method/revocation guards. Generic dispatch, session storage/TTL/reconnect, admission/auth и transport остаются прежними; полный #107, feature qualification и production deployment не завершены.
|
||||
|
||||
Negotiation-handler-срез #107 поверх rc.36/rmcp3.9.0 заменяет описанные выше DTO-only negotiation/ping helpers на прямые await настоящих `ServerHandler::initialize/discover/ping` в request-owned `app/rmcp_negotiation.rs`. Реальные consumers — legacy initialize/ping и modern discover/ping штатного `build_app` JSON/SSE; typed Result/ErrorData определяет ответ, а legacy session создаётся только после успешного initialize. Bootstrap инертен и закрывается до handler; pending trait future принадлежит запросу и прекращается при drop. Allowlist/порядок revisions, registry capabilities, identity, discovery cache hints, ignored inputs и прежние durable guards сохранены; projection восстанавливает только непредставимые SDK registry extensions и era-specific wire omissions. HTTP completed/consumed oracle обеих revisions дополнен typed-result mutation/error и drop controls; прежние wire/session/admission/revocation проверки сохраняются. DTO-only production builders удалены, initialized notification остаётся прежним typed переходом. Это не перенос SDK HTTP transport/SessionManager, callbacks или полного lifecycle: #107 остаётся open/partial, bootstrap performance и full/load/external-client qualification не завершены; #108/4.7/production не запускаются.
|
||||
|
||||
Initialized-срез #107 на базе rc.29/rmcp3.9.0 подключает штатный legacy HTTP handshake к `InitializedNotification` и `ClientNotification`: после registry/admission проекция метода декодируется SDK, а matched initialized variant после прежних session/scope guards разрешает существующий durable `mark_initialized`. Игнорируемые params/extensions, 202 с пустым телом, JSON/SSE и modern no-session поведение сохранены; SDK SessionManager не используется. Runtime-тесты отдельно наблюдают decoding и consumption, проверяют PostgreSQL reconnect и отказ store на чтении/записи. Это только lifecycle-срез, не завершение #107.
|
||||
|
||||
Notification handler-срез #107 на базе rc.37/rmcp3.9.0 заменяет DTO-only execution legacy `notifications/initialized` и `notifications/cancelled` прямым await настоящих `ServerHandler::on_initialized/on_cancelled` в `app/rmcp_notifications.rs`. Ближайшие подключённые consumers — `dispatch::handle_initialized_notification` и `legacy_dispatch::handle_cancelled_notification` штатного `build_app` HTTP. Durable mark и scoped lookup/cancel выполняются внутри overrides; caller забирает request-local outcome после await, сохраняя empty202/400/404/500 и непрозрачный cancellation ACK. Инертный capture-bootstrap получает настоящий SDK NotificationContext и закрывается до рабочего handler; closed Peer callbacks не поддерживает. No-op/missing outcome, typed-target mutation, numeric/string separation, bootstrap refusal и pending store drop controls дополняют HTTP completed/consumed ATDD; PostgreSQL reconnect/read/write refusal и исчезновение session между get/mark сохраняют прежние guards. Drop прекращает polling request-owned операции, но не обещает rollback уже отправленного SQL или отзыв выполненной отмены. Modern notifications остаются ACK-only без sessions/domain; storage/TTL/reconnect, capabilities, progress/logging/signals/subscriptions и transport не заменены SDK defaults. Старый cancellation decoder оставлен только как test entry к новому production decoder. #107 остаётся open/partial; full/load/external-client qualification, bootstrap performance, #108/4.7 и production не входят в срез.
|
||||
|
||||
Envelope-dispatch-срез #107 на базе rc.30/rmcp3.9.0 подключает обе действующие HTTP ветки `app/dispatch.rs` и `app/legacy_dispatch.rs` к общему `protocol/dispatch_sdk.rs`: после прежних admission/auth guards минимальная проекция декодируется в настоящие `JsonRpcRequest<Value>`/`JsonRpcNotification<Value>`. SDK payload method выбирает прежний `registry::dispatch_decision`, SDK variant определяет request/notification routing вместо повторных raw-JSON predicates. Второй таблицы методов нет; registry остаётся policy gate revisions/capabilities/registered kind. Modern notification ACK по-прежнему предшествует request-only Mcp-Method/Mcp-Name checks и не обращается к sessions/domain. Params и ignored extensions/result/error остаются вне routing projection; SDK-incompatible числовые ID получают только внутренний surrogate, исходные ID/числовая форма остаются в raw message для wire/correlation/cancellation ownership. Для выбранного registry Ping handler typed projection использует canonical ping, сохраняя registered alias semantics. Runtime HTTP ATDD отдельно проверяет SDK decode/consumption и прежний JSON/SSE wire; affected registry/admission, durable initialized/reconnect, progress/cancel и auth guards проверяются без замены storage/transport. Это перенос только generic request/notification envelope routing: domain/generic handler execution, inbound response/error envelopes и их shape validation, session storage/TTL/reconnect, transport и feature qualification остаются вне среза. Полный #107 остаётся open; #108/4.7 и production switch не запускаются.
|
||||
|
||||
Inbound-response-срез #107 на базе rc.31/rmcp3.9.0 подключает no-method ветку общего envelope guard к `protocol/response_sdk.rs`: реальные `JsonRpcResponse<Value>`/`JsonRpcError` определяют response classification и ранний HTTP202 ACK штатного `build_app` POST обеих revisions. Сохранены object-only result без обязательного resultType, exclusivity result/error, optional error id, произвольные data/params/extensions и любые JSON number id/code; только SDK-несовместимые числа получают внутренние surrogates после проверки исходного wire-предиката, raw message не меняется. Заменён handwritten response classifier/error-object parser. Обнаруженный ATDD обход credentials ранним ACK устранён свежей read-авторизацией no-method сообщений до SDK decode; порядок method-bearing запросов не меняется. Origin/Accept/ambiguous carrier checks предшествуют decode/ACK, ACK остаётся до era/session resolution без session/domain вызовов. HTTP wire и SDK decoded/consumed oracles проверяются отдельно. Domain/generic handler execution, session storage/TTL/reconnect, transport и feature qualification остаются вне среза; полный #107 остаётся open, #108/4.7/production не запускаются.
|
||||
@@ -61,6 +67,8 @@ Prompts handler-срез #107 на базе rc.33 заменяет прежни
|
||||
|
||||
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