Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8068fd7910 | ||
|
|
2f9c4cb568 | ||
|
|
61378224b2 | ||
|
|
1b51d44121 | ||
|
|
077be3b069 | ||
|
|
42e7728b3a | ||
|
|
541b135baf | ||
|
|
835947e9fc | ||
|
|
2b36add550 | ||
|
|
4832878468 | ||
|
|
5bf4e3e9bf | ||
|
|
1ac5b10c67 | ||
|
|
07a9ef0a4a | ||
|
|
4f83d8d24c | ||
|
|
2a57800f63 | ||
|
|
e359077f6e | ||
|
|
c0117ff6b8 | ||
|
|
24bba2cf33 | ||
|
|
f56553c4d6 | ||
|
|
027e2cb911 | ||
|
|
adabb2065a | ||
|
|
bf773d61b8 | ||
|
|
74a98d9362 |
No files matched your search
Generated
+13
-5
@@ -590,6 +590,12 @@ dependencies = [
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
@@ -1098,6 +1104,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
@@ -3030,9 +3037,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.7.0"
|
||||
version = "3.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ece64e19631fc38758181e637c15509a2c2709ee53bfde1e1d58f9dc991f919e"
|
||||
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -3051,6 +3058,7 @@ dependencies = [
|
||||
"schemars 1.2.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
"sse-stream",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
@@ -3101,9 +3109,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@@ -4854,7 +4862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.4",
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -33,10 +33,10 @@ tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
# Typed Tools dispatch uses the SDK; its HTTP transport remains test-only.
|
||||
rmcp = { version = "=3.7.0" }
|
||||
rmcp = { version = "=3.9.0" }
|
||||
|
||||
[dev-dependencies]
|
||||
rmcp = { version = "=3.7.0", features = ["transport-streamable-http-server"] }
|
||||
rmcp = { version = "=3.9.0", features = ["transport-streamable-http-server"] }
|
||||
crank-mapping = { path = "../crank-mapping" }
|
||||
crank-test-support = { path = "../crank-test-support" }
|
||||
metrics-util = "0.20.4"
|
||||
|
||||
@@ -40,6 +40,7 @@ mod rmcp_http;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
mod rmcp_progress_cancel;
|
||||
#[cfg(test)]
|
||||
mod rmcp_session_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
//! 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_tools_command;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
@@ -19,8 +21,7 @@ use crate::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
declared_mcp_method, discover_result, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, validate_modern_request_name,
|
||||
declared_mcp_method, discover_result, validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
@@ -43,7 +44,7 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
||||
use crate::protocol::ResourceTemplatesListError;
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -161,19 +162,18 @@ pub(super) async fn handle_modern_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
tools_list_result(tools, next_cursor),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
@@ -287,10 +287,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
match resources_list_result(resources, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -346,10 +346,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_read_result(contents),
|
||||
),
|
||||
match resource_read_result(contents, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -435,10 +435,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
match resource_templates_list_result(templates, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -467,7 +467,7 @@ pub(super) async fn handle_modern_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
@@ -484,7 +484,10 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
match prompts_list_result(prompts, next_cursor) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -526,7 +529,7 @@ pub(super) async fn handle_modern_request(
|
||||
if let Err(response) = validate_modern_request_name(message, headers, &command.name) {
|
||||
return *response;
|
||||
}
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
@@ -543,7 +546,10 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
prompt_get_result(description, messages),
|
||||
match prompt_get_result(description, messages) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -617,7 +623,7 @@ pub(super) async fn handle_modern_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
let outcome = super::rmcp_dispatch::handle_completion_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
@@ -771,7 +777,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(
|
||||
@@ -783,7 +790,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.
|
||||
@@ -804,9 +814,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
|
||||
@@ -829,14 +839,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),
|
||||
|
||||
@@ -52,14 +52,128 @@ pub(crate) struct CounterSet {
|
||||
era_legacy: AtomicUsize,
|
||||
tools_service: AtomicUsize,
|
||||
sdk_tools_dispatch: AtomicUsize,
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
sdk_resources_dispatch: AtomicUsize,
|
||||
sdk_resources_list_result: AtomicUsize,
|
||||
sdk_resources_read_result: AtomicUsize,
|
||||
sdk_resource_templates_list_result: AtomicUsize,
|
||||
sdk_prompts_dispatch: AtomicUsize,
|
||||
sdk_prompts_list_result: AtomicUsize,
|
||||
sdk_prompts_get_result: AtomicUsize,
|
||||
sdk_completion_dispatch: AtomicUsize,
|
||||
sdk_completion_result: 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_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
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)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_cancelled_params(&self) -> usize {
|
||||
self.sdk_cancelled_params.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_dispatch(&self) -> usize {
|
||||
self.sdk_logging_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_level(&self) -> usize {
|
||||
self.sdk_logging_level.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_notification(&self) -> usize {
|
||||
self.sdk_logging_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
|
||||
self.sdk_completion_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_completion_result(&self) -> usize {
|
||||
self.sdk_completion_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_prompts_dispatch(&self) -> usize {
|
||||
self.sdk_prompts_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_prompts_list_result(&self) -> usize {
|
||||
self.sdk_prompts_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_prompts_get_result(&self) -> usize {
|
||||
self.sdk_prompts_get_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_dispatch(&self) -> usize {
|
||||
self.sdk_resources_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_list_result(&self) -> usize {
|
||||
self.sdk_resources_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_read_result(&self) -> usize {
|
||||
self.sdk_resources_read_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resource_templates_list_result(&self) -> usize {
|
||||
self.sdk_resource_templates_list_result
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// SDK typed Tools dispatch entries, separate from the existing era/service snapshot.
|
||||
pub(crate) fn sdk_tools_dispatch(&self) -> usize {
|
||||
self.sdk_tools_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK ListToolsResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_list_result(&self) -> usize {
|
||||
self.sdk_tools_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK CallToolResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_call_result(&self) -> usize {
|
||||
self.sdk_tools_call_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Read the counters of one observed request as one comparable snapshot.
|
||||
pub(crate) fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
@@ -145,6 +259,157 @@ pub(crate) fn sdk_tools_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_tools_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK ListToolsResult successfully.
|
||||
pub(crate) fn sdk_tools_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK CallToolResult successfully.
|
||||
pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourcesResult.
|
||||
pub(crate) fn sdk_resources_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ReadResourceResult.
|
||||
pub(crate) fn sdk_resources_read_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_read_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourceTemplatesResult.
|
||||
pub(crate) fn sdk_resource_templates_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resource_templates_list_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_resources_runtime_tests.rs"]
|
||||
mod rmcp_resources_runtime_tests;
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListPromptsResult.
|
||||
pub(crate) fn sdk_prompts_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_prompts_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK GetPromptResult.
|
||||
pub(crate) fn sdk_prompts_get_result_serialized() {
|
||||
increment(|counters| &counters.sdk_prompts_get_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_prompts_runtime_tests.rs"]
|
||||
mod rmcp_prompts_runtime_tests;
|
||||
|
||||
/// Mark only after constructing real SDK CompleteRequestParams.
|
||||
pub(crate) fn sdk_completion_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_completion_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing real SDK CompleteResult/CompletionInfo.
|
||||
pub(crate) fn sdk_completion_result_serialized() {
|
||||
increment(|counters| &counters.sdk_completion_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_completion_runtime_tests.rs"]
|
||||
mod rmcp_completion_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);
|
||||
}
|
||||
|
||||
/// Mark only after successfully decoding a real SDK LoggingLevel at either input.
|
||||
pub(crate) fn sdk_logging_level_parsed() {
|
||||
increment(|counters| &counters.sdk_logging_level);
|
||||
}
|
||||
|
||||
/// Mark only after serializing real SDK LoggingMessageNotificationParam params, not an envelope.
|
||||
pub(crate) fn sdk_logging_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_logging_notification);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_logging_runtime_tests.rs"]
|
||||
mod rmcp_logging_runtime_tests;
|
||||
|
||||
/// Mark only after successfully serializing real SDK ProgressNotificationParam params.
|
||||
pub(crate) fn sdk_progress_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_progress_notification);
|
||||
}
|
||||
|
||||
/// Mark successful SDK CancelledNotificationParam decoding, not successful cancellation.
|
||||
pub(crate) fn sdk_cancelled_params_decoded() {
|
||||
increment(|counters| &counters.sdk_cancelled_params);
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -24,7 +24,9 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
@@ -37,8 +39,7 @@ use crate::{
|
||||
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
|
||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_logging_command,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -143,13 +144,18 @@ pub(super) async fn handle_legacy_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, &session.protocol_version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
@@ -278,7 +284,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resources_list_result(resources, next_cursor),
|
||||
match resources_list_result(
|
||||
resources,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -335,7 +348,13 @@ pub(super) async fn handle_legacy_request(
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
match resource_read_result(contents, &session.protocol_version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
@@ -394,7 +413,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
@@ -425,7 +444,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
match resource_templates_list_result(
|
||||
templates,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -458,7 +484,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
@@ -480,7 +506,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
match prompts_list_result(prompts, next_cursor) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -520,7 +549,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
let outcome = super::rmcp_dispatch::handle_prompts_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
@@ -542,7 +571,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
prompt_get_result(description, messages),
|
||||
match prompt_get_result(description, messages) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -615,7 +647,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
let outcome = super::rmcp_dispatch::handle_completion_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
@@ -767,27 +799,24 @@ async fn handle_cancelled_notification(
|
||||
message: &Value,
|
||||
credential: &VerifiedMachineCredential,
|
||||
) -> Response {
|
||||
let request_id = params(message).get("requestId").cloned();
|
||||
let request_id = super::rmcp_progress_cancel::decode_cancelled_request_id(¶ms(message));
|
||||
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
||||
// Only a string or a number is a pinned `RequestId`; anything else cannot name a call.
|
||||
if matches!(request_id, Value::String(_) | Value::Number(_)) {
|
||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned_by_session {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id,
|
||||
owner: in_flight_owner(credential),
|
||||
},
|
||||
&request_id,
|
||||
);
|
||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned_by_session {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id,
|
||||
owner: in_flight_owner(credential),
|
||||
},
|
||||
&request_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
|
||||
@@ -34,6 +34,7 @@ use axum::{
|
||||
};
|
||||
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
||||
use futures_util::stream;
|
||||
use rmcp::model::{NumberOrString, ProgressNotificationParam};
|
||||
use serde_json::{Number, Value, json};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
@@ -82,10 +83,13 @@ impl ProgressToken {
|
||||
}
|
||||
}
|
||||
|
||||
fn as_value(&self) -> Value {
|
||||
fn sdk_token(&self) -> NumberOrString {
|
||||
match self {
|
||||
Self::Text(text) => Value::String(text.clone()),
|
||||
Self::Number(number) => Value::Number(number.clone()),
|
||||
Self::Text(text) => NumberOrString::String(text.clone().into()),
|
||||
Self::Number(number) => number.as_i64().map_or_else(
|
||||
|| NumberOrString::String(number.to_string().into()),
|
||||
NumberOrString::Number,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,14 +136,24 @@ pub(crate) struct ProgressEvent {
|
||||
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
|
||||
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
|
||||
pub(super) fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
||||
let sdk_params = ProgressNotificationParam::new(
|
||||
rmcp::model::ProgressToken(token.sdk_token()),
|
||||
event.progress as f64,
|
||||
)
|
||||
.with_message(event.message);
|
||||
let mut params = serde_json::to_value(sdk_params)
|
||||
.expect("finite progress and string/number token are serializable SDK params");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_progress_notification_serialized();
|
||||
// SDK uses i64 tokens and f64 progress; restore the original JSON numbers before wire delivery.
|
||||
if let ProgressToken::Number(number) = token {
|
||||
params["progressToken"] = Value::Number(number.clone());
|
||||
}
|
||||
params["progress"] = Value::from(event.progress);
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/progress",
|
||||
"params": {
|
||||
"progressToken": token.as_value(),
|
||||
"progress": event.progress,
|
||||
"message": event.message,
|
||||
}
|
||||
"params": params,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,44 @@ fn token(value: Value) -> Option<ProgressToken> {
|
||||
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
||||
for wire_token in [
|
||||
"\"token\"",
|
||||
"-7",
|
||||
"1.5",
|
||||
"1.0",
|
||||
"-0.0",
|
||||
"18446744073709551615",
|
||||
] {
|
||||
let value: Value = serde_json::from_str(wire_token).unwrap();
|
||||
for progress in [2, 9_007_199_254_740_993, u64::MAX] {
|
||||
let frame = progress_frame(
|
||||
&token(value.clone()).unwrap(),
|
||||
&ProgressEvent {
|
||||
progress,
|
||||
message: "execution_dispatched",
|
||||
},
|
||||
);
|
||||
assert_eq!(frame["params"]["progressToken"].to_string(), wire_token);
|
||||
assert_eq!(
|
||||
frame["params"]["progress"].to_string(),
|
||||
progress.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
frame["params"],
|
||||
json!({
|
||||
"progressToken": value, "progress": progress, "message": "execution_dispatched"
|
||||
})
|
||||
);
|
||||
assert!(frame["params"].get("total").is_none());
|
||||
assert!(frame["params"].get("_meta").is_none());
|
||||
assert_eq!(frame["jsonrpc"], "2.0");
|
||||
assert_eq!(frame["method"], "notifications/progress");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use rmcp::model::{CacheScope, CallToolResult, ContentBlock, ListToolsResult, ResultType, Tool};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{jsonrpc_result, request_id},
|
||||
protocol::project_modern_result,
|
||||
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
@@ -30,22 +30,7 @@ pub(super) fn success_tool_payload(
|
||||
protocol_version: &str,
|
||||
output: Value,
|
||||
) -> Value {
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_success_tool_result(output))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -69,85 +54,273 @@ pub(super) fn tool_error_payload(
|
||||
protocol_version: &str,
|
||||
error: ToolErrorContract,
|
||||
) -> Value {
|
||||
let error_message = tool_error_text(&error);
|
||||
let error_value = tool_error_value(&error);
|
||||
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_error_tool_result(error))
|
||||
}
|
||||
|
||||
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
||||
/// up byte-lexicographically ordered, exactly as before the extraction.
|
||||
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "tools": tools });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
pub(super) fn sdk_success_tool_result(output: Value) -> CallToolResult {
|
||||
let text = serde_json::to_string_pretty(&output).expect("JSON value serializes");
|
||||
let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
|
||||
result.structured_content = Some(output);
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/list` result shape (Story 3.8). Same pagination wire keys as
|
||||
/// `tools/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn resources_list_result(resources: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "resources": resources });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
pub(super) fn sdk_error_tool_result(error: ToolErrorContract) -> CallToolResult {
|
||||
let mut result = CallToolResult::error(vec![ContentBlock::text(tool_error_text(&error))]);
|
||||
result.structured_content = Some(json!({ "error": tool_error_value(&error) }));
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/read` result shape: exactly the typed `contents[]` the revision
|
||||
/// converter produced.
|
||||
pub(super) fn resource_read_result(contents: Value) -> Value {
|
||||
json!({ "contents": contents })
|
||||
fn call_result_payload(message: &Value, version: &str, mut result: CallToolResult) -> Value {
|
||||
result.result_type =
|
||||
(version == crate::jsonrpc::MODERN_PROTOCOL_VERSION).then_some(ResultType::COMPLETE);
|
||||
let result = serde_json::to_value(result).expect("SDK call result contains JSON values");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_call_result_serialized();
|
||||
jsonrpc_result(request_id(message), result)
|
||||
}
|
||||
|
||||
pub(super) fn sdk_tools_list_result(
|
||||
tools: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<ListToolsResult, serde_json::Error> {
|
||||
Ok(ListToolsResult {
|
||||
tools: tools
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Serialize the SDK model, preserving catalog extensions that pinned Tool serde cannot represent.
|
||||
pub(super) fn tools_list_result(
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result = sdk_tools_list_result(&tools, next_cursor)?;
|
||||
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)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_list_result_serialized();
|
||||
for (raw, serialized) in tools
|
||||
.iter()
|
||||
.zip(result["tools"].as_array_mut().expect("SDK tools array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK Tool object");
|
||||
for (key, value) in raw.as_object().expect("validated Tool object") {
|
||||
if matches!(key.as_str(), "annotations" | "icons")
|
||||
|| !matches!(
|
||||
key.as_str(),
|
||||
"name" | "title" | "description" | "inputSchema" | "outputSchema" | "_meta"
|
||||
)
|
||||
|| value.is_null()
|
||||
{
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// SDK results are serialized before the minimal lossless projection of descriptor extensions.
|
||||
pub(super) fn resources_list_result(
|
||||
resources: Vec<Value>,
|
||||
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)?;
|
||||
#[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)
|
||||
}
|
||||
|
||||
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)?;
|
||||
#[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)
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/templates/list` result shape.
|
||||
pub(super) fn resource_templates_list_result(
|
||||
templates: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Value {
|
||||
let mut result = json!({ "resourceTemplates": templates });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
}
|
||||
result
|
||||
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)?;
|
||||
#[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)
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/list` result shape (Story 3.14). Same pagination wire keys as
|
||||
/// `resources/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn prompts_list_result(prompts: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "prompts": prompts });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/get` result shape: the rendered `messages[]` and the description of the
|
||||
/// exact bound Published Prompt Version it came from.
|
||||
pub(super) fn prompt_get_result(description: Option<String>, messages: Vec<Value>) -> Value {
|
||||
let mut result = json!({ "messages": messages });
|
||||
if let Some(description) = description {
|
||||
result["description"] = Value::String(description);
|
||||
/// 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"],
|
||||
);
|
||||
}
|
||||
}
|
||||
result
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_list_result_serialized();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Preserve Crank's system role, which the pinned SDK's user/assistant Role cannot express.
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_prompts_get_result_serialized();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `completion/complete` result shape (Story 3.17): the bounded `values[]`, the
|
||||
@@ -158,14 +331,18 @@ pub(super) fn completion_result(
|
||||
total: Option<usize>,
|
||||
has_more: bool,
|
||||
) -> Value {
|
||||
let mut completion = json!({ "values": values });
|
||||
if let Some(total) = total {
|
||||
completion["total"] = json!(total);
|
||||
}
|
||||
if has_more {
|
||||
completion["hasMore"] = json!(true);
|
||||
}
|
||||
json!({ "completion": completion })
|
||||
let mut completion = rmcp::model::CompletionInfo::default();
|
||||
completion.values = values;
|
||||
// The domain scans at most 1024 candidates, so its exact count fits the SDK's u32.
|
||||
completion.total = total.map(|total| u32::try_from(total).expect("bounded completion count"));
|
||||
completion.has_more = has_more.then_some(true);
|
||||
let mut result = rmcp::model::CompleteResult::new(completion);
|
||||
// Keep the shared result era-neutral; the existing caller projects modern resultType.
|
||||
result.result_type = None;
|
||||
let result = serde_json::to_value(result).expect("SDK completion contains strings and counts");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_completion_result_serialized();
|
||||
result
|
||||
}
|
||||
|
||||
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
|
||||
@@ -310,3 +487,195 @@ pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Dis
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sdk_result_tests {
|
||||
use super::*;
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
#[test]
|
||||
fn prompts_sdk_projection_preserves_typed_extensions_and_system_content() {
|
||||
let prompt = json!({"name":"p", "description":null, "icons":null,
|
||||
"x-prompt":{}, "arguments":[{"name":"count", "description":null,
|
||||
"required":false, "schema":{"type":"integer"}, "default":7}]});
|
||||
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
||||
let result = prompts_list_result(vec![prompt.clone()], cursor.clone()).unwrap();
|
||||
assert_eq!(result["prompts"], json!([prompt]));
|
||||
assert_eq!(result.get("nextCursor"), cursor.map(Value::String).as_ref());
|
||||
assert!(result.get("resultType").is_none());
|
||||
}
|
||||
let messages = vec![
|
||||
json!({"role":"system", "x-message":null,
|
||||
"content":{"type":"text", "text":"\0é\n", "annotations":null, "x-content":[]}}),
|
||||
json!({"role":"assistant", "content":{"type":"text", "text":""}}),
|
||||
];
|
||||
assert_eq!(
|
||||
prompt_get_result(None, messages.clone()).unwrap(),
|
||||
json!({"messages":messages})
|
||||
);
|
||||
assert_eq!(
|
||||
prompts_list_result(vec![], None).unwrap(),
|
||||
json!({"prompts":[]})
|
||||
);
|
||||
assert_eq!(
|
||||
prompt_get_result(Some(String::new()), vec![]).unwrap(),
|
||||
json!({"description":"", "messages":[]})
|
||||
);
|
||||
assert!(prompts_list_result(vec![json!({"name":42})], None).is_err());
|
||||
assert!(
|
||||
prompt_get_result(
|
||||
None,
|
||||
vec![json!({"role":"invalid", "content":{"type":"text", "text":"secret"}})]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_sdk_projection_is_lossless_for_templates_contents_and_catalog() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for optional in [Value::Null, json!({}), json!({"x-extension":[null,{}]})] {
|
||||
let raw = json!({"uri":"crank://r","name":"r","description":null,
|
||||
"mimeType":"text/plain","_meta":optional,"x-resource":[],
|
||||
"annotations":{"x-nested":null},"icons":[{"src":"icon","x-icon":{}}]});
|
||||
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
||||
let list =
|
||||
resources_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(list["resources"], json!([raw]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert!(list.get("_meta").is_none());
|
||||
let template = json!({"uriTemplate":"crank://r/{id}","name":"r",
|
||||
"description":null,"mimeType":null,"_meta":optional,
|
||||
"parameters":[{"name":"id","required":true,"opaque":null}],
|
||||
"annotations":{"x-nested":[]},"icons":null});
|
||||
let list = resource_templates_list_result(
|
||||
vec![template.clone()],
|
||||
cursor.clone(),
|
||||
version,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(list["resourceTemplates"], json!([template]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
}
|
||||
let contents = json!([
|
||||
{"uri":"crank://r","mimeType":null,"text":"\0é\n","_meta":optional,"x-content":[]},
|
||||
{"uri":"crank://b","mimeType":"application/octet-stream","blob":"AP8=","_meta":null}
|
||||
]);
|
||||
assert_eq!(
|
||||
resource_read_result(contents.clone(), version).unwrap()["contents"],
|
||||
contents
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resources_list_result(vec![], None, version).unwrap()["resources"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_templates_list_result(vec![], None, version).unwrap()["resourceTemplates"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_read_result(json!([]), version).unwrap()["contents"],
|
||||
json!([])
|
||||
);
|
||||
assert!(resources_list_result(vec![json!({"uri":42})], None, version).is_err());
|
||||
assert!(
|
||||
resource_templates_list_result(vec![json!({"name":"r"})], None, version).is_err()
|
||||
);
|
||||
assert!(resource_read_result(json!([{"uri":"r"}]), version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_projection_preserves_extensions_null_and_empty() {
|
||||
let descriptor = json!({
|
||||
"name":"tool", "title":"", "description":null,
|
||||
"inputSchema":{"type":"object", "x-schema":{"nested":null}},
|
||||
"outputSchema":{"type":"object", "x-output":[]},
|
||||
"_meta":{"custom":{"empty":{}}}, "x-tool":{"nested":[]},
|
||||
"annotations":{"readOnlyHint":true,"x-annotation":{"nested":null}},
|
||||
"icons":[{"src":"https://example.test/icon", "x-icon":{"nested":[]}}]
|
||||
});
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for raw in [
|
||||
descriptor.clone(),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"title":null,"description":"","outputSchema":null,"_meta":null,
|
||||
"annotations":null,"icons":null}),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"annotations":{},"icons":[]}),
|
||||
] {
|
||||
for cursor in [None, Some(String::new()), Some("next".to_owned())] {
|
||||
let value =
|
||||
tools_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(value["tools"], json!([raw]));
|
||||
assert_eq!(
|
||||
value.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| Value::String(s.clone())).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
tools_list_result(vec![], None, version).unwrap()["tools"],
|
||||
json!([])
|
||||
);
|
||||
assert!(tools_list_result(vec![json!({"name":42})], None, version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_success_and_rpc_failures_keep_their_distinct_shapes() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
let message = json!({"id":9007199254740993_u64});
|
||||
let payload = success_tool_payload(&message, version, Value::Null);
|
||||
assert_eq!(payload["id"], message["id"]);
|
||||
assert_eq!(
|
||||
payload["result"]["content"],
|
||||
json!([{"type":"text","text":"null"}])
|
||||
);
|
||||
assert_eq!(
|
||||
payload["result"].get("structuredContent"),
|
||||
Some(&Value::Null)
|
||||
);
|
||||
assert_eq!(payload["result"]["isError"], false);
|
||||
let correlation = CorrelationContext::generate();
|
||||
let internal = tool_command_payload(
|
||||
&message,
|
||||
version,
|
||||
&correlation,
|
||||
ToolsOutcome::Call(ToolCallOutcome::InternalFailure),
|
||||
);
|
||||
assert!(matches!(internal, ToolCommandPayload::Internal(_)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Runtime SDK Tools dispatch; admission, lifecycle and response projection stay with the caller.
|
||||
//! Runtime SDK dispatch; admission, lifecycle and response projection stay with the caller.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams};
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, ReadResourceRequestParams};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle};
|
||||
@@ -65,3 +65,117 @@ pub(super) async fn handle_tools_command(
|
||||
};
|
||||
crate::protocol::handle_tools_command(state, context, command, lifecycle).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_prompts_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
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
|
||||
}
|
||||
|
||||
pub(super) async fn handle_resources_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
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
|
||||
}
|
||||
|
||||
pub(super) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
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
|
||||
}
|
||||
|
||||
pub(super) async fn handle_completion_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Lossless projection of legacy cancellation targets through the pinned SDK.
|
||||
|
||||
use rmcp::model::CancelledNotificationParam;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn decode_cancelled_request_id(params: &Value) -> Option<Value> {
|
||||
let mut projection = Map::new();
|
||||
let original_id = params.get("requestId");
|
||||
if let Some(id) = original_id {
|
||||
// SDK IDs use i64; the temporary string never reaches the in-flight lookup.
|
||||
let projected = match id {
|
||||
Value::Number(number) if number.as_i64().is_none() => Value::String(number.to_string()),
|
||||
_ => id.clone(),
|
||||
};
|
||||
projection.insert("requestId".to_owned(), projected);
|
||||
}
|
||||
// Only requestId names a target; reason, _meta and extensions retain their ignore semantics.
|
||||
let decoded =
|
||||
serde_json::from_value::<CancelledNotificationParam>(Value::Object(projection)).ok()?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_params_decoded();
|
||||
let id = decoded.request_id?;
|
||||
Some(match original_id {
|
||||
Some(Value::Number(number)) => Value::Number(number.clone()),
|
||||
_ => id.into_json_value(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_progress_cancel_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,52 @@
|
||||
use super::decode_cancelled_request_id;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn rmcp_progress_cancel_decoder_preserves_exact_ids_and_ignores_other_fields() {
|
||||
for wire_id in [
|
||||
"\"7\"",
|
||||
"7",
|
||||
"-7",
|
||||
"1.5",
|
||||
"1.0",
|
||||
"-0.0",
|
||||
"18446744073709551615",
|
||||
"\"\"",
|
||||
"\"line\\nbreak\"",
|
||||
] {
|
||||
let id: Value = serde_json::from_str(wire_id).unwrap();
|
||||
let params = json!({
|
||||
"requestId": id, "reason": 42, "_meta": [], "unknown": {"nested": [true]}
|
||||
});
|
||||
let decoded = decode_cancelled_request_id(¶ms).unwrap();
|
||||
assert_eq!(decoded.to_string(), wire_id);
|
||||
}
|
||||
let long_id = Value::String("x".repeat(1024));
|
||||
assert_eq!(
|
||||
decode_cancelled_request_id(&json!({"requestId": long_id})),
|
||||
Some(long_id)
|
||||
);
|
||||
assert_ne!(
|
||||
decode_cancelled_request_id(&json!({"requestId": "7"})),
|
||||
decode_cancelled_request_id(&json!({"requestId": 7}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rmcp_progress_cancel_decoder_has_no_target_for_invalid_or_missing_ids() {
|
||||
for params in [
|
||||
json!(null),
|
||||
json!(true),
|
||||
json!(7),
|
||||
json!("requestId"),
|
||||
json!([]),
|
||||
json!({}),
|
||||
json!({"requestId": null}),
|
||||
json!({"requestId": true}),
|
||||
json!({"requestId": []}),
|
||||
json!({"requestId": {}}),
|
||||
json!({"reason": "ignored", "_meta": []}),
|
||||
] {
|
||||
assert_eq!(decode_cancelled_request_id(¶ms), None, "{params}");
|
||||
}
|
||||
}
|
||||
@@ -90,10 +90,7 @@ impl RmcpTools {
|
||||
}
|
||||
}
|
||||
use rmcp::ErrorData as McpError;
|
||||
use rmcp::model::{
|
||||
CallToolRequestParams, CallToolResult, ContentBlock, ListToolsResult, PaginatedRequestParams,
|
||||
Tool,
|
||||
};
|
||||
use rmcp::model::{CallToolRequestParams, ListToolsResult, PaginatedRequestParams};
|
||||
use rmcp::service::RequestContext;
|
||||
use rmcp::{RoleServer, ServerHandler};
|
||||
|
||||
@@ -138,18 +135,8 @@ impl ServerHandler for RmcpTools {
|
||||
};
|
||||
match self.list_tools(&identity, command, None).await {
|
||||
crate::protocol::ToolsOutcome::List { tools, next_cursor } => {
|
||||
let tools = tools
|
||||
.into_iter()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| {
|
||||
McpError::internal_error("invalid tool catalog entry", None)
|
||||
})?;
|
||||
Ok(ListToolsResult {
|
||||
tools,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
super::response::sdk_tools_list_result(&tools, next_cursor)
|
||||
.map_err(|_| McpError::internal_error("invalid tool catalog entry", None))
|
||||
}
|
||||
crate::protocol::ToolsOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
@@ -223,27 +210,24 @@ impl ServerHandler for RmcpTools {
|
||||
crate::protocol::ToolsOutcome::Call(outcome) => match outcome {
|
||||
crate::protocol::ToolCallOutcome::Completed(value)
|
||||
| crate::protocol::ToolCallOutcome::ApprovalPending(value) => {
|
||||
let text = value.to_string();
|
||||
let mut result = CallToolResult::default();
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
result.structured_content = if value.is_null() { None } else { Some(value) };
|
||||
Ok(result.into())
|
||||
Ok(super::response::sdk_success_tool_result(value).into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(_) => {
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text("approval elicitation not supported")];
|
||||
Ok(result.into())
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(error) => {
|
||||
Ok(super::response::sdk_error_tool_result(
|
||||
crate::tool_error::control_tool_error_contract(
|
||||
error,
|
||||
identity.correlation.request_id().as_str(),
|
||||
identity.correlation.trace_id().as_str(),
|
||||
identity.locale,
|
||||
),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::Error(contract) => {
|
||||
let text = serde_json::to_string(&contract).unwrap_or_default();
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
Ok(result.into())
|
||||
Ok(super::response::sdk_error_tool_result(contract).into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InternalFailure => {
|
||||
Err(McpError::internal_error("tool execution failed", None))
|
||||
|
||||
@@ -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,99 @@
|
||||
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
||||
|
||||
use rmcp::model::{
|
||||
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
|
||||
ProtocolVersion, ServerCapabilities,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::advertised_server_capabilities;
|
||||
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
|
||||
|
||||
pub(crate) fn initialize_params(
|
||||
params: &Value,
|
||||
) -> Result<InitializeRequestParams, serde_json::Error> {
|
||||
// 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 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);
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ use std::{
|
||||
sync::{Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
// Both pinned revisions still require logging despite the SDK's SEP-2577 deprecation.
|
||||
#[allow(deprecated)]
|
||||
use rmcp::model::{LoggingLevel, LoggingMessageNotificationParam, SetLevelRequestParams};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use tokio::task_local;
|
||||
@@ -61,7 +64,8 @@ pub(crate) enum LogLevel {
|
||||
}
|
||||
|
||||
impl LogLevel {
|
||||
/// The exact wire literal of this level.
|
||||
/// The exact wire literal of this level (contract assertions only; runtime uses SDK serde).
|
||||
#[cfg(test)]
|
||||
pub(crate) const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Debug => "debug",
|
||||
@@ -80,17 +84,47 @@ impl LogLevel {
|
||||
/// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that
|
||||
/// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type
|
||||
/// says and what `InvalidParamsError` is for.
|
||||
#[allow(deprecated)]
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"debug" => Some(Self::Debug),
|
||||
"info" => Some(Self::Info),
|
||||
"notice" => Some(Self::Notice),
|
||||
"warning" => Some(Self::Warning),
|
||||
"error" => Some(Self::Error),
|
||||
"critical" => Some(Self::Critical),
|
||||
"alert" => Some(Self::Alert),
|
||||
"emergency" => Some(Self::Emergency),
|
||||
_ => None,
|
||||
if value.len() > MAX_LEVEL_BYTES {
|
||||
return None;
|
||||
}
|
||||
let level: LoggingLevel = serde_json::from_value(Value::String(value.to_owned())).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_logging_level_parsed();
|
||||
Some(level.into())
|
||||
}
|
||||
}
|
||||
|
||||
// Keep domain severity ordering independent of SDK enum discriminants (which have no Ord).
|
||||
#[allow(deprecated)]
|
||||
impl From<LoggingLevel> for LogLevel {
|
||||
fn from(level: LoggingLevel) -> Self {
|
||||
match level {
|
||||
LoggingLevel::Debug => Self::Debug,
|
||||
LoggingLevel::Info => Self::Info,
|
||||
LoggingLevel::Notice => Self::Notice,
|
||||
LoggingLevel::Warning => Self::Warning,
|
||||
LoggingLevel::Error => Self::Error,
|
||||
LoggingLevel::Critical => Self::Critical,
|
||||
LoggingLevel::Alert => Self::Alert,
|
||||
LoggingLevel::Emergency => Self::Emergency,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl From<LogLevel> for LoggingLevel {
|
||||
fn from(level: LogLevel) -> Self {
|
||||
match level {
|
||||
LogLevel::Debug => Self::Debug,
|
||||
LogLevel::Info => Self::Info,
|
||||
LogLevel::Notice => Self::Notice,
|
||||
LogLevel::Warning => Self::Warning,
|
||||
LogLevel::Error => Self::Error,
|
||||
LogLevel::Critical => Self::Critical,
|
||||
LogLevel::Alert => Self::Alert,
|
||||
LogLevel::Emergency => Self::Emergency,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,11 +169,20 @@ pub(crate) struct SetLevelCommand {
|
||||
impl SetLevelCommand {
|
||||
/// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a
|
||||
/// malformed or oversized value is refused with bounded work and one safe detail.
|
||||
pub(crate) fn validate(&self) -> Result<LogLevel, &'static str> {
|
||||
#[allow(deprecated)]
|
||||
pub(crate) fn validate(&self) -> Result<SetLevelRequestParams, &'static str> {
|
||||
if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES {
|
||||
return Err(INVALID_LEVEL);
|
||||
}
|
||||
LogLevel::parse(&self.level).ok_or(INVALID_LEVEL)
|
||||
// Only level was part of the old command: unknown members (including _meta) stay ignored.
|
||||
let request =
|
||||
serde_json::from_value(json!({"level": self.level})).map_err(|_| INVALID_LEVEL)?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::app::dispatch_observer::sdk_logging_level_parsed();
|
||||
crate::app::dispatch_observer::sdk_logging_dispatch_enter();
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,19 +325,22 @@ pub(crate) fn take_notifications() -> Vec<Value> {
|
||||
}
|
||||
std::mem::take(&mut log.pending)
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
json!({
|
||||
.filter_map(|event| {
|
||||
#[allow(deprecated)]
|
||||
let params = LoggingMessageNotificationParam::new(
|
||||
event.level.into(),
|
||||
json!({"event": event.event, "outcome": event.outcome}),
|
||||
)
|
||||
.with_logger(LOGGER_NAME);
|
||||
// Logging remains best-effort: a serialization failure drops only this event.
|
||||
let params = serde_json::to_value(params).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_logging_notification_serialized();
|
||||
Some(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": event.level.as_str(),
|
||||
"logger": LOGGER_NAME,
|
||||
"data": {
|
||||
"event": event.event,
|
||||
"outcome": event.outcome,
|
||||
}
|
||||
}
|
||||
})
|
||||
"params": params,
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -354,7 +400,9 @@ pub(crate) fn handle_logging_command(
|
||||
command: SetLevelCommand,
|
||||
) -> LoggingOutcome {
|
||||
match command.validate() {
|
||||
Ok(level) => {
|
||||
Ok(request) => {
|
||||
#[allow(deprecated)]
|
||||
let level = request.level.into();
|
||||
store.set(session_id, level);
|
||||
LoggingOutcome::Applied(level)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ use super::*;
|
||||
/// is malformed (which the adapter answers with the same safe detail).
|
||||
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
|
||||
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
|
||||
Some(command.validate())
|
||||
#[allow(deprecated)]
|
||||
Some(command.validate().map(|request| request.level.into()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -291,8 +292,11 @@ fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
|
||||
fn the_command_records_the_level_of_its_own_session_only() {
|
||||
let store = LogLevelStore::new();
|
||||
store.set("other-session", LogLevel::Debug);
|
||||
let command: SetLevelCommand =
|
||||
serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses");
|
||||
// Unknown members were ignored by the legacy command; SDK metadata must not narrow that wire.
|
||||
let command: SetLevelCommand = serde_json::from_value(json!({
|
||||
"level": "critical", "_meta": 7, "unknown": {"private": "ignored"}
|
||||
}))
|
||||
.expect("a pinned level parses regardless of unknown members");
|
||||
let outcome = handle_logging_command(&store, "this-session", command);
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
|
||||
@@ -26,6 +26,7 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod lifecycle_sdk;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
@@ -36,7 +37,11 @@ pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
};
|
||||
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
||||
pub(crate) use completion::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
handle_completion_command,
|
||||
};
|
||||
pub(crate) use lifecycle_sdk::{discover_result, initialize_params, initialize_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,
|
||||
@@ -841,20 +846,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"
|
||||
})
|
||||
}
|
||||
@@ -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,345 @@
|
||||
//! #107 Completion: real build_app HTTP wire controls and a separate SDK-path oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_completion_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, c)| async move {
|
||||
observe(c.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, c)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_completion_dispatch(), c.sdk_completion_result()]
|
||||
}
|
||||
fn params(reference: Value, name: &str, value: &str) -> Value {
|
||||
json!({"ref":reference,"argument":{"name":name,"value":value}})
|
||||
}
|
||||
fn prompt(name: &str) -> Value {
|
||||
json!({"type":"ref/prompt","name":name})
|
||||
}
|
||||
fn resource(uri: &str) -> Value {
|
||||
json!({"type":"ref/resource","uri":uri})
|
||||
}
|
||||
fn request(revision: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":"completion/complete","params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-completion-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|f| f.get("id") == Some(&json!(9007199254740993_u64)))
|
||||
.collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(body["id"], json!(9007199254740993_u64));
|
||||
body
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
p: Value,
|
||||
sse: bool,
|
||||
) -> (Value, [usize; 2]) {
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
let result = &body["result"];
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{body}");
|
||||
} else {
|
||||
assert!(result.get("resultType").is_none(), "{body}");
|
||||
}
|
||||
for key in ["ttlMs", "cacheScope", "_meta"] {
|
||||
assert!(result.get(key).is_none(), "{body}");
|
||||
}
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
result["completion"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let modes: &[bool] = if revision == MODERN_REVISION {
|
||||
&[false, true]
|
||||
} else {
|
||||
&[false]
|
||||
};
|
||||
let mut deltas = Vec::new();
|
||||
for &sse in modes {
|
||||
for (p, expected) in [
|
||||
(
|
||||
params(prompt("greeting"), "tone", ""),
|
||||
json!({"values":["warm","dry"],"total":2}),
|
||||
),
|
||||
(
|
||||
params(prompt("archived-prompt"), "tone", "W"),
|
||||
json!({"values":["warm"],"total":1}),
|
||||
),
|
||||
(
|
||||
params(prompt("greeting"), "name", "A"),
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", ""),
|
||||
json!({"values":["eu","us","apac"],"total":3}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", "A"),
|
||||
json!({"values":["apac"],"total":1}),
|
||||
),
|
||||
(
|
||||
params(resource(URI), "region", "zzz"),
|
||||
json!({"values":[],"total":0}),
|
||||
),
|
||||
] {
|
||||
let (completion, delta) = success(&h, revision, session, p, sse).await;
|
||||
assert_eq!(completion, expected);
|
||||
deltas.push(delta);
|
||||
}
|
||||
for (uri, total) in [(BOUNDED_URI, Some(150)), (LARGE_URI, None)] {
|
||||
let (completion, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
params(resource(uri), "region", "item"),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
completion["values"],
|
||||
json!((0..100).map(|i| format!("item{i:04}")).collect::<Vec<_>>())
|
||||
);
|
||||
assert_eq!(completion["hasMore"], true);
|
||||
if let Some(total) = total {
|
||||
assert_eq!(completion["total"], total);
|
||||
} else {
|
||||
assert!(
|
||||
completion.get("total").is_none(),
|
||||
"partial scan: {completion}"
|
||||
);
|
||||
}
|
||||
deltas.push(delta);
|
||||
}
|
||||
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;
|
||||
assert_eq!(completion, json!({"values":["warm"],"total":1}));
|
||||
deltas.push(delta);
|
||||
let mut unavailable = None;
|
||||
for p in [
|
||||
params(prompt("draft-prompt"), "tone", ""),
|
||||
params(prompt("unbound-prompt"), "tone", ""),
|
||||
params(prompt("other-agent-prompt"), "tone", ""),
|
||||
params(prompt("never-existed"), "tone", ""),
|
||||
params(prompt("changed-draft"), "tone", ""),
|
||||
params(prompt("greeting"), "unknown-argument", ""),
|
||||
params(resource("crank://foreign/{region}"), "region", ""),
|
||||
params(resource(URI), "unknown-parameter", ""),
|
||||
] {
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"the completion reference is not available"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
if let Some(ref previous) = unavailable {
|
||||
assert_eq!(&body, previous);
|
||||
}
|
||||
unavailable = Some(body);
|
||||
}
|
||||
let mut invalid = vec![
|
||||
json!({"argument":{"name":"tone","value":""}}),
|
||||
params(json!({"type":"ref/tool","name":"greeting"}), "tone", ""),
|
||||
params(prompt("greeting"), "tone", &"s".repeat(1025)),
|
||||
params(prompt("greeting"), &"n".repeat(129), ""),
|
||||
];
|
||||
// Preserve domain validation on arbitrary JSON, never drop or stringify context values for SDK.
|
||||
for value in [
|
||||
json!(7),
|
||||
json!(true),
|
||||
json!(null),
|
||||
json!(["eu"]),
|
||||
json!({"region":"eu"}),
|
||||
json!("s".repeat(1025)),
|
||||
] {
|
||||
let mut p = params(prompt("greeting"), "tone", "");
|
||||
p["context"] = json!({"arguments":{"secret-context":value}});
|
||||
invalid.push(p);
|
||||
}
|
||||
let mut p = params(prompt("greeting"), "tone", "");
|
||||
p["context"] = json!({"arguments":(0..33).map(|i| (format!("arg{i}"), json!("eu"))).collect::<serde_json::Map<_,_>>()});
|
||||
invalid.push(p);
|
||||
for p in invalid {
|
||||
let body = wire(
|
||||
h.post(revision, session, &request(revision, p), sse).await,
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"invalid completion/complete parameters"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
for leaked in ["secret-context", &"s".repeat(1025), &"n".repeat(129)] {
|
||||
assert!(!body.to_string().contains(leaked), "{body}");
|
||||
}
|
||||
}
|
||||
}
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = h.counters.snapshot();
|
||||
let sdk_before = counts(&h.counters);
|
||||
let response = h
|
||||
.post(
|
||||
revision,
|
||||
session,
|
||||
&request(revision, params(prompt("greeting"), "tone", "")),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 401);
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(
|
||||
counts(&h.counters),
|
||||
sdk_before,
|
||||
"revoked key must not dispatch to SDK"
|
||||
);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(after.era_modern, before.era_modern);
|
||||
assert_eq!(after.era_legacy, before.era_legacy);
|
||||
assert_eq!(after.tools_service, before.tools_service);
|
||||
eprintln!(
|
||||
"existing GREEN Completion HTTP {revision}: Prompt+Resource refs, exact bound v1/archive, prefix/empty/bounded/truncated, JSON/context/errors/correlation/auth; SDK actual={deltas:?}, expected=[1,1] per success"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 1]),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_completion_observer_scope_control() {
|
||||
use super::{sdk_completion_dispatch_enter, sdk_completion_result_serialized};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_completion_dispatch_enter();
|
||||
sdk_completion_result_serialized();
|
||||
assert_eq!(counts(&a), [0; 2]);
|
||||
let snapshot = a.snapshot();
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_completion_dispatch_enter();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_completion_result_serialized();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_completion_result_serialized();
|
||||
})
|
||||
);
|
||||
assert_eq!(counts(&a), [1, 1]);
|
||||
assert_eq!(counts(&b), [0, 1]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_completion_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(counts(&b), [0, 1], "body must be deferred");
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"data: terminal\n\n"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 2]);
|
||||
assert_eq!(counts(&a), [1, 1]);
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Completion HTTP fixture using the existing observed HTTP app and disposable PostgreSQL.
|
||||
use super::*;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use crank_core::{
|
||||
Agent, AgentStatus, AgentVersion, HttpMethod, RestTarget, Target, ToolSelectionPolicy,
|
||||
ids::PromptId,
|
||||
};
|
||||
use crank_registry::PostgresRegistry;
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
|
||||
pub(super) fn definition(name: &str, content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("completion_owner", "t_3fa1ad63").await;
|
||||
let registry = test_registry().await;
|
||||
publish_region_operation(®istry, "completion_lookup").await;
|
||||
for (id, uri, size) in [
|
||||
("res_completion_small", URI, 3),
|
||||
("res_completion_large", LARGE_URI, 1025),
|
||||
("res_completion_bounded", BOUNDED_URI, 150),
|
||||
] {
|
||||
publish_template(®istry, &ResourceId::new(id), uri, size).await;
|
||||
}
|
||||
let mut archived_at = test_time();
|
||||
for (id, name, publish) in [
|
||||
("prm_a", "greeting", true),
|
||||
("prm_b", "archived-prompt", true),
|
||||
("prm_c", "unbound-prompt", true),
|
||||
("prm_d", "draft-prompt", false),
|
||||
("prm_e", "other-agent-prompt", true),
|
||||
] {
|
||||
let row = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition(
|
||||
name,
|
||||
"Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}",
|
||||
),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if publish {
|
||||
let row = registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
expected_updated_at: row.updated_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if id == "prm_b" {
|
||||
archived_at = row.updated_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, slug) in [
|
||||
(agent_id(), AGENT_SLUG),
|
||||
(
|
||||
crank_core::AgentId::new("agent_other_prompts"),
|
||||
"other-prompts",
|
||||
),
|
||||
] {
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: slug.into(),
|
||||
display_name: "SDK Prompts".into(),
|
||||
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,
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let other_agent = crank_core::AgentId::new("agent_other_prompts");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_e"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_small"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_large"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_completion_bounded"),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: archived_at,
|
||||
archived_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// A mutable v2 draft must not change the bound v1 rendering or discovery metadata.
|
||||
let draft = registry
|
||||
.get_prompt_draft(&workspace_id(), &PromptId::new("prm_a"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition("changed-draft", "Changed {{name}}"),
|
||||
expected_updated_at: draft.updated_at,
|
||||
updated_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
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).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move { observe_body(next.run(request).await, counters) }
|
||||
}
|
||||
}));
|
||||
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,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-completion-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
|
||||
use crank_core::{ids::ResourceId, resource::TemplateSource};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::model::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
};
|
||||
use crank_registry::{AgentResourceBinding, PublishRequest};
|
||||
use sha2::{Digest, Sha256};
|
||||
pub(super) const URI: &str = "crank://completion-orders/{region}";
|
||||
pub(super) const LARGE_URI: &str = "crank://completion-large/{region}";
|
||||
pub(super) const BOUNDED_URI: &str = "crank://completion-bounded/{region}";
|
||||
async fn publish_region_operation(registry: &PostgresRegistry, name: &str) {
|
||||
let mut operation = test_operation("http://127.0.0.1:9");
|
||||
operation.id = crank_core::OperationId::new(format!("op_{name}"));
|
||||
operation.name = name.to_owned();
|
||||
operation.display_name = "Region lookup".to_owned();
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: "http://127.0.0.1:9".to_owned(),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/regions/{region}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("region");
|
||||
operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("region")
|
||||
.unwrap()
|
||||
.enum_values = vec!["eu".to_owned(), "us".to_owned(), "apac".to_owned()];
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.region".to_owned(),
|
||||
target: "$.request.path.region".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the Read Operation is created through the registry API");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &time::OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("the Read Operation exact version publishes");
|
||||
}
|
||||
|
||||
/// One published Resource template with an enumerated `region` parameter.
|
||||
async fn publish_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
uri_template: &str,
|
||||
size: usize,
|
||||
) {
|
||||
let operation_name = "completion_lookup";
|
||||
let options: Vec<String> = if size == 3 {
|
||||
vec!["eu".into(), "us".into(), "apac".into()]
|
||||
} else {
|
||||
(0..size).map(|i| format!("item{i:04}")).collect()
|
||||
};
|
||||
let definition = json!({
|
||||
"operation_id": format!("op_{operation_name}"),
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{
|
||||
"name": "region",
|
||||
"input_path": "input.region",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"enum_values": options
|
||||
}
|
||||
}],
|
||||
"cache": {"ttl_ms": 60_000, "vary": ["region"], "max_bytes": 65_536},
|
||||
"failure": {"outcome": "error"}
|
||||
});
|
||||
let source = TemplateSource::parse(&definition)
|
||||
.expect("the template fixture satisfies the Story 3.10 source contract");
|
||||
let definition_json =
|
||||
serde_json::to_string(&source).expect("the normalized definition serializes canonically");
|
||||
let digest = format!("{:x}", Sha256::digest(definition_json.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: format!("crank://templates/{}", resource_id.as_str()),
|
||||
name: format!("{}_template", resource_id.as_str()),
|
||||
description: "Bound completion fixture template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.clone(),
|
||||
definition_digest: digest.clone(),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the template Draft is created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the template exact version publishes");
|
||||
}
|
||||
@@ -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,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,258 @@
|
||||
//! #107 logging: existing HTTP wire control before the independent SDK marker assertions.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_logging_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
const LEVEL: &str = "io.modelcontextprotocol/logLevel";
|
||||
|
||||
fn counts(c: &CounterSet) -> [usize; 3] {
|
||||
[
|
||||
c.sdk_logging_dispatch(),
|
||||
c.sdk_logging_level(),
|
||||
c.sdk_logging_notification(),
|
||||
]
|
||||
}
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, c)| async move {
|
||||
observe(c.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, c)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn notification(level: &str, event: &str, outcome: &str) -> Value {
|
||||
json!({"jsonrpc":"2.0","method":"notifications/message","params":{
|
||||
"level":level,"logger":"crank-mcp-server","data":{"event":event,"outcome":outcome}}})
|
||||
}
|
||||
async fn reply(response: reqwest::Response) -> (Value, Vec<Value>, String) {
|
||||
let status = response.status();
|
||||
assert!(
|
||||
status == 200 || status == 404,
|
||||
"unexpected HTTP status {status}"
|
||||
);
|
||||
let sse = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream");
|
||||
let raw = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut frames: Vec<Value> = if sse {
|
||||
raw.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
vec![serde_json::from_str(&raw).unwrap()]
|
||||
};
|
||||
let terminal = frames.pop().expect("one terminal response");
|
||||
assert_eq!(terminal["jsonrpc"], "2.0");
|
||||
assert_eq!(terminal["id"], 51);
|
||||
assert_eq!(
|
||||
status.as_u16(),
|
||||
if terminal["error"]["code"] == -32601 {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
}
|
||||
);
|
||||
if !frames.is_empty() {
|
||||
assert!(sse, "notifications require SSE");
|
||||
}
|
||||
assert!(frames.iter().all(|f| f.get("id").is_none()));
|
||||
(terminal, frames, raw)
|
||||
}
|
||||
fn opted(level: Value) -> Value {
|
||||
let mut meta = modern_meta();
|
||||
meta[LEVEL] = level;
|
||||
json!({"_meta":meta})
|
||||
}
|
||||
async fn control(revision: &str) -> [usize; 3] {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
// Negative opt-in controls precede any accepted level; a silent response is not enough alone.
|
||||
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
assert!(events.is_empty());
|
||||
assert_eq!(counts(&h.counters), [0; 3]);
|
||||
if revision == MODERN_REVISION {
|
||||
for value in [
|
||||
json!("verbose"),
|
||||
json!(7),
|
||||
json!(null),
|
||||
json!("CANARY".repeat(1000)),
|
||||
] {
|
||||
let (body, events, _) =
|
||||
reply(h.post(revision, session, "tools/list", opted(value)).await).await;
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
assert!(events.is_empty());
|
||||
assert_eq!(counts(&h.counters), [0; 3]);
|
||||
}
|
||||
let (body, events, _) = reply(
|
||||
h.post(
|
||||
revision,
|
||||
session,
|
||||
"logging/setLevel",
|
||||
json!({"level":"notice"}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32601);
|
||||
assert!(events.is_empty());
|
||||
assert_eq!(counts(&h.counters), [0; 3]);
|
||||
} else {
|
||||
for params in [
|
||||
json!({}),
|
||||
json!({"level":7}),
|
||||
json!({"level":"CANARY".repeat(1000)}),
|
||||
] {
|
||||
let (body, events, raw) =
|
||||
reply(h.post(revision, session, "logging/setLevel", params).await).await;
|
||||
assert_eq!(body["error"]["code"], -32602);
|
||||
assert_eq!(body["error"]["message"], "invalid logging level");
|
||||
assert!(body.get("result").is_none());
|
||||
assert!(!raw.contains("CANARY"));
|
||||
assert!(raw.len() < 4096);
|
||||
assert!(events.is_empty());
|
||||
assert_eq!(h.counters.sdk_logging_level(), 0);
|
||||
assert_eq!(h.counters.sdk_logging_notification(), 0);
|
||||
}
|
||||
}
|
||||
let before = counts(&h.counters);
|
||||
let (method, params, expected) = if revision == LEGACY_REVISION {
|
||||
(
|
||||
"logging/setLevel",
|
||||
json!({"level":"notice"}),
|
||||
notification("notice", "mcp.logging.level_applied", "applied"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"tools/list",
|
||||
opted(json!("info")),
|
||||
notification("info", "mcp.request.served", "ok"),
|
||||
)
|
||||
};
|
||||
let (body, events, raw) = reply(h.post(revision, session, method, params).await).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
if revision == LEGACY_REVISION {
|
||||
assert_eq!(body["result"], json!({}));
|
||||
} else {
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
}
|
||||
assert_eq!(events, vec![expected]);
|
||||
assert!(raw.len() < 4096);
|
||||
let after = counts(&h.counters);
|
||||
let delta = std::array::from_fn(|i| after[i] - before[i]);
|
||||
// Legacy severity persists, modern opt-in does not leak into the next request.
|
||||
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
assert!(events.is_empty());
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = counts(&h.counters);
|
||||
let era = h.counters.snapshot();
|
||||
let response = h
|
||||
.post(
|
||||
revision,
|
||||
session,
|
||||
method,
|
||||
if revision == LEGACY_REVISION {
|
||||
json!({"level":"notice"})
|
||||
} else {
|
||||
opted(json!("info"))
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 401);
|
||||
let raw = response.text().await.unwrap();
|
||||
assert!(!raw.contains("notifications/message"));
|
||||
assert_eq!(counts(&h.counters), before);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(after.era_modern, era.era_modern);
|
||||
assert_eq!(after.era_legacy, era.era_legacy);
|
||||
eprintln!(
|
||||
"existing GREEN logging HTTP {revision}: safe SSE, result, opt-in/invalid/era/auth controls passed; SDK positive delta={delta:?}"
|
||||
);
|
||||
delta
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_sdk_legacy() {
|
||||
assert_eq!(
|
||||
control(LEGACY_REVISION).await,
|
||||
[1, 1, 1],
|
||||
"missing SDK legacy request/level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_sdk_modern() {
|
||||
assert_eq!(
|
||||
control(MODERN_REVISION).await,
|
||||
[0, 1, 1],
|
||||
"missing SDK modern level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_logging_dispatch_enter, sdk_logging_level_parsed, sdk_logging_notification_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_logging_dispatch_enter();
|
||||
sdk_logging_level_parsed();
|
||||
sdk_logging_notification_serialized();
|
||||
assert_eq!(counts(&a), [0; 3]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_logging_dispatch_enter();
|
||||
tokio::task::yield_now().await;
|
||||
sdk_logging_level_parsed();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_logging_notification_serialized();
|
||||
})
|
||||
);
|
||||
assert_eq!(counts(&a), [1, 1, 0]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_logging_notification_serialized();
|
||||
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), a.clone());
|
||||
assert_eq!(counts(&a), [1, 1, 0]);
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"data: terminal\n\n"
|
||||
);
|
||||
assert_eq!(counts(&a), [1, 1, 1]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Minimal logging HTTP fixture; shared registry/auth/lifecycle fixtures remain authoritative.
|
||||
use super::*;
|
||||
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 {
|
||||
crank_test_support::postgres_schema_url_for_task("logging_owner", "t_c28c3800").await;
|
||||
let registry = test_registry().await;
|
||||
let operation = test_operation("http://127.0.0.1:9");
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(crank_registry::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,
|
||||
Some("https://crank.example.com".into()),
|
||||
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 scope = counters.clone();
|
||||
let app = app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = scope.clone();
|
||||
async move {
|
||||
let response = observe(counters.clone(), next.run(request)).await;
|
||||
observe_body(response, counters)
|
||||
}
|
||||
},
|
||||
));
|
||||
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>,
|
||||
method: &str,
|
||||
mut params: Value,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "text/event-stream, application/json")
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", method);
|
||||
if params.get("_meta").is_none() {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
}
|
||||
request
|
||||
.json(&json!({"jsonrpc":"2.0", "id":51, "method":method, "params":params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(
|
||||
revision,
|
||||
None,
|
||||
"initialize",
|
||||
json!({"protocolVersion":revision,"capabilities":{}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
reply(response).await.0["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
let response = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.header("MCP-Protocol-Version", revision)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.json(&initialized_notification())
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
response.bytes().await.unwrap();
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Narrow #107 HTTP fixture; registry/catalog/auth data reuse the dispatch observer support.
|
||||
use super::*;
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
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>,
|
||||
pub started: Arc<AtomicUsize>,
|
||||
url: String,
|
||||
servers: Vec<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
for server in &self.servers {
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> 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));
|
||||
let started = Arc::new(AtomicUsize::new(0));
|
||||
let (g, s) = (gate.clone(), started.clone());
|
||||
let upstream = axum::Router::new().route(
|
||||
"/crm/leads",
|
||||
axum::routing::post(move || {
|
||||
let (g, s) = (g.clone(), s.clone());
|
||||
async move {
|
||||
s.fetch_add(1, Ordering::SeqCst);
|
||||
g.acquire().await.unwrap().forget();
|
||||
axum::Json(json!({"id":"lead_progress"}))
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let upstream_server = tokio::spawn(async move {
|
||||
axum::serve(listener, upstream).await.unwrap();
|
||||
});
|
||||
let mut operation = test_operation(&base);
|
||||
operation.execution_config.timeout_ms = 30_000;
|
||||
registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(crank_registry::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 other_key = format!("crk_test_{}", uuid::Uuid::now_v7().simple());
|
||||
let other = crank_core::PlatformApiKey {
|
||||
id: crank_core::PlatformApiKeyId::new("pk_progress_other"),
|
||||
workspace_id: workspace_id(),
|
||||
agent_id: Some(agent_id()),
|
||||
key_kind: crank_core::PlatformApiKeyKind::McpClient,
|
||||
name: "progress-other".into(),
|
||||
prefix: other_key.chars().take(16).collect(),
|
||||
scopes: vec![
|
||||
crank_core::PlatformApiKeyScope::Read,
|
||||
crank_core::PlatformApiKeyScope::Write,
|
||||
],
|
||||
status: crank_core::PlatformApiKeyStatus::Active,
|
||||
created_at: test_time(),
|
||||
last_used_at: None,
|
||||
expires_at: None,
|
||||
allowed_origins: vec![],
|
||||
};
|
||||
registry
|
||||
.create_platform_api_key(crank_registry::CreatePlatformApiKeyRequest {
|
||||
api_key: &other,
|
||||
secret_hash: &hash_access_secret(&other_key),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let sessions = Arc::new(CountedSessionStore::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
Some("https://crank.example.com".into()),
|
||||
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()),
|
||||
sessions.clone(),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
let app = app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let c = scope.clone();
|
||||
async move {
|
||||
let response = observe(c.clone(), next.run(request)).await;
|
||||
observe_body(response, c)
|
||||
}
|
||||
},
|
||||
));
|
||||
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,
|
||||
sessions,
|
||||
key,
|
||||
other_key,
|
||||
gate,
|
||||
started,
|
||||
url,
|
||||
servers: vec![server, upstream_server],
|
||||
}
|
||||
}
|
||||
pub fn request(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
key: &str,
|
||||
accept: &str,
|
||||
payload: Value,
|
||||
) -> reqwest::RequestBuilder {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(key)
|
||||
.header("Accept", accept)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request
|
||||
.header("Mcp-Method", payload["method"].as_str().unwrap())
|
||||
.header("Mcp-Name", TOOL_NAME);
|
||||
}
|
||||
request.json(&payload)
|
||||
}
|
||||
pub fn call(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
id: Value,
|
||||
token: Option<Value>,
|
||||
accept: &str,
|
||||
) -> reqwest::RequestBuilder {
|
||||
let mut meta = if revision == MODERN_REVISION {
|
||||
modern_meta()
|
||||
} else {
|
||||
json!({})
|
||||
};
|
||||
if let Some(token) = token {
|
||||
meta["progressToken"] = token;
|
||||
}
|
||||
self.request(
|
||||
revision,
|
||||
session,
|
||||
&self.key,
|
||||
accept,
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/call",
|
||||
"params":{"name":TOOL_NAME,"arguments":{"email":"progress@example.com"},"_meta":meta}}),
|
||||
)
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.request(
|
||||
revision,
|
||||
None,
|
||||
&self.key,
|
||||
"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();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
let response = self
|
||||
.request(
|
||||
revision,
|
||||
Some(&session),
|
||||
&self.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
Some(session)
|
||||
}
|
||||
pub async fn cancel(&self, key: &str, session: &str, params: Value) {
|
||||
let shape = match params.get("requestId") {
|
||||
None => "missing",
|
||||
Some(Value::Null) => "null",
|
||||
Some(Value::Bool(_)) => "bool",
|
||||
Some(Value::Array(_)) => "array",
|
||||
Some(Value::Object(_)) => "object",
|
||||
Some(Value::Number(_)) => "number",
|
||||
Some(Value::String(_)) => "string",
|
||||
};
|
||||
let response = self
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(session),
|
||||
key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":params}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.bytes().await.unwrap();
|
||||
if status != 202 {
|
||||
let error: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
||||
panic!(
|
||||
"cancel target shape={shape}, HTTP {status}, code={}, message={}, details={}",
|
||||
error["error"]["code"],
|
||||
error["error"]["message"],
|
||||
error["error"]["data"]["details"]
|
||||
);
|
||||
}
|
||||
assert!(body.is_empty(), "ack must disclose nothing");
|
||||
}
|
||||
pub async fn wait_started(&self, count: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while self.started.load(Ordering::SeqCst) < count {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("actual outbound dispatch before cancellation");
|
||||
}
|
||||
pub async fn history(&self, request: &str) -> Vec<crank_core::InvocationLog> {
|
||||
self.registry
|
||||
.list_invocation_logs(crank_registry::ListInvocationLogsQuery {
|
||||
workspace_id: &workspace_id(),
|
||||
level: None,
|
||||
status: None,
|
||||
outcome_group: None,
|
||||
search_text: None,
|
||||
source: Some(crank_core::InvocationSource::AgentToolCall),
|
||||
operation_id: Some(&crank_core::OperationId::new(format!("op_{TOOL_NAME}"))),
|
||||
agent_id: None,
|
||||
created_after: None,
|
||||
created_before: None,
|
||||
cursor_created_at: None,
|
||||
cursor_id: None,
|
||||
limit: 50,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.log)
|
||||
.filter(|log| log.request_id.as_deref() == Some(request))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
//! #107: real HTTP wire controls first; SDK participation is an independent migration oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_progress_cancel_http_support.rs"]
|
||||
pub(super) mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, c)| async move {
|
||||
observe(c.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, c)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
async fn frames(response: reqwest::Response) -> Vec<Value> {
|
||||
assert_eq!(response.status(), 200);
|
||||
let sse = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream");
|
||||
let raw = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
raw.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
})
|
||||
.collect()
|
||||
} else if raw.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
vec![serde_json::from_str(&raw).unwrap()]
|
||||
}
|
||||
}
|
||||
fn terminal(frames: &[Value], revision: &str, id: Value) -> Value {
|
||||
let last = frames.last().expect("terminal result");
|
||||
assert_eq!(last["jsonrpc"], "2.0");
|
||||
assert_eq!(last["id"], id);
|
||||
assert!(last.get("method").is_none());
|
||||
assert!(last.get("error").is_none());
|
||||
assert_eq!(last["result"]["isError"], false);
|
||||
assert_eq!(
|
||||
last["result"]["structuredContent"],
|
||||
json!({"id":"lead_progress"})
|
||||
);
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(last["result"]["resultType"], "complete");
|
||||
}
|
||||
last["result"].clone()
|
||||
}
|
||||
async fn progress_control(revision: &str) -> usize {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
// Establish the unchanged successful execution independently of any notification/marker.
|
||||
h.gate.add_permits(1);
|
||||
let plain = frames(
|
||||
h.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(51),
|
||||
None,
|
||||
"application/json",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(plain.len(), 1);
|
||||
let expected = terminal(&plain, revision, json!(51));
|
||||
assert_eq!(h.counters.sdk_progress_notification(), 0);
|
||||
let mut sdk_positive = usize::MAX;
|
||||
for token in [
|
||||
json!("opaque-token"),
|
||||
json!(-7),
|
||||
json!(1.5),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
json!(u64::MAX),
|
||||
] {
|
||||
let before = h.counters.sdk_progress_notification();
|
||||
h.gate.add_permits(1);
|
||||
let reply = h
|
||||
.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(51),
|
||||
Some(token.clone()),
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
reply.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("text/event-stream")
|
||||
);
|
||||
let reply = frames(reply).await;
|
||||
assert_eq!(reply.len(), 4, "three bounded real steps and one terminal");
|
||||
for (index, message) in [
|
||||
"tool_resolved",
|
||||
"authorization_resolved",
|
||||
"execution_dispatched",
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let expected_frame = json!({"jsonrpc":"2.0","method":"notifications/progress","params":{
|
||||
"progressToken":token,"progress":index+1,"message":message}});
|
||||
// Stringify too: float-form tokens must not silently become integers/strings.
|
||||
assert_eq!(reply[index].to_string(), expected_frame.to_string());
|
||||
assert!(reply[index]["params"]["progress"].as_u64().is_some());
|
||||
}
|
||||
assert_eq!(terminal(&reply, revision, json!(51)), expected);
|
||||
sdk_positive = sdk_positive.min(h.counters.sdk_progress_notification() - before);
|
||||
}
|
||||
for token in [
|
||||
None,
|
||||
Some(json!(null)),
|
||||
Some(json!(true)),
|
||||
Some(json!({})),
|
||||
Some(json!([])),
|
||||
Some(json!("")),
|
||||
Some(json!("bad\ntoken")),
|
||||
Some(json!("x".repeat(129))),
|
||||
] {
|
||||
h.gate.add_permits(1);
|
||||
let before = h.counters.sdk_progress_notification();
|
||||
let reply = frames(
|
||||
h.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(51),
|
||||
token,
|
||||
"text/event-stream",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(reply.len(), 1, "invalid/absent token is silent");
|
||||
assert_eq!(terminal(&reply, revision, json!(51)), expected);
|
||||
assert_eq!(h.counters.sdk_progress_notification(), before);
|
||||
}
|
||||
h.gate.add_permits(1);
|
||||
let before = h.counters.sdk_progress_notification();
|
||||
let reply = frames(
|
||||
h.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(51),
|
||||
Some(json!(u64::MAX)),
|
||||
"application/json",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(reply.len(), 1, "no SSE means no progress");
|
||||
assert_eq!(terminal(&reply, revision, json!(51)), expected);
|
||||
assert_eq!(h.counters.sdk_progress_notification(), before);
|
||||
eprintln!(
|
||||
"existing GREEN progress HTTP {revision}: exact token forms, bounded integer steps, unchanged result and silent negatives; minimum per-token SDK delta={sdk_positive}"
|
||||
);
|
||||
sdk_positive
|
||||
}
|
||||
async fn cancel_control(with_meta: bool) -> usize {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
let foreign = h.session(LEGACY_REVISION).await.unwrap();
|
||||
let request = h
|
||||
.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(u64::MAX),
|
||||
Some(json!("cancel-token")),
|
||||
"text/event-stream",
|
||||
)
|
||||
.header("x-request-id", "progress-cancel-owner");
|
||||
let mut call = tokio::spawn(async move { frames(request.send().await.unwrap()).await });
|
||||
h.wait_started(1).await;
|
||||
// All no-ops target this active call while its upstream response is held, not a completed call.
|
||||
for params in [
|
||||
json!({"requestId":u64::MAX.to_string()}),
|
||||
json!({"requestId":999}),
|
||||
json!({}),
|
||||
json!({"requestId":null}),
|
||||
json!({"requestId":true}),
|
||||
json!({"requestId":[]}),
|
||||
json!({"requestId":{}}),
|
||||
] {
|
||||
h.cancel(&h.key, &session, params).await;
|
||||
}
|
||||
eprintln!("cancel diagnostic: malformed/unknown/lookalike controls passed");
|
||||
h.cancel(&h.other_key, &session, json!({"requestId":u64::MAX}))
|
||||
.await;
|
||||
h.cancel(&h.key, &foreign, json!({"requestId":u64::MAX}))
|
||||
.await;
|
||||
eprintln!("cancel diagnostic: foreign ownership controls passed");
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), &mut call)
|
||||
.await
|
||||
.is_err(),
|
||||
"no-op targets must leave the owned call running"
|
||||
);
|
||||
// Now let exactly that call finish: this proves no-op, rather than just delayed cancellation.
|
||||
h.gate.add_permits(1);
|
||||
let reply = call.await.unwrap();
|
||||
terminal(&reply, LEGACY_REVISION, json!(u64::MAX));
|
||||
let history = h.history("progress-cancel-owner").await;
|
||||
assert_eq!(history.len(), 1);
|
||||
assert_eq!(history[0].status, crank_core::InvocationStatus::Ok);
|
||||
h.cancel(&h.key, &session, json!({"requestId":u64::MAX}))
|
||||
.await;
|
||||
assert_eq!(
|
||||
h.history("progress-cancel-owner").await.len(),
|
||||
1,
|
||||
"late cancel adds no outcome"
|
||||
);
|
||||
|
||||
let request = h
|
||||
.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(u64::MAX),
|
||||
Some(json!("cancel-token")),
|
||||
"text/event-stream",
|
||||
)
|
||||
.header("x-request-id", "progress-cancel-stop");
|
||||
let call = tokio::spawn(async move { frames(request.send().await.unwrap()).await });
|
||||
h.wait_started(2).await;
|
||||
let before = h.counters.sdk_cancelled_params();
|
||||
let mut params = json!({"requestId":u64::MAX,"reason":42,"unknown":{"nested":true}});
|
||||
if with_meta {
|
||||
params["_meta"] = json!({});
|
||||
}
|
||||
h.cancel(&h.key, &session, params).await;
|
||||
let delta = h.counters.sdk_cancelled_params() - before;
|
||||
let reply = tokio::time::timeout(Duration::from_secs(1), call)
|
||||
.await
|
||||
.expect("cancel releases call while upstream is still held")
|
||||
.unwrap();
|
||||
assert_eq!(reply.len(), 3);
|
||||
assert!(
|
||||
reply
|
||||
.iter()
|
||||
.all(|f| f["method"] == "notifications/progress"),
|
||||
"no false terminal result"
|
||||
);
|
||||
assert!(h.history("progress-cancel-stop").await.is_empty());
|
||||
// Releasing an abandoned upstream cannot turn the cancelled execution into completed history.
|
||||
h.gate.add_permits(2);
|
||||
let reply = frames(
|
||||
h.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(u64::MAX),
|
||||
None,
|
||||
"application/json",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
terminal(&reply, LEGACY_REVISION, json!(u64::MAX));
|
||||
assert!(h.history("progress-cancel-stop").await.is_empty());
|
||||
assert_eq!(
|
||||
h.started.load(std::sync::atomic::Ordering::SeqCst),
|
||||
3,
|
||||
"no automatic write retry"
|
||||
);
|
||||
eprintln!(
|
||||
"existing GREEN cancel HTTP legacy: active no-ops, numeric owner stop with ignored fields, released/reused id and no false history; SDK delta={delta}"
|
||||
);
|
||||
delta
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_wire_legacy() {
|
||||
progress_control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_wire_modern() {
|
||||
progress_control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_wire_cancellation() {
|
||||
cancel_control(false).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_sdk_legacy() {
|
||||
assert!(
|
||||
progress_control(LEGACY_REVISION).await > 0,
|
||||
"missing SDK progress serialization after successful HTTP controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_sdk_modern() {
|
||||
assert!(
|
||||
progress_control(MODERN_REVISION).await > 0,
|
||||
"missing SDK progress serialization after successful HTTP controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_sdk_cancellation() {
|
||||
assert!(
|
||||
cancel_control(false).await > 0,
|
||||
"missing SDK cancelled params decode after successful HTTP stop controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_wire_modern_stream_close() {
|
||||
let h = Endpoint::started().await;
|
||||
let response = h
|
||||
.call(
|
||||
MODERN_REVISION,
|
||||
None,
|
||||
json!(52),
|
||||
Some(json!("disconnect")),
|
||||
"text/event-stream",
|
||||
)
|
||||
.header("x-request-id", "progress-modern-stop")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
h.wait_started(1).await;
|
||||
drop(response);
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
// Match the existing lifecycle grace; an un-stopped future would complete after gate release.
|
||||
h.gate.add_permits(2);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
assert!(
|
||||
h.history("progress-modern-stop").await.is_empty(),
|
||||
"closed stream must not reach completed history"
|
||||
);
|
||||
let reply = frames(
|
||||
h.call(MODERN_REVISION, None, json!(52), None, "application/json")
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
terminal(&reply, MODERN_REVISION, json!(52));
|
||||
assert_eq!(
|
||||
h.started.load(std::sync::atomic::Ordering::SeqCst),
|
||||
2,
|
||||
"no retry after disconnect"
|
||||
);
|
||||
assert!(h.history("progress-modern-stop").await.is_empty());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_admitted_meta_cancellation() {
|
||||
assert!(cancel_control(true).await > 0);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_malformed_meta_rejected_before_decode() {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
let request = h
|
||||
.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(u64::MAX),
|
||||
Some(json!("meta-boundary")),
|
||||
"text/event-stream",
|
||||
)
|
||||
.header("x-request-id", "progress-meta-rejected");
|
||||
let mut call = tokio::spawn(async move { frames(request.send().await.unwrap()).await });
|
||||
h.wait_started(1).await;
|
||||
let before = h.counters.sdk_cancelled_params();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{
|
||||
"requestId":u64::MAX,"reason":42,"_meta":[],"unknown":{"nested":true}}}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
let error = json_body(response).await;
|
||||
assert_eq!(error["error"]["code"], -32020);
|
||||
assert_eq!(error["error"]["message"], "protocol identity mismatch");
|
||||
assert_eq!(
|
||||
error["error"]["data"]["details"],
|
||||
"request _meta must be an object"
|
||||
);
|
||||
assert_eq!(h.counters.sdk_cancelled_params(), before);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), &mut call)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
h.gate.add_permits(1);
|
||||
let reply = call.await.unwrap();
|
||||
terminal(&reply, LEGACY_REVISION, json!(u64::MAX));
|
||||
let history = h.history("progress-meta-rejected").await;
|
||||
assert_eq!(history.len(), 1);
|
||||
assert_eq!(history[0].status, crank_core::InvocationStatus::Ok);
|
||||
assert_eq!(h.started.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
assert_eq!(h.counters.sdk_cancelled_params(), before);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_observer_scope_control() {
|
||||
use super::{sdk_cancelled_params_decoded, sdk_progress_notification_serialized};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_cancelled_params_decoded();
|
||||
sdk_progress_notification_serialized();
|
||||
assert_eq!(a.sdk_cancelled_params(), 0);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
sdk_cancelled_params_decoded();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
sdk_progress_notification_serialized();
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
[a.sdk_cancelled_params(), a.sdk_progress_notification()],
|
||||
[1, 0]
|
||||
);
|
||||
assert_eq!(
|
||||
[b.sdk_cancelled_params(), b.sdk_progress_notification()],
|
||||
[0, 1]
|
||||
);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_progress_notification_serialized();
|
||||
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), a.clone());
|
||||
assert_eq!(a.sdk_progress_notification(), 0);
|
||||
axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(a.sdk_progress_notification(), 1);
|
||||
assert_eq!(b.sdk_progress_notification(), 1);
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
//! #107 Prompts: existing wire GREEN and an independent SDK typed-path RED oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_prompts_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 3] {
|
||||
[
|
||||
c.sdk_prompts_dispatch(),
|
||||
c.sdk_prompts_list_result(),
|
||||
c.sdk_prompts_get_result(),
|
||||
]
|
||||
}
|
||||
fn request(revision: &str, method: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":method,"params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-prompts-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames.iter().filter(|f| f.get("id") == Some(id)).collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
fn era(result: &Value, revision: &str, method: &str) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
if method == "prompts/list" {
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
} else {
|
||||
assert!(result.get("ttlMs").is_none(), "{result}");
|
||||
assert!(result.get("cacheScope").is_none(), "{result}");
|
||||
}
|
||||
} else {
|
||||
for key in ["resultType", "ttlMs", "cacheScope"] {
|
||||
assert!(result.get(key).is_none(), "{result}");
|
||||
}
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
sse: bool,
|
||||
) -> (Value, [usize; 3]) {
|
||||
let req = request(revision, method, params);
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
era(&body["result"], revision, method);
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
body["result"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> 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 first_cursor = None;
|
||||
// Both revisions' JSON contract, plus modern terminal SSE through the same normal app.
|
||||
let modes: &[bool] = if revision == MODERN_REVISION {
|
||||
&[false, true]
|
||||
} else {
|
||||
&[false]
|
||||
};
|
||||
for &sse in modes {
|
||||
let mut cursor = None;
|
||||
for (page, name) in ["greeting", "archived-prompt"].iter().enumerate() {
|
||||
let mut params = json!({"limit":1});
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let (result, delta) = success(&h, revision, session, "prompts/list", params, sse).await;
|
||||
let prompts = result["prompts"].as_array().unwrap();
|
||||
assert_eq!(prompts.len(), 1, "{result}");
|
||||
assert_eq!(
|
||||
prompts[0],
|
||||
json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
]
|
||||
})
|
||||
);
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.map(|v| v.as_str().unwrap().to_owned());
|
||||
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
||||
if page == 0 {
|
||||
assert_ne!(cursor.as_deref(), Some("1"));
|
||||
first_cursor = cursor.clone();
|
||||
}
|
||||
deltas.push((delta, [1, 1, 0]));
|
||||
}
|
||||
for (name, args, text) in [
|
||||
(
|
||||
"greeting",
|
||||
json!({"name":"Ada"}),
|
||||
"Hello Ada count=2 enabled=true tone=warm",
|
||||
),
|
||||
(
|
||||
"greeting",
|
||||
json!({"name":"Ada","count":7,"enabled":false,"tone":"dry"}),
|
||||
"Hello Ada count=7 enabled=false tone=dry",
|
||||
),
|
||||
(
|
||||
"archived-prompt",
|
||||
json!({"name":"Ada"}),
|
||||
"Hello Ada count=2 enabled=true tone=warm",
|
||||
),
|
||||
] {
|
||||
let mut previous = None;
|
||||
for _ in 0..2 {
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"prompts/get",
|
||||
json!({"name":name,"arguments":args}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result["description"], format!("Published {name}"));
|
||||
assert_eq!(
|
||||
result["messages"],
|
||||
json!([
|
||||
{"role":"system","content":{"type":"text","text":"Be brief."}},
|
||||
{"role":"user","content":{"type":"text","text":text}}
|
||||
])
|
||||
);
|
||||
if let Some(ref previous) = previous {
|
||||
assert_eq!(&result, previous);
|
||||
}
|
||||
previous = Some(result);
|
||||
deltas.push((delta, [1, 0, 1]));
|
||||
}
|
||||
}
|
||||
for (arguments, reason, argument) in [
|
||||
(json!({}), "missing_argument", "name"),
|
||||
(
|
||||
json!({"name":"Ada","extra":"x"}),
|
||||
"unknown_argument",
|
||||
"extra",
|
||||
),
|
||||
(json!({"name":5}), "argument_invalid", "name"),
|
||||
(
|
||||
json!({"name":"Ada","count":"7"}),
|
||||
"argument_invalid",
|
||||
"count",
|
||||
),
|
||||
(
|
||||
json!({"name":"Ada","enabled":"false"}),
|
||||
"argument_invalid",
|
||||
"enabled",
|
||||
),
|
||||
(
|
||||
json!({"name":"Ada","tone":"loud"}),
|
||||
"argument_invalid",
|
||||
"tone",
|
||||
),
|
||||
(
|
||||
json!({"name":"x".repeat(crank_core::prompt::MAX_TEXT_BYTES + 1)}),
|
||||
"argument_too_large",
|
||||
"name",
|
||||
),
|
||||
] {
|
||||
let req = request(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name":"greeting","arguments":arguments}),
|
||||
);
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(body["error"]["data"]["reason"], reason, "{body}");
|
||||
assert_eq!(body["error"]["data"]["argument"], argument);
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
for leaked in [
|
||||
"Be brief.",
|
||||
"Hello ",
|
||||
"Changed ",
|
||||
"Published unbound-prompt",
|
||||
] {
|
||||
assert!(!body.to_string().contains(leaked), "{body}");
|
||||
}
|
||||
}
|
||||
let mut unavailable = None;
|
||||
for name in [
|
||||
"draft-prompt",
|
||||
"unbound-prompt",
|
||||
"other-agent-prompt",
|
||||
"never-existed",
|
||||
"prm_a",
|
||||
] {
|
||||
let req = request(revision, "prompts/get", json!({"name":name}));
|
||||
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
"the requested prompt is not available"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
if let Some(ref previous) = unavailable {
|
||||
assert_eq!(&body, previous);
|
||||
}
|
||||
unavailable = Some(body);
|
||||
}
|
||||
}
|
||||
for params in [json!({"cursor":"invalid"}), json!({"limit":"invalid"})] {
|
||||
let req = request(revision, "prompts/list", params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
}
|
||||
let other = if revision == MODERN_REVISION {
|
||||
LEGACY_REVISION
|
||||
} else {
|
||||
MODERN_REVISION
|
||||
};
|
||||
let other_session = h.session(other).await;
|
||||
let req = request(
|
||||
other,
|
||||
"prompts/list",
|
||||
json!({"cursor":first_cursor.unwrap()}),
|
||||
);
|
||||
let body = wire(
|
||||
h.post(other, other_session.as_deref(), &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["error"]["code"], -32602,
|
||||
"cross-revision cursor: {body}"
|
||||
);
|
||||
// Archive keeps serving v1 above, but disallows new publications and bindings.
|
||||
use crank_core::ids::PromptId;
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, PublishPromptRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
let publication = h
|
||||
.registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: h.archived_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
publication,
|
||||
Err(crank_registry::RegistryError::PromptNotDraft { .. })
|
||||
),
|
||||
"{publication:?}"
|
||||
);
|
||||
let binding = h
|
||||
.registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
binding,
|
||||
Err(crank_registry::RegistryError::PromptArchived { .. })
|
||||
),
|
||||
"{binding:?}"
|
||||
);
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (method, params) in [
|
||||
("prompts/list", json!({})),
|
||||
(
|
||||
"prompts/get",
|
||||
json!({"name":"greeting","arguments":{"name":"Ada"}}),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
h.post(revision, session, &request(revision, method, params), false)
|
||||
.await
|
||||
.status(),
|
||||
401
|
||||
);
|
||||
}
|
||||
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:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(a, e)| a == e),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_prompts_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_prompts_dispatch_enter, sdk_prompts_get_result_serialized,
|
||||
sdk_prompts_list_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_prompts_dispatch_enter();
|
||||
assert_eq!(counts(&a), [0; 3]);
|
||||
let snapshot = a.snapshot();
|
||||
observe(a.clone(), async {
|
||||
sdk_prompts_dispatch_enter();
|
||||
sdk_prompts_list_result_serialized();
|
||||
sdk_prompts_get_result_serialized();
|
||||
})
|
||||
.await;
|
||||
observe(b.clone(), async {
|
||||
sdk_prompts_get_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&a), [1; 3]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
assert_eq!(a.snapshot(), snapshot);
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_prompts_list_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"terminal"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 1, 1]);
|
||||
assert_eq!(counts(&a), [1; 3]);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Published Prompts fixture using the existing observed HTTP app and disposable PostgreSQL.
|
||||
use super::*;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::PromptId};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
|
||||
pub(super) fn definition(name: &str, content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":name, "description":format!("Published {name}"),
|
||||
"arguments":[
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
pub archived_at: time::OffsetDateTime,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("prompts_owner", "t_160a763a").await;
|
||||
let registry = test_registry().await;
|
||||
let mut archived_at = test_time();
|
||||
for (id, name, publish) in [
|
||||
("prm_a", "greeting", true),
|
||||
("prm_b", "archived-prompt", true),
|
||||
("prm_c", "unbound-prompt", true),
|
||||
("prm_d", "draft-prompt", false),
|
||||
("prm_e", "other-agent-prompt", true),
|
||||
] {
|
||||
let row = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition(
|
||||
name,
|
||||
"Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}",
|
||||
),
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if publish {
|
||||
let row = registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new(id),
|
||||
expected_updated_at: row.updated_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if id == "prm_b" {
|
||||
archived_at = row.updated_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, slug) in [
|
||||
(agent_id(), AGENT_SLUG),
|
||||
(
|
||||
crank_core::AgentId::new("agent_other_prompts"),
|
||||
"other-prompts",
|
||||
),
|
||||
] {
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: slug.into(),
|
||||
display_name: "SDK Prompts".into(),
|
||||
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,
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let other_agent = crank_core::AgentId::new("agent_other_prompts");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_e"),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &other_agent,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let archived_at = registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_b"),
|
||||
expected_updated_at: archived_at,
|
||||
archived_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.updated_at;
|
||||
// A mutable v2 draft must not change the bound v1 rendering or discovery metadata.
|
||||
let draft = registry
|
||||
.get_prompt_draft(&workspace_id(), &PromptId::new("prm_a"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id(),
|
||||
prompt_id: PromptId::new("prm_a"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition("changed-draft", "Changed {{name}}"),
|
||||
expected_updated_at: draft.updated_at,
|
||||
updated_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
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).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move { observe_body(next.run(request).await, counters) }
|
||||
}
|
||||
}));
|
||||
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,
|
||||
archived_at,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-prompts-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
if let Some(name) = body["params"]["name"].as_str() {
|
||||
request = request.header("Mcp-Name", name);
|
||||
}
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! #107 Resources: existing wire GREEN is independent of the missing SDK typed-path oracle.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_resources_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, TEXT, URI};
|
||||
|
||||
// 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();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
fn counts(c: &CounterSet) -> [usize; 4] {
|
||||
[
|
||||
c.sdk_resources_dispatch(),
|
||||
c.sdk_resources_list_result(),
|
||||
c.sdk_resources_read_result(),
|
||||
c.sdk_resource_templates_list_result(),
|
||||
]
|
||||
}
|
||||
fn request(revision: &str, method: &str, mut params: Value) -> Value {
|
||||
if revision == MODERN_REVISION {
|
||||
params["_meta"] = modern_meta();
|
||||
}
|
||||
json!({"jsonrpc":"2.0", "id":9007199254740993_u64, "method":method, "params":params})
|
||||
}
|
||||
async fn wire(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], "sdk-resources-wire");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames.iter().filter(|f| f.get("id") == Some(id)).collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}: {text}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
fn era(result: &Value, revision: &str) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
} else {
|
||||
for key in ["resultType", "ttlMs", "cacheScope"] {
|
||||
assert!(result.get(key).is_none(), "{result}");
|
||||
}
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
async fn success(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
sse_accept: bool,
|
||||
) -> (Value, [usize; 4]) {
|
||||
let req = request(revision, method, params);
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, sse_accept).await,
|
||||
&req["id"],
|
||||
sse_accept,
|
||||
)
|
||||
.await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
era(&body["result"], revision);
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
body["result"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
// Preference order negotiates JSON or terminal SSE in both Resources revisions.
|
||||
for sse in [false, true] {
|
||||
let mut cursor = None;
|
||||
let mut names = Vec::new();
|
||||
for page in 0..2 {
|
||||
let mut params = json!({"limit":1});
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let (result, delta) =
|
||||
success(&h, revision, session, "resources/list", params, sse).await;
|
||||
let resources = result["resources"].as_array().unwrap();
|
||||
assert_eq!(resources.len(), 1, "{result}");
|
||||
let item = &resources[0];
|
||||
assert_eq!(item["mimeType"], "text/plain");
|
||||
assert!(
|
||||
item.get("description").is_none(),
|
||||
"static descriptors omit description: {item}"
|
||||
);
|
||||
names.push((item["name"].clone(), item["uri"].clone()));
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.map(|v| v.as_str().unwrap().to_owned());
|
||||
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
||||
if let Some(ref cursor) = cursor {
|
||||
assert_ne!(cursor, "1", "opaque cursor required");
|
||||
}
|
||||
deltas.push((delta, [1, 1, 0, 0]));
|
||||
}
|
||||
names.sort_by_key(|n| n.0.as_str().unwrap().to_owned());
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
(json!("sdk_a"), json!(URI)),
|
||||
(json!("sdk_b"), json!("crank://resources/sdk-b"))
|
||||
]
|
||||
);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/read",
|
||||
json!({"uri":URI}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result["contents"],
|
||||
json!([{"uri":URI,"mimeType":"text/plain","text":TEXT}])
|
||||
);
|
||||
deltas.push((delta, [1, 0, 1, 0]));
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/templates/list",
|
||||
json!({}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result["resourceTemplates"], json!([]));
|
||||
assert!(result.get("nextCursor").is_none());
|
||||
deltas.push((delta, [1, 0, 0, 1]));
|
||||
}
|
||||
// Malformed parameters/cursors and indistinguishable unavailable URIs remain command errors.
|
||||
for (method, params) in [
|
||||
("resources/list", json!({"cursor":"invalid"})),
|
||||
("resources/list", json!({"limit":"invalid"})),
|
||||
("resources/templates/list", json!({"cursor":"invalid"})),
|
||||
("resources/templates/list", json!({"limit":"invalid"})),
|
||||
("resources/read", json!({"uri":"crank://resources/unbound"})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
}
|
||||
// An existing session does not preserve revoked authorization.
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (method, params) in [
|
||||
("resources/list", json!({})),
|
||||
("resources/read", json!({"uri":URI})),
|
||||
("resources/templates/list", json!({})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 401);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Resources wire {revision}: pagination, exact content URI/bytes, empty templates, JSON/SSE negotiation, InvalidParams, revoked401; actual/expected SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_resource_templates_list_result_serialized, sdk_resources_dispatch_enter,
|
||||
sdk_resources_list_result_serialized, sdk_resources_read_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_resources_dispatch_enter();
|
||||
assert_eq!(counts(&a), [0; 4]);
|
||||
let snapshot = a.snapshot();
|
||||
observe(a.clone(), async {
|
||||
sdk_resources_dispatch_enter();
|
||||
sdk_resources_list_result_serialized();
|
||||
sdk_resources_read_result_serialized();
|
||||
sdk_resource_templates_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
observe(b.clone(), async {
|
||||
sdk_resources_read_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
assert_eq!(counts(&b), [0, 0, 1, 0]);
|
||||
assert_eq!(a.snapshot(), snapshot, "old Snapshot stays unchanged");
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_resource_templates_list_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), b.clone());
|
||||
assert_eq!(
|
||||
&axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap()[..],
|
||||
b"terminal"
|
||||
);
|
||||
assert_eq!(counts(&b), [0, 0, 1, 1]);
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Small Resources fixture: existing observer helpers, exact artifact publications, normal app.
|
||||
use super::*;
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::ResourceId};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, PublishAgentRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub(super) const URI: &str = "crank://resources/sdk-a";
|
||||
pub(super) const TEXT: &str = "published v1\n";
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub key: String,
|
||||
pub url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
root: std::path::PathBuf,
|
||||
}
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("resources_owner", "t_73561633").await;
|
||||
let registry = test_registry().await;
|
||||
let root = std::env::temp_dir().join(format!("rmcp-resources-{}", uuid::Uuid::now_v7()));
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let store = ArtifactStore::open(&root).unwrap();
|
||||
// Same immutable row shapes and real ArtifactStore::put as static_resources/fixtures.rs.
|
||||
for (id, uri, name, bytes) in [
|
||||
("res_sdk_a", URI, "sdk_a", TEXT),
|
||||
(
|
||||
"res_sdk_b",
|
||||
"crank://resources/sdk-b",
|
||||
"sdk_b",
|
||||
"second published resource\n",
|
||||
),
|
||||
] {
|
||||
let stored = store.put(bytes.as_bytes()).unwrap();
|
||||
let digest = format!("{:x}", Sha256::digest(bytes.as_bytes()));
|
||||
let source = format!("src_{id}");
|
||||
sqlx::query("insert into artifact_blobs (digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at) values ($1,$2,$3,'available',now(),now())")
|
||||
.bind(&digest).bind(format!("sha256:{digest}")).bind(stored.size_bytes as i64).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into artifact_sources (workspace_id,source_id,blob_digest,mime_type,sensitivity,lifecycle,created_at,updated_at) values ('ws_default',$1,$2,'text/plain','internal','active',now(),now())")
|
||||
.bind(&source).bind(&digest).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resources (workspace_id,resource_id,uri,name,description,status,kind,current_draft_version,created_at,updated_at) values ('ws_default',$1,$2,$3,'','published','text',1,now(),now())")
|
||||
.bind(id).bind(uri).bind(name).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resource_versions (workspace_id,resource_id,version,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,created_at,superseded_at) values ('ws_default',$1,1,'text','text/plain',$2,$3,'internal',$4,now(),null)")
|
||||
.bind(id).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
||||
sqlx::query("insert into resource_publications (workspace_id,resource_id,version,uri,name,description,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,published_at) values ('ws_default',$1,1,$2,$3,'','text','text/plain',$4,$5,'internal',$6,now())")
|
||||
.bind(id).bind(uri).bind(name).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
||||
}
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: AGENT_SLUG.into(),
|
||||
display_name: "SDK Resources".into(),
|
||||
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: agent_id(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_sdk_a"),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_sdk_b"),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
// Normal build_app composition with its sanctioned artifact root, not the isolated SDK router.
|
||||
let app = crate::build_app_with_artifacts(
|
||||
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),
|
||||
16,
|
||||
store,
|
||||
);
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move {
|
||||
let response = next.run(request).await;
|
||||
observe_body(response, counters)
|
||||
}
|
||||
}
|
||||
}));
|
||||
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,
|
||||
root,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
sse: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header(
|
||||
"Accept",
|
||||
if sse {
|
||||
"text/event-stream, application/json"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.header("x-request-id", "sdk-resources-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
||||
if let Some(uri) = body["params"]["uri"].as_str() {
|
||||
request = request.header("Mcp-Name", uri);
|
||||
}
|
||||
}
|
||||
request.json(body).send().await.unwrap()
|
||||
}
|
||||
pub async fn session(&self, revision: &str) -> Option<String> {
|
||||
if revision == MODERN_REVISION {
|
||||
return None;
|
||||
}
|
||||
let response = self
|
||||
.post(revision, None, &legacy_initialize(1), false)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
json_body(response).await["result"]["protocolVersion"],
|
||||
revision
|
||||
);
|
||||
assert_eq!(
|
||||
self.post(revision, Some(&session), &initialized_notification(), false)
|
||||
.await
|
||||
.status(),
|
||||
202
|
||||
);
|
||||
Some(session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
//! #107 result serialization: wire controls run independently of the structural SDK oracle.
|
||||
use super::*;
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use futures_util::{StreamExt, stream};
|
||||
|
||||
const ERROR_EMAIL: &str = "upstream-error@example.test";
|
||||
const REQUEST_ID: &str = "sdk-result-wire";
|
||||
const TRACE_ID: &str = "11111111111111111111111111111111";
|
||||
|
||||
pub(super) async fn upstream(state: State<Arc<AtomicUsize>>, payload: Json<Value>) -> Response {
|
||||
if payload.0["email"] == ERROR_EMAIL {
|
||||
state.0.fetch_add(1, Ordering::SeqCst);
|
||||
return (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
Json(json!({"error":"fixture rejection"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
create_lead(state, payload).await.into_response()
|
||||
}
|
||||
|
||||
// The HTTP body is polled after next.run returns. Carry only the test observer, not a new lifecycle.
|
||||
pub(super) fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_http_pagination_both_revisions() {
|
||||
let h = Endpoint::started().await;
|
||||
let mut operation = test_operation(&h._upstream.1);
|
||||
operation.id = crank_core::OperationId::new("op_second_lead");
|
||||
operation.name = "second_lead".to_owned();
|
||||
h.registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
h.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: now,
|
||||
},
|
||||
bindings: &[
|
||||
AgentOperationBinding {
|
||||
operation_id: crank_core::OperationId::new("op_create_lead"),
|
||||
operation_version: 1,
|
||||
tool_name: TOOL_NAME.into(),
|
||||
tool_title: "Create Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
AgentOperationBinding {
|
||||
operation_id: operation.id,
|
||||
operation_version: 1,
|
||||
tool_name: "second_lead".into(),
|
||||
tool_title: "Second Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = h.session(revision).await;
|
||||
let mut names = Vec::new();
|
||||
for (cursor, expected_next, expected_len) in [
|
||||
(None, Some("1"), 1),
|
||||
(Some("1"), None, 1),
|
||||
(Some("2"), None, 0),
|
||||
] {
|
||||
let id = json!(format!("page-{cursor:?}"));
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let body = wire_body(
|
||||
h.post(revision, session.as_deref(), &request).await,
|
||||
&id,
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(
|
||||
body["result"].get("nextCursor"),
|
||||
expected_next.map(|s| json!(s)).as_ref()
|
||||
);
|
||||
let tools = body["result"]["tools"].as_array().unwrap();
|
||||
assert_eq!(tools.len(), expected_len);
|
||||
names.extend(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| tool["name"].as_str().unwrap().to_owned()),
|
||||
);
|
||||
assert_eq!(h.counters.sdk_tools_list_result() - before, 1);
|
||||
}
|
||||
names.sort();
|
||||
let mut expected = vec![TOOL_NAME.to_owned(), "second_lead".to_owned()];
|
||||
expected.sort();
|
||||
assert_eq!(names, expected);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn assert_era(result: &Value, revision: &str, list: bool) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
if list {
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
}
|
||||
} else {
|
||||
assert!(result.get("resultType").is_none(), "{result}");
|
||||
assert!(result.get("ttlMs").is_none(), "{result}");
|
||||
assert!(result.get("cacheScope").is_none(), "{result}");
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
|
||||
async fn wire_body(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-trace-id"], TRACE_ID);
|
||||
let content_type = response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"{content_type}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|frame| frame.get("id") == Some(id))
|
||||
.collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
assert!(
|
||||
frames
|
||||
.iter()
|
||||
.any(|frame| frame["method"] == "notifications/progress"
|
||||
&& frame["params"]["progressToken"] == "result-progress"),
|
||||
"{frames:?}"
|
||||
);
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
|
||||
fn assert_call_result(body: &Value, revision: &str, email: &str) {
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
let result = &body["result"];
|
||||
assert_era(result, revision, false);
|
||||
let (output, text, is_error) = if email == ERROR_EMAIL {
|
||||
let contract = crate::tool_error::tool_error_contract_from_runtime(
|
||||
&crank_runtime::RuntimeError::ProtocolAdapter(
|
||||
crank_core::ProtocolAdapterError::UnexpectedStatus {
|
||||
status: 422,
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
},
|
||||
),
|
||||
REQUEST_ID,
|
||||
TRACE_ID,
|
||||
crank_core::ExecutionLocale::En,
|
||||
);
|
||||
(
|
||||
json!({"error":crate::tool_error::tool_error_value(&contract)}),
|
||||
crate::tool_error::tool_error_text(&contract),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let output = json!({"id":format!("lead_for_{email}")});
|
||||
let text = serde_json::to_string_pretty(&output).unwrap();
|
||||
(output, text, false)
|
||||
};
|
||||
assert_eq!(result["structuredContent"], output, "{body}");
|
||||
assert_eq!(result["content"], json!([{"type":"text", "text":text}]));
|
||||
assert_eq!(result["isError"], is_error);
|
||||
assert_eq!(
|
||||
result.as_object().unwrap().len(),
|
||||
if revision == MODERN_REVISION { 4 } else { 3 },
|
||||
"no unexpected optional fields: {result}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn result_control(revision: &str) -> Vec<usize> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut counts = Vec::new();
|
||||
// Actual published descriptor and schema, then the empty page at the catalog boundary.
|
||||
for (cursor, expected_tools, id) in [
|
||||
(
|
||||
None,
|
||||
json!([{"name":TOOL_NAME,"title":"Create Lead","description":"Creates a CRM lead","inputSchema":{"type":"object","properties":{"email":{"type":"string"}},"required":["email"]}}]),
|
||||
json!("list-string-id"),
|
||||
),
|
||||
(Some("1"), json!([]), json!(9007199254740993_u64)),
|
||||
] {
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let before_call = h.counters.sdk_tools_call_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let body = wire_body(h.post(revision, session, &request).await, &id, false).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
assert_eq!(body["result"]["tools"], expected_tools);
|
||||
assert!(body["result"].get("nextCursor").is_none(), "{body}");
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before_call);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_list_result() - before);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
for (email, id, sse) in [
|
||||
(
|
||||
"result-success@example.test",
|
||||
json!(9007199254740993_u64),
|
||||
false,
|
||||
),
|
||||
(ERROR_EMAIL, json!("tool-error-string-id"), false),
|
||||
("result-sse@example.test", json!("sse-string-id"), true),
|
||||
(ERROR_EMAIL, json!(92), true),
|
||||
] {
|
||||
if sse && revision != MODERN_REVISION {
|
||||
continue;
|
||||
}
|
||||
let mut request = if revision == MODERN_REVISION {
|
||||
modern_tool_call(90, email)
|
||||
} else {
|
||||
legacy_tool_call(90, email)
|
||||
};
|
||||
request["id"] = id.clone();
|
||||
if sse {
|
||||
request["params"]["_meta"]["progressToken"] = json!("result-progress");
|
||||
}
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let before_list = h.counters.sdk_tools_list_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let response = h
|
||||
.post_accept(
|
||||
revision,
|
||||
session,
|
||||
&request,
|
||||
if sse {
|
||||
"application/json, text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let body = wire_body(response, &id, sse).await;
|
||||
assert_call_result(&body, revision, email);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst) - arrivals, 1);
|
||||
assert_eq!(h.counters.sdk_tools_list_result(), before_list);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_call_result() - before);
|
||||
}
|
||||
// Unknown tool is a command InvalidParams, not an execution tool-error result.
|
||||
let mut invalid = if revision == MODERN_REVISION {
|
||||
modern_tool_call(93, "unused@example.test")
|
||||
} else {
|
||||
legacy_tool_call(93, "unused@example.test")
|
||||
};
|
||||
invalid["params"]["name"] = json!("missing_tool");
|
||||
invalid["id"] = json!("invalid-params-id");
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let body = wire_body(
|
||||
h.post(revision, session, &invalid).await,
|
||||
&invalid["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
assert_eq!(body["error"]["data"]["request_id"], REQUEST_ID);
|
||||
assert_eq!(body["error"]["data"]["trace_id"], TRACE_ID);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), arrivals);
|
||||
eprintln!(
|
||||
"existing GREEN result wire {revision}: published list/schema + empty page, exact success/error JSON{}; InvalidParams/no result/no marker/no outbound; SDK result deltas={counts:?}",
|
||||
if revision == MODERN_REVISION {
|
||||
" + success/error terminal SSE"
|
||||
} else {
|
||||
" (legacy JSON-only)"
|
||||
}
|
||||
);
|
||||
counts
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_modern() {
|
||||
result_control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_legacy() {
|
||||
result_control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_modern() {
|
||||
assert_eq!(
|
||||
result_control(MODERN_REVISION).await,
|
||||
vec![1; 6],
|
||||
"structural oracle: SDK list/final-empty/success/error/SSE-success/SSE-error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_legacy() {
|
||||
assert_eq!(
|
||||
result_control(LEGACY_REVISION).await,
|
||||
vec![1; 4],
|
||||
"structural oracle: SDK list/final-empty/success/error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_observer_scope_control() {
|
||||
use crate::app::dispatch_observer::{
|
||||
sdk_tools_call_result_serialized, sdk_tools_list_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(0, 0)
|
||||
);
|
||||
observe(a.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
})
|
||||
.await;
|
||||
// A different request cannot alter a's result counters.
|
||||
observe(b.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(
|
||||
(b.sdk_tools_list_result(), b.sdk_tools_call_result()),
|
||||
(1, 0)
|
||||
);
|
||||
// Prove the stream-body scope actually records deferred work after the header scope ended.
|
||||
let stream_counters = b.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
sdk_tools_call_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), stream_counters);
|
||||
let bytes = axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&bytes[..], b"terminal");
|
||||
assert_eq!(b.sdk_tools_call_result(), 1);
|
||||
assert_eq!(a.sdk_tools_call_result(), 1);
|
||||
}
|
||||
@@ -23,6 +23,9 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{CounterSet, observe, sdk_tools_dispatch_enter, support::*};
|
||||
|
||||
#[path = "rmcp_result_runtime_tests.rs"]
|
||||
mod result_serialization;
|
||||
|
||||
struct Server(tokio::task::JoinHandle<()>, String);
|
||||
|
||||
impl Drop for Server {
|
||||
@@ -55,13 +58,13 @@ impl Endpoint {
|
||||
async fn started() -> Self {
|
||||
// First caller owns the process-wide fixture and its atexit cleanup, including RED panics.
|
||||
let _ =
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_aaaea124")
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_c559abb1")
|
||||
.await;
|
||||
let registry = test_registry().await;
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = serve(
|
||||
Router::new()
|
||||
.route("/crm/leads", post(create_lead))
|
||||
.route("/crm/leads", post(result_serialization::upstream))
|
||||
.with_state(calls.clone()),
|
||||
)
|
||||
.await;
|
||||
@@ -97,7 +100,17 @@ impl Endpoint {
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let server = serve(observe_requests(app, counters.clone(), None)).await;
|
||||
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
|
||||
let counters = counters.clone();
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = counters.clone();
|
||||
async move {
|
||||
let response = next.run(request).await;
|
||||
result_serialization::observe_body(response, counters)
|
||||
}
|
||||
}
|
||||
}));
|
||||
let server = serve(app).await;
|
||||
Self {
|
||||
server,
|
||||
_upstream: upstream,
|
||||
@@ -109,6 +122,17 @@ impl Endpoint {
|
||||
}
|
||||
|
||||
async fn post(&self, revision: &str, session: Option<&str>, body: &Value) -> reqwest::Response {
|
||||
self.post_accept(revision, session, body, "application/json")
|
||||
.await
|
||||
}
|
||||
|
||||
async fn post_accept(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
accept: &str,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(format!(
|
||||
"{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
@@ -116,7 +140,12 @@ impl Endpoint {
|
||||
))
|
||||
.bearer_auth(&self.key)
|
||||
// Also guards the legacy JSON-only contract; no SSE parsing fallback here.
|
||||
.header("Accept", "application/json")
|
||||
.header("Accept", accept)
|
||||
.header("x-request-id", "sdk-result-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -31,7 +31,23 @@
|
||||
|
||||
Подключить SDK к действующему пути и перенести стандартные envelopes, dispatch, lifecycle и transport. Порядок переноса устанавливается по результату первого опыта, без параллельных writers одних MCP-файлов.
|
||||
|
||||
Первый срез #107: `build_app` направляет `tools/list` обеих revisions и `tools/call` через `app/rmcp_dispatch.rs`. Параметры rmcp=3.7.0 (`PaginatedRequestParams`/`CallToolRequestParams`) определяют команду существующего shared Tools service; расширения Crank `limit`/confirmation сохраняются отдельно. Потребитель — штатный MCP HTTP клиент, не изолированный router #106. Текущие admission, свежая identity, lifecycle, era-specific ответы и PostgreSQL sessions остаются у прежнего transport; SDK HTTP transport не подключён. Это только Tools request dispatch/model seam: SDK response envelopes, остальные handlers, transport и lifecycle ещё не перенесены. Полный #107 не завершён; проверки #106 не являются доказательством завершения миграции.
|
||||
Первый срез #107: `build_app` направляет `tools/list` обеих revisions и `tools/call` через `app/rmcp_dispatch.rs`. Параметры rmcp=3.7.0 (`PaginatedRequestParams`/`CallToolRequestParams`) определяют команду существующего shared Tools service; расширения Crank `limit`/confirmation сохраняются отдельно. Потребитель — штатный MCP HTTP клиент, не изолированный router #106. Текущие admission, свежая identity, lifecycle, era-specific ответы и PostgreSQL sessions остаются у прежнего transport; SDK HTTP transport не подключён. В следующем Tools response-срезе `app/response.rs` строит и сериализует настоящие rmcp `ListToolsResult`/`Tool` и `CallToolResult`/`ContentBlock`; эти builders используют оба HTTP dispatch и общий JSON/SSE terminal, а изолированный `rmcp_tools` переиспользует typed builders. Явная проекция сохраняет revision defaults, pretty text, tool-error contract, `isError` и present-null `structuredContent`; после SDK list serialization сохраняются исходные top-level extensions/optional null и непрозрачные annotations/icons. Штатный producer публикует name/title/description/inputSchema: расширения защищены локальной builder-регрессией, а не объявлены новыми runtime-полями. HTTP-тесты проверяют обе revisions, success/tool errors/InvalidParams, ID/correlation, modern SSE terminal и несколько страниц опубликованного каталога. JSON-RPC envelope/status остаются прежней внешней границей; остальные handlers, transport и lifecycle ещё не перенесены. Полный #107 не завершён; проверки #106 не являются доказательством завершения миграции.
|
||||
|
||||
Следующий Resources-срез #107 подключает `resources/list`, `resources/read` и `resources/templates/list` обеих revisions к тому же `app/rmcp_dispatch.rs`: `PaginatedRequestParams`/`ReadResourceRequestParams` передают cursor/URI прежнему shared Resources service, а Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListResourcesResult`/`Resource`, `ReadResourceResult`/`ResourceContents` и `ListResourceTemplatesResult`/`ResourceTemplate` с прежними revision-specific cache defaults. Минимальная lossless-проекция сохраняет Crank template `parameters`, extensions/optional null и непрозрачные annotations/icons. Штатные producers по-прежнему публикуют прежние поля; builder-регрессия не добавляет runtime-возможностей. Потребитель — действующий `build_app` HTTP JSON/SSE terminal. Реальные HTTP-тесты отдельно подтверждают SDK request/result seam и сохранение wire; существующая Resources-матрица проверяет заполненные templates, exact-version binding, text/JSON/blob, scope/revocation и cursors. Handwritten builders этих трёх результатов заменены; domain/storage/auth, envelopes, transport и lifecycle не меняются. Subscribe/unsubscribe/notifications остаются прежними и не объявляются перенесёнными; остальные handlers и полный #107 ещё не завершены.
|
||||
|
||||
Prompts-срез #107 подключает `prompts/list` и `prompts/get` обеих revisions к `app/rmcp_dispatch.rs`: реальные `PaginatedRequestParams`/`GetPromptRequestParams` передают cursor/name и JSON-значения аргументов прежнему shared Prompts service; Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListPromptsResult`/`Prompt` и `GetPromptResult`/`PromptMessage`/`ContentBlock`, используемые штатным `build_app` HTTP JSON/SSE. Lossless-проекция сохраняет typed argument schemas/defaults, extensions/optional null и существующую роль `system`, которую pinned SDK Role не представляет; она восстанавливается после SDK serialization, не меняя опубликованные message boundaries. Прежний dispatch сохраняет revision-specific result/cache projections и ошибки. HTTP ATDD проверяет wire обеих revisions и реальный SDK request/result seam отдельно; affected Prompts/composition regression — exact binding, archive, typed rendering, pinned static/dynamic Resource content и fail-closed dependency errors. Handwritten list/get builders заменены; domain/storage/auth/envelopes/transport/lifecycle не меняются. Completion, notifications/subscriptions/progress/cancel/logging не объявляются перенесёнными. Полный #107 и feature qualification (UI/full/load/p95) этим срезом не завершены.
|
||||
|
||||
Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `completion/complete` обеих revisions к тому же request-scoped `app/rmcp_dispatch.rs`: настоящие `CompleteRequestParams`/`Reference`/`ArgumentInfo` передают reference и argument прежнему shared service. SDK context представляет только строки, поэтому исходный Crank JSON context сохраняется отдельно без фильтрации/приведения типов и проходит прежнюю domain validation. `app/response.rs` заменяет handwritten completion builder сериализацией `CompleteResult`/`CompletionInfo`, сохраняя omission `hasMore=false`, точный bounded total либо его отсутствие при partial scan и прежнюю внешнюю modern/legacy result projection. Потребитель — штатный `build_app` MCP HTTP JSON/SSE. Runtime ATDD отдельно наблюдает SDK request/result seam и сохранение Prompt/Resource refs, pinned/archive, populated/empty/bounded результатов, safe refusals/context, correlation/IDs и revoked-key rejection. Domain/storage/auth/envelopes/transport/lifecycle не меняются; signals/logging/subscriptions ещё не перенесены. Это не завершение #107, не external-client/feature qualification и не production deployment.
|
||||
|
||||
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
|
||||
|
||||
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 не завершены.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
|
||||
Reference in new issue
Block a user