refactor(mcp): consume SDK initialized notification in legacy handshake
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 33m16s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 33m16s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
This commit is contained in:
1 parent
326f209bc5
commit
156a849087
9 files changed
+611
-3
No files matched your search
@@ -851,6 +851,7 @@ pub(super) async fn handle_initialized_notification(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
notification: rmcp::model::ClientNotification,
|
||||
) -> Response {
|
||||
match session_id_from_headers(headers) {
|
||||
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
||||
@@ -858,6 +859,15 @@ pub(super) async fn handle_initialized_notification(
|
||||
if session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug =>
|
||||
{
|
||||
let rmcp::model::ClientNotification::InitializedNotification(initialized) =
|
||||
notification
|
||||
else {
|
||||
unreachable!("initialized handler requires the SDK initialized variant")
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
|
||||
#[cfg(not(test))]
|
||||
let _ = initialized;
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
|
||||
@@ -75,12 +75,20 @@ pub(crate) struct CounterSet {
|
||||
sdk_jsonrpc_error: AtomicUsize,
|
||||
sdk_ping_request: AtomicUsize,
|
||||
sdk_ping_result: AtomicUsize,
|
||||
sdk_initialized_decoded: AtomicUsize,
|
||||
sdk_initialized_consumed: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_initialized_decoded(&self) -> usize {
|
||||
self.sdk_initialized_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialized_consumed(&self) -> usize {
|
||||
self.sdk_initialized_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_request(&self) -> usize {
|
||||
self.sdk_ping_request.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -431,6 +439,23 @@ pub(crate) fn sdk_ping_result_serialized() {
|
||||
#[path = "../rmcp_ping_runtime_tests.rs"]
|
||||
mod rmcp_ping_runtime_tests;
|
||||
|
||||
/// Mark immediately after typed method-projection decode, not variant consumption.
|
||||
pub(crate) fn sdk_initialized_notification_decoded(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_decoded);
|
||||
}
|
||||
|
||||
/// Mark inside the matched SDK variant, after guards and immediately before session mutation.
|
||||
pub(crate) fn sdk_initialized_notification_consumed(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialized_runtime_tests.rs"]
|
||||
mod rmcp_initialized_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -83,7 +83,13 @@ pub(super) async fn handle_legacy_request(
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_initialized_notification(state, path, headers).await
|
||||
handle_initialized_notification(
|
||||
state,
|
||||
path,
|
||||
headers,
|
||||
crate::protocol::initialized_notification(message),
|
||||
)
|
||||
.await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
|
||||
@@ -45,6 +45,16 @@ fn restore_registry_extensions(result: &mut Value, advertised: Value) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn initialized_notification(message: &Value) -> rmcp::model::ClientNotification {
|
||||
// Admission already checked the envelope; ignored params must not acquire SDK constraints.
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(serde_json::json!({"method": message["method"]}))
|
||||
.expect("registry dispatched a validated initialized notification");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_initialized_notification_decoded(¬ification);
|
||||
notification.into()
|
||||
}
|
||||
|
||||
pub(crate) fn ping_result(message: &Value, revision: &str) -> Value {
|
||||
// Ping params were ignored after admission; do not add SDK constraints to extensions.
|
||||
let request: PingRequest = serde_json::from_value(serde_json::json!({
|
||||
|
||||
@@ -42,7 +42,7 @@ pub(crate) use completion::{
|
||||
handle_completion_command,
|
||||
};
|
||||
pub(crate) use lifecycle_sdk::{
|
||||
discover_result, initialize_params, initialize_result, ping_result,
|
||||
discover_result, initialize_params, initialize_result, initialized_notification, ping_result,
|
||||
};
|
||||
pub(crate) use logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Initialized HTTP transition against the existing PostgreSQL store, not an SDK session manager.
|
||||
use super::*;
|
||||
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
|
||||
use crate::session::{SessionState, SessionStoreError};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
struct FaultStore {
|
||||
inner: PostgresTransportSessionStore,
|
||||
fail_get: AtomicBool,
|
||||
fail_mark: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for FaultStore {
|
||||
async fn create(
|
||||
&self,
|
||||
revision: &str,
|
||||
workspace: &str,
|
||||
agent: &str,
|
||||
elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.inner
|
||||
.create(revision, workspace, agent, elicitation, now, expires)
|
||||
.await
|
||||
}
|
||||
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
if self.fail_get.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test read failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.get(id).await
|
||||
}
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
if self.fail_mark.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test mark failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.mark_initialized(id, now).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(id).await
|
||||
}
|
||||
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(now).await
|
||||
}
|
||||
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(now).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_durable", "t_9c033310").await;
|
||||
let registry = test_registry().await;
|
||||
let pool = registry.pool().clone();
|
||||
let store = Arc::new(FaultStore {
|
||||
inner: PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap(),
|
||||
fail_get: AtomicBool::new(false),
|
||||
fail_mark: AtomicBool::new(false),
|
||||
});
|
||||
let h = Endpoint::started_with_store(Some(store.clone())).await;
|
||||
let response = post(&h, None, "application/json", legacy_initialize(80)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let before = store.get(&id).await.unwrap().unwrap();
|
||||
assert!(!before.initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [1, 1]);
|
||||
let restarted = PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let after = restarted.get(&id).await.unwrap().unwrap();
|
||||
assert!(after.initialized);
|
||||
assert_eq!(after.id, before.id);
|
||||
assert_eq!(after.workspace_slug, before.workspace_slug);
|
||||
assert_eq!(after.agent_slug, before.agent_slug);
|
||||
assert_eq!(after.protocol_version, before.protocol_version);
|
||||
assert_eq!(after.created_at, before.created_at);
|
||||
assert_eq!(after.expires_at, before.expires_at);
|
||||
assert_eq!(after.supports_elicitation, before.supports_elicitation);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":81,"method":"ping"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(body(response, false).await.get("error").is_none());
|
||||
|
||||
let pending = store
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
AGENT_SLUG,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
store.fail_mark.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [counts[0] + 1, counts[1] + 1]);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
store.fail_mark.store(false, Ordering::SeqCst);
|
||||
|
||||
// Fail reads without touching registry/auth tables; admission must stop before the SDK.
|
||||
store.fail_get.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
store.fail_get.store(false, Ordering::SeqCst);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_foreign_and_revision_guards_leave_state_untouched() {
|
||||
let h = endpoint().await;
|
||||
for (revision, workspace, agent) in [
|
||||
(LEGACY_REVISION, "foreign-workspace", AGENT_SLUG),
|
||||
(LEGACY_REVISION, WORKSPACE_SLUG, "foreign-agent"),
|
||||
("2024-11-05", WORKSPACE_SLUG, AGENT_SLUG),
|
||||
(MODERN_REVISION, WORKSPACE_SLUG, AGENT_SLUG),
|
||||
] {
|
||||
let id = h
|
||||
.sessions
|
||||
.create(
|
||||
revision,
|
||||
workspace,
|
||||
agent,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
let ops = h.sessions.snapshot();
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
if workspace != WORKSPACE_SLUG || agent != AGENT_SLUG {
|
||||
404
|
||||
} else {
|
||||
400
|
||||
}
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), counts[1]);
|
||||
if workspace == WORKSPACE_SLUG && agent == AGENT_SLUG {
|
||||
assert_eq!(h.counters.sdk_initialized_decoded(), counts[0]);
|
||||
}
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.sessions.retained(&id).await.unwrap(), state);
|
||||
}
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.header("MCP-Session-Id", "conflicting-session")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
h.registry
|
||||
.revoke_platform_api_key_for_agent(
|
||||
&workspace_id(),
|
||||
&agent_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_progress_other"),
|
||||
&OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.other_key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 401);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().create, ops.create);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! #107 initialized: real HTTP wire control, independent SDK decode and consumption oracles.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
#[path = "rmcp_initialized_durable_tests.rs"]
|
||||
mod durable;
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_owner", "t_9c033310").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
fn sdk(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_initialized_decoded(), c.sdk_initialized_consumed()]
|
||||
}
|
||||
|
||||
async fn post(
|
||||
h: &Endpoint,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
payload: Value,
|
||||
) -> reqwest::Response {
|
||||
h.request(LEGACY_REVISION, session, &h.key, accept, payload)
|
||||
.header("x-request-id", "initialized-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn correlation(response: &reqwest::Response) {
|
||||
assert_eq!(response.headers()["x-request-id"], "initialized-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
}
|
||||
|
||||
async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
correlation(&response);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("data:"))
|
||||
.map(|l| serde_json::from_str(l.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
async fn initialize(h: &Endpoint, accept: &str) -> String {
|
||||
let response = post(h, None, accept, legacy_initialize(71)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], 71);
|
||||
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
assert!(wire.get("error").is_none());
|
||||
let state = h.sessions.retained(&id).await.expect("retained session");
|
||||
assert!(!state.initialized);
|
||||
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
|
||||
assert_eq!(state.agent_slug, AGENT_SLUG);
|
||||
id
|
||||
}
|
||||
|
||||
async fn control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({"ignored":[null,true],
|
||||
"protocolVersion":false,"capabilities":42,"_meta":{"future":[]}})),
|
||||
] {
|
||||
let id = initialize(&h, accept).await;
|
||||
let untouched = initialize(&h, "application/json").await;
|
||||
let before_state = h.sessions.retained(&id).await.unwrap();
|
||||
let mut notification = json!({"jsonrpc":"2.0","method":"notifications/initialized",
|
||||
"extension":{"future":[null,42]}});
|
||||
if let Some(params) = params {
|
||||
notification["params"] = params;
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let response = post(&h, Some(&id), accept, notification.clone()).await;
|
||||
assert_eq!(response.status(), 202);
|
||||
correlation(&response);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_session_ops(
|
||||
"initialized",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
assert_deltas(
|
||||
"initialized",
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
assert!(state.initialized);
|
||||
assert_eq!(state.id, before_state.id);
|
||||
assert_eq!(state.workspace_slug, before_state.workspace_slug);
|
||||
assert_eq!(state.agent_slug, before_state.agent_slug);
|
||||
assert_eq!(state.protocol_version, before_state.protocol_version);
|
||||
assert_eq!(state.created_at, before_state.created_at);
|
||||
assert_eq!(state.expires_at, before_state.expires_at);
|
||||
assert_eq!(
|
||||
state.supports_elicitation,
|
||||
before_state.supports_elicitation
|
||||
);
|
||||
assert!(state.updated_at >= before_state.updated_at);
|
||||
assert!(!h.sessions.retained(&untouched).await.unwrap().initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
accept,
|
||||
json!({"jsonrpc":"2.0","id":"tools/Ю","method":"tools/list"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], "tools/Ю");
|
||||
assert!(wire.get("error").is_none());
|
||||
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
eprintln!(
|
||||
"existing GREEN initialize -> initialized -> tools/list accept={accept} notification={notification}; SDK delta={:?}",
|
||||
deltas.last().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_wire_handshake_tolerance_and_scoped_state() {
|
||||
control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_decoded_on_real_http_handshake() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"real HTTP initialized must decode the SDK InitializedNotification"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_variant_consumed_by_session_transition() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"matched ClientNotification variant must drive the real scoped session mutation, not just decode"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_admission_and_wrong_kind_never_mutate_or_consume() {
|
||||
let h = endpoint().await;
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let mut wrong_initialize = legacy_initialize(72);
|
||||
wrong_initialize.as_object_mut().unwrap().remove("id");
|
||||
let mut wrong_initialized = initialized_notification();
|
||||
wrong_initialized["id"] = json!(73);
|
||||
let mut cases = vec![
|
||||
(wrong_initialize, 202, None),
|
||||
(wrong_initialized, 200, Some(-32601)),
|
||||
];
|
||||
for params in [json!(null), json!(true), json!(42), json!("bad"), json!([])] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":params}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
}
|
||||
for meta in [
|
||||
json!(null),
|
||||
json!(false),
|
||||
json!(42),
|
||||
json!("bad"),
|
||||
json!([]),
|
||||
] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":meta}}),
|
||||
400,
|
||||
Some(-32020),
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
json!({"jsonrpc":"1.0","method":"notifications/initialized"}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
for (payload, status, code) in cases {
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = sdk(&h.counters);
|
||||
let response = post(&h, Some(&id), "application/json", payload.clone()).await;
|
||||
assert_eq!(response.status().as_u16(), status, "{payload}");
|
||||
if let Some(code) = code {
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(wire["error"]["code"], code, "{payload}: {wire}");
|
||||
assert!(wire.get("result").is_none());
|
||||
} else {
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
let after = h.sessions.snapshot();
|
||||
assert_eq!(after.create, ops.create);
|
||||
assert_eq!(after.mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
assert_eq!(
|
||||
sdk(&h.counters),
|
||||
before,
|
||||
"rejected before SDK decode/consume: {payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_missing_unknown_sessions_and_modern_never_consume() {
|
||||
let h = endpoint().await;
|
||||
for (session, status) in [(None, 400), (Some("unknown-session"), 404)] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = post(&h, session, "application/json", initialized_notification()).await;
|
||||
assert_eq!(response.status().as_u16(), status);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":modern_meta()}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(
|
||||
h.sessions.snapshot(),
|
||||
ops,
|
||||
"modern signal never accesses storage"
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_observer_independent_positive_control() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(json!({"method":"notifications/initialized"})).unwrap();
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
assert_eq!(sdk(&a), [0, 0]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0]);
|
||||
assert_eq!(sdk(&b), [0, 1], "decode alone never proves consumption");
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -26,6 +26,9 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
Self::started_with_store(None).await
|
||||
}
|
||||
pub async fn started_with_store(store: Option<crate::session::SharedSessionStore>) -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("progress_owner", "t_d65dd129").await;
|
||||
let registry = test_registry().await;
|
||||
let gate = Arc::new(Semaphore::new(0));
|
||||
@@ -103,7 +106,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
sessions.clone(),
|
||||
store.unwrap_or_else(|| sessions.clone()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
|
||||
@@ -51,6 +51,8 @@ Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет
|
||||
|
||||
Ping-срез #107 на базе rc.28/rmcp3.9.0 подключает обе штатные HTTP ветки к общему `protocol/lifecycle_sdk.rs::ping_result`: проекция уже допущенного метода декодируется в `PingRequest`, его SDK request variant выбирает `ServerResult::empty(())`, а сериализованный SDK результат поступает в прежний JSON/SSE terminal. Удалены два handwritten ping result builder; Crank добавляет прежний `protocolVersion` из legacy session либо modern identity, а modern result projection сохраняется. Игнорируемые params/extensions не получают новых SDK ограничений. Legacy initialized-session guard остаётся перед helper; modern ping не обращается к sessions. Runtime ATDD отдельно подтверждает SDK request/result execution и прежние wire/status/headers/id/correlation обеих revisions; affected regressions проверяют session/admission/method/revocation guards. Generic dispatch, session storage/TTL/reconnect, admission/auth и transport остаются прежними; полный #107, feature qualification и production deployment не завершены.
|
||||
|
||||
Initialized-срез #107 на базе rc.29/rmcp3.9.0 подключает штатный legacy HTTP handshake к `InitializedNotification` и `ClientNotification`: после registry/admission проекция метода декодируется SDK, а matched initialized variant после прежних session/scope guards разрешает существующий durable `mark_initialized`. Игнорируемые params/extensions, 202 с пустым телом, JSON/SSE и modern no-session поведение сохранены; SDK SessionManager не используется. Runtime-тесты отдельно наблюдают decoding и consumption, проверяют PostgreSQL reconnect и отказ store на чтении/записи. Это только lifecycle-срез, не завершение #107.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user