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

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:
bsodfather committed 2026-10-25 21:00:51 +00:00
1 parent 47a6e54660
commit a965bc4137
22 files changed
+2247 -55

No files matched your search

+3 -2
View File
@@ -81,6 +81,9 @@ jobs:
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
python3 scripts/check-metrics-boundaries.py --root .
- name: Run tooling unit tests
run: python3 -m unittest discover -s tests/unit
- name: Check Capability Inventory
run: |
required_args=""
@@ -203,8 +206,6 @@ jobs:
docker info
- name: Install dependency policy tool
run: cargo install cargo-deny --version 0.20.2 --locked
- name: Run tooling unit tests
run: python3 -m unittest discover -s tests/unit
- name: Check dependency licenses and advisories
run: cargo deny --locked check advisories bans licenses sources
- name: Run offline OpenAPI support corpus gate
+1
View File
@@ -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(&registry, &PromptId::new("prm_a_greeting"), "greeting").await;
let review = publish_prompt(&registry, &PromptId::new("prm_b_review"), "review").await;
let extra_prompt = publish_prompt(&registry, &PromptId::new("prm_c_extra"), "extra").await;
let notice = ResourceId::new("res_a_notice");
publish_resource(&registry, &artifact_store, &notice, 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(
&registry,
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}"
);
}
+4
View File
@@ -86,6 +86,9 @@ pub(super) struct AppState {
/// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a
/// client-scoped level, never a process-global one, and it needs no schema migration.
pub(super) logging_levels: Arc<crate::protocol::LogLevelStore>,
/// Story 3.19: the bounded table of the legacy session that currently owns the notification
/// stream, so one session never broadcasts the same list-change signal into two streams.
pub(super) signal_streams: Arc<crate::protocol::StreamRegistry>,
}
#[derive(Clone)]
@@ -253,6 +256,7 @@ fn build_app_inner(
credential_verifier,
allowed_origins: AllowedOrigins::new(public_base_url),
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
});
if start_background_workers {
spawn_approval_recovery(Arc::clone(&state));
+77 -1
View File
@@ -23,7 +23,9 @@ use crate::{
},
session::SessionState,
tool_error::execution_locale,
transport::{ResponseMode, json_response, session_id_from_headers, transport_response},
transport::{
ResponseMode, json_response, session_id_from_headers, sse_response, transport_response,
},
};
use axum::{
http::{HeaderMap, StatusCode},
@@ -658,6 +660,80 @@ pub(super) async fn handle_modern_request(
}
}
}
// Story 3.19: the modern long-lived notification stream. The response is itself the SSE
// stream that stays open, so it is built here instead of going through the one-shot
// response helpers: the acknowledgment is its first frame, then the coalesced list-change
// signals, and closing the HTTP stream ends the producer.
DispatchDecision::Allowed {
handler: MethodHandler::SubscriptionsListen,
..
} => {
// A notification stream is an SSE body by construction: a client that did not offer
// `text/event-stream` could not receive it.
if !crate::transport::accepts_event_stream(headers) {
return StatusCode::NOT_ACCEPTABLE.into_response();
}
let filter: crate::protocol::ListenParams =
match serde_json::from_value(params(message)) {
Ok(filter) => filter,
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(
request_id(message),
-32602,
crate::protocol::INVALID_LISTEN_FILTER,
),
response_mode,
None,
Some(version),
);
}
};
let accepted = match filter.notifications.accepted() {
crate::protocol::FilterOutcome::Accepted(accepted) => accepted,
crate::protocol::FilterOutcome::Invalid(detail) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, detail),
response_mode,
None,
Some(version),
);
}
};
// The subscription id is the JSON-RPC id of this request; a value whose encoding is not
// bounded cannot be a frame identity carrier and is refused before the stream opens.
let Some(subscription_id) = crate::protocol::subscription_id(&request_id(message))
else {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32600, "invalid JSON-RPC message"),
response_mode,
None,
Some(version),
);
};
let Ok(permit) = super::metrics::ActiveStreamGuard::try_acquire(&state.session_slots)
else {
return StatusCode::TOO_MANY_REQUESTS.into_response();
};
let acknowledged = crate::protocol::acknowledged_frame(&subscription_id, accepted);
let receiver = crate::protocol::spawn_signal_watch(
Arc::clone(state),
crate::protocol::Watch {
workspace_slug: path.workspace_slug.clone(),
agent_slug: path.agent_slug.clone(),
signals: accepted,
wire: crate::protocol::Wire::Modern(subscription_id),
legacy_stream: None,
deadline: None,
},
);
let stream = crate::protocol::frames_stream(vec![acknowledged], receiver, permit);
sse_response(StatusCode::OK, stream, None, Some(version))
}
// The standard Prompt requests are registered capabilities now; any other
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
_ => crate::protocol::modern_method_not_found_response(message),
+29 -8
View File
@@ -26,12 +26,11 @@ use axum::{
Json,
extract::{Extension, Path, State, rejection::JsonRejection},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response, sse::Event},
response::{IntoResponse, Response},
};
use crank_core::{CorrelationContext, PlatformApiKeyScope};
use futures_util::stream;
use serde_json::Value;
use std::{convert::Infallible, sync::Arc, time::Duration};
use std::{sync::Arc, time::Duration, time::Instant};
use tracing::info;
use super::dispatch::handle_modern_request;
@@ -103,11 +102,32 @@ pub(super) async fn mcp_get(
return StatusCode::TOO_MANY_REQUESTS.into_response();
};
let stream = stream::unfold(permit, |permit| async move {
tokio::time::sleep(Duration::from_millis(TRANSPORT_SESSION_TTL_MS)).await;
drop(permit);
None::<(Result<Event, Infallible>, _)>
});
// Story 3.19: the pinned legacy transport forbids broadcasting one JSON-RPC message across the
// SSE streams of a session, so exactly one admitted `GET` receives the Resource/Prompt
// list-change signals. A newer `GET` takes them over and the older stream simply ends; a
// `DELETE` retires the producer, so a stale generation never writes into a reconnect.
let Some(generation) = state.signal_streams.admit(&session_id) else {
// The bounded owner table is contended: refuse this admission instead of waiting.
return StatusCode::TOO_MANY_REQUESTS.into_response();
};
let receiver = crate::protocol::spawn_signal_watch(
Arc::clone(&state),
crate::protocol::Watch {
workspace_slug: path.workspace_slug.clone(),
agent_slug: path.agent_slug.clone(),
signals: crate::protocol::Signals::BOTH,
wire: crate::protocol::Wire::Legacy,
legacy_stream: Some((
Arc::clone(&state.signal_streams),
session_id.clone(),
generation,
)),
deadline: Some(Instant::now() + Duration::from_millis(TRANSPORT_SESSION_TTL_MS)),
},
);
// The stream permit lives in the response stream: a client that closes the SSE connection ends
// the producer and releases the slot, and no signal is queued for a reader that is gone.
let stream = crate::protocol::frames_stream(Vec::new(), receiver, permit);
sse_response(
StatusCode::OK,
@@ -160,6 +180,7 @@ pub(super) async fn mcp_delete(
match state.sessions.delete(&session_id).await {
Ok(true) => {
state.signal_streams.retire(&session_id);
state.session_metrics.refresh();
StatusCode::NO_CONTENT.into_response()
}
@@ -30,6 +30,7 @@ mod logging;
mod prompts;
mod registry;
mod resources;
mod signals;
pub(crate) use command::{
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
@@ -48,6 +49,10 @@ pub(crate) use resources::{
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
ResourcesOutcome, handle_resources_command, list_resource_templates,
};
pub(crate) use signals::{
FilterOutcome, INVALID_LISTEN_FILTER, ListenParams, Signals, StreamRegistry, Watch, Wire,
acknowledged_frame, frames_stream, spawn as spawn_signal_watch, subscription_id,
};
/// Resolved era of an incoming POST request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -22,6 +22,11 @@ pub(crate) enum CapabilityId {
Prompts,
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
Completions,
/// `subscriptions/listen` of the modern revision: a *client-sent* request that opens the
/// notification stream (Story 3.19). It is a dispatch-only registration without an advertisement
/// fragment because the pinned modern schema has no server `subscriptions` capability object;
/// there is no such method in the legacy revision at all.
Subscriptions,
/// `logging` server capability: safe structured `notifications/message` events of the negotiated
/// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries
/// the level per request in `_meta` and marks the capability deprecated (SEP-2577).
@@ -90,6 +95,9 @@ pub(crate) enum MethodHandler {
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
/// argument or one exact bound Resource template parameter (Story 3.17).
Completion,
/// `subscriptions/listen`: open the long-lived modern notification stream and deliver the
/// Resource/Prompt list-change signals the client opted in to (Story 3.19).
SubscriptionsListen,
/// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the
/// adapter can deliver safe structured `notifications/message` events of that context
/// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input.
@@ -371,7 +379,9 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
extension: None,
deprecated: None,
sub_features: FeatureSet(&["subscribe", "listChanged"]),
advertised: Some(("resources", &[("subscribe", false), ("listChanged", false)])),
// Story 3.19: the server really emits `notifications/resources/list_changed`; URI-content
// subscriptions (`subscribe`) remain unimplemented and are still advertised as false.
advertised: Some(("resources", &[("subscribe", false), ("listChanged", true)])),
revisions: MODERN_AND_LEGACY,
},
CapabilityIdDescriptor {
@@ -381,7 +391,8 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
extension: None,
deprecated: None,
sub_features: FeatureSet(&["listChanged"]),
advertised: Some(("prompts", &[("listChanged", false)])),
// Story 3.19: the server really emits `notifications/prompts/list_changed`.
advertised: Some(("prompts", &[("listChanged", true)])),
revisions: MODERN_AND_LEGACY,
},
CapabilityIdDescriptor {
@@ -422,6 +433,19 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
advertised: None,
revisions: LEGACY_ONLY,
},
CapabilityIdDescriptor {
// Story 3.19: dispatch-only registration of the modern `subscriptions/listen` request. The
// client sends it; the pinned modern schema declares no server `subscriptions` capability
// object, so it carries no advertisement fragment. The legacy revision has no such method.
id: CapabilityId::Subscriptions,
roster: Roster::Client,
kind: Kind::Method,
extension: None,
deprecated: None,
sub_features: FeatureSet(&[]),
advertised: None,
revisions: MODERN_ONLY,
},
CapabilityIdDescriptor {
id: CapabilityId::Ping,
roster: Roster::Server,
@@ -536,6 +560,17 @@ pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
required_headers: HEADERS_METHOD_ONLY,
handler: MethodHandler::LoggingSetLevel,
},
MethodDescriptor {
// Story 3.19: the modern long-lived notification stream. It declares the notification filter
// in its params, not a server-side name, so only the method header applies. The legacy
// revision opens its notification stream with `GET` instead, so this name is a wrong-era
// request there and must never be served.
name: "subscriptions/listen",
capability: CapabilityId::Subscriptions,
kind: Kind::Method,
required_headers: HEADERS_METHOD_ONLY,
handler: MethodHandler::SubscriptionsListen,
},
MethodDescriptor {
name: "ping",
capability: CapabilityId::Ping,
@@ -37,8 +37,8 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
json!({
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
}),
"the registered advertisement must be the same reviewed object in {revision}"
@@ -48,8 +48,8 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability()
json!({
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
}),
"the production advertisement entry point must serve {revision}"
@@ -262,8 +262,8 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
json!({
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
})
);
@@ -273,8 +273,8 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
"inert_test_capability": {"enabled": true},
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
})
);
@@ -284,8 +284,8 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_
"inert_test_capability": {"enabled": true},
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
})
);
@@ -468,8 +468,8 @@ fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() {
json!({
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
}),
"the other era advertisement stays the reviewed object"
@@ -759,8 +759,8 @@ fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
"inert_test_capability": {"enabled": true},
"completions": {},
"logging": {},
"prompts": {"listChanged": false},
"resources": {"listChanged": false, "subscribe": false},
"prompts": {"listChanged": true},
"resources": {"listChanged": true, "subscribe": false},
"tools": {"listChanged": false}
})
);
@@ -0,0 +1,482 @@
//! Story 3.19: Resource and Prompt list-change signals (FR-19).
//!
//! The positive result of the story is that a client which asked for the list-change signal of its
//! revision learns that the *committed* Resource or Prompt catalog changed, and that the ordinary
//! `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list` and `prompts/get`
//! stay authoritative for a client that misses the notification.
//!
//! Shape of the chosen seam (ARC decision, kanban t_c12863fb): a **stream-local watcher**. One open
//! notification stream owns one bounded periodic read of the published Agent catalog the stream is
//! scoped to; a change of the visible Resource/Prompt binding projection produces the revision's
//! list-change notification. There is no post-commit hook, no cross-process bus and no durable
//! queue: the committed catalog is the source of truth, so a signal can never be produced before its
//! commit, and a failed read can never roll the commit back — it only skips that tick and stays
//! observable in tracing.
//!
//! Bounds (issue requirement: bounded queues/frequency/bytes):
//! * one in-flight read per stream, one fixed poll interval, a read timeout and skipped ticks;
//! * at most one frame per change type per tick, so a burst coalesces by the latest observed
//! revision instead of queueing every intermediate commit;
//! * the queue is a fixed-capacity channel; a slow reader drops the newest frame instead of blocking
//! the producer or growing memory, and recovers through the authoritative list methods;
//! * every frame has a fixed shape — a closed method name plus the request id of the subscription —
//! so the byte bound follows from the id bound ([`MAX_SUBSCRIPTION_ID_BYTES`]).
//!
//! Scope boundary: this module serves list-change signals only. URI-content subscriptions
//! (`resources/subscribe` / `notifications/resources/updated`) stay unimplemented and are never
//! acknowledged or emitted here.
use std::{
collections::{HashMap, VecDeque},
future::Future,
pin::Pin,
sync::{
Arc, Mutex, MutexGuard,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use axum::response::sse::Event;
use crank_registry::PublishedAgentCatalog;
use futures_util::stream;
use serde::Deserialize;
use serde_json::{Map, Value, json};
use tokio::sync::mpsc;
use tracing::warn;
use crate::app::AppState;
/// The pinned key that correlates every message of one subscription stream with its
/// `subscriptions/listen` request id.
pub(crate) const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId";
/// `notifications/resources/list_changed` (both approved revisions).
pub(crate) const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed";
/// `notifications/prompts/list_changed` (both approved revisions).
pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed";
/// `notifications/subscriptions/acknowledged` (modern revision only).
pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged";
/// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs
/// "after commit", and the client always keeps the authoritative list methods for recovery.
pub(crate) const POLL_INTERVAL: Duration = Duration::from_secs(1);
/// Upper bound of one watcher read. A read that exceeds it is a skipped tick, exactly like a failed
/// read: no signal, no rollback, one safe tracing event.
pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(5);
/// Frames a slow reader may fall behind before the newest frame is dropped (`coalescing`).
pub(crate) const SIGNAL_QUEUE_CAPACITY: usize = 4;
/// Bound of the encoded `subscriptions/listen` id carried by every frame of one stream.
pub(crate) const MAX_SUBSCRIPTION_ID_BYTES: usize = 64;
/// Bound of the legacy session stream table (memory bound; see [`StreamRegistry`]).
pub(crate) const MAX_TRACKED_STREAMS: usize = 1_024;
/// Bound of the URIs a modern filter may name. The server does not implement URI subscriptions, so
/// this many names is already far more than a well-behaved client asks for.
pub(crate) const MAX_FILTER_URIS: usize = 32;
/// Bound of one URI in the modern filter: longer values are rejected without being echoed back.
pub(crate) const MAX_FILTER_URI_BYTES: usize = 2_048;
/// The one safe detail of a malformed or oversized `subscriptions/listen` filter.
pub(crate) const INVALID_LISTEN_FILTER: &str = "invalid subscriptions/listen notification filter";
/// The two list-change signal types this server implements.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Signals {
pub(crate) resources: bool,
pub(crate) prompts: bool,
}
impl Signals {
/// Both types: the legacy revision defines no client opt-in, so its stream carries both.
pub(crate) const BOTH: Self = Self {
resources: true,
prompts: true,
};
#[cfg_attr(not(test), allow(dead_code))] // read by the unit oracle of the projection
pub(crate) fn any(self) -> bool {
self.resources || self.prompts
}
fn intersect(self, other: Self) -> Self {
Self {
resources: self.resources && other.resources,
prompts: self.prompts && other.prompts,
}
}
}
/// The pinned modern `SubscriptionFilter`, as far as this server reads it.
///
/// Unknown members are ignored and a malformed shape is a deserialization error, so a client cannot
/// reach the watcher with anything but the reviewed field set.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ListenFilter {
#[serde(default)]
/// `toolsListChanged` is not implemented in this scope and is therefore never acknowledged.
#[allow(dead_code)]
tools_list_changed: bool,
#[serde(default)]
prompts_list_changed: bool,
#[serde(default)]
resources_list_changed: bool,
#[serde(default)]
resource_subscriptions: Vec<String>,
}
/// The pinned `SubscriptionsListenRequestParams`: the notification filter is a required member.
///
/// Only the reviewed member is read; `_meta` and any other member of the request params is not part
/// of this contract.
#[derive(Debug, Deserialize)]
pub(crate) struct ListenParams {
pub(crate) notifications: ListenFilter,
}
/// The bounded input contract of a `subscriptions/listen` filter.
pub(crate) enum FilterOutcome {
/// The list-change subset this server honours for the stream.
Accepted(Signals),
/// One safe detail: no URI, name or value the client sent is echoed back.
Invalid(&'static str),
}
impl ListenFilter {
/// Validate the bounded inputs and keep only the honoured types.
///
/// `toolsListChanged` and `resourceSubscriptions` are not implemented in the current scope, which
/// is what the acknowledgment reports: they are simply not honoured, and the pinned schema
/// forbids the server from sending a type it did not agree to.
pub(crate) fn accepted(&self) -> FilterOutcome {
if self.resource_subscriptions.len() > MAX_FILTER_URIS
|| self
.resource_subscriptions
.iter()
.any(|uri| uri.len() > MAX_FILTER_URI_BYTES)
{
return FilterOutcome::Invalid(INVALID_LISTEN_FILTER);
}
FilterOutcome::Accepted(Signals {
resources: self.resources_list_changed,
prompts: self.prompts_list_changed,
})
}
}
/// The `notifications` object of the acknowledgment: exactly the subset that will be delivered.
fn acknowledged_filter_wire(accepted: Signals) -> Value {
let mut filter = Map::new();
if accepted.prompts {
filter.insert("promptsListChanged".to_owned(), Value::Bool(true));
}
if accepted.resources {
filter.insert("resourcesListChanged".to_owned(), Value::Bool(true));
}
Value::Object(filter)
}
/// The exact bound Resource/Prompt projection of one published Agent catalog.
///
/// The projection is derived from the same committed catalog read that already feeds
/// `resources/list`, `resources/templates/list`, `prompts/list` and `prompts/get`: the exact Resource
/// and Prompt bindings of the published Agent snapshot, in deterministic binding order.
/// `catalog_revision` alone is *not* the comparison key — a commit that only changes Tools must not
/// produce a Resource/Prompt signal — so the two binding vectors are compared on their own.
///
/// shortcut: a Resource revocation invalidates a bound publication without a new Agent snapshot, so
/// it does not change this projection and produces no list-change signal; the revocation gate at
/// read time (Story 3.8) still fails closed, and a faithful revocation signal needs a bounded
/// registry read that the current scope does not have.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CatalogFingerprint {
resources: Vec<(String, u32)>,
prompts: Vec<(String, u32)>,
}
impl CatalogFingerprint {
pub(crate) fn of(catalog: &PublishedAgentCatalog) -> Self {
let mut resources = catalog
.resources
.iter()
.map(|binding| {
(
binding.resource_id.as_str().to_owned(),
binding.resource_version,
)
})
.collect::<Vec<_>>();
let mut prompts = catalog
.prompts
.iter()
.map(|binding| {
(
binding.prompt_id.as_str().to_owned(),
binding.prompt_version,
)
})
.collect::<Vec<_>>();
resources.sort();
prompts.sort();
Self { resources, prompts }
}
/// The list-change types whose visible binding projection differs between `previous` and `self`.
pub(crate) fn changes_since(&self, previous: &Self) -> Signals {
Signals {
resources: self.resources != previous.resources,
prompts: self.prompts != previous.prompts,
}
}
}
/// The wire contract of one stream.
#[derive(Clone, Debug)]
pub(crate) enum Wire {
/// `2025-11-25`: a bare server notification without parameters.
Legacy,
/// `2026-07-28`: every message carries the subscription id of its `subscriptions/listen` request.
Modern(Value),
}
impl Wire {
fn signal_frames(&self, signals: Signals) -> Vec<String> {
let mut frames = Vec::with_capacity(2);
for (changed, method) in [
(signals.resources, RESOURCE_LIST_CHANGED),
(signals.prompts, PROMPT_LIST_CHANGED),
] {
if !changed {
continue;
}
let frame = match self {
Wire::Legacy => json!({ "jsonrpc": "2.0", "method": method }),
Wire::Modern(subscription_id) => json!({
"jsonrpc": "2.0",
"method": method,
"params": { "_meta": { SUBSCRIPTION_ID_KEY: subscription_id } }
}),
};
frames.push(frame.to_string());
}
frames
}
}
/// The first modern frame: the accepted subset, before any list-change notification of the stream.
pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
json!({
"jsonrpc": "2.0",
"method": SUBSCRIPTIONS_ACKNOWLEDGED,
"params": {
"_meta": { SUBSCRIPTION_ID_KEY: subscription_id },
"notifications": acknowledged_filter_wire(accepted),
}
})
.to_string()
}
/// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a
/// bounded identity carrier.
pub(crate) fn subscription_id(request_id: &Value) -> Option<Value> {
let encoded = request_id.to_string();
(encoded.len() <= MAX_SUBSCRIPTION_ID_BYTES).then(|| request_id.clone())
}
/// Bounded table of the legacy session that currently owns the notification stream.
///
/// The pinned legacy transport forbids broadcasting one message across several SSE streams of the
/// same session, and the community scope keeps exactly one producer per session: the newest admitted
/// `GET` takes the signals over and the older stream ends. A retired stream (session `DELETE`) or a
/// superseded generation never writes into a reconnect.
#[derive(Default)]
pub(crate) struct StreamRegistry {
next_generation: AtomicU64,
owners: Mutex<HashMap<String, u64>>,
}
impl StreamRegistry {
pub(crate) fn new() -> Self {
Self::default()
}
/// Admit the notification stream of one session and return its generation.
pub(crate) fn admit(&self, session_id: &str) -> Option<u64> {
let generation = self.next_generation.fetch_add(1, Ordering::Relaxed) + 1;
let mut owners = self.lock()?;
if owners.len() >= MAX_TRACKED_STREAMS && !owners.contains_key(session_id) {
// Bounded table: forget the whole owner set instead of growing without a limit. Each
// running producer still holds its own generation, so the worst case is a stream that
// can no longer be told apart from a newer one — never unbounded memory.
owners.clear();
}
owners.insert(session_id.to_owned(), generation);
Some(generation)
}
/// Whether `generation` still owns the stream of `session_id`.
pub(crate) fn is_current(&self, session_id: &str, generation: u64) -> bool {
self.lock()
.and_then(|owners| owners.get(session_id).copied())
.is_some_and(|current| current == generation)
}
/// Stop the producer of one session (`DELETE`, or a session that no longer exists).
pub(crate) fn retire(&self, session_id: &str) {
if let Some(mut owners) = self.lock() {
owners.remove(session_id);
}
}
fn lock(&self) -> Option<MutexGuard<'_, HashMap<String, u64>>> {
self.owners.try_lock().ok()
}
}
/// Everything one watcher needs.
pub(crate) struct Watch {
pub(crate) workspace_slug: String,
pub(crate) agent_slug: String,
/// The signal types this stream may deliver.
pub(crate) signals: Signals,
pub(crate) wire: Wire,
/// The legacy session lease: the producer stops when the stream is superseded or retired.
pub(crate) legacy_stream: Option<(Arc<StreamRegistry>, String, u64)>,
/// Lifetime bound inherited from the legacy transport session TTL.
pub(crate) deadline: Option<Instant>,
}
/// One committed-catalog read of a watcher tick.
///
/// The reader is a closure so the failure path is driveable in a unit oracle without a live
/// registry: production passes [`read`] over the shared [`AppState`], and the oracle passes a
/// scripted sequence.
pub(crate) type ReadFuture =
Pin<Box<dyn Future<Output = Result<CatalogFingerprint, ReadError>> + Send>>;
/// A source of committed-catalog reads. One call per tick.
pub(crate) type Reader = Box<dyn FnMut() -> ReadFuture + Send>;
/// Start the stream-local watcher and return the bounded frame queue of the response stream.
///
/// The first read is the baseline taken **before** the acknowledgment is written; it is never reset
/// afterwards, so a publication between the baseline and the acknowledgment is still delivered.
pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String> {
let scope = (watch.workspace_slug.clone(), watch.agent_slug.clone());
let reader: Reader = Box::new(move || {
let state = Arc::clone(&state);
let scope = scope.clone();
Box::pin(async move { read(&state, &scope).await })
});
let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
tokio::spawn(run(watch, sender, reader));
receiver
}
async fn run(watch: Watch, sender: mpsc::Sender<String>, mut read: Reader) {
let mut baseline = match read().await {
Ok(fingerprint) => Some(fingerprint),
Err(ReadError::Gone) => return,
Err(ReadError::Retry) => {
observe_failure();
None
}
};
loop {
if !still_owned(&watch) || sender.is_closed() {
return;
}
if watch
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
return;
}
tokio::time::sleep(POLL_INTERVAL).await;
if !still_owned(&watch) {
return;
}
match read().await {
Ok(fingerprint) => {
if let Some(previous) = baseline.as_ref() {
let changes = fingerprint.changes_since(previous).intersect(watch.signals);
for frame in watch.wire.signal_frames(changes) {
// A slow reader coalesces: the newest frame is dropped instead of blocking
// the producer or growing a queue, and the client recovers through the
// authoritative list methods.
let _ = sender.try_send(frame);
}
}
baseline = Some(fingerprint);
}
// The Agent is no longer published: fail closed by ending the stream instead of serving a
// catalog nobody may read any more.
Err(ReadError::Gone) => return,
// The committed catalog is untouched: the failure is observable and this tick is skipped.
Err(_) => observe_failure(),
}
}
}
pub(crate) enum ReadError {
/// The published Agent behind this stream is gone: the producer ends.
Gone,
/// The catalog could not be read this tick: skip it, keep the committed state.
Retry,
}
fn still_owned(watch: &Watch) -> bool {
match &watch.legacy_stream {
Some((registry, session_id, generation)) => registry.is_current(session_id, *generation),
None => true,
}
}
async fn read(state: &AppState, scope: &(String, String)) -> Result<CatalogFingerprint, ReadError> {
let catalog = tokio::time::timeout(READ_TIMEOUT, state.catalog.get_catalog(&scope.0, &scope.1))
.await
.map_err(|_| ReadError::Retry)?
.map_err(|error| match error {
crank_registry::RegistryError::PublishedAgentNotFound { .. } => ReadError::Gone,
_ => ReadError::Retry,
})?;
Ok(CatalogFingerprint::of(&catalog))
}
/// One safe, closed-vocabulary observation of a skipped tick: no URI, Agent name, credential or raw
/// error text is read here.
fn observe_failure() {
warn!(
name: "mcp.signals.read_failed",
error_category = "catalog",
"catalog change signal read failed"
);
}
/// The bounded SSE body of one signal stream: the leading frames (acknowledgment), then the queue,
/// ending when the producer ends. The caller's stream permit lives in `guard` and is released when
/// the response stream is dropped.
pub(crate) fn frames_stream<G: Send + 'static>(
first: Vec<String>,
receiver: mpsc::Receiver<String>,
guard: G,
) -> impl stream::Stream<Item = Result<Event, std::convert::Infallible>> {
let pending: VecDeque<String> = first.into();
stream::unfold(
(pending, receiver, guard),
|(mut pending, mut receiver, guard)| async move {
loop {
if let Some(frame) = pending.pop_front() {
return Some((Ok(Event::default().data(frame)), (pending, receiver, guard)));
}
let frame = receiver.recv().await?;
pending.push_back(frame);
}
},
)
}
#[cfg(test)]
#[path = "signals_tests.rs"]
mod tests;
@@ -0,0 +1,411 @@
//! Unit oracles of the Story 3.19 signal seam: the catalog projection, the bounded filter, the exact
//! wire frames of both approved revisions and the bounded legacy stream ownership.
use std::{
io,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use crank_core::ToolSelectionPolicy;
use crank_core::ids::{PromptId, ResourceId};
use crank_registry::PublishedAgentCatalog;
use crank_registry::model::{AgentPromptBinding, AgentResourceBinding};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use super::{
CatalogFingerprint, FilterOutcome, INVALID_LISTEN_FILTER, ListenFilter, MAX_FILTER_URIS,
MAX_SUBSCRIPTION_ID_BYTES, PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, ReadError, Reader,
SIGNAL_QUEUE_CAPACITY, SUBSCRIPTION_ID_KEY, SUBSCRIPTIONS_ACKNOWLEDGED, Signals,
StreamRegistry, Watch, Wire, acknowledged_frame, run, subscription_id,
};
fn catalog(
resources: &[(&str, u32)],
prompts: &[(&str, u32)],
catalog_revision: &str,
) -> PublishedAgentCatalog {
PublishedAgentCatalog {
agent_version: 1,
catalog_revision: catalog_revision.to_owned(),
tool_selection_policy: ToolSelectionPolicy::default(),
tools: Vec::new(),
resources: resources
.iter()
.map(|(id, version)| AgentResourceBinding {
resource_id: ResourceId::new(*id),
resource_version: *version,
})
.collect(),
prompts: prompts
.iter()
.map(|(id, version)| AgentPromptBinding {
prompt_id: PromptId::new(*id),
prompt_version: *version,
})
.collect(),
}
}
#[test]
fn a_committed_resource_binding_is_a_resource_change_only() {
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
let after = CatalogFingerprint::of(&catalog(
&[("res_a", 1), ("res_b", 1)],
&[("prm_a", 1)],
"rev-2",
));
assert_eq!(
after.changes_since(&before),
Signals {
resources: true,
prompts: false
}
);
assert!(!before.changes_since(&after).prompts);
assert_eq!(
before.changes_since(&after),
Signals {
resources: true,
prompts: false
}
);
}
#[test]
fn a_committed_prompt_binding_is_a_prompt_change_only() {
let before = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
let after = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 2)], "rev-2"));
assert_eq!(
after.changes_since(&before),
Signals {
resources: false,
prompts: true
}
);
}
#[test]
fn a_pinned_version_bump_is_a_change_even_when_the_binding_names_are_stable() {
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
let after = CatalogFingerprint::of(&catalog(&[("res_a", 2)], &[("prm_a", 1)], "rev-1"));
assert_eq!(
after.changes_since(&before),
Signals {
resources: true,
prompts: false
}
);
}
#[test]
fn a_tool_only_catalog_commit_is_silent() {
// `catalog_revision` moved, but the visible Resource/Prompt projection did not: a Tool-only
// commit must not produce a Resource or Prompt list-change signal.
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
let after = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-2"));
assert!(!after.changes_since(&before).any());
}
#[test]
fn the_projection_is_order_independent_and_has_no_duplicate_growth() {
let forward = CatalogFingerprint::of(&catalog(
&[("res_a", 1), ("res_b", 2)],
&[("prm_a", 1), ("prm_b", 2)],
"rev-1",
));
let reversed = CatalogFingerprint::of(&catalog(
&[("res_b", 2), ("res_a", 1)],
&[("prm_b", 2), ("prm_a", 1)],
"rev-1",
));
assert!(!reversed.changes_since(&forward).any());
}
#[test]
fn the_legacy_frames_carry_a_closed_method_name_and_no_parameters() {
let frames = Wire::Legacy.signal_frames(Signals::BOTH);
assert_eq!(
frames,
vec![
json!({"jsonrpc": "2.0", "method": RESOURCE_LIST_CHANGED}).to_string(),
json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string(),
]
);
// No URI, name or payload of a changed object is part of a list-change notification.
assert!(frames.iter().all(|frame| !frame.contains("uri")));
}
#[test]
fn the_modern_frames_carry_the_subscription_id_of_their_listen_request() {
let id = json!(41);
let frames = Wire::Modern(id.clone()).signal_frames(Signals::BOTH);
assert_eq!(
frames,
vec![
json!({
"jsonrpc": "2.0",
"method": RESOURCE_LIST_CHANGED,
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
})
.to_string(),
json!({
"jsonrpc": "2.0",
"method": PROMPT_LIST_CHANGED,
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
})
.to_string(),
]
);
assert_eq!(
serde_json::from_str::<Value>(&frames[0]).unwrap()["params"]["_meta"][SUBSCRIPTION_ID_KEY],
id
);
}
#[test]
fn only_the_requested_and_honoured_types_are_encoded() {
let frames = Wire::Modern(json!(1)).signal_frames(Signals {
resources: false,
prompts: true,
});
assert_eq!(frames.len(), 1);
assert!(frames[0].contains(PROMPT_LIST_CHANGED));
}
#[test]
fn the_acknowledgment_reports_exactly_the_honoured_subset() {
let frame: Value = serde_json::from_str(&acknowledged_frame(
&json!(7),
Signals {
resources: true,
prompts: false,
},
))
.unwrap();
assert_eq!(frame["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(7));
assert_eq!(
frame["params"]["notifications"],
json!({ "resourcesListChanged": true })
);
}
#[test]
fn an_empty_honoured_subset_is_an_empty_filter_object() {
let frame: Value =
serde_json::from_str(&acknowledged_frame(&json!("sub-1"), Signals::default())).unwrap();
assert_eq!(frame["params"]["notifications"], json!({}));
}
#[test]
fn the_filter_keeps_only_the_implemented_list_change_types() {
let filter: ListenFilter = serde_json::from_value(json!({
"toolsListChanged": true,
"promptsListChanged": true,
"resourcesListChanged": false,
"resourceSubscriptions": ["file:///project/config.json"]
}))
.unwrap();
match filter.accepted() {
FilterOutcome::Accepted(signals) => assert_eq!(
signals,
Signals {
resources: false,
prompts: true
}
),
FilterOutcome::Invalid(detail) => panic!("a bounded filter must be accepted: {detail}"),
}
}
#[test]
fn an_absent_filter_field_means_not_subscribed() {
let filter: ListenFilter = serde_json::from_value(json!({})).unwrap();
match filter.accepted() {
FilterOutcome::Accepted(signals) => assert!(!signals.any()),
FilterOutcome::Invalid(detail) => panic!("an empty filter must be accepted: {detail}"),
}
}
#[test]
fn an_oversized_uri_filter_is_refused_without_echoing_it() {
let filter: ListenFilter = serde_json::from_value(json!({
"resourceSubscriptions": (0..=MAX_FILTER_URIS)
.map(|index| format!("file:///resource-{index}"))
.collect::<Vec<_>>()
}))
.unwrap();
match filter.accepted() {
FilterOutcome::Invalid(detail) => assert_eq!(detail, INVALID_LISTEN_FILTER),
FilterOutcome::Accepted(_) => panic!("an oversized filter must be refused"),
}
let oversized: ListenFilter = serde_json::from_value(json!({
"resourceSubscriptions": ["u".repeat(super::MAX_FILTER_URI_BYTES + 1)]
}))
.unwrap();
assert!(matches!(
oversized.accepted(),
FilterOutcome::Invalid(INVALID_LISTEN_FILTER)
));
}
#[test]
fn a_non_object_filter_is_a_deserialization_error() {
assert!(serde_json::from_value::<ListenFilter>(json!(["toolsListChanged"])).is_err());
assert!(serde_json::from_value::<ListenFilter>(json!({"promptsListChanged": "yes"})).is_err());
}
#[test]
fn the_subscription_id_is_bound_by_its_encoded_size() {
assert_eq!(subscription_id(&json!(1)), Some(json!(1)));
assert_eq!(subscription_id(&json!("sub-1")), Some(json!("sub-1")));
assert_eq!(
subscription_id(&json!("x".repeat(MAX_SUBSCRIPTION_ID_BYTES))),
None,
"an id longer than the frame bound must not be used as a subscription id"
);
}
#[test]
fn a_newer_legacy_stream_supersedes_the_previous_one() {
let streams = StreamRegistry::new();
let first = streams.admit("session-1").unwrap();
let second = streams.admit("session-1").unwrap();
assert!(!streams.is_current("session-1", first));
assert!(streams.is_current("session-1", second));
// Another session is unaffected.
let other = streams.admit("session-2").unwrap();
assert!(streams.is_current("session-2", other));
streams.retire("session-1");
assert!(!streams.is_current("session-1", second));
assert!(streams.is_current("session-2", other));
}
#[derive(Clone, Default)]
struct SharedLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl SharedLogWriter {
fn output(&self) -> String {
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedLogWriter {
type Writer = SharedLogGuard;
fn make_writer(&'a self) -> Self::Writer {
SharedLogGuard {
buffer: Arc::clone(&self.buffer),
}
}
}
struct SharedLogGuard {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl io::Write for SharedLogGuard {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.buffer.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// AC-2: a failed committed-catalog read is observable and loses nothing — the tick is skipped (no
/// fabricated signal, no write path that could roll the catalog back) while the baseline survives, so
/// the next successful read still reports the change of the committed catalog.
#[tokio::test]
async fn a_failed_catalog_read_is_observable_and_loses_no_committed_change() {
let writer = SharedLogWriter::default();
let subscriber = crank_observability::build_subscriber(
crank_observability::ObservabilityConfig::new(
crank_observability::ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
"info",
crank_observability::RedactionLimits::default(),
),
writer.clone(),
)
.unwrap();
let dispatch = tracing::Dispatch::new(subscriber);
let _guard = tracing::dispatcher::set_default(&dispatch);
let baseline = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
let committed = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 1)], "rev-2"));
let script = Arc::new(Mutex::new(
vec![Ok(baseline), Err(ReadError::Retry), Ok(committed)].into_iter(),
));
let reader: Reader = Box::new(move || {
let next = script
.lock()
.unwrap()
.next()
.unwrap_or(Err(ReadError::Retry));
Box::pin(async move { next })
});
let (sender, mut receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
tokio::spawn(run(
Watch {
workspace_slug: "workspace-canary".to_owned(),
agent_slug: "agent-canary".to_owned(),
signals: Signals::BOTH,
wire: Wire::Legacy,
legacy_stream: None,
deadline: Some(Instant::now() + Duration::from_millis(2_100)),
},
sender,
reader,
));
let mut frames = Vec::new();
while let Some(frame) = receiver.recv().await {
frames.push(frame);
}
// The failed tick produced no frame; the committed change of the next successful read did.
assert_eq!(
frames,
vec![json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string()]
);
let output = writer.output();
let failures: Vec<Value> = output
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.filter(|event| event["event"] == "mcp.signals.read_failed")
.collect();
assert!(
!failures.is_empty(),
"a skipped tick must be observable: {output}"
);
for event in &failures {
assert_eq!(event["fields"]["error_category"], "catalog");
}
// Closed vocabulary: no workspace, Agent, URI or raw database text is read into the event.
assert!(!output.contains("workspace-canary"));
assert!(!output.contains("agent-canary"));
}
+14 -12
View File
@@ -932,7 +932,7 @@
{
"advertised": {
"prompts": {
"listChanged": false
"listChanged": true
}
},
"applicability": "stable",
@@ -941,6 +941,7 @@
"kind": "capability",
"open_subfeatures": false,
"owner": "community-release",
"reason": "the adapter emits `notifications/prompts/list_changed` from the committed published Prompt bindings of the Agent snapshot since Story 3.19",
"requirement": "FR-17",
"revisions": [
"2026-07-28",
@@ -956,7 +957,7 @@
{
"advertised": {
"resources": {
"listChanged": false,
"listChanged": true,
"subscribe": false
}
},
@@ -966,6 +967,7 @@
"kind": "capability",
"open_subfeatures": false,
"owner": "community-release",
"reason": "the adapter emits `notifications/resources/list_changed` from the committed published Resource bindings of the Agent snapshot since Story 3.19; URI-content subscriptions remain unimplemented",
"requirement": "FR-15",
"revisions": [
"2026-07-28",
@@ -1438,13 +1440,13 @@
"kind": "method",
"open_subfeatures": false,
"owner": "community-release",
"reason": "the community scope serves no subscription stream, so the modern listen request is not served",
"reason": "served since Story 3.19 (FR-19) as the modern long-lived notification stream; the acknowledged filter carries only the implemented Resource/Prompt list-change types",
"requirement": "FR-13",
"revisions": [
"2026-07-28"
],
"role": "client",
"status": "not_applicable",
"status": "supported",
"subfeatures": [],
"surface": "subscriptions/listen"
},
@@ -1613,15 +1615,15 @@
"fallback": "capability not advertised, request not dispatched",
"kind": "notification",
"open_subfeatures": false,
"owner": "story 3.19",
"reason": "Resource and Prompt change signals are owned by story 3.19",
"owner": "community-release",
"reason": "emitted since Story 3.19 (FR-19) from the committed published Resource bindings of the Agent snapshot; carries no parameters, so no URI, name or content is disclosed",
"requirement": "FR-19",
"revisions": [
"2026-07-28",
"2025-11-25"
],
"role": "server",
"status": "deferred",
"status": "supported",
"subfeatures": [],
"surface": "notifications/resources/list_changed"
},
@@ -1632,15 +1634,15 @@
"fallback": "capability not advertised, request not dispatched",
"kind": "notification",
"open_subfeatures": false,
"owner": "story 3.19",
"reason": "Resource and Prompt change signals are owned by story 3.19",
"owner": "community-release",
"reason": "emitted since Story 3.19 (FR-19) from the committed published Prompt bindings of the Agent snapshot; carries no parameters, so no Prompt name or content is disclosed",
"requirement": "FR-19",
"revisions": [
"2026-07-28",
"2025-11-25"
],
"role": "server",
"status": "deferred",
"status": "supported",
"subfeatures": [],
"surface": "notifications/prompts/list_changed"
},
@@ -1719,13 +1721,13 @@
"kind": "notification",
"open_subfeatures": false,
"owner": "community-release",
"reason": "the community scope serves no subscription stream",
"reason": "sent since Story 3.19 (FR-19) as the first frame of a `subscriptions/listen` stream, carrying the request id as the subscription id and the honoured filter subset",
"requirement": "FR-13",
"revisions": [
"2026-07-28"
],
"role": "server",
"status": "not_applicable",
"status": "supported",
"subfeatures": [],
"surface": "notifications/subscriptions/acknowledged"
},
+6
View File
@@ -39,3 +39,9 @@ run_atdd "bound template resources/list regression" -p mcp-server --test integra
run_atdd "MCP log level vocabulary" -p crank-community-mcp --lib protocol::logging -- --test-threads=1
run_atdd "MCP safe logging" -p mcp-server --test integration mcp_logging -- --test-threads=1
run_atdd "capability inventory projection" -p mcp-server --test integration inventory_projection -- --test-threads=1
# Story 3.19 (FR-19): a committed Resource/Prompt catalog change is announced to the client that
# asked for the signal, in both revisions, and the authoritative list methods stay the recovery path.
# The advertisement projection is already covered by the `inventory_projection` entry above.
run_atdd "Resource/Prompt change signals" -p mcp-server --test integration mcp_signals -- --test-threads=1
run_atdd "change signal wire oracles" -p crank-community-mcp --lib protocol::signals -- --test-threads=1
@@ -1 +1 @@
{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}
@@ -1,7 +1,7 @@
{
"revision": "2025-11-25",
"inventory_path": "docs/capability-inventory.json",
"inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d",
"inventory_sha256": "10ca3538aa1b6b25868f80e19932c7ef918398c4817c52bc1aae52f18c31522b",
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
"projection_inputs": [
{
@@ -1 +1 @@
{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}
@@ -1,7 +1,7 @@
{
"revision": "2026-07-28",
"inventory_path": "docs/capability-inventory.json",
"inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d",
"inventory_sha256": "10ca3538aa1b6b25868f80e19932c7ef918398c4817c52bc1aae52f18c31522b",
"rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4",
"projection_inputs": [
{
@@ -1,15 +1,15 @@
{
"oracle": "crank-current-scope-advertised-capabilities",
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list.",
"note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list. Story 3.19 implements the Resource/Prompt list-change signals, so both listChanged leaves are advertised; URI-content subscriptions stay unimplemented.",
"expected_keys": ["completions", "logging", "prompts", "resources", "tools"],
"expected_descriptor": {
"completions": {},
"logging": {},
"prompts": {
"listChanged": false
"listChanged": true
},
"resources": {
"listChanged": false,
"listChanged": true,
"subscribe": false
},
"tools": {
@@ -18,7 +18,7 @@
},
"must_not_be_advertised": ["experimental", "extensions"],
"deferred_with_owner": {
"change_signals": "story 3.19 (FR-19)",
"resource_content_subscriptions": "story 3.19 scope boundary (URI-content subscriptions deferred)",
"io.modelcontextprotocol/tasks": "story 4.7"
}
}
@@ -47,12 +47,14 @@ EXPECTED_FROZEN = (
b'{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
)
EXPECTED_SHA256 = "e38c795fc28fee74168cb045427df55d882f8f7ace206af5c9a3ca4df5892c9a"
# The canonical inventory also implements the logging surface (Story 3.18, FR-19), so the committed
# oracle and the canonical projection carry `logging` next to `completions`/`prompts`/`resources`/`tools`.
# The canonical inventory also implements the logging surface (Story 3.18, FR-19) and the
# Resource/Prompt list-change signals (Story 3.19, FR-19), so the committed oracle and the canonical
# projection carry `logging` next to `completions`/`prompts`/`resources`/`tools`, and both
# `listChanged` leaves are now implemented.
COMMITTED_FROZEN = (
b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}'
)
COMMITTED_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2"
COMMITTED_SHA256 = "b90b59f32e2e5c43e829b96339b99a52852bc04f48a2ca0ce7e971affa3a878e"
class AdvertisedCapabilitiesProjectionTests(unittest.TestCase):
@@ -1276,9 +1276,9 @@ class Story31FoundationProjectionBoundaryTests(unittest.TestCase):
"""
EXPECTED_FROZEN = (
b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}'
b'{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":false}}'
)
EXPECTED_FROZEN_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2"
EXPECTED_FROZEN_SHA256 = "b90b59f32e2e5c43e829b96339b99a52852bc04f48a2ca0ce7e971affa3a878e"
def test_control_committed_frozen_oracle_is_the_canonical_projection(self) -> None:
"""Positive control (existing GREEN, AT-13): the committed frozen bytes are canonical."""