Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b769a2ed2e | ||
|
|
0139eeaac6 | ||
|
|
5cce1b09df | ||
|
|
5b0af84d5a | ||
|
|
9b3e0248d1 | ||
|
|
163b519979 | ||
|
|
65144fd8c6 | ||
|
|
66bb135398 | ||
|
|
0de1e94df4 | ||
|
|
7a1fc0d761 | ||
|
|
156a849087 | ||
|
|
a4cf5ed8cf | ||
|
|
326f209bc5 | ||
|
|
c32e24b268 | ||
|
|
8068fd7910 | ||
|
|
ca126004af | ||
|
|
2f9c4cb568 | ||
|
|
61378224b2 | ||
|
|
1b51d44121 | ||
|
|
077be3b069 | ||
|
|
42e7728b3a | ||
|
|
541b135baf |
No files matched your search
@@ -34,6 +34,7 @@ pub(crate) mod lifecycle;
|
||||
mod metrics;
|
||||
mod request;
|
||||
mod response;
|
||||
mod rmcp_completion;
|
||||
mod rmcp_dispatch;
|
||||
#[cfg(test)]
|
||||
mod rmcp_http;
|
||||
@@ -41,6 +42,10 @@ mod rmcp_http;
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
mod rmcp_progress_cancel;
|
||||
mod rmcp_prompts;
|
||||
mod rmcp_prompts_projection;
|
||||
mod rmcp_resources;
|
||||
mod rmcp_resources_projection;
|
||||
#[cfg(test)]
|
||||
mod rmcp_session_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,17 +5,14 @@
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is called from
|
||||
//! `app/endpoint.rs`, so the entry points are `pub(super)`. No behaviour changed.
|
||||
|
||||
use super::request::{InitializeParams, ToolCallParams};
|
||||
use super::request::ToolCallParams;
|
||||
use super::response::take_confirmation_token;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version,
|
||||
params, request_id,
|
||||
},
|
||||
jsonrpc::{jsonrpc_error, jsonrpc_result, negotiated_protocol_version, params, request_id},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
@@ -81,7 +78,20 @@ pub(super) async fn handle_modern_request(
|
||||
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
||||
// already run at this point, so this early return cannot admit a malformed identity or a session
|
||||
// conflict, and the notification is never dispatched.
|
||||
if is_notification(message) {
|
||||
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
|
||||
Ok(Some(envelope)) => envelope,
|
||||
_ => {
|
||||
return internal_jsonrpc_error(
|
||||
message,
|
||||
"admitted dispatch envelope could not be decoded",
|
||||
);
|
||||
}
|
||||
};
|
||||
let method = envelope.method();
|
||||
let notification = envelope.is_notification();
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_dispatch_envelope_consumed();
|
||||
if notification {
|
||||
return crate::protocol::modern_notification_response();
|
||||
}
|
||||
|
||||
@@ -89,15 +99,14 @@ pub(super) async fn handle_modern_request(
|
||||
Ok(declared_method) => declared_method,
|
||||
Err(response) => return *response,
|
||||
};
|
||||
if declared_method != method_name(message) {
|
||||
if declared_method != method {
|
||||
return crate::protocol::modern_header_mismatch_response(message);
|
||||
}
|
||||
|
||||
// R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by
|
||||
// the owning registration (not by a literal method list inside this adapter), and a method whose
|
||||
// capability is not eligible in this revision is never served here.
|
||||
let dispatch =
|
||||
crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version);
|
||||
let dispatch = crate::protocol::dispatch_decision(method.unwrap_or_default(), version);
|
||||
match dispatch {
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Discover,
|
||||
@@ -121,7 +130,7 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
json!({ "protocolVersion": version }),
|
||||
crate::protocol::ping_result(&json!({"method": "ping"}), version),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -406,8 +415,7 @@ pub(super) async fn handle_modern_request(
|
||||
};
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
command,
|
||||
)
|
||||
@@ -777,7 +785,8 @@ pub(super) async fn handle_initialize(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
) -> Response {
|
||||
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
|
||||
let raw_params = params(message);
|
||||
let initialize_params = match crate::protocol::initialize_params(&raw_params) {
|
||||
Ok(value) => value,
|
||||
Err(_error) => {
|
||||
return transport_response(
|
||||
@@ -789,7 +798,10 @@ pub(super) async fn handle_initialize(
|
||||
);
|
||||
}
|
||||
};
|
||||
let Some(protocol_version) = negotiated_protocol_version(&initialize_params.protocol_version)
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialize_input_consumed(&initialize_params);
|
||||
let Some(protocol_version) =
|
||||
negotiated_protocol_version(initialize_params.protocol_version.as_str())
|
||||
else {
|
||||
// A revision outside the approved window is rejected without minting a session and without
|
||||
// echoing any withdrawn revision as the served identity.
|
||||
@@ -810,9 +822,9 @@ pub(super) async fn handle_initialize(
|
||||
};
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||
let supports_elicitation = initialize_params
|
||||
.capabilities
|
||||
.get("elicitation")
|
||||
let supports_elicitation = raw_params
|
||||
.get("capabilities")
|
||||
.and_then(|capabilities| capabilities.get("elicitation"))
|
||||
.is_some_and(Value::is_object);
|
||||
let session_id = match state
|
||||
.sessions
|
||||
@@ -835,14 +847,7 @@ pub(super) async fn handle_initialize(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!( {
|
||||
"protocolVersion": protocol_version,
|
||||
"capabilities": crate::protocol::advertised_server_capabilities(protocol_version),
|
||||
"serverInfo": {
|
||||
"name": SERVER_NAME,
|
||||
"version": SERVER_VERSION
|
||||
}
|
||||
}),
|
||||
crate::protocol::initialize_result(protocol_version, SERVER_NAME, SERVER_VERSION),
|
||||
),
|
||||
response_mode,
|
||||
Some(&session_id),
|
||||
@@ -854,6 +859,7 @@ pub(super) async fn handle_initialized_notification(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
notification: rmcp::model::ClientNotification,
|
||||
) -> Response {
|
||||
match session_id_from_headers(headers) {
|
||||
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
||||
@@ -861,6 +867,15 @@ pub(super) async fn handle_initialized_notification(
|
||||
if session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug =>
|
||||
{
|
||||
let rmcp::model::ClientNotification::InitializedNotification(initialized) =
|
||||
notification
|
||||
else {
|
||||
unreachable!("initialized handler requires the SDK initialized variant")
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
|
||||
#[cfg(not(test))]
|
||||
let _ = initialized;
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
|
||||
@@ -55,22 +55,145 @@ pub(crate) struct CounterSet {
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
sdk_resources_dispatch: AtomicUsize,
|
||||
sdk_resources_list_handler_completed: AtomicUsize,
|
||||
sdk_resources_read_handler_completed: AtomicUsize,
|
||||
sdk_resources_templates_handler_completed: AtomicUsize,
|
||||
sdk_resources_list_handler_consumed: AtomicUsize,
|
||||
sdk_resources_read_handler_consumed: AtomicUsize,
|
||||
sdk_resources_templates_handler_consumed: AtomicUsize,
|
||||
sdk_resources_list_result: AtomicUsize,
|
||||
sdk_resources_read_result: AtomicUsize,
|
||||
sdk_resource_templates_list_result: AtomicUsize,
|
||||
sdk_prompts_list_handler_completed: AtomicUsize,
|
||||
sdk_prompts_get_handler_completed: AtomicUsize,
|
||||
sdk_prompts_list_handler_consumed: AtomicUsize,
|
||||
sdk_prompts_get_handler_consumed: AtomicUsize,
|
||||
sdk_prompts_dispatch: AtomicUsize,
|
||||
sdk_prompts_list_result: AtomicUsize,
|
||||
sdk_prompts_get_result: AtomicUsize,
|
||||
sdk_completion_dispatch: AtomicUsize,
|
||||
sdk_completion_result: AtomicUsize,
|
||||
sdk_completion_handler_completed: AtomicUsize,
|
||||
sdk_completion_handler_consumed: AtomicUsize,
|
||||
sdk_logging_dispatch: AtomicUsize,
|
||||
sdk_logging_level: AtomicUsize,
|
||||
sdk_logging_notification: AtomicUsize,
|
||||
sdk_progress_notification: AtomicUsize,
|
||||
sdk_cancelled_params: AtomicUsize,
|
||||
sdk_subscriptions_listen: AtomicUsize,
|
||||
sdk_subscriptions_acknowledged: AtomicUsize,
|
||||
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,
|
||||
sdk_inbound_error_consumed: AtomicUsize,
|
||||
sdk_dispatch_decoded: AtomicUsize,
|
||||
sdk_dispatch_consumed: AtomicUsize,
|
||||
sdk_initialized_decoded: AtomicUsize,
|
||||
sdk_initialized_consumed: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_prompts_list_handler_completed(&self) -> usize {
|
||||
self.sdk_prompts_list_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_get_handler_completed(&self) -> usize {
|
||||
self.sdk_prompts_get_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_list_handler_consumed(&self) -> usize {
|
||||
self.sdk_prompts_list_handler_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_get_handler_consumed(&self) -> usize {
|
||||
self.sdk_prompts_get_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_list_handler_completed(&self) -> usize {
|
||||
self.sdk_resources_list_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_read_handler_completed(&self) -> usize {
|
||||
self.sdk_resources_read_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_templates_handler_completed(&self) -> usize {
|
||||
self.sdk_resources_templates_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_list_handler_consumed(&self) -> usize {
|
||||
self.sdk_resources_list_handler_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_read_handler_consumed(&self) -> usize {
|
||||
self.sdk_resources_read_handler_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_resources_templates_handler_consumed(&self) -> usize {
|
||||
self.sdk_resources_templates_handler_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_response_decoded(&self) -> usize {
|
||||
self.sdk_inbound_response_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_error_decoded(&self) -> usize {
|
||||
self.sdk_inbound_error_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_response_consumed(&self) -> usize {
|
||||
self.sdk_inbound_response_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_error_consumed(&self) -> usize {
|
||||
self.sdk_inbound_error_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_dispatch_decoded(&self) -> usize {
|
||||
self.sdk_dispatch_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_dispatch_consumed(&self) -> usize {
|
||||
self.sdk_dispatch_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialized_decoded(&self) -> usize {
|
||||
self.sdk_initialized_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
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_ping_result(&self) -> usize {
|
||||
self.sdk_ping_result.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_discover_result(&self) -> usize {
|
||||
self.sdk_discover_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_jsonrpc_response(&self) -> usize {
|
||||
self.sdk_jsonrpc_response.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_jsonrpc_error(&self) -> usize {
|
||||
self.sdk_jsonrpc_error.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscriptions_listen(&self) -> usize {
|
||||
self.sdk_subscriptions_listen.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscriptions_acknowledged(&self) -> usize {
|
||||
self.sdk_subscriptions_acknowledged.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_signal_notification(&self) -> usize {
|
||||
self.sdk_signal_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_progress_notification(&self) -> usize {
|
||||
self.sdk_progress_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -98,6 +221,12 @@ impl CounterSet {
|
||||
pub(crate) fn sdk_completion_result(&self) -> usize {
|
||||
self.sdk_completion_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_completion_handler_completed(&self) -> usize {
|
||||
self.sdk_completion_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_completion_handler_consumed(&self) -> usize {
|
||||
self.sdk_completion_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_dispatch(&self) -> usize {
|
||||
self.sdk_prompts_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -237,6 +366,31 @@ pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
/// Mark inside the ServerHandler override after domain await and typed result/error construction.
|
||||
pub(crate) fn sdk_resources_read_handler_completed() {
|
||||
increment(|c| &c.sdk_resources_read_handler_completed);
|
||||
}
|
||||
/// Mark inside the ServerHandler override after domain await and typed result/error construction.
|
||||
pub(crate) fn sdk_resources_templates_handler_completed() {
|
||||
increment(|c| &c.sdk_resources_templates_handler_completed);
|
||||
}
|
||||
/// Mark in the caller only after matching and consuming the actual trait Result.
|
||||
pub(crate) fn sdk_resources_list_handler_consumed() {
|
||||
increment(|c| &c.sdk_resources_list_handler_consumed);
|
||||
}
|
||||
/// Mark in the caller only after matching and consuming the actual trait Result.
|
||||
pub(crate) fn sdk_resources_read_handler_consumed() {
|
||||
increment(|c| &c.sdk_resources_read_handler_consumed);
|
||||
}
|
||||
/// Mark in the caller only after matching and consuming the actual trait Result.
|
||||
pub(crate) fn sdk_resources_templates_handler_consumed() {
|
||||
increment(|c| &c.sdk_resources_templates_handler_consumed);
|
||||
}
|
||||
|
||||
/// Mark only after converting a Resources request through the real SDK typed path.
|
||||
pub(crate) fn sdk_resources_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_resources_dispatch);
|
||||
@@ -261,6 +415,29 @@ pub(crate) fn sdk_resource_templates_list_result_serialized() {
|
||||
#[path = "../rmcp_resources_runtime_tests.rs"]
|
||||
mod rmcp_resources_runtime_tests;
|
||||
|
||||
#[path = "../rmcp_resources_handler_runtime_tests.rs"]
|
||||
mod rmcp_resources_handler_runtime_tests;
|
||||
|
||||
#[path = "../rmcp_prompts_handler_runtime_tests.rs"]
|
||||
mod rmcp_prompts_handler_runtime_tests;
|
||||
|
||||
/// Mark inside the override after domain await and typed Result construction.
|
||||
pub(crate) fn sdk_prompts_list_handler_completed() {
|
||||
increment(|c| &c.sdk_prompts_list_handler_completed);
|
||||
}
|
||||
/// Mark inside the override after domain await and typed Result construction.
|
||||
pub(crate) fn sdk_prompts_get_handler_completed() {
|
||||
increment(|c| &c.sdk_prompts_get_handler_completed);
|
||||
}
|
||||
/// Mark after matching/restoring the actual trait Result in the caller.
|
||||
pub(crate) fn sdk_prompts_list_handler_consumed() {
|
||||
increment(|c| &c.sdk_prompts_list_handler_consumed);
|
||||
}
|
||||
/// Mark after matching/restoring the actual trait Result in the caller.
|
||||
pub(crate) fn sdk_prompts_get_handler_consumed() {
|
||||
increment(|c| &c.sdk_prompts_get_handler_consumed);
|
||||
}
|
||||
|
||||
/// Mark only after converting a Prompts request through the real SDK typed path.
|
||||
pub(crate) fn sdk_prompts_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_prompts_dispatch);
|
||||
@@ -290,10 +467,24 @@ pub(crate) fn sdk_completion_result_serialized() {
|
||||
increment(|counters| &counters.sdk_completion_result);
|
||||
}
|
||||
|
||||
/// Mark inside the ServerHandler override after domain await and typed Result construction.
|
||||
pub(crate) fn sdk_completion_handler_completed() {
|
||||
increment(|counters| &counters.sdk_completion_handler_completed);
|
||||
}
|
||||
|
||||
/// Mark in the caller only after matching and consuming the actual trait Result.
|
||||
pub(crate) fn sdk_completion_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_completion_handler_consumed);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_runtime_tests.rs"]
|
||||
mod rmcp_completion_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_handler_runtime_tests.rs"]
|
||||
mod rmcp_completion_handler_runtime_tests;
|
||||
|
||||
/// Mark only after constructing the real SDK typed legacy logging request.
|
||||
pub(crate) fn sdk_logging_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_logging_dispatch);
|
||||
@@ -325,6 +516,122 @@ pub(crate) fn sdk_cancelled_params_decoded() {
|
||||
#[path = "../rmcp_progress_cancel_runtime_tests.rs"]
|
||||
mod rmcp_progress_cancel_runtime_tests;
|
||||
|
||||
pub(crate) fn installed_observer() -> Option<Arc<CounterSet>> {
|
||||
OBSERVER.try_with(Arc::clone).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_subscriptions_listen_decoded() {
|
||||
increment(|counters| &counters.sdk_subscriptions_listen);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_subscriptions_acknowledged_serialized() {
|
||||
increment(|counters| &counters.sdk_subscriptions_acknowledged);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_signal_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_signal_notification);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_signals_runtime_tests.rs"]
|
||||
mod rmcp_signals_runtime_tests;
|
||||
|
||||
/// Mark only immediately after successfully serializing a real SDK JsonRpcResponse.
|
||||
pub(crate) fn sdk_jsonrpc_response_serialized() {
|
||||
increment(|counters| &counters.sdk_jsonrpc_response);
|
||||
}
|
||||
|
||||
/// Mark only immediately after successfully serializing a real SDK JsonRpcError.
|
||||
pub(crate) fn sdk_jsonrpc_error_serialized() {
|
||||
increment(|counters| &counters.sdk_jsonrpc_error);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real rmcp DiscoverResult.
|
||||
pub(crate) fn sdk_discover_result_serialized() {
|
||||
increment(|counters| &counters.sdk_discover_result);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
|
||||
mod rmcp_lifecycle_negotiation_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);
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
/// Mark immediately after typed method-projection decode, not variant consumption.
|
||||
pub(crate) fn sdk_initialized_notification_decoded(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_decoded);
|
||||
}
|
||||
|
||||
/// Mark inside the matched SDK variant, after guards and immediately before session mutation.
|
||||
pub(crate) fn sdk_initialized_notification_consumed(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialized_runtime_tests.rs"]
|
||||
mod rmcp_initialized_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);
|
||||
}
|
||||
|
||||
/// Mark only when decoded method/kind selects the existing registry-backed route.
|
||||
pub(crate) fn sdk_dispatch_envelope_consumed() {
|
||||
increment(|counters| &counters.sdk_dispatch_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_dispatch_runtime_tests.rs"]
|
||||
mod rmcp_dispatch_runtime_tests;
|
||||
|
||||
/// Mark only after a real SDK success-response from_value succeeds.
|
||||
pub(crate) fn sdk_inbound_response_decoded() {
|
||||
increment(|c| &c.sdk_inbound_response_decoded);
|
||||
}
|
||||
/// Mark only after a real SDK error-response from_value succeeds.
|
||||
pub(crate) fn sdk_inbound_error_decoded() {
|
||||
increment(|c| &c.sdk_inbound_error_decoded);
|
||||
}
|
||||
/// Mark inside the matched typed SDK success variant that selects ACK.
|
||||
pub(crate) fn sdk_inbound_response_consumed() {
|
||||
increment(|c| &c.sdk_inbound_response_consumed);
|
||||
}
|
||||
/// Mark inside the matched typed SDK error variant that selects ACK.
|
||||
pub(crate) fn sdk_inbound_error_consumed() {
|
||||
increment(|c| &c.sdk_inbound_error_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_response_runtime_tests.rs"]
|
||||
mod rmcp_response_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -278,6 +278,17 @@ async fn mcp_post_response(
|
||||
Err(_status) => return ambiguous_session_carrier_response(headers, message),
|
||||
};
|
||||
|
||||
// Responses ACK before era/session resolution, but must not bypass fresh credentials.
|
||||
// Method-bearing messages retain their existing scoped authorization path below.
|
||||
if message
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("method"))
|
||||
&& let Err(error) =
|
||||
require_traced_machine_access(&state, path, headers, PlatformApiKeyScope::Read).await
|
||||
{
|
||||
return error.into_response();
|
||||
}
|
||||
|
||||
// Single JSON-RPC envelope guard: only a well-formed message reaches era resolution, dispatch,
|
||||
// approval or any outbound request. Syntactically valid JSON is not the same as a valid envelope.
|
||||
let envelope = match crate::protocol::validate_jsonrpc_envelope(message) {
|
||||
|
||||
@@ -30,10 +30,7 @@ use super::rmcp_dispatch::{
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||
method_name, params, request_id,
|
||||
},
|
||||
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,
|
||||
@@ -65,10 +62,20 @@ pub(super) async fn handle_legacy_request(
|
||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||
let dispatch = crate::protocol::dispatch_decision(
|
||||
method_name(message).unwrap_or_default(),
|
||||
registration_revision,
|
||||
);
|
||||
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
|
||||
Ok(Some(envelope)) => envelope,
|
||||
_ => {
|
||||
return internal_jsonrpc_error(
|
||||
message,
|
||||
"admitted dispatch envelope could not be decoded",
|
||||
);
|
||||
}
|
||||
};
|
||||
let method = envelope.method();
|
||||
let dispatch =
|
||||
crate::protocol::dispatch_decision(method.unwrap_or_default(), registration_revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_dispatch_envelope_consumed();
|
||||
match dispatch {
|
||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||
@@ -78,17 +85,23 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||
} if envelope.is_request() => handle_initialize(state, path, message, response_mode).await,
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_initialized_notification(state, path, headers).await
|
||||
} if envelope.is_notification() => {
|
||||
handle_initialized_notification(
|
||||
state,
|
||||
path,
|
||||
headers,
|
||||
crate::protocol::initialized_notification(message),
|
||||
)
|
||||
.await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -98,7 +111,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({ "protocolVersion": session.protocol_version }),
|
||||
crate::protocol::ping_result(
|
||||
&json!({"method": "ping"}),
|
||||
&session.protocol_version,
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -108,7 +124,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -177,7 +193,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -235,13 +251,13 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Cancelled,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
} if envelope.is_notification() => {
|
||||
handle_cancelled_notification(&state, path, headers, message, credential).await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -310,7 +326,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceRead,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -391,7 +407,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -415,8 +431,14 @@ pub(super) async fn handle_legacy_request(
|
||||
};
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
&session.protocol_version,
|
||||
command,
|
||||
)
|
||||
@@ -463,7 +485,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -528,7 +550,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptGet,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -626,7 +648,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -705,7 +727,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -751,10 +773,10 @@ pub(super) async fn handle_legacy_request(
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||
_ if envelope.is_notification() => StatusCode::ACCEPTED.into_response(),
|
||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||
_ => match method_name(message) {
|
||||
_ => match method {
|
||||
Some(method) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct InitializeParams {
|
||||
#[serde(rename = "protocolVersion")]
|
||||
pub(super) protocol_version: String,
|
||||
#[serde(default)]
|
||||
pub(super) capabilities: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct ToolCallParams {
|
||||
pub(super) name: String,
|
||||
|
||||
@@ -134,35 +134,11 @@ pub(super) fn resources_list_result(
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourcesResult {
|
||||
resources: resources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
let (result, extras) =
|
||||
super::rmcp_resources_projection::list(&resources, next_cursor, version)?;
|
||||
let result = super::rmcp_resources_projection::serialize(result, extras, "resources")?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&resources,
|
||||
&mut result["resources"],
|
||||
&[
|
||||
"uri",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"size",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -170,20 +146,10 @@ pub(super) fn resource_read_result(
|
||||
contents: Value,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result =
|
||||
rmcp::model::ReadResourceResult::new(serde_json::from_value(contents.clone())?);
|
||||
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)?;
|
||||
let (result, extras) = super::rmcp_resources_projection::read(&contents, version)?;
|
||||
let result = super::rmcp_resources_projection::serialize(result, extras, "contents")?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_read_result_serialized();
|
||||
preserve_resource_fields(
|
||||
contents.as_array().expect("validated contents array"),
|
||||
&mut result["contents"],
|
||||
&["uri", "mimeType", "text", "blob", "_meta"],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -192,88 +158,21 @@ pub(super) fn resource_templates_list_result(
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourceTemplatesResult {
|
||||
resource_templates: templates
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
let (result, extras) =
|
||||
super::rmcp_resources_projection::templates(&templates, next_cursor, version)?;
|
||||
let result = super::rmcp_resources_projection::serialize(result, extras, "resourceTemplates")?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resource_templates_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&templates,
|
||||
&mut result["resourceTemplates"],
|
||||
&[
|
||||
"uriTemplate",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// Pinned SDK serde drops unknown fields and optional nulls, including Crank template parameters.
|
||||
// Treat annotations/icons as opaque too: their nested extensions are not represented by the SDK.
|
||||
fn preserve_resource_fields(raw: &[Value], serialized: &mut Value, sdk_fields: &[&str]) {
|
||||
for (raw, serialized) in raw
|
||||
.iter()
|
||||
.zip(serialized.as_array_mut().expect("SDK array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK object");
|
||||
for (key, value) in raw.as_object().expect("validated resource object") {
|
||||
if !sdk_fields.contains(&key.as_str()) || value.is_null() {
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SDK pagination with lossless Crank argument schemas/defaults and optional nulls.
|
||||
pub(super) fn prompts_list_result(
|
||||
prompts: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let result = rmcp::model::ListPromptsResult {
|
||||
prompts: prompts
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<Vec<rmcp::model::Prompt>, _>>()?,
|
||||
next_cursor,
|
||||
result_type: None,
|
||||
ttl_ms: None,
|
||||
cache_scope: None,
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
preserve_resource_fields(
|
||||
&prompts,
|
||||
&mut result["prompts"],
|
||||
&["name", "title", "description", "arguments", "_meta"],
|
||||
);
|
||||
for (raw, serialized) in prompts
|
||||
.iter()
|
||||
.zip(result["prompts"].as_array_mut().expect("SDK prompts"))
|
||||
{
|
||||
if let Some(arguments) = raw["arguments"].as_array() {
|
||||
preserve_resource_fields(
|
||||
arguments,
|
||||
&mut serialized["arguments"],
|
||||
&["name", "title", "description", "required"],
|
||||
);
|
||||
}
|
||||
}
|
||||
let (result, extras) = super::rmcp_prompts_projection::list(&prompts, next_cursor)?;
|
||||
let result = super::rmcp_prompts_projection::serialize(result, extras, "prompts")?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_list_result_serialized();
|
||||
Ok(result)
|
||||
@@ -284,40 +183,8 @@ pub(super) fn prompt_get_result(
|
||||
description: Option<String>,
|
||||
messages: Vec<Value>,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let sdk_messages = messages
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut message| {
|
||||
if message["role"] == "system" {
|
||||
message["role"] = json!("user");
|
||||
}
|
||||
serde_json::from_value::<rmcp::model::PromptMessage>(message)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut result = rmcp::model::GetPromptResult::new(sdk_messages);
|
||||
result.description = description;
|
||||
// Era-specific resultType/cache projection remains at the existing dispatch boundary.
|
||||
result.result_type = None;
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
preserve_resource_fields(&messages, &mut result["messages"], &["role", "content"]);
|
||||
for (raw, serialized) in messages
|
||||
.iter()
|
||||
.zip(result["messages"].as_array_mut().expect("SDK messages"))
|
||||
{
|
||||
if raw["role"] == "system" {
|
||||
serialized["role"] = raw["role"].clone();
|
||||
}
|
||||
// Content extensions/optional nulls are opaque to the pinned SDK.
|
||||
let content = serialized["content"].as_object_mut().expect("SDK content");
|
||||
for (key, value) in raw["content"].as_object().expect("validated content") {
|
||||
if !content.contains_key(key)
|
||||
|| value.is_null()
|
||||
|| matches!(key.as_str(), "annotations" | "resource")
|
||||
{
|
||||
content.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let (result, extras) = super::rmcp_prompts_projection::get(description, &messages)?;
|
||||
let result = super::rmcp_prompts_projection::serialize(result, extras, "messages")?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_get_result_serialized();
|
||||
Ok(result)
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Request-owned SDK completion handler; the domain future remains in its caller.
|
||||
use std::sync::Arc;
|
||||
|
||||
use crank_core::{CorrelationContext, ExecutionLocale};
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::AppState;
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
protocol::{self, CompletionCommand, CompletionOutcome, CompletionReference, ServiceContext},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Scope {
|
||||
workspace: String,
|
||||
agent: String,
|
||||
credential: VerifiedMachineCredential,
|
||||
correlation: CorrelationContext,
|
||||
continuation: protocol::ContinuationSupport,
|
||||
locale: ExecutionLocale,
|
||||
revision: String,
|
||||
context: Option<Map<String, Value>>,
|
||||
}
|
||||
impl Scope {
|
||||
fn service(&self) -> ServiceContext<'_> {
|
||||
ServiceContext {
|
||||
workspace_slug: &self.workspace,
|
||||
agent_slug: &self.agent,
|
||||
credential: &self.credential,
|
||||
correlation: &self.correlation,
|
||||
continuation: self.continuation,
|
||||
locale: self.locale,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct CompletionHandler {
|
||||
state: Arc<AppState>,
|
||||
#[cfg(test)]
|
||||
domain: Option<Arc<tests::Domain>>,
|
||||
}
|
||||
fn internal() -> ErrorData {
|
||||
ErrorData::internal_error("completion handler unavailable", None)
|
||||
}
|
||||
impl CompletionHandler {
|
||||
async fn domain(&self, scope: &Scope, command: CompletionCommand) -> CompletionOutcome {
|
||||
#[cfg(test)]
|
||||
if let Some(domain) = &self.domain {
|
||||
return domain.complete(command).await;
|
||||
}
|
||||
protocol::handle_completion_command(&self.state, scope.service(), &scope.revision, command)
|
||||
.await
|
||||
}
|
||||
fn scope(context: &RequestContext<RoleServer>) -> Result<Scope, ErrorData> {
|
||||
context
|
||||
.extensions
|
||||
.get::<Scope>()
|
||||
.cloned()
|
||||
.ok_or_else(internal)
|
||||
}
|
||||
async fn execute(
|
||||
&self,
|
||||
scope: &Scope,
|
||||
params: CompleteRequestParams,
|
||||
) -> Result<CompleteResult, ErrorData> {
|
||||
let reference = match params.r#ref {
|
||||
Reference::Prompt(prompt) => CompletionReference::Prompt { name: prompt.name },
|
||||
Reference::Resource(resource) => CompletionReference::Resource { uri: resource.uri },
|
||||
_ => {
|
||||
return Err(ErrorData::invalid_params(
|
||||
"invalid completion/complete parameters",
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
// SDK context only accepts strings; retain the original JSON for domain validation.
|
||||
let context = scope
|
||||
.context
|
||||
.clone()
|
||||
.map(|arguments| serde_json::from_value(serde_json::json!({"arguments": arguments})))
|
||||
.transpose()
|
||||
.map_err(|_| internal())?;
|
||||
let command = CompletionCommand {
|
||||
reference,
|
||||
argument: crate::protocol::CompletionArgument {
|
||||
name: params.argument.name,
|
||||
value: params.argument.value,
|
||||
},
|
||||
context,
|
||||
};
|
||||
match self.domain(scope, command).await {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => {
|
||||
let mut info = CompletionInfo::new(values).map_err(|_| internal())?;
|
||||
info.total = total.and_then(|v| u32::try_from(v).ok());
|
||||
info.has_more = Some(has_more);
|
||||
Ok(CompleteResult::new(info))
|
||||
}
|
||||
CompletionOutcome::InvalidParams(detail) => {
|
||||
Err(ErrorData::invalid_params(detail, None))
|
||||
}
|
||||
CompletionOutcome::NotAvailable => Err(ErrorData::invalid_params(
|
||||
"the completion reference is not available",
|
||||
None,
|
||||
)),
|
||||
CompletionOutcome::CatalogUnavailable => Err(internal()),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ServerHandler for CompletionHandler {
|
||||
async fn complete(
|
||||
&self,
|
||||
request: CompleteRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<CompleteResult, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let result = self.execute(&scope, request).await;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_handler_completed();
|
||||
result
|
||||
}
|
||||
}
|
||||
async fn request_context(
|
||||
handler: &CompletionHandler,
|
||||
scope: Scope,
|
||||
) -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping =
|
||||
serde_json::from_value(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"ping"}))
|
||||
.map_err(|_| internal())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let revision =
|
||||
serde_json::from_value(Value::String(scope.revision.clone())).map_err(|_| internal())?;
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-completion-context", "1"),
|
||||
)
|
||||
.with_protocol_version(revision);
|
||||
let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running.close().await.map_err(|_| internal())?;
|
||||
drop(receiver);
|
||||
let mut context = RequestContext::new(RequestId::Number(1), peer);
|
||||
context.extensions.insert(scope);
|
||||
Ok(context)
|
||||
}
|
||||
pub(super) async fn handle(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: CompletionCommand,
|
||||
) -> CompletionOutcome {
|
||||
let (reference, context_args) = match command.reference {
|
||||
CompletionReference::Prompt { name } => (
|
||||
Reference::for_prompt(name),
|
||||
command.context.and_then(|c| c.arguments),
|
||||
),
|
||||
CompletionReference::Resource { uri } => (
|
||||
Reference::for_resource(uri),
|
||||
command.context.and_then(|c| c.arguments),
|
||||
),
|
||||
};
|
||||
let scope = Scope {
|
||||
workspace: context.workspace_slug.to_owned(),
|
||||
agent: context.agent_slug.to_owned(),
|
||||
credential: context.credential.clone(),
|
||||
correlation: context.correlation.clone(),
|
||||
continuation: context.continuation,
|
||||
locale: context.locale,
|
||||
revision: revision.to_owned(),
|
||||
context: context_args,
|
||||
};
|
||||
let handler = CompletionHandler {
|
||||
state: state.clone(),
|
||||
#[cfg(test)]
|
||||
domain: None,
|
||||
};
|
||||
let sdk_context = match request_context(&handler, scope).await {
|
||||
Ok(context) => context,
|
||||
Err(_) => return CompletionOutcome::CatalogUnavailable,
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_dispatch_enter();
|
||||
let params = CompleteRequestParams::new(
|
||||
reference,
|
||||
ArgumentInfo::new(command.argument.name, command.argument.value),
|
||||
);
|
||||
let result = ServerHandler::complete(&handler, params, sdk_context).await;
|
||||
restore(result)
|
||||
}
|
||||
fn restore(result: Result<CompleteResult, ErrorData>) -> CompletionOutcome {
|
||||
let outcome = match result {
|
||||
Ok(result) => CompletionOutcome::Completed {
|
||||
values: result.completion.values,
|
||||
total: result.completion.total.map(|v| v as usize),
|
||||
has_more: result.completion.has_more.unwrap_or(false),
|
||||
},
|
||||
Err(error) if error.message == "the completion reference is not available" => {
|
||||
CompletionOutcome::NotAvailable
|
||||
}
|
||||
Err(error) if error.code == ErrorCode::INVALID_PARAMS => {
|
||||
CompletionOutcome::InvalidParams("invalid completion/complete parameters")
|
||||
}
|
||||
Err(_) => CompletionOutcome::CatalogUnavailable,
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, ReadResourceRequestParams};
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle};
|
||||
@@ -72,27 +72,7 @@ pub(super) async fn handle_prompts_command(
|
||||
revision: &str,
|
||||
command: crate::protocol::PromptsCommand,
|
||||
) -> crate::protocol::PromptsOutcome {
|
||||
use crate::protocol::{PromptGetCommand, PromptsCommand, PromptsListCommand};
|
||||
let command = match command {
|
||||
PromptsCommand::List(list) => {
|
||||
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
|
||||
PromptsCommand::List(PromptsListCommand {
|
||||
cursor: params.cursor,
|
||||
limit: list.limit,
|
||||
})
|
||||
}
|
||||
PromptsCommand::Get(get) => {
|
||||
let mut params = rmcp::model::GetPromptRequestParams::new(get.name);
|
||||
params.arguments = get.arguments;
|
||||
PromptsCommand::Get(PromptGetCommand {
|
||||
name: params.name,
|
||||
arguments: params.arguments,
|
||||
})
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_dispatch_enter();
|
||||
crate::protocol::handle_prompts_command(state, context, revision, command).await
|
||||
super::rmcp_prompts::handle(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_resources_command(
|
||||
@@ -101,31 +81,16 @@ pub(super) async fn handle_resources_command(
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesCommand,
|
||||
) -> crate::protocol::ResourcesOutcome {
|
||||
use crate::protocol::{ResourceReadCommand, ResourcesCommand};
|
||||
let command = match command {
|
||||
ResourcesCommand::List(list) => ResourcesCommand::List(sdk_resource_page(list)),
|
||||
ResourcesCommand::Read(read) => {
|
||||
let params = ReadResourceRequestParams::new(read.uri);
|
||||
ResourcesCommand::Read(ResourceReadCommand { uri: params.uri })
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::handle_resources_command(state, context, revision, command).await
|
||||
super::rmcp_resources::handle(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), crate::protocol::ResourceTemplatesListError> {
|
||||
let command = sdk_resource_page(command);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::list_resource_templates(state, workspace_slug, agent_slug, revision, command)
|
||||
.await
|
||||
super::rmcp_resources::templates(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_completion_command(
|
||||
@@ -134,48 +99,5 @@ pub(super) async fn handle_completion_command(
|
||||
revision: &str,
|
||||
command: crate::protocol::CompletionCommand,
|
||||
) -> crate::protocol::CompletionOutcome {
|
||||
use crate::protocol::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
};
|
||||
use rmcp::model::{ArgumentInfo, CompleteRequestParams, Reference};
|
||||
|
||||
let reference = match command.reference {
|
||||
CompletionReference::Prompt { name } => Reference::for_prompt(name),
|
||||
CompletionReference::Resource { uri } => Reference::for_resource(uri),
|
||||
};
|
||||
let params = CompleteRequestParams::new(
|
||||
reference,
|
||||
ArgumentInfo::new(command.argument.name, command.argument.value),
|
||||
);
|
||||
// SDK context only supports strings; retain arbitrary JSON unchanged for domain validation.
|
||||
let context_arguments = command.context;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_dispatch_enter();
|
||||
let reference = match params.r#ref {
|
||||
Reference::Prompt(reference) => CompletionReference::Prompt {
|
||||
name: reference.name,
|
||||
},
|
||||
Reference::Resource(reference) => CompletionReference::Resource { uri: reference.uri },
|
||||
_ => return CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
|
||||
};
|
||||
let command = CompletionCommand {
|
||||
reference,
|
||||
argument: CompletionArgument {
|
||||
name: params.argument.name,
|
||||
value: params.argument.value,
|
||||
},
|
||||
context: context_arguments,
|
||||
};
|
||||
crate::protocol::handle_completion_command(state, context, revision, command).await
|
||||
}
|
||||
|
||||
fn sdk_resource_page(
|
||||
list: crate::protocol::ResourcesListCommand,
|
||||
) -> crate::protocol::ResourcesListCommand {
|
||||
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
|
||||
// Crank's page limit is not an SDK field; retain its existing validation and clamping.
|
||||
crate::protocol::ResourcesListCommand {
|
||||
cursor: params.cursor,
|
||||
limit: list.limit,
|
||||
}
|
||||
super::rmcp_completion::handle(state, context, revision, command).await
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Request-owned Prompts trait adapter; domain execution stays in the parent HTTP future.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crank_core::{CorrelationContext, ExecutionLocale};
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, rmcp_prompts_projection as projection};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
protocol::{
|
||||
self, ContinuationSupport, PromptGetCommand, PromptsCommand, PromptsListCommand,
|
||||
PromptsOutcome, ServiceContext,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PromptScope {
|
||||
workspace_slug: String,
|
||||
agent_slug: String,
|
||||
credential: VerifiedMachineCredential,
|
||||
correlation: CorrelationContext,
|
||||
continuation: ContinuationSupport,
|
||||
locale: ExecutionLocale,
|
||||
revision: String,
|
||||
limit: Option<usize>,
|
||||
}
|
||||
impl PromptScope {
|
||||
fn new(context: ServiceContext<'_>, revision: &str, limit: Option<usize>) -> Self {
|
||||
Self {
|
||||
workspace_slug: context.workspace_slug.to_owned(),
|
||||
agent_slug: context.agent_slug.to_owned(),
|
||||
credential: context.credential.clone(),
|
||||
correlation: context.correlation.clone(),
|
||||
continuation: context.continuation,
|
||||
locale: context.locale,
|
||||
revision: revision.to_owned(),
|
||||
limit,
|
||||
}
|
||||
}
|
||||
fn context(&self) -> ServiceContext<'_> {
|
||||
ServiceContext {
|
||||
workspace_slug: &self.workspace_slug,
|
||||
agent_slug: &self.agent_slug,
|
||||
credential: &self.credential,
|
||||
correlation: &self.correlation,
|
||||
continuation: self.continuation,
|
||||
locale: self.locale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ReplyExtras {
|
||||
List(projection::Projection),
|
||||
Get(projection::Projection),
|
||||
DomainError(PromptsOutcome),
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct PromptHandler {
|
||||
state: Arc<AppState>,
|
||||
reply: Arc<Mutex<Option<ReplyExtras>>>,
|
||||
#[cfg(test)]
|
||||
domain: Option<Arc<tests::Domain>>,
|
||||
}
|
||||
fn internal() -> ErrorData {
|
||||
ErrorData::internal_error("prompt handler unavailable", None)
|
||||
}
|
||||
|
||||
impl PromptHandler {
|
||||
fn new(state: &Arc<AppState>) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
reply: Arc::new(Mutex::new(None)),
|
||||
#[cfg(test)]
|
||||
domain: None,
|
||||
}
|
||||
}
|
||||
async fn execute(&self, scope: &PromptScope, command: PromptsCommand) -> PromptsOutcome {
|
||||
#[cfg(test)]
|
||||
if let Some(domain) = &self.domain {
|
||||
return domain.prompts(command).await;
|
||||
}
|
||||
protocol::handle_prompts_command(&self.state, scope.context(), &scope.revision, command)
|
||||
.await
|
||||
}
|
||||
fn save(&self, extras: ReplyExtras) -> Result<(), ErrorData> {
|
||||
let mut slot = self.reply.lock().map_err(|_| internal())?;
|
||||
if slot.is_some() {
|
||||
return Err(internal());
|
||||
}
|
||||
*slot = Some(extras);
|
||||
Ok(())
|
||||
}
|
||||
fn take(&self) -> Option<ReplyExtras> {
|
||||
self.reply.lock().ok()?.take()
|
||||
}
|
||||
fn scope(context: &RequestContext<RoleServer>) -> Result<PromptScope, ErrorData> {
|
||||
context
|
||||
.extensions
|
||||
.get::<PromptScope>()
|
||||
.cloned()
|
||||
.ok_or_else(internal)
|
||||
}
|
||||
fn domain_error(&self, outcome: PromptsOutcome) -> ErrorData {
|
||||
let error = match &outcome {
|
||||
PromptsOutcome::Listed { .. } | PromptsOutcome::Got { .. } => return internal(),
|
||||
PromptsOutcome::InvalidParams(detail) => {
|
||||
ErrorData::invalid_params(detail.clone(), None)
|
||||
}
|
||||
PromptsOutcome::NotAvailable => {
|
||||
ErrorData::invalid_params("the requested prompt is not available", None)
|
||||
}
|
||||
PromptsOutcome::ArgumentsRejected { .. } => {
|
||||
ErrorData::invalid_params("the prompt arguments were rejected", None)
|
||||
}
|
||||
_ => internal(),
|
||||
};
|
||||
if self.save(ReplyExtras::DomainError(outcome)).is_err() {
|
||||
return internal();
|
||||
}
|
||||
error
|
||||
}
|
||||
fn project_list(&self, outcome: PromptsOutcome) -> Result<ListPromptsResult, ErrorData> {
|
||||
match outcome {
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} => {
|
||||
let (result, extras) =
|
||||
projection::list(&prompts, next_cursor).map_err(|_| internal())?;
|
||||
self.save(ReplyExtras::List(extras))?;
|
||||
Ok(result)
|
||||
}
|
||||
other => Err(self.domain_error(other)),
|
||||
}
|
||||
}
|
||||
fn project_get(&self, outcome: PromptsOutcome) -> Result<GetPromptResult, ErrorData> {
|
||||
match outcome {
|
||||
PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} => {
|
||||
let (result, extras) =
|
||||
projection::get(description, &messages).map_err(|_| internal())?;
|
||||
self.save(ReplyExtras::Get(extras))?;
|
||||
Ok(result)
|
||||
}
|
||||
other => Err(self.domain_error(other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ServerHandler for PromptHandler {
|
||||
async fn list_prompts(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<ListPromptsResult, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let command = PromptsCommand::List(PromptsListCommand {
|
||||
cursor: request.unwrap_or_default().cursor,
|
||||
limit: scope.limit,
|
||||
});
|
||||
let outcome = self.execute(&scope, command).await;
|
||||
let result = self.project_list(outcome);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_list_handler_completed();
|
||||
result
|
||||
}
|
||||
async fn get_prompt(
|
||||
&self,
|
||||
request: GetPromptRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<GetPromptResponse, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let command = PromptsCommand::Get(PromptGetCommand {
|
||||
name: request.name,
|
||||
arguments: request.arguments,
|
||||
});
|
||||
let outcome = self.execute(&scope, command).await;
|
||||
let result = self.project_get(outcome).map(Into::into);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_get_handler_completed();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Public SDK context seed only; close the inert service before any domain execution.
|
||||
/// shortcut: the closed Peer cannot send callbacks, revisit if Prompts need peer messaging.
|
||||
async fn request_context(
|
||||
handler: &PromptHandler,
|
||||
scope: PromptScope,
|
||||
) -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping =
|
||||
serde_json::from_value(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"ping"}))
|
||||
.map_err(|_| internal())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let revision =
|
||||
serde_json::from_value(Value::String(scope.revision.clone())).map_err(|_| internal())?;
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-prompt-context", "1"),
|
||||
)
|
||||
.with_protocol_version(revision);
|
||||
let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running.close().await.map_err(|_| internal())?;
|
||||
drop(receiver);
|
||||
let mut context = RequestContext::new(RequestId::Number(1), peer);
|
||||
context.extensions.insert(scope);
|
||||
Ok(context)
|
||||
}
|
||||
fn restore_list(
|
||||
handler: &PromptHandler,
|
||||
result: Result<ListPromptsResult, ErrorData>,
|
||||
) -> PromptsOutcome {
|
||||
match (result, handler.take()) {
|
||||
(Ok(result), Some(ReplyExtras::List(extras))) => {
|
||||
let cursor = result.next_cursor.clone();
|
||||
match projection::serialize(result, extras, "prompts") {
|
||||
Ok(mut result) => match result["prompts"].take() {
|
||||
Value::Array(prompts) => PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor: cursor,
|
||||
},
|
||||
_ => PromptsOutcome::CatalogUnavailable,
|
||||
},
|
||||
Err(_) => PromptsOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
||||
_ => PromptsOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
fn restore_get(
|
||||
handler: &PromptHandler,
|
||||
result: Result<GetPromptResponse, ErrorData>,
|
||||
) -> PromptsOutcome {
|
||||
match (result, handler.take()) {
|
||||
(Ok(GetPromptResponse::Complete(result)), Some(ReplyExtras::Get(extras))) => {
|
||||
let description = result.description.clone();
|
||||
match projection::serialize(result, extras, "messages") {
|
||||
Ok(mut result) => match result["messages"].take() {
|
||||
Value::Array(messages) => PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
},
|
||||
_ => PromptsOutcome::CatalogUnavailable,
|
||||
},
|
||||
Err(_) => PromptsOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
||||
_ => PromptsOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: PromptsCommand,
|
||||
) -> PromptsOutcome {
|
||||
let limit = match &command {
|
||||
PromptsCommand::List(list) => list.limit,
|
||||
_ => None,
|
||||
};
|
||||
let handler = PromptHandler::new(state);
|
||||
let context = match request_context(&handler, PromptScope::new(context, revision, limit)).await
|
||||
{
|
||||
Ok(context) => context,
|
||||
Err(_) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_dispatch_enter();
|
||||
match command {
|
||||
PromptsCommand::List(list) => {
|
||||
let result = ServerHandler::list_prompts(
|
||||
&handler,
|
||||
Some(PaginatedRequestParams::default().with_cursor(list.cursor)),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = restore_list(&handler, result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_list_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
PromptsCommand::Get(get) => {
|
||||
let mut request = GetPromptRequestParams::new(get.name);
|
||||
request.arguments = get.arguments;
|
||||
let result = ServerHandler::get_prompt(&handler, request, context).await;
|
||||
let outcome = restore_get(&handler, result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_get_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_prompts_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Prompt-only lossless projection: SDK fields remain sourced from the actual trait result.
|
||||
use rmcp::model::{GetPromptResult, ListPromptsResult};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn invalid() -> serde_json::Error {
|
||||
<serde_json::Error as serde::de::Error>::custom("invalid prompt projection")
|
||||
}
|
||||
|
||||
// Store only differences from SDK serialization, not an alternate successful response.
|
||||
pub(super) enum Projection {
|
||||
Same,
|
||||
Opaque(Value),
|
||||
Object {
|
||||
extras: Map<String, Value>,
|
||||
absent: Vec<String>,
|
||||
children: Vec<(String, Projection)>,
|
||||
identity: Map<String, Value>,
|
||||
},
|
||||
Array(Vec<Projection>),
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
fn between(raw: &Value, sdk: &Value) -> Self {
|
||||
match (raw, sdk) {
|
||||
(Value::Object(raw), Value::Object(sdk)) => {
|
||||
let extras = raw
|
||||
.iter()
|
||||
.filter(|(k, _)| !sdk.contains_key(*k))
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
let absent = sdk
|
||||
.keys()
|
||||
.filter(|k| !raw.contains_key(*k))
|
||||
.cloned()
|
||||
.collect();
|
||||
let children = raw
|
||||
.iter()
|
||||
.filter_map(|(k, v)| sdk.get(k).map(|s| (k.clone(), Self::between(v, s))))
|
||||
.collect();
|
||||
let identity = sdk
|
||||
.iter()
|
||||
.filter(|(k, _)| matches!(k.as_str(), "name" | "role" | "type" | "uri"))
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
Self::Object {
|
||||
extras,
|
||||
absent,
|
||||
children,
|
||||
identity,
|
||||
}
|
||||
}
|
||||
(Value::Array(raw), Value::Array(sdk)) => Self::Array(
|
||||
raw.iter()
|
||||
.zip(sdk)
|
||||
.map(|(r, s)| Self::between(r, s))
|
||||
.collect(),
|
||||
),
|
||||
_ if raw == sdk => Self::Same,
|
||||
_ => Self::Opaque(raw.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn restore(self, sdk: &mut Value) -> Result<(), serde_json::Error> {
|
||||
match self {
|
||||
Self::Same => {}
|
||||
Self::Opaque(value) => *sdk = value,
|
||||
Self::Object {
|
||||
extras,
|
||||
absent,
|
||||
children,
|
||||
identity,
|
||||
} => {
|
||||
let object = sdk.as_object_mut().ok_or_else(invalid)?;
|
||||
if identity.iter().any(|(k, v)| object.get(k) != Some(v)) {
|
||||
return Err(invalid());
|
||||
}
|
||||
for (key, projection) in children {
|
||||
projection.restore(object.get_mut(&key).ok_or_else(invalid)?)?;
|
||||
}
|
||||
for key in absent {
|
||||
object.remove(&key);
|
||||
}
|
||||
object.extend(extras);
|
||||
}
|
||||
Self::Array(children) => {
|
||||
let array = sdk.as_array_mut().ok_or_else(invalid)?;
|
||||
if array.len() != children.len() {
|
||||
return Err(invalid());
|
||||
}
|
||||
for (projection, item) in children.into_iter().zip(array) {
|
||||
projection.restore(item)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn visible(raw: &Value, fields: &[&str]) -> Result<Value, serde_json::Error> {
|
||||
let raw = raw.as_object().ok_or_else(invalid)?;
|
||||
Ok(Value::Object(
|
||||
raw.iter()
|
||||
.filter(|(key, _)| fields.contains(&key.as_str()))
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn list(
|
||||
prompts: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<(ListPromptsResult, Projection), serde_json::Error> {
|
||||
let mut typed = Vec::with_capacity(prompts.len());
|
||||
for prompt in prompts {
|
||||
let mut prompt = visible(
|
||||
prompt,
|
||||
&["name", "title", "description", "arguments", "_meta"],
|
||||
)?;
|
||||
if let Some(Value::Array(arguments)) = prompt.get_mut("arguments") {
|
||||
for argument in arguments {
|
||||
*argument = visible(argument, &["name", "title", "description", "required"])?;
|
||||
}
|
||||
}
|
||||
typed.push(serde_json::from_value(prompt)?);
|
||||
}
|
||||
let result = ListPromptsResult {
|
||||
prompts: typed,
|
||||
next_cursor,
|
||||
result_type: None,
|
||||
ttl_ms: None,
|
||||
cache_scope: None,
|
||||
meta: None,
|
||||
};
|
||||
let extras = Projection::between(
|
||||
&Value::Array(prompts.to_vec()),
|
||||
&serde_json::to_value(&result)?["prompts"],
|
||||
);
|
||||
Ok((result, extras))
|
||||
}
|
||||
|
||||
pub(super) fn get(
|
||||
description: Option<String>,
|
||||
messages: &[Value],
|
||||
) -> Result<(GetPromptResult, Projection), serde_json::Error> {
|
||||
let mut typed = Vec::with_capacity(messages.len());
|
||||
for message in messages {
|
||||
let mut message = visible(message, &["role", "content"])?;
|
||||
if message["role"] == "system" {
|
||||
message["role"] = Value::String("user".into());
|
||||
}
|
||||
let content = message.get_mut("content").ok_or_else(invalid)?;
|
||||
// Opaque annotations and newly known SDK extensions must not add validation to Crank.
|
||||
let fields: &[&str] = match content["type"].as_str() {
|
||||
Some("text") => &["type", "text", "_meta"],
|
||||
Some("image" | "audio") => &["type", "data", "mimeType", "_meta"],
|
||||
Some("resource") => &["type", "resource", "_meta"],
|
||||
Some("resource_link") => &[
|
||||
"type",
|
||||
"uri",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"size",
|
||||
"_meta",
|
||||
],
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
*content = visible(content, fields)?;
|
||||
if let Some(resource) = content.get_mut("resource") {
|
||||
*resource = visible(resource, &["uri", "mimeType", "text", "blob", "_meta"])?;
|
||||
}
|
||||
typed.push(serde_json::from_value(message)?);
|
||||
}
|
||||
let mut result = GetPromptResult::new(typed);
|
||||
result.description = description;
|
||||
result.result_type = None;
|
||||
let extras = Projection::between(
|
||||
&Value::Array(messages.to_vec()),
|
||||
&serde_json::to_value(&result)?["messages"],
|
||||
);
|
||||
Ok((result, extras))
|
||||
}
|
||||
|
||||
pub(super) fn serialize(
|
||||
result: impl Serialize,
|
||||
extras: Projection,
|
||||
field: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
extras.restore(result.get_mut(field).ok_or_else(invalid)?)?;
|
||||
Ok(result)
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
//! Request-owned Resources trait adapter. Crank remains the only domain executor.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crank_core::{CorrelationContext, ExecutionLocale};
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, rmcp_resources_projection as projection};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
protocol::{
|
||||
self, ContinuationSupport, ResourceReadCommand, ResourceTemplatesListError,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ResourceScope {
|
||||
workspace_slug: String,
|
||||
agent_slug: String,
|
||||
credential: VerifiedMachineCredential,
|
||||
correlation: CorrelationContext,
|
||||
continuation: ContinuationSupport,
|
||||
locale: ExecutionLocale,
|
||||
revision: String,
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
impl ResourceScope {
|
||||
fn new(context: ServiceContext<'_>, revision: &str, limit: Option<usize>) -> Self {
|
||||
Self {
|
||||
workspace_slug: context.workspace_slug.to_owned(),
|
||||
agent_slug: context.agent_slug.to_owned(),
|
||||
credential: context.credential.clone(),
|
||||
correlation: context.correlation.clone(),
|
||||
continuation: context.continuation,
|
||||
locale: context.locale,
|
||||
revision: revision.to_owned(),
|
||||
limit,
|
||||
}
|
||||
}
|
||||
|
||||
fn context(&self) -> ServiceContext<'_> {
|
||||
ServiceContext {
|
||||
workspace_slug: &self.workspace_slug,
|
||||
agent_slug: &self.agent_slug,
|
||||
credential: &self.credential,
|
||||
correlation: &self.correlation,
|
||||
continuation: self.continuation,
|
||||
locale: self.locale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ReplyExtras {
|
||||
List(projection::Projection),
|
||||
Read(projection::Projection),
|
||||
Templates(projection::Projection),
|
||||
DomainError(ResourcesOutcome),
|
||||
TemplateError(ResourceTemplatesListError),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ResourceHandler {
|
||||
state: Arc<AppState>,
|
||||
reply: Arc<Mutex<Option<ReplyExtras>>>,
|
||||
#[cfg(test)]
|
||||
domain: Option<Arc<tests::Domain>>,
|
||||
}
|
||||
|
||||
fn internal() -> ErrorData {
|
||||
ErrorData::internal_error("resource handler unavailable", None)
|
||||
}
|
||||
|
||||
impl ResourceHandler {
|
||||
fn new(state: &Arc<AppState>) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
reply: Arc::new(Mutex::new(None)),
|
||||
#[cfg(test)]
|
||||
domain: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute(&self, scope: &ResourceScope, command: ResourcesCommand) -> ResourcesOutcome {
|
||||
#[cfg(test)]
|
||||
if let Some(domain) = &self.domain {
|
||||
return domain.resources(command).await;
|
||||
}
|
||||
protocol::handle_resources_command(&self.state, scope.context(), &scope.revision, command)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn execute_templates(
|
||||
&self,
|
||||
scope: &ResourceScope,
|
||||
command: ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
#[cfg(test)]
|
||||
if let Some(domain) = &self.domain {
|
||||
return domain.templates(command).await;
|
||||
}
|
||||
protocol::list_resource_templates(
|
||||
&self.state,
|
||||
&scope.workspace_slug,
|
||||
&scope.agent_slug,
|
||||
&scope.revision,
|
||||
command,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn save(&self, extras: ReplyExtras) -> Result<(), ErrorData> {
|
||||
let mut slot = self.reply.lock().map_err(|_| internal())?;
|
||||
if slot.is_some() {
|
||||
return Err(internal());
|
||||
}
|
||||
*slot = Some(extras);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take(&self) -> Option<ReplyExtras> {
|
||||
self.reply.lock().ok()?.take()
|
||||
}
|
||||
|
||||
fn scope(context: &RequestContext<RoleServer>) -> Result<ResourceScope, ErrorData> {
|
||||
context
|
||||
.extensions
|
||||
.get::<ResourceScope>()
|
||||
.cloned()
|
||||
.ok_or_else(internal)
|
||||
}
|
||||
|
||||
fn domain_error(&self, outcome: ResourcesOutcome) -> ErrorData {
|
||||
let error = match &outcome {
|
||||
ResourcesOutcome::Listed { .. } | ResourcesOutcome::Read { .. } => return internal(),
|
||||
ResourcesOutcome::InvalidParams(detail) => {
|
||||
ErrorData::invalid_params(detail.clone(), None)
|
||||
}
|
||||
ResourcesOutcome::NotAvailable => {
|
||||
ErrorData::invalid_params("the requested resource is not available", None)
|
||||
}
|
||||
_ => internal(),
|
||||
};
|
||||
if self.save(ReplyExtras::DomainError(outcome)).is_err() {
|
||||
return internal();
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
fn project_list(
|
||||
&self,
|
||||
outcome: ResourcesOutcome,
|
||||
revision: &str,
|
||||
) -> Result<ListResourcesResult, ErrorData> {
|
||||
match outcome {
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
} => {
|
||||
let (result, extras) =
|
||||
projection::list(&resources, next_cursor, revision).map_err(|_| internal())?;
|
||||
self.save(ReplyExtras::List(extras))?;
|
||||
Ok(result)
|
||||
}
|
||||
other => Err(self.domain_error(other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_read(
|
||||
&self,
|
||||
outcome: ResourcesOutcome,
|
||||
revision: &str,
|
||||
) -> Result<ReadResourceResponse, ErrorData> {
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => {
|
||||
let (result, extras) =
|
||||
projection::read(&contents, revision).map_err(|_| internal())?;
|
||||
self.save(ReplyExtras::Read(extras))?;
|
||||
Ok(result.into())
|
||||
}
|
||||
other => Err(self.domain_error(other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_templates(
|
||||
&self,
|
||||
outcome: Result<(Vec<Value>, Option<String>), ResourceTemplatesListError>,
|
||||
revision: &str,
|
||||
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
||||
match outcome {
|
||||
Ok((templates, next_cursor)) => {
|
||||
let (result, extras) = projection::templates(&templates, next_cursor, revision)
|
||||
.map_err(|_| internal())?;
|
||||
self.save(ReplyExtras::Templates(extras))?;
|
||||
Ok(result)
|
||||
}
|
||||
Err(error) => {
|
||||
let sdk_error = match error {
|
||||
ResourceTemplatesListError::InvalidCursor => {
|
||||
ErrorData::invalid_params("invalid resources/templates/list cursor", None)
|
||||
}
|
||||
ResourceTemplatesListError::Unavailable => internal(),
|
||||
};
|
||||
self.save(ReplyExtras::TemplateError(error))?;
|
||||
Err(sdk_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandler for ResourceHandler {
|
||||
async fn list_resources(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<ListResourcesResult, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let command = ResourcesCommand::List(ResourcesListCommand {
|
||||
cursor: request.unwrap_or_default().cursor,
|
||||
limit: scope.limit,
|
||||
});
|
||||
let outcome = self.execute(&scope, command).await;
|
||||
let result = self.project_list(outcome, &scope.revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_list_handler_completed();
|
||||
result
|
||||
}
|
||||
|
||||
async fn read_resource(
|
||||
&self,
|
||||
request: ReadResourceRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<ReadResourceResponse, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let command = ResourcesCommand::Read(ResourceReadCommand { uri: request.uri });
|
||||
let outcome = self.execute(&scope, command).await;
|
||||
let result = self.project_read(outcome, &scope.revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_read_handler_completed();
|
||||
result
|
||||
}
|
||||
|
||||
async fn list_resource_templates(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
||||
let scope = Self::scope(&context)?;
|
||||
let command = ResourcesListCommand {
|
||||
cursor: request.unwrap_or_default().cursor,
|
||||
limit: scope.limit,
|
||||
};
|
||||
let outcome = self.execute_templates(&scope, command).await;
|
||||
let result = self.project_templates(outcome, &scope.revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_templates_handler_completed();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Public SDK Peer construction only; the inert seed service closes before domain execution.
|
||||
/// shortcut: the closed Peer cannot send callbacks, revisit if Resources require peer messaging.
|
||||
async fn request_context(
|
||||
handler: &ResourceHandler,
|
||||
scope: ResourceScope,
|
||||
) -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping =
|
||||
serde_json::from_value(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"ping"}))
|
||||
.map_err(|_| internal())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let revision =
|
||||
serde_json::from_value(Value::String(scope.revision.clone())).map_err(|_| internal())?;
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-resource-context", "1"),
|
||||
)
|
||||
.with_protocol_version(revision);
|
||||
let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running.close().await.map_err(|_| internal())?;
|
||||
drop(receiver);
|
||||
let mut context = RequestContext::new(RequestId::Number(1), peer);
|
||||
context.extensions.insert(scope);
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
fn restore_list(
|
||||
handler: &ResourceHandler,
|
||||
result: Result<ListResourcesResult, ErrorData>,
|
||||
) -> ResourcesOutcome {
|
||||
match (result, handler.take()) {
|
||||
(Ok(result), Some(ReplyExtras::List(extras))) => {
|
||||
let cursor = result.next_cursor.clone();
|
||||
match projection::serialize(result, extras, "resources") {
|
||||
Ok(mut result) => match result["resources"].take() {
|
||||
Value::Array(resources) => ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor: cursor,
|
||||
},
|
||||
_ => ResourcesOutcome::CatalogUnavailable,
|
||||
},
|
||||
Err(_) => ResourcesOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
||||
_ => ResourcesOutcome::CatalogUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_read(
|
||||
handler: &ResourceHandler,
|
||||
result: Result<ReadResourceResponse, ErrorData>,
|
||||
) -> ResourcesOutcome {
|
||||
match (result, handler.take()) {
|
||||
(Ok(ReadResourceResponse::Complete(result)), Some(ReplyExtras::Read(extras))) => {
|
||||
match projection::serialize(result, extras, "contents") {
|
||||
Ok(mut result) => ResourcesOutcome::Read {
|
||||
contents: result["contents"].take(),
|
||||
},
|
||||
Err(_) => ResourcesOutcome::ArtifactUnavailable,
|
||||
}
|
||||
}
|
||||
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
||||
_ => ResourcesOutcome::ArtifactUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_templates(
|
||||
handler: &ResourceHandler,
|
||||
result: Result<ListResourceTemplatesResult, ErrorData>,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
match (result, handler.take()) {
|
||||
(Ok(result), Some(ReplyExtras::Templates(extras))) => {
|
||||
let cursor = result.next_cursor.clone();
|
||||
let mut result = projection::serialize(result, extras, "resourceTemplates")
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
match result["resourceTemplates"].take() {
|
||||
Value::Array(templates) => Ok((templates, cursor)),
|
||||
_ => Err(ResourceTemplatesListError::Unavailable),
|
||||
}
|
||||
}
|
||||
(Err(_), Some(ReplyExtras::TemplateError(error))) => Err(error),
|
||||
_ => Err(ResourceTemplatesListError::Unavailable),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: ResourcesCommand,
|
||||
) -> ResourcesOutcome {
|
||||
let limit = match &command {
|
||||
ResourcesCommand::List(list) => list.limit,
|
||||
_ => None,
|
||||
};
|
||||
let handler = ResourceHandler::new(state);
|
||||
let context =
|
||||
match request_context(&handler, ResourceScope::new(context, revision, limit)).await {
|
||||
Ok(context) => context,
|
||||
Err(_) => return ResourcesOutcome::CatalogUnavailable,
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
match command {
|
||||
ResourcesCommand::List(list) => {
|
||||
let result = ServerHandler::list_resources(
|
||||
&handler,
|
||||
Some(PaginatedRequestParams::default().with_cursor(list.cursor)),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = restore_list(&handler, result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_list_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
ResourcesCommand::Read(read) => {
|
||||
let result = ServerHandler::read_resource(
|
||||
&handler,
|
||||
ReadResourceRequestParams::new(read.uri),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = restore_read(&handler, result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_read_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn templates(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
let handler = ResourceHandler::new(state);
|
||||
let context = request_context(
|
||||
&handler,
|
||||
ResourceScope::new(context, revision, command.limit),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
let result = ServerHandler::list_resource_templates(
|
||||
&handler,
|
||||
Some(PaginatedRequestParams::default().with_cursor(command.cursor)),
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
let outcome = restore_templates(&handler, result);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_templates_handler_consumed();
|
||||
outcome
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_resources_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Lossless Resource-only projection shared by the handler and existing wire builders.
|
||||
use rmcp::model::{
|
||||
CacheScope, ListResourceTemplatesResult, ListResourcesResult, ReadResourceResult, ResultType,
|
||||
};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) const RESOURCE_FIELDS: &[&str] = &[
|
||||
"uri",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"size",
|
||||
"_meta",
|
||||
];
|
||||
pub(super) const TEMPLATE_FIELDS: &[&str] = &[
|
||||
"uriTemplate",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"_meta",
|
||||
];
|
||||
pub(super) const CONTENT_FIELDS: &[&str] = &["uri", "mimeType", "text", "blob", "_meta"];
|
||||
|
||||
/// Only unrepresentable fields plus order/identity witnesses, never a saved success response.
|
||||
pub(super) struct Projection {
|
||||
extras: Vec<Map<String, Value>>,
|
||||
identities: Vec<Map<String, Value>>,
|
||||
}
|
||||
|
||||
fn invalid() -> serde_json::Error {
|
||||
<serde_json::Error as serde::de::Error>::custom("invalid resource projection")
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
fn project<T: DeserializeOwned>(
|
||||
raw: &[Value],
|
||||
fields: &[&str],
|
||||
) -> Result<(Vec<T>, Self), serde_json::Error> {
|
||||
let mut extras = Vec::with_capacity(raw.len());
|
||||
let mut identities = Vec::with_capacity(raw.len());
|
||||
let mut typed = Vec::with_capacity(raw.len());
|
||||
for raw in raw {
|
||||
let mut visible = raw.as_object().ok_or_else(invalid)?.clone();
|
||||
let extra = visible
|
||||
.iter()
|
||||
.filter(|(key, value)| !fields.contains(&key.as_str()) || value.is_null())
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
let identity = visible
|
||||
.iter()
|
||||
.filter(|(key, _)| matches!(key.as_str(), "uri" | "uriTemplate" | "name"))
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
// Opaque descriptor JSON must not acquire SDK annotation/icon schema validation.
|
||||
visible.remove("annotations");
|
||||
visible.remove("icons");
|
||||
typed.push(serde_json::from_value(Value::Object(visible))?);
|
||||
extras.push(extra);
|
||||
identities.push(identity);
|
||||
}
|
||||
Ok((typed, Self { extras, identities }))
|
||||
}
|
||||
|
||||
pub(super) fn restore(self, serialized: &mut Value) -> Result<(), serde_json::Error> {
|
||||
let array = serialized.as_array_mut().ok_or_else(invalid)?;
|
||||
if array.len() != self.extras.len() {
|
||||
return Err(invalid());
|
||||
}
|
||||
for ((item, extras), identity) in array.iter_mut().zip(self.extras).zip(self.identities) {
|
||||
let item = item.as_object_mut().ok_or_else(invalid)?;
|
||||
if identity
|
||||
.iter()
|
||||
.any(|(key, value)| item.get(key) != Some(value))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
item.extend(extras);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn list(
|
||||
resources: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<(ListResourcesResult, Projection), serde_json::Error> {
|
||||
let (resources, extras) = Projection::project(resources, RESOURCE_FIELDS)?;
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
Ok((
|
||||
ListResourcesResult {
|
||||
resources,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
},
|
||||
extras,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn templates(
|
||||
templates: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<(ListResourceTemplatesResult, Projection), serde_json::Error> {
|
||||
let (resource_templates, extras) = Projection::project(templates, TEMPLATE_FIELDS)?;
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
Ok((
|
||||
ListResourceTemplatesResult {
|
||||
resource_templates,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
},
|
||||
extras,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn read(
|
||||
contents: &Value,
|
||||
version: &str,
|
||||
) -> Result<(ReadResourceResult, Projection), serde_json::Error> {
|
||||
let (contents, extras) =
|
||||
Projection::project(contents.as_array().ok_or_else(invalid)?, CONTENT_FIELDS)?;
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let mut result = ReadResourceResult::new(contents);
|
||||
result.result_type = modern.then_some(ResultType::COMPLETE);
|
||||
result.ttl_ms = modern.then_some(0);
|
||||
result.cache_scope = modern.then_some(CacheScope::Private);
|
||||
Ok((result, extras))
|
||||
}
|
||||
|
||||
pub(super) fn serialize(
|
||||
result: impl Serialize,
|
||||
extras: Projection,
|
||||
field: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
extras.restore(result.get_mut(field).ok_or_else(invalid)?)?;
|
||||
Ok(result)
|
||||
}
|
||||
@@ -122,6 +122,17 @@ pub(super) struct CountedSessionStore {
|
||||
counters: Arc<SessionCounters>,
|
||||
}
|
||||
|
||||
impl CountedSessionStore {
|
||||
pub(super) fn snapshot(&self) -> SessionOps {
|
||||
self.counters.snapshot()
|
||||
}
|
||||
|
||||
/// Inspect retained state without incrementing the HTTP request's session-read oracle.
|
||||
pub(super) async fn retained(&self, id: &str) -> Option<SessionState> {
|
||||
self.inner.get(id).await.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for CountedSessionStore {
|
||||
async fn create(
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use rmcp::model::{
|
||||
ErrorCode, ErrorData, JsonRpcError, JsonRpcResponse, JsonRpcVersion2_0, RequestId,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The two approved MCP revisions (`docs/`-approved window of 2026-10-11).
|
||||
@@ -60,28 +63,50 @@ pub fn is_response(message: &Value) -> bool {
|
||||
&& (message.get("result").is_some() || message.get("error").is_some())
|
||||
}
|
||||
|
||||
fn projected_sdk_id(id: &Value) -> RequestId {
|
||||
match id {
|
||||
Value::String(value) => RequestId::String(value.as_str().into()),
|
||||
Value::Number(value) => RequestId::Number(value.as_i64().unwrap_or(0)),
|
||||
_ => RequestId::Number(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn jsonrpc_result(id: Value, result: Value) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": result
|
||||
})
|
||||
let sdk = JsonRpcResponse::<Value> {
|
||||
jsonrpc: JsonRpcVersion2_0,
|
||||
id: projected_sdk_id(&id),
|
||||
result,
|
||||
};
|
||||
let mut wire = serde_json::to_value(sdk).expect("SDK response contains only JSON values");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_jsonrpc_response_serialized();
|
||||
// SDK RequestId cannot preserve the full Value domain or floating-point form.
|
||||
wire["id"] = id;
|
||||
wire
|
||||
}
|
||||
|
||||
pub fn jsonrpc_error(id: Value, code: i64, message: impl Into<String>) -> Value {
|
||||
let mut error = json!({
|
||||
"code": code,
|
||||
"message": message.into()
|
||||
});
|
||||
let (request_id, trace_id) = crank_observability::current_request_correlation();
|
||||
if request_id.is_some() && trace_id.is_some() {
|
||||
error["data"] = correlated_error_data(json!({}));
|
||||
}
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"error": error
|
||||
})
|
||||
let data = if request_id.is_some() && trace_id.is_some() {
|
||||
Some(correlated_error_data(json!({})))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let sdk = JsonRpcError::new(
|
||||
Some(projected_sdk_id(&id)),
|
||||
ErrorData::new(
|
||||
ErrorCode(i32::try_from(code).unwrap_or(0)),
|
||||
message.into(),
|
||||
data,
|
||||
),
|
||||
);
|
||||
let mut wire = serde_json::to_value(sdk).expect("SDK error contains only JSON values");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_jsonrpc_error_serialized();
|
||||
// Restore the helper's wider id/code contract before exposing the SDK envelope.
|
||||
wire["id"] = id;
|
||||
wire["error"]["code"] = Value::from(code);
|
||||
wire
|
||||
}
|
||||
|
||||
pub fn correlated_error_data(mut data: Value) -> Value {
|
||||
@@ -104,3 +129,86 @@ pub fn negotiated_protocol_version(requested: &str) -> Option<&'static str> {
|
||||
.copied()
|
||||
.find(|version| *version == requested)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn jsonrpc_preserves_helper_values_and_numeric_forms() {
|
||||
let values = [
|
||||
json!(""),
|
||||
json!("Юникод"),
|
||||
json!(i64::MIN),
|
||||
json!(i64::MAX),
|
||||
json!(9007199254740993_u64),
|
||||
json!(u64::MAX),
|
||||
json!(1.5),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
Value::Null,
|
||||
json!(true),
|
||||
json!([null, u64::MAX]),
|
||||
json!({"extension": {"nested": null}}),
|
||||
];
|
||||
for id in &values {
|
||||
for result in &values {
|
||||
let actual = jsonrpc_result(id.clone(), result.clone());
|
||||
let expected = json!({"jsonrpc": "2.0", "id": id, "result": result});
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual.to_string(), expected.to_string());
|
||||
}
|
||||
for code in [
|
||||
i64::MIN,
|
||||
i64::from(i32::MIN) - 1,
|
||||
i64::from(i32::MIN),
|
||||
-32602,
|
||||
0,
|
||||
i64::from(i32::MAX),
|
||||
i64::from(i32::MAX) + 1,
|
||||
i64::MAX,
|
||||
] {
|
||||
for message in ["", "Ошибка Ю"] {
|
||||
let actual = jsonrpc_error(id.clone(), code, message);
|
||||
let expected = json!({"jsonrpc": "2.0", "id": id,
|
||||
"error": {"code": code, "message": message}});
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual.to_string(), expected.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn jsonrpc_error_requires_complete_valid_correlation() {
|
||||
use crank_observability::{current_request_correlation, with_request_correlation};
|
||||
let request_id = "request-123";
|
||||
let trace_id = "1234567890abcdef1234567890abcdef";
|
||||
for (request, trace) in [("", ""), (request_id, ""), ("", trace_id)] {
|
||||
with_request_correlation(request.into(), trace.into(), async {
|
||||
assert_eq!(current_request_correlation(), (None, None));
|
||||
assert_eq!(
|
||||
jsonrpc_error(Value::Null, -32602, "error"),
|
||||
json!({"jsonrpc": "2.0", "id": null,
|
||||
"error": {"code": -32602, "message": "error"}})
|
||||
);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
with_request_correlation(request_id.into(), trace_id.into(), async {
|
||||
assert_eq!(
|
||||
jsonrpc_error(Value::Null, i64::MAX, "Ошибка"),
|
||||
json!({"jsonrpc": "2.0", "id": null, "error": {
|
||||
"code": i64::MAX, "message": "Ошибка",
|
||||
"data": {"request_id": request_id, "trace_id": trace_id}}})
|
||||
);
|
||||
assert_eq!(
|
||||
correlated_error_data(json!({"extension": [null, u64::MAX]})),
|
||||
json!({"extension": [null, u64::MAX],
|
||||
"request_id": request_id, "trace_id": trace_id})
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(current_request_correlation(), (None, None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Generic SDK envelopes for routing after the authoritative Crank admission guard.
|
||||
|
||||
use rmcp::model::{JsonRpcNotification, JsonRpcRequest};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum DispatchEnvelope {
|
||||
Request(JsonRpcRequest<Value>),
|
||||
Notification(JsonRpcNotification<Value>),
|
||||
}
|
||||
|
||||
impl DispatchEnvelope {
|
||||
pub(crate) fn method(&self) -> Option<&str> {
|
||||
let payload = match self {
|
||||
Self::Request(envelope) => &envelope.request,
|
||||
Self::Notification(envelope) => &envelope.notification,
|
||||
};
|
||||
payload.get("method").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn is_request(&self) -> bool {
|
||||
matches!(self, Self::Request(_))
|
||||
}
|
||||
|
||||
pub(crate) fn is_notification(&self) -> bool {
|
||||
matches!(self, Self::Notification(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// Call only after `validate_jsonrpc_envelope`; responses use the separate response SDK classifier.
|
||||
/// Params and extensions stay in the raw message, not in this routing-only projection.
|
||||
pub(crate) fn decode_dispatch_envelope(
|
||||
message: &Value,
|
||||
) -> Result<Option<DispatchEnvelope>, serde_json::Error> {
|
||||
let Some(method) = message.get("method") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut projection = json!({"jsonrpc": message.get("jsonrpc"), "method": method});
|
||||
let envelope = if let Some(id) = message.get("id") {
|
||||
// SDK ids are string/i64; the surrogate must never leave this routing-only envelope.
|
||||
projection["id"] = if id.is_number() && id.as_i64().is_none() {
|
||||
json!(0)
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
DispatchEnvelope::Request(serde_json::from_value(projection)?)
|
||||
} else {
|
||||
DispatchEnvelope::Notification(serde_json::from_value(projection)?)
|
||||
};
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_dispatch_envelope_decoded();
|
||||
Ok(Some(envelope))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn arbitrary_method_ignores_params_and_mixed_extra_fields() {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({
|
||||
"_meta": {"clientInfo": false}, "extension": [null, 3]
|
||||
})),
|
||||
] {
|
||||
let mut message = json!({
|
||||
"jsonrpc": "2.0", "id": "request", "method": "private/arbitrary",
|
||||
"result": false, "error": [1], "extension": {"anything": true}
|
||||
});
|
||||
if let Some(params) = params {
|
||||
message["params"] = params;
|
||||
}
|
||||
let original = message.clone();
|
||||
let envelope = decode_dispatch_envelope(&message)
|
||||
.expect("admitted request decodes")
|
||||
.expect("request envelope");
|
||||
assert_eq!(envelope.method(), Some("private/arbitrary"));
|
||||
assert!(envelope.is_request());
|
||||
assert!(!envelope.is_notification());
|
||||
let DispatchEnvelope::Request(request) = envelope else {
|
||||
panic!("request must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(request.request, json!({"method": "private/arbitrary"}));
|
||||
assert_eq!(message, original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_ids_preserve_raw_value_and_only_surrogate_sdk_incompatible_numbers() {
|
||||
for (id, sdk_id) in [
|
||||
(json!("string-id"), json!("string-id")),
|
||||
(json!(i64::MIN), json!(i64::MIN)),
|
||||
(json!(i64::MAX), json!(i64::MAX)),
|
||||
(json!(u64::MAX), json!(0)),
|
||||
(json!(1.25), json!(0)),
|
||||
(json!(1.0), json!(0)),
|
||||
] {
|
||||
let message = json!({"jsonrpc": "2.0", "id": id, "method": "arbitrary"});
|
||||
let original = message.clone();
|
||||
let DispatchEnvelope::Request(request) = decode_dispatch_envelope(&message)
|
||||
.expect("admitted id decodes")
|
||||
.expect("request envelope")
|
||||
else {
|
||||
panic!("id-bearing method must be a request");
|
||||
};
|
||||
assert_eq!(serde_json::to_value(request.id).expect("SDK id"), sdk_id);
|
||||
assert_eq!(message, original);
|
||||
assert_eq!(message.to_string(), original.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_kind_is_independent_of_method_and_ignored_fields() {
|
||||
let message = json!({
|
||||
"jsonrpc": "2.0", "method": "private/arbitrary", "params": {},
|
||||
"result": {}, "error": {}, "extension": 42
|
||||
});
|
||||
let original = message.clone();
|
||||
let envelope = decode_dispatch_envelope(&message)
|
||||
.expect("notification decodes")
|
||||
.expect("notification envelope");
|
||||
assert_eq!(envelope.method(), Some("private/arbitrary"));
|
||||
assert!(!envelope.is_request());
|
||||
assert!(envelope.is_notification());
|
||||
let DispatchEnvelope::Notification(notification) = envelope else {
|
||||
panic!("notification must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(
|
||||
notification.notification,
|
||||
json!({"method": "private/arbitrary"})
|
||||
);
|
||||
assert_eq!(message, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_success_and_error_responses_do_not_enter_method_dispatch() {
|
||||
for message in [
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": "id", "error": {"code": -1, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "error"}}),
|
||||
] {
|
||||
assert!(
|
||||
decode_dispatch_envelope(&message)
|
||||
.expect("response bypass")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! 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 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> {
|
||||
// Only protocolVersion was validated here; ignored client fields must not acquire SDK constraints.
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"protocolVersion": params.get("protocolVersion"),
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "", "version": ""}
|
||||
}))
|
||||
}
|
||||
|
||||
fn protocol_version(revision: &str) -> ProtocolVersion {
|
||||
serde_json::from_value(Value::String(revision.to_owned()))
|
||||
.expect("served protocol revisions are strings")
|
||||
}
|
||||
|
||||
fn capabilities(advertised: &Value) -> ServerCapabilities {
|
||||
serde_json::from_value(advertised.clone())
|
||||
.expect("registry capability fragments match SDK capability shapes")
|
||||
}
|
||||
|
||||
fn restore_registry_extensions(result: &mut Value, advertised: Value) {
|
||||
let capabilities = result["capabilities"]
|
||||
.as_object_mut()
|
||||
.expect("SDK server capabilities serialize as an object");
|
||||
// SDK ServerCapabilities has no flattened map for extra registry capability names.
|
||||
for (name, settings) in advertised
|
||||
.as_object()
|
||||
.expect("registry capabilities are an object")
|
||||
{
|
||||
capabilities
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| settings.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn initialized_notification(message: &Value) -> rmcp::model::ClientNotification {
|
||||
// Admission already checked the envelope; ignored params must not acquire SDK constraints.
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(serde_json::json!({"method": message["method"]}))
|
||||
.expect("registry dispatched a validated initialized notification");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_initialized_notification_decoded(¬ification);
|
||||
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::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn lifecycle_sdk_retains_extra_registry_capabilities_without_replacing_sdk_fields() {
|
||||
let advertised =
|
||||
json!({"tools":{"listChanged":false}, "inert_test_capability":{"enabled":true}});
|
||||
let mut result = serde_json::to_value(InitializeResult::new(capabilities(&advertised)))
|
||||
.expect("typed result serializes");
|
||||
assert_eq!(
|
||||
result["capabilities"],
|
||||
json!({"tools":{"listChanged":false}})
|
||||
);
|
||||
restore_registry_extensions(&mut result, advertised.clone());
|
||||
assert_eq!(result["capabilities"], advertised);
|
||||
}
|
||||
}
|
||||
@@ -26,12 +26,17 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod dispatch_sdk;
|
||||
mod lifecycle_sdk;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
mod response_sdk;
|
||||
mod signals;
|
||||
|
||||
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
|
||||
|
||||
pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
@@ -40,6 +45,9 @@ 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 logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||
@@ -84,50 +92,6 @@ fn is_valid_request_id(id: &Value) -> bool {
|
||||
id.is_string() || id.is_number()
|
||||
}
|
||||
|
||||
/// The pinned error object: `Error { code: number; message: string; data?: unknown }`.
|
||||
fn is_valid_error_object(error: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(error)) = error else {
|
||||
return false;
|
||||
};
|
||||
error.get("code").is_some_and(Value::is_number)
|
||||
&& error.get("message").is_some_and(Value::is_string)
|
||||
}
|
||||
|
||||
/// Classify a wire response (a message without `method`).
|
||||
///
|
||||
/// Pinned shapes are exclusive: a success response carries `result: Result` (an object) and a required
|
||||
/// `id: RequestId`, an error response carries `error: Error` and may omit the id (a present id must
|
||||
/// still be a `RequestId`). Both together, neither, a foreign id, a non-object `result` or a malformed
|
||||
/// error object are all invalid requests rather than an acknowledgement.
|
||||
///
|
||||
/// The `result` value is required to be an object because the pinned `JSONRPCResultResponse` types it as
|
||||
/// `Result`; the modern `resultType` member is deliberately **not** required here, because an incoming
|
||||
/// response may come from a client implementing an earlier revision.
|
||||
fn classify_wire_response(object: &serde_json::Map<String, Value>) -> Option<EnvelopeKind> {
|
||||
match (object.contains_key("result"), object.contains_key("error")) {
|
||||
(true, false) => {
|
||||
if !matches!(object.get("result"), Some(Value::Object(_))) {
|
||||
return None;
|
||||
}
|
||||
object
|
||||
.get("id")
|
||||
.filter(|id| is_valid_request_id(id))
|
||||
.map(|_| EnvelopeKind::Response)
|
||||
}
|
||||
(false, true) => {
|
||||
if !is_valid_error_object(object.get("error")) {
|
||||
return None;
|
||||
}
|
||||
match object.get("id") {
|
||||
None => Some(EnvelopeKind::Response),
|
||||
Some(id) if is_valid_request_id(id) => Some(EnvelopeKind::Response),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned modern wire projection of a success result.
|
||||
///
|
||||
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
|
||||
@@ -253,7 +217,7 @@ pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind,
|
||||
}
|
||||
}
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
None => match classify_wire_response(object) {
|
||||
None => match response_sdk::classify_response(message) {
|
||||
Some(kind) => Ok(kind),
|
||||
None => Err(rejected(invalid_request_response())),
|
||||
},
|
||||
@@ -844,20 +808,3 @@ pub(crate) fn resolve_request_identity(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned `DiscoverResult` for `server/discover` of the revision the caller serves.
|
||||
pub(crate) fn discover_result(revision: &str, server_name: &str, server_version: &str) -> Value {
|
||||
json!({
|
||||
"resultType": "complete",
|
||||
"supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
|
||||
"capabilities": advertised_server_capabilities(revision),
|
||||
"_meta": {
|
||||
crate::jsonrpc::META_SERVER_INFO_KEY: {
|
||||
"name": server_name,
|
||||
"version": server_version,
|
||||
}
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private"
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! SDK classification of inbound responses, without narrowing the admitted wire numbers.
|
||||
|
||||
use rmcp::model::{JsonRpcError, JsonRpcResponse};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::EnvelopeKind;
|
||||
|
||||
enum ResponseEnvelope {
|
||||
Success(JsonRpcResponse<Value>),
|
||||
Error(JsonRpcError),
|
||||
}
|
||||
|
||||
/// Only the no-method branch of the envelope guard calls this helper.
|
||||
pub(super) fn classify_response(message: &Value) -> Option<EnvelopeKind> {
|
||||
match decode_response(message)? {
|
||||
ResponseEnvelope::Success(JsonRpcResponse { result, .. }) => {
|
||||
// The generic SDK result must still satisfy the pinned object-only contract.
|
||||
if !result.is_object() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_response_consumed();
|
||||
Some(EnvelopeKind::Response)
|
||||
}
|
||||
ResponseEnvelope::Error(JsonRpcError { .. }) => {
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_error_consumed();
|
||||
Some(EnvelopeKind::Response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_response(message: &Value) -> Option<ResponseEnvelope> {
|
||||
let object = message.as_object()?;
|
||||
if object.get("jsonrpc")?.as_str()? != "2.0" || object.contains_key("method") {
|
||||
return None;
|
||||
}
|
||||
let id = object.get("id");
|
||||
if id.is_some_and(|id| !id.is_string() && !id.is_number()) {
|
||||
return None;
|
||||
}
|
||||
let mut projection = json!({"jsonrpc": "2.0"});
|
||||
if let Some(id) = id {
|
||||
// SDK ids are string/i64; this surrogate stays in the classification-only clone.
|
||||
projection["id"] = if id.is_number() && id.as_i64().is_none() {
|
||||
json!(0)
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
}
|
||||
match (object.get("result"), object.get("error")) {
|
||||
(Some(result), None) if result.is_object() && id.is_some() => {
|
||||
projection["result"] = result.clone();
|
||||
let response = serde_json::from_value::<JsonRpcResponse<Value>>(projection).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_response_decoded();
|
||||
Some(ResponseEnvelope::Success(response))
|
||||
}
|
||||
(None, Some(error)) if error.is_object() => {
|
||||
let code = error.get("code")?;
|
||||
if !code.is_number() || !error.get("message")?.is_string() {
|
||||
return None;
|
||||
}
|
||||
projection["error"] = error.clone();
|
||||
// SDK codes are i32; validate the original number before projecting only that field.
|
||||
if code
|
||||
.as_i64()
|
||||
.and_then(|code| i32::try_from(code).ok())
|
||||
.is_none()
|
||||
{
|
||||
projection["error"]["code"] = json!(0);
|
||||
}
|
||||
let error = serde_json::from_value::<JsonRpcError>(projection).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_error_decoded();
|
||||
Some(ResponseEnvelope::Error(error))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_response_shapes_without_constraining_params_or_extensions() {
|
||||
for message in [
|
||||
json!({"jsonrpc": "2.0", "id": "", "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {"resultType": false},
|
||||
"params": false, "extension": [null, 1]}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": ""}}),
|
||||
json!({"jsonrpc": "2.0", "id": "id", "error": {
|
||||
"code": -1, "message": "error", "data": [null, {"nested": true}]
|
||||
}, "params": [], "extension": false}),
|
||||
] {
|
||||
let original = message.to_string();
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
assert_eq!(message.to_string(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_shapes_before_sdk_projection() {
|
||||
for message in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({"id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "1.0", "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0"}),
|
||||
json!({"jsonrpc": "2.0", "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {}, "error": null}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": null}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": []}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": true}),
|
||||
json!({"jsonrpc": "2.0", "error": null}),
|
||||
json!({"jsonrpc": "2.0", "error": []}),
|
||||
json!({"jsonrpc": "2.0", "error": {"message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": "-1", "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": null, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": true, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": false}}),
|
||||
json!({"jsonrpc": "2.0", "method": null, "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "method": "request", "id": 1, "result": {}}),
|
||||
] {
|
||||
assert_eq!(classify_response(&message), None, "{message}");
|
||||
}
|
||||
for id in [Value::Null, json!(true), json!([]), json!({})] {
|
||||
for payload in [
|
||||
json!({"result": {}}),
|
||||
json!({"error": {"code": -1, "message": "e"}}),
|
||||
] {
|
||||
let mut message = payload;
|
||||
message["jsonrpc"] = json!("2.0");
|
||||
message["id"] = id.clone();
|
||||
assert_eq!(classify_response(&message), None, "{message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_projection_preserves_raw_json_and_executes_typed_variants() {
|
||||
let numbers = [
|
||||
json!(i64::MIN),
|
||||
json!(i64::MAX),
|
||||
json!(u64::MAX),
|
||||
json!(i32::MIN),
|
||||
json!(i32::MAX),
|
||||
json!(2147483648_i64),
|
||||
json!(-2147483649_i64),
|
||||
json!(1.25),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
json!(f64::MAX),
|
||||
];
|
||||
for number in numbers {
|
||||
let sdk_id = if number.as_i64().is_some() {
|
||||
number.clone()
|
||||
} else {
|
||||
json!(0)
|
||||
};
|
||||
let sdk_code = if number
|
||||
.as_i64()
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.is_some()
|
||||
{
|
||||
number.clone()
|
||||
} else {
|
||||
json!(0)
|
||||
};
|
||||
for error in [false, true] {
|
||||
let mut message = json!({"jsonrpc": "2.0", "id": number});
|
||||
if error {
|
||||
message["error"] = json!({"code": number, "message": "e", "data": number});
|
||||
} else {
|
||||
message["result"] = json!({"nested": [number, null]});
|
||||
}
|
||||
let original = message.to_string();
|
||||
match decode_response(&message).expect("numeric wire shape decodes") {
|
||||
ResponseEnvelope::Success(response) => {
|
||||
assert!(!error);
|
||||
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
|
||||
assert_eq!(response.result, message["result"]);
|
||||
}
|
||||
ResponseEnvelope::Error(response) => {
|
||||
assert!(error);
|
||||
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
|
||||
assert_eq!(serde_json::to_value(response.error.code).unwrap(), sdk_code);
|
||||
assert_eq!(response.error.data.as_ref(), Some(&number));
|
||||
}
|
||||
}
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
assert_eq!(message.to_string(), original);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_error_keeps_optional_id_and_arbitrary_data() {
|
||||
for data in [
|
||||
Value::Null,
|
||||
json!(true),
|
||||
json!(1.0),
|
||||
json!("text"),
|
||||
json!([]),
|
||||
json!({}),
|
||||
] {
|
||||
let message =
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "e", "data": data}});
|
||||
let ResponseEnvelope::Error(error) = decode_response(&message).unwrap() else {
|
||||
panic!("error must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(error.id, None);
|
||||
// SDK Option<Value> maps explicit null to None; classification never rewrites the wire.
|
||||
assert_eq!(
|
||||
error.error.data,
|
||||
if data.is_null() { None } else { Some(data) }
|
||||
);
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,12 @@ use std::{
|
||||
use axum::response::sse::Event;
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use futures_util::stream;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use rmcp::model::{SubscriptionFilter, SubscriptionsListenRequestParams};
|
||||
use serde::{Deserialize, Deserializer, de::Error};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[path = "signals_sdk.rs"]
|
||||
mod sdk;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::warn;
|
||||
|
||||
@@ -60,6 +64,7 @@ pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed
|
||||
/// `notifications/tools/list_changed` (both approved revisions, Story 3.5).
|
||||
pub(crate) const TOOL_LIST_CHANGED: &str = "notifications/tools/list_changed";
|
||||
/// `notifications/subscriptions/acknowledged` (modern revision only).
|
||||
#[cfg(test)]
|
||||
pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||
|
||||
/// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs
|
||||
@@ -113,32 +118,61 @@ impl Signals {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned modern `SubscriptionFilter`, as far as this server reads it.
|
||||
///
|
||||
/// Unknown members are ignored and a malformed shape is a deserialization error, so a client cannot
|
||||
/// reach the watcher with anything but the reviewed field set.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ListenFilter {
|
||||
#[serde(default)]
|
||||
tools_list_changed: bool,
|
||||
#[serde(default)]
|
||||
prompts_list_changed: bool,
|
||||
#[serde(default)]
|
||||
resources_list_changed: bool,
|
||||
#[serde(default)]
|
||||
resource_subscriptions: Vec<String>,
|
||||
/// Compatibility bounds around the real SDK filter, not a second protocol field model.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ListenFilter(SubscriptionFilter);
|
||||
|
||||
// SDK optional fields accept null; the existing public filter contract rejects explicit null.
|
||||
fn validate_filter(value: &Value) -> Result<(), &'static str> {
|
||||
let object = value.as_object().ok_or(INVALID_LISTEN_FILTER)?;
|
||||
for key in [
|
||||
"toolsListChanged",
|
||||
"promptsListChanged",
|
||||
"resourcesListChanged",
|
||||
"resourceSubscriptions",
|
||||
] {
|
||||
if object.get(key).is_some_and(Value::is_null) {
|
||||
return Err(INVALID_LISTEN_FILTER);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The pinned `SubscriptionsListenRequestParams`: the notification filter is a required member.
|
||||
///
|
||||
/// Only the reviewed member is read; `_meta` and any other member of the request params is not part
|
||||
/// of this contract.
|
||||
#[derive(Debug, Deserialize)]
|
||||
impl<'de> Deserialize<'de> for ListenFilter {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = Value::deserialize(deserializer)?;
|
||||
validate_filter(&value).map_err(D::Error::custom)?;
|
||||
serde_json::from_value(value)
|
||||
.map(Self)
|
||||
.map_err(D::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode only the reviewed notifications projection: HTTP admission already owns `_meta`.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ListenParams {
|
||||
pub(crate) notifications: ListenFilter,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ListenParams {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = Value::deserialize(deserializer)?;
|
||||
let notifications = value
|
||||
.as_object()
|
||||
.and_then(|object| object.get("notifications"))
|
||||
.ok_or_else(|| D::Error::custom(INVALID_LISTEN_FILTER))?;
|
||||
validate_filter(notifications).map_err(D::Error::custom)?;
|
||||
let params: SubscriptionsListenRequestParams =
|
||||
serde_json::from_value(json!({"notifications": notifications}))
|
||||
.map_err(D::Error::custom)?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_subscriptions_listen_decoded();
|
||||
Ok(Self {
|
||||
notifications: ListenFilter(params.notifications),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounded input contract of a `subscriptions/listen` filter.
|
||||
pub(crate) enum FilterOutcome {
|
||||
/// The list-change subset this server honours for the stream.
|
||||
@@ -154,37 +188,18 @@ impl ListenFilter {
|
||||
/// acknowledgment reports: it is simply not honoured, and the pinned schema forbids the server
|
||||
/// from sending a type it did not agree to.
|
||||
pub(crate) fn accepted(&self) -> FilterOutcome {
|
||||
if self.resource_subscriptions.len() > MAX_FILTER_URIS
|
||||
|| self
|
||||
.resource_subscriptions
|
||||
.iter()
|
||||
.any(|uri| uri.len() > MAX_FILTER_URI_BYTES)
|
||||
{
|
||||
let uris = self.0.resource_subscriptions.as_deref().unwrap_or_default();
|
||||
if uris.len() > MAX_FILTER_URIS || uris.iter().any(|uri| uri.len() > MAX_FILTER_URI_BYTES) {
|
||||
return FilterOutcome::Invalid(INVALID_LISTEN_FILTER);
|
||||
}
|
||||
FilterOutcome::Accepted(Signals {
|
||||
resources: self.resources_list_changed,
|
||||
prompts: self.prompts_list_changed,
|
||||
tools: self.tools_list_changed,
|
||||
resources: self.0.resources_list_changed == Some(true),
|
||||
prompts: self.0.prompts_list_changed == Some(true),
|
||||
tools: self.0.tools_list_changed == Some(true),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `notifications` object of the acknowledgment: exactly the subset that will be delivered.
|
||||
fn acknowledged_filter_wire(accepted: Signals) -> Value {
|
||||
let mut filter = Map::new();
|
||||
if accepted.prompts {
|
||||
filter.insert("promptsListChanged".to_owned(), Value::Bool(true));
|
||||
}
|
||||
if accepted.resources {
|
||||
filter.insert("resourcesListChanged".to_owned(), Value::Bool(true));
|
||||
}
|
||||
if accepted.tools {
|
||||
filter.insert("toolsListChanged".to_owned(), Value::Bool(true));
|
||||
}
|
||||
Value::Object(filter)
|
||||
}
|
||||
|
||||
/// The exact bound Resource/Prompt/Tool projection of one published Agent catalog.
|
||||
///
|
||||
/// The projection is derived from the same committed catalog read that already feeds
|
||||
@@ -268,15 +283,11 @@ impl Wire {
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
let frame = match self {
|
||||
Wire::Legacy => json!({ "jsonrpc": "2.0", "method": method }),
|
||||
Wire::Modern(subscription_id) => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": method,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: subscription_id } }
|
||||
}),
|
||||
let subscription_id = match self {
|
||||
Wire::Legacy => None,
|
||||
Wire::Modern(subscription_id) => Some(subscription_id),
|
||||
};
|
||||
frames.push(frame.to_string());
|
||||
frames.push(sdk::signal_frame(method, subscription_id));
|
||||
}
|
||||
frames
|
||||
}
|
||||
@@ -284,15 +295,7 @@ impl Wire {
|
||||
|
||||
/// The first modern frame: the accepted subset, before any list-change notification of the stream.
|
||||
pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": SUBSCRIPTIONS_ACKNOWLEDGED,
|
||||
"params": {
|
||||
"_meta": { SUBSCRIPTION_ID_KEY: subscription_id },
|
||||
"notifications": acknowledged_filter_wire(accepted),
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
sdk::acknowledged_frame(subscription_id, accepted)
|
||||
}
|
||||
|
||||
/// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a
|
||||
@@ -387,7 +390,21 @@ pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String
|
||||
Box::pin(async move { read(&state, &scope).await })
|
||||
});
|
||||
let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||
#[cfg(not(test))]
|
||||
tokio::spawn(run(watch, sender, reader));
|
||||
#[cfg(test)]
|
||||
{
|
||||
let observer = crate::app::dispatch_observer::installed_observer();
|
||||
tokio::spawn(async move {
|
||||
match observer {
|
||||
Some(observer) => {
|
||||
crate::app::dispatch_observer::observe(observer, run(watch, sender, reader))
|
||||
.await
|
||||
}
|
||||
None => run(watch, sender, reader).await,
|
||||
}
|
||||
});
|
||||
}
|
||||
receiver
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! SDK serialization for the stream-local list-change notifications.
|
||||
|
||||
use rmcp::model::{
|
||||
JsonRpcNotification, JsonRpcVersion2_0, NotificationMetaObject, PromptListChangedNotification,
|
||||
ResourceListChangedNotification, SubscriptionFilter, SubscriptionsAcknowledgedNotification,
|
||||
SubscriptionsAcknowledgedNotificationParams, ToolListChangedNotification,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::{PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, Signals, TOOL_LIST_CHANGED};
|
||||
|
||||
fn subscription_meta(subscription_id: &Value) -> NotificationMetaObject {
|
||||
let mut meta = Map::new();
|
||||
// Keep the JSON identity: SDK RequestId narrows numbers to i64.
|
||||
meta.insert(
|
||||
super::SUBSCRIPTION_ID_KEY.to_owned(),
|
||||
subscription_id.clone(),
|
||||
);
|
||||
NotificationMetaObject::from(meta)
|
||||
}
|
||||
|
||||
pub(super) fn signal_frame(method: &str, subscription_id: Option<&Value>) -> String {
|
||||
let meta = subscription_id.map(subscription_meta);
|
||||
let frame = match method {
|
||||
RESOURCE_LIST_CHANGED => {
|
||||
let mut notification = ResourceListChangedNotification::default();
|
||||
if let Some(meta) = meta {
|
||||
notification.extensions.insert(meta);
|
||||
}
|
||||
serde_json::to_string(&JsonRpcNotification {
|
||||
jsonrpc: JsonRpcVersion2_0,
|
||||
notification,
|
||||
})
|
||||
}
|
||||
PROMPT_LIST_CHANGED => {
|
||||
let mut notification = PromptListChangedNotification::default();
|
||||
if let Some(meta) = meta {
|
||||
notification.extensions.insert(meta);
|
||||
}
|
||||
serde_json::to_string(&JsonRpcNotification {
|
||||
jsonrpc: JsonRpcVersion2_0,
|
||||
notification,
|
||||
})
|
||||
}
|
||||
TOOL_LIST_CHANGED => {
|
||||
let mut notification = ToolListChangedNotification::default();
|
||||
if let Some(meta) = meta {
|
||||
notification.extensions.insert(meta);
|
||||
}
|
||||
serde_json::to_string(&JsonRpcNotification {
|
||||
jsonrpc: JsonRpcVersion2_0,
|
||||
notification,
|
||||
})
|
||||
}
|
||||
_ => unreachable!("list-change methods are a closed set"),
|
||||
}
|
||||
.expect("SDK list-change notification with JSON metadata is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_signal_notification_serialized();
|
||||
frame
|
||||
}
|
||||
|
||||
pub(super) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||
let mut notifications = SubscriptionFilter::new();
|
||||
notifications.resources_list_changed = accepted.resources.then_some(true);
|
||||
notifications.prompts_list_changed = accepted.prompts.then_some(true);
|
||||
notifications.tools_list_changed = accepted.tools.then_some(true);
|
||||
let params = SubscriptionsAcknowledgedNotificationParams::new(notifications)
|
||||
.with_meta(subscription_meta(subscription_id));
|
||||
let notification = SubscriptionsAcknowledgedNotification::new(params);
|
||||
let frame = serde_json::to_string(&JsonRpcNotification {
|
||||
jsonrpc: JsonRpcVersion2_0,
|
||||
notification,
|
||||
})
|
||||
.expect("SDK subscription acknowledgment with JSON metadata is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_subscriptions_acknowledged_serialized();
|
||||
frame
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
const METHODS: [&str; 3] = [
|
||||
RESOURCE_LIST_CHANGED,
|
||||
PROMPT_LIST_CHANGED,
|
||||
TOOL_LIST_CHANGED,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn legacy_signals_omit_params() {
|
||||
for method in METHODS {
|
||||
let frame: Value = serde_json::from_str(&signal_frame(method, None)).unwrap();
|
||||
assert_eq!(frame, json!({"jsonrpc": "2.0", "method": method}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modern_signals_and_acknowledgments_preserve_json_identity() {
|
||||
for encoded in [
|
||||
r#""subscription-\"quoted""#,
|
||||
"-7",
|
||||
"18446744073709551615",
|
||||
"1.0",
|
||||
"0.12345678901234567890123456789",
|
||||
"1.234567890123456789e+25",
|
||||
] {
|
||||
let id: Value = serde_json::from_str(encoded).unwrap();
|
||||
let mut frames = METHODS
|
||||
.map(|method| (signal_frame(method, Some(&id)), method))
|
||||
.to_vec();
|
||||
frames.push((
|
||||
acknowledged_frame(&id, Signals::default()),
|
||||
super::super::SUBSCRIPTIONS_ACKNOWLEDGED,
|
||||
));
|
||||
for (encoded_frame, method) in frames {
|
||||
let frame: Value = serde_json::from_str(&encoded_frame).unwrap();
|
||||
assert_eq!(frame["jsonrpc"], "2.0");
|
||||
assert_eq!(frame["method"], method);
|
||||
assert_eq!(
|
||||
frame["params"]["_meta"][super::super::SUBSCRIPTION_ID_KEY],
|
||||
id
|
||||
);
|
||||
assert_eq!(
|
||||
frame["params"]["_meta"][super::super::SUBSCRIPTION_ID_KEY].to_string(),
|
||||
id.to_string(),
|
||||
);
|
||||
assert_eq!(frame["params"]["_meta"].as_object().unwrap().len(), 1);
|
||||
assert!(frame.get("id").is_none());
|
||||
if method != super::super::SUBSCRIPTIONS_ACKNOWLEDGED {
|
||||
assert_eq!(frame["params"].as_object().unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acknowledgment_reports_only_accepted_true_flags_and_never_uris() {
|
||||
for resources in [false, true] {
|
||||
for prompts in [false, true] {
|
||||
for tools in [false, true] {
|
||||
let accepted = Signals {
|
||||
resources,
|
||||
prompts,
|
||||
tools,
|
||||
};
|
||||
let frame: Value =
|
||||
serde_json::from_str(&acknowledged_frame(&json!("listen"), accepted))
|
||||
.unwrap();
|
||||
let mut expected = Map::new();
|
||||
for (enabled, name) in [
|
||||
(resources, "resourcesListChanged"),
|
||||
(prompts, "promptsListChanged"),
|
||||
(tools, "toolsListChanged"),
|
||||
] {
|
||||
if enabled {
|
||||
expected.insert(name.to_owned(), Value::Bool(true));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
frame,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": super::super::SUBSCRIPTIONS_ACKNOWLEDGED,
|
||||
"params": {
|
||||
"_meta": {super::super::SUBSCRIPTION_ID_KEY: "listen"},
|
||||
"notifications": expected,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Completion actual ServerHandler execution/consumption observer oracle.
|
||||
use super::{CounterSet, observe};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[
|
||||
c.sdk_completion_handler_completed(),
|
||||
c.sdk_completion_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn delta(c: &CounterSet, before: [usize; 2]) -> ([usize; 2], [usize; 2]) {
|
||||
let after = counts(c);
|
||||
(std::array::from_fn(|i| after[i] - before[i]), [1, 1])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_handler_observer_positive_control() {
|
||||
use super::{sdk_completion_handler_completed, sdk_completion_handler_consumed};
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
sdk_completion_handler_completed();
|
||||
sdk_completion_handler_consumed();
|
||||
assert_eq!(counts(&counters), [0, 0], "out-of-scope markers are no-ops");
|
||||
observe(counters.clone(), async {
|
||||
sdk_completion_handler_completed();
|
||||
sdk_completion_handler_consumed();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&counters), [1, 1]);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Real trait execution, lossless request context, typed result consumption and drop ownership.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Domain {
|
||||
outcome: Mutex<Option<CompletionOutcome>>,
|
||||
calls: AtomicUsize,
|
||||
pending: bool,
|
||||
dropped: AtomicBool,
|
||||
finished: AtomicBool,
|
||||
}
|
||||
struct DropWitness<'a>(&'a AtomicBool);
|
||||
impl Drop for DropWitness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Domain {
|
||||
pub(super) async fn complete(&self, command: CompletionCommand) -> CompletionOutcome {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
assert!(
|
||||
matches!(command.reference, CompletionReference::Resource { uri } if uri == "crank://bound/{region}")
|
||||
);
|
||||
assert_eq!(command.argument.name, "region");
|
||||
assert_eq!(command.argument.value, "e");
|
||||
assert_eq!(command.context.unwrap().arguments.unwrap(), args());
|
||||
let _guard = DropWitness(&self.dropped);
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
self.finished.store(true, SeqCst);
|
||||
self.outcome
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("single domain execution")
|
||||
}
|
||||
}
|
||||
fn args() -> Map<String, Value> {
|
||||
json!({"number":42,"bool":true,"null":null,"array":["x"],"object":{"a":1}})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
fn scope(revision: &str) -> Scope {
|
||||
Scope {
|
||||
workspace: "workspace".into(),
|
||||
agent: "agent".into(),
|
||||
credential: VerifiedMachineCredential {
|
||||
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
scopes: vec![crank_core::PlatformApiKeyScope::Read],
|
||||
platform_api_key_id: Some("key".into()),
|
||||
},
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: protocol::ContinuationSupport::from_supported(false),
|
||||
locale: ExecutionLocale::En,
|
||||
revision: revision.into(),
|
||||
context: Some(args()),
|
||||
}
|
||||
}
|
||||
fn params() -> CompleteRequestParams {
|
||||
CompleteRequestParams::new(
|
||||
Reference::for_resource("crank://bound/{region}"),
|
||||
ArgumentInfo::new("region", "e"),
|
||||
)
|
||||
}
|
||||
async fn state() -> Arc<AppState> {
|
||||
crank_test_support::postgres_schema_url_for_task("completion_handler_local", "t_7458fe3b")
|
||||
.await;
|
||||
super::super::rmcp_tools_tests::test_state().await
|
||||
}
|
||||
fn handler(state: &Arc<AppState>, outcome: CompletionOutcome, pending: bool) -> CompletionHandler {
|
||||
CompletionHandler {
|
||||
state: state.clone(),
|
||||
domain: Some(Arc::new(Domain {
|
||||
outcome: Mutex::new(Some(outcome)),
|
||||
pending,
|
||||
..Default::default()
|
||||
})),
|
||||
}
|
||||
}
|
||||
async fn context(h: &CompletionHandler, revision: &str) -> RequestContext<RoleServer> {
|
||||
let c = request_context(h, scope(revision)).await.unwrap();
|
||||
assert!(c.peer.is_transport_closed());
|
||||
assert_eq!(
|
||||
h.domain.as_ref().unwrap().calls.load(SeqCst),
|
||||
0,
|
||||
"bootstrap must not execute domain"
|
||||
);
|
||||
let s = CompletionHandler::scope(&c).unwrap();
|
||||
assert_eq!(s.workspace, "workspace");
|
||||
assert_eq!(s.agent, "agent");
|
||||
assert_eq!(s.revision, revision);
|
||||
assert_eq!(s.credential.platform_api_key_id.unwrap().as_str(), "key");
|
||||
c
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_trait_result_is_consumed_and_domain_runs_once() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let h = handler(
|
||||
&state,
|
||||
CompletionOutcome::Completed {
|
||||
values: vec!["eu".into()],
|
||||
total: Some(1),
|
||||
has_more: false,
|
||||
},
|
||||
false,
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let mut result = ServerHandler::complete(&h, params(), c).await.unwrap();
|
||||
assert_eq!(result.completion.values, ["eu"]);
|
||||
result.completion.values = vec!["typed".into()];
|
||||
result.completion.total = None;
|
||||
result.completion.has_more = Some(true);
|
||||
match restore(Ok(result)) {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => {
|
||||
assert_eq!(values, ["typed"]);
|
||||
assert_eq!(total, None);
|
||||
assert!(has_more);
|
||||
}
|
||||
_ => panic!("typed result not consumed"),
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let h = handler(
|
||||
&state,
|
||||
CompletionOutcome::Completed {
|
||||
values: vec![],
|
||||
total: None,
|
||||
has_more: false,
|
||||
},
|
||||
false,
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let result = ServerHandler::complete(&h, params(), c).await.unwrap();
|
||||
assert!(result.completion.values.is_empty());
|
||||
assert_eq!(result.completion.total, None);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_dropping_trait_future_drops_pending_domain() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let h = handler(&state, CompletionOutcome::CatalogUnavailable, true);
|
||||
let c = context(&h, revision).await;
|
||||
let domain = h.domain.as_ref().unwrap();
|
||||
let mut future = Box::pin(ServerHandler::complete(&h, params(), c));
|
||||
assert!(futures_util::poll!(&mut future).is_pending());
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
assert!(!domain.dropped.load(SeqCst));
|
||||
drop(future);
|
||||
assert!(domain.dropped.load(SeqCst));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!domain.finished.load(SeqCst));
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_trait_errors_remain_safe() {
|
||||
let state = state().await;
|
||||
for outcome in [
|
||||
CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
|
||||
CompletionOutcome::NotAvailable,
|
||||
CompletionOutcome::CatalogUnavailable,
|
||||
] {
|
||||
let h = handler(&state, outcome, false);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::complete(&h, params(), c).await;
|
||||
assert!(result.is_err());
|
||||
let error = result.as_ref().unwrap_err();
|
||||
assert!(!error.to_string().contains("crank://bound"));
|
||||
match error.code {
|
||||
ErrorCode::INVALID_PARAMS => assert!(matches!(
|
||||
restore(result),
|
||||
CompletionOutcome::InvalidParams(_) | CompletionOutcome::NotAvailable
|
||||
)),
|
||||
ErrorCode::INTERNAL_ERROR => assert!(matches!(
|
||||
restore(result),
|
||||
CompletionOutcome::CatalogUnavailable
|
||||
)),
|
||||
_ => panic!("unexpected error"),
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_completion_test_support.rs"]
|
||||
mod fixtures;
|
||||
use super::rmcp_completion_handler_runtime_tests as handler;
|
||||
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
@@ -89,8 +90,10 @@ async fn success(
|
||||
session: Option<&str>,
|
||||
p: Value,
|
||||
sse: bool,
|
||||
require_handler: bool,
|
||||
) -> (Value, [usize; 2]) {
|
||||
let before = counts(&h.counters);
|
||||
let handler_before = handler::counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
@@ -107,12 +110,19 @@ async fn success(
|
||||
assert!(result.get(key).is_none(), "{body}");
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
let handler_delta = handler::delta(&h.counters, handler_before);
|
||||
if require_handler {
|
||||
assert_eq!(
|
||||
handler_delta.0, handler_delta.1,
|
||||
"actual completion handler execution/consumption: {handler_delta:?}"
|
||||
);
|
||||
}
|
||||
(
|
||||
result["completion"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
async fn control(revision: &str, require_handler: bool) -> Vec<[usize; 2]> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
@@ -149,7 +159,7 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
] {
|
||||
let (completion, delta) = success(&h, revision, session, p, sse).await;
|
||||
let (completion, delta) = success(&h, revision, session, p, sse, require_handler).await;
|
||||
assert_eq!(completion, expected);
|
||||
deltas.push(delta);
|
||||
}
|
||||
@@ -160,6 +170,7 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
session,
|
||||
params(resource(uri), "region", "item"),
|
||||
sse,
|
||||
require_handler,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
@@ -179,7 +190,8 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
}
|
||||
let mut with_context = params(prompt("greeting"), "tone", "w");
|
||||
with_context["context"] = json!({"arguments":{"name":"Ada","tone":"dry"}});
|
||||
let (completion, delta) = success(&h, revision, session, with_context, sse).await;
|
||||
let (completion, delta) =
|
||||
success(&h, revision, session, with_context, sse, require_handler).await;
|
||||
assert_eq!(completion, json!({"values":["warm"],"total":1}));
|
||||
deltas.push(delta);
|
||||
let mut unavailable = None;
|
||||
@@ -284,15 +296,15 @@ async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
control(LEGACY_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
control(MODERN_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
let deltas = control(LEGACY_REVISION, true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
@@ -300,7 +312,7 @@ async fn rmcp_completion_sdk_legacy() {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
let deltas = control(MODERN_REVISION, true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! #107 generic dispatch: existing wire GREEN precedes independent SDK RED assertions.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, atomic::Ordering};
|
||||
#[path = "rmcp_dispatch_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::*;
|
||||
|
||||
async fn success_control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = prepared(&h, revision).await;
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for id in [
|
||||
json!("dispatch/Ю"),
|
||||
json!(18446744073709551615u64),
|
||||
json!(3.25),
|
||||
] {
|
||||
for method in ["tools/list", "ping"] {
|
||||
let mut message = payload(revision, method, id.clone());
|
||||
// Legacy params remain absent; modern identity metadata remains mandatory.
|
||||
message["extension"] = json!({"future":[null,true]});
|
||||
message["result"] = json!({"ignored":true});
|
||||
message["error"] = json!({"ignored":"not an error envelope"});
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let response = request(&h, revision, session.as_deref(), accept, message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(wire["id"], id, "lossless response correlation");
|
||||
assert!(wire.get("error").is_none(), "{wire}");
|
||||
if method == "tools/list" {
|
||||
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
assert_eq!(wire["result"]["tools"].as_array().unwrap().len(), 1);
|
||||
} else {
|
||||
let result = if revision == MODERN_REVISION {
|
||||
json!({"protocolVersion":revision,"resultType":"complete"})
|
||||
} else {
|
||||
json!({"protocolVersion":revision})
|
||||
};
|
||||
assert_eq!(wire, json!({"jsonrpc":"2.0","id":id,"result":result}));
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(wire["result"]["resultType"], "complete");
|
||||
assert_eq!(h.sessions.snapshot(), ops, "no modern session access");
|
||||
}
|
||||
assert_deltas(
|
||||
method,
|
||||
entries,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(
|
||||
1,
|
||||
usize::from(revision == MODERN_REVISION),
|
||||
usize::from(revision == LEGACY_REVISION),
|
||||
usize::from(method == "tools/list"),
|
||||
),
|
||||
);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN 24 HTTP requests after legacy handshake / modern discovery; SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wire_positive_control_json_sse_ids_tolerance_and_routes() {
|
||||
success_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_envelope_decoded_on_successful_http() {
|
||||
let deltas = success_control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
|
||||
vec![1; 24],
|
||||
"successful HTTP must decode a real SDK request envelope"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_envelope_consumed_for_registry_routing_on_successful_http() {
|
||||
let deltas = success_control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
|
||||
vec![1; 24],
|
||||
"decoded SDK method/kind must drive registry routing, not decode-and-discard"
|
||||
);
|
||||
}
|
||||
|
||||
async fn notification_control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let response = request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
None,
|
||||
"application/json",
|
||||
legacy_initialize(1),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let _ = body(response, false).await;
|
||||
for method in ["notifications/initialized", "unknown/notification"] {
|
||||
let mut wrong_kind = json!({"jsonrpc":"2.0","id":"wrong-kind","method":method});
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
wrong_kind.clone(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(body(response, false).await["error"]["code"], -32601);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
|
||||
wrong_kind.as_object_mut().unwrap().remove("id");
|
||||
if method.starts_with("unknown") {
|
||||
ack(request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
wrong_kind,
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
|
||||
}
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
ack(request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
assert!(h.sessions.retained(&session).await.unwrap().initialized);
|
||||
let after = sdk(&h.counters);
|
||||
let mut deltas = vec![[after[0] - before[0], after[1] - before[1]]];
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
for method in [
|
||||
"notifications/initialized",
|
||||
"unknown/notification",
|
||||
"tools/call",
|
||||
] {
|
||||
let mut message = payload(MODERN_REVISION, method, json!(1));
|
||||
message.as_object_mut().unwrap().remove("id");
|
||||
let mut req = request(&h, MODERN_REVISION, None, "application/json", message)
|
||||
.build()
|
||||
.unwrap();
|
||||
req.headers_mut().remove("Mcp-Method");
|
||||
req.headers_mut().remove("Mcp-Name");
|
||||
let before = sdk(&h.counters);
|
||||
ack(reqwest::Client::new().execute(req).await.unwrap()).await;
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
eprintln!("existing GREEN notification kind/state/early ACK; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_order_and_legacy_registered_kind_wire_control() {
|
||||
notification_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_notification_kind_consumed_on_successful_http() {
|
||||
assert_eq!(
|
||||
notification_control().await,
|
||||
vec![[1, 1]; 4],
|
||||
"SDK notification variant must drive legacy handshake / modern early ACK"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejection_controls_never_enter_service_or_outbound() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = prepared(&h, revision).await;
|
||||
let base = payload(revision, "tools/list", json!("reject"));
|
||||
let mut malformed = base.clone();
|
||||
malformed["jsonrpc"] = json!("1.0");
|
||||
let mut bad_params = base.clone();
|
||||
bad_params["params"] = json!([]);
|
||||
let mut bad_meta = base.clone();
|
||||
bad_meta["params"] = json!({"_meta":false});
|
||||
let unknown = payload(revision, "unknown/request", json!("reject"));
|
||||
let wrong_era = payload(
|
||||
revision,
|
||||
if revision == MODERN_REVISION {
|
||||
"initialize"
|
||||
} else {
|
||||
"server/discover"
|
||||
},
|
||||
json!("reject"),
|
||||
);
|
||||
for (message, status, code) in [
|
||||
(malformed, 400, -32600),
|
||||
(bad_params, 400, -32600),
|
||||
(bad_meta, 400, -32020),
|
||||
(
|
||||
unknown,
|
||||
if revision == MODERN_REVISION {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
},
|
||||
-32601,
|
||||
),
|
||||
(
|
||||
wrong_era,
|
||||
if revision == MODERN_REVISION {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
},
|
||||
-32601,
|
||||
),
|
||||
] {
|
||||
let entries = h.counters.snapshot();
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
revision,
|
||||
session.as_deref(),
|
||||
"application/json",
|
||||
message.clone(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status().as_u16(), status, "{revision} {message}");
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(wire["error"]["code"], code, "{revision} {message}: {wire}");
|
||||
assert!(wire.get("result").is_none());
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (header, value) in [("Mcp-Method", "ping"), ("Mcp-Name", "wrong-tool")] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let message = json!({"jsonrpc":"2.0","id":"headers","method":"tools/call","params":{"name":TOOL_NAME,"arguments":{"email":"dispatch@example.com"},"_meta":modern_meta()}});
|
||||
let response = request(&h, MODERN_REVISION, None, "application/json", message)
|
||||
.header(header, value)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert!(body(response, false).await.get("error").is_some());
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
"2099-01-01",
|
||||
None,
|
||||
"application/json",
|
||||
payload(LEGACY_REVISION, "tools/list", json!(1)),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert!(body(response, false).await.get("error").is_some());
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observer_independent_positive_control() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
super::sdk_dispatch_envelope_decoded();
|
||||
super::sdk_dispatch_envelope_consumed();
|
||||
assert_eq!(sdk(&a), [0, 0]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_dispatch_envelope_decoded();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_dispatch_envelope_consumed();
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0]);
|
||||
assert_eq!(sdk(&b), [0, 1]);
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Narrow HTTP helpers; all app/auth/catalog/upstream fixtures remain shared.
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("dispatch_owner", "t_e862066c").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
pub(super) fn sdk(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_dispatch_decoded(), c.sdk_dispatch_consumed()]
|
||||
}
|
||||
|
||||
pub(super) fn payload(revision: &str, method: &str, id: Value) -> Value {
|
||||
let mut message = json!({"jsonrpc":"2.0","id":id,"method":method});
|
||||
if revision == MODERN_REVISION {
|
||||
message["params"] = json!({"_meta":modern_meta()});
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
pub(super) fn request(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
message: Value,
|
||||
) -> reqwest::RequestBuilder {
|
||||
h.request(revision, session, &h.key, accept, message)
|
||||
.header("x-request-id", "dispatch-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "dispatch-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
let raw = tokio::time::timeout(std::time::Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("data:"))
|
||||
.map(|l| serde_json::from_str(l.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn ack(response: reqwest::Response) {
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
pub(super) async fn prepared(h: &Endpoint, revision: &str) -> Option<String> {
|
||||
if revision == LEGACY_REVISION {
|
||||
return h.session(revision).await;
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
h,
|
||||
revision,
|
||||
None,
|
||||
"application/json",
|
||||
payload(revision, "server/discover", json!(1)),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(
|
||||
wire["result"]["supportedVersions"],
|
||||
json!([MODERN_REVISION, LEGACY_REVISION])
|
||||
);
|
||||
assert_eq!(wire["result"]["resultType"], "complete");
|
||||
assert!(wire.get("error").is_none(), "{wire}");
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! #107 envelope migration: independent real HTTP wire and SDK participation controls.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
// Reuse the existing real build_app, published catalog, auth and loopback execution fixture.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
|
||||
fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_jsonrpc_response(), c.sdk_jsonrpc_error()]
|
||||
}
|
||||
|
||||
async fn wire(
|
||||
response: reqwest::Response,
|
||||
revision: &str,
|
||||
id: &Value,
|
||||
sse: bool,
|
||||
session: Option<&str>,
|
||||
) -> Value {
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
200,
|
||||
"envelope id={id}, SSE={sse}, revision={revision}"
|
||||
);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.map(|v| v.to_str().unwrap()),
|
||||
if sse { session } else { None }
|
||||
);
|
||||
let request_id = response.headers()["x-request-id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let trace_id = response.headers()["x-trace-id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let content_type = response.headers()["content-type"].to_str().unwrap();
|
||||
assert!(content_type.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
}));
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
let terminals: Vec<_> = frames.iter().filter(|f| f.get("id").is_some()).collect();
|
||||
assert_eq!(terminals.len(), 1, "one terminal envelope: {raw}");
|
||||
assert_eq!(frames.last(), Some(terminals[0]), "terminal must be last");
|
||||
for frame in &frames[..frames.len() - 1] {
|
||||
assert_eq!(frame["method"], "notifications/progress");
|
||||
assert_eq!(frame["params"]["progressToken"], "envelope-stream");
|
||||
}
|
||||
terminals[0].clone()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(body["id"], *id);
|
||||
assert_eq!(
|
||||
body["id"].to_string(),
|
||||
id.to_string(),
|
||||
"preserve numeric form"
|
||||
);
|
||||
assert_eq!(
|
||||
body.as_object().unwrap().len(),
|
||||
3,
|
||||
"no envelope extensions: {body}"
|
||||
);
|
||||
assert!(body.get("method").is_none());
|
||||
if let Some(error) = body.get("error") {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"protocol error, not tool isError"
|
||||
);
|
||||
assert_eq!(error["code"], -32602);
|
||||
if sse {
|
||||
// Existing stream polling has no request correlation scope; preserve omission.
|
||||
assert!(
|
||||
error.get("data").is_none(),
|
||||
"existing SSE omission: {error}"
|
||||
);
|
||||
assert_eq!(error.as_object().unwrap().len(), 2);
|
||||
} else {
|
||||
assert_eq!(
|
||||
error["data"],
|
||||
json!({"request_id":request_id,"trace_id":trace_id})
|
||||
);
|
||||
assert_eq!(error.as_object().unwrap().len(), 3);
|
||||
}
|
||||
} else {
|
||||
assert!(body.get("result").is_some());
|
||||
}
|
||||
body
|
||||
}
|
||||
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
// Own the process-wide disposable DB before the reused fixture's older ownership hint.
|
||||
crank_test_support::postgres_schema_url_for_task("envelopes_owner", "t_b27f5c9d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let mut deltas = vec![];
|
||||
for id in [
|
||||
json!("opaque/Ю"),
|
||||
json!(""),
|
||||
json!(i64::MIN),
|
||||
json!(i64::MAX),
|
||||
json!(9007199254740993_u64),
|
||||
json!(u64::MAX),
|
||||
json!(1.5),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
] {
|
||||
for invalid in [false, true] {
|
||||
let mut params = if invalid {
|
||||
json!({"cursor":"not-a-cursor"})
|
||||
} else {
|
||||
json!({"cursor":"1"})
|
||||
};
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
let before = counts(&h.counters);
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":params}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let body = wire(response, revision, &id, false, session.as_deref()).await;
|
||||
if invalid {
|
||||
assert_eq!(body["error"]["message"], "invalid tools/list cursor");
|
||||
} else {
|
||||
let mut expected = json!({"tools":[]});
|
||||
if revision == MODERN_REVISION {
|
||||
expected["resultType"] = json!("complete");
|
||||
expected["cacheScope"] = json!("private");
|
||||
expected["ttlMs"] = json!(0);
|
||||
}
|
||||
assert_eq!(
|
||||
body["result"], expected,
|
||||
"empty result and omission of nextCursor"
|
||||
);
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
}
|
||||
// Both revisions support streamed calls with the combined Accept negotiation.
|
||||
// Missing tool resolves inside the shared Tools command, after the stream opens.
|
||||
for sse in [false, true] {
|
||||
for invalid in [false, true] {
|
||||
let id = if invalid {
|
||||
json!(u64::MAX)
|
||||
} else {
|
||||
json!(-0.0)
|
||||
};
|
||||
let mut params =
|
||||
json!({"name":TOOL_NAME,"arguments":{"email":"envelopes@example.test"}});
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
if invalid {
|
||||
params["name"] = json!("missing_tool");
|
||||
} else {
|
||||
h.gate.add_permits(1);
|
||||
}
|
||||
if sse {
|
||||
params["_meta"]["progressToken"] = json!("envelope-stream");
|
||||
}
|
||||
let before = counts(&h.counters);
|
||||
let mut request = h
|
||||
.request(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
&h.key,
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":params}),
|
||||
)
|
||||
.build()
|
||||
.unwrap();
|
||||
if revision == MODERN_REVISION {
|
||||
request.headers_mut().insert(
|
||||
"Mcp-Name",
|
||||
if invalid { "missing_tool" } else { TOOL_NAME }
|
||||
.parse()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let response = reqwest::Client::new().execute(request).await.unwrap();
|
||||
let body = wire(response, revision, &id, sse, session.as_deref()).await;
|
||||
if invalid {
|
||||
assert_eq!(body["error"]["message"], "tool missing_tool was not found");
|
||||
} else {
|
||||
assert_eq!(
|
||||
body["result"].as_object().unwrap().len(),
|
||||
if revision == MODERN_REVISION { 4 } else { 3 }
|
||||
);
|
||||
assert_eq!(body["result"]["isError"], false);
|
||||
assert_eq!(
|
||||
body["result"]["structuredContent"],
|
||||
json!({"id":"lead_progress"})
|
||||
);
|
||||
assert_eq!(
|
||||
body["result"]["content"],
|
||||
json!([{"type":"text","text":serde_json::to_string_pretty(&json!({"id":"lead_progress"})).unwrap()}])
|
||||
);
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(body["result"]["resultType"], "complete");
|
||||
} else {
|
||||
assert!(body["result"].get("resultType").is_none());
|
||||
}
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN envelopes wire {revision}: exact id forms, JSON success/protocol error, terminal SSE success/protocol error; SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_envelopes_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_envelopes_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_envelopes_sdk_legacy() {
|
||||
let actual = control(LEGACY_REVISION).await;
|
||||
let expected: Vec<_> = (0..actual.len())
|
||||
.map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] })
|
||||
.collect();
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"real SDK envelope serialization after complete HTTP body"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_envelopes_sdk_modern() {
|
||||
let actual = control(MODERN_REVISION).await;
|
||||
let expected: Vec<_> = (0..actual.len())
|
||||
.map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] })
|
||||
.collect();
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"real SDK envelope serialization after complete HTTP body"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_envelopes_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observe(c.clone(), async {
|
||||
super::sdk_jsonrpc_response_serialized();
|
||||
super::sdk_jsonrpc_error_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&c), [1, 1]);
|
||||
super::sdk_jsonrpc_response_serialized();
|
||||
super::sdk_jsonrpc_error_serialized();
|
||||
assert_eq!(counts(&c), [1, 1], "out-of-scope markers are no-ops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rmcp_envelopes_helper_lossless_control() {
|
||||
use crate::jsonrpc::{jsonrpc_error, jsonrpc_result};
|
||||
let values = [
|
||||
json!(null),
|
||||
json!(""),
|
||||
json!("Ю"),
|
||||
json!(i64::MIN),
|
||||
json!(i64::MAX),
|
||||
json!(9007199254740993_u64),
|
||||
json!(u64::MAX),
|
||||
json!(1.5),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
json!([null, {"nested":u64::MAX}]),
|
||||
json!({"x":null}),
|
||||
];
|
||||
for id in &values {
|
||||
for result in &values {
|
||||
let actual = jsonrpc_result(id.clone(), result.clone());
|
||||
let expected = json!({"jsonrpc":"2.0","id":id,"result":result});
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual.to_string(), expected.to_string());
|
||||
}
|
||||
for code in [
|
||||
i64::MIN,
|
||||
i32::MIN as i64 - 1,
|
||||
i32::MIN as i64,
|
||||
-32602,
|
||||
i32::MAX as i64,
|
||||
i32::MAX as i64 + 1,
|
||||
i64::MAX,
|
||||
] {
|
||||
for message in ["", "Ошибка Ю"] {
|
||||
let actual = jsonrpc_error(id.clone(), code, message);
|
||||
let expected =
|
||||
json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}});
|
||||
assert_eq!(actual, expected, "data absent outside correlation scope");
|
||||
assert_eq!(actual.to_string(), expected.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! #107 initialize input: existing wire tolerance GREEN, independent SDK-consumption RED.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
const ACCEPTS: [&str; 2] = ["application/json", "text/event-stream, application/json"];
|
||||
const TRACE: &str = "11111111111111111111111111111111";
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("initialize_input_owner", "t_ffc30fcd").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
async fn post(h: &Endpoint, params: Option<Value>, accept: &str) -> reqwest::Response {
|
||||
let mut payload = json!({"jsonrpc":"2.0","id":"initialize/Ю","method":"initialize"});
|
||||
if let Some(params) = params {
|
||||
payload["params"] = params;
|
||||
}
|
||||
h.request(LEGACY_REVISION, None, &h.key, accept, payload)
|
||||
.header("x-request-id", "initialize-input")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "initialize-input");
|
||||
assert_eq!(response.headers()["x-trace-id"], TRACE);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
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(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "exactly one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_shapes() -> Vec<(&'static str, Value, bool)> {
|
||||
let mut cases = vec![(
|
||||
"capabilities omitted",
|
||||
json!({"protocolVersion":LEGACY_REVISION}),
|
||||
false,
|
||||
)];
|
||||
for (name, caps, elicitation) in [
|
||||
("null capabilities", Value::Null, false),
|
||||
("boolean capabilities", json!(true), false),
|
||||
("number capabilities", json!(7), false),
|
||||
("string capabilities", json!("caps"), false),
|
||||
("array capabilities", json!([{"elicitation":{}}]), false),
|
||||
("empty capabilities", json!({}), false),
|
||||
("null elicitation", json!({"elicitation":null}), false),
|
||||
("boolean elicitation", json!({"elicitation":true}), false),
|
||||
("number elicitation", json!({"elicitation":1}), false),
|
||||
("string elicitation", json!({"elicitation":"yes"}), false),
|
||||
("array elicitation", json!({"elicitation":[]}), false),
|
||||
("empty elicitation object", json!({"elicitation":{}}), true),
|
||||
(
|
||||
"extended elicitation",
|
||||
json!({"elicitation":{"form":{},"future":42},"future":[1]}),
|
||||
true,
|
||||
),
|
||||
] {
|
||||
cases.push((
|
||||
name,
|
||||
json!({"protocolVersion":LEGACY_REVISION,"capabilities":caps}),
|
||||
elicitation,
|
||||
));
|
||||
}
|
||||
for info in [
|
||||
Value::Null,
|
||||
json!(42),
|
||||
json!([]),
|
||||
json!({"name":false,"version":null}),
|
||||
json!({"name":"client","version":"1","future":true}),
|
||||
] {
|
||||
cases.push((
|
||||
"ignored clientInfo and extensions",
|
||||
json!({"protocolVersion":LEGACY_REVISION,
|
||||
"clientInfo":info,"unknown":{"nested":[null,1]},"_meta":{"future":true}}),
|
||||
false,
|
||||
));
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
async fn valid_control() -> Vec<usize> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ACCEPTS {
|
||||
for (name, params, elicitation) in valid_shapes() {
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
let response = post(&h, Some(params), accept).await;
|
||||
assert_eq!(response.status(), 200, "{name}");
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert!(!id.is_empty());
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(wire["id"], "initialize/Ю");
|
||||
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
assert!(wire.get("error").is_none());
|
||||
assert_deltas(
|
||||
name,
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
name,
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 1,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
let state = h
|
||||
.sessions
|
||||
.retained(&id)
|
||||
.await
|
||||
.expect("retained session, not a discarded DTO");
|
||||
assert_eq!(state.id, id);
|
||||
assert_eq!(state.protocol_version, LEGACY_REVISION);
|
||||
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
|
||||
assert_eq!(state.agent_slug, AGENT_SLUG);
|
||||
assert_eq!(state.supports_elicitation, elicitation, "{name}");
|
||||
assert!(!state.initialized);
|
||||
assert_eq!(state.updated_at, state.created_at);
|
||||
assert_eq!(
|
||||
(state.expires_at.unwrap() - state.created_at).whole_milliseconds(),
|
||||
86_400_000
|
||||
);
|
||||
deltas.push(h.counters.sdk_initialize_input() - sdk);
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert!(h.sessions.retained(&id).await.unwrap().initialized);
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let result = json_body(response).await;
|
||||
assert!(
|
||||
result.get("error").is_none(),
|
||||
"initialized opens a protected request: {result}"
|
||||
);
|
||||
assert_eq!(result["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
eprintln!("existing GREEN {name}; accept={accept}; elicitation={elicitation}");
|
||||
}
|
||||
}
|
||||
eprintln!("SDK input consumption deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_wire_tolerance_and_retained_sessions() {
|
||||
valid_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_sdk_consumed_by_negotiation() {
|
||||
let deltas = valid_control().await;
|
||||
assert!(!deltas.is_empty());
|
||||
assert_eq!(
|
||||
deltas,
|
||||
vec![1; valid_shapes().len() * ACCEPTS.len()],
|
||||
"real HTTP initialize must consume SDK InitializeRequestParams.protocol_version in negotiation"
|
||||
);
|
||||
}
|
||||
|
||||
// Current HTTP envelope admission rejects sequence params before serde's derived struct decoder.
|
||||
// Pin that observed boundary instead of imposing a new object-only check in the SDK decoder.
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_wire_invalid_shapes_and_admission() {
|
||||
let h = endpoint().await;
|
||||
for accept in ACCEPTS {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({"protocolVersion":null})),
|
||||
Some(json!({"protocolVersion":true})),
|
||||
Some(json!({"protocolVersion":42})),
|
||||
Some(json!({"protocolVersion":[]})),
|
||||
Some(json!({"protocolVersion":{}})),
|
||||
] {
|
||||
rejection(
|
||||
&h,
|
||||
params,
|
||||
accept,
|
||||
200,
|
||||
-32602,
|
||||
"invalid initialize parameters",
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for params in [
|
||||
json!(null),
|
||||
json!(true),
|
||||
json!(42),
|
||||
json!("bad"),
|
||||
json!([]),
|
||||
json!([LEGACY_REVISION]),
|
||||
json!([LEGACY_REVISION, {}]),
|
||||
json!([LEGACY_REVISION, {}, {}]),
|
||||
] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(params),
|
||||
accept,
|
||||
400,
|
||||
-32600,
|
||||
"invalid JSON-RPC request",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":version})),
|
||||
accept,
|
||||
400,
|
||||
-32602,
|
||||
&format!("unsupported protocol version {version}"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for meta in [Value::Null, json!(true), json!(42), json!("bad"), json!([])] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":LEGACY_REVISION,"_meta":meta})),
|
||||
accept,
|
||||
400,
|
||||
-32020,
|
||||
"protocol identity mismatch",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn rejection(
|
||||
h: &Endpoint,
|
||||
params: Option<Value>,
|
||||
accept: &str,
|
||||
status: u16,
|
||||
code: i64,
|
||||
message: &str,
|
||||
admission_only: bool,
|
||||
) {
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
let response = post(h, params.clone(), accept).await;
|
||||
assert_eq!(response.status().as_u16(), status, "params={params:?}");
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
// Only HTTP 200 dispatch errors use SSE; HTTP 400 stays JSON regardless of Accept.
|
||||
let sse = status == 200 && !admission_only && accept.starts_with("text/event-stream");
|
||||
let wire = body(response, sse).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(
|
||||
wire["id"],
|
||||
if code == -32600 {
|
||||
Value::Null
|
||||
} else {
|
||||
json!("initialize/Ю")
|
||||
}
|
||||
);
|
||||
assert_eq!(wire["error"]["code"], code, "params={params:?}; {wire}");
|
||||
assert_eq!(wire["error"]["message"], message);
|
||||
assert!(wire.get("result").is_none());
|
||||
// Initialize errors are constructed in the request scope, including terminal SSE errors.
|
||||
assert_eq!(wire["error"]["data"]["request_id"], "initialize-input");
|
||||
assert_eq!(wire["error"]["data"]["trace_id"], TRACE);
|
||||
if code == -32020 {
|
||||
assert_eq!(
|
||||
wire["error"]["data"]["details"],
|
||||
"request _meta must be an object"
|
||||
);
|
||||
}
|
||||
assert_deltas(
|
||||
"reject",
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, usize::from(!admission_only), 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
"reject",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
if !message.starts_with("unsupported protocol version") {
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialize_input(),
|
||||
sdk,
|
||||
"malformed input never reaches SDK consumption"
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN reject params={params:?}; accept={accept}; status={status}; code={code}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_sdk_unsupported_revision_uses_same_allowlist() {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ACCEPTS {
|
||||
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":version})),
|
||||
accept,
|
||||
400,
|
||||
-32602,
|
||||
&format!("unsupported protocol version {version}"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
deltas.push(h.counters.sdk_initialize_input() - sdk);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
deltas,
|
||||
vec![1; 8],
|
||||
"unsupported strings must reach the same SDK-backed negotiation, without minting sessions"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
let params: rmcp::model::InitializeRequestParams = serde_json::from_value(json!({
|
||||
"protocolVersion":LEGACY_REVISION,"capabilities":{},"clientInfo":{"name":"control","version":"1"}
|
||||
})).unwrap();
|
||||
observe(c.clone(), async {
|
||||
super::admission_enter();
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
assert_eq!(c.sdk_initialize_input(), 1);
|
||||
assert_eq!(
|
||||
c.sdk_initialize_result(),
|
||||
0,
|
||||
"input and output are independent"
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(c.snapshot(), Snapshot::new(1, 0, 0, 0));
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
assert_eq!(c.sdk_initialize_input(), 1, "out-of-scope call is a no-op");
|
||||
observe(Arc::new(CounterSet::default()), async {
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
c.sdk_initialize_input(),
|
||||
1,
|
||||
"another request scope is isolated"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Initialized HTTP transition against the existing PostgreSQL store, not an SDK session manager.
|
||||
use super::*;
|
||||
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
|
||||
use crate::session::{SessionState, SessionStoreError};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
struct FaultStore {
|
||||
inner: PostgresTransportSessionStore,
|
||||
fail_get: AtomicBool,
|
||||
fail_mark: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for FaultStore {
|
||||
async fn create(
|
||||
&self,
|
||||
revision: &str,
|
||||
workspace: &str,
|
||||
agent: &str,
|
||||
elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.inner
|
||||
.create(revision, workspace, agent, elicitation, now, expires)
|
||||
.await
|
||||
}
|
||||
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
if self.fail_get.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test read failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.get(id).await
|
||||
}
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
if self.fail_mark.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test mark failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.mark_initialized(id, now).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(id).await
|
||||
}
|
||||
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(now).await
|
||||
}
|
||||
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(now).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_durable", "t_9c033310").await;
|
||||
let registry = test_registry().await;
|
||||
let pool = registry.pool().clone();
|
||||
let store = Arc::new(FaultStore {
|
||||
inner: PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap(),
|
||||
fail_get: AtomicBool::new(false),
|
||||
fail_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;
|
||||
assert_eq!(response.status(), 200);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let before = store.get(&id).await.unwrap().unwrap();
|
||||
assert!(!before.initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [1, 1]);
|
||||
let restarted = PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let after = restarted.get(&id).await.unwrap().unwrap();
|
||||
assert!(after.initialized);
|
||||
assert_eq!(after.id, before.id);
|
||||
assert_eq!(after.workspace_slug, before.workspace_slug);
|
||||
assert_eq!(after.agent_slug, before.agent_slug);
|
||||
assert_eq!(after.protocol_version, before.protocol_version);
|
||||
assert_eq!(after.created_at, before.created_at);
|
||||
assert_eq!(after.expires_at, before.expires_at);
|
||||
assert_eq!(after.supports_elicitation, before.supports_elicitation);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":81,"method":"ping"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(body(response, false).await.get("error").is_none());
|
||||
|
||||
let pending = store
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
AGENT_SLUG,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
store.fail_mark.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [counts[0] + 1, counts[1] + 1]);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
store.fail_mark.store(false, Ordering::SeqCst);
|
||||
|
||||
// Fail reads without touching registry/auth tables; admission must stop before the SDK.
|
||||
store.fail_get.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
store.fail_get.store(false, Ordering::SeqCst);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_foreign_and_revision_guards_leave_state_untouched() {
|
||||
let h = endpoint().await;
|
||||
for (revision, workspace, agent) in [
|
||||
(LEGACY_REVISION, "foreign-workspace", AGENT_SLUG),
|
||||
(LEGACY_REVISION, WORKSPACE_SLUG, "foreign-agent"),
|
||||
("2024-11-05", WORKSPACE_SLUG, AGENT_SLUG),
|
||||
(MODERN_REVISION, WORKSPACE_SLUG, AGENT_SLUG),
|
||||
] {
|
||||
let id = h
|
||||
.sessions
|
||||
.create(
|
||||
revision,
|
||||
workspace,
|
||||
agent,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
let ops = h.sessions.snapshot();
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
if workspace != WORKSPACE_SLUG || agent != AGENT_SLUG {
|
||||
404
|
||||
} else {
|
||||
400
|
||||
}
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), counts[1]);
|
||||
if workspace == WORKSPACE_SLUG && agent == AGENT_SLUG {
|
||||
assert_eq!(h.counters.sdk_initialized_decoded(), counts[0]);
|
||||
}
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.sessions.retained(&id).await.unwrap(), state);
|
||||
}
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.header("MCP-Session-Id", "conflicting-session")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
h.registry
|
||||
.revoke_platform_api_key_for_agent(
|
||||
&workspace_id(),
|
||||
&agent_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_progress_other"),
|
||||
&OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.other_key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 401);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().create, ops.create);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! #107 initialized: real HTTP wire control, independent SDK decode and consumption oracles.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
#[path = "rmcp_initialized_durable_tests.rs"]
|
||||
mod durable;
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_owner", "t_9c033310").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
fn sdk(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_initialized_decoded(), c.sdk_initialized_consumed()]
|
||||
}
|
||||
|
||||
async fn post(
|
||||
h: &Endpoint,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
payload: Value,
|
||||
) -> reqwest::Response {
|
||||
h.request(LEGACY_REVISION, session, &h.key, accept, payload)
|
||||
.header("x-request-id", "initialized-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn correlation(response: &reqwest::Response) {
|
||||
assert_eq!(response.headers()["x-request-id"], "initialized-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
}
|
||||
|
||||
async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
correlation(&response);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("data:"))
|
||||
.map(|l| serde_json::from_str(l.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
async fn initialize(h: &Endpoint, accept: &str) -> String {
|
||||
let response = post(h, None, accept, legacy_initialize(71)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], 71);
|
||||
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
assert!(wire.get("error").is_none());
|
||||
let state = h.sessions.retained(&id).await.expect("retained session");
|
||||
assert!(!state.initialized);
|
||||
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
|
||||
assert_eq!(state.agent_slug, AGENT_SLUG);
|
||||
id
|
||||
}
|
||||
|
||||
async fn control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({"ignored":[null,true],
|
||||
"protocolVersion":false,"capabilities":42,"_meta":{"future":[]}})),
|
||||
] {
|
||||
let id = initialize(&h, accept).await;
|
||||
let untouched = initialize(&h, "application/json").await;
|
||||
let before_state = h.sessions.retained(&id).await.unwrap();
|
||||
let mut notification = json!({"jsonrpc":"2.0","method":"notifications/initialized",
|
||||
"extension":{"future":[null,42]}});
|
||||
if let Some(params) = params {
|
||||
notification["params"] = params;
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let response = post(&h, Some(&id), accept, notification.clone()).await;
|
||||
assert_eq!(response.status(), 202);
|
||||
correlation(&response);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_session_ops(
|
||||
"initialized",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
assert_deltas(
|
||||
"initialized",
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
assert!(state.initialized);
|
||||
assert_eq!(state.id, before_state.id);
|
||||
assert_eq!(state.workspace_slug, before_state.workspace_slug);
|
||||
assert_eq!(state.agent_slug, before_state.agent_slug);
|
||||
assert_eq!(state.protocol_version, before_state.protocol_version);
|
||||
assert_eq!(state.created_at, before_state.created_at);
|
||||
assert_eq!(state.expires_at, before_state.expires_at);
|
||||
assert_eq!(
|
||||
state.supports_elicitation,
|
||||
before_state.supports_elicitation
|
||||
);
|
||||
assert!(state.updated_at >= before_state.updated_at);
|
||||
assert!(!h.sessions.retained(&untouched).await.unwrap().initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
accept,
|
||||
json!({"jsonrpc":"2.0","id":"tools/Ю","method":"tools/list"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], "tools/Ю");
|
||||
assert!(wire.get("error").is_none());
|
||||
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
eprintln!(
|
||||
"existing GREEN initialize -> initialized -> tools/list accept={accept} notification={notification}; SDK delta={:?}",
|
||||
deltas.last().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_wire_handshake_tolerance_and_scoped_state() {
|
||||
control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_decoded_on_real_http_handshake() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"real HTTP initialized must decode the SDK InitializedNotification"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_variant_consumed_by_session_transition() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"matched ClientNotification variant must drive the real scoped session mutation, not just decode"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_admission_and_wrong_kind_never_mutate_or_consume() {
|
||||
let h = endpoint().await;
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let mut wrong_initialize = legacy_initialize(72);
|
||||
wrong_initialize.as_object_mut().unwrap().remove("id");
|
||||
let mut wrong_initialized = initialized_notification();
|
||||
wrong_initialized["id"] = json!(73);
|
||||
let mut cases = vec![
|
||||
(wrong_initialize, 202, None),
|
||||
(wrong_initialized, 200, Some(-32601)),
|
||||
];
|
||||
for params in [json!(null), json!(true), json!(42), json!("bad"), json!([])] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":params}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
}
|
||||
for meta in [
|
||||
json!(null),
|
||||
json!(false),
|
||||
json!(42),
|
||||
json!("bad"),
|
||||
json!([]),
|
||||
] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":meta}}),
|
||||
400,
|
||||
Some(-32020),
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
json!({"jsonrpc":"1.0","method":"notifications/initialized"}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
for (payload, status, code) in cases {
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = sdk(&h.counters);
|
||||
let response = post(&h, Some(&id), "application/json", payload.clone()).await;
|
||||
assert_eq!(response.status().as_u16(), status, "{payload}");
|
||||
if let Some(code) = code {
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(wire["error"]["code"], code, "{payload}: {wire}");
|
||||
assert!(wire.get("result").is_none());
|
||||
} else {
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
let after = h.sessions.snapshot();
|
||||
assert_eq!(after.create, ops.create);
|
||||
assert_eq!(after.mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
assert_eq!(
|
||||
sdk(&h.counters),
|
||||
before,
|
||||
"rejected before SDK decode/consume: {payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_missing_unknown_sessions_and_modern_never_consume() {
|
||||
let h = endpoint().await;
|
||||
for (session, status) in [(None, 400), (Some("unknown-session"), 404)] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = post(&h, session, "application/json", initialized_notification()).await;
|
||||
assert_eq!(response.status().as_u16(), status);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
let ops = 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());
|
||||
assert_eq!(
|
||||
h.sessions.snapshot(),
|
||||
ops,
|
||||
"modern signal never accesses storage"
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_observer_independent_positive_control() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(json!({"method":"notifications/initialized"})).unwrap();
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
assert_eq!(sdk(&a), [0, 0]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0]);
|
||||
assert_eq!(sdk(&b), [0, 1], "decode alone never proves consumption");
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! #107 negotiation results: existing HTTP wire GREEN, independent SDK execution oracle RED.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
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()]
|
||||
}
|
||||
|
||||
fn capabilities() -> Value {
|
||||
// Pin the reviewed advertisement, not a call to the builder under test or SDK defaults.
|
||||
json!({"completions":{},"logging":{},"prompts":{"listChanged":true},
|
||||
"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}})
|
||||
}
|
||||
|
||||
fn expected_result(revision: &str) -> Value {
|
||||
let server = json!({"name":"crank-mcp-server","version":env!("CARGO_PKG_VERSION")});
|
||||
if revision == LEGACY_REVISION {
|
||||
json!({"protocolVersion":LEGACY_REVISION,"capabilities":capabilities(),"serverInfo":server})
|
||||
} else {
|
||||
json!({"resultType":"complete","supportedVersions":["2026-07-28","2025-11-25"],
|
||||
"capabilities":capabilities(),"_meta":{"io.modelcontextprotocol/serverInfo":server},
|
||||
"ttlMs":0,"cacheScope":"private"})
|
||||
}
|
||||
}
|
||||
|
||||
async fn wire(response: reqwest::Response, revision: &str, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert_eq!(response.headers()["x-request-id"], "negotiation-request");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"].to_str().unwrap();
|
||||
assert!(content_type.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
}));
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
frames.len(),
|
||||
1,
|
||||
"one terminal, no unsolicited notifications: {raw}"
|
||||
);
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({"jsonrpc":"2.0","id":id,"result":expected_result(revision)}),
|
||||
"exact result/envelope fields and omissions (including title/icons/instructions/defaults)"
|
||||
);
|
||||
body
|
||||
}
|
||||
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
crank_test_support::postgres_schema_url_for_task("negotiation_owner", "t_99aa603c").await;
|
||||
let h = Endpoint::started().await;
|
||||
let mut deltas = vec![];
|
||||
// Accept order selects JSON or a single terminal SSE frame on the real transport.
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
let id = json!("negotiation/Ю");
|
||||
let payload = if revision == LEGACY_REVISION {
|
||||
let mut initialize = legacy_initialize(1);
|
||||
initialize["id"] = id.clone();
|
||||
initialize
|
||||
} else {
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"server/discover","params":{"_meta":modern_meta()}})
|
||||
};
|
||||
let before = sdk_counts(&h.counters);
|
||||
let admission_before = h.counters.snapshot();
|
||||
let response = h
|
||||
.request(revision, None, &h.key, accept, payload)
|
||||
.header("x-request-id", "negotiation-request")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let session = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.map(|v| v.to_str().unwrap().to_owned());
|
||||
if revision == LEGACY_REVISION {
|
||||
assert!(
|
||||
!session
|
||||
.as_deref()
|
||||
.expect("initialize creates a session")
|
||||
.is_empty()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
session, None,
|
||||
"stateless discovery never creates a session carrier"
|
||||
);
|
||||
}
|
||||
wire(
|
||||
response,
|
||||
revision,
|
||||
&id,
|
||||
accept.starts_with("text/event-stream"),
|
||||
)
|
||||
.await;
|
||||
assert_deltas(
|
||||
"negotiation admission positive control",
|
||||
admission_before,
|
||||
h.counters.snapshot(),
|
||||
if revision == LEGACY_REVISION {
|
||||
super::Snapshot::new(1, 0, 1, 0)
|
||||
} else {
|
||||
super::Snapshot::new(1, 1, 0, 0)
|
||||
},
|
||||
);
|
||||
let after = sdk_counts(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
if let Some(session) = session {
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
accept,
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
// Prove the minted session can authorize the next protected request.
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"ping"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(
|
||||
json_body(response).await,
|
||||
json!({"jsonrpc":"2.0","id":2,"result":{"protocolVersion":LEGACY_REVISION}})
|
||||
);
|
||||
}
|
||||
}
|
||||
eprintln!("existing GREEN lifecycle negotiation wire {revision}; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_sdk_legacy() {
|
||||
assert_eq!(
|
||||
control(LEGACY_REVISION).await,
|
||||
vec![[1, 0]; 2],
|
||||
"real HTTP initialize must serialize SDK InitializeResult (not admission/envelope only)"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_sdk_modern() {
|
||||
assert_eq!(
|
||||
control(MODERN_REVISION).await,
|
||||
vec![[0, 1]; 2],
|
||||
"real HTTP discovery must serialize SDK DiscoverResult (not admission/envelope only)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
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();
|
||||
assert_eq!(
|
||||
sdk_counts(&c),
|
||||
[1, 0],
|
||||
"initialize and discovery are separate markers"
|
||||
);
|
||||
super::sdk_discover_result_serialized();
|
||||
})
|
||||
.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();
|
||||
assert_eq!(sdk_counts(&c), [1, 1], "out-of-scope markers are no-ops");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_session_operations() {
|
||||
crank_test_support::postgres_schema_url_for_task("negotiation_sessions_owner", "t_99aa603c")
|
||||
.await;
|
||||
let h = Harness::started().await;
|
||||
// Existing counted-session fixture supplies independent get/create/initialized oracles.
|
||||
run_valid_legacy_initialize(&h, 10, "legacy create exactly once").await;
|
||||
let session = h.initialize_legacy_session().await;
|
||||
run_valid_legacy_call(
|
||||
&h,
|
||||
&session,
|
||||
11,
|
||||
"negotiation@example.test",
|
||||
"initialized session works",
|
||||
)
|
||||
.await;
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
let before = h.session_ops();
|
||||
let admission_before = h.snapshot();
|
||||
let response = h
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
("Accept", accept),
|
||||
("x-request-id", "negotiation-request"),
|
||||
(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
),
|
||||
],
|
||||
&json!({"jsonrpc":"2.0","id":"discovery","method":"server/discover",
|
||||
"params":{"_meta":modern_meta()}}),
|
||||
)
|
||||
.await;
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
wire(response, MODERN_REVISION, &json!("discovery"), false).await;
|
||||
assert_deltas(
|
||||
"modern discovery",
|
||||
admission_before,
|
||||
h.snapshot(),
|
||||
super::Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
"stateless discovery",
|
||||
before,
|
||||
h.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! #107 ping: existing wire GREEN is independent from the SDK execution oracle.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("ping_owner", "t_83746dc7").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
fn ping(revision: &str, extended: bool) -> Value {
|
||||
let mut payload = json!({"jsonrpc":"2.0","id":"ping/Ю","method":"ping"});
|
||||
if revision == MODERN_REVISION || extended {
|
||||
payload["params"] = json!({"_meta":if revision == MODERN_REVISION {
|
||||
modern_meta()
|
||||
} else { json!({}) }});
|
||||
}
|
||||
if extended {
|
||||
payload["params"]["ignored"] = json!([null, {"future":true}]);
|
||||
payload["params"]["_meta"]["future"] = json!(42);
|
||||
payload["extension"] = json!({"nested":[false]});
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
async fn wire_body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "ping-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
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, "one terminal frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn correlated(request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||
request.header("x-request-id", "ping-atdd").header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
}
|
||||
|
||||
async fn success_control(revision: &str) -> Vec<(usize, usize)> {
|
||||
let h = endpoint().await;
|
||||
// The existing fixture performs real initialize -> initialized for legacy only.
|
||||
let session = h.session(revision).await;
|
||||
let mut sdk = vec![];
|
||||
for (accept, extended) in [
|
||||
("application/json", false),
|
||||
("text/event-stream, application/json", true),
|
||||
] {
|
||||
let counters = h.counters.snapshot();
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = (h.counters.sdk_ping_request(), h.counters.sdk_ping_result());
|
||||
let response = correlated(h.request(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
&h.key,
|
||||
accept,
|
||||
ping(revision, extended),
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = wire_body(response, accept.starts_with("text/event-stream")).await;
|
||||
let result = if revision == MODERN_REVISION {
|
||||
json!({"protocolVersion":revision,"resultType":"complete"})
|
||||
} else {
|
||||
json!({"protocolVersion":revision})
|
||||
};
|
||||
assert_eq!(wire, json!({"jsonrpc":"2.0","id":"ping/Ю","result":result}));
|
||||
assert_deltas(
|
||||
"ping",
|
||||
counters,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(
|
||||
1,
|
||||
usize::from(revision == MODERN_REVISION),
|
||||
usize::from(revision == LEGACY_REVISION),
|
||||
0,
|
||||
),
|
||||
);
|
||||
assert_session_ops(
|
||||
"ping",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 2 * usize::from(revision == LEGACY_REVISION),
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
sdk.push((
|
||||
h.counters.sdk_ping_request() - before.0,
|
||||
h.counters.sdk_ping_result() - before.1,
|
||||
));
|
||||
eprintln!(
|
||||
"existing GREEN ping revision={revision} accept={accept} extended={extended}; SDK delta={:?}",
|
||||
sdk.last().unwrap()
|
||||
);
|
||||
}
|
||||
sdk
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_wire_json_sse_tolerance_and_session_contract() {
|
||||
success_control(LEGACY_REVISION).await;
|
||||
success_control(MODERN_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_sdk_legacy_request_and_result() {
|
||||
assert_eq!(
|
||||
success_control(LEGACY_REVISION).await,
|
||||
vec![(1, 1); 2],
|
||||
"successful legacy HTTP ping must consume SDK request and serialize SDK result"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_sdk_modern_request_and_result() {
|
||||
assert_eq!(
|
||||
success_control(MODERN_REVISION).await,
|
||||
vec![(1, 1); 2],
|
||||
"successful stateless HTTP ping must consume SDK request and serialize SDK result"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_guards_never_enter_sdk() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let mut payload = ping(revision, true);
|
||||
if revision == MODERN_REVISION {
|
||||
payload["params"]["_meta"] = Value::Null;
|
||||
}
|
||||
let response = correlated(h.request(revision, None, &h.key, "application/json", payload))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
if revision == LEGACY_REVISION {
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
} else {
|
||||
let wire = wire_body(response, false).await;
|
||||
assert_eq!(wire["id"], "ping/Ю");
|
||||
assert_eq!(wire["error"]["code"], -32020);
|
||||
assert!(wire.get("result").is_none());
|
||||
}
|
||||
assert_eq!(
|
||||
(h.counters.sdk_ping_request(), h.counters.sdk_ping_result()),
|
||||
(0, 0)
|
||||
);
|
||||
eprintln!("existing GREEN pre-seam guard revision={revision}; SDK=(0,0)");
|
||||
}
|
||||
}
|
||||
|
||||
#[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));
|
||||
})
|
||||
.await;
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
observe(Arc::new(CounterSet::default()), async {
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(c.sdk_ping_request(), c.sdk_ping_result()),
|
||||
(1, 1),
|
||||
"scope isolation and out-of-scope no-op"
|
||||
);
|
||||
assert_eq!(c.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -6,9 +6,10 @@ use crank_runtime::{
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub(in crate::app::dispatch_observer) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub sessions: Arc<CountedSessionStore>,
|
||||
pub key: String,
|
||||
pub other_key: String,
|
||||
pub gate: Arc<Semaphore>,
|
||||
@@ -25,6 +26,9 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
Self::started_with_store(None).await
|
||||
}
|
||||
pub async fn started_with_store(store: Option<crate::session::SharedSessionStore>) -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("progress_owner", "t_d65dd129").await;
|
||||
let registry = test_registry().await;
|
||||
let gate = Arc::new(Semaphore::new(0));
|
||||
@@ -90,6 +94,7 @@ impl Endpoint {
|
||||
.await
|
||||
.unwrap();
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let sessions = Arc::new(CountedSessionStore::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
@@ -101,7 +106,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
store.unwrap_or_else(|| sessions.clone()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
@@ -125,6 +130,7 @@ impl Endpoint {
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
sessions,
|
||||
key,
|
||||
other_key,
|
||||
gate,
|
||||
|
||||
@@ -5,7 +5,7 @@ use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_progress_cancel_http_support.rs"]
|
||||
mod fixtures;
|
||||
pub(super) mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Handler completion/consumption is independent of the existing DTO wire oracle.
|
||||
use super::{CounterSet, observe, rmcp_prompts_runtime_tests::control, support::*};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn counts(c: &CounterSet) -> [usize; 4] {
|
||||
[
|
||||
c.sdk_prompts_list_handler_completed(),
|
||||
c.sdk_prompts_get_handler_completed(),
|
||||
c.sdk_prompts_list_handler_consumed(),
|
||||
c.sdk_prompts_get_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn delta(c: &CounterSet, before: [usize; 4], method: &str) -> ([usize; 4], [usize; 4]) {
|
||||
let after = counts(c);
|
||||
let expected = match method {
|
||||
"prompts/list" => [1, 0, 1, 0],
|
||||
"prompts/get" => [0, 1, 0, 1],
|
||||
_ => panic!("not a Prompts method: {method}"),
|
||||
};
|
||||
(std::array::from_fn(|i| after[i] - before[i]), expected)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_handler_legacy() {
|
||||
control(LEGACY_REVISION, true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_handler_modern() {
|
||||
control(MODERN_REVISION, true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_handler_observer_positive_control() {
|
||||
use super::{
|
||||
sdk_prompts_get_handler_completed, sdk_prompts_get_handler_consumed,
|
||||
sdk_prompts_list_handler_completed, sdk_prompts_list_handler_consumed,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_prompts_list_handler_completed();
|
||||
sdk_prompts_get_handler_completed();
|
||||
sdk_prompts_list_handler_consumed();
|
||||
sdk_prompts_get_handler_consumed();
|
||||
assert_eq!(counts(&a), [0; 4], "no-scope markers must be no-ops");
|
||||
let snapshot = a.snapshot();
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_prompts_list_handler_completed();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_prompts_get_handler_completed();
|
||||
sdk_prompts_list_handler_consumed();
|
||||
sdk_prompts_get_handler_consumed();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_prompts_get_handler_completed();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_prompts_get_handler_consumed();
|
||||
}),
|
||||
);
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
assert_eq!(counts(&b), [0, 1, 0, 1]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
assert_eq!(b.snapshot(), CounterSet::default().snapshot());
|
||||
for c in [&a, &b] {
|
||||
assert_eq!(c.sdk_prompts_dispatch(), 0);
|
||||
assert_eq!(c.sdk_prompts_list_result(), 0);
|
||||
assert_eq!(c.sdk_prompts_get_result(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Synthetic replies exercise real trait results, restoration and structured cancellation.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Domain {
|
||||
outcome: Mutex<Option<PromptsOutcome>>,
|
||||
calls: AtomicUsize,
|
||||
pending: bool,
|
||||
started: tokio::sync::Notify,
|
||||
release: tokio::sync::Notify,
|
||||
dropped: AtomicBool,
|
||||
finished: AtomicBool,
|
||||
}
|
||||
struct DropWitness<'a>(&'a AtomicBool);
|
||||
impl Drop for DropWitness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Domain {
|
||||
pub(super) async fn prompts(&self, command: PromptsCommand) -> PromptsOutcome {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
match command {
|
||||
PromptsCommand::List(list) => {
|
||||
assert_eq!(list.limit, Some(7));
|
||||
assert_eq!(list.cursor.as_deref(), Some("opaque"));
|
||||
}
|
||||
PromptsCommand::Get(get) => {
|
||||
assert_eq!(get.name, "bound-prompt");
|
||||
assert_eq!(
|
||||
get.arguments,
|
||||
Some(
|
||||
json!({"number":42,"enabled":true,"nested":[null]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
let _guard = DropWitness(&self.dropped);
|
||||
if self.pending {
|
||||
self.started.notify_one();
|
||||
self.release.notified().await;
|
||||
}
|
||||
self.finished.store(true, SeqCst);
|
||||
self.outcome
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("exactly one domain execution")
|
||||
}
|
||||
}
|
||||
fn scope(revision: &str) -> PromptScope {
|
||||
PromptScope {
|
||||
workspace_slug: "fresh-workspace".into(),
|
||||
agent_slug: "fresh-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("fresh-key".into()),
|
||||
},
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: ContinuationSupport::from_supported(false),
|
||||
locale: ExecutionLocale::En,
|
||||
revision: revision.into(),
|
||||
limit: Some(7),
|
||||
}
|
||||
}
|
||||
async fn state() -> Arc<AppState> {
|
||||
crank_test_support::postgres_schema_url_for_task("prompts_handler_local", "t_2d797361").await;
|
||||
super::super::rmcp_tools_tests::test_state().await
|
||||
}
|
||||
fn handler(state: &Arc<AppState>, outcome: PromptsOutcome) -> PromptHandler {
|
||||
let mut handler = PromptHandler::new(state);
|
||||
handler.domain = Some(Arc::new(Domain {
|
||||
outcome: Mutex::new(Some(outcome)),
|
||||
..Default::default()
|
||||
}));
|
||||
handler
|
||||
}
|
||||
fn page() -> Option<PaginatedRequestParams> {
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("opaque".into())))
|
||||
}
|
||||
fn get() -> GetPromptRequestParams {
|
||||
let mut request = GetPromptRequestParams::new("bound-prompt");
|
||||
request.arguments = Some(
|
||||
json!({"number":42,"enabled":true,"nested":[null]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
request
|
||||
}
|
||||
async fn context(handler: &PromptHandler, revision: &str) -> RequestContext<RoleServer> {
|
||||
let context = request_context(handler, scope(revision)).await.unwrap();
|
||||
assert!(context.peer.is_transport_closed());
|
||||
assert_eq!(
|
||||
Arc::strong_count(&handler.reply),
|
||||
1,
|
||||
"seed service released handler"
|
||||
);
|
||||
assert_eq!(handler.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
||||
let actual = PromptHandler::scope(&context).unwrap();
|
||||
assert_eq!(actual.workspace_slug, "fresh-workspace");
|
||||
assert_eq!(actual.agent_slug, "fresh-agent");
|
||||
assert_eq!(
|
||||
actual
|
||||
.credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str()),
|
||||
Some("fresh-key")
|
||||
);
|
||||
assert_eq!(actual.revision, revision);
|
||||
context
|
||||
}
|
||||
fn assert_list(outcome: PromptsOutcome, raw: Vec<Value>, cursor: Option<&str>) {
|
||||
match outcome {
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} => {
|
||||
assert_eq!(prompts, raw);
|
||||
assert_eq!(next_cursor.as_deref(), cursor);
|
||||
}
|
||||
_ => panic!("list restore failed"),
|
||||
}
|
||||
}
|
||||
fn assert_get(outcome: PromptsOutcome, raw: Vec<Value>, expected: Option<&str>) {
|
||||
match outcome {
|
||||
PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} => {
|
||||
assert_eq!(messages, raw);
|
||||
assert_eq!(description.as_deref(), expected);
|
||||
}
|
||||
_ => panic!("get restore failed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_trait_lossless_and_actual_typed_mutations_consumed() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let raw = vec![
|
||||
json!({"name":"a","description":null,"icons":{"not":"SDK array"},"annotations":false,"x":[null,{"nested":true}],"arguments":[{"name":"n","required":null,"description":null,"type":"integer","default":42,"enum":[1,42],"x":null}]}),
|
||||
json!({"name":"b","arguments":null}),
|
||||
json!({"name":"c"}),
|
||||
];
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Listed {
|
||||
prompts: raw.clone(),
|
||||
next_cursor: Some("next".into()),
|
||||
},
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let mut result = ServerHandler::list_prompts(&h, page(), c).await.unwrap();
|
||||
result.prompts[0].title = Some("typed-title".into());
|
||||
result.prompts[0].arguments.as_mut().unwrap()[0].title = Some("typed-argument".into());
|
||||
result.next_cursor = Some("typed-cursor".into());
|
||||
let mut expected = raw;
|
||||
expected[0]["title"] = json!("typed-title");
|
||||
expected[0]["arguments"][0]["title"] = json!("typed-argument");
|
||||
assert_list(restore_list(&h, Ok(result)), expected, Some("typed-cursor"));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let text = serde_json::to_string_pretty(&json!({"exact":[null,true]})).unwrap();
|
||||
let raw = vec![
|
||||
json!({"role":"system","content":{"type":"text","text":text,"annotations":[null,42],"x":null},"x":{"nested":true}}),
|
||||
json!({"role":"user","content":{"type":"image","data":"AAEC/w==","mimeType":"image/png","annotations":false,"x":[1,null]}}),
|
||||
json!({"role":"assistant","content":{"type":"audio","data":"AAEC/w==","mimeType":"audio/wav"}}),
|
||||
json!({"role":"user","content":{"type":"resource","resource":{"uri":"crank://text","text":"exact\nbytes","mimeType":null,"x":[null]},"annotations":{"arbitrary":true}}}),
|
||||
json!({"role":"user","content":{"type":"resource","resource":{"uri":"crank://blob","blob":"AAEC/w==","x":false},"x":null}}),
|
||||
json!({"role":"user","content":{"type":"resource_link","uri":"crank://link","name":"link","description":null,"icons":false,"annotations":42,"x":{"a":null}}}),
|
||||
];
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Got {
|
||||
description: None,
|
||||
messages: raw.clone(),
|
||||
},
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let GetPromptResponse::Complete(mut result) =
|
||||
ServerHandler::get_prompt(&h, get(), c).await.unwrap()
|
||||
else {
|
||||
panic!("expected complete prompt")
|
||||
};
|
||||
result.description = Some("typed-description".into());
|
||||
// Content is mutated through the SDK result, not the original domain JSON.
|
||||
let mut message = serde_json::to_value(&result.messages[0]).unwrap();
|
||||
message["content"]["text"] = json!("typed-text");
|
||||
result.messages[0] = serde_json::from_value(message).unwrap();
|
||||
let mut expected = raw;
|
||||
expected[0]["content"]["text"] = json!("typed-text");
|
||||
assert_get(
|
||||
restore_get(&h, Ok(result.into())),
|
||||
expected,
|
||||
Some("typed-description"),
|
||||
);
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Got {
|
||||
description: None,
|
||||
messages: vec![],
|
||||
},
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let result = ServerHandler::get_prompt(&h, get(), c).await;
|
||||
assert_get(restore_get(&h, result), vec![], None);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_trait_errors_fail_closed_without_reexecution() {
|
||||
let state = state().await;
|
||||
for is_list in [true, false] {
|
||||
for outcome in [
|
||||
PromptsOutcome::InvalidParams("exact-detail".into()),
|
||||
PromptsOutcome::NotAvailable,
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: "wrong_type",
|
||||
argument: Some("number".into()),
|
||||
},
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: "missing",
|
||||
argument: None,
|
||||
},
|
||||
PromptsOutcome::DependencyUnavailable { position: 13 },
|
||||
PromptsOutcome::CatalogUnavailable,
|
||||
] {
|
||||
let expected = std::mem::discriminant(&outcome);
|
||||
let h = handler(&state, outcome);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let actual = if is_list {
|
||||
let result = ServerHandler::list_prompts(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
restore_list(&h, result)
|
||||
} else {
|
||||
let result = ServerHandler::get_prompt(&h, get(), c).await;
|
||||
assert!(result.is_err());
|
||||
restore_get(&h, result)
|
||||
};
|
||||
assert_eq!(std::mem::discriminant(&actual), expected);
|
||||
match actual {
|
||||
PromptsOutcome::InvalidParams(detail) => assert_eq!(detail, "exact-detail"),
|
||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||
assert_eq!(
|
||||
reason,
|
||||
if argument.is_some() {
|
||||
"wrong_type"
|
||||
} else {
|
||||
"missing"
|
||||
}
|
||||
);
|
||||
if let Some(argument) = argument {
|
||||
assert_eq!(argument, "number");
|
||||
}
|
||||
}
|
||||
PromptsOutcome::DependencyUnavailable { position } => assert_eq!(position, 13),
|
||||
_ => {}
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Listed {
|
||||
prompts: vec![json!({"description":"missing name"})],
|
||||
next_cursor: None,
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::list_prompts(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert!(matches!(
|
||||
restore_list(&h, result),
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
for message in [
|
||||
json!({"role":"invalid","content":{"type":"text","text":"x"}}),
|
||||
json!({"role":"user","content":{"type":"text"}}),
|
||||
] {
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Got {
|
||||
description: None,
|
||||
messages: vec![message],
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::get_prompt(&h, get(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert!(matches!(
|
||||
restore_get(&h, result),
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
for change in 0..3 {
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Listed {
|
||||
prompts: vec![json!({"name":"a","x":1}), json!({"name":"b","x":2})],
|
||||
next_cursor: None,
|
||||
},
|
||||
);
|
||||
let mut c = context(&h, "2026-07-28").await;
|
||||
c.extensions = Default::default();
|
||||
assert!(ServerHandler::list_prompts(&h, page(), c).await.is_err());
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let mut result = ServerHandler::list_prompts(&h, page(), c).await.unwrap();
|
||||
let result = match change {
|
||||
0 => {
|
||||
result.prompts.clear();
|
||||
Ok(result)
|
||||
}
|
||||
1 => {
|
||||
result.prompts.swap(0, 1);
|
||||
Ok(result)
|
||||
}
|
||||
_ => Err(internal()),
|
||||
};
|
||||
assert!(matches!(
|
||||
restore_list(&h, result),
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
let h = handler(
|
||||
&state,
|
||||
PromptsOutcome::Got {
|
||||
description: None,
|
||||
messages: vec![],
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::list_prompts(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert!(matches!(
|
||||
restore_list(&h, result),
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
));
|
||||
assert!(matches!(
|
||||
restore_get(&h, Err(internal())),
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_parent_drop_cancels_domain_and_bootstrap_is_closed() {
|
||||
let state = state().await;
|
||||
for is_list in [true, false] {
|
||||
let mut h = PromptHandler::new(&state);
|
||||
let domain = Arc::new(Domain {
|
||||
pending: true,
|
||||
..Default::default()
|
||||
});
|
||||
h.domain = Some(domain.clone());
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let mut parent = Box::pin(async {
|
||||
if is_list {
|
||||
let result = ServerHandler::list_prompts(&h, page(), c).await;
|
||||
restore_list(&h, result)
|
||||
} else {
|
||||
let result = ServerHandler::get_prompt(&h, get(), c).await;
|
||||
restore_get(&h, result)
|
||||
}
|
||||
});
|
||||
tokio::select! { _ = &mut parent => panic!("domain should wait"), _ = domain.started.notified() => {} }
|
||||
assert!(!domain.dropped.load(SeqCst));
|
||||
drop(parent);
|
||||
assert!(
|
||||
domain.dropped.load(SeqCst),
|
||||
"domain future dropped synchronously with parent"
|
||||
);
|
||||
domain.release.notify_one();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!domain.finished.load(SeqCst), "no detached continuation");
|
||||
assert!(h.take().is_none());
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
assert_eq!(Arc::strong_count(&domain), 2);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_prompts_test_support.rs"]
|
||||
mod fixtures;
|
||||
use super::rmcp_prompts_handler_runtime_tests as handler;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
@@ -111,11 +112,15 @@ async fn success(
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
pub(super) async fn control(
|
||||
revision: &str,
|
||||
require_handler: bool,
|
||||
) -> Vec<([usize; 3], [usize; 3])> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
let mut handlers = Vec::new();
|
||||
let mut first_cursor = None;
|
||||
// Both revisions' JSON contract, plus modern terminal SSE through the same normal app.
|
||||
let modes: &[bool] = if revision == MODERN_REVISION {
|
||||
@@ -130,7 +135,9 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let before = handler::counts(&h.counters);
|
||||
let (result, delta) = success(&h, revision, session, "prompts/list", params, sse).await;
|
||||
handlers.push(handler::delta(&h.counters, before, "prompts/list"));
|
||||
let prompts = result["prompts"].as_array().unwrap();
|
||||
assert_eq!(prompts.len(), 1, "{result}");
|
||||
assert_eq!(
|
||||
@@ -174,6 +181,7 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
] {
|
||||
let mut previous = None;
|
||||
for _ in 0..2 {
|
||||
let before = handler::counts(&h.counters);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
@@ -183,6 +191,7 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
||||
assert_eq!(result["description"], format!("Published {name}"));
|
||||
assert_eq!(
|
||||
result["messages"],
|
||||
@@ -232,7 +241,9 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
"prompts/get",
|
||||
json!({"name":"greeting","arguments":arguments}),
|
||||
);
|
||||
let before = handler::counts(&h.counters);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(body["error"]["data"]["reason"], reason, "{body}");
|
||||
assert_eq!(body["error"]["data"]["argument"], argument);
|
||||
@@ -255,7 +266,9 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
"prm_a",
|
||||
] {
|
||||
let req = request(revision, "prompts/get", json!({"name":name}));
|
||||
let before = handler::counts(&h.counters);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
@@ -269,7 +282,8 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
}
|
||||
}
|
||||
for params in [json!({"cursor":"invalid"}), json!({"limit":"invalid"})] {
|
||||
let req = request(revision, "prompts/list", params);
|
||||
let before = handler::counts(&h.counters);
|
||||
let req = request(revision, "prompts/list", params.clone());
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
@@ -277,6 +291,15 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
if params.get("cursor").is_some() {
|
||||
handlers.push(handler::delta(&h.counters, before, "prompts/list"));
|
||||
} else {
|
||||
assert_eq!(
|
||||
handler::counts(&h.counters),
|
||||
before,
|
||||
"parsing rejects must not enter handlers"
|
||||
);
|
||||
}
|
||||
}
|
||||
let other = if revision == MODERN_REVISION {
|
||||
LEGACY_REVISION
|
||||
@@ -345,6 +368,27 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
),
|
||||
"{binding:?}"
|
||||
);
|
||||
sqlx::query(
|
||||
"update platform_api_keys set scopes_json = '[]'::jsonb where id = 'pk_dispatch_observer'",
|
||||
)
|
||||
.execute(h.registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
for (method, params) in [
|
||||
("prompts/list", json!({})),
|
||||
("prompts/get", json!({"name":"greeting"})),
|
||||
] {
|
||||
let before = handler::counts(&h.counters);
|
||||
let req = request(revision, method, params);
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 403);
|
||||
assert_eq!(
|
||||
handler::counts(&h.counters),
|
||||
before,
|
||||
"scope rejects must precede handlers"
|
||||
);
|
||||
}
|
||||
sqlx::query("update platform_api_keys set scopes_json = '[\"read\",\"write\"]'::jsonb where id = 'pk_dispatch_observer'")
|
||||
.execute(h.registry.pool()).await.unwrap();
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
@@ -360,29 +404,41 @@ async fn control(revision: &str) -> Vec<([usize; 3], [usize; 3])> {
|
||||
json!({"name":"greeting","arguments":{"name":"Ada"}}),
|
||||
),
|
||||
] {
|
||||
let before = handler::counts(&h.counters);
|
||||
assert_eq!(
|
||||
h.post(revision, session, &request(revision, method, params), false)
|
||||
.await
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
assert_eq!(
|
||||
handler::counts(&h.counters),
|
||||
before,
|
||||
"revocation must precede handlers"
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Prompts wire {revision}: populated pagination, typed metadata/values, exact immutable rendering, archive, structured refusals/non-disclosure, correlation/ID/cache, revoked401; SDK actual/expected={deltas:?}"
|
||||
);
|
||||
if require_handler {
|
||||
assert!(
|
||||
handlers.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK Prompts handler completion/consumption missing after successful HTTP wire/error/guard checks: {handlers:?}"
|
||||
);
|
||||
}
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
control(LEGACY_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
control(MODERN_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
let deltas = control(LEGACY_REVISION, false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
@@ -390,7 +446,7 @@ async fn rmcp_prompts_sdk_legacy() {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
let deltas = control(MODERN_REVISION, false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
|
||||
@@ -39,7 +39,7 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("prompts_owner", "t_160a763a").await;
|
||||
crank_test_support::postgres_schema_url_for_task("prompts_handler", "t_7afaaafe").await;
|
||||
let registry = test_registry().await;
|
||||
let mut archived_at = test_time();
|
||||
for (id, name, publish) in [
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Actual handler completion and Result consumption, separate from DTO serialization.
|
||||
use super::{CounterSet, observe, rmcp_resources_runtime_tests::control, support::*};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) async fn foreign_agent(registry: &crank_registry::PostgresRegistry) -> &'static str {
|
||||
use crank_core::{Agent, AgentId, AgentStatus, AgentVersion, ToolSelectionPolicy};
|
||||
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
|
||||
let id = AgentId::new("agent_resources_foreign");
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: "resources-foreign".to_owned(),
|
||||
display_name: "Other published Agent".to_owned(),
|
||||
description: String::new(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: serde_json::json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
"resources-foreign"
|
||||
}
|
||||
|
||||
pub(super) fn counts(c: &CounterSet) -> [usize; 6] {
|
||||
[
|
||||
c.sdk_resources_list_handler_completed(),
|
||||
c.sdk_resources_read_handler_completed(),
|
||||
c.sdk_resources_templates_handler_completed(),
|
||||
c.sdk_resources_list_handler_consumed(),
|
||||
c.sdk_resources_read_handler_consumed(),
|
||||
c.sdk_resources_templates_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn delta(c: &CounterSet, before: [usize; 6], method: &str) -> ([usize; 6], [usize; 6]) {
|
||||
let after = counts(c);
|
||||
let expected = match method {
|
||||
"resources/list" => [1, 0, 0, 1, 0, 0],
|
||||
"resources/read" => [0, 1, 0, 0, 1, 0],
|
||||
"resources/templates/list" => [0, 0, 1, 0, 0, 1],
|
||||
_ => panic!("not a Resources family: {method}"),
|
||||
};
|
||||
(std::array::from_fn(|i| after[i] - before[i]), expected)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_handler_legacy() {
|
||||
control(LEGACY_REVISION, true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_handler_modern() {
|
||||
control(MODERN_REVISION, true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_handler_observer_positive_control() {
|
||||
use super::{
|
||||
sdk_resources_list_handler_completed, sdk_resources_list_handler_consumed,
|
||||
sdk_resources_read_handler_completed, sdk_resources_read_handler_consumed,
|
||||
sdk_resources_templates_handler_completed, sdk_resources_templates_handler_consumed,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_resources_list_handler_completed();
|
||||
sdk_resources_read_handler_completed();
|
||||
sdk_resources_templates_handler_completed();
|
||||
sdk_resources_list_handler_consumed();
|
||||
sdk_resources_read_handler_consumed();
|
||||
sdk_resources_templates_handler_consumed();
|
||||
assert_eq!(counts(&a), [0; 6], "no-scope markers must be no-ops");
|
||||
let snapshot = a.snapshot();
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_resources_list_handler_completed();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_resources_read_handler_completed();
|
||||
sdk_resources_templates_handler_completed();
|
||||
sdk_resources_list_handler_consumed();
|
||||
sdk_resources_read_handler_consumed();
|
||||
sdk_resources_templates_handler_consumed();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_resources_read_handler_completed();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_resources_read_handler_consumed();
|
||||
}),
|
||||
);
|
||||
assert_eq!(counts(&a), [1; 6]);
|
||||
assert_eq!(counts(&b), [0, 1, 0, 0, 1, 0]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
assert_eq!(b.snapshot(), CounterSet::default().snapshot());
|
||||
for c in [&a, &b] {
|
||||
assert_eq!(c.sdk_resources_dispatch(), 0);
|
||||
assert_eq!(c.sdk_resources_list_result(), 0);
|
||||
assert_eq!(c.sdk_resources_read_result(), 0);
|
||||
assert_eq!(c.sdk_resource_templates_list_result(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Synthetic domain replies exercise the real trait/restore path, not wire producer coverage.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
type TemplateReply = Result<(Vec<Value>, Option<String>), ResourceTemplatesListError>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Domain {
|
||||
outcome: Mutex<Option<ResourcesOutcome>>,
|
||||
templates: Mutex<Option<TemplateReply>>,
|
||||
calls: AtomicUsize,
|
||||
pending: bool,
|
||||
started: tokio::sync::Notify,
|
||||
release: tokio::sync::Notify,
|
||||
dropped: AtomicBool,
|
||||
finished: AtomicBool,
|
||||
}
|
||||
struct DropWitness<'a>(&'a AtomicBool);
|
||||
impl Drop for DropWitness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Domain {
|
||||
pub(super) async fn resources(&self, command: ResourcesCommand) -> ResourcesOutcome {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
match command {
|
||||
ResourcesCommand::List(list) => {
|
||||
assert_eq!(list.limit, Some(7));
|
||||
assert_eq!(list.cursor.as_deref(), Some("opaque"));
|
||||
}
|
||||
ResourcesCommand::Read(read) => assert_eq!(read.uri, "crank://read"),
|
||||
}
|
||||
let _guard = DropWitness(&self.dropped);
|
||||
if self.pending {
|
||||
self.started.notify_one();
|
||||
self.release.notified().await;
|
||||
}
|
||||
self.finished.store(true, SeqCst);
|
||||
self.outcome
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("exactly one domain execution")
|
||||
}
|
||||
pub(super) async fn templates(
|
||||
&self,
|
||||
command: ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
self.calls.fetch_add(1, SeqCst);
|
||||
assert_eq!(command.limit, Some(7));
|
||||
assert_eq!(command.cursor.as_deref(), Some("opaque"));
|
||||
self.templates
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("exactly one template execution")
|
||||
}
|
||||
}
|
||||
fn scope(revision: &str) -> ResourceScope {
|
||||
ResourceScope {
|
||||
workspace_slug: "fresh-workspace".into(),
|
||||
agent_slug: "fresh-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("fresh-key".into()),
|
||||
},
|
||||
correlation: CorrelationContext::generate(),
|
||||
continuation: ContinuationSupport::from_supported(false),
|
||||
locale: ExecutionLocale::En,
|
||||
revision: revision.into(),
|
||||
limit: Some(7),
|
||||
}
|
||||
}
|
||||
async fn state() -> Arc<AppState> {
|
||||
crank_test_support::postgres_schema_url_for_task("resources_handler_local", "t_b2b08b44").await;
|
||||
super::super::rmcp_tools_tests::test_state().await
|
||||
}
|
||||
fn handler(state: &Arc<AppState>, outcome: ResourcesOutcome) -> ResourceHandler {
|
||||
let mut handler = ResourceHandler::new(state);
|
||||
handler.domain = Some(Arc::new(Domain {
|
||||
outcome: Mutex::new(Some(outcome)),
|
||||
..Default::default()
|
||||
}));
|
||||
handler
|
||||
}
|
||||
fn page() -> Option<PaginatedRequestParams> {
|
||||
Some(PaginatedRequestParams::default().with_cursor(Some("opaque".into())))
|
||||
}
|
||||
async fn context(handler: &ResourceHandler, revision: &str) -> RequestContext<RoleServer> {
|
||||
let context = request_context(handler, scope(revision)).await.unwrap();
|
||||
// Closed Peer and released seed handler ownership independently witness bootstrap cleanup.
|
||||
assert!(context.peer.is_transport_closed());
|
||||
assert_eq!(Arc::strong_count(&handler.reply), 1);
|
||||
assert_eq!(handler.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
||||
assert_eq!(
|
||||
ResourceHandler::scope(&context)
|
||||
.unwrap()
|
||||
.credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str()),
|
||||
Some("fresh-key")
|
||||
);
|
||||
context
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_trait_lossless_populated_results() {
|
||||
let state = state().await;
|
||||
for revision in ["2025-11-25", "2026-07-28"] {
|
||||
let raw = vec![
|
||||
json!({"uri":"crank://a", "name":"a", "description":null, "annotations":{"arbitrary":[null,{"nested":true}]}, "icons":{"not":"an SDK icon array"}, "x": [1,null]}),
|
||||
json!({"uri":"crank://b","name":"b"}),
|
||||
];
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Listed {
|
||||
resources: raw.clone(),
|
||||
next_cursor: Some("next".into()),
|
||||
},
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
||||
// Mutating a known field demonstrates the actual typed result is consumed, not old success.
|
||||
result.resources[0].title = Some("from-sdk-result".into());
|
||||
result.next_cursor = Some("typed-cursor".into());
|
||||
match restore_list(&h, Ok(result)) {
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
} => {
|
||||
let mut expected = raw;
|
||||
expected[0]["title"] = json!("from-sdk-result");
|
||||
assert_eq!(resources, expected);
|
||||
assert_eq!(next_cursor.as_deref(), Some("typed-cursor"));
|
||||
}
|
||||
_ => panic!("list restore failed"),
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let text = serde_json::to_string_pretty(&json!({"exact":true})).unwrap();
|
||||
let raw = json!([{"uri":"crank://text", "text":text, "mimeType":null, "annotations": [null,42], "x":null}, {"uri":"crank://blob", "blob":"AAEC/w==", "icons":false}]);
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Read {
|
||||
contents: raw.clone(),
|
||||
},
|
||||
);
|
||||
let c = context(&h, revision).await;
|
||||
let result =
|
||||
ServerHandler::read_resource(&h, ReadResourceRequestParams::new("crank://read"), c)
|
||||
.await;
|
||||
match restore_read(&h, result) {
|
||||
ResourcesOutcome::Read { contents } => assert_eq!(contents, raw),
|
||||
_ => panic!("read restore failed"),
|
||||
}
|
||||
let raw = vec![
|
||||
json!({"uriTemplate":"crank://{id}", "name":"template", "parameters":{"id":{"type":"string","default":null}}, "annotations":false, "icons":[{"unknown":null}], "description":null, "x":{"nested":[null]}}),
|
||||
];
|
||||
let mut h = ResourceHandler::new(&state);
|
||||
h.domain = Some(Arc::new(Domain {
|
||||
templates: Mutex::new(Some(Ok((raw.clone(), Some("next".into()))))),
|
||||
..Default::default()
|
||||
}));
|
||||
let c = context(&h, revision).await;
|
||||
let result = ServerHandler::list_resource_templates(&h, page(), c).await;
|
||||
let (actual, cursor) = restore_templates(&h, result).ok().unwrap();
|
||||
assert_eq!(actual, raw);
|
||||
assert_eq!(cursor.as_deref(), Some("next"));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_trait_errors_and_broken_projection_fail_closed() {
|
||||
let state = state().await;
|
||||
let contract = crate::tool_error::control_tool_error_contract(
|
||||
crate::tool_error::McpControlError::CatalogRevisionChanged,
|
||||
"request",
|
||||
"trace",
|
||||
ExecutionLocale::En,
|
||||
);
|
||||
for outcome in [
|
||||
ResourcesOutcome::InvalidParams("exact detail".into()),
|
||||
ResourcesOutcome::NotAvailable,
|
||||
ResourcesOutcome::CatalogUnavailable,
|
||||
ResourcesOutcome::ArtifactUnavailable,
|
||||
ResourcesOutcome::ExecutionError(contract.clone()),
|
||||
] {
|
||||
let expected = std::mem::discriminant(&outcome);
|
||||
let h = handler(&state, outcome);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result =
|
||||
ServerHandler::read_resource(&h, ReadResourceRequestParams::new("crank://read"), c)
|
||||
.await;
|
||||
assert!(result.is_err());
|
||||
let actual = restore_read(&h, result);
|
||||
assert_eq!(std::mem::discriminant(&actual), expected);
|
||||
match actual {
|
||||
ResourcesOutcome::ExecutionError(actual) => assert_eq!(actual, contract),
|
||||
ResourcesOutcome::InvalidParams(detail) => assert_eq!(detail, "exact detail"),
|
||||
_ => {}
|
||||
}
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
}
|
||||
for error in [
|
||||
ResourceTemplatesListError::InvalidCursor,
|
||||
ResourceTemplatesListError::Unavailable,
|
||||
] {
|
||||
let expected = std::mem::discriminant(&error);
|
||||
let mut h = ResourceHandler::new(&state);
|
||||
h.domain = Some(Arc::new(Domain {
|
||||
templates: Mutex::new(Some(Err(error))),
|
||||
..Default::default()
|
||||
}));
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::list_resource_templates(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(
|
||||
std::mem::discriminant(&restore_templates(&h, result).err().unwrap()),
|
||||
expected
|
||||
);
|
||||
}
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Listed {
|
||||
resources: vec![json!({"name":"missing-required-uri"})],
|
||||
next_cursor: None,
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::list_resources(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert!(matches!(
|
||||
restore_list(&h, result),
|
||||
ResourcesOutcome::CatalogUnavailable
|
||||
));
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Listed {
|
||||
resources: vec![json!({"uri":"crank://a","name":"a"})],
|
||||
next_cursor: None,
|
||||
},
|
||||
);
|
||||
let mut c = context(&h, "2026-07-28").await;
|
||||
c.extensions = Default::default();
|
||||
assert!(ServerHandler::list_resources(&h, page(), c).await.is_err());
|
||||
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
||||
result.resources.clear();
|
||||
assert!(matches!(
|
||||
restore_list(&h, Ok(result)),
|
||||
ResourcesOutcome::CatalogUnavailable
|
||||
));
|
||||
// An impossible domain variant or unpaired SDK Err cannot become a saved success.
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Read {
|
||||
contents: json!([]),
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let result = ServerHandler::list_resources(&h, page(), c).await;
|
||||
assert!(result.is_err());
|
||||
assert!(matches!(
|
||||
restore_list(&h, result),
|
||||
ResourcesOutcome::CatalogUnavailable
|
||||
));
|
||||
assert!(matches!(
|
||||
restore_read(&h, Err(internal())),
|
||||
ResourcesOutcome::ArtifactUnavailable
|
||||
));
|
||||
let h = handler(
|
||||
&state,
|
||||
ResourcesOutcome::Listed {
|
||||
resources: vec![
|
||||
json!({"uri":"crank://a","name":"a","x":1}),
|
||||
json!({"uri":"crank://b","name":"b","x":2}),
|
||||
],
|
||||
next_cursor: None,
|
||||
},
|
||||
);
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
||||
result.resources.swap(0, 1);
|
||||
assert!(matches!(
|
||||
restore_list(&h, Ok(result)),
|
||||
ResourcesOutcome::CatalogUnavailable
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_parent_drop_releases_domain_future_without_detached_execution() {
|
||||
let state = state().await;
|
||||
let mut h = ResourceHandler::new(&state);
|
||||
let domain = Arc::new(Domain {
|
||||
pending: true,
|
||||
..Default::default()
|
||||
});
|
||||
h.domain = Some(domain.clone());
|
||||
let c = context(&h, "2026-07-28").await;
|
||||
let mut parent = Box::pin(ServerHandler::read_resource(
|
||||
&h,
|
||||
ReadResourceRequestParams::new("crank://read"),
|
||||
c,
|
||||
));
|
||||
tokio::select! { _ = &mut parent => panic!("domain should be waiting"), _ = domain.started.notified() => {} }
|
||||
assert!(!domain.dropped.load(SeqCst));
|
||||
drop(parent);
|
||||
assert!(
|
||||
domain.dropped.load(SeqCst),
|
||||
"owned domain future must be dropped synchronously"
|
||||
);
|
||||
domain.release.notify_one();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(
|
||||
!domain.finished.load(SeqCst),
|
||||
"no detached future may resume execution"
|
||||
);
|
||||
assert!(h.take().is_none());
|
||||
assert_eq!(domain.calls.load(SeqCst), 1);
|
||||
assert_eq!(Arc::strong_count(&domain), 2);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! #107 Resources: existing wire GREEN is independent of the missing SDK typed-path oracle.
|
||||
//! #107 Resources: wire GREEN is independent of actual ServerHandler execution.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
@@ -8,6 +8,8 @@ use std::{sync::Arc, time::Duration};
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, TEXT, URI};
|
||||
|
||||
use super::rmcp_resources_handler_runtime_tests as handler;
|
||||
|
||||
// As in rmcp_result_runtime_tests: deferred body polling keeps this request's observer.
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
@@ -113,11 +115,16 @@ async fn success(
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
let h = Endpoint::started().await;
|
||||
pub(super) async fn control(
|
||||
revision: &str,
|
||||
require_handler: bool,
|
||||
) -> Vec<([usize; 4], [usize; 4])> {
|
||||
crank_test_support::postgres_schema_url_for_task("resources_handler", "t_48a39ca6").await;
|
||||
let mut h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
let mut handlers = Vec::new();
|
||||
// Preference order negotiates JSON or terminal SSE in both Resources revisions.
|
||||
for sse in [false, true] {
|
||||
let mut cursor = None;
|
||||
@@ -127,8 +134,10 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let before = handler::counts(&h.counters);
|
||||
let (result, delta) =
|
||||
success(&h, revision, session, "resources/list", params, sse).await;
|
||||
handlers.push(handler::delta(&h.counters, before, "resources/list"));
|
||||
let resources = result["resources"].as_array().unwrap();
|
||||
assert_eq!(resources.len(), 1, "{result}");
|
||||
let item = &resources[0];
|
||||
@@ -155,6 +164,7 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
(json!("sdk_b"), json!("crank://resources/sdk-b"))
|
||||
]
|
||||
);
|
||||
let before = handler::counts(&h.counters);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
@@ -168,7 +178,9 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
result["contents"],
|
||||
json!([{"uri":URI,"mimeType":"text/plain","text":TEXT}])
|
||||
);
|
||||
handlers.push(handler::delta(&h.counters, before, "resources/read"));
|
||||
deltas.push((delta, [1, 0, 1, 0]));
|
||||
let before = handler::counts(&h.counters);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
@@ -180,6 +192,11 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
.await;
|
||||
assert_eq!(result["resourceTemplates"], json!([]));
|
||||
assert!(result.get("nextCursor").is_none());
|
||||
handlers.push(handler::delta(
|
||||
&h.counters,
|
||||
before,
|
||||
"resources/templates/list",
|
||||
));
|
||||
deltas.push((delta, [1, 0, 0, 1]));
|
||||
}
|
||||
// Malformed parameters/cursors and indistinguishable unavailable URIs remain command errors.
|
||||
@@ -188,8 +205,13 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
("resources/list", json!({"limit":"invalid"})),
|
||||
("resources/templates/list", json!({"cursor":"invalid"})),
|
||||
("resources/templates/list", json!({"limit":"invalid"})),
|
||||
("resources/read", json!({"uri":42})),
|
||||
("resources/read", json!({})),
|
||||
("resources/read", json!({"uri":"crank://resources/unbound"})),
|
||||
] {
|
||||
let before = handler::counts(&h.counters);
|
||||
let parsing_reject = params.get("limit").is_some()
|
||||
|| (method == "resources/read" && !params["uri"].is_string());
|
||||
let req = request(revision, method, params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
@@ -198,8 +220,66 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
let expected_message = if parsing_reject {
|
||||
format!("invalid {method} parameters")
|
||||
} else if method == "resources/read" {
|
||||
"the requested resource is not available".to_owned()
|
||||
} else {
|
||||
format!("invalid {method} cursor")
|
||||
};
|
||||
assert_eq!(body["error"]["message"], expected_message, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
if parsing_reject {
|
||||
assert_eq!(
|
||||
handler::counts(&h.counters),
|
||||
before,
|
||||
"parsing reject: {req}"
|
||||
);
|
||||
} else {
|
||||
handlers.push(handler::delta(&h.counters, before, method));
|
||||
}
|
||||
}
|
||||
// Fresh scope and Agent binding are checked even after a successful handshake/read.
|
||||
let foreign_slug = handler::foreign_agent(&h.registry).await;
|
||||
let original_url = h.url.clone();
|
||||
h.url = format!(
|
||||
"{}/{foreign_slug}",
|
||||
original_url.rsplit_once('/').unwrap().0
|
||||
);
|
||||
for method in [
|
||||
"resources/list",
|
||||
"resources/read",
|
||||
"resources/templates/list",
|
||||
] {
|
||||
let before = handler::counts(&h.counters);
|
||||
let req = request(revision, method, json!({"uri":URI}));
|
||||
// Agent-bound credential lookup intentionally does not reveal the other Agent.
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 401);
|
||||
assert_eq!(handler::counts(&h.counters), before, "cross-agent: {req}");
|
||||
}
|
||||
h.url = original_url;
|
||||
sqlx::query(
|
||||
"update platform_api_keys set scopes_json = '[]'::jsonb where id = 'pk_dispatch_observer'",
|
||||
)
|
||||
.execute(h.registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
for method in [
|
||||
"resources/list",
|
||||
"resources/read",
|
||||
"resources/templates/list",
|
||||
] {
|
||||
let before = handler::counts(&h.counters);
|
||||
let req = request(revision, method, json!({"uri":URI}));
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 403);
|
||||
assert_eq!(
|
||||
handler::counts(&h.counters),
|
||||
before,
|
||||
"read scope required: {req}"
|
||||
);
|
||||
}
|
||||
sqlx::query("update platform_api_keys set scopes_json = '[\"read\",\"write\"]'::jsonb where id = 'pk_dispatch_observer'")
|
||||
.execute(h.registry.pool()).await.unwrap();
|
||||
// An existing session does not preserve revoked authorization.
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
@@ -215,24 +295,35 @@ async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
("resources/templates/list", json!({})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
let before = handler::counts(&h.counters);
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 401);
|
||||
assert_eq!(handler::counts(&h.counters), before, "revoked: {req}");
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Resources wire {revision}: pagination, exact content URI/bytes, empty templates, JSON/SSE negotiation, InvalidParams, revoked401; actual/expected SDK deltas={deltas:?}"
|
||||
);
|
||||
eprintln!(
|
||||
"Resources handler {revision}: completed[list,read,templates], consumed[list,read,templates]; actual/expected per admitted request={handlers:?}; parsing/revoked guards=0"
|
||||
);
|
||||
if require_handler {
|
||||
assert!(
|
||||
handlers.iter().all(|(actual, expected)| actual == expected),
|
||||
"ServerHandler completion/Result consumption missing after successful HTTP wire/error/guard checks ({revision}): {handlers:?}"
|
||||
);
|
||||
}
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
control(LEGACY_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
control(MODERN_REVISION, false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
let deltas = control(LEGACY_REVISION, false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
@@ -240,7 +331,7 @@ async fn rmcp_resources_sdk_legacy() {
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
let deltas = control(MODERN_REVISION, false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
//! #107 inbound responses: wire compatibility and independent SDK execution oracles.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, atomic::Ordering};
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("response_owner", "t_d427ee76").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
fn sdk(c: &CounterSet) -> [usize; 4] {
|
||||
[
|
||||
c.sdk_inbound_response_decoded(),
|
||||
c.sdk_inbound_error_decoded(),
|
||||
c.sdk_inbound_response_consumed(),
|
||||
c.sdk_inbound_error_consumed(),
|
||||
]
|
||||
}
|
||||
fn request(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
raw: &str,
|
||||
) -> reqwest::RequestBuilder {
|
||||
// Reuse the HTTP fixture without its request-only modern method/name headers.
|
||||
let mut req = h
|
||||
.request(LEGACY_REVISION, session, &h.key, accept, json!({}))
|
||||
.header("x-request-id", "response-atdd")
|
||||
.body(raw.to_owned())
|
||||
.build()
|
||||
.unwrap();
|
||||
req.headers_mut()
|
||||
.insert("MCP-Protocol-Version", revision.parse().unwrap());
|
||||
reqwest::RequestBuilder::from_parts(reqwest::Client::new(), req)
|
||||
}
|
||||
async fn ack(response: reqwest::Response) {
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
async fn no_effects(h: &Endpoint, ops: SessionOps, entries: Snapshot) {
|
||||
assert_eq!(
|
||||
h.sessions.snapshot(),
|
||||
ops,
|
||||
"response ACK must not access sessions"
|
||||
);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(
|
||||
(after.era_modern, after.era_legacy, after.tools_service),
|
||||
(
|
||||
entries.era_modern,
|
||||
entries.era_legacy,
|
||||
entries.tools_service
|
||||
)
|
||||
);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
assert!(
|
||||
h.history("response-atdd").await.is_empty(),
|
||||
"no domain invocation"
|
||||
);
|
||||
}
|
||||
async fn success_control(error: bool) -> Vec<[usize; 4]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
let numbers = [
|
||||
"-9223372036854775808",
|
||||
"9223372036854775807",
|
||||
"18446744073709551615",
|
||||
"3.25",
|
||||
"1.0",
|
||||
"-0.0",
|
||||
"1.7976931348623157e308",
|
||||
"-1.7976931348623157e308",
|
||||
"5e-324",
|
||||
];
|
||||
let mut ids = vec!["\"reply/Ю\""];
|
||||
ids.extend(numbers);
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for session in [None, Some("nonexistent-response-session")] {
|
||||
for (index, id) in ids.iter().enumerate() {
|
||||
let messages = if error {
|
||||
let code = numbers[index % numbers.len()];
|
||||
let data = [
|
||||
"null",
|
||||
"true",
|
||||
"3.25",
|
||||
"\"text\"",
|
||||
"[]",
|
||||
"{}",
|
||||
"[null,true,{\"nested\":1}]",
|
||||
][index % 7];
|
||||
vec![
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"error":{{"code":{code},"message":"failed","data":{data}}},"params":false,"extension":[]}}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"failed"}},"params":{{"_meta":false}}}}"#
|
||||
),
|
||||
]
|
||||
} else {
|
||||
vec![format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"result":{{"arbitrary":[null,true,3]}},"params":false,"extension":[]}}"#
|
||||
)]
|
||||
};
|
||||
for raw in messages {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
ack(request(&h, revision, session, accept, &raw)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
no_effects(&h, ops, entries).await;
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push(std::array::from_fn(|i| after[i] - before[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("existing wire GREEN error={error}; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn wire_success_and_error_ack_without_session_or_modern_metadata() {
|
||||
success_control(false).await;
|
||||
success_control(true).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sdk_success_response_decoded_and_consumed_after_http_ack() {
|
||||
let deltas = success_control(false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 0, 1, 0]),
|
||||
"real SDK success decode/typed variant consumption required; actual={deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sdk_error_response_decoded_and_consumed_after_http_ack() {
|
||||
let deltas = success_control(true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [0, 1, 0, 1]),
|
||||
"real SDK error decode/typed variant consumption required; actual={deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn malformed_responses_reject_before_sdk_or_effects() {
|
||||
let h = endpoint().await;
|
||||
let mut cases = vec![
|
||||
json!({}),
|
||||
json!({"jsonrpc":"2.0","id":1}),
|
||||
json!({"jsonrpc":"2.0","id":1,"result":{},"error":{"code":1,"message":"x"}}),
|
||||
json!({"jsonrpc":"2.0","result":{}}),
|
||||
json!({"id":1,"result":{}}),
|
||||
json!({"jsonrpc":2,"id":1,"result":{}}),
|
||||
json!({"jsonrpc":"2.0","id":1,"result":3}),
|
||||
json!({"jsonrpc":"2.0","error":{}}),
|
||||
json!({"jsonrpc":"2.0","error":{"code":1,"message":3}}),
|
||||
];
|
||||
for value in [Value::Null, json!(true), json!([]), json!({}), json!("bad")] {
|
||||
for field in ["jsonrpc", "result", "id"] {
|
||||
if (field == "result" && value.is_object()) || (field == "id" && value.is_string()) {
|
||||
continue;
|
||||
}
|
||||
let mut m = json!({"jsonrpc":"2.0","id":1,"result":{}});
|
||||
m[field] = value.clone();
|
||||
cases.push(m);
|
||||
}
|
||||
for field in ["error", "code", "message", "id"] {
|
||||
if (field == "error" && value.is_object())
|
||||
|| (field == "message" && value.is_string())
|
||||
|| (field == "id" && value.is_string())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut m = json!({"jsonrpc":"2.0","id":1,"error":{"code":1,"message":"x"}});
|
||||
if ["code", "message"].contains(&field) {
|
||||
m["error"][field] = value.clone();
|
||||
} else {
|
||||
m[field] = value.clone();
|
||||
}
|
||||
cases.push(m);
|
||||
}
|
||||
}
|
||||
for missing in ["code", "message"] {
|
||||
let mut m = json!({"jsonrpc":"2.0","error":{"code":1,"message":"x"}});
|
||||
m["error"].as_object_mut().unwrap().remove(missing);
|
||||
cases.push(m);
|
||||
}
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for m in &cases {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let response = request(&h, revision, None, "application/json", &m.to_string())
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400, "{m}");
|
||||
let wire: Value = response.json().await.unwrap();
|
||||
assert_eq!(wire["error"]["code"], -32600, "{m}: {wire}");
|
||||
assert_eq!(wire["id"], Value::Null);
|
||||
assert!(wire.get("result").is_none());
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn admission_guards_precede_response_ack_and_sdk() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for raw in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
|
||||
r#"{"jsonrpc":"2.0","error":{"code":1,"message":"x"}}"#,
|
||||
] {
|
||||
for guard in ["origin", "accept", "ambiguous"] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let before = sdk(&h.counters);
|
||||
let mut req = request(&h, revision, None, "application/json", raw)
|
||||
.build()
|
||||
.unwrap();
|
||||
let expected = match guard {
|
||||
"origin" => {
|
||||
req.headers_mut()
|
||||
.insert("origin", "https://evil.example".parse().unwrap());
|
||||
403
|
||||
}
|
||||
"accept" => {
|
||||
req.headers_mut()
|
||||
.insert("accept", "text/plain".parse().unwrap());
|
||||
406
|
||||
}
|
||||
_ => {
|
||||
req.headers_mut()
|
||||
.append("MCP-Session-Id", "one".parse().unwrap());
|
||||
req.headers_mut()
|
||||
.append("MCP-Session-Id", "two".parse().unwrap());
|
||||
400
|
||||
}
|
||||
};
|
||||
let response = reqwest::Client::new().execute(req).await.unwrap();
|
||||
assert_eq!(response.status().as_u16(), expected, "{guard}");
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn authentication_and_revocation_precede_response_ack() {
|
||||
let h = endpoint().await;
|
||||
let mut statuses = vec![];
|
||||
for revoked in [false, true] {
|
||||
if revoked {
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for raw in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
|
||||
r#"{"jsonrpc":"2.0","error":{"code":1,"message":"x"}}"#,
|
||||
] {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let mut req = request(&h, revision, None, "application/json", raw)
|
||||
.build()
|
||||
.unwrap();
|
||||
if !revoked {
|
||||
req.headers_mut().remove("authorization");
|
||||
}
|
||||
let response = reqwest::Client::new().execute(req).await.unwrap();
|
||||
statuses.push(response.status().as_u16());
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
statuses,
|
||||
vec![401; 8],
|
||||
"missing/revoked credentials must reject before ACK and SDK"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn method_bearing_messages_keep_priority_over_response_fields() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = h.session(revision).await;
|
||||
for notification in [false, true] {
|
||||
let mut m = json!({"jsonrpc":"2.0","method":"ping","id":7,"result":false,"error":[],"extension":null});
|
||||
if notification {
|
||||
m.as_object_mut().unwrap().remove("id");
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
m["params"] = json!({"_meta":modern_meta()});
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
let response = h
|
||||
.request(revision, session.as_deref(), &h.key, "application/json", m)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
if notification {
|
||||
ack(response).await;
|
||||
} else {
|
||||
assert_eq!(response.status(), 200);
|
||||
let wire: Value = response.json().await.unwrap();
|
||||
assert_eq!(wire["id"], 7);
|
||||
assert!(wire["result"].is_object());
|
||||
assert!(wire.get("error").is_none());
|
||||
}
|
||||
assert_eq!(sdk(&h.counters), before, "not an inbound response");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn observer_positive_control_is_task_scoped_and_independent() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
super::sdk_inbound_response_decoded();
|
||||
super::sdk_inbound_error_decoded();
|
||||
super::sdk_inbound_response_consumed();
|
||||
super::sdk_inbound_error_consumed();
|
||||
assert_eq!(sdk(&a), [0; 4]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_inbound_response_decoded();
|
||||
super::sdk_inbound_error_consumed();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_inbound_error_decoded();
|
||||
super::sdk_inbound_response_consumed();
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0, 0, 1]);
|
||||
assert_eq!(sdk(&b), [0, 1, 1, 0]);
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! #107: HTTP wire controls are independent of the SDK execution oracle.
|
||||
//! A real committed Tool removal exercises the watcher; existing mcp_signals::scenarios covers
|
||||
//! Resource/Prompt publications, isolation, coalescing, reconnect and authoritative recovery.
|
||||
use super::{CounterSet, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_signals_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, terminal};
|
||||
|
||||
const SUB_ID: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
const ACK: &str = "notifications/subscriptions/acknowledged";
|
||||
const TOOLS: &str = "notifications/tools/list_changed";
|
||||
const INVALID_FILTER: &str = "invalid subscriptions/listen notification filter";
|
||||
|
||||
fn counts(c: &CounterSet) -> [usize; 3] {
|
||||
[
|
||||
c.sdk_subscriptions_listen(),
|
||||
c.sdk_subscriptions_acknowledged(),
|
||||
c.sdk_signal_notification(),
|
||||
]
|
||||
}
|
||||
fn ack(id: &Value, notifications: Value) -> Value {
|
||||
json!({"jsonrpc":"2.0", "method":ACK,
|
||||
"params":{"_meta":{SUB_ID:id},"notifications":notifications}})
|
||||
}
|
||||
fn listen_body(id: Value, params: Value) -> Value {
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"subscriptions/listen","params":params})
|
||||
}
|
||||
|
||||
async fn catalog_control(revision: &str) -> [usize; 3] {
|
||||
let h = Endpoint::started().await;
|
||||
let session = if revision == LEGACY_REVISION {
|
||||
Some(h.session().await)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let admission_before = h.counters.snapshot().admission;
|
||||
let before_list = h.tools(revision, session.as_deref()).await;
|
||||
assert_eq!(
|
||||
h.counters.snapshot().admission - admission_before,
|
||||
1,
|
||||
"positive control: the HTTP request must carry this observer"
|
||||
);
|
||||
assert_eq!(before_list["result"]["tools"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(before_list["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
let id = json!(u64::MAX);
|
||||
let before = counts(&h.counters);
|
||||
let mut stream = if revision == MODERN_REVISION {
|
||||
let mut stream = h
|
||||
.listen(
|
||||
id.clone(),
|
||||
json!({
|
||||
"toolsListChanged":true,"resourcesListChanged":true,"promptsListChanged":true,
|
||||
"resourceSubscriptions":["crank://CANARY-URI"], "unknown":null
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
// Whole-frame equality proves ack first, exact id, no result/id/URI/payload leakage.
|
||||
assert_eq!(
|
||||
stream.frame().await,
|
||||
ack(
|
||||
&id,
|
||||
json!({
|
||||
"toolsListChanged":true,"resourcesListChanged":true,"promptsListChanged":true
|
||||
})
|
||||
)
|
||||
);
|
||||
stream
|
||||
} else {
|
||||
h.legacy_stream(session.as_deref().unwrap()).await
|
||||
};
|
||||
// Enough for the existing one-second watcher to establish its initial committed fingerprint.
|
||||
stream.silent().await;
|
||||
h.draft_without_tools().await;
|
||||
stream.silent().await;
|
||||
assert_eq!(
|
||||
h.tools(revision, session.as_deref()).await["result"]["tools"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
h.publish_without_tools().await;
|
||||
let expected = if revision == MODERN_REVISION {
|
||||
json!({"jsonrpc":"2.0","method":TOOLS,"params":{"_meta":{SUB_ID:id}}})
|
||||
} else {
|
||||
json!({"jsonrpc":"2.0","method":TOOLS})
|
||||
};
|
||||
assert_eq!(
|
||||
stream.frame().await,
|
||||
expected,
|
||||
"exact committed signal, no catalog payload"
|
||||
);
|
||||
stream.silent().await;
|
||||
assert_eq!(
|
||||
h.tools(revision, session.as_deref()).await["result"]["tools"],
|
||||
json!([])
|
||||
);
|
||||
let after = counts(&h.counters);
|
||||
std::array::from_fn(|i| after[i] - before[i])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_wire_control() {
|
||||
catalog_control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn legacy_wire_control() {
|
||||
catalog_control(LEGACY_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_sdk_runtime_oracle() {
|
||||
// All real HTTP/commit assertions above must pass before missing SDK behavior can be RED.
|
||||
assert_eq!(
|
||||
catalog_control(MODERN_REVISION).await,
|
||||
[1, 1, 1],
|
||||
"real HTTP listen decode / ack serialization / watcher signal serialization SDK entries"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn legacy_sdk_runtime_oracle() {
|
||||
assert_eq!(
|
||||
catalog_control(LEGACY_REVISION).await,
|
||||
[0, 0, 1],
|
||||
"legacy GET must use SDK signal serialization but not modern listen/ack"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_false_absent_and_uri_only_do_not_opt_in() {
|
||||
let h = Endpoint::started().await;
|
||||
let mut absent = h.listen(json!("absent"), json!({})).await;
|
||||
assert_eq!(absent.frame().await, ack(&json!("absent"), json!({})));
|
||||
let mut disabled = h
|
||||
.listen(
|
||||
json!("disabled"),
|
||||
json!({
|
||||
"toolsListChanged":false,"resourcesListChanged":false,"promptsListChanged":false,
|
||||
"resourceSubscriptions":["crank://CANARY-URI"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(disabled.frame().await, ack(&json!("disabled"), json!({})));
|
||||
// A simultaneous positive stream proves the publication was visible to the running watchers.
|
||||
let mut enabled = h
|
||||
.listen(json!("enabled"), json!({"toolsListChanged":true}))
|
||||
.await;
|
||||
assert_eq!(
|
||||
enabled.frame().await,
|
||||
ack(&json!("enabled"), json!({"toolsListChanged":true}))
|
||||
);
|
||||
enabled.silent().await;
|
||||
h.draft_without_tools().await;
|
||||
h.publish_without_tools().await;
|
||||
assert_eq!(
|
||||
enabled.frame().await,
|
||||
json!({"jsonrpc":"2.0","method":TOOLS,"params":{"_meta":{SUB_ID:"enabled"}}})
|
||||
);
|
||||
absent.silent().await;
|
||||
disabled.silent().await;
|
||||
let body = terminal(
|
||||
h.post(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
json!({
|
||||
"jsonrpc":"2.0","id":4,"method":"resources/subscribe",
|
||||
"params":{"_meta":modern_meta(),"uri":"crank://CANARY-URI"}
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32601);
|
||||
assert!(body.get("result").is_none());
|
||||
assert!(!body.to_string().contains("CANARY"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_http_filter_shape_and_bounds_stay_compatible() {
|
||||
let h = Endpoint::started().await;
|
||||
let mut invalid = vec![
|
||||
json!({}),
|
||||
json!({"notifications":null}),
|
||||
json!({"notifications":[]}),
|
||||
json!({"notifications":{"toolsListChanged":"CANARY"}}),
|
||||
json!({"notifications":{"resourceSubscriptions":[null]}}),
|
||||
json!({"notifications":{"resourceSubscriptions":vec!["CANARY";33]}}),
|
||||
json!({"notifications":{"resourceSubscriptions":["X".repeat(2049)]}}),
|
||||
];
|
||||
for key in [
|
||||
"toolsListChanged",
|
||||
"resourcesListChanged",
|
||||
"promptsListChanged",
|
||||
"resourceSubscriptions",
|
||||
] {
|
||||
let mut filter = json!({});
|
||||
filter[key] = Value::Null;
|
||||
invalid.push(json!({"notifications":filter}));
|
||||
}
|
||||
for mut params in invalid {
|
||||
params["_meta"] = modern_meta();
|
||||
let body = terminal(
|
||||
h.post(MODERN_REVISION, None, listen_body(json!(7), params))
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["id"], 7);
|
||||
assert_eq!(body["error"]["code"], -32602);
|
||||
assert_eq!(body["error"]["message"], INVALID_FILTER);
|
||||
assert!(body.get("result").is_none());
|
||||
assert!(!body.to_string().contains("CANARY"));
|
||||
assert!(body.to_string().len() < 4096);
|
||||
}
|
||||
// Inclusive bounds, unknown null extension and explicit false are accepted, never acknowledged
|
||||
// as a URI-content subscription or an extra list-change type.
|
||||
let mut stream = h
|
||||
.listen(
|
||||
json!(8),
|
||||
json!({
|
||||
"resourceSubscriptions":vec!["é".repeat(1024);32], "toolsListChanged":false,
|
||||
"unknown":null
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(stream.frame().await, ack(&json!(8), json!({})));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_http_ids_are_lossless_and_bounded() {
|
||||
let h = Endpoint::started().await;
|
||||
for id in [
|
||||
json!("a".repeat(62)),
|
||||
json!("é".repeat(31)),
|
||||
json!(u64::MAX),
|
||||
json!(9_007_199_254_740_993_u64),
|
||||
json!(1.25),
|
||||
json!(1.0),
|
||||
] {
|
||||
let mut stream = h.listen(id.clone(), json!({})).await;
|
||||
let frame = stream.frame().await;
|
||||
assert_eq!(frame, ack(&id, json!({})));
|
||||
assert_eq!(frame["params"]["_meta"][SUB_ID].to_string(), id.to_string());
|
||||
}
|
||||
for id in [json!("a".repeat(63)), json!("é".repeat(32))] {
|
||||
let body = terminal(
|
||||
h.post(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
listen_body(
|
||||
id.clone(),
|
||||
json!({"_meta":modern_meta(),"notifications":{}}),
|
||||
),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["id"], id);
|
||||
assert_eq!(body["error"]["code"], -32600);
|
||||
assert!(body.get("result").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_http_meta_admission_precedes_sdk_decode() {
|
||||
let h = Endpoint::started().await;
|
||||
for meta in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({META_PROTOCOL_VERSION:MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES:null}),
|
||||
] {
|
||||
let before = counts(&h.counters);
|
||||
let response = h
|
||||
.post(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
listen_body(json!(9), json!({"_meta":meta,"notifications":{}})),
|
||||
)
|
||||
.await;
|
||||
// Admission rejections are HTTP 400, not a successful SSE response.
|
||||
assert_eq!(response.status(), 400);
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(body["error"]["code"], -32020);
|
||||
assert!(body.get("result").is_none());
|
||||
assert_eq!(
|
||||
counts(&h.counters),
|
||||
before,
|
||||
"admission must reject before any SDK entry"
|
||||
);
|
||||
}
|
||||
// clientInfo is optional at HTTP admission; SDK decoding must not newly require it.
|
||||
let mut meta = modern_meta();
|
||||
meta.as_object_mut().unwrap().remove(META_CLIENT_INFO);
|
||||
let response = h
|
||||
.post(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
listen_body(
|
||||
json!(10),
|
||||
json!({"_meta":meta,"notifications":{},"extension":null}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let mut stream = fixtures::Events::open(response);
|
||||
assert_eq!(stream.frame().await, ack(&json!(10), json!({})));
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! Small real catalog fixture; broader Resource/Prompt mutations stay in mcp_signals::scenarios.
|
||||
use super::*;
|
||||
use crank_core::{AgentStatus, AgentVersion, ToolSelectionPolicy};
|
||||
use crank_registry::{CreateAgentDraftVersionRequest, PublishAgentRequest, PublishRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
key: String,
|
||||
url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
// First caller labels the shared, exit-cleaned disposable PostgreSQL with this owner.
|
||||
crank_test_support::postgres_schema_url_for_task("signals_owner", "t_7d5f77a6").await;
|
||||
let registry = test_registry().await;
|
||||
// This fixture only lists/removes a Tool; no upstream execution is needed.
|
||||
let operation = test_operation("http://127.0.0.1:9");
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
publish_agent(®istry, &operation).await;
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
None,
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
listener.local_addr().unwrap()
|
||||
);
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
key,
|
||||
url,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: Value,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
}
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(6), request.json(&body).send())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
pub async fn listen(&self, id: Value, notifications: Value) -> Events {
|
||||
Events::open(
|
||||
self.post(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
json!({
|
||||
"jsonrpc":"2.0", "id":id, "method":"subscriptions/listen",
|
||||
"params":{"_meta":modern_meta(), "notifications":notifications}
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
pub async fn session(&self) -> String {
|
||||
let response = self.post(LEGACY_REVISION, None, legacy_initialize(1)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = terminal(response).await;
|
||||
assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
let response = self
|
||||
.post(LEGACY_REVISION, Some(&session), initialized_notification())
|
||||
.await;
|
||||
assert_eq!(response.status(), 202);
|
||||
session
|
||||
}
|
||||
pub async fn legacy_stream(&self, session: &str) -> Events {
|
||||
let response = tokio::time::timeout(
|
||||
Duration::from_secs(6),
|
||||
reqwest::Client::new()
|
||||
.get(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "text/event-stream")
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.send(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
Events::open(response)
|
||||
}
|
||||
pub async fn tools(&self, revision: &str, session: Option<&str>) -> Value {
|
||||
let params = if revision == MODERN_REVISION {
|
||||
json!({"_meta":modern_meta()})
|
||||
} else {
|
||||
json!({})
|
||||
};
|
||||
terminal(
|
||||
self.post(
|
||||
revision,
|
||||
session,
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":params}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub async fn draft_without_tools(&self) {
|
||||
self.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 2,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
updated_at: &test_time(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub async fn publish_without_tools(&self) {
|
||||
self.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 2,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Events {
|
||||
response: reqwest::Response,
|
||||
buffer: Vec<u8>,
|
||||
}
|
||||
impl Events {
|
||||
pub fn open(response: reqwest::Response) -> Self {
|
||||
assert_eq!(response.status(), 200, "notification stream must open");
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream")
|
||||
);
|
||||
Self {
|
||||
response,
|
||||
buffer: Vec::new(),
|
||||
}
|
||||
}
|
||||
// One absolute deadline: keepalive comments cannot extend a missing-frame assertion forever.
|
||||
pub async fn next(&mut self, wait: Duration) -> Option<Value> {
|
||||
let deadline = tokio::time::Instant::now() + wait;
|
||||
loop {
|
||||
if let Some(index) = self.buffer.windows(2).position(|w| w == b"\n\n") {
|
||||
let frame: Vec<u8> = self.buffer.drain(..index + 2).collect();
|
||||
let frame = std::str::from_utf8(&frame).unwrap();
|
||||
if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data:")) {
|
||||
return Some(serde_json::from_str(data.trim()).expect("SSE data must be JSON"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match tokio::time::timeout_at(deadline, self.response.chunk()).await {
|
||||
Err(_) => return None,
|
||||
Ok(Err(error)) => panic!("SSE transport failure, not silence: {error}"),
|
||||
Ok(Ok(None)) => panic!("SSE closed unexpectedly, not silence"),
|
||||
Ok(Ok(Some(bytes))) => self.buffer.extend_from_slice(&bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub async fn frame(&mut self) -> Value {
|
||||
self.next(Duration::from_secs(6))
|
||||
.await
|
||||
.expect("notification must arrive before deadline")
|
||||
}
|
||||
pub async fn silent(&mut self) {
|
||||
assert_eq!(
|
||||
self.next(Duration::from_millis(2200)).await,
|
||||
None,
|
||||
"no duplicate/unrequested signal"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn terminal(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
assert!(
|
||||
status == 200 || status == 404,
|
||||
"unexpected terminal status {status}"
|
||||
);
|
||||
let sse = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream");
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
frames.len(),
|
||||
1,
|
||||
"one terminal frame, no notification: {raw}"
|
||||
);
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
status.as_u16(),
|
||||
if body["error"]["code"] == -32601 {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
}
|
||||
);
|
||||
body
|
||||
}
|
||||
@@ -43,6 +43,24 @@ Logging-срез #107 на базе rc.22/rmcp3.9.0 использует сущ
|
||||
|
||||
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 этим срезом не завершены.
|
||||
|
||||
Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritten `jsonrpc_result`/`jsonrpc_error` в `jsonrpc.rs` сериализацией настоящих `JsonRpcResponse<Value>` и `JsonRpcError`/`ErrorData`. Уже подключённые consumers — общий `build_app` HTTP JSON и lifecycle SSE terminal обеих revisions; новые dispatch/transport пути не добавляются. Локальная projection+restore сразу возвращает исходные JSON id (включая null, u64 и точную floating-point форму) и i64 error code, которые SDK-типы не представляют полностью; произвольный result и omission error.data сохраняются. Прежний guard correlation не меняется: JSON protocol errors содержат correlation data, lifecycle SSE terminal errors по-прежнему её опускают. Runtime wire controls и отдельный SDK oracle проверяют success/protocol error, а affected regressions — admission, revoked credentials, tool isError и cancellation. Входная валидация, safe response id, auth, статусы/headers, очереди/сессии и transport остаются прежними; это не завершение #107, feature qualification или production deployment.
|
||||
|
||||
Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет handwritten ответы legacy `initialize` и modern `server/discover` на настоящие `InitializeResult`/`DiscoverResult` в `protocol/lifecycle_sdk.rs`. Уже подключённый потребитель — штатный `build_app` HTTP JSON/SSE. Версии и их порядок заданы прежним allowlist, capabilities поступают только из registry; server identity, omissions и discovery ttlMs=0/cacheScope=private сохранены. SDK `ServerCapabilities` не представляет дополнительные top-level имена registry: после typed serialization восстанавливаются только отсутствующие ключи, без замены SDK-known полей. HTTP ATDD отдельно проверяет прежний wire и SDK execution, legacy initialize→initialized→защищённый вызов и отсутствие session operations у modern discovery; affected regression сохраняет frozen advertisement, unsupported revision rejection, auth/revocation/Agent scope и legacy transport lifecycle. Следующий initialize-input-срез на базе rc.27 заменяет `app/request.rs::InitializeParams` декодированием настоящего `InitializeRequestParams` в `protocol/lifecycle_sdk.rs`: штатный `handle_initialize` использует SDK `protocol_version` в прежнем allowlist. Локальная projection передаёт только protocolVersion с инертными обязательными SDK capabilities/clientInfo; исходные ignored clientInfo/extensions не валидируются, а raw capabilities сохраняют прежний object-предикат elicitation. HTTP admission (включая запрет sequence params и malformed _meta) остаётся до SDK. Отдельный typed runtime oracle и JSON/SSE tolerance/session ATDD подтверждают использование результата SDK, отсутствие новых отказов и прежний initialize→initialized→защищённый вызов. Generic dispatch/ping, session storage/TTL/reconnect, admission/auth и transport не переносились. Существующий SSE error.data omission не исправляется; полный #107, feature qualification и production deployment не завершены.
|
||||
|
||||
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 не завершены.
|
||||
|
||||
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.
|
||||
|
||||
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 не запускаются.
|
||||
|
||||
Prompts handler-срез #107 на базе rc.33 заменяет прежний DTO-only shim настоящими `ServerHandler::list_prompts/get_prompt` в `app/rmcp_prompts.rs`. Уже подключённый потребитель — `build_app` → обе HTTP dispatch-ветки → `rmcp_dispatch::handle_prompts_command`. Overrides напрямую await-ят прежний domain service ровно один раз; caller потребляет actual typed SDK Result, а request-local projection восстанавливает только непредставимые поля/omissions. Инертный ping-bootstrap закрывается до domain execution; domain future остаётся в parent HTTP future и отменяется при drop. Closed Peer не поддерживает callbacks. HTTP handler completed/consumed ATDD обеих revisions и trait-result mutation/drop regressions подтверждают реальное исполнение, прежние wire/access/error boundaries и lossless content; affected Prompts integration проверяет pinned static/dynamic Resource composition и dependency errors. Domain/auth/storage/session/transport не меняются. Это не завершение #107, feature qualification или разрешение #108/4.7/production.
|
||||
|
||||
Completion handler-срез #107 на базе rc.34 заменяет DTO-only completion shim настоящим `ServerHandler::complete` в `app/rmcp_completion.rs`. Подключённый потребитель — обе штатные HTTP dispatch-ветки через `rmcp_dispatch::handle_completion_command`. Override напрямую await-ит прежний domain service один раз; caller потребляет возвращённый SDK `CompleteResult`/`ErrorData`, сохраняя прежнюю JSON/SSE проекцию. Исходный JSON context передаётся request-local без сужения до SDK string map. Инертный ping-bootstrap закрывается до domain execution; drop parent future отменяет незавершённый domain future, закрытый Peer не поддерживает callbacks. Отдельные HTTP handler-completed/caller-consumed oracles и trait mutation/drop/error regressions проверяют этот переход, а wire controls сохраняют refs, published/archive binding, bounded/empty/omitted totals, safe errors и revocation. Domain/auth/storage/session/transport/capabilities не меняются. Полный #107, нагрузочная квалификация, #108/4.7 и production не завершены и не запускаются.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user