Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
835947e9fc | ||
|
|
2b36add550 |
No files matched your search
@@ -40,6 +40,7 @@ mod rmcp_http;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[path = "rmcp_http_tests.rs"]
|
#[path = "rmcp_http_tests.rs"]
|
||||||
mod rmcp_http_tests;
|
mod rmcp_http_tests;
|
||||||
|
mod rmcp_progress_cancel;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod rmcp_session_tests;
|
mod rmcp_session_tests;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -66,9 +66,19 @@ pub(crate) struct CounterSet {
|
|||||||
sdk_logging_dispatch: AtomicUsize,
|
sdk_logging_dispatch: AtomicUsize,
|
||||||
sdk_logging_level: AtomicUsize,
|
sdk_logging_level: AtomicUsize,
|
||||||
sdk_logging_notification: AtomicUsize,
|
sdk_logging_notification: AtomicUsize,
|
||||||
|
sdk_progress_notification: AtomicUsize,
|
||||||
|
sdk_cancelled_params: AtomicUsize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CounterSet {
|
impl CounterSet {
|
||||||
|
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 {
|
pub(crate) fn sdk_logging_dispatch(&self) -> usize {
|
||||||
self.sdk_logging_dispatch.load(Ordering::SeqCst)
|
self.sdk_logging_dispatch.load(Ordering::SeqCst)
|
||||||
}
|
}
|
||||||
@@ -302,6 +312,19 @@ pub(crate) fn sdk_logging_notification_serialized() {
|
|||||||
#[path = "../rmcp_logging_runtime_tests.rs"]
|
#[path = "../rmcp_logging_runtime_tests.rs"]
|
||||||
mod rmcp_logging_runtime_tests;
|
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;
|
||||||
|
|
||||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||||
let _ = OBSERVER.try_with(|counters| {
|
let _ = OBSERVER.try_with(|counters| {
|
||||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||||
|
|||||||
@@ -799,27 +799,24 @@ async fn handle_cancelled_notification(
|
|||||||
message: &Value,
|
message: &Value,
|
||||||
credential: &VerifiedMachineCredential,
|
credential: &VerifiedMachineCredential,
|
||||||
) -> Response {
|
) -> 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();
|
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||||
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
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.
|
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||||
if matches!(request_id, Value::String(_) | Value::Number(_)) {
|
Ok(Some(session)) => {
|
||||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
session.workspace_slug == path.workspace_slug
|
||||||
Ok(Some(session)) => {
|
&& session.agent_slug == path.agent_slug
|
||||||
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,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
_ => 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()
|
StatusCode::ACCEPTED.into_response()
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
||||||
use futures_util::stream;
|
use futures_util::stream;
|
||||||
|
use rmcp::model::{NumberOrString, ProgressNotificationParam};
|
||||||
use serde_json::{Number, Value, json};
|
use serde_json::{Number, Value, json};
|
||||||
use tokio::sync::{mpsc, watch};
|
use tokio::sync::{mpsc, watch};
|
||||||
|
|
||||||
@@ -82,10 +83,13 @@ impl ProgressToken {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_value(&self) -> Value {
|
fn sdk_token(&self) -> NumberOrString {
|
||||||
match self {
|
match self {
|
||||||
Self::Text(text) => Value::String(text.clone()),
|
Self::Text(text) => NumberOrString::String(text.clone().into()),
|
||||||
Self::Number(number) => Value::Number(number.clone()),
|
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,
|
/// 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.
|
/// 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 {
|
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!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"method": "notifications/progress",
|
"method": "notifications/progress",
|
||||||
"params": {
|
"params": params,
|
||||||
"progressToken": token.as_value(),
|
|
||||||
"progress": event.progress,
|
|
||||||
"message": event.message,
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,44 @@ fn token(value: Value) -> Option<ProgressToken> {
|
|||||||
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
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]
|
#[test]
|
||||||
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
|
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
//! 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(super) struct Endpoint {
|
||||||
|
pub registry: crank_registry::PostgresRegistry,
|
||||||
|
pub counters: Arc<CounterSet>,
|
||||||
|
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 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 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,
|
||||||
|
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"]
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -41,6 +41,8 @@ Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `com
|
|||||||
|
|
||||||
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
|
Logging-срез #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.
|
||||||
|
|
||||||
Проверяемый результат:
|
Проверяемый результат:
|
||||||
|
|
||||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||||
|
|||||||
Reference in new issue
Block a user