feat(epic3): уведомления об изменении Resource/Prompt каталога MCP (Story 3.19)
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Failing after 4m10s
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) Failing after 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Failing after 4m10s
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) Failing after 1s
CI / Deploy (pull_request) Skipped
Story 3.19 / FR-19 на принятой базе Story 3.18 (`47a6e54`, PR #99): после commit опубликованного каталога Agent клиент получает `notifications/resources/list_changed` и/или `notifications/prompts/list_changed`, обе pinned revisions, а обычное чтение каталога остаётся авторитетным при потере сигнала. Scope ограничен list-change: `resources/subscribe`/`unsubscribe` остаются `-32601`, значение `resources.subscribe` остаётся `false` (одобренный владельцем вариант A). Публикация переносит только semantic delta Story 3.19 из `/home/codex/code/crank-worktrees/story31-worktree` (`1b6db09` + cumulative overlay) на принятый head 3.18, а не копирует worktree: - новый `protocol/signals.rs` (watcher, отпечаток каталога, bounded filter, revision-correct encoders, bounded legacy stream registry) и `protocol/signals_tests.rs` (17 unit oracles); - `subscriptions/listen` (modern-only dispatch registration) + честные `listChanged: true` объявления; `app/endpoint.rs` получает legacy GET producer/DELETE retire, `app/dispatch.rs` — modern listen stream; - ATDD `mcp_signals` 5 сценариев на реальном endpoint/PostgreSQL/artifact store; capability inventory и frozen/provenance проекции обновлены (`b90b59f3…`, inventory `10ca3538…`); - `scripts/ci-story-checks.sh`: добавлены 3.19-проверки, записи Story 3.18 сохранены (гейт не ослаблен). Принятая правка code-health `206ca78` сохранена: `app/endpoint.rs` 402 строки (было 381), `app/legacy_dispatch.rs` 731 без изменений, т.е. split не переписан. Новый ATDD-файл `mcp_signals.rs` до 1138 строк превышал лимит `scripts/check-rust-code-health.sh`, поэтому его сценарии механически вынесены в `mcp_signals/scenarios.rs` без изменения проверок. Наследованный дефект tooling-гейта: `tests/unit/test_validate_capability_inventory.py` требует, чтобы `Run tooling unit tests` шёл раньше `scripts/validate-capability-inventory.py`; в принятом `ci.yml` (3.18) шаг оказался в условном feature-job. Шаг перенесён в обязательный `rust` job перед проверкой inventory — исполняемый tooling-гейт теперь проверяется там же, где применяется; ни одна проверка не отключена и не ослаблена. Проверки на этом коммите: `ci-story-checks.sh` exit 0 — 4/9/1/12/10/3/5(+1 manual ignored)/17 passed; `crank-community-mcp --lib` 102/0; transport 20/0, mcp_prompts 15/0, revision_matrix::negotiation 23/0, era_isolation 5/0; `cargo fmt --check` и `cargo clippy -p crank-community-mcp -p mcp-server --all-targets -D warnings` — 0; `check-rust-code-health.sh` — pass; capability inventory `status=valid protocol_items=50 revisions=2`; `python3 -m unittest discover -s tests/unit` — 305 OK. NOT_RUN (честно, не PASS): полный `just verify`, межкомпонентная интеграция, нагрузка и квалификация ≥3 реальных клиентов — остаются на собранной фиче 3.20 по validation-policy.md.
This commit is contained in:
1 parent
47a6e54660
commit
a965bc4137
22 files changed
+2247
-55
No files matched your search
@@ -9,6 +9,7 @@ mod integration {
|
||||
mod mcp_completion;
|
||||
mod mcp_logging;
|
||||
mod mcp_prompts;
|
||||
mod mcp_signals;
|
||||
mod request_context;
|
||||
mod revision_matrix;
|
||||
mod static_resources;
|
||||
|
||||
@@ -23,7 +23,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
||||
let discover = endpoint.modern("server/discover", json!({}), None).await;
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["prompts"],
|
||||
json!({"listChanged": false}),
|
||||
json!({"listChanged": true}),
|
||||
"the modern advertisement must declare the prompts capability: {discover}"
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ async fn advertisement_declares_prompts_on_both_revisions() {
|
||||
let initialize = json_body(initialize_response).await;
|
||||
assert_eq!(
|
||||
initialize["result"]["capabilities"]["prompts"],
|
||||
json!({"listChanged": false}),
|
||||
json!({"listChanged": true}),
|
||||
"the legacy advertisement must declare the prompts capability: {initialize}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
//! Story 3.19 acceptance tests (AT-3.19-01..03, FR-19): committed Resource/Prompt catalog changes
|
||||
//! are announced to a client that asked for the signal of its revision, and the ordinary list
|
||||
//! methods stay authoritative when a notification is lost.
|
||||
//!
|
||||
//! Everything here is the production path: the real loopback MCP endpoint, the real PostgreSQL
|
||||
//! registry, the real immutable artifact store and real commits through the registry API. No stubbed
|
||||
//! route, no faked notification, no seeded notification table.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
mod scenarios;
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::http::header;
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{PromptDefinition, PromptSensitivity},
|
||||
};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest,
|
||||
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentDraftVersionRequest, CreateAgentRequest, PostgresRegistry,
|
||||
PublishAgentRequest, PublishRequest,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::common::*;
|
||||
|
||||
const MODERN_REVISION: &str = "2026-07-28";
|
||||
const LEGACY_REVISION: &str = "2025-11-25";
|
||||
|
||||
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
|
||||
const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
|
||||
const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
|
||||
const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
|
||||
const AGENT_SLUG: &str = "sales-signals";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Test-owned artifact root (0700), removed on drop.
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-mcp-signals-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&path).expect("artifact root must be creatable");
|
||||
let mut permissions = fs::metadata(&path).unwrap().permissions();
|
||||
std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
|
||||
fs::set_permissions(&path, permissions).expect("artifact root must be private");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The published fixture: one Tool, two bound Prompts, one published but initially unbound Resource.
|
||||
struct SignalsEndpoint {
|
||||
client: reqwest::Client,
|
||||
base_url: String,
|
||||
mcp_url: String,
|
||||
api_key: String,
|
||||
registry: PostgresRegistry,
|
||||
artifact_store: ArtifactStore,
|
||||
root: TestRoot,
|
||||
agent_id: AgentId,
|
||||
operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||
second_operation: crank_core::Operation<crank_schema::Schema, crank_mapping::MappingSet>,
|
||||
greeting: PromptId,
|
||||
review: PromptId,
|
||||
extra_prompt: PromptId,
|
||||
notice: ResourceId,
|
||||
}
|
||||
|
||||
impl SignalsEndpoint {
|
||||
fn modern_meta() -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-signals-atdd", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
async fn modern_post(&self, payload: Value) -> reqwest::Response {
|
||||
self.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// One modern request whose result is a JSON body (never a stream).
|
||||
async fn modern(&self, method: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = Self::modern_meta();
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", method)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 5, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// One modern request that offers both response modes and is expected to answer a JSON body
|
||||
/// (an admission or validation rejection, never a stream).
|
||||
async fn modern_offering_stream(&self, method: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = Self::modern_meta();
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", method)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 9, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected a JSON rejection for {method}: {body:?} {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy request inside the initialized session of this Agent.
|
||||
async fn legacy(&self, session: &str, method: &str, params: Value) -> Value {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 6, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected JSON for {method}, {status} {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
async fn legacy_session(&self) -> String {
|
||||
initialize_session(&self.client, &self.mcp_url, &self.api_key).await
|
||||
}
|
||||
|
||||
/// The legacy notification stream (`GET`), consumed as an SSE response.
|
||||
async fn legacy_stream(&self, session: &str) -> SseResponse {
|
||||
let response = self
|
||||
.client
|
||||
.get(&self.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
SseResponse::assert_open(response).await
|
||||
}
|
||||
|
||||
/// Open the modern `subscriptions/listen` stream with an explicit filter.
|
||||
async fn listen(&self, request_id: Value, filter: Value) -> SseResponse {
|
||||
let params = json!({ "notifications": filter, "_meta": Self::modern_meta() });
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "subscriptions/listen")
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"method": "subscriptions/listen",
|
||||
"params": params
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
SseResponse::assert_open(response).await
|
||||
}
|
||||
|
||||
fn agent_version(&self, version: u32) -> AgentVersion {
|
||||
AgentVersion {
|
||||
agent_id: self.agent_id.clone(),
|
||||
version,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_draft(&self, version: u32) {
|
||||
self.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
version: &self.agent_version(version),
|
||||
bindings: &[],
|
||||
updated_at: &OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a new Agent draft version opens");
|
||||
}
|
||||
|
||||
/// Write the exact catalog config of one draft version: Tool bindings, Resource bindings and
|
||||
/// Prompt bindings in the single accepted transition.
|
||||
async fn configure_draft(
|
||||
&self,
|
||||
version: u32,
|
||||
tool_bindings: &[crank_core::AgentOperationBinding],
|
||||
resource_bindings: &[AgentResourceBinding],
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) {
|
||||
self.registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
agent_version: version,
|
||||
bindings: tool_bindings,
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings,
|
||||
expected_state: None,
|
||||
},
|
||||
prompt_bindings,
|
||||
)
|
||||
.await
|
||||
.expect("the exact catalog config of the draft version saves");
|
||||
}
|
||||
|
||||
async fn publish_version(&self, version: u32) {
|
||||
self.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &self.agent_id,
|
||||
version,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the draft Agent version publishes");
|
||||
}
|
||||
|
||||
fn tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||
vec![binding_for_operation(&self.operation)]
|
||||
}
|
||||
|
||||
fn both_tool_bindings(&self) -> Vec<crank_core::AgentOperationBinding> {
|
||||
vec![
|
||||
binding_for_operation(&self.operation),
|
||||
binding_for_operation(&self.second_operation),
|
||||
]
|
||||
}
|
||||
|
||||
fn base_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||
vec![
|
||||
AgentPromptBinding {
|
||||
prompt_id: self.greeting.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: self.review.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn extended_prompts(&self) -> Vec<AgentPromptBinding> {
|
||||
let mut prompts = self.base_prompts();
|
||||
prompts.push(AgentPromptBinding {
|
||||
prompt_id: self.extra_prompt.clone(),
|
||||
prompt_version: 1,
|
||||
});
|
||||
prompts
|
||||
}
|
||||
|
||||
fn notice_binding(&self) -> AgentResourceBinding {
|
||||
AgentResourceBinding {
|
||||
resource_id: self.notice.clone(),
|
||||
resource_version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The draft version this Agent would open next, so the commit helpers do not depend on the
|
||||
/// order the test calls them in.
|
||||
async fn next_draft_version(&self) -> u32 {
|
||||
self.registry
|
||||
.get_agent_summary(&test_workspace_id(), &self.agent_id)
|
||||
.await
|
||||
.expect("the Agent summary reads")
|
||||
.expect("the fixture Agent exists")
|
||||
.current_draft_version
|
||||
+ 1
|
||||
}
|
||||
|
||||
/// The committed catalog change of AT-3.19-01: one Resource binding and one Prompt binding join
|
||||
/// the published Agent snapshot in a single publication.
|
||||
async fn commit_resource_and_prompt_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Tool catalog: the visible Resource/Prompt projection is
|
||||
/// identical, so it must not produce a Resource or Prompt signal.
|
||||
async fn commit_tool_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.both_tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Resource catalog: the visible Prompt projection is identical,
|
||||
/// so it must produce a Resource signal only.
|
||||
async fn commit_resource_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.base_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A commit that only changes the Prompt catalog: the visible Resource projection is identical,
|
||||
/// so it must produce a Prompt signal only.
|
||||
async fn commit_prompt_only_change(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.extended_prompts(),
|
||||
)
|
||||
.await;
|
||||
self.publish_version(version).await;
|
||||
}
|
||||
|
||||
/// A draft-only edit: nothing is published, so no committed catalog state changed.
|
||||
async fn edit_draft_without_publishing(&self) {
|
||||
let version = self.next_draft_version().await;
|
||||
self.open_draft(version).await;
|
||||
self.configure_draft(
|
||||
version,
|
||||
&self.both_tool_bindings(),
|
||||
&[self.notice_binding()],
|
||||
&self.base_prompts(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A live SSE response, read event by event.
|
||||
struct SseResponse {
|
||||
response: reqwest::Response,
|
||||
buffer: String,
|
||||
}
|
||||
|
||||
impl SseResponse {
|
||||
async fn assert_open(response: reqwest::Response) -> Self {
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
reqwest::StatusCode::OK,
|
||||
"the notification stream must be served"
|
||||
);
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
assert!(
|
||||
content_type.starts_with("text/event-stream"),
|
||||
"the notification stream must be an SSE response, got {content_type}"
|
||||
);
|
||||
Self {
|
||||
response,
|
||||
buffer: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The payload of the next `data:` frame, or `None` when nothing arrived within `timeout`.
|
||||
async fn next_data(&mut self, timeout: Duration) -> Option<Value> {
|
||||
loop {
|
||||
if let Some(index) = self.buffer.find("\n\n") {
|
||||
let block: String = self.buffer.drain(..index + 2).collect();
|
||||
for line in block.lines() {
|
||||
if let Some(data) = line.strip_prefix("data:") {
|
||||
return Some(
|
||||
serde_json::from_str(data.trim_start())
|
||||
.unwrap_or_else(|error| panic!("SSE frame must be JSON: {error}")),
|
||||
);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let chunk = tokio::time::timeout(timeout, self.response.chunk())
|
||||
.await
|
||||
.ok()?
|
||||
.ok()??;
|
||||
self.buffer.push_str(&String::from_utf8_lossy(&chunk));
|
||||
}
|
||||
}
|
||||
|
||||
/// The next frame within the watcher's bound.
|
||||
async fn expect_frame(&mut self, what: &str) -> Value {
|
||||
self.next_data(Duration::from_secs(6))
|
||||
.await
|
||||
.unwrap_or_else(|| panic!("expected {what} on the notification stream"))
|
||||
}
|
||||
|
||||
/// Exactly one safe negative window: no frame within `wait`.
|
||||
async fn expect_silence(&mut self, wait: Duration, what: &str) {
|
||||
if let Some(frame) = self.next_data(wait).await {
|
||||
panic!("expected no {what}, got {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_prompt(registry: &PostgresRegistry, prompt_id: &PromptId, name: &str) -> PromptId {
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": format!("{name} fixture"),
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": format!("Use {name}.")}]
|
||||
}))
|
||||
.expect("the fixture Prompt definition is valid");
|
||||
let created = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Prompt Draft is created");
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: created.updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Prompt version publishes");
|
||||
prompt_id.clone()
|
||||
}
|
||||
|
||||
/// Publish one static Resource through the production 3.6/3.7 registry transition.
|
||||
async fn publish_resource(
|
||||
registry: &PostgresRegistry,
|
||||
store: &ArtifactStore,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
let artifact = store
|
||||
.put_registered(bytes)
|
||||
.expect("the fixture bytes are registered durably");
|
||||
registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: format!("crank://resources/{}", resource_id.as_str()),
|
||||
name: resource_id.as_str().to_owned(),
|
||||
description: "Story 3.19 signal fixture".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Resource Draft is created");
|
||||
let current = registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), resource_id)
|
||||
.await
|
||||
.expect("the Resource Draft reads");
|
||||
registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: store
|
||||
.put_registered(bytes)
|
||||
.expect("the published bytes are registered durably"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Resource version publishes");
|
||||
}
|
||||
|
||||
async fn signals_endpoint() -> SignalsEndpoint {
|
||||
let root = TestRoot::new();
|
||||
let artifact_store = ArtifactStore::open(root.0.clone()).expect("the artifact store opens");
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
|
||||
let operation = test_operation(&upstream_base_url, "crm_create_lead");
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let second_operation = test_operation(&upstream_base_url, "crm_create_second");
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &second_operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &second_operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let greeting = publish_prompt(®istry, &PromptId::new("prm_a_greeting"), "greeting").await;
|
||||
let review = publish_prompt(®istry, &PromptId::new("prm_b_review"), "review").await;
|
||||
let extra_prompt = publish_prompt(®istry, &PromptId::new("prm_c_extra"), "extra").await;
|
||||
let notice = ResourceId::new("res_a_notice");
|
||||
publish_resource(®istry, &artifact_store, ¬ice, b"first notice").await;
|
||||
|
||||
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: AGENT_SLUG.to_owned(),
|
||||
description: "Story 3.19 signal fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[binding_for_operation(&operation)],
|
||||
})
|
||||
.await
|
||||
.expect("the draft Agent is created");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[binding_for_operation(&operation)],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: greeting.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: review.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("the exact bound Prompt versions are accepted");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the bound Agent publishes");
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
AGENT_SLUG,
|
||||
"mcp-signals",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
None,
|
||||
artifact_store.clone(),
|
||||
))
|
||||
.await;
|
||||
|
||||
SignalsEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
|
||||
base_url,
|
||||
api_key,
|
||||
registry,
|
||||
artifact_store,
|
||||
root,
|
||||
agent_id,
|
||||
operation,
|
||||
second_operation,
|
||||
greeting,
|
||||
review,
|
||||
extra_prompt,
|
||||
notice,
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_names(list: &Value) -> Vec<String> {
|
||||
list["result"]["prompts"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("prompts/list must return a page: {list}"))
|
||||
.iter()
|
||||
.map(|prompt| prompt["name"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resource_uris(list: &Value) -> Vec<String> {
|
||||
list["result"]["resources"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("resources/list must return a page: {list}"))
|
||||
.iter()
|
||||
.map(|resource| resource["uri"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Write a stand file that only the current user may read (credential files live here).
|
||||
fn write_private(path: &PathBuf, contents: &str) {
|
||||
use std::io::Write as _;
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.unwrap_or_else(|error| panic!("stand file {path:?} must be writable: {error}"));
|
||||
file.write_all(contents.as_bytes())
|
||||
.expect("the stand file must be written");
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Story 3.19 acceptance scenarios (AT-3.19-01..03, FR-19) on the harness in the parent module.
|
||||
//!
|
||||
//! Moved out of `mcp_signals.rs` verbatim (code-health split, 1000-line limit); no scenario,
|
||||
//! assertion or fixture changed.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Loopback disposable stand for the AC-3 representative-client evidence. This is deliberately not
|
||||
/// part of the automated ATDD: it publishes the fixture catalog, serves the real MCP endpoint on
|
||||
/// `127.0.0.1`, and then performs one commit per command file so an external MCP client can observe
|
||||
/// the signals on its own stream.
|
||||
///
|
||||
/// Run it explicitly (the credential file is `0600` and never printed):
|
||||
///
|
||||
/// ```text
|
||||
/// MCP_SIGNALS_STAND_DIR=/tmp/crank-signals-stand \
|
||||
/// cargo test -p mcp-server --test integration mcp_signals::scenarios::representative_client_stand \
|
||||
/// -- --ignored --exact --nocapture
|
||||
/// ```
|
||||
///
|
||||
/// Commands (create the file, wait for `<command>.done`): `commit-both`, `commit-prompt`,
|
||||
/// `commit-resource`, `commit-tool`, `draft`, `stop`.
|
||||
#[tokio::test]
|
||||
#[ignore = "manual loopback stand for the representative MCP Inspector client evidence"]
|
||||
async fn representative_client_stand() {
|
||||
let directory = PathBuf::from(
|
||||
std::env::var("MCP_SIGNALS_STAND_DIR")
|
||||
.expect("MCP_SIGNALS_STAND_DIR names the disposable stand directory"),
|
||||
);
|
||||
fs::create_dir_all(&directory).expect("the stand directory is creatable");
|
||||
let endpoint = signals_endpoint().await;
|
||||
write_private(
|
||||
&directory.join("stand.json"),
|
||||
&json!({ "url": endpoint.mcp_url, "token": endpoint.api_key }).to_string(),
|
||||
);
|
||||
println!("stand ready: {}", directory.join("stand.json").display());
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(900);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
for command in [
|
||||
"commit-both",
|
||||
"commit-prompt",
|
||||
"commit-resource",
|
||||
"commit-tool",
|
||||
"draft",
|
||||
"stop",
|
||||
] {
|
||||
let marker = directory.join(command);
|
||||
if !marker.exists() {
|
||||
continue;
|
||||
}
|
||||
fs::remove_file(&marker).expect("the command file is consumed once");
|
||||
if command == "stop" {
|
||||
println!("stand stopped: {command}");
|
||||
return;
|
||||
}
|
||||
match command {
|
||||
"commit-both" => endpoint.commit_resource_and_prompt_change().await,
|
||||
"commit-prompt" => endpoint.commit_prompt_only_change().await,
|
||||
"commit-resource" => endpoint.commit_resource_only_change().await,
|
||||
"commit-tool" => endpoint.commit_tool_only_change().await,
|
||||
_ => endpoint.edit_draft_without_publishing().await,
|
||||
}
|
||||
write_private(&directory.join(format!("{command}.done")), "done");
|
||||
println!("stand committed: {command}");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.19-01 (legacy): an open notification stream receives the Resource and Prompt list-change
|
||||
/// notifications only after the catalog commit, and `resources/list` / `prompts/list` serve the new
|
||||
/// state afterwards.
|
||||
#[tokio::test]
|
||||
async fn legacy_stream_announces_a_committed_catalog_change_after_the_commit() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let session = endpoint.legacy_session().await;
|
||||
|
||||
let mut stream = endpoint.legacy_stream(&session).await;
|
||||
// The watcher takes its baseline before it can report anything; let it settle before the commit.
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
stream
|
||||
.expect_silence(Duration::from_millis(1_200), "signal before any commit")
|
||||
.await;
|
||||
|
||||
// A draft-only edit is not a commit: nothing is announced.
|
||||
endpoint.edit_draft_without_publishing().await;
|
||||
stream
|
||||
.expect_silence(Duration::from_millis(2_500), "signal for a draft-only edit")
|
||||
.await;
|
||||
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
|
||||
let mut methods = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let frame = stream
|
||||
.expect_frame("the committed list-change signals")
|
||||
.await;
|
||||
assert_eq!(frame["jsonrpc"], json!("2.0"));
|
||||
assert!(
|
||||
frame.get("params").is_none(),
|
||||
"a legacy list-change notification carries no parameters: {frame}"
|
||||
);
|
||||
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||
}
|
||||
methods.sort();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![
|
||||
PROMPT_LIST_CHANGED.to_owned(),
|
||||
RESOURCE_LIST_CHANGED.to_owned()
|
||||
],
|
||||
"one signal per changed catalog type"
|
||||
);
|
||||
|
||||
// The ordinary list methods are authoritative for the same committed state.
|
||||
let prompts = endpoint.legacy(&session, "prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"prompts/list must serve the newly bound Prompt: {prompts}"
|
||||
);
|
||||
let resources = endpoint.legacy(&session, "resources/list", json!({})).await;
|
||||
assert!(
|
||||
resource_uris(&resources)
|
||||
.iter()
|
||||
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||
"resources/list must serve the newly bound Resource: {resources}"
|
||||
);
|
||||
|
||||
// A Tool-only commit keeps the Resource/Prompt projection: no further signal.
|
||||
endpoint.commit_tool_only_change().await;
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"signal for a Tool-only commit",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// AT-3.19-01/03 (modern): `subscriptions/listen` acknowledges the honoured filter with the request
|
||||
/// id, then delivers coalesced list-change notifications carrying the subscription id.
|
||||
#[tokio::test]
|
||||
async fn modern_listen_stream_acknowledges_then_announces_coalesced_changes() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let mut stream = endpoint
|
||||
.listen(
|
||||
json!(41),
|
||||
json!({
|
||||
"resourcesListChanged": true,
|
||||
"promptsListChanged": true,
|
||||
"toolsListChanged": true,
|
||||
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!(41)
|
||||
);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["notifications"],
|
||||
json!({ "promptsListChanged": true, "resourcesListChanged": true }),
|
||||
"only the implemented list-change types are acknowledged: {acknowledgement}"
|
||||
);
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
// Two commits in quick succession coalesce into one signal per changed type.
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
endpoint.commit_tool_only_change().await;
|
||||
|
||||
let mut methods = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let frame = stream
|
||||
.expect_frame("the coalesced list-change signal")
|
||||
.await;
|
||||
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(41));
|
||||
methods.push(frame["method"].as_str().unwrap().to_owned());
|
||||
}
|
||||
methods.sort();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![
|
||||
PROMPT_LIST_CHANGED.to_owned(),
|
||||
RESOURCE_LIST_CHANGED.to_owned()
|
||||
]
|
||||
);
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a duplicate or unrequested signal",
|
||||
)
|
||||
.await;
|
||||
|
||||
// A client that missed every notification still recovers the authoritative catalog.
|
||||
let prompts = endpoint.modern("prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"{prompts}"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.19-01/03 (modern): the acknowledged filter is the delivery contract. A prompts-only stream
|
||||
/// stays silent for a Resource-only commit, delivers exactly one Prompt frame with the subscription
|
||||
/// id for a Prompt commit, and never delivers an unrequested type.
|
||||
#[tokio::test]
|
||||
async fn modern_listen_delivers_only_the_negotiated_signal_types() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
let mut stream = endpoint
|
||||
.listen(
|
||||
json!("prompts-only"),
|
||||
json!({
|
||||
"promptsListChanged": true,
|
||||
"toolsListChanged": true,
|
||||
"resourceSubscriptions": ["crank://resources/res_a_notice"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let acknowledgement = stream.expect_frame("the acknowledgment").await;
|
||||
assert_eq!(acknowledgement["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!("prompts-only")
|
||||
);
|
||||
assert_eq!(
|
||||
acknowledgement["params"]["notifications"],
|
||||
json!({ "promptsListChanged": true }),
|
||||
"only the implemented and requested type is acknowledged: {acknowledgement}"
|
||||
);
|
||||
|
||||
// The watcher takes its baseline before it can report anything.
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
// A Resource-only commit is outside the negotiated filter: a server that ignored the filter would
|
||||
// emit a Resource frame here.
|
||||
endpoint.commit_resource_only_change().await;
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"signal for a Resource-only commit on a prompts-only stream",
|
||||
)
|
||||
.await;
|
||||
|
||||
// A Prompt-only commit is inside it: exactly one frame, correlated by the subscription id.
|
||||
endpoint.commit_prompt_only_change().await;
|
||||
let frame = stream
|
||||
.expect_frame("the negotiated Prompt list-change signal")
|
||||
.await;
|
||||
assert_eq!(frame["method"], PROMPT_LIST_CHANGED);
|
||||
assert_eq!(
|
||||
frame["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
json!("prompts-only")
|
||||
);
|
||||
|
||||
// Neither `toolsListChanged` nor `resourceSubscriptions` were honoured, so nothing else follows.
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a duplicate, Tools or URI-content signal",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// AT-3.19-03: the unsupported URI-content subscription surface is never acknowledged, and the
|
||||
/// legacy revision has no `subscriptions/listen` request at all.
|
||||
#[tokio::test]
|
||||
async fn unsupported_subscription_surfaces_are_refused_rather_than_faked() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
|
||||
for method in ["resources/subscribe", "resources/unsubscribe"] {
|
||||
let reply = endpoint
|
||||
.modern(method, json!({ "uri": "crank://resources/res_a_notice" }))
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply["error"]["code"],
|
||||
json!(-32601),
|
||||
"{method} must stay unimplemented: {reply}"
|
||||
);
|
||||
}
|
||||
|
||||
// The legacy revision opens its notification stream with GET only.
|
||||
let session = endpoint.legacy_session().await;
|
||||
let legacy_listen = endpoint
|
||||
.legacy(
|
||||
&session,
|
||||
"subscriptions/listen",
|
||||
json!({ "notifications": {} }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
legacy_listen["error"]["code"],
|
||||
json!(-32601),
|
||||
"subscriptions/listen is a modern-only request: {legacy_listen}"
|
||||
);
|
||||
|
||||
// A malformed filter is a bounded invalid-params answer with no echoed value.
|
||||
let malformed = endpoint
|
||||
.modern_offering_stream(
|
||||
"subscriptions/listen",
|
||||
json!({ "notifications": ["promptsListChanged"] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(malformed["error"]["code"], json!(-32602));
|
||||
assert_eq!(
|
||||
malformed["error"]["message"],
|
||||
json!("invalid subscriptions/listen notification filter")
|
||||
);
|
||||
|
||||
// Without an SSE-capable client the stream cannot be served at all.
|
||||
let without_sse = endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(header::ACCEPT, "application/json")
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "subscriptions/listen")
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 42,
|
||||
"method": "subscriptions/listen",
|
||||
"params": {
|
||||
"notifications": { "promptsListChanged": true },
|
||||
"_meta": SignalsEndpoint::modern_meta()
|
||||
}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(without_sse.status(), reqwest::StatusCode::NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
/// AT-3.19-02: a missed notification never loses committed state — a legacy client re-initializes
|
||||
/// (the retired session is a safe `404`) and reads the authoritative catalog, while the modern
|
||||
/// stateless client recovers through `server/discover` and the list methods.
|
||||
#[tokio::test]
|
||||
async fn a_lost_notification_is_recovered_through_the_authoritative_methods() {
|
||||
let endpoint = signals_endpoint().await;
|
||||
|
||||
// Modern recovery: the commit happens with no stream open at all.
|
||||
endpoint.commit_resource_and_prompt_change().await;
|
||||
let discover = endpoint.modern("server/discover", json!({})).await;
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["prompts"]["listChanged"],
|
||||
json!(true)
|
||||
);
|
||||
assert_eq!(
|
||||
discover["result"]["capabilities"]["resources"]["listChanged"],
|
||||
json!(true)
|
||||
);
|
||||
let resources = endpoint.modern("resources/list", json!({})).await;
|
||||
assert!(
|
||||
resource_uris(&resources)
|
||||
.iter()
|
||||
.any(|uri| uri == &format!("crank://resources/{}", endpoint.notice.as_str())),
|
||||
"the committed Resource is served to a client that missed the signal: {resources}"
|
||||
);
|
||||
|
||||
// Legacy recovery: the negotiated session can be dropped, and the revision-correct answer is a
|
||||
// safe `404` that makes the client re-initialize instead of resuming a stale stream.
|
||||
let session = endpoint.legacy_session().await;
|
||||
let mut stream = endpoint.legacy_stream(&session).await;
|
||||
tokio::time::sleep(Duration::from_millis(1_500)).await;
|
||||
|
||||
let deleted = endpoint
|
||||
.client
|
||||
.delete(&endpoint.mcp_url)
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(deleted.status(), reqwest::StatusCode::NO_CONTENT);
|
||||
stream
|
||||
.expect_silence(
|
||||
Duration::from_millis(2_500),
|
||||
"a signal on the retired session",
|
||||
)
|
||||
.await;
|
||||
|
||||
let stale_get = endpoint
|
||||
.client
|
||||
.get(&endpoint.mcp_url)
|
||||
.header(header::ACCEPT, "text/event-stream")
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
)
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", &session)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stale_get.status(),
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"a retired session is never resumed"
|
||||
);
|
||||
|
||||
let fresh = endpoint.legacy_session().await;
|
||||
let prompts = endpoint.legacy(&fresh, "prompts/list", json!({})).await;
|
||||
assert!(
|
||||
prompt_names(&prompts).contains(&"extra".to_owned()),
|
||||
"re-initialization serves the authoritative catalog: {prompts}"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user