feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s

Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

+6
View File
@@ -1,10 +1,16 @@
mod integration {
mod catalog_access;
mod common;
mod era_isolation;
mod execution_certainty;
mod execution_stages;
mod inventory_projection;
mod jsonrpc_correlation;
mod mcp_completion;
mod mcp_prompts;
mod request_context;
mod revision_matrix;
mod static_resources;
mod tool_search;
mod transport_protocol;
}
+76 -4
View File
@@ -85,11 +85,11 @@ impl io::Write for SharedLogGuard {
}
}
fn test_workspace_slug() -> &'static str {
pub(super) fn test_workspace_slug() -> &'static str {
"default"
}
fn test_agent_id(agent_slug: &str) -> AgentId {
pub(super) fn test_agent_id(agent_slug: &str) -> AgentId {
AgentId::new(format!("agent_{agent_slug}"))
}
@@ -106,7 +106,7 @@ pub(super) fn build_test_app(
)
}
fn build_test_app_with_rate_limit(
pub(super) fn build_test_app_with_rate_limit(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
@@ -122,7 +122,7 @@ fn build_test_app_with_rate_limit(
)
}
fn build_test_app_with_store(
pub(super) fn build_test_app_with_store(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
@@ -146,6 +146,55 @@ fn build_test_app_with_store(
)
}
/// Story 3.8 support: build the real app with the process artifact store, so `resources/read` serves
/// published bytes from a real immutable root (the same seam the production launcher uses).
pub(super) fn build_test_app_with_artifacts(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
artifact_store: crank_artifacts::ArtifactStore,
) -> axum::Router {
crank_community_mcp::build_app_with_artifacts(
registry,
refresh_interval,
public_base_url,
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
std::sync::Arc::new(InMemoryCoordinationStateStore::default()),
std::sync::Arc::new(InMemorySessionStore::default()),
std::sync::Arc::new(CommunityMachineCredentialVerifier),
// The same default concurrency the existing `build_app` helper uses.
16,
artifact_store,
)
}
/// Story 3.1 ATDD support: build the real app with an injected session store.
///
/// The store seam (`TransportSessionStore` / `SharedSessionStore`) is already public; this helper
/// only exposes the existing instrumented-app path to the new subject modules, so a test can count
/// or gate session-store *operations* (`get`/`create`/`mark_initialized`) without touching
/// production code. It is deliberately the only addition to this file.
pub(super) fn build_test_app_with_sessions(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
sessions: SharedSessionStore,
) -> axum::Router {
build_test_app_with_store(
registry,
refresh_interval,
public_base_url,
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
sessions,
std::sync::Arc::new(CommunityMachineCredentialVerifier),
)
}
pub(super) async fn initialize_session(
client: &reqwest::Client,
mcp_url: &str,
@@ -219,6 +268,29 @@ pub(super) async fn post_jsonrpc(
.unwrap()
}
/// Story 3.1 ATDD support: POST a JSON-RPC payload with explicitly chosen identity headers.
///
/// The helper only adds the headers the caller passes, so a test can express "no version header",
/// "modern header without body identity" or an unknown revision without touching existing helpers.
pub(super) async fn post_jsonrpc_with_headers(
client: &reqwest::Client,
mcp_url: &str,
api_key: &str,
headers: &[(&str, &str)],
payload: Value,
) -> reqwest::Response {
let mut request = client
.post(mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"));
for (name, value) in headers {
request = request.header(*name, *value);
}
request.json(&payload).send().await.unwrap()
}
pub(super) async fn post_jsonrpc_response(
client: &reqwest::Client,
mcp_url: &str,
@@ -0,0 +1,735 @@
#![allow(dead_code, unused_imports)]
//! Story 3.1 ATDD (AT-04/06/07/10/11): mixed-era isolation, honest bounded counters and causal
//! capture.
//!
//! What this module observes, and what it deliberately does NOT observe:
//!
//! * **session-store operations** - a test-only `TransportSessionStore` counts `get`/`create`/
//! `mark_initialized` calls. These are *store* operations, not service/dispatch entries: a request
//! can enter the Tools/approval path and finish (approval refusal, invalid params, catalog refusal,
//! pagination) **before** any outbound call, so no counter here is renamed into a "service entry"
//! or "dispatch" counter.
//! * **upstream outbound calls** - a held, counted loopback upstream signals the moment a
//! tool-execution request actually arrives; it is an *outbound* counter for the same reason.
//! * **in-processing arrival markers** - the barrier is released only after (a) the legacy handler has
//! called the session store from `require_initialized_session` (i.e. after admission and era
//! selection) and (b) the modern handler's tool-execution request has physically reached the
//! upstream. A client-side "request sent" signal is a precondition only and never releases the
//! barrier; there is no sleep-only overlap and no stress profile.
//!
//! Barrier discipline (TL ATDD round-1 R1):
//!
//! * a held handler waits **until the explicit coordinated release** - there is no internal
//! `timeout`-and-continue branch that could let one era leave the gate before the other arrives,
//! and no stored permit can turn a later phase into a false overlap (the release flag itself is
//! re-checked, so a stale permit simply exits the loop);
//! * the *test* owns the bound: `tokio::time::timeout` wraps the arrival wait, and the timeout is an
//! error, not a continuation of a success path;
//! * on any error the failure path releases both gates first, then bounded-joins or cancels the
//! request tasks, aborts the test's own server tasks, and only then fails naming the marker that
//! never arrived (`OverlapRun::cleanup`); the same cleanup also runs from `Drop`, so an assertion
//! failure cannot leak a parked handler or a live test server;
//! * `parked_waiters()` proves that both handlers really were held at the same time *before* the
//! release, and returns to zero afterwards.
//!
//! Scoped output (TL ATDD round-1 R3): each side is a **distinct Agent with its own catalog and its
//! own canary email**, and the counted upstream echoes the canary into the tool result. A swapped
//! legacy/modern result - or a crossed Agent/catalog scope - therefore fails the exact response
//! assertions instead of passing on a shared fixed id.
//!
//! Statements that the available seams genuinely cannot prove - "the rejected request did not enter
//! any other handler" (AT-06) and "no residual state is left on the short rejection branches"
//! (AT-11) - stay **NOT-PROVEN** here: they need the BUILD-only semantic era-adapter/service-entry
//! markers inside `crates/crank-community-mcp`. This module never weakens an assertion to satisfy the
//! current code, and never claims those two statements.
use super::common::*;
use axum::{Json, Router, extract::State, http::header, routing::post};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::time::Duration;
use self::harness::{
LEGACY_CANARY, LEGACY_REVISION, LEGACY_TOOL, META_CLIENT_CAPABILITIES, META_CLIENT_INFO,
META_PROTOCOL_VERSION, MODERN_CANARY, MODERN_REVISION, MODERN_TOOL, OverlapRun, REAP_TIMEOUT,
canary_id, harness, harness_with_two_agents, header_refs,
};
mod harness;
fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-era-client", "version": "0.1.0" }
})
}
fn legacy_tool_call(id: u64, tool_name: &str, email: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": { "name": tool_name, "arguments": { "email": email } }
})
}
fn modern_tool_call(id: u64, tool_name: &str, email: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": {
"_meta": modern_meta(MODERN_REVISION),
"name": tool_name,
"arguments": { "email": email }
}
})
}
fn legacy_headers(session_id: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
("MCP-Session-Id", session_id.to_owned()),
]
}
fn modern_headers(tool_name: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "tools/call".to_owned()),
("Mcp-Name", tool_name.to_owned()),
]
}
/// Bounded response read: the overlap test must not be able to hang inside a body read.
async fn bounded_json_body(response: reqwest::Response) -> (Value, String) {
let status = response.status();
let body = match tokio::time::timeout(REAP_TIMEOUT, response.text()).await {
Ok(Ok(body)) => body,
Ok(Err(error)) => panic!("reading the response body failed (status {status}): {error}"),
Err(_elapsed) => {
panic!("bounded {REAP_TIMEOUT:?} response-body read expired (status {status})")
}
};
let parsed = serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
});
(parsed, body)
}
// ---------------------------------------------------------------------------------------------
// AT-04: the modern stateless era performs no session-store operation at all.
// ---------------------------------------------------------------------------------------------
#[tokio::test]
async fn era_isolation_modern_requests_never_touch_the_session_store() {
let harness = harness("era-modern-only").await;
let side = harness.primary();
assert_eq!(
harness.counters.snapshot(),
(0, 0, 0),
"no session store operation may happen before any legacy request"
);
// `server/discover` is mandatory for the modern era; `tools/list` and `tools/call` follow on
// separate, independent stateless requests (no priming, no session).
let discover = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&[
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "server/discover".to_owned()),
]),
json!({
"jsonrpc": "2.0",
"id": 11,
"method": "server/discover",
"params": { "_meta": modern_meta(MODERN_REVISION) }
}),
)
.await;
assert_eq!(discover.status().as_u16(), 200);
assert!(discover.headers().get("MCP-Session-Id").is_none());
let listed = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&[
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "tools/list".to_owned()),
]),
json!({
"jsonrpc": "2.0",
"id": 12,
"method": "tools/list",
"params": { "_meta": modern_meta(MODERN_REVISION) }
}),
)
.await;
assert_eq!(listed.status().as_u16(), 200);
let called = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&modern_headers(&side.tool_name)),
modern_tool_call(13, &side.tool_name, MODERN_CANARY),
)
.await;
assert_eq!(called.status().as_u16(), 200);
let (called_body, _) = bounded_json_body(called).await;
assert!(
called_body["error"].is_null(),
"a valid modern tools/call must succeed, got {called_body}"
);
assert_eq!(
called_body["result"]["structuredContent"]["id"],
canary_id(MODERN_CANARY),
"the modern response must carry the canary this side sent"
);
assert_eq!(
harness.counters.snapshot(),
(0, 0, 0),
"the modern stateless path must not create, read or initialize any session; store operations \
are not service/dispatch counters, but on this path zero is the honest expected value"
);
assert_eq!(
harness.upstream.arrivals(),
1,
"exactly one outbound tool execution"
);
}
// ---------------------------------------------------------------------------------------------
// AT-07 / AT-06: overlapping legacy and modern tool calls stay scoped, released only by real
// in-processing arrival markers.
// ---------------------------------------------------------------------------------------------
#[tokio::test]
async fn era_isolation_overlapping_legacy_and_modern_calls_stay_scoped() {
// Two Agents: the legacy side and the modern side have different catalogs, so the Agent/catalog
// scope is part of what this test checks.
let harness = harness_with_two_agents("era-overlap", "era-overlap-modern").await;
let legacy_side = harness.primary();
let modern_side = harness.alternate();
let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await;
let baseline = harness.counters.snapshot();
let arrivals_baseline = harness.upstream.arrivals();
harness.store.hold(&session);
harness.upstream.hold();
let mut run = OverlapRun::new(&harness);
// Precondition only: the legacy request is *sent*. This never releases the barrier.
run.spawn(
&legacy_side,
legacy_headers(&session),
legacy_tool_call(21, &legacy_side.tool_name, LEGACY_CANARY),
);
// In-processing marker (legacy era): the handler reached `require_initialized_session`.
if let Err(timeout) = harness
.store
.await_arrival(
"the legacy handler's post-admission session-store lookup",
run.deadline,
)
.await
{
run.fail(timeout).await;
}
run.spawn(
&modern_side,
modern_headers(&modern_side.tool_name),
modern_tool_call(22, &modern_side.tool_name, MODERN_CANARY),
);
// In-processing marker (both eras): the modern handler's tool execution reached the upstream.
if let Err(timeout) = harness
.upstream
.await_arrival(
"the modern tool-execution request reaching the counted upstream",
run.deadline,
)
.await
{
run.fail(timeout).await;
}
// Both markers observed: prove the REAL simultaneous hold *before* releasing the gates. A false
// overlap (one side already past the gate) would show up as a zero parked count or a finished
// request.
assert_eq!(
harness.store.parked_waiters(),
1,
"the legacy handler must still be parked inside its post-admission store lookup"
);
assert_eq!(
harness.upstream.parked_waiters(),
1,
"the modern tool execution must still be parked at the counted upstream"
);
assert!(
!run.is_finished(0) && !run.is_finished(1),
"both requests must still be in processing when the barrier is released"
);
// Both arrivals observed: release the gates, join, then collect the results.
harness.store.release();
harness.upstream.release();
assert_eq!(
(harness.store.is_holding(), harness.upstream.is_holding()),
(false, false),
"the coordinated release must open both gates"
);
let legacy_response = run.join_bounded(0, "legacy").await;
let modern_response = run.join_bounded(1, "modern").await;
assert_eq!(
(
harness.store.parked_waiters(),
harness.upstream.parked_waiters()
),
(0, 0),
"no handler may stay parked after the release"
);
assert_eq!(legacy_response.status().as_u16(), 200);
assert_eq!(modern_response.status().as_u16(), 200);
let (legacy_body, legacy_raw) = bounded_json_body(legacy_response).await;
let (modern_body, modern_raw) = bounded_json_body(modern_response).await;
assert_eq!(legacy_body["jsonrpc"], "2.0");
assert_eq!(modern_body["jsonrpc"], "2.0");
assert_eq!(
legacy_body["id"], 21,
"legacy correlation must not cross eras"
);
assert_eq!(
modern_body["id"], 22,
"modern correlation must not cross eras"
);
assert!(
legacy_body["error"].is_null(),
"legacy call must succeed, got {legacy_body}"
);
assert!(
modern_body["error"].is_null(),
"modern call must succeed, got {modern_body}"
);
// Scoped output: each era's response carries the canary of ITS OWN Agent/catalog call and never
// the other side's. A swapped result would satisfy the id/resultType checks but fail here.
assert_eq!(
legacy_body["result"]["structuredContent"]["id"],
canary_id(LEGACY_CANARY),
"the legacy response must carry the legacy side's scoped canary, got {legacy_body}"
);
assert_eq!(
modern_body["result"]["structuredContent"]["id"],
canary_id(MODERN_CANARY),
"the modern response must carry the modern side's scoped canary, got {modern_body}"
);
assert!(
!legacy_raw.contains(MODERN_CANARY),
"the legacy response must not contain the modern side's canary: {legacy_raw}"
);
assert!(
!modern_raw.contains(LEGACY_CANARY),
"the modern response must not contain the legacy side's canary: {modern_raw}"
);
assert!(
legacy_body["result"].get("resultType").is_none(),
"the legacy era must not receive modern-only result members, got {legacy_body}"
);
assert_eq!(
modern_body["result"]["resultType"], "complete",
"the modern era keeps its own result projection, got {modern_body}"
);
// Store/upstream observables must be measured BEFORE the Agent/catalog scope probes below, which
// add their own (legacy) store lookups.
let after = harness.counters.snapshot();
assert_eq!(
(after.0, after.2),
(baseline.0, baseline.2),
"only the legacy request may consult the store, and it must not create or initialize a session"
);
assert_eq!(
after.1 - baseline.1,
2,
"one legacy tools/call performs exactly the two store lookups (carrier lookup before era \
resolution plus require_initialized_session); the modern request performs none"
);
assert_eq!(
harness.upstream.arrivals() - arrivals_baseline,
2,
"each era performs exactly one outbound tool execution"
);
// Agent/catalog scope: each Agent advertises exactly its own tool and never the other side's.
let legacy_tools = post_jsonrpc_with_headers(
&harness.client,
&legacy_side.mcp_url,
&legacy_side.api_key,
&header_refs(&legacy_headers(&session)),
json!({ "jsonrpc": "2.0", "id": 23, "method": "tools/list", "params": {} }),
)
.await;
assert_eq!(legacy_tools.status().as_u16(), 200);
let (legacy_tools_body, _legacy_tools_raw) = bounded_json_body(legacy_tools).await;
let legacy_names: Vec<String> = legacy_tools_body["result"]["tools"]
.as_array()
.expect("tools/list returns an array")
.iter()
.map(|tool| tool["name"].as_str().unwrap_or_default().to_owned())
.collect();
assert_eq!(
legacy_names,
vec![LEGACY_TOOL.to_owned()],
"the legacy Agent's catalog must be exactly its own tool, got {legacy_tools_body}"
);
let modern_tools = post_jsonrpc_with_headers(
&harness.client,
&modern_side.mcp_url,
&modern_side.api_key,
&header_refs(&[
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "tools/list".to_owned()),
]),
json!({
"jsonrpc": "2.0",
"id": 24,
"method": "tools/list",
"params": { "_meta": modern_meta(MODERN_REVISION) }
}),
)
.await;
assert_eq!(modern_tools.status().as_u16(), 200);
let (modern_tools_body, _modern_tools_raw) = bounded_json_body(modern_tools).await;
let modern_names: Vec<String> = modern_tools_body["result"]["tools"]
.as_array()
.expect("tools/list returns an array")
.iter()
.map(|tool| tool["name"].as_str().unwrap_or_default().to_owned())
.collect();
assert_eq!(
modern_names,
vec![MODERN_TOOL.to_owned()],
"the modern Agent's catalog must be exactly its own tool, got {modern_tools_body}"
);
}
// ---------------------------------------------------------------------------------------------
// R1 failure path: a missing in-processing marker must release the gates, cancel the run's own
// tasks and fail naming the marker - bounded, deterministic and without sleep-only waits.
// ---------------------------------------------------------------------------------------------
#[tokio::test]
async fn era_isolation_marker_timeout_path_releases_the_gates_and_cancels_its_own_tasks() {
let harness = harness("era-timeout-path").await;
let side = harness.primary();
let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await;
// The store gate is armed for a session id that no request will ever present, so the legacy
// in-processing marker cannot arrive; the upstream gate is armed normally, so the request really
// is held in processing while the bounded wait expires.
harness.store.hold("session-that-no-request-uses");
harness.upstream.hold();
let mut run = OverlapRun::with_deadline(&harness, Duration::from_millis(250));
run.spawn(
&side,
legacy_headers(&session),
legacy_tool_call(51, &side.tool_name, LEGACY_CANARY),
);
let timeout = harness
.store
.await_arrival("the marker that never arrives", run.deadline)
.await
.expect_err("the marker cannot arrive for a session id no request uses");
assert!(
timeout.describe().contains("the marker that never arrives"),
"the failure must name the missing marker: {}",
timeout.describe()
);
assert!(
harness.upstream.parked_waiters() >= 1,
"the request must be held in processing"
);
assert_eq!(
harness.store.parked_waiters(),
0,
"the gate armed for an unused session id must not have parked any handler"
);
// The failure path releases both gates first, then bounded-joins/cancels every task it started.
let responses = run.cleanup().await;
assert_eq!(
(harness.store.is_holding(), harness.upstream.is_holding()),
(false, false),
"the failure path must release both gates"
);
assert_eq!(
(
harness.store.parked_waiters(),
harness.upstream.parked_waiters()
),
(0, 0),
"no handler may stay parked after the failure-path cleanup"
);
assert_eq!(
(run.joined, run.cancelled),
(1, 0),
"the started request must be joined in bounded time (no leak, no unbounded join)"
);
let (body, raw) =
bounded_json_body(responses.into_iter().next().expect("one joined response")).await;
assert!(
body["error"].is_null(),
"releasing the gate must let the held request finish normally, got {body}"
);
assert_eq!(
body["result"]["structuredContent"]["id"],
canary_id(LEGACY_CANARY)
);
assert!(!raw.contains(MODERN_CANARY));
}
// ---------------------------------------------------------------------------------------------
// AT-11: positive control -> one-factor mutation -> valid follow-up on the same session.
// ---------------------------------------------------------------------------------------------
#[tokio::test]
async fn era_isolation_reject_then_valid_follow_up_keeps_the_legacy_session() {
let harness = harness("era-reject-follow-up").await;
let side = harness.primary();
let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await;
// 1. Positive control of EXACTLY the shape the mutation uses: a stateless modern tools/call with
// no session carrier. It must succeed on the real endpoint (existing GREEN).
let control = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&modern_headers(&side.tool_name)),
modern_tool_call(31, &side.tool_name, MODERN_CANARY),
)
.await;
assert_eq!(
control.status().as_u16(),
200,
"the positive control must pass"
);
let (control_body, _) = bounded_json_body(control).await;
assert!(control_body["error"].is_null(), "got {control_body}");
assert_eq!(control_body["jsonrpc"], "2.0");
assert_eq!(control_body["id"], 31);
assert_eq!(
control_body["result"]["structuredContent"]["id"],
canary_id(MODERN_CANARY),
"the control must return the canary this side sent, got {control_body}"
);
let baseline = harness.counters.snapshot();
let arrivals_baseline = harness.upstream.arrivals();
// 2. One-factor mutation: the SAME modern request (same body, same identity headers, same id,
// same email) with exactly one factor added - the legacy session carrier.
let mut mutated_headers = modern_headers(&side.tool_name);
mutated_headers.push(("MCP-Session-Id", session.clone()));
let mutated = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&mutated_headers),
modern_tool_call(31, &side.tool_name, MODERN_CANARY),
)
.await;
assert_eq!(
mutated.status().as_u16(),
400,
"a modern identity carrying a session carrier is an era-correct rejection"
);
let (mutated_body, _) = bounded_json_body(mutated).await;
assert_eq!(mutated_body["jsonrpc"], "2.0");
assert_eq!(
mutated_body["id"], 31,
"the rejection must keep the request correlation"
);
assert_eq!(
mutated_body["error"]["code"], -32020,
"the modern carrier conflict keeps its era-correct code, got {mutated_body}"
);
assert!(
mutated_body.get("result").is_none(),
"a rejected request must not return a result, got {mutated_body}"
);
// The conflict is decided before any session lookup, any rate-limit accounting and any dispatch.
// NOT-PROVEN (AT-06/AT-11): that the rejected request "did not enter any other handler" and left
// "no residual state" cannot be proven with the seams available here; that needs the BUILD-only
// semantic era-adapter/service-entry markers. Only store/outbound observables are asserted.
assert_eq!(
harness.counters.snapshot(),
baseline,
"a pre-admission rejection must not perform any session-store operation"
);
assert_eq!(
harness.upstream.arrivals(),
arrivals_baseline,
"a pre-admission rejection must not reach the upstream"
);
// 3. Valid follow-ups: the SAME legacy session is still served, and the stateless modern request
// of the positive-control shape still succeeds. Each carries its own scoped canary.
let follow_up = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&legacy_headers(&session)),
legacy_tool_call(33, &side.tool_name, LEGACY_CANARY),
)
.await;
assert_eq!(
follow_up.status().as_u16(),
200,
"the same legacy session must still be served"
);
let (follow_up_body, follow_up_raw) = bounded_json_body(follow_up).await;
assert!(follow_up_body["error"].is_null(), "got {follow_up_body}");
assert_eq!(follow_up_body["jsonrpc"], "2.0");
assert_eq!(follow_up_body["id"], 33);
assert_eq!(
follow_up_body["result"]["structuredContent"]["id"],
canary_id(LEGACY_CANARY),
"the legacy follow-up must return the legacy side's canary, got {follow_up_body}"
);
assert!(!follow_up_raw.contains(MODERN_CANARY));
let modern_follow_up = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&modern_headers(&side.tool_name)),
modern_tool_call(34, &side.tool_name, MODERN_CANARY),
)
.await;
assert_eq!(modern_follow_up.status().as_u16(), 200);
let (modern_body, modern_raw) = bounded_json_body(modern_follow_up).await;
assert!(modern_body["error"].is_null(), "got {modern_body}");
assert_eq!(modern_body["id"], 34);
assert_eq!(
modern_body["result"]["structuredContent"]["id"],
canary_id(MODERN_CANARY),
"the modern follow-up must return the modern side's canary, got {modern_body}"
);
assert!(!modern_raw.contains(LEGACY_CANARY));
assert_eq!(modern_body["result"]["resultType"], "complete");
let after = harness.counters.snapshot();
assert_eq!(
after.0 - baseline.0,
0,
"the follow-ups must not mint a new session"
);
assert_eq!(
after.1 - baseline.1,
2,
"only the legacy follow-up consults the store (twice); the independent modern request does not"
);
assert_eq!(after.2 - baseline.2, 0);
assert_eq!(
harness.upstream.arrivals() - arrivals_baseline,
2,
"exactly one outbound call per follow-up"
);
}
// ---------------------------------------------------------------------------------------------
// AT-10: causal capture - a minimal legacy client receives no undeclared server->client message.
// ---------------------------------------------------------------------------------------------
#[tokio::test]
async fn era_isolation_minimal_client_receives_no_undeclared_server_to_client_message() {
let harness = harness("era-minimal-client").await;
let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await;
// Capture happens strictly after the response future completes (no sleep, no polling); the
// minimal client advertises no capabilities at all.
let response = post_jsonrpc_with_headers(
&harness.client,
&harness.mcp_url,
&harness.api_key,
&header_refs(&legacy_headers(&session)),
json!({ "jsonrpc": "2.0", "id": 41, "method": "tools/list", "params": {} }),
)
.await;
assert_eq!(response.status().as_u16(), 200);
let content_type = response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
.to_owned();
let captured_headers: BTreeMap<String, String> = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_ascii_lowercase(),
value.to_str().unwrap_or_default().to_owned(),
)
})
.collect();
let (body, _raw) = bounded_json_body(response).await;
// A single JSON-RPC answer, not a stream, and no extra server->client notification/method.
assert!(
content_type.starts_with("application/json"),
"a minimal client asked for JSON and must receive JSON, got {content_type:?}"
);
assert!(
body.get("method").is_none(),
"no server->client method may be emitted: {body}"
);
assert!(body.get("id").is_some() && body.get("jsonrpc").is_some());
assert!(
body["error"].is_null(),
"the minimal client's tools/list must succeed, got {body}"
);
assert_eq!(body["result"]["tools"][0]["name"], harness.tool_name);
// Current pagination only: no new opaque cursor contract is introduced here (that stays 3.2).
assert!(
body["result"].get("nextCursor").is_none(),
"a single-page catalog must not invent a cursor, got {body}"
);
assert!(
!captured_headers.contains_key("mcp-session-id"),
"only initialize mints a session header; the captured headers were {captured_headers:?}"
);
// A legacy request that never asks for Tools does not reach the upstream either.
assert_eq!(
harness.upstream.arrivals(),
0,
"tools/list performs no outbound tool execution"
);
}
@@ -0,0 +1,645 @@
//! Instrumented harness of `era_isolation`: counted session store, arrival barriers, held upstream,
//! test-server lifecycle and cleanup, plus the fixture constants the scenarios share.
//!
//! Moved verbatim out of `era_isolation.rs` (Story 3.6, kanban t_987bf309). Expectations, timeouts,
//! the Drop/cleanup order and every counter are unchanged; the scenario module reaches these items
//! through `super::harness`.
use super::super::common::*;
use async_trait::async_trait;
use axum::{Json, Router, extract::State, http::header, routing::post};
use crank_community_mcp::session::{
InMemorySessionStore, SessionState, SessionStoreError, SharedSessionStore,
TransportSessionStore,
};
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
};
use std::time::Duration;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
/// Bound on waiting for one in-processing arrival marker. The held handler itself has no bound: the
/// test bounds the wait and is responsible for releasing the gate on every path.
const MARKER_TIMEOUT: Duration = Duration::from_secs(5);
/// Bound on joining a request task after the gates were released, and on reading a response body.
pub(super) const REAP_TIMEOUT: Duration = Duration::from_secs(5);
/// The two sides are different Agents with different catalogs and different canary payloads, so a
/// crossed result cannot pass on a shared fixed id.
pub(super) const LEGACY_TOOL: &str = "crm_create_lead";
pub(super) const MODERN_TOOL: &str = "crm_create_lead_modern";
pub(super) const LEGACY_CANARY: &str = "legacy-canary@example.com";
pub(super) const MODERN_CANARY: &str = "modern-canary@example.com";
pub(super) fn canary_id(canary: &str) -> String {
format!("lead::{canary}")
}
/// A bounded wait that expired before the named in-processing marker arrived.
#[derive(Debug)]
pub(super) struct MarkerTimeout {
marker: &'static str,
deadline: Duration,
}
impl MarkerTimeout {
pub(super) fn describe(&self) -> String {
format!(
"bounded {:?} wait expired: {} never arrived",
self.deadline, self.marker
)
}
}
async fn await_notification(
notified: &Notify,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
if tokio::time::timeout(deadline, notified.notified())
.await
.is_ok()
{
Ok(())
} else {
Err(MarkerTimeout { marker, deadline })
}
}
// ---------------------------------------------------------------------------------------------
// Instrumented session store: counts store *operations* and can hold one session's `get`.
// ---------------------------------------------------------------------------------------------
#[derive(Default)]
pub(super) struct StoreCounters {
creates: AtomicU64,
gets: AtomicU64,
marks: AtomicU64,
}
impl StoreCounters {
pub(super) fn snapshot(&self) -> (u64, u64, u64) {
(
self.creates.load(Ordering::SeqCst),
self.gets.load(Ordering::SeqCst),
self.marks.load(Ordering::SeqCst),
)
}
}
pub(super) struct InstrumentedSessionStore {
inner: InMemorySessionStore,
counters: Arc<StoreCounters>,
holding: AtomicBool,
hold_session: Mutex<Option<String>>,
gets_for_held_session: AtomicU64,
/// Index of the `get` call for the held session that acts as the in-processing arrival marker.
/// `2` is deliberate: `mcp_post_response` performs its own session lookup for any request that
/// carries a session header **before** era resolution (`app.rs:866-895`), while the legacy
/// handler's `require_initialized_session` lookup happens **after** admission and inside the
/// legacy branch - only the latter proves that the legacy handler is in processing.
hold_on_get_number: AtomicU64,
/// Handlers currently parked inside the held `get`: proves that the legacy side really is held.
parked_waiters: AtomicU64,
arrived: Arc<Notify>,
released: Arc<Notify>,
}
impl InstrumentedSessionStore {
fn new() -> (Arc<Self>, Arc<StoreCounters>) {
let counters = Arc::new(StoreCounters::default());
let store = Arc::new(Self {
inner: InMemorySessionStore::default(),
counters: Arc::clone(&counters),
holding: AtomicBool::new(false),
hold_session: Mutex::new(None),
gets_for_held_session: AtomicU64::new(0),
hold_on_get_number: AtomicU64::new(2),
parked_waiters: AtomicU64::new(0),
arrived: Arc::new(Notify::new()),
released: Arc::new(Notify::new()),
});
(store, counters)
}
pub(super) fn hold(&self, session_id: &str) {
*self.hold_session.lock().unwrap() = Some(session_id.to_owned());
self.gets_for_held_session.store(0, Ordering::SeqCst);
self.holding.store(true, Ordering::SeqCst);
}
pub(super) fn release(&self) {
self.holding.store(false, Ordering::SeqCst);
// Leave a permit for a waiter that has not parked yet, then wake the parked ones. The gate
// flag (not the permit) is the source of truth, so a leftover permit cannot keep a handler
// inside the gate and cannot fake a later overlap.
self.released.notify_one();
self.released.notify_waiters();
}
pub(super) fn is_holding(&self) -> bool {
self.holding.load(Ordering::SeqCst)
}
pub(super) fn parked_waiters(&self) -> u64 {
self.parked_waiters.load(Ordering::SeqCst)
}
pub(super) async fn await_arrival(
&self,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
await_notification(&self.arrived, marker, deadline).await
}
async fn hold_if_needed(&self, session_id: &str) {
if !self.holding.load(Ordering::SeqCst) {
return;
}
let is_held = self.hold_session.lock().unwrap().as_deref() == Some(session_id);
if !is_held {
return;
}
let call_number = self.gets_for_held_session.fetch_add(1, Ordering::SeqCst) + 1;
if call_number != self.hold_on_get_number.load(Ordering::SeqCst) {
return;
}
self.parked_waiters.fetch_add(1, Ordering::SeqCst);
self.arrived.notify_one();
// Hold until the explicit coordinated release. There is deliberately no internal deadline:
// an internal timeout-and-continue could let this era proceed while the other era has not
// arrived yet, which is exactly the false overlap the barrier must not allow.
while self.holding.load(Ordering::SeqCst) {
self.released.notified().await;
}
self.parked_waiters.fetch_sub(1, Ordering::SeqCst);
}
}
#[async_trait]
impl TransportSessionStore for InstrumentedSessionStore {
async fn create(
&self,
protocol_version: &str,
workspace_slug: &str,
agent_slug: &str,
supports_elicitation: bool,
now: OffsetDateTime,
expires_at: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError> {
self.counters.creates.fetch_add(1, Ordering::SeqCst);
self.inner
.create(
protocol_version,
workspace_slug,
agent_slug,
supports_elicitation,
now,
expires_at,
)
.await
}
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
self.counters.gets.fetch_add(1, Ordering::SeqCst);
self.hold_if_needed(session_id).await;
self.inner.get(session_id).await
}
async fn mark_initialized(
&self,
session_id: &str,
now: OffsetDateTime,
) -> Result<bool, SessionStoreError> {
self.counters.marks.fetch_add(1, Ordering::SeqCst);
self.inner.mark_initialized(session_id, now).await
}
async fn delete(&self, session_id: &str) -> Result<bool, SessionStoreError> {
self.inner.delete(session_id).await
}
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.cleanup_expired(now).await
}
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.active_count(now).await
}
}
// ---------------------------------------------------------------------------------------------
// Held, counted loopback upstream: signals that a tool-execution request physically arrived and
// echoes a per-side canary back into the tool result.
// ---------------------------------------------------------------------------------------------
#[derive(Clone)]
pub(super) struct HeldUpstream {
arrivals: Arc<AtomicU64>,
holding: Arc<AtomicBool>,
parked_waiters: Arc<AtomicU64>,
arrived: Arc<Notify>,
released: Arc<Notify>,
}
impl HeldUpstream {
fn new() -> Self {
Self {
arrivals: Arc::new(AtomicU64::new(0)),
holding: Arc::new(AtomicBool::new(false)),
parked_waiters: Arc::new(AtomicU64::new(0)),
arrived: Arc::new(Notify::new()),
released: Arc::new(Notify::new()),
}
}
pub(super) fn hold(&self) {
self.holding.store(true, Ordering::SeqCst);
}
pub(super) fn release(&self) {
self.holding.store(false, Ordering::SeqCst);
self.released.notify_one();
self.released.notify_waiters();
}
pub(super) fn is_holding(&self) -> bool {
self.holding.load(Ordering::SeqCst)
}
pub(super) fn parked_waiters(&self) -> u64 {
self.parked_waiters.load(Ordering::SeqCst)
}
pub(super) async fn await_arrival(
&self,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
await_notification(&self.arrived, marker, deadline).await
}
pub(super) fn arrivals(&self) -> u64 {
self.arrivals.load(Ordering::SeqCst)
}
}
async fn held_create_lead(
State(upstream): State<HeldUpstream>,
Json(payload): Json<Value>,
) -> Json<Value> {
upstream.arrivals.fetch_add(1, Ordering::SeqCst);
upstream.parked_waiters.fetch_add(1, Ordering::SeqCst);
upstream.arrived.notify_one();
// Same discipline as the session-store gate: wait for the explicit release, never continue on an
// internal timeout (that would let this side finish before the other side's marker arrives).
while upstream.holding.load(Ordering::SeqCst) {
upstream.released.notified().await;
}
upstream.parked_waiters.fetch_sub(1, Ordering::SeqCst);
// Per-side scoped output: the canary the caller sent comes back inside the tool result, so a
// swapped or crossed result is visible in the response instead of hiding behind a fixed id.
let email = payload["email"].as_str().unwrap_or("unknown-canary");
Json(json!({ "id": canary_id(email), "email": email }))
}
async fn spawn_held_upstream(upstream: HeldUpstream) -> (String, JoinHandle<()>) {
let app = Router::new()
.route("/crm/leads", post(held_create_lead))
.with_state(upstream);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{}", address), handle)
}
/// The module keeps the MCP server task handle for its own bounded cleanup (abort on the failure
/// path and when the harness is dropped), so it does not use the fire-and-forget helper.
async fn spawn_mcp_server_task(app: Router) -> (String, JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{}", address), handle)
}
// ---------------------------------------------------------------------------------------------
// Harness
// ---------------------------------------------------------------------------------------------
#[derive(Clone)]
pub(super) struct ClientSide {
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) tool_name: String,
}
pub(super) struct Harness {
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) tool_name: String,
/// A second Agent with its own catalog, used by the mixed-era overlap test to also cover the
/// agreed Agent/catalog scope.
alternate: Option<ClientSide>,
pub(super) store: Arc<InstrumentedSessionStore>,
pub(super) counters: Arc<StoreCounters>,
pub(super) upstream: HeldUpstream,
mcp_server: JoinHandle<()>,
upstream_server: JoinHandle<()>,
}
impl Harness {
pub(super) fn primary(&self) -> ClientSide {
ClientSide {
mcp_url: self.mcp_url.clone(),
api_key: self.api_key.clone(),
tool_name: self.tool_name.clone(),
}
}
pub(super) fn alternate(&self) -> ClientSide {
self.alternate
.clone()
.expect("this harness runs two Agents; the overlap test is the only caller")
}
}
impl Drop for Harness {
fn drop(&mut self) {
// Stop only this test's own servers.
self.mcp_server.abort();
self.upstream_server.abort();
}
}
pub(super) async fn harness(agent_slug: &str) -> Harness {
harness_with_sides(agent_slug, None).await
}
pub(super) async fn harness_with_two_agents(legacy_slug: &str, modern_slug: &str) -> Harness {
harness_with_sides(legacy_slug, Some(modern_slug)).await
}
async fn harness_with_sides(agent_slug: &str, modern_agent_slug: Option<&str>) -> Harness {
let registry = test_registry().await;
let upstream = HeldUpstream::new();
let (upstream_base_url, upstream_server) = spawn_held_upstream(upstream.clone()).await;
let operation = test_operation(&upstream_base_url, LEGACY_TOOL);
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, agent_slug).await;
let api_key = create_platform_api_key(
&registry,
agent_slug,
"mcp-era-isolation",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
// Optional second Agent: its own catalog (its own tool), its own key, its own canary.
let alternate = match modern_agent_slug {
None => None,
Some(modern_slug) => {
let modern_operation = test_operation(&upstream_base_url, MODERN_TOOL);
registry
.create_operation(&test_workspace_id(), &modern_operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &modern_operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &modern_operation, modern_slug).await;
let modern_api_key = create_platform_api_key(
&registry,
modern_slug,
"mcp-era-isolation-modern",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
Some(ClientSide {
mcp_url: String::new(),
api_key: modern_api_key,
tool_name: MODERN_TOOL.to_owned(),
})
}
};
let (store, counters) = InstrumentedSessionStore::new();
let sessions: SharedSessionStore = store.clone();
let (base_url, mcp_server) = spawn_mcp_server_task(build_test_app_with_sessions(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
sessions,
))
.await;
let alternate = alternate.map(|mut side| {
side.mcp_url = agent_mcp_url(&base_url, modern_agent_slug.expect("a modern agent slug"));
side
});
Harness {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, agent_slug),
api_key,
tool_name: LEGACY_TOOL.to_owned(),
alternate,
store,
counters,
upstream,
mcp_server,
upstream_server,
}
}
pub(super) fn header_refs<'a>(
headers: &'a [(&'static str, String)],
) -> Vec<(&'static str, &'a str)> {
headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect()
}
// ---------------------------------------------------------------------------------------------
// Bounded overlap run: owns the request tasks and the failure-path cleanup.
// ---------------------------------------------------------------------------------------------
pub(super) struct OverlapRun<'a> {
harness: &'a Harness,
pub(super) deadline: Duration,
tasks: Vec<Option<JoinHandle<reqwest::Response>>>,
pub(super) joined: usize,
pub(super) cancelled: usize,
}
impl<'a> OverlapRun<'a> {
pub(super) fn new(harness: &'a Harness) -> Self {
Self {
harness,
deadline: MARKER_TIMEOUT,
tasks: Vec::new(),
joined: 0,
cancelled: 0,
}
}
pub(super) fn with_deadline(harness: &'a Harness, deadline: Duration) -> Self {
Self {
harness,
deadline,
tasks: Vec::new(),
joined: 0,
cancelled: 0,
}
}
pub(super) fn spawn(
&mut self,
side: &ClientSide,
headers: Vec<(&'static str, String)>,
payload: Value,
) -> usize {
let client = self.harness.client.clone();
let url = side.mcp_url.clone();
let key = side.api_key.clone();
self.tasks.push(Some(tokio::spawn(async move {
post_jsonrpc_with_headers(&client, &url, &key, &header_refs(&headers), payload).await
})));
self.tasks.len() - 1
}
pub(super) fn is_finished(&self, index: usize) -> bool {
self.tasks
.get(index)
.and_then(|task| task.as_ref())
.is_none_or(|task| task.is_finished())
}
/// Bounded join of one request task. Any failure runs the full cleanup and then fails.
pub(super) async fn join_bounded(
&mut self,
index: usize,
what: &'static str,
) -> reqwest::Response {
let mut task = self.tasks[index]
.take()
.unwrap_or_else(|| panic!("the {what} request task was already joined"));
match tokio::time::timeout(REAP_TIMEOUT, &mut task).await {
Ok(Ok(response)) => {
self.joined += 1;
response
}
Ok(Err(join_error)) => {
self.cancelled += 1;
self.cleanup().await;
panic!("the {what} request task failed: {join_error}");
}
Err(_elapsed) => {
self.cancelled += 1;
task.abort();
let _ = task.await;
self.cleanup().await;
panic!(
"the {what} request task did not finish within {REAP_TIMEOUT:?} after the barrier \
was released"
);
}
}
}
/// Failure path required by R1: release both gates FIRST, then bounded-join or cancel every task
/// this run started, then abort the test's own servers - and only afterwards fail.
pub(super) async fn fail(&mut self, timeout: MarkerTimeout) -> ! {
self.cleanup().await;
panic!("{}", timeout.describe());
}
pub(super) async fn cleanup(&mut self) -> Vec<reqwest::Response> {
self.harness.store.release();
self.harness.upstream.release();
let mut responses = Vec::new();
for slot in self.tasks.iter_mut() {
let Some(mut task) = slot.take() else {
continue;
};
match tokio::time::timeout(REAP_TIMEOUT, &mut task).await {
Ok(Ok(response)) => {
self.joined += 1;
responses.push(response);
}
Ok(Err(_join_error)) => {
self.cancelled += 1;
}
Err(_elapsed) => {
self.cancelled += 1;
task.abort();
let _ = task.await;
}
}
}
self.harness.mcp_server.abort();
self.harness.upstream_server.abort();
responses
}
}
impl Drop for OverlapRun<'_> {
fn drop(&mut self) {
// Never leave a parked handler or a live request task behind, even when an assertion above
// panicked before the coordinated release.
self.harness.store.release();
self.harness.upstream.release();
for slot in self.tasks.iter_mut() {
if let Some(task) = slot.take() {
task.abort();
}
}
}
}
@@ -0,0 +1,275 @@
#![allow(dead_code, unused_imports)]
//! Story 3.1 ATDD (AT-13): per-era advertisement compared against an *independent*, pre-frozen,
//! inventory-derived oracle.
//!
//! Oracle: `tests/fixtures/mcp-revisions/<revision>-advertised-capabilities.frozen.json`, produced by
//! the server-only projection of the reviewed inventory (spec section 5, rules 1-4) - never from a
//! captured server response, never era-vs-era. Each era is compared **on its own**: the parsed
//! `result.capabilities` is re-serialized with the workspace's actual deterministic `serde_json`
//! serialization (default map order, no `preserve_order`) and compared byte-for-byte.
//!
//! The sidecar `<revision>-advertised-capabilities.provenance.json` is audit-only: it is never
//! byte-compared with the endpoint and carries the participating identity triples instead.
use super::common::*;
use std::path::PathBuf;
use std::time::Duration;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
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";
fn fixture_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/mcp-revisions")
.join(name)
}
fn frozen_capabilities(revision: &str) -> Vec<u8> {
let path = fixture_path(&format!("{revision}-advertised-capabilities.frozen.json"));
std::fs::read(&path).unwrap_or_else(|error| {
panic!(
"the pre-frozen per-era oracle must be readable at {}: {error}",
path.display()
)
})
}
fn provenance_sidecar(revision: &str) -> Value {
let path = fixture_path(&format!(
"{revision}-advertised-capabilities.provenance.json"
));
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
panic!(
"the projection provenance sidecar must be readable at {}: {error}",
path.display()
)
});
serde_json::from_str(&raw).unwrap()
}
/// The same deterministic serialization the test compares against: compact, and (because this
/// workspace does not enable `serde_json`'s `preserve_order`) object keys follow the default map
/// order rather than insertion order.
fn canonical(component: &Value) -> Vec<u8> {
serde_json::to_vec(component).expect("a parsed capability object is always serializable")
}
fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-inventory-client", "version": "0.1.0" }
})
}
struct Endpoint {
client: reqwest::Client,
mcp_url: String,
api_key: String,
}
async fn endpoint() -> Endpoint {
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-inventory").await;
let api_key = create_platform_api_key(
&registry,
"sales-inventory",
"mcp-inventory",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
Endpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-inventory"),
api_key,
}
}
async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
})
}
/// AT-13 / AT-05: the legacy `initialize` advertisement equals the frozen legacy-era oracle.
#[tokio::test]
async fn inventory_projection_legacy_initialize_matches_the_frozen_oracle() {
let endpoint = endpoint().await;
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.json(&json!({
"jsonrpc": "2.0",
"id": 101,
"method": "initialize",
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
}))
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"legacy initialize must be served"
);
let body = json_body(response).await;
let capabilities = body["result"]["capabilities"]
.as_object()
.unwrap_or_else(|| {
panic!("legacy initialize must return a capabilities object, got {body}")
});
assert_eq!(
canonical(&Value::Object(capabilities.clone())),
frozen_capabilities(LEGACY_REVISION),
"the served legacy capabilities must be byte-equal to the independent frozen oracle, got {body}"
);
}
/// AT-13 / AT-04: the modern `server/discover` advertisement equals the frozen modern-era oracle.
#[tokio::test]
async fn inventory_projection_modern_discover_matches_the_frozen_oracle() {
let endpoint = endpoint().await;
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "server/discover")
.json(&json!({
"jsonrpc": "2.0",
"id": 102,
"method": "server/discover",
"params": { "_meta": modern_meta(MODERN_REVISION) }
}))
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"modern discover must be served"
);
let body = json_body(response).await;
let capabilities = body["result"]["capabilities"]
.as_object()
.unwrap_or_else(|| panic!("modern discover must return a capabilities object, got {body}"));
assert_eq!(
canonical(&Value::Object(capabilities.clone())),
frozen_capabilities(MODERN_REVISION),
"the served modern capabilities must be byte-equal to the independent frozen oracle, got {body}"
);
}
/// AT-13: both eras are compared against their own oracle, and the provenance sidecar is an audit
/// document (inventory digest + participating triples), never another copy of the endpoint answer.
#[tokio::test]
async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projection_inputs() {
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let frozen = frozen_capabilities(revision);
let sidecar = provenance_sidecar(revision);
assert!(
sidecar["rule"].is_string() && sidecar["inventory_sha256"].is_string(),
"{revision} sidecar must record the projection rule and the inventory digest"
);
let triples: Vec<(String, String, String)> = sidecar["projection_inputs"]
.as_array()
.unwrap_or_else(|| panic!("{revision} sidecar must list the projection inputs"))
.iter()
.map(|item| {
(
item["role"].as_str().unwrap().to_owned(),
item["kind"].as_str().unwrap().to_owned(),
item["surface"].as_str().unwrap().to_owned(),
)
})
.collect();
assert_eq!(
triples,
vec![
(
"server".to_owned(),
"capability".to_owned(),
"completions".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"prompts".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"resources".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"tools".to_owned()
)
],
"the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`"
);
// The sidecar is not the payload: byte comparison is against the frozen file only.
assert_ne!(
serde_json::to_vec(&sidecar).unwrap(),
frozen,
"the provenance sidecar must never be the byte oracle"
);
}
}
@@ -0,0 +1,408 @@
//! Story 3.17 acceptance tests: bounded completion of the arguments of bound Published Prompts and of
//! the parameters of bound Published Resource templates through MCP (AT-3.17-01..03).
//!
//! Oracles: `docs/acceptance-test-plan.md` AT-3.17-01..03, `epics.md` Story 3.17 and the pinned
//! `completion/complete` schemas of both supported revisions. Every request travels through the real
//! HTTP endpoint built by `build_test_app` against a real PostgreSQL registry; the bound versions are
//! produced through the production registry path. Each case runs on both supported revisions, because
//! AC3 requires per-revision positive/negative/authorization coverage.
//!
//! No real external MCP client is exercised here: these are local harness results against the pinned
//! wire shapes. That is stated as NOT_RUN in the story handoff instead of being claimed as a client
//! qualification.
mod fixtures;
mod response_metrics;
use serde_json::{Value, json};
use fixtures::*;
fn completion(body: &Value) -> &Value {
body.pointer("/result/completion")
.unwrap_or_else(|| panic!("the completion result is missing: {body}"))
}
fn values(body: &Value) -> Vec<String> {
completion(body)["values"]
.as_array()
.unwrap_or_else(|| panic!("`completion.values` must be an array: {body}"))
.iter()
.map(|value| {
value
.as_str()
.unwrap_or_else(|| panic!("every completion value is a string: {body}"))
.to_owned()
})
.collect()
}
fn error(body: &Value) -> (i64, String) {
let code = body
.pointer("/error/code")
.and_then(Value::as_i64)
.unwrap_or_else(|| panic!("expected a JSON-RPC error code: {body}"));
let message = body
.pointer("/error/message")
.and_then(Value::as_str)
.unwrap_or_else(|| panic!("expected a JSON-RPC error message: {body}"))
.to_owned();
(code, message)
}
fn prompt_ref(name: &str) -> Value {
json!({"type": "ref/prompt", "name": name})
}
fn resource_ref(uri: &str) -> Value {
json!({"type": "ref/resource", "uri": uri})
}
fn request(reference: Value, argument: &str, value: &str) -> Value {
json!({
"ref": reference,
"argument": {"name": argument, "value": value}
})
}
/// AT-3.17-01/03: the advertised capability equals the implemented method on both revisions.
#[tokio::test]
async fn advertisement_declares_completions_on_both_revisions() {
let endpoint = completion_endpoint().await;
let discover = endpoint.modern_method("server/discover", json!({})).await;
assert_eq!(
discover["result"]["capabilities"]["completions"],
json!({}),
"the modern advertisement must declare the completions capability: {discover}"
);
let initialize = endpoint.legacy_initialize().await;
assert_eq!(
initialize["result"]["capabilities"]["completions"],
json!({}),
"the legacy advertisement must declare the completions capability: {initialize}"
);
}
/// AT-3.17-01: bounded, authorized suggestions from the typed schema of the bound Prompt argument.
#[tokio::test]
async fn prompt_argument_completion_is_bounded_and_typed_on_every_revision() {
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let all = endpoint
.on_revision(revision, request(prompt_ref("greeting"), "tone", ""))
.await;
assert_eq!(
values(&all),
["warm", "dry"],
"the whole typed enumeration is suggested on {revision}: {all}"
);
assert_eq!(
completion(&all)["total"],
json!(2),
"the exact option count is reported on {revision}: {all}"
);
assert!(
completion(&all).get("hasMore").is_none(),
"a complete enumeration carries no `hasMore` on {revision}: {all}"
);
let filtered = endpoint
.on_revision(revision, request(prompt_ref("greeting"), "tone", "w"))
.await;
assert_eq!(
values(&filtered),
["warm"],
"the partial token filters the enumeration on {revision}: {filtered}"
);
assert_eq!(completion(&filtered)["total"], json!(1));
// Prefix matching is ASCII-case-insensitive, so a client that upper-cases a token still gets
// the published option; the value itself is served exactly as published.
let caseless = endpoint
.on_revision(revision, request(prompt_ref("greeting"), "tone", "D"))
.await;
assert_eq!(
values(&caseless),
["dry"],
"case-insensitive prefix matching on {revision}: {caseless}"
);
}
}
/// AT-3.17-01: a typed schema without an enumeration suggests nothing rather than inventing values.
#[tokio::test]
async fn an_argument_without_an_enumeration_gets_no_invented_suggestions() {
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let body = endpoint
.on_revision(revision, request(prompt_ref("greeting"), "name", "A"))
.await;
assert_eq!(
values(&body),
Vec::<String>::new(),
"a plain string argument has no enumerated suggestions on {revision}: {body}"
);
assert_eq!(completion(&body)["total"], json!(0));
assert!(completion(&body).get("hasMore").is_none());
}
}
/// AT-3.17-01/03: a Draft, unbound, foreign or unknown Prompt (and an unknown argument) is one
/// indistinguishable refusal that discloses no identifier.
#[tokio::test]
async fn a_draft_unbound_or_foreign_prompt_is_indistinguishable() {
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let mut observed = Vec::new();
for (case, request_value) in [
(
"foreign prompt",
request(prompt_ref("other-agent-prompt"), "tone", ""),
),
(
"draft prompt",
request(prompt_ref("draft-prompt"), "tone", ""),
),
(
"unbound prompt",
request(prompt_ref("unbound-prompt"), "tone", ""),
),
(
"unknown prompt",
request(prompt_ref("no-such-prompt"), "tone", ""),
),
(
"unknown argument",
request(prompt_ref("greeting"), "no-such-argument", ""),
),
] {
let body = endpoint.on_revision(revision, request_value).await;
let (code, message) = error(&body);
assert_eq!(code, -32602, "{case} on {revision}: {body}");
assert_eq!(
message, NOT_AVAILABLE,
"{case} on {revision} must use the single safe refusal: {body}"
);
assert!(
body.get("result").is_none(),
"{case} on {revision} must not carry a result: {body}"
);
let serialized = body.to_string();
for leaked in [
"other-agent-prompt",
"draft-prompt",
"unbound-prompt",
"no-such-prompt",
"no-such-argument",
"Other agent secret.",
"Draft content.",
"Unbound content.",
] {
assert!(
!serialized.contains(leaked),
"{case} on {revision} must not disclose {leaked:?}: {serialized}"
);
}
observed.push((code, message));
}
assert!(
observed.windows(2).all(|pair| pair[0] == pair[1]),
"every unavailable case must answer identically on {revision}: {observed:?}"
);
}
}
/// AT-3.17-01: the second supported reference form — a bound Resource template parameter.
#[tokio::test]
async fn resource_template_parameter_completion_uses_the_bound_schema() {
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let all = endpoint
.on_revision(
revision,
request(resource_ref(BOUND_TEMPLATE_URI), "region", ""),
)
.await;
assert_eq!(
values(&all),
["eu", "us", "apac"],
"the bound template's enumerated parameter is suggested on {revision}: {all}"
);
assert_eq!(completion(&all)["total"], json!(3));
let filtered = endpoint
.on_revision(
revision,
request(resource_ref(BOUND_TEMPLATE_URI), "region", "a"),
)
.await;
assert_eq!(
values(&filtered),
["apac"],
"the partial token filters the template parameter on {revision}: {filtered}"
);
}
}
/// AT-3.17-01/03: a foreign or unknown URI template, and an unknown parameter, share one refusal.
#[tokio::test]
async fn a_foreign_or_unknown_template_uri_is_indistinguishable() {
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let mut observed = Vec::new();
for request_value in [
request(resource_ref(FOREIGN_TEMPLATE_URI), "region", ""),
request(resource_ref("crank://no-such/{region}"), "region", ""),
request(resource_ref(BOUND_TEMPLATE_URI), "no-such-parameter", ""),
] {
let body = endpoint.on_revision(revision, request_value).await;
let (code, message) = error(&body);
assert_eq!(code, -32602, "{body}");
assert_eq!(message, NOT_AVAILABLE, "{body}");
let serialized = body.to_string();
for leaked in [
FOREIGN_TEMPLATE_URI,
"crank://no-such/{region}",
"no-such-parameter",
] {
assert!(
!serialized.contains(leaked),
"an unavailable template must not disclose {leaked:?}: {serialized}"
);
}
observed.push((code, message));
}
assert!(
observed.windows(2).all(|pair| pair[0] == pair[1]),
"every unavailable template case must answer identically on {revision}: {observed:?}"
);
}
}
/// AT-3.17-02: malformed or oversized requests are safe errors and never echo the input.
#[tokio::test]
async fn malformed_requests_are_safe_errors_without_echoing_input() {
let endpoint = completion_endpoint().await;
let oversized_token = "s".repeat(2_000);
for revision in [MODERN_REVISION, LEGACY_REVISION] {
for (case, params) in [
(
"missing ref",
json!({"argument": {"name": "tone", "value": ""}}),
),
(
"unknown ref type",
request(json!({"type": "ref/tool", "name": "x"}), "tone", ""),
),
(
"argument is not an object",
json!({"ref": prompt_ref("greeting"), "argument": "tone"}),
),
(
"oversized token",
request(prompt_ref("greeting"), "tone", &oversized_token),
),
(
"oversized argument name",
request(prompt_ref("greeting"), &"n".repeat(200), ""),
),
(
"context with a non-string value",
json!({
"ref": prompt_ref("greeting"),
"argument": {"name": "tone", "value": ""},
"context": {"arguments": {"region": 7}}
}),
),
] {
let body = endpoint.on_revision(revision, params).await;
let (code, message) = error(&body);
assert_eq!(code, -32602, "{case} on {revision}: {body}");
assert!(
message == INVALID_PARAMS || message == NOT_AVAILABLE,
"{case} on {revision} must be answered with one safe detail: {body}"
);
let serialized = body.to_string();
assert!(
!serialized.contains(&oversized_token),
"{case} on {revision} must not echo the client token: {serialized}"
);
assert!(
!serialized.contains(&"n".repeat(200)),
"{case} on {revision} must not echo the argument name: {serialized}"
);
}
}
}
/// AT-3.17-03: the authorization boundary is the Agent route and its bound snapshot — the other
/// Agent of the same workspace cannot address this Agent's Prompt or template, and this Agent cannot
/// address the other Agent's.
#[tokio::test]
async fn the_other_agents_snapshot_is_not_addressable() {
let endpoint = completion_endpoint().await;
let other_key = endpoint.other_agent_key().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
// The other Agent's credential and route complete its own Prompt argument…
let own = match revision {
MODERN_REVISION => {
endpoint
.modern_for(
OTHER_AGENT_SLUG,
&other_key,
request(prompt_ref("other-agent-prompt"), "tone", ""),
)
.await
}
_ => {
endpoint
.legacy_for(
OTHER_AGENT_SLUG,
&other_key,
request(prompt_ref("other-agent-prompt"), "tone", ""),
)
.await
}
};
let (code, message) = error(&own);
assert_eq!(
(code, message.as_str()),
(-32602, NOT_AVAILABLE),
"the other Agent's Prompt has no argument of that name, so nothing is suggested on {revision}: {own}"
);
// …and cannot address this Agent's bound Prompt or template.
for request_value in [
request(prompt_ref("greeting"), "tone", ""),
request(resource_ref(BOUND_TEMPLATE_URI), "region", ""),
] {
let body = match revision {
MODERN_REVISION => {
endpoint
.modern_for(OTHER_AGENT_SLUG, &other_key, request_value)
.await
}
_ => {
endpoint
.legacy_for(OTHER_AGENT_SLUG, &other_key, request_value)
.await
}
};
let (code, message) = error(&body);
assert_eq!(
(code, message.as_str()),
(-32602, NOT_AVAILABLE),
"a foreign snapshot is not addressable on {revision}: {body}"
);
}
}
}
@@ -0,0 +1,558 @@
//! Story 3.17 acceptance fixtures: a real MCP endpoint over a real PostgreSQL registry.
//!
//! Everything is the production path: `build_test_app` + the real
//! `CommunityMachineCredentialVerifier`, published Prompt versions created through the registry
//! (`create_prompt_draft` → `publish_prompt_draft`), one published Resource template with a typed
//! enum parameter (`create_resource_template_draft` → `publish_resource_template_version`) whose
//! declared Read Operation is published too, exact bindings written through
//! `save_agent_catalog_config_editable_with_prompts`, and an Agent published with `publish_agent`.
//! No route stub, no fake service, no row written behind the registry's back.
//!
//! Bounded fixture set:
//! - `greeting` (bound to `completion-agent`) — argument `name` (plain string, no enumeration) and
//! `tone` (enum `warm|dry`, default `warm`);
//! - `completion-orders` (bound template) — URI template `crank://completion-orders/{region}` with an
//! enumerated `region` parameter (`eu|us|apac`);
//! - `draft-prompt` — Draft only, never published;
//! - `unbound-prompt` — published but not bound to any Agent;
//! - `other-agent-prompt` and `crank://completion-other/{region}` — bound to the other Agent of the
//! same workspace (scope isolation).
//!
//! Test-owned identifiers are distinctive on purpose: the AC1 cases assert that none of these names or
//! URIs is echoed by an unavailable completion.
#![allow(dead_code)]
use std::time::Duration;
use crank_core::ids::{PromptId, ResourceId};
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
use crank_core::resource::TemplateSource;
use crank_core::{
Agent, AgentId, AgentStatus, AgentVersion, HttpMethod, PlatformApiKeyScope, RestTarget, Target,
ToolSelectionPolicy, WorkspaceId,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::model::{
AgentPromptBinding, CreatePromptDraftRequest, CreateResourceTemplateDraftRequest,
PublishPromptRequest, PublishResourceTemplateVersionRequest, SaveAgentCatalogConfigRequest,
};
use crank_registry::{
AgentResourceBinding, CreateAgentRequest, PostgresRegistry, PublishAgentRequest, PublishRequest,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use super::super::common::{
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session, object_schema,
post_jsonrpc_with_headers, spawn_mcp_server, test_operation, test_registry, test_workspace_id,
};
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
pub(super) const AGENT_SLUG: &str = "completion-agent";
pub(super) const OTHER_AGENT_SLUG: &str = "completion-other";
/// The exact URI template of the bound template fixture.
pub(super) const BOUND_TEMPLATE_URI: &str = "crank://completion-orders/{region}";
/// The exact URI template bound only to the other Agent.
pub(super) const FOREIGN_TEMPLATE_URI: &str = "crank://completion-other/{region}";
/// The one safe wire detail of a malformed completion request.
pub(super) const INVALID_PARAMS: &str = "invalid completion/complete parameters";
/// The one safe wire detail of an unavailable completion reference.
pub(super) const NOT_AVAILABLE: &str = "the completion reference is not available";
fn greeting_definition() -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "greeting",
"description": "Greets the customer",
"arguments": [
{"name": "name", "schema": {"type": "string"}, "required": true},
{
"name": "tone",
"schema": {"type": "string", "enum": ["warm", "dry"]},
"required": false,
"default": "warm"
}
],
"messages": [{"role": "user", "content": "Hello {{name}}"}]
}))
.expect("the greeting definition is valid")
}
fn simple_definition(name: &str, description: &str, content: &str) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": name,
"description": description,
"arguments": [],
"messages": [{"role": "user", "content": content}]
}))
.expect("the simple definition is valid")
}
pub(super) struct CompletionEndpoint {
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) base_url: String,
pub(super) api_key: String,
pub(super) registry: PostgresRegistry,
}
impl CompletionEndpoint {
/// One modern `completion/complete` request with the required per-request identity. The method
/// declares no `Mcp-Name` (its `ref` is a union), so only `Mcp-Method` travels with it.
pub(super) async fn modern(&self, params: Value) -> Value {
self.modern_for(AGENT_SLUG, &self.api_key, params).await
}
pub(super) async fn modern_for(&self, agent_slug: &str, api_key: &str, params: Value) -> Value {
let mut params = params;
params["_meta"] = json!({
META_PROTOCOL_VERSION: MODERN_REVISION,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: {"name": "crank-completion-atdd", "version": "0.1.0"}
});
let response = post_jsonrpc_with_headers(
&self.client,
&agent_mcp_url(&self.base_url, agent_slug),
api_key,
&[
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "completion/complete"),
],
json!({"jsonrpc": "2.0", "id": 21, "method": "completion/complete", "params": params}),
)
.await;
json_body(response).await
}
/// The same request inside the initialized legacy session of the chosen Agent.
pub(super) async fn legacy(&self, params: Value) -> Value {
self.legacy_for(AGENT_SLUG, &self.api_key, params).await
}
pub(super) async fn legacy_for(&self, agent_slug: &str, api_key: &str, params: Value) -> Value {
let session = self.legacy_session_for(agent_slug, api_key).await;
let response = self
.client
.post(agent_mcp_url(&self.base_url, agent_slug))
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header("MCP-Session-Id", session)
.json(&json!({"jsonrpc": "2.0", "id": 22, "method": "completion/complete", "params": params}))
.send()
.await
.unwrap();
json_body(response).await
}
/// One modern request of an arbitrary method (advertisement probes); the request declares its
/// `Mcp-Method` header exactly as the pinned transport requires.
pub(super) async fn modern_method(&self, method: &str, params: Value) -> Value {
let mut params = params;
params["_meta"] = json!({
META_PROTOCOL_VERSION: MODERN_REVISION,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: {"name": "crank-completion-atdd", "version": "0.1.0"}
});
let response = post_jsonrpc_with_headers(
&self.client,
&self.mcp_url,
&self.api_key,
&[
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", method),
],
json!({"jsonrpc": "2.0", "id": 31, "method": method, "params": params}),
)
.await;
json_body(response).await
}
/// The legacy `initialize` response of this Agent route (the legacy advertisement probe).
pub(super) async fn legacy_initialize(&self) -> Value {
let response = self
.client
.post(&self.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", self.api_key),
)
.json(&json!({
"jsonrpc": "2.0",
"id": 32,
"method": "initialize",
"params": {"protocolVersion": LEGACY_REVISION, "capabilities": {}}
}))
.send()
.await
.unwrap();
json_body(response).await
}
pub(super) async fn legacy_session_for(&self, agent_slug: &str, api_key: &str) -> String {
initialize_session(
&self.client,
&agent_mcp_url(&self.base_url, agent_slug),
api_key,
)
.await
}
/// The same completion case on the requested supported revision.
pub(super) async fn on_revision(&self, revision: &str, params: Value) -> Value {
match revision {
MODERN_REVISION => self.modern(params).await,
LEGACY_REVISION => self.legacy(params).await,
other => panic!("{other} is not a supported protocol revision"),
}
}
pub(super) async fn other_agent_key(&self) -> String {
create_platform_api_key(
&self.registry,
OTHER_AGENT_SLUG,
"mcp-completion-other",
&[PlatformApiKeyScope::Read],
)
.await
}
}
pub(super) async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body)
.unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {status} {body:?}: {error}"))
}
async fn create_published_prompt(
registry: &PostgresRegistry,
prompt_id: &PromptId,
definition: PromptDefinition,
) {
let created_at = 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")
.updated_at;
registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: test_workspace_id(),
prompt_id: prompt_id.clone(),
expected_updated_at: created_at,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("the Prompt publishes as an immutable version");
}
/// One published Read Operation with an enumerated `region` path parameter, the exact target the
/// bound template declares.
async fn publish_region_operation(registry: &PostgresRegistry, name: &str) {
let mut operation = test_operation("http://127.0.0.1:9", name);
operation.id = crank_core::OperationId::new(format!("op_{name}"));
operation.display_name = "Region lookup".to_owned();
operation.target = Target::Rest(RestTarget {
base_url: "http://127.0.0.1:9".to_owned(),
method: HttpMethod::Get,
path_template: "/regions/{region}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("region");
operation
.input_schema
.fields
.get_mut("region")
.unwrap()
.enum_values = vec!["eu".to_owned(), "us".to_owned(), "apac".to_owned()];
operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.region".to_owned(),
target: "$.request.path.region".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("the Read Operation is created through the registry API");
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
.expect("the Read Operation exact version publishes");
}
/// One published Resource template with an enumerated `region` parameter.
async fn publish_template(
registry: &PostgresRegistry,
resource_id: &ResourceId,
uri_template: &str,
operation_name: &str,
) {
let definition = json!({
"operation_id": format!("op_{operation_name}"),
"operation_version": 1,
"uri_template": uri_template,
"parameters": [{
"name": "region",
"input_path": "input.region",
"schema": {
"type": "string",
"required": true,
"enum_values": ["eu", "us", "apac"]
}
}],
"cache": {"ttl_ms": 60_000, "vary": ["region"], "max_bytes": 65_536},
"failure": {"outcome": "error"}
});
let source = TemplateSource::parse(&definition)
.expect("the template fixture satisfies the Story 3.10 source contract");
let definition_json =
serde_json::to_string(&source).expect("the normalized definition serializes canonically");
let digest = format!("{:x}", Sha256::digest(definition_json.as_bytes()));
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: format!("crank://templates/{operation_name}"),
name: format!("{operation_name}_template"),
description: "Bound completion fixture template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition_json.clone(),
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("the template Draft is created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("the template exact version publishes");
}
async fn create_agent(registry: &PostgresRegistry, agent_slug: &str) -> AgentId {
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.17 completion 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: &[],
})
.await
.expect("the draft Agent is created");
agent_id
}
async fn bind_snapshot(
registry: &PostgresRegistry,
agent_id: &AgentId,
prompts: &[AgentPromptBinding],
resources: &[AgentResourceBinding],
) {
registry
.save_agent_catalog_config_editable_with_prompts(
SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: resources,
expected_state: None,
},
prompts,
)
.await
.expect("the exact bound snapshot is accepted");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("the bound Agent publishes");
}
/// Publish the whole fixture set and start the real MCP server.
pub(super) async fn completion_endpoint() -> CompletionEndpoint {
let registry = test_registry().await;
let greeting_id = PromptId::new("prm_completion_greeting");
let draft_id = PromptId::new("prm_completion_draft");
let unbound_id = PromptId::new("prm_completion_unbound");
let other_id = PromptId::new("prm_completion_other");
create_published_prompt(&registry, &greeting_id, greeting_definition()).await;
registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: test_workspace_id(),
prompt_id: draft_id,
sensitivity: PromptSensitivity::Internal,
definition: simple_definition("draft-prompt", "Never published", "Draft content."),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("the Draft-only Prompt is created");
create_published_prompt(
&registry,
&unbound_id,
simple_definition(
"unbound-prompt",
"Published, never bound",
"Unbound content.",
),
)
.await;
create_published_prompt(
&registry,
&other_id,
simple_definition(
"other-agent-prompt",
"Bound elsewhere",
"Other agent secret.",
),
)
.await;
publish_region_operation(&registry, "completion_region_lookup").await;
publish_region_operation(&registry, "completion_other_region_lookup").await;
let bound_template = ResourceId::new("res_completion_orders");
publish_template(
&registry,
&bound_template,
BOUND_TEMPLATE_URI,
"completion_region_lookup",
)
.await;
let foreign_template = ResourceId::new("res_completion_other_orders");
publish_template(
&registry,
&foreign_template,
FOREIGN_TEMPLATE_URI,
"completion_other_region_lookup",
)
.await;
let agent_id = create_agent(&registry, AGENT_SLUG).await;
bind_snapshot(
&registry,
&agent_id,
&[AgentPromptBinding {
prompt_id: greeting_id.clone(),
prompt_version: 1,
}],
&[AgentResourceBinding {
resource_id: bound_template,
resource_version: 1,
}],
)
.await;
let other_agent_id = create_agent(&registry, OTHER_AGENT_SLUG).await;
bind_snapshot(
&registry,
&other_agent_id,
&[AgentPromptBinding {
prompt_id: other_id,
prompt_version: 1,
}],
&[AgentResourceBinding {
resource_id: foreign_template,
resource_version: 1,
}],
)
.await;
let api_key = create_platform_api_key(
&registry,
AGENT_SLUG,
"mcp-completion",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
CompletionEndpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
base_url,
api_key,
registry,
}
}
/// The workspace identity the fixture published into.
pub(super) fn workspace_id() -> WorkspaceId {
test_workspace_id()
}
@@ -0,0 +1,116 @@
//! AT-3.17-02: completion identifiers never reach metric labels.
//!
//! The MCP request metric is recorded with a closed `McpMethod` label and the completion service emits
//! only fixed labels, counts and the served revision. This test proves it against a real recorder: the
//! rendered series of a snapshot taken after completion traffic carries no Prompt name, URI template,
//! argument name, suggestion value or Agent slug, and every `method` label value stays inside the
//! fixed enum.
use std::{collections::BTreeSet, time::Duration};
use metrics_util::debugging::DebuggingRecorder;
use serde_json::{Value, json};
use super::fixtures::*;
/// The closed `method` label set of `crank_mcp_requests_total` (crank-metrics `McpMethod`).
const METHOD_LABELS: [&str; 9] = [
"initialize",
"initialized",
"ping",
"tools_list",
"tools_call",
"notification",
"unsupported",
"response",
"invalid",
];
fn request(reference: Value, argument: &str, value: &str) -> Value {
json!({"ref": reference, "argument": {"name": argument, "value": value}})
}
#[tokio::test]
async fn completion_identifiers_never_reach_metric_labels() {
crank_observability::bind_metric_service(crank_observability::MetricService::McpServer)
.expect("explicit MCP service binding before the recorder");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
recorder
.install()
.expect("isolated completion test recorder");
let endpoint = completion_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
for params in [
// A matched published value, a partially matched token and an unavailable reference: the
// three shapes that a naive implementation would be tempted to label with.
request(
json!({"type": "ref/prompt", "name": "greeting"}),
"tone",
"warm",
),
request(
json!({"type": "ref/resource", "uri": BOUND_TEMPLATE_URI}),
"region",
"apac",
),
request(
json!({"type": "ref/prompt", "name": "no-such-prompt"}),
"tone",
"no-such-token",
),
] {
let _ = endpoint.on_revision(revision, params).await;
}
}
tokio::time::sleep(Duration::from_millis(25)).await;
let snapshot = snapshotter.snapshot().into_vec();
assert!(
!snapshot.is_empty(),
"the completion traffic must be observable at all, otherwise this check proves nothing"
);
let rendered = format!("{snapshot:?}");
for forbidden in [
"greeting",
"prm_completion_greeting",
"completion-agent",
"completion-orders",
"no-such-prompt",
"no-such-token",
"warm",
"apac",
"tone",
"region",
] {
assert!(
!rendered.contains(forbidden),
"a completion identifier leaked into metric labels: {forbidden:?}"
);
}
let mut observed_methods = BTreeSet::new();
for (key, _, _, _) in &snapshot {
if key.key().name() != "crank_mcp_requests_total" {
continue;
}
for label in key.key().labels() {
if label.key() == "method" {
observed_methods.insert(label.value().to_owned());
}
}
}
assert!(
!observed_methods.is_empty(),
"the completion requests must produce `crank_mcp_requests_total` series"
);
for method in &observed_methods {
assert!(
METHOD_LABELS.contains(&method.as_str()),
"the `method` label must stay inside the fixed taxonomy, got {method:?} \
from {observed_methods:?}"
);
}
}
@@ -0,0 +1,56 @@
//! Story 3.14 pre-build acceptance tests: discover and render the bound Published Prompts through
//! MCP (AT-3.14-01..04).
//!
//! Oracles: `docs/acceptance-test-plan.md` AT-3.14-01..04 and `_bmad-output/.../epics-source.md`
//! Story 3.14. Every request travels through the real HTTP endpoint built by `build_test_app` against
//! a real PostgreSQL registry; the bound versions are produced through the production registry path.
mod composition;
mod fixtures;
mod get;
mod latency;
mod list;
use serde_json::json;
use fixtures::*;
/// AT-3.14-04: the advertised capability equals the implemented surface on both revisions.
#[tokio::test]
async fn advertisement_declares_prompts_on_both_revisions() {
let endpoint = prompt_endpoint().await;
let discover = endpoint.modern("server/discover", json!({}), None).await;
assert_eq!(
discover["result"]["capabilities"]["prompts"],
json!({"listChanged": false}),
"the modern advertisement must declare the prompts capability: {discover}"
);
let initialize_response = endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.json(&json!({
"jsonrpc": "2.0",
"id": 11,
"method": "initialize",
"params": {"protocolVersion": LEGACY_REVISION, "capabilities": {}}
}))
.send()
.await
.unwrap();
let initialize = json_body(initialize_response).await;
assert_eq!(
initialize["result"]["capabilities"]["prompts"],
json!({"listChanged": false}),
"the legacy advertisement must declare the prompts capability: {initialize}"
);
}
@@ -0,0 +1,590 @@
//! Story 3.16 / FR-18 на границе MCP `prompts/get`: составной Prompt из опубликованных Resource.
//!
//! Всё идёт production-путём: реальный registry (create/publish Prompt, exact bindings, publish
//! Agent), реальный artifact root для опубликованного Resource и настоящий MCP endpoint.
//!
//! Проверяется:
//! - точный pinned-текст вставляется дословно внутрь объявленного сообщения, роли и число
//! сообщений не меняются (AC4/AC5);
//! - новая опубликованная версия Resource не меняет то, что получает агент (AC8);
//! - недоступная (отозванная) зависимость — структурированный отказ без `messages` (AC6).
use std::{
fs,
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
time::Duration,
};
use crank_artifacts::ArtifactStore;
use crank_core::{
Agent, AgentId, AgentStatus, AgentVersion, HttpMethod, OperationSafetyClass,
OperationSafetyPolicy, PlatformApiKeyScope, RestTarget, Target, ToolSelectionPolicy,
ids::{PromptId, ResourceId},
prompt::{PromptDefinition, PromptSensitivity},
resource::template::TemplateSource,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::{
PostgresRegistry, PublishRequest,
model::{
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
resource::{
CreateResourceDraftRequest, CreateResourceTemplateDraftRequest,
PublishResourceTemplateVersionRequest, PublishResourceVersionRequest,
},
},
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use super::super::common::{
agent_mcp_url, build_test_app_with_artifacts, create_platform_api_key, object_schema,
spawn_mcp_server, test_operation, test_registry, test_workspace_id,
};
use super::fixtures::{
META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION, MODERN_REVISION,
PromptEndpoint,
};
const AGENT_SLUG: &str = "composed-prompts";
const PINNED_V1: &str = "PINNED CHANGELOG v1";
const PINNED_V2: &str = "PINNED CHANGELOG v2";
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
struct TestRoot(PathBuf);
impl TestRoot {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"crank-mcp-prompt-composition-{}-{}",
std::process::id(),
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&path).expect("artifact root must be creatable");
// Тот же контракт приватности, что у production root: 0700.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
.expect("artifact root must be 0700");
}
Self(path)
}
}
impl Drop for TestRoot {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Публикует static Resource через production-путь 3.6/3.7 в реальном artifact root.
async fn publish_resource(
registry: &PostgresRegistry,
store: &ArtifactStore,
resource_id: &str,
bytes: &[u8],
) -> u32 {
let id = ResourceId::new(resource_id);
let artifact = store
.put_registered(bytes)
.expect("fixture bytes are registered durably");
if registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.is_ok()
{
let current = registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.expect("current draft reads");
registry
.update_resource_draft(
crank_registry::model::resource::UpdateResourceDraftRequest {
workspace_id: test_workspace_id(),
resource_id: id.clone(),
description: "next version".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: current.resource.updated_at,
artifact,
},
)
.await
.expect("next draft version is created");
} else {
registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: test_workspace_id(),
resource_id: id.clone(),
uri: format!("crank://resources/{resource_id}"),
name: resource_id.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
artifact,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("resource draft is created");
}
let current = registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.expect("draft reads");
registry
.publish_resource_version(PublishResourceVersionRequest {
workspace_id: test_workspace_id(),
resource_id: id,
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("fixture bytes are registered durably"),
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("resource version publishes")
.version
}
fn composed_definition(resource_id: &str, version: u32) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "release-notes",
"description": "Composed release notes",
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": [0]}
],
"dependencies": [{"resource_id": resource_id, "version": version}]
}))
.expect("composed definition is valid")
}
/// Стенд: опубликованный Resource v1, составной Prompt, exact binding и опубликованный Agent.
///
/// Возвращает endpoint, store и корень артефактов: `ArtifactStore` клонируется в приложение, поэтому
/// последующая публикация новой версии Resource идёт в тот же immutable root.
async fn composed_endpoint() -> (PromptEndpoint, ArtifactStore, TestRoot) {
let root = TestRoot::new();
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
let registry = test_registry().await;
let resource_id = "res_story316_mcp_composed";
let version = publish_resource(&registry, &store, resource_id, PINNED_V1.as_bytes()).await;
let endpoint = bound_prompt_endpoint(
registry,
store.clone(),
PromptId::new("prm_story316_mcp_composed"),
composed_definition(resource_id, version),
)
.await;
(endpoint, store, root)
}
/// Опубликованный Prompt + exact binding в опубликованном Agent и живой MCP endpoint.
async fn bound_prompt_endpoint(
registry: PostgresRegistry,
store: ArtifactStore,
prompt_id: PromptId,
definition: PromptDefinition,
) -> PromptEndpoint {
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("composed 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("composed prompt publishes");
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
let now = OffsetDateTime::now_utc();
registry
.create_agent(crank_registry::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.16 composed Prompt 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: &[],
})
.await
.expect("draft Agent is created");
registry
.save_agent_catalog_config_editable_with_prompts(
crank_registry::model::SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: &[],
expected_state: None,
},
&[AgentPromptBinding {
prompt_id: prompt_id.clone(),
prompt_version: 1,
}],
)
.await
.expect("exact published Prompt binding is accepted");
registry
.publish_agent(crank_registry::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("bound Agent publishes");
let api_key = create_platform_api_key(
&registry,
AGENT_SLUG,
"mcp-prompts-composed",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
store,
))
.await;
PromptEndpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
base_url,
api_key,
registry,
greeting_id: prompt_id,
archived_id: PromptId::new("prm_story316_unused_archived"),
archived_updated_at: now,
}
}
/// Один modern `prompts/get` запрос через тот же adapter, что у остальных Prompt-тестов.
async fn get(endpoint: &PromptEndpoint, channel: &str) -> Value {
let headers = [
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "prompts/get"),
("Mcp-Name", "release-notes"),
];
let params = json!({
"name": "release-notes",
"arguments": {"channel": channel},
"_meta": {
META_PROTOCOL_VERSION: MODERN_REVISION,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: {"name": "crank-prompts-story316", "version": "0.1.0"}
}
});
let response = super::super::common::post_jsonrpc_with_headers(
&endpoint.client,
&agent_mcp_url(&endpoint.base_url, AGENT_SLUG),
&endpoint.api_key,
&headers,
json!({"jsonrpc": "2.0", "id": 7, "method": "prompts/get", "params": params}),
)
.await;
super::fixtures::json_body(response).await
}
fn message_texts(body: &Value) -> Vec<(String, String)> {
body["result"]["messages"]
.as_array()
.unwrap_or_else(|| panic!("prompts/get must carry messages: {body}"))
.iter()
.map(|message| {
(
message["role"].as_str().unwrap_or_default().to_owned(),
message["content"]["text"]
.as_str()
.unwrap_or_default()
.to_owned(),
)
})
.collect()
}
#[tokio::test]
async fn get_inserts_pinned_text_inside_the_declared_message() {
let (endpoint, _store, _root) = composed_endpoint().await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert_eq!(
messages.len(),
2,
"the declared message count is unchanged: {body}"
);
assert_eq!(messages[0].0, "system");
assert_eq!(
messages[0].1, "Summarise only the attached document.",
"the system message never receives document text: {body}"
);
assert_eq!(messages[1].0, "user");
assert_eq!(
messages[1].1,
format!("Channel: ops\n\n{PINNED_V1}"),
"the pinned text is inserted verbatim after the rendered template: {body}"
);
assert!(
body["result"]["messages"][1].get("tool_calls").is_none(),
"content never becomes a tool call: {body}"
);
}
#[tokio::test]
async fn get_keeps_the_pinned_version_after_a_new_resource_version() {
let (endpoint, store, _root) = composed_endpoint().await;
// Новая опубликованная версия того же Resource не переписывает пин.
publish_resource(
&endpoint.registry,
&store,
"res_story316_mcp_composed",
PINNED_V2.as_bytes(),
)
.await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert!(
messages[1].1.contains(PINNED_V1),
"the agent keeps receiving the pinned version: {body}"
);
assert!(
!messages[1].1.contains(PINNED_V2),
"a newer Resource version requires a new Prompt publication: {body}"
);
}
#[tokio::test]
async fn get_unavailable_dependency_is_structured_without_messages() {
let (endpoint, _store, _root) = composed_endpoint().await;
endpoint
.registry
.revoke_resource(crank_registry::model::resource::RevokeResourceRequest {
workspace_id: test_workspace_id(),
resource_id: ResourceId::new("res_story316_mcp_composed"),
actor_user_id: "user_default_owner".to_owned(),
request_id: "story316-mcp".to_owned(),
trace_id: "story316-mcp".to_owned(),
revoked_at: OffsetDateTime::now_utc(),
})
.await
.expect("revocation is the accepted 3.8 path");
let body = get(&endpoint, "ops").await;
assert!(
body.get("result").is_none(),
"no partial prompt is returned: {body}"
);
let message = body["error"]["message"].as_str().unwrap_or_default();
assert!(
message.contains("dependencies[0]"),
"the failure names the declaration position: {body}"
);
assert!(
!serde_json::to_string(&body)
.unwrap_or_default()
.contains(PINNED_V1),
"no dependency content appears in the failure: {body}"
);
}
// ---------------------------------------------------------------------------
// AC6 (§4): dynamic (template) dependency читается runtime 3.11 через prompts/get
// ---------------------------------------------------------------------------
const DYNAMIC_RESOURCE_ID: &str = "res_story316_mcp_dynamic";
const DYNAMIC_DEFAULT_ID: &str = "order-42";
/// Upstream шаблона: `GET /orders/{order_id}` → `{"id": "<order_id>"}`.
async fn spawn_orders_upstream() -> String {
use axum::{Router, extract::Path, routing::get};
let app = Router::new().route(
"/orders/{order_id}",
get(|Path(order_id): Path<String>| async move { axum::Json(json!({ "id": order_id })) }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("upstream must bind a loopback port");
let address = listener.local_addr().expect("upstream address");
tokio::spawn(async move {
axum::serve(listener, app).await.expect("upstream serves");
});
format!("http://{address}")
}
/// Стенд динамической зависимости: опубликованная read Operation, опубликованный template
/// Resource с параметром по умолчанию, составной Prompt и опубликованный Agent.
async fn dynamic_endpoint() -> (PromptEndpoint, TestRoot) {
let root = TestRoot::new();
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
let registry = test_registry().await;
let upstream = spawn_orders_upstream().await;
let mut operation = test_operation(&upstream, "story316_prompt_dynamic");
operation.id = crank_core::OperationId::new("op_story316_prompt_dynamic");
operation.target = Target::Rest(RestTarget {
base_url: upstream,
method: HttpMethod::Get,
path_template: "/orders/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("order_id");
operation.execution_config.timeout_ms = 1_000;
operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.order_id".to_owned(),
target: "$.request.path.order_id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("GET Read operation is created through the registry API");
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
.expect("GET Read operation exact version publishes");
let resource_id = ResourceId::new(DYNAMIC_RESOURCE_ID);
let definition_value = json!({
"operation_id": operation.id.to_string(),
"operation_version": 1,
"uri_template": "crank://orders/{order_id}",
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "default_value": DYNAMIC_DEFAULT_ID }
}],
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
});
let definition = serde_json::to_string(
&TemplateSource::parse(&definition_value).expect("template source is valid"),
)
.expect("normalized definition serializes canonically");
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: "crank://templates/story316-order".to_owned(),
name: "story316_order".to_owned(),
description: "Story 3.16 dynamic dependency".to_owned(),
kind: "json".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition,
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("template Draft is created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("template exact version publishes");
let endpoint = bound_prompt_endpoint(
registry,
store,
PromptId::new("prm_story316_mcp_dynamic"),
composed_definition(DYNAMIC_RESOURCE_ID, 1),
)
.await;
(endpoint, root)
}
/// AT-3.16-06 (§4): `prompts/get` читает «живой» документ через Resource runtime; вывод вставлен
/// дословно внутри объявленного сообщения, роли и число сообщений не меняются.
#[tokio::test]
async fn get_reads_a_dynamic_dependency_through_the_resource_runtime() {
let (endpoint, _root) = dynamic_endpoint().await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert_eq!(
messages.len(),
2,
"a dependency cannot add or remove a declared message: {body}"
);
assert_eq!(messages[0].0, "system");
assert_eq!(
messages[0].1, "Summarise only the attached document.",
"the system message never receives document text: {body}"
);
assert_eq!(messages[1].0, "user");
assert_eq!(
messages[1].1,
format!("Channel: ops\n\n{{\"id\":\"{DYNAMIC_DEFAULT_ID}\"}}"),
"the pinned template output is inserted verbatim after one blank line: {body}"
);
assert!(
body["result"]["messages"][1].get("tool_calls").is_none(),
"content never becomes a tool call: {body}"
);
}
@@ -0,0 +1,502 @@
//! Story 3.14 acceptance fixtures: a real MCP endpoint over a real PostgreSQL registry.
//!
//! Everything here is the production path: `build_test_app` + the real
//! `CommunityMachineCredentialVerifier`, published Prompt versions created through the registry
//! (`create_prompt_draft` → `publish_prompt_draft`), exact bindings written through
//! `save_agent_catalog_config_editable_with_prompts`, and an Agent published with `publish_agent`.
//! No route stub, no fake service, no seeded Prompt rows behind the registry's back.
//!
//! Bounded fixture set (names chosen so the bound snapshot order is explicit):
//! - `prm_a_greeting` — typed arguments (`name` required string, `tone` optional enum with default)
//! and a system + user message;
//! - `prm_b_review` — no arguments;
//! - `prm_c_archived` — bound, published, then archived (AT-3.14-03);
//! - `prm_d_unbound` — published but not bound to the Agent;
//! - `prm_e_draft` — Draft only;
//! - `prm_f_other` — bound to another Agent of the same workspace (scope isolation).
#![allow(dead_code)]
use std::time::Duration;
use crank_core::{
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy,
ids::PromptId,
prompt::{PromptDefinition, PromptSensitivity},
};
use crank_registry::model::{
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
};
use crank_registry::{CreateAgentRequest, PostgresRegistry, PublishAgentRequest};
use serde_json::{Value, json};
use time::OffsetDateTime;
use super::super::common::{
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session,
post_jsonrpc_with_headers, spawn_mcp_server, test_registry, test_workspace_id,
};
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
pub(super) const SALES_AGENT_SLUG: &str = "sales-prompts";
pub(super) const OTHER_AGENT_SLUG: &str = "other-prompts";
/// The exact bound Prompt names of `sales-prompts`, in the deterministic snapshot order
/// (`prompt_id` ascending) the service pages over.
pub(super) const BOUND_PROMPT_NAMES: [&str; 3] = ["greeting", "review", "archived-prompt"];
pub(super) fn greeting_definition(content: &str) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "greeting",
"description": "Greets the customer",
"arguments": [
{"name": "name", "schema": {"type": "string"}, "required": true},
{
"name": "tone",
"schema": {"type": "string", "enum": ["warm", "dry"]},
"required": false,
"default": "warm"
}
],
"messages": [
{"role": "system", "content": "Be brief."},
{"role": "user", "content": content}
]
}))
.expect("greeting definition is valid")
}
fn review_definition() -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "review",
"description": "Reviews a change",
"arguments": [],
"messages": [{"role": "user", "content": "Review the change."}]
}))
.expect("review definition is valid")
}
fn archived_definition() -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "archived-prompt",
"description": "Still bound after archive",
"arguments": [],
"messages": [{"role": "user", "content": "Archived but bound."}]
}))
.expect("archived definition is valid")
}
fn other_definition() -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "other-agent-prompt",
"description": "Bound to another Agent",
"arguments": [],
"messages": [{"role": "user", "content": "Other agent secret."}]
}))
.expect("other definition is valid")
}
fn draft_definition() -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "draft-prompt",
"description": "Never published",
"arguments": [],
"messages": [{"role": "user", "content": "Draft content."}]
}))
.expect("draft definition is valid")
}
pub(super) struct PromptEndpoint {
pub(super) client: reqwest::Client,
pub(super) base_url: String,
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) registry: PostgresRegistry,
pub(super) greeting_id: PromptId,
pub(super) archived_id: PromptId,
pub(super) archived_updated_at: OffsetDateTime,
}
impl PromptEndpoint {
/// One modern `prompts/*` request with the required per-request identity.
pub(super) async fn modern(&self, method: &str, params: Value, name: Option<&str>) -> Value {
self.modern_for(SALES_AGENT_SLUG, &self.api_key, method, params, name)
.await
}
/// The same request for an explicitly chosen Agent route and credential.
pub(super) async fn modern_for(
&self,
agent_slug: &str,
api_key: &str,
method: &str,
params: Value,
name: Option<&str>,
) -> Value {
let headers = match name {
Some(name) => vec![
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", method),
("Mcp-Name", name),
],
None => vec![
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", method),
],
};
let mut params = params;
params["_meta"] = json!({
META_PROTOCOL_VERSION: MODERN_REVISION,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: {"name": "crank-prompts-atdd", "version": "0.1.0"}
});
let response = post_jsonrpc_with_headers(
&self.client,
&agent_mcp_url(&self.base_url, agent_slug),
api_key,
&headers,
json!({"jsonrpc": "2.0", "id": 7, "method": method, "params": params}),
)
.await;
json_body(response).await
}
/// One legacy `prompts/*` request inside the sales Agent's initialized session.
pub(super) async fn legacy(&self, session: &str, method: &str, params: Value) -> Value {
self.legacy_for(SALES_AGENT_SLUG, &self.api_key, session, method, params)
.await
}
/// The legacy era resolves workspace and Agent from the initialized *session*, so an explicit
/// Agent route and credential select the snapshot the request is served from.
pub(super) async fn legacy_for(
&self,
agent_slug: &str,
api_key: &str,
session: &str,
method: &str,
params: Value,
) -> Value {
let response = self
.client
.post(agent_mcp_url(&self.base_url, agent_slug))
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header("MCP-Session-Id", session)
.json(&json!({"jsonrpc": "2.0", "id": 8, "method": method, "params": params}))
.send()
.await
.unwrap();
json_body(response).await
}
pub(super) async fn legacy_session(&self) -> String {
initialize_session(&self.client, &self.mcp_url, &self.api_key).await
}
/// An initialized legacy session of an explicitly chosen Agent (its route and credential).
pub(super) async fn legacy_session_for(&self, agent_slug: &str, api_key: &str) -> String {
initialize_session(
&self.client,
&agent_mcp_url(&self.base_url, agent_slug),
api_key,
)
.await
}
/// One `prompts/*` request on the sales Agent of the explicitly chosen supported revision.
pub(super) async fn on_revision(
&self,
revision: &str,
method: &str,
params: Value,
name: Option<&str>,
) -> Value {
self.on_revision_for(
SALES_AGENT_SLUG,
&self.api_key,
revision,
method,
params,
name,
)
.await
}
/// The same request on an explicitly chosen Agent, revision and credential.
pub(super) async fn on_revision_for(
&self,
agent_slug: &str,
api_key: &str,
revision: &str,
method: &str,
params: Value,
name: Option<&str>,
) -> Value {
match revision {
MODERN_REVISION => {
self.modern_for(agent_slug, api_key, method, params, name)
.await
}
LEGACY_REVISION => {
let session = self.legacy_session_for(agent_slug, api_key).await;
self.legacy_for(agent_slug, api_key, &session, method, params)
.await
}
other => panic!("{other} is not a supported protocol revision"),
}
}
/// A read-only credential of the other Agent of the same workspace.
pub(super) async fn other_agent_key(&self) -> String {
create_platform_api_key(
&self.registry,
OTHER_AGENT_SLUG,
"mcp-prompts-other",
&[crank_core::PlatformApiKeyScope::Read],
)
.await
}
}
pub(super) async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body)
.unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {status} {body:?}: {error}"))
}
async fn create_prompt(
registry: &PostgresRegistry,
prompt_id: &PromptId,
definition: PromptDefinition,
) -> OffsetDateTime {
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("Prompt Draft is created")
.updated_at
}
async fn publish_prompt(
registry: &PostgresRegistry,
prompt_id: &PromptId,
expected_updated_at: OffsetDateTime,
) -> OffsetDateTime {
registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: test_workspace_id(),
prompt_id: prompt_id.clone(),
expected_updated_at,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("prompt publishes as an immutable version")
.updated_at
}
async fn create_agent(registry: &PostgresRegistry, agent_slug: &str) -> AgentId {
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.14 Prompt 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: &[],
})
.await
.expect("draft Agent is created");
agent_id
}
pub(super) async fn bind_prompts(
registry: &PostgresRegistry,
agent_id: &AgentId,
bindings: &[AgentPromptBinding],
) -> Result<u32, crank_registry::RegistryError> {
registry
.save_agent_catalog_config_editable_with_prompts(
SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: &[],
expected_state: None,
},
bindings,
)
.await
}
async fn publish_agent(registry: &PostgresRegistry, agent_id: &AgentId) {
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("bound Agent publishes");
}
/// Publish the whole fixture set and start the real MCP server.
pub(super) async fn prompt_endpoint() -> PromptEndpoint {
let registry = test_registry().await;
let greeting_id = PromptId::new("prm_a_greeting");
let review_id = PromptId::new("prm_b_review");
let archived_id = PromptId::new("prm_c_archived");
let unbound_id = PromptId::new("prm_d_unbound");
let draft_id = PromptId::new("prm_e_draft");
let other_id = PromptId::new("prm_f_other");
let greeting_at = create_prompt(
&registry,
&greeting_id,
greeting_definition("Hello {{name}}"),
)
.await;
publish_prompt(&registry, &greeting_id, greeting_at).await;
let review_at = create_prompt(&registry, &review_id, review_definition()).await;
publish_prompt(&registry, &review_id, review_at).await;
let archived_created = create_prompt(&registry, &archived_id, archived_definition()).await;
let archived_at = publish_prompt(&registry, &archived_id, archived_created).await;
let unbound_at = create_prompt(&registry, &unbound_id, review_definition()).await;
publish_prompt(&registry, &unbound_id, unbound_at).await;
create_prompt(&registry, &draft_id, draft_definition()).await;
let other_at = create_prompt(&registry, &other_id, other_definition()).await;
publish_prompt(&registry, &other_id, other_at).await;
let agent_id = create_agent(&registry, SALES_AGENT_SLUG).await;
bind_prompts(
&registry,
&agent_id,
&[
AgentPromptBinding {
prompt_id: greeting_id.clone(),
prompt_version: 1,
},
AgentPromptBinding {
prompt_id: review_id.clone(),
prompt_version: 1,
},
AgentPromptBinding {
prompt_id: archived_id.clone(),
prompt_version: 1,
},
],
)
.await
.expect("exact published Prompt bindings are accepted");
publish_agent(&registry, &agent_id).await;
// AT-3.14-03: archive *after* the binding is fixed in the published Agent snapshot.
let archived_updated_at = registry
.archive_prompt_draft(ArchivePromptRequest {
workspace_id: test_workspace_id(),
prompt_id: archived_id.clone(),
expected_updated_at: archived_at,
archived_at: OffsetDateTime::now_utc(),
})
.await
.expect("the bound Prompt is archived after the snapshot")
.updated_at;
let other_agent_id = create_agent(&registry, OTHER_AGENT_SLUG).await;
bind_prompts(
&registry,
&other_agent_id,
&[AgentPromptBinding {
prompt_id: other_id,
prompt_version: 1,
}],
)
.await
.expect("another Agent binds its own Prompt");
publish_agent(&registry, &other_agent_id).await;
let api_key = create_platform_api_key(
&registry,
SALES_AGENT_SLUG,
"mcp-prompts",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
PromptEndpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, SALES_AGENT_SLUG),
base_url,
api_key,
registry,
greeting_id,
archived_id,
archived_updated_at,
}
}
/// Turn a bound greeting Draft edit into a new Draft version (v2) without touching v1.
pub(super) async fn edit_greeting_draft(endpoint: &PromptEndpoint) -> OffsetDateTime {
let draft = endpoint
.registry
.get_prompt_draft(&test_workspace_id(), &endpoint.greeting_id)
.await
.expect("greeting Draft reads");
endpoint
.registry
.update_prompt_draft(UpdatePromptDraftRequest {
workspace_id: test_workspace_id(),
prompt_id: endpoint.greeting_id.clone(),
sensitivity: PromptSensitivity::Internal,
definition: greeting_definition("Changed {{name}}"),
expected_updated_at: draft.updated_at,
updated_at: OffsetDateTime::now_utc(),
})
.await
.expect("editing a published Prompt opens a new Draft")
.updated_at
}
@@ -0,0 +1,348 @@
//! AT-3.14-02 / AT-3.14-03 / AT-3.14-04: `prompts/get` renders one exact bound Published Prompt
//! Version deterministically, rejects every invalid argument before rendering, keeps an archived
//! bound version readable, and never serves another Agent's snapshot. Every case runs on both
//! supported protocol revisions: the legacy era resolves workspace and Agent from the initialized
//! session, so its snapshot selection is proven separately below.
use crank_core::prompt::MAX_TEXT_BYTES;
use crank_registry::RegistryError;
use crank_registry::model::AgentPromptBinding;
use serde_json::{Value, json};
use super::fixtures::*;
fn messages(body: &Value) -> &Vec<Value> {
body["result"]["messages"]
.as_array()
.unwrap_or_else(|| panic!("prompts/get must carry messages: {body}"))
}
fn greeting_messages() -> Vec<Value> {
vec![
json!({"role": "system", "content": {"type": "text", "text": "Be brief."}}),
json!({"role": "user", "content": {"type": "text", "text": "Hello Ada"}}),
]
}
#[tokio::test]
async fn get_renders_typed_arguments_deterministically_on_both_revisions() {
let endpoint = prompt_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let body = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
Some("greeting"),
)
.await;
assert_eq!(
body["result"]["description"],
json!("Greets the customer"),
"the bound description is served on {revision}: {body}"
);
assert_eq!(
messages(&body),
&greeting_messages(),
"the typed renderer output is served unchanged on {revision}: {body}"
);
let repeated = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
Some("greeting"),
)
.await;
assert_eq!(
body, repeated,
"rendering is deterministic on {revision}: {repeated}"
);
// The rendered enum/default argument path is accepted too.
let with_tone = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "greeting", "arguments": {"name": "Ada", "tone": "dry"}}),
Some("greeting"),
)
.await;
assert_eq!(
messages(&with_tone)[1]["content"],
json!({"type": "text", "text": "Hello Ada"}),
"an explicit enum value still renders the bound template on {revision}: {with_tone}"
);
}
}
#[tokio::test]
async fn get_rejects_each_invalid_argument_before_rendering_without_disclosure() {
let endpoint = prompt_endpoint().await;
let oversized = "x".repeat(MAX_TEXT_BYTES + 1);
for revision in [MODERN_REVISION, LEGACY_REVISION] {
for (arguments, reason, argument) in [
(json!({}), "missing_argument", "name"),
(
json!({"name": "Ada", "extra": "x"}),
"unknown_argument",
"extra",
),
(json!({"name": 5}), "argument_invalid", "name"),
(
json!({"name": "Ada", "tone": "loud"}),
"argument_invalid",
"tone",
),
(json!({"name": oversized}), "argument_too_large", "name"),
] {
let body = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "greeting", "arguments": arguments}),
Some("greeting"),
)
.await;
assert_eq!(
body["error"]["code"],
json!(-32602),
"{reason} on {revision}: a typed argument rejection is invalid params: {body}"
);
assert_eq!(
body["error"]["data"]["reason"],
json!(reason),
"{reason} on {revision}: {body}"
);
assert_eq!(
body["error"]["data"]["argument"],
json!(argument),
"{reason} on {revision}: {body}"
);
// No partial rendering and no foreign metadata: neither bound content nor any prompt
// message may appear anywhere in the error envelope.
let serialized = body.to_string();
for leaked in [
"Be brief.",
"Hello ",
"Archived but bound.",
"Draft content.",
] {
assert!(
!serialized.contains(leaked),
"{reason} on {revision}: the rejection must not disclose {leaked:?}: {serialized}"
);
}
assert!(
body.get("result").is_none(),
"{reason} on {revision}: a rejected request carries no result: {body}"
);
}
}
}
#[tokio::test]
async fn get_serves_the_archived_bound_version_and_archive_blocks_new_bindings() {
let endpoint = prompt_endpoint().await;
// AT-3.14-03: the immutable snapshot behaviour survives the archive, on every revision.
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let serving = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "archived-prompt"}),
Some("archived-prompt"),
)
.await;
assert_eq!(
messages(&serving),
&vec![
json!({"role": "user", "content": {"type": "text", "text": "Archived but bound."}})
],
"an archived Prompt Version bound before the archive keeps serving on {revision}: {serving}"
);
}
// Archive forbids new bindings: the exact version may not be attached to another Agent.
let other_agent = crank_core::AgentId::new(format!("agent_{OTHER_AGENT_SLUG}"));
let rebind = bind_prompts(
&endpoint.registry,
&other_agent,
&[AgentPromptBinding {
prompt_id: endpoint.archived_id.clone(),
prompt_version: 1,
}],
)
.await;
assert!(
matches!(rebind, Err(RegistryError::PromptArchived { .. })),
"archive must refuse new bindings, got {rebind:?}"
);
// Archive forbids new publications of the same Prompt (archived is terminal lifecycle).
let publication = endpoint
.registry
.publish_prompt_draft(crank_registry::model::PublishPromptRequest {
workspace_id: crank_core::WorkspaceId::new("ws_default"),
prompt_id: endpoint.archived_id.clone(),
expected_updated_at: endpoint.archived_updated_at,
published_at: time::OffsetDateTime::now_utc(),
})
.await;
assert!(
matches!(publication, Err(RegistryError::PromptNotDraft { .. })),
"archive must refuse new publications, got {publication:?}"
);
}
#[tokio::test]
async fn get_of_an_unknown_unbound_or_foreign_prompt_is_indistinguishable() {
let endpoint = prompt_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
for name in [
"draft-prompt",
"other-agent-prompt",
"prm_a_greeting",
"never-existed",
] {
let body = endpoint
.on_revision(revision, "prompts/get", json!({"name": name}), Some(name))
.await;
assert_eq!(
body["error"]["code"],
json!(-32602),
"{name} on {revision}: an unaddressable Prompt is invalid params: {body}"
);
assert_eq!(
body["error"]["message"],
json!("the requested prompt is not available"),
"Draft, unbound, foreign and unknown names share one safe answer on {revision}: {body}"
);
let serialized = body.to_string();
for leaked in ["Other agent secret.", "Draft content.", "Be brief."] {
assert!(
!serialized.contains(leaked),
"{name} on {revision}: leaked {leaked:?}: {serialized}"
);
}
}
}
}
#[tokio::test]
async fn get_serves_the_exact_bound_version_after_a_draft_edit() {
let endpoint = prompt_endpoint().await;
edit_greeting_draft(&endpoint).await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let body = endpoint
.on_revision(
revision,
"prompts/get",
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
Some("greeting"),
)
.await;
assert_eq!(
messages(&body)[1]["content"],
json!({"type": "text", "text": "Hello Ada"}),
"the bound v1 snapshot stays immutable after a Draft edit on {revision}: {body}"
);
let listed = endpoint
.on_revision(revision, "prompts/list", json!({}), None)
.await;
assert_eq!(
listed["result"]["prompts"][0]["description"],
json!("Greets the customer"),
"discovery still describes the bound version, not the new Draft, on {revision}: {listed}"
);
}
}
/// The legacy era takes workspace and Agent from the *initialized session*, not from the request
/// body. A session of the other Agent therefore serves that Agent's snapshot, and a Prompt bound to
/// the sales Agent is indistinguishable from an unknown name on it.
#[tokio::test]
async fn legacy_session_serves_only_its_own_agent_snapshot() {
let endpoint = prompt_endpoint().await;
let other_key = endpoint.other_agent_key().await;
let session = endpoint
.legacy_session_for(OTHER_AGENT_SLUG, &other_key)
.await;
let own = endpoint
.legacy_for(
OTHER_AGENT_SLUG,
&other_key,
&session,
"prompts/get",
json!({"name": "other-agent-prompt"}),
)
.await;
assert_eq!(
messages(&own),
&vec![json!({"role": "user", "content": {"type": "text", "text": "Other agent secret."}})],
"the session's own bound snapshot is served: {own}"
);
let listed = endpoint
.legacy_for(
OTHER_AGENT_SLUG,
&other_key,
&session,
"prompts/list",
json!({}),
)
.await;
assert_eq!(
listed["result"]["prompts"]
.as_array()
.expect("the session lists its own prompts")
.iter()
.map(|prompt| prompt["name"].as_str().unwrap_or_default().to_owned())
.collect::<Vec<String>>(),
vec!["other-agent-prompt"],
"the legacy session lists only its own bound Prompt: {listed}"
);
// Every Prompt bound to the sales Agent is foreign to this session.
for name in ["greeting", "review", "archived-prompt"] {
let body = endpoint
.legacy_for(
OTHER_AGENT_SLUG,
&other_key,
&session,
"prompts/get",
json!({"name": name}),
)
.await;
assert_eq!(
body["error"]["code"],
json!(-32602),
"{name}: a foreign bound Prompt is invalid params on the legacy era: {body}"
);
assert_eq!(
body["error"]["message"],
json!("the requested prompt is not available"),
"{name}: a foreign bound Prompt shares the safe answer: {body}"
);
assert!(
body.get("result").is_none(),
"{name}: a foreign bound Prompt carries no result: {body}"
);
let serialized = body.to_string();
for leaked in ["Be brief.", "Hello ", "Archived but bound."] {
assert!(
!serialized.contains(leaked),
"{name}: the foreign rejection must not disclose {leaked:?}: {serialized}"
);
}
}
}
@@ -0,0 +1,75 @@
//! AT-3.14-04: the accepted discovery budget (≤150 ms p95) measured on the real endpoint.
//!
//! The measurement is a real one: sequential HTTP `prompts/list` requests against the task-owned
//! loopback MCP server, the real PostgreSQL registry and the fixture's three bound Published Prompt
//! Versions in a debug build. It is recorded as evidence with workload/revision/environment/sample
//! count instead of being replaced by an assertion about speed. A future release benchmark is not
//! part of this story.
use std::time::{Duration, Instant};
use serde_json::json;
use super::fixtures::*;
const SAMPLES: usize = 30;
const WARMUP: usize = 3;
const BUDGET: Duration = Duration::from_millis(150);
fn percentile(sorted: &[Duration], percentile: f64) -> Duration {
let rank = ((percentile / 100.0) * sorted.len() as f64).ceil() as usize;
sorted[rank.saturating_sub(1).min(sorted.len() - 1)]
}
#[tokio::test]
async fn prompts_list_discovery_p95_stays_within_the_accepted_budget() {
let endpoint = prompt_endpoint().await;
for _ in 0..WARMUP {
let body = endpoint.modern("prompts/list", json!({}), None).await;
assert!(
body["result"].is_object(),
"warmup list must succeed: {body}"
);
}
let mut samples = Vec::with_capacity(SAMPLES);
for _ in 0..SAMPLES {
let started = Instant::now();
let body = endpoint.modern("prompts/list", json!({}), None).await;
samples.push(started.elapsed());
assert!(
body["result"]["prompts"].is_array(),
"every measured list must serve the bound page: {body}"
);
}
samples.sort_unstable();
let p50 = percentile(&samples, 50.0);
let p95 = percentile(&samples, 95.0);
let max = *samples.last().unwrap();
let report = json!({
"case": "AT-3.14-04",
"surface": "prompts/list",
"revision": MODERN_REVISION,
"workload": "one bound Published Prompt snapshot of 3 versions (typed arguments), no pagination",
"environment": "debug build, task-owned loopback MCP server, PostgreSQL test container, 4 vCPU",
"samples": SAMPLES,
"warmup_samples": WARMUP,
"p50_ms": p50.as_secs_f64() * 1_000.0,
"p95_ms": p95.as_secs_f64() * 1_000.0,
"max_ms": max.as_secs_f64() * 1_000.0,
"budget_ms": BUDGET.as_millis(),
});
println!("AT-3.14-04 discovery latency evidence: {report}");
if let Ok(path) = std::env::var("CRANK_PROMPTS_P95_REPORT") {
std::fs::write(&path, serde_json::to_vec_pretty(&report).unwrap())
.unwrap_or_else(|error| panic!("latency evidence must be writable at {path}: {error}"));
}
assert!(
p95 <= BUDGET,
"prompts/list discovery p95 {p95:?} must stay within {BUDGET:?} ({report})"
);
}
@@ -0,0 +1,170 @@
//! AT-3.14-01 / AT-3.14-04: `prompts/list` serves exactly the bound Published Prompt Versions with
//! revision-scoped pagination and typed argument metadata; Draft, unbound and foreign Prompts of
//! another Agent are never disclosed. Every case runs on both supported protocol revisions, because
//! AC-4 requires the behaviour to be proven per revision and the legacy era resolves workspace and
//! Agent from the initialized session instead of the request body.
use serde_json::{Value, json};
use super::fixtures::*;
fn names(page: &Value) -> Vec<String> {
page["result"]["prompts"]
.as_array()
.unwrap_or_else(|| panic!("prompts/list must carry a prompts array: {page}"))
.iter()
.map(|prompt| prompt["name"].as_str().unwrap_or_default().to_owned())
.collect()
}
#[tokio::test]
async fn list_serves_only_bound_published_prompts_with_typed_arguments() {
let endpoint = prompt_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let body = endpoint
.on_revision(revision, "prompts/list", json!({}), None)
.await;
assert!(
body.get("error").is_none(),
"prompts/list must succeed on {revision}: {body}"
);
let listed = names(&body);
assert_eq!(
listed, BOUND_PROMPT_NAMES,
"only the bound Published Prompt Versions may be listed on {revision}: {body}"
);
for excluded in ["draft-prompt", "other-agent-prompt"] {
assert!(
!listed.contains(&excluded.to_owned()),
"{excluded} must not be discoverable on {revision}: {body}"
);
}
let greeting = body["result"]["prompts"]
.as_array()
.unwrap()
.iter()
.find(|prompt| prompt["name"] == json!("greeting"))
.expect("the bound greeting is listed");
assert_eq!(greeting["description"], json!("Greets the customer"));
let arguments = greeting["arguments"]
.as_array()
.expect("the listed Prompt must carry argument metadata");
assert_eq!(
arguments.len(),
2,
"both arguments are advertised on {revision}: {greeting}"
);
assert_eq!(arguments[0]["name"], json!("name"));
assert_eq!(arguments[0]["required"], json!(true));
assert_eq!(arguments[0]["schema"]["type"], json!("string"));
assert_eq!(arguments[1]["name"], json!("tone"));
assert_eq!(arguments[1]["required"], json!(false));
assert_eq!(arguments[1]["schema"]["enum"], json!(["warm", "dry"]));
assert_eq!(arguments[1]["default"], json!("warm"));
assert!(
greeting.get("messages").is_none(),
"discovery must not disclose message content on {revision}: {greeting}"
);
}
}
#[tokio::test]
async fn list_paginates_deterministically_and_binds_the_cursor_to_the_revision() {
let endpoint = prompt_endpoint().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let first = endpoint
.on_revision(revision, "prompts/list", json!({"limit": 2}), None)
.await;
let cursor = first["result"]["nextCursor"]
.as_str()
.unwrap_or_else(|| {
panic!("a bounded first page must carry a continuation on {revision}: {first}")
})
.to_owned();
assert_eq!(
names(&first),
vec!["greeting", "review"],
"the first page is deterministic on {revision}: {first}"
);
let second = endpoint
.on_revision(
revision,
"prompts/list",
json!({"cursor": cursor.clone(), "limit": 2}),
None,
)
.await;
assert_eq!(
names(&second),
vec!["archived-prompt"],
"the continuation serves the next bound slice and nothing else on {revision}: {second}"
);
assert!(
second["result"].get("nextCursor").is_none(),
"the last page carries no continuation on {revision}: {second}"
);
// A page is never mixed across protocol revisions: the other era refuses this cursor.
let other_revision = match revision {
MODERN_REVISION => LEGACY_REVISION,
_ => MODERN_REVISION,
};
let cross_revision = endpoint
.on_revision(
other_revision,
"prompts/list",
json!({"cursor": cursor.clone()}),
None,
)
.await;
assert_eq!(
cross_revision["error"]["code"],
json!(-32602),
"a {revision} cursor must be refused as invalid params on {other_revision}: {cross_revision}"
);
// A malformed token is invalid params, never the first page.
let malformed = endpoint
.on_revision(
revision,
"prompts/list",
json!({"cursor": "not-a-cursor"}),
None,
)
.await;
assert_eq!(
malformed["error"]["code"],
json!(-32602),
"a malformed cursor is invalid params on {revision}: {malformed}"
);
}
}
#[tokio::test]
async fn list_of_an_agent_shows_only_its_own_bound_snapshot() {
let endpoint = prompt_endpoint().await;
// The other Agent binds exactly one Prompt; it must not see the sales Agent's snapshot.
let other_key = endpoint.other_agent_key().await;
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let body = endpoint
.on_revision_for(
OTHER_AGENT_SLUG,
&other_key,
revision,
"prompts/list",
json!({}),
None,
)
.await;
assert_eq!(
names(&body),
vec!["other-agent-prompt"],
"an Agent sees only its own bound snapshot on {revision}: {body}"
);
}
}
@@ -0,0 +1,22 @@
#![allow(dead_code, unused_imports)]
//! Story 3.1 acceptance tests (red phase): MCP revision negotiation on the real endpoint.
//!
//! Oracles: `tests/fixtures/mcp-revisions/wire-identity-cases.json` (case ids `wm-*`, each mapped to a
//! row of the binding precedence table in `protocol-era-matrix.md`) and
//! `supported-revisions.json`. Every request travels through the real HTTP endpoint built by
//! `build_app`; nothing here is backed by a fake implementation.
// Story 3.6 (kanban t_987bf309): the module file is navigation only. The 96 tests and their helpers
// moved verbatim into thematic submodules grouped by observable contract; `review8_identity` keeps its
// own file. Bodies, literals, assertions and timeouts are unchanged - only the module prefix.
mod duplicate_carriers;
mod envelope;
mod harness;
mod method_name;
mod negotiation;
mod result_shapes;
mod review8_identity;
mod session_guards;
mod tools_call;
@@ -0,0 +1,619 @@
//! Duplicate-carrier hygiene: conflicting/identical duplicate protocol-version headers, duplicate
//! `Mcp-Name`/method carriers and duplicate session carriers, with the era-correct diagnostic.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
//!
//! Split out of the accepted `carriers` group as the plan's documented alternative: the merged file
//! measured 1018 body lines, above the enforced 1000-line health ceiling.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, DuplicateSessionCarrierEra, LEGACY_REVISION, MODERN_REVISION,
counted_call_params, counted_tool, duplicated_header, endpoint, modern_post,
modern_request_with_params,
};
/// R12: two conflicting `MCP-Protocol-Version` header lines are an ambiguous identity and must be
/// rejected before dispatch instead of silently using the first value. Our policy (recorded for the
/// accepted matrix): conflicting duplicate identity carriers are rejected; identical duplicates carry
/// no ambiguity and are served.
#[tokio::test]
async fn r12_conflicting_duplicate_protocol_version_headers_are_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(120),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
for order in [
[MODERN_REVISION, LEGACY_REVISION],
[LEGACY_REVISION, MODERN_REVISION],
] {
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.headers(duplicated_header("mcp-protocol-version", order))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
400,
"conflicting duplicate version headers ({order:?}) must be rejected, not resolved by order"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream"
);
}
#[tokio::test]
async fn r12_identical_duplicate_protocol_version_headers_are_served() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(121),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.headers(duplicated_header(
"mcp-protocol-version",
[MODERN_REVISION, MODERN_REVISION],
))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"identical duplicate version headers carry no ambiguity"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 1);
}
/// Assert the era-correct structured diagnostic for a single-fault version-carrier rejection.
///
/// Every R28 probe sends a request whose **only** fault is the `MCP-Protocol-Version` carrier: the body
/// carries the complete modern `_meta` identity, the JSON-RPC id and the `Mcp-Method`/`Mcp-Name` headers
/// are valid, and the upstream counter is asserted by each probe. `protocol-era-matrix.md` row 17 requires
/// the era-correct structured error for every malformed carrier (modern shape: `-32020`), and the modern
/// rows 2/5/6 require the same JSON-RPC id plus the `error.data` correlation proven by R6.
///
/// Defect this oracle pins: `resolve_request_identity`
/// (`crates/crank-community-mcp/src/protocol/mod.rs` 511-519) turns both an unreadable/ambiguous header
/// (`Err(status)` from `singleton_header`) and a blank header value into a **bare** `400` with an empty
/// body, so the required JSON-RPC diagnostic is missing on both members of that branch.
fn assert_carrier_rejection_is_structured(
status: u16,
raw: &str,
id: i64,
correlation: &str,
case: &str,
) {
assert_eq!(
status, 400,
"{case}: a malformed carrier must be a safe rejection"
);
assert!(
!raw.trim().is_empty(),
"{case}: matrix row 17 requires the era-correct structured error for a malformed carrier, but \
the response body was empty"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!("{case}: the carrier diagnostic must be JSON-RPC, got {raw:?}: {error}")
});
assert_eq!(
body["jsonrpc"], "2.0",
"{case}: the carrier diagnostic must be a complete JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(id),
"{case}: the carrier diagnostic must keep the JSON-RPC request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{case}: matrix row 17 requires the era-correct structured error (modern shape: -32020), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{case}: the structured error must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{case}: the carrier diagnostic must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{case}: a rejected request must not carry a `result` key at all, got {body}"
);
assert!(
body["result"].is_null(),
"{case}: a rejected request must not carry a result, got {body}"
);
}
/// R28 probe A: a `MCP-Protocol-Version` value the era resolver rejects on its own — empty,
/// whitespace-only or unparsable. Single fault: the carrier value.
async fn assert_modern_carrier_value_is_a_structured_mismatch(value: &str, correlation: &str) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![
("MCP-Protocol-Version", value.to_owned()),
("Mcp-Method", "tools/call".to_owned()),
("Mcp-Name", COUNTED_TOOL_NAME.to_owned()),
];
let message = modern_request_with_params(
Some(130),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, Some(correlation)).await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
130,
correlation,
&format!("version carrier {value:?} ({correlation})"),
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an identity diagnostic must not reach the upstream"
);
}
/// R28: an **empty** `MCP-Protocol-Version` value on an otherwise valid modern request.
#[tokio::test]
async fn r28_modern_empty_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch("", "r28-empty-carrier").await;
}
/// R28: a **whitespace-only** version value is the same single-fault class as the empty one.
#[tokio::test]
async fn r28_modern_whitespace_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch(" ", "r28-whitespace-carrier").await;
}
/// R28: an **unparsable** (non-blank) version value. Same row-17 obligation as the blank value, but this
/// one is already resolved by the header/body mismatch branch (`protocol/mod.rs` 543-550), so it is
/// expected **existing GREEN**: it separates the bare-`400` defect from the well-formed-value paths and
/// pins that a malformed carrier must not be answered as `-32022` or as an unknown revision.
#[tokio::test]
async fn r28_modern_malformed_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch("not-a-version", "r28-malformed-carrier")
.await;
}
/// R28 probe B: two **conflicting** `MCP-Protocol-Version` carriers in one request whose body carries a
/// valid modern identity. The pair cannot be resolved to one era, so `protocol-era-matrix.md` row 17
/// (era-correct structured error) applies to the same `Err(status)` branch as the unreadable value. The
/// duplicate policy itself ("identical duplicates are served") is the accepted R12 record; the matrix has
/// no separate duplicate row and the existing R12 test asserts only the status, so the diagnostic shape is
/// pinned here. Single fault: the ambiguity of the carrier, one order at a time.
async fn assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
order: [&'static str; 2],
correlation: &str,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(131),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-protocol-version", order))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
131,
correlation,
&format!("conflicting carriers {order:?}"),
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream"
);
}
/// R28: the modern value first, the legacy value second.
#[tokio::test]
async fn r28_modern_conflicting_duplicate_protocol_headers_modern_first_are_a_structured_mismatch()
{
assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
[MODERN_REVISION, LEGACY_REVISION],
"r28-duplicate-modern-first",
)
.await;
}
/// R28: the same conflicting pair in the opposite order — the rejection must not depend on header order.
#[tokio::test]
async fn r28_modern_conflicting_duplicate_protocol_headers_legacy_first_are_a_structured_mismatch()
{
assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
[LEGACY_REVISION, MODERN_REVISION],
"r28-duplicate-legacy-first",
)
.await;
}
/// R28 probe C: an **unreadable** carrier value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field
/// value, so a non-UTF-8 byte sequence is a real, transferable value that reaches the server and fails
/// `HeaderValue::to_str()` inside `singleton_header` (`transport.rs` 185-190) — the second member of the
/// `Err(status)` branch. Single fault: the carrier value only.
#[tokio::test]
async fn r28_modern_unreadable_protocol_version_header_is_a_structured_mismatch() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(132),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let mut carrier = reqwest::header::HeaderMap::new();
carrier.append(
reqwest::header::HeaderName::from_static("mcp-protocol-version"),
reqwest::header::HeaderValue::from_bytes(&[b'2', 0x30, 0x32, 0x36, 0xf8, 0xfe]).unwrap(),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", "r28-unreadable-carrier")
.headers(carrier)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
132,
"r28-unreadable-carrier",
"unreadable version carrier",
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an identity diagnostic must not reach the upstream"
);
}
/// R12 (session carrier half): two conflicting session identifiers are the same ambiguity class and
/// must be rejected instead of resolving to the first value.
#[tokio::test]
async fn r12_conflicting_duplicate_session_headers_are_rejected() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let message = json!({ "jsonrpc": "2.0", "id": 122, "method": "tools/list", "params": {} });
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.headers(duplicated_header(
"mcp-session-id",
[session.as_str(), "session-that-never-existed"],
))
.header("MCP-Protocol-Version", LEGACY_REVISION)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
400,
"conflicting duplicate session identifiers must be rejected"
);
}
/// Review pass 6 (P3 / matrix rows 16-17): conflicting duplicate `MCP-Session-Id` carriers are
/// rejected in `mcp_post_response` (`app.rs` 820-823) through `transport.rs::singleton_header` with
/// a **bare** `400` and an empty body, before era resolution, envelope validation, rate limiting and
/// any dispatch.
///
/// Row 17 requires the era-correct structured diagnostic for an ambiguous carrier, and the era must
/// be read from the rest of the request, never guessed from the ambiguous value. The duplicate
/// *version*-carrier case already does exactly that
/// (`protocol/mod.rs::malformed_carrier_response` 441-448); this oracle pins the same contract for
/// the session carrier: modern shape → `400` + `-32020` with the request id and correlation, legacy
/// shape → a numeric legacy error that is neither `-32020` nor `-32022`. `GET`/`DELETE` keep their
/// separate lifecycle admission and are deliberately untouched.
async fn assert_duplicate_session_carrier_rejection(
session_values: [&str; 2],
correlation: &str,
id: i64,
era: DuplicateSessionCarrierEra,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let mut request = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-session-id", session_values));
let message = match era {
DuplicateSessionCarrierEra::Modern => {
request = request
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME);
modern_request_with_params(
Some(id as u64),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
)
}
DuplicateSessionCarrierEra::Legacy => {
request = request.header("MCP-Protocol-Version", LEGACY_REVISION);
json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": counted_call_params(COUNTED_TOOL_NAME)
})
}
};
let response = request.json(&message).send().await.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an ambiguous session carrier must be a safe rejection ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"row 17 requires the era-correct structured diagnostic for an ambiguous session carrier \
({correlation}), but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the ambiguous-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the ambiguous-session diagnostic must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
json!(id),
"the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}"
);
match era {
DuplicateSessionCarrierEra::Modern => assert_eq!(
body["error"]["code"],
json!(-32020),
"a request whose dominant identity is modern answers the modern shape ({correlation}), \
got {body}"
),
DuplicateSessionCarrierEra::Legacy => {
assert!(
body["error"]["code"].is_i64(),
"the legacy shape must carry a numeric code ({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be guessed for a legacy-shaped ambiguity \
({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersion code must not be guessed for a legacy-shaped \
ambiguity ({correlation}), got {body}"
);
}
}
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream ({correlation})"
);
}
/// Review pass 6 (P3): the modern request, first header value order.
#[tokio::test]
async fn review6_p3_modern_duplicate_session_carrier_first_order_is_structured() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-a", "review6-p3-session-b"],
"review6-p3-modern-a-first",
141,
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 6 (P3): the modern request, reversed header value order — the outcome must not depend
/// on which of the two conflicting values comes first.
#[tokio::test]
async fn review6_p3_modern_duplicate_session_carrier_second_order_is_structured() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-b", "review6-p3-session-a"],
"review6-p3-modern-b-first",
142,
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 6 (P3): the legacy-shaped request, first header value order.
#[tokio::test]
async fn review6_p3_legacy_duplicate_session_carrier_first_order_is_legacy_shaped() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-a", "review6-p3-session-b"],
"review6-p3-legacy-a-first",
143,
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 6 (P3): the legacy-shaped request, reversed header value order.
#[tokio::test]
async fn review6_p3_legacy_duplicate_session_carrier_second_order_is_legacy_shaped() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-b", "review6-p3-session-a"],
"review6-p3-legacy-b-first",
144,
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
@@ -0,0 +1,757 @@
//! JSON-RPC envelope validity: notifications versus requests, invalid/missing envelope fields,
//! request-id correlation of errors and duplicate `mcp method`/`mcp name` carriers.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO,
MODERN_REVISION, UNKNOWN_REVISION, approved_revisions, counted_call_params, counted_tool,
duplicated_header, endpoint, json_body, modern_call_headers, modern_headers, modern_meta,
modern_post, modern_request_with_params, pending_approvals,
};
/// Review pass 6 (P1 / matrix row 4): modern-specific request metadata without **any** version
/// carrier must be rejected as a header-validation failure instead of being admitted as legacy.
///
/// Defect this oracle pins: `resolve_request_identity` (`protocol/mod.rs` 568-642) reads only the
/// `_meta` version field and the `MCP-Protocol-Version` header. A request whose `_meta` carries the
/// modern-specific `clientCapabilities`/`clientInfo` keys but no version at all yields an effective
/// identity of `None`, so it is admitted as `Legacy` (`638-641`) and a **live initialized legacy
/// session** executes it as a legacy `tools/call`. Row 4 requires a rejection before any adapter
/// admission; the modern era defines a header-validation failure as `400` + `-32020`
/// `HeaderMismatch`, the same shape this resolver already emits for a modern identity with a missing
/// version header (`648-653`) and for a missing `_meta` version (`492-497`).
///
/// The probe is repeated once so row 21 (a repeated request has the same outcome and leaves no
/// residual state) is asserted observably, and the counted upstream proves that no legacy outbound
/// call happened.
#[tokio::test]
async fn review6_p1_modern_metadata_without_version_carrier_is_rejected_before_legacy_admission() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let headers = vec![("MCP-Session-Id", session.clone())];
let message = modern_request_with_params(
Some(140),
"tools/call",
json!({
"name": COUNTED_TOOL_NAME,
"arguments": { "email": "review6-p1@example.com" },
"_meta": {
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-client", "version": "0.1.0" }
}
}),
);
for attempt in 1..=2 {
let response = modern_post(
&fixture.endpoint,
&headers,
message.clone(),
Some("review6-p1"),
)
.await;
let status = response.status().as_u16();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"attempt {attempt}: a rejected request must not mint a session"
);
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"attempt {attempt}: modern `_meta` without a version carrier must be rejected before \
legacy admission (matrix row 4), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"attempt {attempt}: row 4 requires a structured rejection, but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"attempt {attempt}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"attempt {attempt}: the rejection must be a JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(140),
"attempt {attempt}: the rejection must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"attempt {attempt}: a modern identity without its required version carrier is a \
header-validation failure (matrix row 4), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"attempt {attempt}: the rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!("review6-p1"),
"attempt {attempt}: the rejection must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"attempt {attempt}: a rejected request must not carry a result, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"modern-specific metadata without a version carrier must not be executed as a legacy request"
);
// Review pass 7 (G3, matrix row 21 valid follow-up): after the repeated rejection the same live
// initialized legacy session must still serve a valid legacy request. This is the narrow
// valid-follow-up half of row 21 — it is not a session-store dump or a full persisted-state
// equality oracle, and it claims no more than "the rejected requests left the session usable".
let follow_up = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 141,
"method": "tools/call",
"params": {
"name": COUNTED_TOOL_NAME,
"arguments": { "email": "review7-p1-follow-up@example.com" }
}
}),
)
.await;
assert!(
follow_up["error"].is_null(),
"a valid legacy follow-up on the same live session must be served, got {follow_up}"
);
assert_eq!(
follow_up["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the valid follow-up must return the published business payload, got {follow_up}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"the valid follow-up must perform exactly one additional outbound call"
);
}
/// R5/R15: a valid modern notification (no `id`) must be acknowledged with exactly `202` and an empty
/// body — not a JSON-RPC result and not an error envelope. Invalid envelopes (e.g. a foreign `id`) are
/// R10's business and are covered separately.
#[tokio::test]
async fn r5_modern_notification_is_not_executed_as_request() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(None, "tools/list", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a valid notification is acknowledged with 202"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
}
/// R6: era errors must keep the existing request correlation data.
///
/// Single fault: the unknown revision is carried identically in the header and in the body `_meta`,
/// while the remaining metadata (`clientCapabilities`, `clientInfo`) and `Mcp-Method` stay valid, so the
/// only defect in play is the unsupported revision itself (`-32022`, not a mismatch).
#[tokio::test]
async fn r6_error_data_preserves_request_correlation() {
let endpoint = endpoint().await;
let headers = modern_headers(UNKNOWN_REVISION, "tools/list");
let message = modern_request_with_params(
Some(70),
"tools/list",
json!({ "_meta": modern_meta(UNKNOWN_REVISION) }),
);
let response = modern_post(&endpoint, &headers, message, Some("r6-correlation-check")).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"],
json!(-32022),
"an identically unknown header/body revision is an unsupported-version error, got {body}"
);
let data = &body["error"]["data"];
assert_eq!(
data["requested"],
json!(UNKNOWN_REVISION),
"the requested revision must be reported, got {body}"
);
let mut supported: Vec<String> = data["supported"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"the supported list must survive alongside the correlation, got {body}"
);
assert_eq!(
data["request_id"],
json!("r6-correlation-check"),
"the unsupported-version error must keep the request correlation, got {body}"
);
}
#[tokio::test]
async fn r6_mismatch_error_data_preserves_request_correlation() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(
Some(71),
"tools/list",
json!({ "_meta": modern_meta(LEGACY_REVISION) }),
);
let response = modern_post(&endpoint, &headers, message, Some("r6-mismatch-check")).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
let data = &body["error"]["data"];
assert_eq!(
data["request_id"],
json!("r6-mismatch-check"),
"the mismatch error must keep the request correlation, got {body}"
);
assert!(
data["details"].is_string(),
"the mismatch detail must survive alongside the correlation, got {body}"
);
}
/// R5/R15: a mutating notification (no `id`) must be acknowledged with exactly `202` and an empty body,
/// must not be dispatched and must not reach the upstream.
#[tokio::test]
async fn r5_modern_mutating_notification_is_not_dispatched_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message =
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME));
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a mutating notification is acknowledged with 202"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a mutating notification must not perform the outbound request"
);
}
/// R10: a modern request must be a well-formed JSON-RPC request before any tool dispatch. The pinned
/// modern schema types the request `id` as `string | number` (`RequestId`), so a missing or foreign
/// `jsonrpc` field and an object/boolean `id` are invalid requests — the JSON syntax being extractable
/// says nothing about the envelope.
#[tokio::test]
async fn r10_modern_missing_jsonrpc_field_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(110),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message.as_object_mut().unwrap().remove("jsonrpc");
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a message without the `jsonrpc` field is not a valid JSON-RPC request"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
body["id"].is_null(),
"an undeterminable request id must be reported as null, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not reach the upstream"
);
}
#[tokio::test]
async fn r10_modern_wrong_jsonrpc_version_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(111),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["jsonrpc"] = json!("1.0");
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0, "got {body}");
}
#[tokio::test]
async fn r10_modern_non_scalar_request_id_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
for foreign_id in [json!({}), json!(true), json!([1, 2])] {
let mut message = modern_request_with_params(
Some(112),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["id"] = foreign_id.clone();
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"the pinned request id is `string | number`, so {foreign_id} is invalid"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
!body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(),
"the response must not echo an arbitrary id value, got {body}"
);
}
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R10 (approval half): an invalid envelope on an approval-gated operation must neither call the
/// upstream nor create a pending approval request.
#[tokio::test]
async fn r10_modern_invalid_envelope_creates_no_pending_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(113),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["jsonrpc"] = json!("1.0");
// R21: the persisted registry state is the proof, not the absence of an id in the response body.
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
!body.to_string().contains("approval_"),
"an invalid envelope must not produce a pending approval, got {body}"
);
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"an invalid envelope must not persist a pending approval request"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not perform the outbound request"
);
}
/// R10 (correlation): an invalid envelope must still answer with the request correlation the ingress
/// already established, and the safe response id must stay null.
#[tokio::test]
async fn r10_invalid_envelope_keeps_request_correlation() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(115),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message.as_object_mut().unwrap().remove("jsonrpc");
let response = modern_post(
&fixture.endpoint,
&headers,
message,
Some("r10-envelope-correlation"),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(
body["error"]["data"]["request_id"],
json!("r10-envelope-correlation"),
"an invalid envelope must keep the ingress correlation, got {body}"
);
assert!(body["id"].is_null(), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R10 (id null): a present but null id is not a valid request id under the pinned `string | number`
/// contract and must never be acknowledged as a notification — no `202`, no dispatch, no outbound.
#[tokio::test]
async fn r10_null_request_id_is_not_a_notification() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(116),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["id"] = Value::Null;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a null id must be an invalid request, not a notification acknowledgement"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not reach the upstream"
);
}
/// R13: a message without `method` and without `Mcp-Method` currently matches `None == None` and is
/// routed to unknown-method dispatch. It is an invalid request and must be rejected as such, not
/// answered as an unknown method with a `-32601` result.
#[tokio::test]
async fn r13_absent_method_with_valid_modern_identity_is_an_invalid_request() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 130,
"params": { "_meta": modern_meta(MODERN_REVISION) }
});
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a message without a method is an invalid request, not an unknown method"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
body["result"].is_null(),
"an invalid request must not be answered with a result, got {body}"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn r13_non_string_method_is_an_invalid_request() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 131,
"method": 42,
"params": { "_meta": modern_meta(MODERN_REVISION) }
});
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R19: matrix row 18 — notifications do not inherit the mandatory request headers. A valid modern
/// notification (no id, valid `_meta`, valid protocol identity) without `Mcp-Method` must be
/// acknowledged with `202` and an empty body, and must not reach the upstream. The request case with a
/// missing method header stays rejected (`r7_modern_missing_mcp_method_is_rejected`).
#[tokio::test]
async fn r19_modern_notification_without_mcp_method_is_acknowledged() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message =
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME));
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a notification does not carry the mandatory request headers"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a notification must not perform the outbound request"
);
}
/// R22: a conflicting duplicate `Mcp-Method` is an ambiguous method declaration and must be rejected
/// with `400 -32020`, the preserved correlation and no outbound request.
#[tokio::test]
async fn r22_conflicting_duplicate_mcp_method_is_rejected() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(160),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.headers(duplicated_header(
"mcp-method",
["tools/call", "tools/list"],
))
.header("Mcp-Name", COUNTED_TOOL_NAME)
.header("x-request-id", "r22-duplicate-mcp-method")
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
body["error"]["data"]["request_id"],
json!("r22-duplicate-mcp-method"),
"got {body}"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R22: a conflicting duplicate `Mcp-Name` is rejected the same way.
#[tokio::test]
async fn r22_conflicting_duplicate_mcp_name_is_rejected() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(161),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.headers(duplicated_header(
"mcp-name",
[COUNTED_TOOL_NAME, "some_other_tool"],
))
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R22: identical duplicates carry no ambiguity and keep working (accepted current semantics).
#[tokio::test]
async fn r22_identical_duplicate_mcp_method_is_served() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(162),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.headers(duplicated_header(
"mcp-method",
["tools/call", "tools/call"],
))
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 200);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 1);
}
@@ -0,0 +1,465 @@
//! Shared harness of the `revision_matrix` module: endpoint bootstrap, oracle fixtures and
//! request builders used by two or more of the thematic submodules (`negotiation`, `session_guards`,
//! `duplicate_carriers`, `envelope`, `method_name`, `tools_call`, `result_shapes`).
//!
//! The bodies were moved verbatim out of `revision_matrix.rs` (Story 3.6, kanban t_987bf309); no
//! literal, ordering, timeout or assertion changed.
use super::super::common::*;
use axum::http::header;
use axum::{Json, Router};
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::Arc;
use std::{path::PathBuf, time::Duration};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const UNKNOWN_REVISION: &str = "1999-01-01";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
pub(super) fn fixture(name: &str) -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/mcp-revisions")
.join(name);
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
panic!(
"oracle fixture must be readable at {}: {error}",
path.display()
)
});
serde_json::from_str(&raw).unwrap()
}
pub(super) fn wire_case(case_id: &str) -> Value {
fixture("wire-identity-cases.json")["cases"]
.as_array()
.unwrap()
.iter()
.find(|case| case["id"] == case_id)
.cloned()
.unwrap_or_else(|| panic!("wire identity case {case_id} must exist in the oracle"))
}
pub(super) fn oracle_status(case_id: &str) -> u16 {
wire_case(case_id)["expected_status"].as_u64().unwrap() as u16
}
pub(super) fn approved_revisions() -> Vec<String> {
fixture("supported-revisions.json")["revisions"]
.as_array()
.unwrap()
.iter()
.map(|entry| entry["revision"].as_str().unwrap().to_owned())
.collect()
}
/// A complete, schema-shaped modern request: required `_meta` (protocol version, client capabilities,
/// client info) plus the standard identity headers. Built once here so every modern case shares the
/// same valid metadata shape.
pub(super) fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-client", "version": "0.1.0" }
})
}
pub(super) fn modern_request(id: u64, method: &str, revision: &str, with_meta: bool) -> Value {
let mut params = json!({});
if with_meta {
params["_meta"] = modern_meta(revision);
}
json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })
}
pub(super) fn modern_headers(revision: &str, method: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", revision.to_owned()),
("Mcp-Method", method.to_owned()),
]
}
pub(super) fn tools_list_request(id: u64) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "method": "tools/list", "params": {} })
}
pub(super) struct Endpoint {
pub(super) registry: PostgresRegistry,
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
}
pub(super) async fn endpoint() -> Endpoint {
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-rest").await;
let api_key = create_platform_api_key(
&registry,
"sales-rest",
"mcp-rest",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
Endpoint {
registry,
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-rest"),
api_key,
}
}
pub(super) async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
})
}
// ---------------------------------------------------------------------------------------------
// Independent code-review regressions (R1-R9). Test-only: no production change is made here.
// Each case is single-fault and asserts observable HTTP/JSON-RPC behaviour of the delivered
// build slice. A failure means the review defect is reproduced on the current build.
// ---------------------------------------------------------------------------------------------
pub(super) fn modern_call_headers(method: &str, name: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", method.to_owned()),
("Mcp-Name", name.to_owned()),
]
}
pub(super) fn modern_request_with_params(id: Option<u64>, method: &str, mut extra: Value) -> Value {
// Only supply the standard modern metadata when the caller did not build its own `_meta`,
// so single-fault cases can omit or corrupt exactly one field.
if extra.get("_meta").is_none() {
extra["_meta"] = modern_meta(MODERN_REVISION);
}
let mut message = json!({ "jsonrpc": "2.0", "method": method, "params": extra });
if let Some(id) = id {
message["id"] = json!(id);
}
message
}
pub(super) async fn modern_post(
endpoint: &Endpoint,
headers: &[(&'static str, String)],
message: Value,
request_id: Option<&str>,
) -> reqwest::Response {
let mut all: Vec<(&str, &str)> = headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect();
if let Some(request_id) = request_id {
all.push(("x-request-id", request_id));
}
post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&all,
message,
)
.await
}
/// Test-only counted upstream: every lead request increments the counter, so a test can prove that an
/// approval-pending tool call performed **no** outbound request.
pub(super) async fn spawn_counted_lead_upstream(
calls: Arc<std::sync::atomic::AtomicUsize>,
) -> String {
use axum::routing::post;
let handler_calls = Arc::clone(&calls);
let app = Router::new().route(
"/crm/leads",
post(move |Json(payload): Json<Value>| {
let calls = Arc::clone(&handler_calls);
async move {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Json(json!({ "id": "lead_123", "email": payload["email"] }))
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://{address}")
}
// ---------------------------------------------------------------------------------------------
// R1 dispatch-safety regressions (test-first for the production fix): the modern era must not
// become an unsafe path once `tools/call` is dispatched without a session.
// ---------------------------------------------------------------------------------------------
pub(super) const COUNTED_TOOL_NAME: &str = "crm_counted_lead";
pub(super) struct CountedTool {
pub(super) endpoint: Endpoint,
pub(super) calls: Arc<std::sync::atomic::AtomicUsize>,
}
/// Test-only fixture: a published operation behind a counted upstream, with the given approval policy
/// and platform-key scopes. Every upstream request increments the counter, so a test can prove that a
/// rejected or pending call performed no outbound request.
pub(super) async fn counted_tool(
approval_policy: Option<crank_core::OperationApprovalPolicy>,
scopes: &[PlatformApiKeyScope],
) -> CountedTool {
use std::sync::atomic::AtomicUsize;
let calls = Arc::new(AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, COUNTED_TOOL_NAME);
operation.execution_config.approval_policy = approval_policy;
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-gated").await;
let api_key = create_platform_api_key(&registry, "sales-gated", "mcp-gated", scopes).await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-gated");
CountedTool {
endpoint: Endpoint {
registry,
client,
mcp_url,
api_key,
},
calls,
}
}
pub(super) fn counted_call_params(name: &str) -> Value {
json!({ "name": name, "arguments": { "email": "counted@example.com" } })
}
// ---------------------------------------------------------------------------------------------
// Review pass 2 regressions (R10-R15). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// Duplicate identity carriers are sent as real duplicate HTTP header lines (one `HeaderMap` with two
/// appended values, transmitted through `reqwest::RequestBuilder::headers`). The assertions below are
/// what settle whether both values actually arrive: a conflicting pair must be rejected, and the
/// pre-fix code that silently reads only the first value cannot pass them.
pub(super) fn duplicated_header(
name: &'static str,
values: [&str; 2],
) -> reqwest::header::HeaderMap {
let mut map = reqwest::header::HeaderMap::new();
let name = reqwest::header::HeaderName::from_static(name);
for value in values {
map.append(
name.clone(),
reqwest::header::HeaderValue::from_str(value).unwrap(),
);
}
map
}
/// Era of a request whose session carrier is ambiguous, read from the non-carrier part of the
/// request only — never guessed from the ambiguous value itself.
#[derive(Clone, Copy)]
pub(super) enum DuplicateSessionCarrierEra {
Modern,
Legacy,
}
// ---------------------------------------------------------------------------------------------
// Review pass 3 regressions (R16, R19-R22). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// Pending approval requests persisted for the fixture agent, read from the registry (never inferred
/// from a response body).
pub(super) async fn pending_approvals(registry: &PostgresRegistry, agent_slug: &str) -> usize {
registry
.list_pending_approval_requests_for_agent(
&test_workspace_id(),
&crank_core::AgentId::new(format!("agent_{agent_slug}")),
)
.await
.unwrap()
.len()
}
// ---------------------------------------------------------------------------------------------
// Review pass 4 regressions (R23-R25, R27). Test-only stage: production is read-only here.
//
// Source of every modern-only requirement — pinned public schema, commit
// 1f520964b295d58494d944f2aea8a5ab51c79f77, `schema/2026-07-28/schema.ts`:
// 223-235 `Result { _meta?; resultType: ResultType; [key: string]: unknown }` — the doc comment of
// `resultType` says "Servers implementing this protocol version MUST include this field";
// an absent `resultType` is only tolerated on results produced by *earlier* revisions.
// 287-290 `JSONRPCResultResponse { jsonrpc; id: RequestId; result: Result }`
// 534 `EmptyResult = Result`
// 1068 `PaginatedResult extends Result { nextCursor?: Cursor }`
// 1081 `CacheableResult extends Result { ttlMs: number; cacheScope: "public" | "private" }`
// 1779 `ListToolsResult extends PaginatedResult, CacheableResult { tools: Tool[] }`
// 1809 `CallToolResult extends Result { content: ContentBlock[]; structuredContent?; isError? }`
// 678-707 `DiscoverResult extends CacheableResult { ...; capabilities: ServerCapabilities }`
// The legacy era keeps its own earlier schema, so these tests never require modern-only fields on a
// legacy result.
// ---------------------------------------------------------------------------------------------
/// R25: every modern success result must satisfy the pinned `Result` contract.
///
/// Tightened oracle: `ResultType` is `"complete" | "input_required" | string`, but every result served
/// by this slice is a synchronous, fully computed result, so the exact value is `"complete"`. An
/// arbitrary non-empty string is not accepted.
pub(super) fn require_modern_result_type(result: &Value, method: &str) {
assert!(
result.is_object(),
"a modern success result must be an object, method={method} got {result}"
);
assert_eq!(
result.get("resultType").and_then(Value::as_str),
Some("complete"),
"the pinned `Result.resultType` is mandatory and must be \"complete\" for a synchronous \
modern success result, method={method} got {result}"
);
}
/// R25: a Search-mode agent over the counted operation with the given approval policy, so a proxy
/// (`call_tool`) case can be observed through real registry and outbound state.
pub(super) async fn counted_search_agent(
approval_policy: Option<crank_core::OperationApprovalPolicy>,
) -> CountedTool {
use crank_core::{ToolAccessMode, ToolGroup, ToolSearchSettings, ToolSelectionPolicy};
use std::sync::atomic::AtomicUsize;
let calls = Arc::new(AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, COUNTED_TOOL_NAME);
operation.execution_config.approval_policy = approval_policy;
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_with_policy(
&registry,
"sales-proxy",
vec![binding_for_operation(&operation)],
ToolSelectionPolicy {
mode: ToolAccessMode::Search,
groups: vec![ToolGroup {
id: "crm".to_owned(),
name: "CRM".to_owned(),
description: "CRM operations".to_owned(),
tool_names: vec![COUNTED_TOOL_NAME.to_owned()],
}],
search: ToolSearchSettings { max_results: 5 },
},
)
.await;
let api_key = create_platform_api_key(
&registry,
"sales-proxy",
"mcp-proxy",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
CountedTool {
endpoint: Endpoint {
registry,
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-proxy"),
api_key,
},
calls,
}
}
/// The pinned `call_tool` wrapper schema advertises `arguments` as a **required object**
/// (`manifest.rs` `CALL_TOOL_NAME` definition: `required: ["name", "arguments", "catalog_revision"]`,
/// `arguments: { "type": "object" }`). The proxy consumer deserializes the inner `arguments` with
/// `#[serde(default)]` into a `Value`, so a missing key becomes `null` and an array/scalar is accepted
/// as is — the nested `object` requirement of the advertised schema is not enforced before the
/// approval decision.
pub(super) fn proxy_call_params(catalog_revision: &str, inner: Option<Value>) -> Value {
let mut wrapper = json!({
"name": COUNTED_TOOL_NAME,
"catalog_revision": catalog_revision,
});
if let Some(inner) = inner {
wrapper["arguments"] = inner;
}
wrapper
}
@@ -0,0 +1,288 @@
//! Required `Mcp-Name`/method identity on modern requests, and the ordering rule that the name is
//! checked before an unsupported-method dispatch.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use serde_json::{Value, json};
use super::harness::{
MODERN_REVISION, endpoint, json_body, modern_headers, modern_post, modern_request_with_params,
};
/// R7: missing or mismatched `Mcp-Method` is a validation failure.
#[tokio::test]
async fn r7_modern_missing_mcp_method_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = modern_request_with_params(Some(80), "tools/list", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(80),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
#[tokio::test]
async fn r7_modern_mismatched_mcp_method_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(Some(81), "server/discover", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(81),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// R9: an unknown RPC on the modern era answers `404` + `-32601` with the request id preserved.
#[tokio::test]
async fn r9_modern_unknown_rpc_is_method_not_found() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/unsupported_thing");
let message = modern_request_with_params(Some(90), "tools/unsupported_thing", json!({}));
let response = modern_post(&endpoint, &headers, message, Some("r9-unknown-rpc")).await;
assert_eq!(response.status().as_u16(), 404);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(90),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32601), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// Review pass 6 (P5 / matrix row 6): `Mcp-Name` is a **required** modern header for `tools/call`,
/// `resources/read` and `prompts/get` (`streamable-http.mdx` "Standard Request Headers"), and its
/// validation must happen **before** the business dispatch. Both standard Resource/Prompt requests
/// implement their handler now (stories 3.8 and 3.14), so the missing/mismatched halves assert the
/// `-32020` header diagnostic and a correctly declared name reaches the implemented handler.
async fn modern_standard_method_name_outcome(
method: &'static str,
params: Value,
declared_name: Option<&str>,
correlation: &str,
) -> (u16, String) {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, method);
if let Some(name) = declared_name {
headers.push(("Mcp-Name", name.to_owned()));
}
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(150), method, params),
Some(correlation),
)
.await;
let status = response.status().as_u16();
(status, response.text().await.unwrap())
}
/// The `Mcp-Name` half of the row-6 oracle: a missing or mismatched required name header is a
/// `400` + `-32020` `HeaderMismatch` that keeps the request id, the request correlation and no result.
///
/// Review pass 7 (G2): the correlation assertion was missing entirely here even though the build
/// walkthrough claimed it was present on this half; the complete envelope is now pinned for both
/// standard names.
fn assert_required_name_header_is_a_structured_mismatch(
status: u16,
raw: &str,
correlation: &str,
case: &str,
) {
assert_eq!(
status, 400,
"{case}: row 6 requires a header-validation failure for a missing/mismatched `Mcp-Name`, got {raw}"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!(
"{case}: the `Mcp-Name` diagnostic must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(body["jsonrpc"], "2.0", "{case}: got {body}");
assert_eq!(
body["id"],
json!(150),
"{case}: the diagnostic must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{case}: row 6 returns `-32020` `HeaderMismatch`, got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{case}: the diagnostic must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{case}: the diagnostic must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{case}: a rejected request must not carry a result, got {body}"
);
}
/// Review pass 6 (P5): `resources/read` takes its `Mcp-Name` from `params.uri`. Since Story 3.8 the
/// method is implemented, so the name is validated before the Resource handler rather than before the
/// unsupported-method answer.
#[tokio::test]
async fn review6_p5_modern_resources_read_requires_mcp_name_before_resource_dispatch() {
let uri = "crank://operations/crm_create_lead";
let missing = "review6-p5-resources-missing-name";
let (status, raw) =
modern_standard_method_name_outcome("resources/read", json!({ "uri": uri }), None, missing)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
missing,
"resources/read missing name",
);
let mismatched = "review6-p5-resources-mismatched-name";
let (status, raw) = modern_standard_method_name_outcome(
"resources/read",
json!({ "uri": uri }),
Some("crank://operations/other"),
mismatched,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
mismatched,
"resources/read mismatched name",
);
let valid = "review6-p5-resources-valid-name";
let (status, raw) = modern_standard_method_name_outcome(
"resources/read",
json!({ "uri": uri }),
Some(uri),
valid,
)
.await;
// Story 3.8: `resources/read` is an implemented capability, so a correctly declared name reaches
// the Resource handler. An unbound URI is answered by one safe, non-disclosing outcome instead of
// the era-correct unsupported-method answer.
assert_eq!(
status, 200,
"a correctly declared `Mcp-Name` must reach the Resource handler, got {raw}"
);
let body: Value = serde_json::from_str(&raw).expect("the safe answer is a JSON-RPC envelope");
assert_eq!(body["jsonrpc"], "2.0", "got {body}");
assert_eq!(
body["id"],
json!(150),
"the answer must keep the request id: {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32602),
"an unbound Resource URI is safe invalid params, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(valid),
"the safe answer must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"a denied Resource read must not carry a result, got {body}"
);
}
/// Review pass 6 (P5): `prompts/get` takes its `Mcp-Name` from `params.name`.
#[tokio::test]
async fn review6_p5_modern_prompts_get_requires_mcp_name_before_unsupported_dispatch() {
let missing = "review6-p5-prompts-missing-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
None,
missing,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
missing,
"prompts/get missing name",
);
let mismatched = "review6-p5-prompts-mismatched-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
Some("crm_other_lead"),
mismatched,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
mismatched,
"prompts/get mismatched name",
);
let valid = "review6-p5-prompts-valid-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
Some("crm_create_lead"),
valid,
)
.await;
// Story 3.14 implements the standard Prompt requests, so a correctly declared name no longer
// reaches the unsupported-method answer: it is a business answer for a Prompt that this Agent
// does not bind, and the row-6 header diagnostic is still asserted on the two halves above.
assert_eq!(
status, 200,
"a correctly declared `prompts/get` name must reach the implemented handler, got {raw}"
);
let body: Value =
serde_json::from_str(&raw).expect("the business answer is a JSON-RPC envelope");
assert_eq!(body["error"]["code"], json!(-32602), "got {body}");
assert_eq!(
body["error"]["message"],
json!("the requested prompt is not available"),
"an unbound Prompt name stays a safe business answer, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(valid),
"the safe answer must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"an unbound Prompt must not carry a result, got {body}"
);
}
@@ -0,0 +1,890 @@
//! Revision negotiation on the real endpoint: modern stateless discovery, legacy
//! initialize/tools-list, withdrawn revisions, unknown/mismatched/missing identity, the negative
//! "no experimental surface" oracle and the minimal client.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use serde_json::{Value, json};
use super::harness::{
LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION,
MODERN_REVISION, UNKNOWN_REVISION, approved_revisions, endpoint, fixture, json_body,
modern_headers, modern_meta, modern_post, modern_request, modern_request_with_params,
oracle_status, require_modern_result_type, tools_list_request, wire_case,
};
/// Exact-descriptor assertion driven by an independent projection fixture
/// (`expected-advertised-capabilities.json`): the current scope may advertise exactly what is
/// implemented, and deferred capabilities must not appear. A generic official-key allowlist would
/// not prove that (TL finding on the descriptor oracle).
fn assert_advertised_descriptor(capabilities: &serde_json::Map<String, Value>, body: &Value) {
let expected = fixture("expected-advertised-capabilities.json");
let mut expected_keys: Vec<String> = expected["expected_keys"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
expected_keys.sort();
let mut actual_keys: Vec<String> = capabilities.keys().cloned().collect();
actual_keys.sort();
assert_eq!(
actual_keys, expected_keys,
"the advertised descriptor must equal the implemented current scope, got {body}"
);
for forbidden in expected["must_not_be_advertised"].as_array().unwrap() {
let key = forbidden.as_str().unwrap();
assert!(
!capabilities.contains_key(key),
"capability {key:?} is not implemented in the current scope and must not be advertised, got {body}"
);
}
// R8: compare the subfeatures as well, not only the key set.
let expected_descriptor = expected["expected_descriptor"]
.as_object()
.expect("the projection fixture must carry the expected descriptor");
assert_eq!(
&Value::Object(capabilities.clone()),
&Value::Object(expected_descriptor.clone()),
"advertised subfeatures must equal the independent golden descriptor, got {body}"
);
}
fn header_refs<'a>(headers: &'a [(&'static str, String)]) -> Vec<(&'static str, &'a str)> {
headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect()
}
fn initialize_request(revision: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": revision, "capabilities": {} }
})
}
/// AT-3.1-04: the modern stateless revision is served and `server/discover` is mandatory.
///
/// Golden coverage from the pinned schema: exact `supportedVersions`, `serverInfo`, revision-correct
/// `resultType` handling, cache hints, and the complete advertised capability descriptor (no
/// experimental or extension surface in the current scope). One positive status alone is **not**
/// treated as full AC-04 evidence.
#[tokio::test]
async fn at_3_1_04_modern_discover_is_served_without_a_session() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-01");
assert_eq!(expected, 200);
let headers = modern_headers(MODERN_REVISION, "server/discover");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(15, "server/discover", MODERN_REVISION, true),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"modern `server/discover` must be served"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"the modern stateless era must not mint a session"
);
let body = json_body(response).await;
let result = &body["result"];
let mut supported: Vec<String> = result["supportedVersions"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"discover must advertise exactly the approved revisions, got {body}"
);
// Pinned `DiscoverResult` places the server identity inside `result._meta`, not on the result
// object itself; the pinned prose makes it a SHOULD for the server to include it.
let server_info = &result["_meta"]["io.modelcontextprotocol/serverInfo"];
assert!(
server_info["name"].is_string() && server_info["version"].is_string(),
"discover must return `_meta['io.modelcontextprotocol/serverInfo']` with name and version, got {body}"
);
assert!(
result.get("serverInfo").is_none(),
"serverInfo must not be projected onto the result object itself, got {body}"
);
// The pinned revision treats an absent resultType as "complete".
assert!(
result.get("resultType").is_none() || result["resultType"] == json!("complete"),
"resultType must be absent or `complete` for a successful discover, got {body}"
);
// `ttlMs` and `cacheScope` are non-optional fields of the pinned `CacheableResult` that
// `DiscoverResult` extends, and both appear in the pinned discover example.
assert!(
result["ttlMs"].is_u64(),
"discover must carry the required cache TTL hint, got {body}"
);
assert!(
matches!(result["cacheScope"].as_str(), Some("public" | "private")),
"discover must carry the required cache scope, got {body}"
);
let capabilities = result["capabilities"]
.as_object()
.unwrap_or_else(|| panic!("capabilities must be an object, got {body}"));
assert_advertised_descriptor(capabilities, &body);
}
/// AT-3.1-04: a second, independent modern request is served without discover/session priming.
#[tokio::test]
async fn at_3_1_04_modern_request_is_served_without_priming() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(16, "tools/list", MODERN_REVISION, true),
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"a complete modern request must be served without priming"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
let body = json_body(response).await;
assert_eq!(body["result"]["tools"][0]["name"], "crm_create_lead");
}
/// AT-3.1-05: the legacy `2025-11-25` session lifecycle keeps working (existing correct behaviour).
#[tokio::test]
async fn at_3_1_05_legacy_initialize_and_tools_list_stay_green() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-06"), 200);
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let tools = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(2),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
}
/// AT-3.1-02: the withdrawn `2025-03-26` revision is rejected and mints no session.
#[tokio::test]
async fn at_3_1_02_withdrawn_2025_03_26_initialize_is_rejected() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-10");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request("2025-03-26"),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"a withdrawn revision must be rejected with {expected}"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected revision must not mint a session"
);
}
/// AT-3.1-02: the withdrawn `2025-06-18` revision is rejected as well.
#[tokio::test]
async fn at_3_1_02_withdrawn_2025_06_18_initialize_is_rejected() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-11");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request("2025-06-18"),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"a withdrawn revision must be rejected with {expected}"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected revision must not mint a session"
);
}
/// AT-3.1-06 (wm-05): an unknown revision, identical in header and body, yields `-32022` with the
/// supported list. All other required metadata stays valid, so this is a single-fault case.
#[tokio::test]
async fn at_3_1_06_unsupported_version_yields_structured_error() {
let endpoint = endpoint().await;
let case = wire_case("wm-05");
assert_eq!(case["expected_error"], "UnsupportedProtocolVersion");
let headers = modern_headers(UNKNOWN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(17, "tools/list", UNKNOWN_REVISION, true),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"], -32022,
"unknown revision must use the era-correct error code, got {body}"
);
let mut supported: Vec<String> = body["error"]["data"]["supported"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"the error must advertise exactly the supported revisions, got {body}"
);
}
/// AT-3.1-06 (wm-02): a known version in the header that differs from the body version is a
/// mismatch (`-32020`), not an unsupported-version error.
#[tokio::test]
async fn at_3_1_06_header_body_version_mismatch_is_rejected() {
let endpoint = endpoint().await;
let case = wire_case("wm-02");
assert_eq!(case["expected_error"], "HeaderMismatch");
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(18, "tools/list", LEGACY_REVISION, true),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"], -32020,
"a header/body version mismatch must use the header-mismatch code, got {body}"
);
}
/// AT-3.1-06 (wm-03): a modern header without the required body `_meta` is rejected.
#[tokio::test]
async fn at_3_1_06_modern_header_without_required_meta_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-03"), 400);
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(19, "tools/list", MODERN_REVISION, false),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a modern header without the required body metadata must be rejected"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// AT-3.1-06 (wm-04): an incomplete `_meta` (missing required client capabilities) is rejected.
#[tokio::test]
async fn at_3_1_06_modern_request_without_required_metadata_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-04"), 400);
let headers = modern_headers(MODERN_REVISION, "tools/list");
let incomplete = json!({
"jsonrpc": "2.0",
"id": 20,
"method": "tools/list",
"params": { "_meta": { META_PROTOCOL_VERSION: MODERN_REVISION } }
});
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
incomplete,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"missing required client capabilities must be rejected"
);
}
/// AT-3.1-06 / AT-3.1-02 (wm-12): a legacy `initialize` with an unknown revision must not mint a
/// session, must not return a successful initialize result, and must never echo the withdrawn
/// `2025-03-26` as the served identity.
///
/// The pinned legacy prose does not pin an HTTP status for an unsupported *body* version on
/// `initialize`, so this case deliberately asserts behaviour instead of guessing a status code.
#[tokio::test]
async fn at_3_1_06_legacy_initialize_unknown_revision_is_rejected() {
let endpoint = endpoint().await;
let case = wire_case("wm-12");
assert_eq!(case["expected"], "no_session_and_no_withdrawn_identity");
assert_eq!(case["status_not_pinned"], true);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request(UNKNOWN_REVISION),
)
.await;
let status = response.status();
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
let session_header = response.headers().get("MCP-Session-Id").is_some();
assert!(
!session_header,
"an unknown revision must not mint a session"
);
assert_ne!(
echoed.as_deref(),
Some("2025-03-26"),
"the withdrawn revision must never be echoed as the served identity"
);
let body = json_body(response).await;
if status.is_success() {
assert!(
body["error"].is_object(),
"a 2xx response for an unknown revision must still carry a JSON-RPC error, got {body}"
);
assert!(
body["result"].is_null(),
"an unknown revision must not produce an initialize result, got {body}"
);
}
}
/// AT-3.1-06 (wm-13) / AT-3.1-02: an authenticated request that carries no identity at all
/// (no initialization, no verified session, no version header, no `_meta`) must fail instead of
/// being served as a withdrawn revision. This replaces the earlier internal-constant assertion.
#[tokio::test]
async fn at_3_1_06_request_without_any_identity_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-13"), 400);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
tools_list_request(21),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a request without any protocol identity must be rejected"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"an unidentified request must not mint a session"
);
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
assert_ne!(
echoed.as_deref(),
Some("2025-03-26"),
"the withdrawn revision must never be echoed as the served identity"
);
}
/// AT-3.1-09 (advertisement half): the negotiated capability descriptor never contains an
/// experimental or extension surface, and unknown RPC/extension methods are not dispatchable.
#[tokio::test]
async fn at_3_1_09_no_extension_surface_is_advertised_or_dispatched() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
// 1. the actual negotiated capabilities from the real initialize response
let capabilities_response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.json(&initialize_request(LEGACY_REVISION))
.send()
.await
.unwrap();
let capabilities_body = json_body(capabilities_response).await;
let advertised = capabilities_body["result"]["capabilities"]
.as_object()
.cloned()
.unwrap_or_default();
assert_advertised_descriptor(&advertised, &capabilities_body);
// 2. an unknown extension method must not be dispatchable
let unknown_method = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "io.modelcontextprotocol/tasks/list",
"params": {}
}),
)
.await;
assert!(
unknown_method["error"].is_object(),
"an unknown extension method must be rejected, got {unknown_method}"
);
// 3. a name that is not a registered tool must not be dispatched
let denied = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 31,
"method": "tools/call",
"params": { "name": "experimental_unknown_extension", "arguments": {} }
}),
)
.await;
assert!(
denied["error"].is_object(),
"an unregistered identifier must be denied, got {denied}"
);
}
/// AT-3.1-10: a minimal client that declares no optional capabilities still lists and calls Tools.
#[tokio::test]
async fn at_3_1_10_minimal_client_still_lists_and_calls_tools() {
let endpoint = endpoint().await;
let session = initialize_session_with_capabilities(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
json!({}),
)
.await;
let tools = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(22),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
let call = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 23,
"method": "tools/call",
"params": {
"name": "crm_create_lead",
"arguments": { "email": "minimal@example.com" }
}
}),
)
.await;
assert_eq!(
call["result"]["structuredContent"],
json!({ "id": "lead_123" })
);
}
/// R2: each **required** modern metadata carrier is validated independently (single-fault cases).
/// The optional `clientInfo` is covered by the corrected oracle below (review pass 6, P4).
#[tokio::test]
async fn r2_modern_missing_body_version_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let mut meta = modern_meta(MODERN_REVISION);
meta.as_object_mut().unwrap().remove(META_PROTOCOL_VERSION);
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(50), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(response.status().as_u16(), 400);
assert!(response.headers().get("MCP-Session-Id").is_none());
let body = json_body(response).await;
assert!(body["error"].is_object(), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// R2 (corrected in review pass 6, P4): `clientInfo` is **optional** in the pinned modern request
/// metadata. `RequestMetaObject` declares it as `"io.modelcontextprotocol/clientInfo"?:
/// Implementation` and its prose says clients **SHOULD** include it unless specifically configured
/// not to, while `protocolVersion` and `clientCapabilities` are declared required
/// (`build/review6/pinned-modern-schema.ts:63-98`, pinned by SHA-256
/// `742750af0bb8c716e7030c4977c992b55d1adc4407e9e66997db5846baedc2cd`).
///
/// The earlier derived oracle promoted that SHOULD to a MUST: `validate_modern_metadata`
/// (`protocol/mod.rs` 516-533) rejects an absent `clientInfo`, so a source-correct modern request is
/// refused today. Correcting this invalid oracle is **not** permission to relax the required
/// metadata: a `clientInfo` that is present but malformed (wrong type, or missing `name`/`version`)
/// is still rejected, and those cases stay asserted separately above.
#[tokio::test]
async fn r2_modern_request_without_optional_client_info_is_served() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let mut meta = modern_meta(MODERN_REVISION);
meta.as_object_mut().unwrap().remove(META_CLIENT_INFO);
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(51), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"a modern request whose only deviation is the omitted **optional** `clientInfo` must be \
served (pinned `RequestMetaObject` marks it optional)"
);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"omitting the optional `clientInfo` must not produce a JSON-RPC error, got {body}"
);
assert_eq!(
body["result"]["tools"][0]["name"], "crm_create_lead",
"the served result must keep the published tool payload, got {body}"
);
require_modern_result_type(&body["result"], "tools/list (without clientInfo)");
}
#[tokio::test]
async fn r2_modern_client_info_without_name_or_version_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
for incomplete in [json!({}), json!({ "name": "crank-atdd-client" })] {
let mut meta = modern_meta(MODERN_REVISION);
meta[META_CLIENT_INFO] = incomplete.clone();
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(52), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"clientInfo {incomplete} must be rejected"
);
}
}
#[tokio::test]
async fn r2_modern_client_info_or_capabilities_of_wrong_type_are_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
for (key, value) in [
(META_CLIENT_INFO, json!("not-an-object")),
(META_CLIENT_CAPABILITIES, json!("not-an-object")),
] {
let mut meta = modern_meta(MODERN_REVISION);
meta[key] = value.clone();
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(53), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"{key} with value {value} must be rejected"
);
}
}
/// R2: body-only modern identity without the required version header must be rejected.
#[tokio::test]
async fn r2_modern_identity_without_version_header_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("Mcp-Method", "tools/list".to_owned())];
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(54), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"the modern era requires the negotiated version header"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// R3: legacy `initialize` must admit only the legacy revision.
#[tokio::test]
async fn r3_legacy_initialize_with_modern_body_version_is_rejected() {
let endpoint = endpoint().await;
let response = modern_post(&endpoint, &[], initialize_request(MODERN_REVISION), None).await;
assert_eq!(response.status().as_u16(), 400);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a modern body version must not mint a legacy session"
);
}
#[tokio::test]
async fn r3_legacy_header_with_modern_initialize_body_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", LEGACY_REVISION.to_owned())];
let response = modern_post(
&endpoint,
&headers,
initialize_request(MODERN_REVISION),
None,
)
.await;
assert_eq!(response.status().as_u16(), 400);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a conflicting modern body version must not mint a session"
);
}
#[tokio::test]
async fn r3_modern_identity_with_legacy_initialize_body_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "initialize");
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(
Some(55),
"initialize",
json!({ "protocolVersion": LEGACY_REVISION, "capabilities": {} }),
),
None,
)
.await;
let status = response.status().as_u16();
assert!(
status == 400 || status == 404,
"a legacy initialize body must not be admitted by the modern era, got {status}"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// Review pass 6 (P2 / matrix rows 14-15): a legacy `initialize` that names a withdrawn revision in
/// **both** carriers it can use — the `MCP-Protocol-Version` header and `params.protocolVersion` —
/// must stay legacy-shaped.
///
/// Defect this oracle pins: with an equal withdrawn identity the resolver takes the `other` branch
/// (`protocol/mod.rs` 665) and answers the modern `-32022` `UnsupportedProtocolVersionError`, while
/// the same withdrawn revision without a header is answered with the legacy `-32602` (`626-630`).
/// Row 14 forbids imposing the modern `-32022` contract on a legacy `initialize`; row 15 forbids an
/// implicit fallback into a withdrawn revision. The exact legacy code is deliberately **not** pinned
/// (the local contract names none for this path) — only the modern codes are excluded.
async fn assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
revision: &str,
correlation: &str,
) {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", revision.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": revision, "capabilities": {} }
});
let response = modern_post(&endpoint, &headers, message, Some(correlation)).await;
let status = response.status().as_u16();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a withdrawn `initialize` must not mint a session ({correlation})"
);
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"a withdrawn `initialize` revision must be rejected safely ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"matrix rows 14/15 require a structured legacy error ({correlation}), but the response body \
was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the legacy initialize rejection must be a JSON-RPC envelope ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the legacy rejection must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
json!(1),
"the legacy rejection must keep the request id ({correlation}), got {body}"
);
assert!(
body["error"]["code"].is_i64(),
"the legacy rejection must carry a numeric JSON-RPC code ({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersionError must not be imposed on a withdrawn legacy \
`initialize` (row 14, {correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy `initialize` (row 14, \
{correlation}), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the legacy rejection must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the legacy rejection must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected `initialize` must not carry a result ({correlation}), got {body}"
);
}
/// Review pass 6 (P2): withdrawn revision `2025-03-26` in both legacy carriers.
#[tokio::test]
async fn review6_p2_legacy_initialize_with_withdrawn_2025_03_26_is_legacy_shaped() {
assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
"2025-03-26",
"review6-p2-withdrawn-2025-03-26",
)
.await;
}
/// Review pass 6 (P2): withdrawn revision `2025-06-18` in both legacy carriers.
#[tokio::test]
async fn review6_p2_legacy_initialize_with_withdrawn_2025_06_18_is_legacy_shaped() {
assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
"2025-06-18",
"review6-p2-withdrawn-2025-06-18",
)
.await;
}
@@ -0,0 +1,579 @@
//! Result shapes: envelope object, required cacheable/paginated fields, `CallToolResult` fields and
//! the legacy result shapes.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, META_CLIENT_CAPABILITIES, MODERN_REVISION, counted_call_params,
counted_search_agent, counted_tool, endpoint, json_body, modern_call_headers, modern_headers,
modern_meta, modern_post, modern_request, modern_request_with_params, proxy_call_params,
require_modern_result_type, tools_list_request,
};
/// R14 (verification gap, expected current GREEN): a modern Elicitation-mode operation must fail
/// closed with `approval_elicitation_not_supported` whether or not the request `_meta` client
/// capabilities declare elicitation — the stateless era has no elicitation channel, and the policy is
/// never converted into a Custom approval.
#[tokio::test]
async fn r14_modern_elicitation_mode_fails_closed_without_outbound() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Elicitation,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: Some("Подтвердите выполнение операции.".to_owned()),
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
for declared_capabilities in [json!({}), json!({ "elicitation": {} })] {
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut meta = modern_meta(MODERN_REVISION);
meta[META_CLIENT_CAPABILITIES] = declared_capabilities.clone();
let message = modern_request_with_params(
Some(140),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let mut message = message;
message["params"]["_meta"] = meta;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"got {declared_capabilities}"
);
let text = response.text().await.unwrap();
assert!(
text.contains("approval_elicitation_not_supported"),
"an elicitation-mode policy must fail closed, got {text}"
);
assert!(
text.contains("\"isError\":true"),
"a fail-closed approval must be reported as a tool error, got {text}"
);
assert!(
!text.contains("approval_id"),
"an elicitation-mode policy must not be converted into a pending Custom approval, got {text}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a fail-closed approval must not perform the outbound request"
);
}
/// R25: `CacheableResult.cacheScope` is the pinned enum `"public" | "private"` (not any string).
fn require_cache_scope(result: &Value, method: &str) {
let scope = result.get("cacheScope").and_then(Value::as_str);
assert!(
matches!(scope, Some("public") | Some("private")),
"`CacheableResult.cacheScope` must be one of the pinned enum values, method={method} got \
{result}"
);
}
/// R25: `CacheableResult.ttlMs` is a non-negative number (the pinned schema marks `@minimum 0`).
fn require_ttl_ms(result: &Value, method: &str) {
assert!(
result
.get("ttlMs")
.and_then(Value::as_f64)
.is_some_and(|value| value >= 0.0),
"`CacheableResult.ttlMs` must be a non-negative number, method={method} got {result}"
);
}
/// R25: the mandatory `content` array of `CallToolResult` must be non-empty and carry a text block, i.e.
/// the projection may add result fields but must not degrade the business payload.
///
/// Review pass 6 (P8): the pinned `ContentBlock` union discriminates its members by `type`, so a block
/// whose payload happens to carry a `text` field is not evidence of a text block. The oracle now
/// asserts the `type: "text"` discriminator on the first block as well, while keeping the existing
/// non-empty-array and non-empty-payload assertions.
fn require_call_tool_content(result: &Value, method: &str) {
let content = result.get("content").and_then(Value::as_array);
assert!(
content.is_some_and(|blocks| !blocks.is_empty()),
"`CallToolResult.content` must be a non-empty array, method={method} got {result}"
);
let first = content.and_then(|blocks| blocks.first());
assert_eq!(
first
.and_then(|block| block.get("type"))
.and_then(Value::as_str),
Some("text"),
"the first `CallToolResult.content` block must carry the pinned `type: \"text\"` \
discriminator, method={method} got {result}"
);
assert!(
first
.and_then(|block| block.get("text"))
.and_then(Value::as_str)
.is_some_and(|text| !text.is_empty()),
"the first content block must keep a non-empty text payload, method={method} got {result}"
);
}
/// R24: the pinned `JSONRPCResultResponse` types `result` as `Result` (an object). The previous guard
/// checked the response id only, so a success response with a non-object `result` was acknowledged.
/// The object requirement stays on the era-agnostic wire envelope and deliberately does **not** require
/// the modern `resultType` inside an incoming result: a client implementing an earlier revision must
/// stay acceptable, which the pinned doc comment states explicitly.
#[tokio::test]
async fn r24_wire_response_result_must_be_an_object() {
let endpoint = endpoint().await;
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": null }),
json!({ "jsonrpc": "2.0", "id": 1, "result": [] }),
json!({ "jsonrpc": "2.0", "id": 1, "result": [1, 2] }),
json!({ "jsonrpc": "2.0", "id": 1, "result": 5 }),
json!({ "jsonrpc": "2.0", "id": 1, "result": "text" }),
json!({ "jsonrpc": "2.0", "id": 1, "result": true }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a non-object `result` is an invalid request, got {body}"
);
let payload = json_body(response).await;
assert_eq!(payload["error"]["code"], json!(-32600), "got {payload}");
assert!(
payload["id"].is_null(),
"an invalid request must answer with a null id, got {payload}"
);
}
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": {} }),
json!({ "jsonrpc": "2.0", "id": 1, "result": { "value": 1 } }),
json!({ "jsonrpc": "2.0", "id": 1, "result": { "resultType": "complete" } }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
202,
"an object `result` stays acknowledged, got {body}"
);
assert!(
response.text().await.unwrap().is_empty(),
"an acknowledgement carries no body, got {body}"
);
}
}
/// R25: `server/discover` already carries the complete `DiscoverResult` shape — the consolidated
/// modern result check must not regress it.
#[tokio::test]
async fn r25_modern_discover_result_carries_required_cacheable_fields() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "server/discover");
let response = modern_post(
&endpoint,
&headers,
modern_request(200, "server/discover", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
let result = &body["result"];
require_modern_result_type(result, "server/discover");
require_ttl_ms(result, "server/discover");
require_cache_scope(result, "server/discover");
assert!(
result["capabilities"].is_object(),
"`DiscoverResult.capabilities` is mandatory, got {result}"
);
}
/// R25: `ping` is not enumerated in the pinned method list, but every modern success response is a
/// `JSONRPCResultResponse` whose `result` must be a `Result`, so the emitted `resultType` requirement
/// still applies to it.
#[tokio::test]
async fn r25_modern_ping_result_carries_result_type() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "ping");
let response = modern_post(
&endpoint,
&headers,
modern_request(201, "ping", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
require_modern_result_type(&body["result"], "ping");
}
/// R25: `tools/list` must satisfy `ListToolsResult extends PaginatedResult, CacheableResult`, i.e. the
/// mandatory `resultType`, `ttlMs`, `cacheScope` and `tools`. `nextCursor` stays optional.
#[tokio::test]
async fn r25_modern_tools_list_result_carries_required_paginated_cacheable_fields() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = modern_post(
&endpoint,
&headers,
modern_request(202, "tools/list", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
let result = &body["result"];
assert_eq!(
result["tools"][0]["name"], "crm_create_lead",
"the tool list payload must not be degraded by the wire projection, got {result}"
);
require_modern_result_type(result, "tools/list");
require_ttl_ms(result, "tools/list");
require_cache_scope(result, "tools/list");
}
/// R25: the direct `tools/call` success result must satisfy `CallToolResult extends Result`, i.e. carry
/// `resultType` and the mandatory `content` array while keeping its business fields. The counted fixture
/// is used so the assertion covers the real upstream round-trip (the echoed request value) and the
/// outbound counter, exactly as the `call_tool` proxy case does.
#[tokio::test]
async fn r25_modern_direct_tool_call_result_carries_call_tool_result_fields() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let direct = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(203),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(direct.status().as_u16(), 200);
let direct_body = json_body(direct).await;
let direct_result = &direct_body["result"];
require_call_tool_content(direct_result, "tools/call (direct)");
assert_eq!(
direct_result["structuredContent"],
json!({ "id": "lead_123" }),
"the real upstream business output must survive the wire projection exactly (the fixture's \
`output_mapping` projects `$.response.body.id` only), got {direct_result}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"a served direct call must perform exactly one outbound request"
);
assert_eq!(
direct_result["isError"], false,
"the business error flag must survive the wire projection, got {direct_result}"
);
require_modern_result_type(direct_result, "tools/call (direct)");
}
/// R25: the Custom pending-approval result is served through `tools/call` too, so it must satisfy the
/// same `CallToolResult` contract (separate case so a fix that only touches one path is visible).
#[tokio::test]
async fn r25_modern_pending_approval_result_carries_call_tool_result_fields() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
let custom_policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let custom_fixture = counted_tool(
Some(custom_policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let custom_headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let pending = modern_post(
&custom_fixture.endpoint,
&custom_headers,
modern_request_with_params(
Some(204),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(pending.status().as_u16(), 200);
let pending_body = json_body(pending).await;
let pending_result = &pending_body["result"];
assert_eq!(
pending_result["structuredContent"]["status"], "approval_required",
"the fixture must produce the pending outcome, got {pending_body}"
);
require_call_tool_content(pending_result, "tools/call (approval_required)");
assert!(
pending_result["structuredContent"]["approval_id"]
.as_str()
.is_some_and(|value| value.starts_with("approval_")),
"the pending approval id must survive the wire projection, got {pending_result}"
);
require_modern_result_type(pending_result, "tools/call (approval_required)");
}
/// R25: the fail-closed Elicitation error result is also a `tools/call` result and must satisfy
/// `CallToolResult` (`content` plus `isError: true` marking the tool-level error).
#[tokio::test]
async fn r25_modern_elicitation_error_result_carries_call_tool_result_fields() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
let elicitation_policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Elicitation,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: Some("Подтвердите выполнение операции.".to_owned()),
};
let elicitation_fixture = counted_tool(
Some(elicitation_policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let elicitation_headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let elicitation = modern_post(
&elicitation_fixture.endpoint,
&elicitation_headers,
modern_request_with_params(
Some(205),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(elicitation.status().as_u16(), 200);
let elicitation_body = json_body(elicitation).await;
let elicitation_result = &elicitation_body["result"];
assert_eq!(
elicitation_result["isError"], true,
"the fixture must fail closed, got {elicitation_body}"
);
require_call_tool_content(elicitation_result, "tools/call (elicitation fail-closed)");
assert_eq!(
elicitation_result["structuredContent"]["error"]["code"],
"approval_elicitation_not_supported",
"the business error code must survive the wire projection, got {elicitation_result}"
);
require_modern_result_type(elicitation_result, "tools/call (elicitation fail-closed)");
}
/// R25: the Search-mode meta tool `search_tools` is served through `tools/call`, so its success result
/// must satisfy `CallToolResult` as well.
#[tokio::test]
async fn r25_modern_search_tools_result_carries_call_tool_result_fields() {
let fixture = counted_search_agent(None).await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(206),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
assert_eq!(search.status().as_u16(), 200);
let search_body = json_body(search).await;
let search_result = &search_body["result"];
let hits = search_result["structuredContent"]["tools"]
.as_array()
.unwrap_or_else(|| panic!("the search result must carry a tools array, got {search_body}"));
assert!(
hits.iter().any(|hit| hit["name"] == COUNTED_TOOL_NAME),
"the search must return the actually published fixture tool {COUNTED_TOOL_NAME} (a bare \
`is_array` check is satisfied by an empty list), got {search_body}"
);
assert!(
search_result["structuredContent"]["catalog_revision"]
.as_str()
.is_some_and(|value| value.starts_with("agent-version-1-catalog-revision-")),
"the search result must carry the real published catalog revision, got {search_result}"
);
require_call_tool_content(search_result, "tools/call (search_tools)");
require_modern_result_type(search_result, "tools/call (search_tools)");
}
/// R25: the `call_tool` proxy success result (same table as the direct call, separately exercised).
#[tokio::test]
async fn r25_modern_call_tool_proxy_result_carries_call_tool_result_fields() {
use std::sync::atomic::Ordering;
let fixture = counted_search_agent(None).await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(206),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
let search_body = json_body(search).await;
let catalog_revision = search_body["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let calls_before_proxy = fixture.calls.load(Ordering::SeqCst);
let proxy_headers = modern_call_headers("tools/call", "call_tool");
let proxy = modern_post(
&fixture.endpoint,
&proxy_headers,
modern_request_with_params(
Some(207),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(
&catalog_revision,
Some(json!({ "email": "proxy@example.com" })),
),
}),
),
None,
)
.await;
assert_eq!(proxy.status().as_u16(), 200);
let proxy_body = json_body(proxy).await;
let proxy_result = &proxy_body["result"];
assert_eq!(
proxy_result["isError"], false,
"the proxy fixture must execute, got {proxy_body}"
);
require_call_tool_content(proxy_result, "tools/call (call_tool proxy)");
assert_eq!(
proxy_result["structuredContent"],
json!({ "id": "lead_123" }),
"the real upstream business output must survive the `call_tool` proxy exactly (a bare \
`is_object` check is satisfied by any object; the fixture's `output_mapping` projects \
`$.response.body.id` only), got {proxy_result}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
calls_before_proxy + 1,
"a served proxy call must perform exactly one outbound request"
);
require_modern_result_type(proxy_result, "tools/call (call_tool proxy)");
}
/// R25: the legacy era keeps its own earlier result schema. These assertions only require the legacy
/// fields that the legacy era already serves; they deliberately say nothing about modern-only fields,
/// so a later modern fix may add `resultType` to shared code without breaking this test.
#[tokio::test]
async fn r25_legacy_result_shapes_stay_legacy() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let ping = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({ "jsonrpc": "2.0", "id": 220, "method": "ping", "params": {} }),
)
.await;
assert!(
ping["result"].is_object(),
"a legacy ping result stays an object, got {ping}"
);
assert!(
ping["error"].is_null(),
"a legacy ping must not become an error, got {ping}"
);
let listed = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(221),
)
.await;
assert!(
listed["result"]["tools"].is_array(),
"the legacy `tools/list` result keeps its `tools`, got {listed}"
);
let call = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 222, "method": "tools/call",
"params": { "name": "crm_create_lead", "arguments": { "email": "legacy-shape@example.com" } }
}),
)
.await;
assert!(
call["result"]["content"].is_array() && call["result"]["isError"].is_boolean(),
"the legacy `tools/call` result keeps `content` and `isError`, got {call}"
);
}
@@ -0,0 +1,382 @@
//! Review pass 8 identity regressions — `review8_identity` child module of `revision_matrix`.
//!
//! Bounded test-only maintenance (kanban t_f6b289ab, Story 3.1 / Gitea #8; TL triage
//! `build/review9-triage/TL-TRIAGE.md`): the three review-8 F1/F2 regressions moved verbatim
//! out of the parent module file, and their business parameters now come from the shared
//! `counted_call_params` factory. No assertion, input, header or wire expectation changed; the
//! shared parent helpers are reached through `super`.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO,
MODERN_REVISION, counted_call_params, counted_tool, duplicated_header, modern_post,
};
// ---------------------------------------------------------------------------------------------
// Review pass 8 — test-only regression for two residual protocol-root defects (F1/F2).
//
// Both oracles pin the **expected** era-correct behaviour of the current binding contract
// (`protocol-era-matrix.md`, CURRENT binding section). This stage changes no production code: it
// demonstrates the behaviour of the accepted freeze on the real endpoint and hands the complete
// oracle to TL review. F1 and F2 are two distinct observed product paths, not the full set of
// reviewer candidates, and neither is a Story/Epic/release qualification.
// ---------------------------------------------------------------------------------------------
/// A modern-specific request `_meta` with **no** version field.
///
/// `clientInfo` is a valid *optional* carrier in the pinned `RequestMetaObject`, so the
/// client-info-less variant is deliberately part of the F1 oracle instead of being treated as a
/// second defect: the rejection is required for the modern-specific identity as such, not for the
/// optional field.
fn review8_modern_meta_without_version(with_client_info: bool) -> Value {
let mut meta = json!({ META_CLIENT_CAPABILITIES: {} });
if with_client_info {
meta[META_CLIENT_INFO] = json!({ "name": "crank-review8-client", "version": "0.1.0" });
}
meta
}
/// Review pass 8 (F1 / matrix rows 4 and 16): an explicit **legacy** `MCP-Protocol-Version` header
/// must not turn a modern-specific request into a legacy admission.
///
/// Static trace of the accepted freeze (`crates/crank-community-mcp/src/protocol/mod.rs`):
/// `:623-643` reads `_meta` and finds no version field → `meta_version = None`; `:671` makes the
/// *effective* identity the legacy header value, so the missing-modern-version guard `:673-706`
/// (including its `declares_modern_metadata` check at `:678`) is skipped entirely; `:726-729`
/// selects `RequestEra::Legacy`. `app.rs` then accepts that header against the live legacy session
/// (`:866-895`), authorizes the valid write credential (`:902-905`) and reaches the real catalog
/// dispatch (`:1000-1041`), which performs the outbound call.
///
/// Binding row 4 ("modern `_meta` present without a version field → reject as header validation
/// failure") and row 16 (mixed carriers are rejected for the era identified by the dominant
/// carrier, with no hidden session and no partial state) require the opposite: a `400` + `-32020`
/// `HeaderMismatch` **before** any adapter or session admission — no business dispatch, no session
/// minting, no approval conversion.
///
/// The probe is bounded to the two metadata variants (client capabilities only, and client
/// capabilities plus a valid optional `clientInfo`) and is preceded by two positive controls on the
/// same live session (a plain legacy call and a legacy call with an ordinary non-modern `_meta`
/// key). The controls prove that the fixture, the session and the write credential are valid, so
/// the rejection cannot be explained by a malformed probe, and they pin that an ordinary `_meta`
/// stays permitted for the legacy era.
#[tokio::test]
async fn review8_f1_legacy_version_header_does_not_bypass_missing_modern_version_rejection() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
// Positive control 1: a plain valid legacy `tools/call` on the same live session. This is the
// accepted legacy behaviour and must stay GREEN before and after any F1 repair.
//
// The business parameters come from the shared `counted_call_params` factory and only the
// stage-specific email is overridden, so the request body keeps exactly the previous shape (M2).
let mut plain_params = counted_call_params(COUNTED_TOOL_NAME);
plain_params["arguments"]["email"] = json!("review8-f1-control-plain@example.com");
let plain = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 811,
"method": "tools/call",
"params": plain_params
}),
)
.await;
assert!(
plain["error"].is_null(),
"the plain legacy positive control must be served, got {plain}"
);
assert_eq!(
plain["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the plain legacy positive control must return the published business payload, got {plain}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"the plain legacy positive control must perform exactly one outbound call"
);
// Positive control 2: the same valid legacy call with an ordinary (non-modern) `_meta` key. The
// legacy era requires no client metadata, and a fix for F1 must not ban every `_meta` object.
// Same shared factory, same fixed email override and the same explicit ordinary `_meta` probe.
let mut ordinary_params = counted_call_params(COUNTED_TOOL_NAME);
ordinary_params["arguments"]["email"] = json!("review8-f1-control-ordinary-meta@example.com");
ordinary_params["_meta"] = json!({ "crank.probe": "ordinary" });
let ordinary_meta = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 812,
"method": "tools/call",
"params": ordinary_params
}),
)
.await;
assert!(
ordinary_meta["error"].is_null(),
"an ordinary non-modern `_meta` must not break a valid legacy call, got {ordinary_meta}"
);
assert_eq!(
ordinary_meta["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the ordinary-`_meta` positive control must return the published business payload, got \
{ordinary_meta}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
2,
"the second positive control must perform exactly one additional outbound call"
);
let calls_before_probe = fixture.calls.load(Ordering::SeqCst);
// The probe: an otherwise valid legacy-shaped `tools/call` whose `_meta` carries the
// modern-specific client identity without any version field, plus the explicit legacy version
// header on the same initialized session.
for (variant, with_client_info, id, correlation) in [
(
"clientCapabilities only",
false,
813_i64,
"review8-f1-capabilities-only",
),
(
"clientCapabilities plus clientInfo",
true,
814_i64,
"review8-f1-client-info",
),
] {
let headers = vec![
("MCP-Session-Id", session.clone()),
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
];
let mut probe_params = counted_call_params(COUNTED_TOOL_NAME);
probe_params["arguments"]["email"] = json!("review8-f1@example.com");
// The adversarial modern-specific `_meta` stays exactly what it was: the same builder, still
// without any version carrier, so the probe only adds it to the shared business shape.
probe_params["_meta"] = review8_modern_meta_without_version(with_client_info);
let probe = json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": probe_params
});
let response = modern_post(&fixture.endpoint, &headers, probe, Some(correlation)).await;
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"{variant}: a rejected request must not mint a session"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"{variant}: modern `_meta` without a version carrier must be rejected even when a \
legacy version header is present (matrix rows 4/16), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"{variant}: the row-4 rejection must be a structured diagnostic, but the body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"{variant}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"{variant}: the rejection must be a JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(id),
"{variant}: the rejection must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{variant}: a modern-specific identity without its required version carrier is a \
header-validation failure (matrix row 4), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{variant}: the rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{variant}: the rejection must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{variant}: a rejected request must not carry a result, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
calls_before_probe,
"{variant}: modern-specific metadata without a version carrier must not be executed as a \
legacy request"
);
}
}
/// Review pass 8 (F2 / matrix rows 3, 16 and 17): the era of an ambiguous `MCP-Session-Id` carrier
/// is read from the unambiguous part of the request, and a valid modern `MCP-Protocol-Version`
/// header is such a marker.
///
/// Static trace of the accepted freeze: `app.rs` `:827-830` projects
/// `protocol::ambiguous_session_carrier_response` (`protocol/mod.rs` `:480-488`) **before** era
/// resolution, and that projection asks `declares_modern_identity` (`:495-508`), which inspects only
/// the `Mcp-Method` header and the request `_meta`. A request that carries
/// `MCP-Protocol-Version: 2026-07-28` but no `Mcp-Method` and no `_meta` is therefore diagnosed in
/// the **legacy** shape (`:486` → `error_response` `:312-318`, `400` + `-32602`). Row 3 forbids
/// exactly that: "a modern header never routes the request into the legacy branch", and row 17
/// requires the era-correct structured diagnostic for an ambiguous carrier.
///
/// This is a compound *diagnostic* failure, not a successful modern admission: the request is
/// intentionally missing its required modern metadata and `Mcp-Method` header, so the expected
/// outcome stays a rejection — but the modern one (row 3/17: `400` + `-32020`) instead of a legacy
/// `-32602`. No result, no session minting and no outbound request in either shape.
async fn assert_modern_version_header_selects_the_modern_carrier_diagnostic(
session_values: [&'static str; 2],
correlation: &str,
id: Value,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(None, &[PlatformApiKeyScope::Read]).await;
let message = json!({
"jsonrpc": "2.0",
"id": id.clone(),
"method": "tools/list",
"params": {}
});
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-session-id", session_values))
.header("MCP-Protocol-Version", MODERN_REVISION)
.json(&message)
.send()
.await
.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"an ambiguous session carrier must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an ambiguous session carrier is a safe rejection ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"row 17 requires the era-correct structured diagnostic for an ambiguous session carrier \
({correlation}), but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the ambiguous-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the ambiguous-session diagnostic must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"], id,
"the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"matrix row 3: a request carrying a valid unambiguous modern version header must not be \
diagnosed in the legacy shape ({correlation}), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream ({correlation})"
);
}
/// Review pass 8 (F2): the numeric request id, first conflicting-value order.
#[tokio::test]
async fn review8_f2_modern_version_header_selects_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-a", "review8-f2-session-b"],
"review8-f2-numeric-id",
json!(1),
)
.await;
}
/// Review pass 8 (F2, bounded sibling): the same compound diagnostic with a valid `string` request id
/// and the opposite conflicting-value order. The pinned `RequestId` is `string | number`, so the
/// diagnostic must keep the modern era shape and preserve the valid string id as well — this is one
/// bounded projection, not a cross-product of era × id × order.
#[tokio::test]
async fn review8_f2_string_request_id_keeps_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-b", "review8-f2-session-a"],
"review8-f2-string-id",
json!("review8-f2-string"),
)
.await;
}
@@ -0,0 +1,424 @@
//! Session-carrier guards: an ambiguous or unusable `MCP-Session-Id` is rejected by the same
//! structured diagnostic per era, and never echoes the invalid value.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, DuplicateSessionCarrierEra, LEGACY_REVISION, MODERN_REVISION,
counted_call_params, counted_tool, duplicated_header, endpoint, json_body, modern_headers,
modern_post, modern_request_with_params, oracle_status, tools_list_request,
};
/// AT-3.1-11 (wm-07): without a version header a live legacy session establishes the revision.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_version_header_keeps_session_revision() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Session-Id", session.as_str())],
tools_list_request(10),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-07"),
"a live legacy session with no version header must still be served"
);
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
assert_eq!(
echoed.as_deref(),
Some(LEGACY_REVISION),
"the negotiated session revision must identify the era"
);
}
/// AT-3.1-11 (wm-08): a session-requiring era rejects a request without the session header.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_session_header_is_rejected() {
let endpoint = endpoint().await;
let _session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Protocol-Version", LEGACY_REVISION)],
tools_list_request(11),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-08"),
"a request without the required session header must be rejected"
);
}
/// AT-3.1-11 (wm-09 / wm-14): a terminated session is answered with `404`, never resurrected.
#[tokio::test]
async fn at_3_1_11_terminated_session_is_rejected_with_not_found() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let deleted = endpoint
.client
.delete(&endpoint.mcp_url)
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header(header::ORIGIN, "https://crank.example.com")
.send()
.await
.unwrap();
assert!(
deleted.status().is_success() || deleted.status().as_u16() == 405,
"session termination must be accepted or explicitly unsupported, got {}",
deleted.status()
);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[
("MCP-Session-Id", session.as_str()),
("MCP-Protocol-Version", LEGACY_REVISION),
],
tools_list_request(12),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-09"),
"a terminated session must be answered with 404 and never restored"
);
}
/// R4: conflicting/modern identity with a session carrier must be rejected before dispatch.
#[tokio::test]
async fn r4_modern_identity_with_unknown_session_header_is_rejected() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "session-that-never-existed".to_owned()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(60), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"an unknown session carrier must not be ignored by the modern path"
);
let body = json_body(response).await;
assert!(body["result"].is_null(), "got {body}");
}
#[tokio::test]
async fn r4_modern_identity_with_live_legacy_session_header_is_rejected() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", session.clone()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(61), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"mixed modern identity plus a legacy session carrier must be rejected"
);
}
/// R4 (observable half only): a modern request carrying an unknown session id must be rejected for the
/// carrier conflict. The quota question itself stays **NOT PROVEN** — it needs an observable counter over
/// the session-keyed limiter, which this harness does not expose.
#[tokio::test]
async fn r4_mixed_carrier_rejection_is_observable_quota_is_not_proven() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "quota-probe-session".to_owned()));
let first = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(62), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
first.status().as_u16(),
400,
"a modern request with an unknown session carrier must be rejected"
);
}
/// The two ways `session_id_from_headers` (`transport.rs` 227-229 → `singleton_header` 177-194)
/// reports an unusable `MCP-Session-Id`. Both surface as the same `Err(_status)` projection branch in
/// `mcp_post_response` (`app.rs` 827-830), so they are one root class for the diagnostic.
enum UnusableSessionCarrier {
/// Two conflicting session values: the carrier cannot identify the era or the session.
Conflicting([&'static str; 2]),
/// A non-text value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field value, so this is a
/// real transferable value that fails `HeaderValue::to_str()` inside `singleton_header`.
Unreadable,
}
/// Review pass 7 (G1): an otherwise-valid request whose `id` is **not** a valid request id must never
/// have that value echoed back.
///
/// `mcp_post_response` projects the ambiguous/unusable-session diagnostic (`app.rs` 827-830 →
/// `protocol::ambiguous_session_carrier_response` 461-468) **before** the single JSON-RPC envelope
/// guard (`app.rs` 832-837), and that projection reads the raw body id through `jsonrpc::request_id`
/// (`jsonrpc.rs` 32-33). The pinned `RequestId` is `string | number`, and the established
/// invalid-request convention answers with a `null` id precisely because an unvalidated value must
/// never be echoed (`protocol/mod.rs` 164-170).
///
/// This oracle pins that safety property only: the era-correct diagnostic keeps one of the existing
/// structured codes (modern `-32020` or the invalid-request `-32600`; legacy numeric and never
/// `-32020`/`-32022`) and the id is `null` instead of `{}`/`true`/`[]`. It deliberately invents no new
/// compound-case code and does not require the envelope guard to move; the valid-id shapes stay the
/// accepted P3 contract.
async fn assert_unusable_session_carrier_never_echoes_an_invalid_id(
carrier: UnusableSessionCarrier,
correlation: &str,
invalid_id: Value,
era: DuplicateSessionCarrierEra,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let mut request = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation);
request = match carrier {
UnusableSessionCarrier::Conflicting(values) => {
request.headers(duplicated_header("mcp-session-id", values))
}
UnusableSessionCarrier::Unreadable => {
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::HeaderName::from_static("mcp-session-id"),
reqwest::header::HeaderValue::from_bytes(&[b'x', 0xf8, 0xfe]).unwrap(),
);
request.headers(headers)
}
};
// The request is otherwise valid for its era: only the session carrier and the id are faulty.
let mut message = match era {
DuplicateSessionCarrierEra::Modern => {
request = request
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME);
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME))
}
DuplicateSessionCarrierEra::Legacy => {
request = request.header("MCP-Protocol-Version", LEGACY_REVISION);
json!({
"jsonrpc": "2.0",
"method": "tools/call",
"params": counted_call_params(COUNTED_TOOL_NAME)
})
}
};
message["id"] = invalid_id.clone();
let response = request.json(&message).send().await.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected request must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an unusable session carrier must be a safe rejection ({correlation}), got {raw}"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the unusable-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the diagnostic must be a complete JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
Value::Null,
"an invalid request id must never be echoed; the established invalid-request convention \
answers with a null id ({correlation}), got {body}"
);
assert!(
!body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(),
"the response id must never be the unvalidated value ({correlation}), got {body}"
);
let code = body["error"]["code"].clone();
assert!(
code.is_i64(),
"the diagnostic must carry a numeric JSON-RPC error code ({correlation}), got {body}"
);
assert_ne!(
code,
json!(-32022),
"the UnsupportedProtocolVersion code is reserved for a well-formed unknown identity \
({correlation}), got {body}"
);
match era {
DuplicateSessionCarrierEra::Modern => assert!(
code == json!(-32020) || code == json!(-32600),
"the modern shape keeps an existing structured code (header mismatch or invalid \
request) ({correlation}), got {body}"
),
DuplicateSessionCarrierEra::Legacy => assert_ne!(
code,
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy-sourced rejection \
({correlation}), got {body}"
),
}
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an unusable identity must not reach the upstream ({correlation})"
);
}
/// Review pass 7 (G1): modern identity, conflicting session carriers (a first), invalid object id.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-object-id",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the same modern case with the conflicting values in the opposite order and a
/// boolean id — the outcome must not depend on the header order or on the id's invalid kind.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_boolean_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-modern-boolean-id",
json!(true),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the third invalid id kind (an array) on the modern identity.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-array-id",
json!([]),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): legacy identity, conflicting session carriers, invalid object id. The legacy
/// diagnostic stays legacy-shaped and must still never echo the invalid id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-legacy-object-id",
json!({}),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): the legacy case, reversed order, array id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-legacy-array-id",
json!([]),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): an **unreadable** (non-text) session carrier reaches the same projection branch,
/// so the same no-echo guarantee is pinned for it.
#[tokio::test]
async fn review7_g1_modern_unreadable_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Unreadable,
"review7-g1-modern-unreadable-carrier",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
@@ -0,0 +1,904 @@
//! `tools/call` authorization and arguments: read-only keys, missing/mismatched/unknown/encoded
//! tool names, wire-response shape, inner-arguments shape of the proxy path and the approval-side
//! side-effect guards.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::Arc;
use std::{path::PathBuf, time::Duration};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use super::harness::{
COUNTED_TOOL_NAME, Endpoint, MODERN_REVISION, counted_call_params, counted_search_agent,
counted_tool, endpoint, json_body, modern_call_headers, modern_post,
modern_request_with_params, pending_approvals, proxy_call_params, spawn_counted_lead_upstream,
};
/// R1: a valid modern `tools/call` must return the same published tool result as the legacy era.
#[tokio::test]
async fn r1_modern_tools_call_returns_the_published_tool_result() {
let endpoint = endpoint().await;
let headers = modern_call_headers("tools/call", "crm_create_lead");
let message = modern_request_with_params(
Some(40),
"tools/call",
json!({
"name": "crm_create_lead",
"arguments": { "email": "modern@example.com" }
}),
);
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"a valid modern tools/call must be served"
);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"a valid modern tools/call must not return a JSON-RPC error, got {body}"
);
assert_eq!(
body["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the modern era must return the same business result as the legacy era, got {body}"
);
assert_eq!(body["result"]["isError"], false, "got {body}");
}
/// R1 (approval parity half): a real Custom-approval operation plus a counted upstream. The legacy era
/// defines the pinned pending outcome; the modern era must reach the same pending outcome and must not
/// perform the outbound call while approval is pending.
#[tokio::test]
async fn r1_modern_custom_approval_pending_before_outbound() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::{sync::Arc, sync::atomic::Ordering};
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, "crm_requires_human_approval");
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
});
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-gated").await;
let api_key = create_platform_api_key(
&registry,
"sales-gated",
"mcp-gated",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-gated");
let call_params = json!({
"name": "crm_requires_human_approval",
"arguments": { "email": "ada@example.com" }
});
// Legacy oracle: the pinned pending outcome on the same operation.
let session = initialize_session(&client, &mcp_url, &api_key).await;
let legacy = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&session),
json!({ "jsonrpc": "2.0", "id": 42, "method": "tools/call", "params": call_params.clone() }),
)
.await;
assert_eq!(
legacy["result"]["structuredContent"]["status"], "approval_required",
"the legacy era is the pinned oracle for the approval outcome, got {legacy}"
);
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"the legacy pending outcome must not perform the outbound call"
);
// Modern era: same operation, same expectation, no session.
let endpoint = Endpoint {
registry: registry.clone(),
client,
mcp_url,
api_key,
};
let headers = modern_call_headers("tools/call", "crm_requires_human_approval");
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(43), "tools/call", call_params),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"the modern era must serve an approval-gated tool call"
);
let modern = json_body(response).await;
assert_eq!(
modern["result"]["structuredContent"]["status"], "approval_required",
"the modern era must reach the same pending outcome as the legacy oracle, got {modern}"
);
assert_eq!(modern["result"]["isError"], false, "got {modern}");
assert!(
modern["result"]["structuredContent"]["approval_id"]
.as_str()
.is_some_and(|value| value.starts_with("approval_")),
"a pending approval id must be returned, got {modern}"
);
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"a pending approval must not perform the outbound call while awaiting approval"
);
}
/// R1: a read-only platform key must not reach a mutating modern tool call, and no outbound request may
/// happen before the scope check.
#[tokio::test]
async fn r1_modern_tools_call_with_read_only_key_is_unauthorized_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(None, &[PlatformApiKeyScope::Read]).await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message = modern_request_with_params(
Some(100),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let status = response.status().as_u16();
assert!(
status == 401 || status == 403,
"a read-only key must not perform a mutating tool call, got {status}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"the scope check must run before any outbound request"
);
}
/// R1: `Mcp-Name` is required for `tools/call`; a missing header is a header-validation failure.
#[tokio::test]
async fn r1_modern_tools_call_rejects_missing_mcp_name_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "tools/call".to_owned()),
];
let message = modern_request_with_params(
Some(101),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a missing required `Mcp-Name` header must be rejected"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"header validation must run before any outbound request"
);
}
/// R1: a `Mcp-Name` that does not match the body value must be rejected before dispatch.
#[tokio::test]
async fn r1_modern_tools_call_rejects_mismatched_mcp_name_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "some_other_tool");
let message = modern_request_with_params(
Some(102),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a mismatched name must not reach the upstream"
);
}
/// R1: an unknown tool is reported without any outbound request.
#[tokio::test]
async fn r1_modern_tools_call_rejects_unknown_tool_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "crm_missing_tool");
let message = modern_request_with_params(
Some(103),
"tools/call",
counted_call_params("crm_missing_tool"),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32602), "got {body}");
assert!(body["result"].is_null(), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an unknown tool must not reach the upstream"
);
}
/// R1: the sentinel-encoded `Mcp-Name` must be decoded before the comparison, and a matching encoded
/// name must be served like a plain one.
#[tokio::test]
async fn r1_modern_tools_call_accepts_sentinel_encoded_mcp_name() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "=?base64?Y3JtX2NvdW50ZWRfbGVhZA==?=");
let message = modern_request_with_params(
Some(104),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"a correctly encoded `Mcp-Name` must be accepted"
);
let body = json_body(response).await;
assert_eq!(
body["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"a matching encoded name must reach the upstream exactly once"
);
}
/// R16: the wire-response branch of the envelope guard must validate the response shape too. Pinned
/// schema: a success response carries `id: RequestId` (`string | number`) plus `result`; an error
/// response carries `error: Error { code: number; message: string }` and may omit the id — the two are
/// exclusive, and neither may be a foreign type. A malformed response must be `400 -32600`, not `202`.
///
/// R27 adds the single-fault `message` cases of the same `Error` shape: a correct numeric `code` with an
/// absent or non-string `message` is still an invalid response (this is a verification gap, not a new
/// defect — the same guard already covers it).
#[tokio::test]
async fn r16_malformed_wire_response_is_rejected() {
let endpoint = endpoint().await;
let malformed = [
json!({ "jsonrpc": "2.0", "id": 1, "error": null }),
json!({ "jsonrpc": "2.0", "id": 1, "error": false }),
json!({ "jsonrpc": "2.0", "id": 1, "result": {}, "error": { "code": -32000, "message": "x" } }),
json!({ "jsonrpc": "2.0", "id": {}, "result": {} }),
json!({ "jsonrpc": "2.0", "result": {} }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "message": "missing code" } }),
// R27 single-fault cases: the numeric `code` is correct, only `message` is wrong/absent.
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000 } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": 42 } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": null } }),
];
for (index, body) in malformed.iter().enumerate() {
let request_id = format!("r16-malformed-response-{index}");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("x-request-id", request_id.as_str())],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a malformed response envelope must be rejected, got {body}"
);
let payload = json_body(response).await;
assert_eq!(payload["error"]["code"], json!(-32600), "got {payload}");
assert!(
payload["id"].is_null(),
"an invalid request must answer with a null id, got {payload}"
);
if index == 0 {
assert_eq!(
payload["error"]["data"]["request_id"],
json!(request_id),
"the rejection must keep the ingress correlation, got {payload}"
);
}
}
}
/// R16 (positive half): legitimate wire responses keep the existing acknowledgement policy.
#[tokio::test]
async fn r16_valid_wire_response_is_acknowledged() {
let endpoint = endpoint().await;
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": {} }),
json!({ "jsonrpc": "2.0", "id": "req-1", "result": { "ok": true } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": "boom" } }),
json!({ "jsonrpc": "2.0", "error": { "code": -32000, "message": "boom" } }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
202,
"a well-formed wire response stays acknowledged, got {body}"
);
assert!(
response.text().await.unwrap().is_empty(),
"an acknowledgement carries no body, got {body}"
);
}
}
/// R20: the pinned `CallToolRequest.params.arguments` is an optional object, so an array or scalar
/// arguments value is invalid params — and it must be rejected **before** an approval policy can
/// persist a pending request. The registry state is read around the calls, not inferred from the
/// response. Omitted arguments keep their existing behaviour (`r20_modern_tools_call_without_arguments_is_preserved`).
#[tokio::test]
async fn r20_modern_tools_call_with_non_object_arguments_creates_no_pending_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let mut observed = Vec::new();
for bad_arguments in [json!([1, 2]), json!(5), json!("not-an-object")] {
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(150),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
message["params"]["arguments"] = bad_arguments.clone();
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
observed.push((bad_arguments, body));
}
// The registry state is checked first: it is the authoritative proof that a malformed arguments
// shape did not create a pending approval request.
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"no pending approval request may be persisted for a malformed arguments shape; observed: {observed:?}"
);
for (bad_arguments, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"arguments {bad_arguments} must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"a malformed arguments shape must not yield a pending approval, got {body}"
);
}
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R20 (preserved behaviour): omitting `arguments` entirely stays a valid method call — it reaches the
/// operation's own input validation instead of being rejected as an invalid `tools/call` parameter
/// shape. The fixture operation requires `email`, so the runtime answers `input_schema_invalid`; the
/// point of the regression is that the *method* shape was accepted (`error` is null, no `-32602`), which
/// the R20 fix must not change.
#[tokio::test]
async fn r20_modern_tools_call_without_arguments_is_preserved() {
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message = modern_request_with_params(
Some(151),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"omitted arguments are not a parameter-shape error, got {body}"
);
assert_eq!(body["result"]["isError"], true, "got {body}");
assert_eq!(
body["result"]["structuredContent"]["error"]["code"],
json!("input_schema_invalid"),
"the fixture operation requires `email`, got {body}"
);
}
/// R20 (fix, corrected oracle): an explicit `null` is *not* an omitted `arguments`. The pinned
/// `CallToolRequest.params.arguments` is an optional object, and an explicit null is not an object, so
/// the method param shape must be rejected as invalid params before any approval is persisted.
#[tokio::test]
async fn r20_modern_tools_call_with_null_arguments_is_rejected() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(152),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
message["params"]["arguments"] = Value::Null;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
// Registry state first: it is the authoritative proof that no pending approval was persisted.
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"an explicit null arguments must not persist a pending approval request; got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32602),
"an explicit null `arguments` is not an object and must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"an explicit null must not reach the approval path, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"no outbound request may happen for an invalid params shape"
);
}
/// R20 (same defect class, legacy sibling): the shared `tools/call` param shape protects the legacy era
/// too, so a non-object `arguments` on a real legacy session is invalid params without a pending
/// approval or an outbound request. The legacy exposure may predate this slice; the test records the
/// current behaviour of the shared guard rather than claiming a new legacy regression.
#[tokio::test]
async fn r20_legacy_tools_call_with_non_object_arguments_is_rejected() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let mut observed = Vec::new();
for bad_arguments in [json!([1, 2]), json!(7), Value::Null] {
let payload = json!({
"jsonrpc": "2.0",
"id": 153,
"method": "tools/call",
"params": { "name": COUNTED_TOOL_NAME, "arguments": bad_arguments.clone() },
});
let response = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
payload,
)
.await;
observed.push((bad_arguments, response));
}
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"the legacy era must not persist a pending approval for a malformed arguments shape; observed: {observed:?}"
);
for (bad_arguments, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"legacy arguments {bad_arguments} must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the legacy era must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"no legacy outbound request may happen for an invalid params shape"
);
}
/// R23 (legacy era): a `call_tool` proxy call whose inner `arguments` violates the advertised required
/// object must be rejected as invalid params before any approval is persisted.
///
/// Provenance: the proxy consumer is shared by both eras, so this bypass pre-existed the modern
/// revision work — it is recorded here as a reproduced defect, not as a new modern-era regression.
#[tokio::test]
async fn r23_legacy_proxy_inner_arguments_shape_is_rejected_before_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_search_agent(Some(policy)).await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let search = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 700, "method": "tools/call",
"params": { "name": "search_tools", "arguments": { "query": "counted" } }
}),
)
.await;
let catalog_revision = search["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let mut observed = Vec::new();
for inner in [
Some(Value::Null),
Some(json!([1, 2])),
Some(json!(5)),
Some(json!("not-an-object")),
Some(json!(true)),
None,
] {
let payload = json!({
"jsonrpc": "2.0", "id": 701, "method": "tools/call",
"params": {
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, inner.clone()),
}
});
let response = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
payload,
)
.await;
observed.push((inner, response));
}
// Registry state first: it is the authoritative proof that no pending approval was persisted.
let after = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
assert_eq!(
after, before,
"an inner arguments shape that violates the advertised `call_tool` schema must not persist a \
pending approval; observed: {observed:?}"
);
for (inner, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"inner arguments {inner:?} must be rejected by the existing invalid-arguments contract, \
got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the proxy must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a malformed proxy call must not reach the upstream"
);
// Positive half: a nested object keeps the real proxy approval outcome.
let accepted = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 702, "method": "tools/call",
"params": {
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, Some(json!({}))),
}
}),
)
.await;
assert_eq!(
accepted["result"]["structuredContent"]["status"], "approval_required",
"a valid nested object must keep the Custom approval outcome, got {accepted}"
);
assert_eq!(
pending_approvals(&fixture.endpoint.registry, "sales-proxy").await,
before + 1,
"the accepted proxy call must persist exactly one pending approval"
);
}
/// R23 (modern era): the same nested bypass through the modern stateless path.
#[tokio::test]
async fn r23_modern_proxy_inner_arguments_shape_is_rejected_before_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_search_agent(Some(policy)).await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(710),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
assert_eq!(search.status().as_u16(), 200);
let search_body = json_body(search).await;
let catalog_revision = search_body["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let headers = modern_call_headers("tools/call", "call_tool");
let mut observed = Vec::new();
for inner in [
Some(Value::Null),
Some(json!([1, 2])),
Some(json!(5)),
Some(json!("not-an-object")),
None,
] {
let response = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(711),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, inner.clone()),
}),
),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200, "got {inner:?}");
let body = json_body(response).await;
observed.push((inner, body));
}
let after = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
assert_eq!(
after, before,
"an inner arguments shape that violates the advertised `call_tool` schema must not persist a \
pending approval on the modern path; observed: {observed:?}"
);
for (inner, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"inner arguments {inner:?} must be rejected by the existing invalid-arguments contract, \
got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the proxy must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a malformed proxy call must not reach the upstream"
);
let accepted = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(712),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, Some(json!({ "email": "proxy@example.com" }))),
}),
),
None,
)
.await;
let accepted_body = json_body(accepted).await;
assert_eq!(
accepted_body["result"]["structuredContent"]["status"], "approval_required",
"a valid nested object must keep the Custom approval outcome, got {accepted_body}"
);
assert_eq!(
pending_approvals(&fixture.endpoint.registry, "sales-proxy").await,
before + 1,
"the accepted proxy call must persist exactly one pending approval"
);
}
@@ -0,0 +1,15 @@
//! Story 3.8 pre-build ATDD: public MCP discovery and read of published static Resources.
//!
//! Oracles: `docs/acceptance-test-plan.md` AT-3.8-01..05, `_bmad-output/test-artifacts/test-design-epic-3.md`
//! (3.8-API-A/B, E3-R2/R3) and the checked-in revision oracle
//! `tests/fixtures/mcp-revisions/supported-revisions.json`. Every request travels through the real
//! HTTP endpoint built by `build_app` against a real PostgreSQL registry; nothing here is backed by a
//! stub. The module `fixtures` documents the one build seam (artifact root) this suite depends on.
mod discovery_diagnostic;
mod fixtures;
mod lifecycle;
mod list;
mod read;
mod revocation;
mod safety;
@@ -0,0 +1,617 @@
//! Story 3.8 · NFR-P4 diagnostics: real `resources/list` latency for both supported MCP revisions.
//!
//! This is an **opt-in local diagnostic**, not a default-suite gate and not Reference evidence.
//! It drives the same real loopback HTTP endpoint, real PostgreSQL registry and real artifact store
//! the accepted AT-3.8-01..05 suite uses (`standard_endpoint`), measures `resources/list` until the
//! complete response body is consumed on a monotonic clock, validates every wire result against the
//! exact bound Resource snapshot, and writes raw samples plus nearest-rank percentiles under
//! `W/.tmp/t_b5624309` (override with `CRANK_DISCOVERY_DIAGNOSTIC_DIR`).
//!
//! Run explicitly:
//!
//! ```text
//! SQLX_OFFLINE=true CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 \
//! cargo test -p mcp-server --test integration \
//! integration::static_resources::discovery_diagnostic -- --ignored --nocapture --test-threads=1
//! ```
//!
//! It never asserts a latency threshold: the accepted ≤150 ms p95 NFR-P4 limit is reported as a
//! comparison only, because the dataset here is the bounded existing fixture (see `dataset` in the
//! summary), not the PRD Reference dataset, and the host is a shared 4 GiB test server. It does
//! assert protocol correctness (exactly the bound snapshot, correct per-revision result shape) so a
//! broken wire response can never be reported as a latency sample.
use std::{
fs,
path::PathBuf,
time::{Duration, Instant},
};
use reqwest::header;
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use super::super::common::initialize_session;
use super::fixtures::*;
/// Hard run bounds agreed for this bounded diagnostic.
const WARMUP_REQUESTS_PER_REVISION: usize = 20;
const MEASURED_REQUESTS_PER_REVISION: usize = 200;
/// At most 5 MCP requests/second with one request in flight: 250 ms between request starts.
const MIN_REQUEST_INTERVAL: Duration = Duration::from_millis(250);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
const NFR_P4_P95_LIMIT_MS: f64 = 150.0;
const JSONRPC_LIST_ID: u64 = 41;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
Warmup,
Measured,
}
impl Phase {
fn as_str(self) -> &'static str {
match self {
Phase::Warmup => "warmup",
Phase::Measured => "measured",
}
}
}
/// One HTTP attempt: latency to the fully consumed body, plus whatever failed.
struct WireCall {
latency_ms: f64,
http_status: Option<u16>,
body_bytes: Option<usize>,
body: Option<String>,
transport_error: Option<String>,
}
impl WireCall {
fn failure(&self, outcome: &'static str, detail: impl Into<String>) -> Sample {
Sample {
revision: "",
phase: Phase::Measured,
index: 0,
latency_ms: self.latency_ms,
http_status: self.http_status,
body_bytes: self.body_bytes,
outcome,
detail: detail.into(),
}
}
}
struct Sample {
revision: &'static str,
phase: Phase,
index: usize,
latency_ms: f64,
http_status: Option<u16>,
body_bytes: Option<usize>,
outcome: &'static str,
detail: String,
}
impl Sample {
fn as_json(&self) -> Value {
json!({
"revision": self.revision,
"phase": self.phase.as_str(),
"index": self.index,
"latency_ms": self.latency_ms,
"http_status": self.http_status,
"body_bytes": self.body_bytes,
"outcome": self.outcome,
"detail": self.detail,
})
}
}
fn now_rfc3339() -> String {
OffsetDateTime::now_utc()
.format(&Rfc3339)
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
}
/// One timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
/// recorded as outcomes instead of aborting the run.
async fn timed_list(
endpoint: &ResourceEndpoint,
revision: &'static str,
session: Option<&str>,
) -> WireCall {
let payload = if revision == LEGACY_REVISION {
json!({
"jsonrpc": "2.0",
"id": JSONRPC_LIST_ID,
"method": "resources/list",
"params": {}
})
} else {
let mut params = json!({});
params["_meta"] = modern_meta(revision);
json!({
"jsonrpc": "2.0",
"id": JSONRPC_LIST_ID,
"method": "resources/list",
"params": params
})
};
let mut request = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
);
if revision == LEGACY_REVISION {
request = request
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header("MCP-Session-Id", session.unwrap_or_default());
} else {
request = request
.header("MCP-Protocol-Version", revision)
.header("Mcp-Method", "resources/list");
}
let started = Instant::now();
let response = match request.json(&payload).send().await {
Ok(response) => response,
Err(error) => {
return WireCall {
latency_ms: started.elapsed().as_secs_f64() * 1000.0,
http_status: None,
body_bytes: None,
body: None,
transport_error: Some(error.to_string()),
};
}
};
let status = response.status().as_u16();
match response.text().await {
Ok(body) => {
let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
let body_bytes = body.len();
WireCall {
latency_ms,
http_status: Some(status),
body_bytes: Some(body_bytes),
body: Some(body),
transport_error: None,
}
}
Err(error) => {
let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
WireCall {
latency_ms,
http_status: Some(status),
body_bytes: None,
body: None,
transport_error: Some(format!("reading the response body failed: {error}")),
}
}
}
}
/// Validate one wire result against the exact bound snapshot and the pinned per-revision shape.
/// Returns the number of listed Resources on success.
fn validate_list_body(
body: &str,
revision: &'static str,
endpoint: &ResourceEndpoint,
) -> Result<usize, String> {
let parsed: Value = serde_json::from_str(body)
.map_err(|error| format!("response body is not JSON ({error}): {body:.400}"))?;
let result = parsed
.get("result")
.ok_or_else(|| format!("no JSON-RPC result: {body:.400}"))?;
let resources = result
.get("resources")
.and_then(Value::as_array)
.ok_or_else(|| format!("result carries no resources array: {result}"))?;
if revision == LEGACY_REVISION {
for field in ["resultType", "ttlMs", "cacheScope"] {
if result.get(field).is_some() {
return Err(format!("legacy result must not carry {field}: {result}"));
}
}
} else if result.get("resultType").and_then(Value::as_str) != Some("complete") {
return Err(format!(
"modern result must carry resultType=complete: {result}"
));
}
if result.get("nextCursor").is_some() {
return Err(format!(
"a 3-Resource snapshot must not advertise a continuation: {result}"
));
}
let expected: Vec<(&str, &str)> = [&endpoint.text, &endpoint.json, &endpoint.binary]
.into_iter()
.map(|bound| (bound.uri.as_str(), bound.name.as_str()))
.collect();
if resources.len() != expected.len() {
return Err(format!(
"expected exactly {} bound Resources, got {}: {result}",
expected.len(),
resources.len()
));
}
for resource in resources {
let uri = resource
.get("uri")
.and_then(Value::as_str)
.ok_or_else(|| format!("listed Resource without uri: {resource}"))?;
let Some((_, name)) = expected
.iter()
.find(|(expected_uri, _)| *expected_uri == uri)
else {
return Err(format!("unexpected listed Resource {uri}: {result}"));
};
if resource.get("name").and_then(Value::as_str) != Some(*name) {
return Err(format!(
"listed Resource {uri} must carry the published name {name}: {resource}"
));
}
if resource
.get("mimeType")
.and_then(Value::as_str)
.is_none_or(|mime| mime.is_empty())
{
return Err(format!(
"listed Resource {uri} must carry a MIME type: {resource}"
));
}
}
Ok(resources.len())
}
fn evaluate(call: WireCall, revision: &'static str, endpoint: &ResourceEndpoint) -> Sample {
let Some(body) = call.body.as_deref() else {
return call.failure(
"transport-error",
call.transport_error.clone().unwrap_or_default(),
);
};
if call.http_status != Some(200) {
return call.failure(
"http-status",
format!("HTTP {}: {body:.400}", call.http_status.unwrap_or(0)),
);
}
match validate_list_body(body, revision, endpoint) {
Ok(_) => Sample {
revision,
phase: Phase::Measured,
index: 0,
latency_ms: call.latency_ms,
http_status: call.http_status,
body_bytes: call.body_bytes,
outcome: "ok",
detail: String::new(),
},
Err(detail) => call.failure("wire-invalid", detail),
}
}
fn percentile_nearest_rank(sorted: &[f64], fraction: f64) -> f64 {
if sorted.is_empty() {
return f64::NAN;
}
let rank = (fraction * sorted.len() as f64).ceil() as usize;
sorted[rank.saturating_sub(1).min(sorted.len() - 1)]
}
fn summarize(
revision: &'static str,
samples: &[Sample],
wall: Duration,
init_ms: Option<f64>,
) -> Value {
let mut latencies: Vec<f64> = samples
.iter()
.filter(|sample| sample.outcome == "ok")
.map(|sample| sample.latency_ms)
.collect();
latencies.sort_by(f64::total_cmp);
let mut error_counts: std::collections::BTreeMap<&'static str, usize> =
std::collections::BTreeMap::new();
for sample in samples.iter().filter(|sample| sample.outcome != "ok") {
*error_counts.entry(sample.outcome).or_default() += 1;
}
let mean = if latencies.is_empty() {
f64::NAN
} else {
latencies.iter().sum::<f64>() / latencies.len() as f64
};
let p95 = percentile_nearest_rank(&latencies, 0.95);
let wall_seconds = wall.as_secs_f64();
json!({
"revision": revision,
"measured_requests": samples.len(),
"ok": latencies.len(),
"errors": error_counts,
"p50_ms": percentile_nearest_rank(&latencies, 0.50),
"p95_ms": p95,
"max_ms": latencies.last().copied().unwrap_or(f64::NAN),
"min_ms": latencies.first().copied().unwrap_or(f64::NAN),
"mean_ms": mean,
"wall_seconds": wall_seconds,
"achieved_requests_per_second": if wall_seconds > 0.0 {
samples.len() as f64 / wall_seconds
} else {
f64::NAN
},
"body_bytes_min": samples.iter().filter_map(|s| s.body_bytes).min(),
"body_bytes_max": samples.iter().filter_map(|s| s.body_bytes).max(),
"session_init_ms": init_ms,
"nfr_p4_p95_limit_ms": NFR_P4_P95_LIMIT_MS,
"p95_within_150ms_local_comparison_only": p95.is_finite() && p95 <= NFR_P4_P95_LIMIT_MS,
})
}
fn git(workdir: &str, args: &[&str]) -> String {
std::process::Command::new("git")
.args(args)
.current_dir(workdir)
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|stdout| stdout.trim().to_owned())
.unwrap_or_default()
}
fn environment_snapshot() -> Value {
let loadavg = fs::read_to_string("/proc/loadavg").unwrap_or_default();
let meminfo = fs::read_to_string("/proc/meminfo").unwrap_or_default();
let mem_available_kib = meminfo
.lines()
.find(|line| line.starts_with("MemAvailable:"))
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|value| value.parse::<u64>().ok());
json!({
"os": std::env::consts::OS,
"arch": std::env::consts::ARCH,
"logical_cpus": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),
"loadavg": loadavg.trim(),
"mem_available_kib": mem_available_kib,
"build_profile": if cfg!(debug_assertions) { "debug" } else { "release" },
"clock": "std::time::Instant (monotonic)",
"shared_host_note": "shared 4 vCPU / 4 GiB test server; loadavg recorded at measurement start and end",
})
}
async fn db_counts(registry: &crank_registry::PostgresRegistry) -> Value {
let pool = registry.pool();
let mut counts = serde_json::Map::new();
for (label, sql) in [
("agents", "select count(*) from agents"),
("published_agents", "select count(*) from published_agents"),
("operations", "select count(*) from operations"),
("resources", "select count(*) from resources"),
(
"resource_publications",
"select count(*) from resource_publications",
),
(
"agent_resource_bindings",
"select count(*) from agent_resource_bindings",
),
] {
let value = sqlx::query_scalar::<_, i64>(sql)
.fetch_one(pool)
.await
.map_err(|error| format!("{label}: {error}"));
match value {
Ok(count) => {
counts.insert(label.to_owned(), json!(count));
}
Err(detail) => {
counts.insert(label.to_owned(), json!({ "error": detail }));
}
}
}
Value::Object(counts)
}
fn output_dir() -> PathBuf {
std::env::var_os("CRANK_DISCOVERY_DIAGNOSTIC_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../.tmp/t_b5624309"))
}
/// Opt-in: `#[ignore]` keeps an unproven timing diagnostic out of the default suite. The console
/// `test result: ignored` line is the visible signal that this measurement did not run.
#[tokio::test]
#[ignore = "opt-in NFR-P4 discovery latency diagnostic (real HTTP + PostgreSQL), not a default-suite gate"]
async fn discovery_latency_diagnostic_p50_p95_both_revisions() {
let mut endpoint = standard_endpoint("nfr_p4_discovery").await;
// The accepted fixture resyncs the published catalog on every request (`refresh_interval` = 0),
// so each sample measures a cold-catalog discovery request: the production read path over HTTP.
endpoint.client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.build()
.expect("diagnostic HTTP client must build");
let revisions = supported_revisions();
for revision in [MODERN_REVISION, LEGACY_REVISION] {
assert!(
revisions.iter().any(|supported| supported == revision),
"the checked-in revision oracle must contain {revision}: {revisions:?}"
);
}
let worktree = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let worktree = worktree.display().to_string();
let environment_start = environment_snapshot();
let counts = db_counts(&endpoint.registry).await;
let started_at = now_rfc3339();
let run_started = Instant::now();
let mut all_samples: Vec<Value> = Vec::new();
let mut summaries = serde_json::Map::new();
for revision in [MODERN_REVISION, LEGACY_REVISION] {
// Session setup is deliberately outside the timed list span: legacy only.
let (init_ms, session) = if revision == LEGACY_REVISION {
let init_started = Instant::now();
let session =
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
(
Some(init_started.elapsed().as_secs_f64() * 1000.0),
Some(session),
)
} else {
(None, None)
};
let mut measured: Vec<Sample> = Vec::new();
let total = WARMUP_REQUESTS_PER_REVISION + MEASURED_REQUESTS_PER_REVISION;
let measured_started = Instant::now();
for index in 0..total {
let phase = if index < WARMUP_REQUESTS_PER_REVISION {
Phase::Warmup
} else {
Phase::Measured
};
let request_started = Instant::now();
let call = timed_list(&endpoint, revision, session.as_deref()).await;
let mut sample = evaluate(call, revision, &endpoint);
sample.revision = revision;
sample.phase = phase;
sample.index = index;
all_samples.push(sample.as_json());
if phase == Phase::Measured {
measured.push(sample);
}
let elapsed = request_started.elapsed();
if elapsed < MIN_REQUEST_INTERVAL {
tokio::time::sleep(MIN_REQUEST_INTERVAL - elapsed).await;
}
}
let wall = measured_started.elapsed();
let summary = summarize(revision, &measured, wall, init_ms);
println!(
"[discovery-diagnostic] revision={revision} samples={} ok={} errors={} p50={:.3}ms p95={:.3}ms max={:.3}ms wall={:.2}s",
summary["measured_requests"],
summary["ok"],
summary["errors"],
summary["p50_ms"].as_f64().unwrap_or(f64::NAN),
summary["p95_ms"].as_f64().unwrap_or(f64::NAN),
summary["max_ms"].as_f64().unwrap_or(f64::NAN),
summary["wall_seconds"].as_f64().unwrap_or(f64::NAN),
);
summaries.insert(revision.to_owned(), summary);
}
let out_dir = output_dir();
fs::create_dir_all(&out_dir).expect("diagnostic output directory must be creatable");
let raw_path = out_dir.join("discovery-samples.jsonl");
let mut raw = String::new();
for sample in &all_samples {
raw.push_str(&sample.to_string());
raw.push('\n');
}
fs::write(&raw_path, raw).expect("raw samples must be written");
let max_payload_bytes = [&endpoint.text, &endpoint.json, &endpoint.binary]
.into_iter()
.map(|bound| bound.bytes.len())
.max()
.unwrap_or(0);
let summary = json!({
"diagnostic": "story38_nfr_p4_resource_discovery_latency",
"generated_at_utc": now_rfc3339(),
"started_at_utc": started_at,
"candidate": {
"head": git(&worktree, &["rev-parse", "HEAD"]),
"branch": git(&worktree, &["rev-parse", "--abbrev-ref", "HEAD"]),
"worktree": worktree,
"dirty_tree": !git(&worktree, &["status", "--porcelain"]).is_empty(),
"note": "HEAD alone is insufficient in this dirty worktree; source identity is recorded in .tmp/t_b5624309/identity-*.json",
},
"scope": {
"measures": "MCP resources/list response latency over the real HTTP endpoint",
"does_not_measure": [
"resources/read latency",
"tools/call or platform execution overhead",
"mixed load, soak, burst or release Reference workload",
"representative real MCP client applications (none used; reqwest is not a client application)",
],
"nfr_p4_p95_limit_ms": NFR_P4_P95_LIMIT_MS,
"qualifies_nfr_p4": false,
"qualification_reason": "bounded existing fixture dataset on a shared 4 GiB host, single in-process test, not the PRD Reference Deployment dataset/load generator",
},
"method": {
"transport": "loopback HTTP (127.0.0.1, ephemeral port) served by the production axum router",
"registry": "real PostgreSQL 16 (testcontainers, own schema) with the real migration authority",
"artifact_store": "real immutable test-owned ArtifactStore root",
"revisions": [MODERN_REVISION, LEGACY_REVISION],
"warmup_requests_per_revision": WARMUP_REQUESTS_PER_REVISION,
"measured_requests_per_revision": MEASURED_REQUESTS_PER_REVISION,
"concurrency": 1,
"min_request_interval_ms": MIN_REQUEST_INTERVAL.as_millis(),
"request_timeout_ms": REQUEST_TIMEOUT.as_millis(),
"timed_span": "request start → complete response body consumed",
"percentile": "nearest-rank",
"warm_cold_policy": "process and fixtures warm after construction; first measured revision runs after its own 20-request warmup; catalog refresh interval is 0 ms, so every request reloads the published catalog from PostgreSQL (cold-catalog path)",
"session_policy": "legacy 2025-11-25: one initialize/initialized handshake before warmup, timed separately; modern 2026-07-28: stateless per request",
"error_policy": "transport, timeout, HTTP-status and wire-validation failures are counted per revision and excluded from percentiles; any error fails the test",
},
"dataset": {
"fixture": "static_resources::fixtures::standard_endpoint (accepted AT-3.8 suite)",
"bound_resources": 3,
"resource_kinds": ["text", "json", "binary"],
"max_resource_payload_bytes": max_payload_bytes,
"page": "no limit parameter: all 3 bound Resources in one page (server max page 100)",
"published_agents_in_request_scope": 1,
"published_operations_in_request_scope": 1,
"seeded_but_not_in_scope": "1 additional draft Agent, 1 published-but-unbound Resource, 1 draft Resource, 1 foreign-workspace Resource",
"db_row_counts": counts,
"dataset_gap": "PRD Reference dataset (200 Agents / 2 000 Operations, 32 static Resources of ≤4 KiB) is NOT seeded: the accepted fixture capabilities cannot seed it without a larger new harness, so this run measures the minimal existing set",
},
"environment": environment_start,
"environment_at_end": environment_snapshot(),
"run_wall_seconds": run_started.elapsed().as_secs_f64(),
"revisions": summaries,
"raw_samples_file": raw_path.display().to_string(),
"total_requests": all_samples.len(),
});
let summary_path = out_dir.join("discovery-summary.json");
fs::write(
&summary_path,
format!(
"{}\n",
serde_json::to_string_pretty(&summary).expect("summary serializes")
),
)
.expect("summary must be written");
println!("[discovery-diagnostic] summary: {}", summary_path.display());
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let entry = &summaries[revision];
let errors = entry["errors"]
.as_object()
.map(|map| map.len())
.unwrap_or(0);
assert_eq!(
entry["measured_requests"].as_u64(),
Some(MEASURED_REQUESTS_PER_REVISION as u64),
"every revision must produce the planned measured sample count: {entry}"
);
assert_eq!(
errors, 0,
"a working local endpoint must not answer transport/HTTP/wire failures on {revision}: {entry}"
);
assert_eq!(
entry["ok"].as_u64(),
Some(MEASURED_REQUESTS_PER_REVISION as u64),
"every measured response must validate against the bound snapshot on {revision}: {entry}"
);
}
}
@@ -0,0 +1,998 @@
//! Story 3.8 (AT-3.8-01..05): real MCP endpoint fixtures for published static Resources.
//!
//! Everything here uses the existing loopback MCP server, the real PostgreSQL registry and the
//! sanctioned `CommunityMachineCredentialVerifier` — no `route.fulfill`, no stubbed backend, no fake
//! service. Fixture data is bounded and test-owned.
//!
//! Resource fixture rows are seeded with SQL and exact published bytes written through the real
//! `ArtifactStore` (the same `put`/content-addressed contract the admin-api publishes with) into a
//! test-owned root. The row shapes are exactly the V16/V17 contracts (`resources`,
//! `resource_versions`, `resource_publications`, `artifact_*`).
//!
//! BUILD SEAM (Story 3.8): `build_app_with_artifacts` gives the MCP app the artifact store of its
//! root (the same seam the admin-api already has via `storage_root`); the existing constructors keep
//! working and fail `resources/read` closed. The production read path
//! (`resolve_resource_publication` + `resource_wire`) is the same code the endpoint runs.
#![allow(dead_code)]
use std::{
fs, io,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use crank_artifacts::ArtifactStore;
use crank_community_mcp::{
auth::CommunityMachineCredentialVerifier, build_app_with_artifacts,
session::InMemorySessionStore,
};
use crank_core::ResponseCacheStore;
use crank_core::ids::ResourceId;
use crank_core::{
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy, Workspace,
WorkspaceId, WorkspaceStatus,
};
use crank_registry::model::resource::ArchiveResourceRequest;
use crank_registry::{
AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentCatalogConfigRequest,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use tracing_subscriber::{filter::LevelFilter, fmt::MakeWriter};
use super::super::common::*;
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) 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";
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
/// Private, test-owned artifact root (0700) removed on drop.
pub(super) struct TestRoot(PathBuf);
impl TestRoot {
fn new(name: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"crank-mcp-static-resources-{name}-{}-{}",
std::process::id(),
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&path).expect("artifact root must be creatable");
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
.expect("artifact root must be private");
Self(path)
}
pub(super) fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TestRoot {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One seeded static Resource. `kind` is the typed kind, never sniffed from bytes.
pub(super) struct SeedResource {
pub(super) resource_id: ResourceId,
pub(super) uri: String,
pub(super) name: String,
pub(super) kind: &'static str,
pub(super) mime_type: &'static str,
pub(super) sensitivity: &'static str,
pub(super) bytes: Vec<u8>,
}
impl SeedResource {
pub(super) fn text(id: &str, uri: &str, name: &str, body: &str) -> Self {
Self::new(id, uri, name, "text", "text/plain", body.as_bytes())
}
pub(super) fn json(id: &str, uri: &str, name: &str, body: &str) -> Self {
Self::new(id, uri, name, "json", "application/json", body.as_bytes())
}
/// `image/png` bytes that are *valid UTF-8*: a text/JSON conversion would silently succeed, so
/// the read result proves the typed kind decides `blob` vs `text` (no content sniffing).
pub(super) fn binary(id: &str, uri: &str, name: &str, bytes: &[u8]) -> Self {
Self::new(id, uri, name, "binary", "image/png", bytes)
}
fn new(
id: &str,
uri: &str,
name: &str,
kind: &'static str,
mime_type: &'static str,
bytes: &[u8],
) -> Self {
Self {
resource_id: ResourceId::new(id),
uri: uri.to_owned(),
name: name.to_owned(),
kind,
mime_type,
sensitivity: "internal",
bytes: bytes.to_vec(),
}
}
}
pub(super) struct BoundResource {
pub(super) id: ResourceId,
pub(super) uri: String,
pub(super) name: String,
pub(super) bytes: Vec<u8>,
}
impl BoundResource {
fn from_seed(seed: &SeedResource) -> Self {
Self {
id: seed.resource_id.clone(),
uri: seed.uri.clone(),
name: seed.name.clone(),
bytes: seed.bytes.clone(),
}
}
}
pub(super) struct ResourceEndpoint {
pub(super) registry: PostgresRegistry,
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) tool_name: String,
pub(super) agent_id: AgentId,
pub(super) draft_agent_id: AgentId,
pub(super) root: TestRoot,
pub(super) artifact_store: ArtifactStore,
pub(super) text: BoundResource,
pub(super) json: BoundResource,
pub(super) binary: BoundResource,
pub(super) unbound_uri: String,
pub(super) unbound_name: String,
pub(super) draft_uri: String,
pub(super) draft_name: String,
pub(super) foreign_uri: String,
}
impl ResourceEndpoint {
pub(super) fn bound_uris(&self) -> Vec<String> {
vec![
self.text.uri.clone(),
self.json.uri.clone(),
self.binary.uri.clone(),
]
}
/// Digest-derived physical blob path of exact published bytes.
pub(super) fn blob_path(&self, bytes: &[u8]) -> PathBuf {
let digest = digest_hex(bytes);
self.root
.path()
.join("sha256")
.join(&digest[..2])
.join(&digest)
}
/// Replace the published binary blob with different bytes of the same length (corruption).
pub(super) fn corrupt_binary_blob(&self) {
let path = self.blob_path(&self.binary.bytes);
fs::remove_file(&path).expect("published blob must be removable in a test-owned root");
fs::write(&path, vec![b'x'; self.binary.bytes.len()])
.expect("corrupt blob must be writable");
fs::set_permissions(&path, fs::Permissions::from_mode(0o444))
.expect("corrupt blob must stay read-only like a published blob");
}
/// Remove the published binary blob entirely (a missing artifact, not a corrupt one).
pub(super) fn delete_binary_blob(&self) {
fs::remove_file(self.blob_path(&self.binary.bytes))
.expect("a test-owned published blob must be removable");
}
/// Make the publication size claim inconsistent with the stored blob, modelling tampered
/// metadata that must be denied before any byte is read. The table check constraint already
/// forbids a claim above the artifact-store ceiling, so an oversize row cannot be created at all;
/// this exercises the same pre-read integrity decision with a valid-but-wrong size.
pub(super) async fn inconsistent_text_publication_size(&self) {
sqlx::query(
"update resource_publications
set size_bytes = $4
where workspace_id = $1 and resource_id = $2 and version = $3",
)
.bind(test_workspace_id().as_str())
.bind(self.text.id.as_str())
.bind(1_i32)
.bind(1_i64)
.execute(self.registry.pool())
.await
.expect("publication size metadata must be updatable in a test-owned fixture");
}
/// Archive the bound text Resource through the accepted Story 3.7 registry transition.
pub(super) async fn archive_text(&self) {
let current = self
.registry
.get_resource_draft(test_workspace_id().as_str(), &self.text.id)
.await
.expect("bound Resource must be readable before archive");
self.registry
.archive_resource(ArchiveResourceRequest {
workspace_id: test_workspace_id(),
resource_id: self.text.id.clone(),
expected_updated_at: current.resource.updated_at,
archived_at: OffsetDateTime::now_utc(),
})
.await
.expect("an active published Resource must archive");
}
}
/// Local constructor seam for tests that need to observe the real runtime cache. It deliberately
/// mirrors the production constructor arguments without changing the shared integration harness.
fn build_resource_test_app(
registry: PostgresRegistry,
artifact_store: ArtifactStore,
cache: Option<Arc<dyn ResponseCacheStore>>,
) -> axum::Router {
let runtime = crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build();
let runtime = cache.map_or(runtime.clone(), |cache| {
runtime.with_response_cache_store(cache)
});
build_app_with_artifacts(
registry,
Duration::from_millis(0),
None,
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
runtime,
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
Arc::new(InMemorySessionStore::default()),
Arc::new(CommunityMachineCredentialVerifier),
16,
artifact_store,
)
}
/// Standard fixture without response caching, retaining the historical behavior of existing tests.
pub(super) async fn standard_endpoint(name: &str) -> ResourceEndpoint {
standard_endpoint_with_cache(name, None).await
}
/// Standard real-registry fixture with an explicitly injected response cache when requested.
pub(super) async fn standard_endpoint_with_cache(
name: &str,
cache: Option<Arc<dyn ResponseCacheStore>>,
) -> ResourceEndpoint {
let registry = test_registry().await;
let root = TestRoot::new(name);
let artifact_store =
ArtifactStore::open(root.path()).expect("the test artifact root must open");
// A published tool keeps the tools/list positive control meaningful on this exact endpoint.
let upstream = spawn_upstream_server().await;
let operation = test_operation(&upstream, "crm_resources_probe");
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 text = SeedResource::text(
"res_bound_text",
"crank://resources/bound-text",
"bound_text",
"bound text v1\n",
);
let json = SeedResource::json(
"res_bound_json",
"crank://resources/bound-json",
"bound_json",
r#"{"kind":"bound","version":1}"#,
);
let binary = SeedResource::binary(
"res_bound_binary",
"crank://resources/bound-binary",
"bound_binary",
b"PNG-but-valid-utf8-bytes",
);
let unbound = SeedResource::text(
"res_unbound_text",
"crank://resources/unbound-text",
"unbound_text",
"unbound text v1\n",
);
let draft = SeedResource::text(
"res_draft_text",
"crank://resources/draft-text",
"draft_text",
"draft text v1\n",
);
let foreign = SeedResource::text(
"res_foreign_text",
"crank://resources/foreign-text",
"foreign_text",
"foreign text v1\n",
);
seed_workspace(&registry).await;
for (seed, status) in [
(&text, "published"),
(&json, "published"),
(&binary, "published"),
(&unbound, "published"),
(&draft, "draft"),
] {
seed_resource(
&registry,
&artifact_store,
test_workspace_id().as_str(),
seed,
status,
)
.await;
}
seed_resource(
&registry,
&artifact_store,
"ws_other",
&foreign,
"published",
)
.await;
let agent_slug = name;
let agent_id = AgentId::new(format!("agent_{agent_slug}"));
let draft_agent_slug = format!("{name}-draft");
let draft_agent_id = AgentId::new(format!("agent_{draft_agent_slug}"));
create_draft_agent(&registry, agent_slug).await;
create_draft_agent(&registry, &draft_agent_slug).await;
registry
.save_agent_catalog_config(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: &[
AgentResourceBinding {
resource_id: text.resource_id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: json.resource_id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: binary.resource_id.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("draft Resource bindings must be saved");
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 Resource-bound Agent must publish");
let api_key = create_platform_api_key(
&registry,
agent_slug,
"mcp-resources",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_resource_test_app(
registry.clone(),
artifact_store.clone(),
cache,
))
.await;
ResourceEndpoint {
registry,
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, agent_slug),
api_key,
tool_name: operation.name.clone(),
agent_id,
draft_agent_id,
root,
artifact_store,
text: BoundResource::from_seed(&text),
json: BoundResource::from_seed(&json),
binary: BoundResource::from_seed(&binary),
unbound_uri: unbound.uri,
unbound_name: unbound.name,
draft_uri: draft.uri,
draft_name: draft.name,
foreign_uri: foreign.uri,
}
}
/// A published Agent with no Resource bindings at all: the empty `resources/list` page control.
/// The endpoint is otherwise the same real loopback MCP server + real registry + artifact root.
pub(super) struct EmptyResourceEndpoint {
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
_root: TestRoot,
_artifact_store: ArtifactStore,
}
pub(super) async fn empty_resource_endpoint(name: &str) -> EmptyResourceEndpoint {
let registry = test_registry().await;
let root = TestRoot::new(name);
let artifact_store =
ArtifactStore::open(root.path()).expect("the test artifact root must open");
create_draft_agent(&registry, name).await;
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &test_agent_id(name),
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("a Resource-free Agent must publish at registry level");
let api_key = create_platform_api_key(
&registry,
name,
"mcp-resources-empty",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
registry,
Duration::from_millis(0),
None,
artifact_store.clone(),
))
.await;
EmptyResourceEndpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, name),
api_key,
_root: root,
_artifact_store: artifact_store,
}
}
async fn seed_workspace(registry: &PostgresRegistry) {
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: WorkspaceId::new("ws_other"),
slug: "other".to_owned(),
display_name: "other".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("foreign workspace must be created");
}
async fn create_draft_agent(registry: &PostgresRegistry, slug: &str) {
let now = OffsetDateTime::now_utc();
let agent_id = AgentId::new(format!("agent_{slug}"));
let agent = Agent {
id: agent_id.clone(),
workspace_id: test_workspace_id(),
slug: slug.to_owned(),
display_name: slug.to_owned(),
description: "Story 3.8 static Resource fixture".to_owned(),
status: AgentStatus::Draft,
current_draft_version: 1,
latest_published_version: None,
created_at: now,
updated_at: now,
published_at: None,
};
let version = AgentVersion {
agent_id,
version: 1,
status: AgentStatus::Draft,
instructions: json!({}),
tool_selection_policy: ToolSelectionPolicy::default(),
created_at: now,
};
registry
.create_agent(CreateAgentRequest {
agent: &agent,
version: &version,
bindings: &[],
})
.await
.expect("draft Agent must be created");
}
/// Seed one exact Resource row set (`resources` + current `resource_versions` + owning blob/source and,
/// for `published`, the immutable `resource_publications` snapshot). The bytes are written through the
/// real `ArtifactStore`, so the fixture never re-implements the storage layout.
async fn seed_resource(
registry: &PostgresRegistry,
artifact_store: &ArtifactStore,
workspace: &str,
seed: &SeedResource,
status: &str,
) {
let stored = artifact_store
.put(&seed.bytes)
.expect("fixture bytes must be published into the test artifact root");
let digest = stored.artifact_ref.digest_hex().to_owned();
let source_id = format!("src_{}", seed.resource_id.as_str());
let size = i64::try_from(stored.size_bytes).expect("bounded fixture bytes");
let pool = registry.pool();
sqlx::query(
"insert into artifact_blobs
(digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at)
values ($1, $2, $3, 'available', now(), now())",
)
.bind(&digest)
.bind(format!("sha256:{digest}"))
.bind(size)
.execute(pool)
.await
.expect("fixture blob metadata must insert");
sqlx::query(
"insert into artifact_sources
(workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle, created_at, updated_at)
values ($1, $2, $3, $4, $5, 'active', now(), now())",
)
.bind(workspace)
.bind(&source_id)
.bind(&digest)
.bind(seed.mime_type)
.bind(seed.sensitivity)
.execute(pool)
.await
.expect("fixture artifact source must insert");
sqlx::query(
"insert into resources
(workspace_id, resource_id, uri, name, description, status, kind, current_draft_version, created_at, updated_at)
values ($1, $2, $3, $4, '', $5, $6, 1, now(), now())",
)
.bind(workspace)
.bind(seed.resource_id.as_str())
.bind(&seed.uri)
.bind(&seed.name)
.bind(status)
.bind(seed.kind)
.execute(pool)
.await
.expect("fixture Resource row must insert");
sqlx::query(
"insert into resource_versions
(workspace_id, resource_id, version, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, created_at, superseded_at)
values ($1, $2, 1, $3, $4, $5, $6, $7, $8, now(), null)",
)
.bind(workspace)
.bind(seed.resource_id.as_str())
.bind(seed.kind)
.bind(seed.mime_type)
.bind(size)
.bind(&digest)
.bind(seed.sensitivity)
.bind(&source_id)
.execute(pool)
.await
.expect("fixture Resource version must insert");
if status == "published" {
sqlx::query(
"insert into resource_publications
(workspace_id, resource_id, version, uri, name, description, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, published_at)
values ($1, $2, 1, $3, $4, '', $5, $6, $7, $8, $9, $10, now())",
)
.bind(workspace)
.bind(seed.resource_id.as_str())
.bind(&seed.uri)
.bind(&seed.name)
.bind(seed.kind)
.bind(seed.mime_type)
.bind(size)
.bind(&digest)
.bind(seed.sensitivity)
.bind(&source_id)
.execute(pool)
.await
.expect("fixture Resource publication must insert");
}
}
pub(super) fn digest_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
/// Revisions come from the checked-in oracle, never from memory.
pub(super) fn supported_revisions() -> Vec<String> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/mcp-revisions/supported-revisions.json");
let raw = fs::read_to_string(&path).unwrap_or_else(|error| {
panic!(
"revision oracle must be readable at {}: {error}",
path.display()
)
});
serde_json::from_str::<Value>(&raw).expect("revision oracle must be JSON")["revisions"]
.as_array()
.expect("revision oracle must list revisions")
.iter()
.map(|entry| {
entry["revision"]
.as_str()
.expect("revision string")
.to_owned()
})
.collect()
}
pub(super) fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-resources", "version": "0.1.0" }
})
}
/// `resources/list` over one supported revision on the standard fixture endpoint.
pub(super) async fn list_resources(
endpoint: &ResourceEndpoint,
revision: &str,
params: Value,
) -> reqwest::Response {
list_resources_at(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
revision,
params,
)
.await
}
/// `resources/list` over one supported revision: modern is stateless (identity in headers + `_meta`),
/// legacy goes through the accepted initialize/session handshake.
pub(super) async fn list_resources_at(
client: &reqwest::Client,
mcp_url: &str,
api_key: &str,
revision: &str,
params: Value,
) -> reqwest::Response {
if revision == LEGACY_REVISION {
let session = initialize_session(client, mcp_url, api_key).await;
post_jsonrpc_response(
client,
mcp_url,
api_key,
Some(&session),
None,
json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }),
)
.await
} else {
let mut params = params;
params["_meta"] = modern_meta(revision);
let headers = [
("MCP-Protocol-Version", revision),
("Mcp-Method", "resources/list"),
];
post_jsonrpc_with_headers(
client,
mcp_url,
api_key,
&headers,
json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }),
)
.await
}
}
/// `resources/templates/list` over one supported revision on the standard fixture endpoint.
pub(super) async fn list_resource_templates(
endpoint: &ResourceEndpoint,
revision: &str,
) -> reqwest::Response {
list_resource_templates_with_params(endpoint, revision, json!({})).await
}
pub(super) async fn list_resource_templates_with_params(
endpoint: &ResourceEndpoint,
revision: &str,
mut params: Value,
) -> reqwest::Response {
if !params.is_object() {
params = json!({});
}
if revision == LEGACY_REVISION {
let session =
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
post_jsonrpc_response(
&endpoint.client, &endpoint.mcp_url, &endpoint.api_key, Some(&session), None,
json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }),
).await
} else {
params
.as_object_mut()
.unwrap()
.insert("_meta".to_owned(), modern_meta(revision));
let headers = [
("MCP-Protocol-Version", revision),
("Mcp-Method", "resources/templates/list"),
];
post_jsonrpc_with_headers(
&endpoint.client, &endpoint.mcp_url, &endpoint.api_key, &headers,
json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }),
).await
}
}
/// `resources/read` over one supported revision, with the required modern `Mcp-Name` equal to the URI.
pub(super) async fn read_resource(
endpoint: &ResourceEndpoint,
revision: &str,
uri: &str,
request_id: Option<&str>,
) -> reqwest::Response {
if revision == LEGACY_REVISION {
let session =
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
post_jsonrpc_response(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
request_id,
json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri } }),
)
.await
} else {
let mut headers = vec![
("MCP-Protocol-Version", revision),
("Mcp-Method", "resources/read"),
("Mcp-Name", uri),
];
if let Some(request_id) = request_id {
headers.push(("x-request-id", request_id));
}
post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&headers,
json!({
"jsonrpc": "2.0",
"id": 21,
"method": "resources/read",
"params": { "uri": uri, "_meta": modern_meta(revision) }
}),
)
.await
}
}
/// Same modern read without any credential: authorization must reject before any Resource lookup.
pub(super) async fn read_resource_without_credentials(
endpoint: &ResourceEndpoint,
uri: &str,
) -> reqwest::Response {
endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "resources/read")
.header("Mcp-Name", uri)
.json(&json!({
"jsonrpc": "2.0",
"id": 31,
"method": "resources/read",
"params": { "uri": uri, "_meta": modern_meta(MODERN_REVISION) }
}))
.send()
.await
.expect("unauthenticated request must reach the server")
}
/// The same credential-less read in the legacy era: the session-based revision must reject it at the
/// transport authorization stage as well.
pub(super) async fn read_resource_without_credentials_legacy(
endpoint: &ResourceEndpoint,
uri: &str,
) -> reqwest::Response {
endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header("MCP-Protocol-Version", LEGACY_REVISION)
.json(&json!({
"jsonrpc": "2.0",
"id": 32,
"method": "resources/read",
"params": { "uri": uri }
}))
.send()
.await
.expect("unauthenticated request must reach the server")
}
pub(super) async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
})
}
pub(super) fn result_of<'a>(body: &'a Value, what: &str) -> &'a Value {
body.get("result").unwrap_or_else(|| {
panic!("{what} must return a JSON-RPC result (missing product capability?), got {body}")
})
}
pub(super) fn error_code(body: &Value) -> i64 {
body["error"]["code"]
.as_i64()
.unwrap_or_else(|| panic!("expected a JSON-RPC error, got {body}"))
}
pub(super) fn listed_uris(result: &Value) -> Vec<String> {
result["resources"]
.as_array()
.unwrap_or_else(|| {
panic!("resources/list result must carry a resources array, got {result}")
})
.iter()
.map(|resource| {
resource["uri"]
.as_str()
.unwrap_or_else(|| panic!("listed resource must carry a uri, got {resource}"))
.to_owned()
})
.collect()
}
pub(super) fn base64_of(bytes: &[u8]) -> String {
STANDARD.encode(bytes)
}
/// Collects per-revision failures so one run proves the RED/GREEN state for *every* supported MCP
/// revision instead of stopping at the first one.
#[derive(Default)]
pub(super) struct RevisionChecks {
failures: Vec<String>,
}
impl RevisionChecks {
pub(super) fn require(&mut self, condition: bool, message: impl FnOnce() -> String) {
if !condition {
self.failures.push(message());
}
}
pub(super) fn result<'a>(
&mut self,
body: &'a Value,
revision: &str,
what: &str,
) -> Option<&'a Value> {
match body.get("result") {
Some(result) => Some(result),
None => {
self.failures.push(format!(
"{what} on {revision} must return a JSON-RPC result, got {body}"
));
None
}
}
}
pub(super) fn finish(self) {
assert!(
self.failures.is_empty(),
"failures:\n---\n{}",
self.failures.join("\n---\n")
);
}
}
/// In-process log capture: proves the read telemetry keeps identity and carries no Resource content.
#[derive(Clone, Default)]
pub(super) struct CapturedLogs {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl CapturedLogs {
pub(super) fn install(&self) -> tracing::subscriber::DefaultGuard {
let subscriber = tracing_subscriber::fmt()
.with_max_level(LevelFilter::INFO)
.with_ansi(false)
.with_writer(LogWriter(Arc::clone(&self.buffer)))
.finish();
tracing::subscriber::set_default(subscriber)
}
pub(super) fn output(&self) -> String {
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap_or_default()
}
}
struct LogWriter(Arc<Mutex<Vec<u8>>>);
impl<'a> MakeWriter<'a> for LogWriter {
type Writer = LogGuard;
fn make_writer(&'a self) -> Self::Writer {
LogGuard(Arc::clone(&self.0))
}
}
struct LogGuard(Arc<Mutex<Vec<u8>>>);
impl io::Write for LogGuard {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
@@ -0,0 +1,125 @@
//! Story 3.8 AC04 / AT-3.8-04: archiving a Published Resource Version after the Agent snapshot is
//! fixed must not break reproducible reads of the exact immutable snapshot, while archive refuses new
//! bindings. Explicit security revocation stays a separate audited transition and is NOT aliased to
//! archive here — its API does not exist yet (reported as a gap, not invented).
use super::super::common::test_workspace_id;
use super::fixtures::*;
#[tokio::test]
async fn archive_keeps_the_exact_published_snapshot_readable_for_the_bound_agent() {
let endpoint = standard_endpoint("archive_read").await;
endpoint.archive_text().await;
// The immutable publication row itself is untouched by archive.
let publication = endpoint
.registry
.resolve_resource_publication(test_workspace_id().as_str(), &endpoint.text.id, 1)
.await
.expect("archiving must not remove the exact published version");
assert_eq!(
publication.publication.digest,
digest_hex(&endpoint.text.bytes),
"archive must not rewrite the published digest"
);
let expected = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
for revision in supported_revisions() {
let body =
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
let result = result_of(&body, &format!("post-archive resources/read on {revision}"));
let contents = result["contents"].as_array().unwrap_or_else(|| {
panic!("post-archive read must return contents on {revision}: {body}")
});
assert_eq!(
contents.len(),
1,
"post-archive read must return one content entry on {revision}: {body}"
);
assert_eq!(
contents[0]["text"].as_str(),
Some(expected.as_str()),
"post-archive read must return the exact immutable snapshot on {revision}: {body}"
);
}
}
/// Archive refuses new bindings, including for a still-mutable Draft Agent version.
#[tokio::test]
async fn archive_refuses_new_resource_bindings() {
let endpoint = standard_endpoint("archive_binding_guard").await;
let binding = crank_registry::AgentResourceBinding {
resource_id: endpoint.text.id.clone(),
resource_version: 1,
};
// Positive control: while the Resource is published and active, a Draft Agent accepts the binding.
endpoint
.registry
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.draft_agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
resource_bindings: std::slice::from_ref(&binding),
expected_state: None,
})
.await
.expect("an active published Resource must be bindable");
// Drop the control binding again so the post-archive attempt is a genuinely new binding.
endpoint
.registry
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.draft_agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
resource_bindings: &[],
expected_state: None,
})
.await
.expect("a Draft Agent must stay mutable");
endpoint.archive_text().await;
let denied = endpoint
.registry
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.draft_agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
resource_bindings: &[binding],
expected_state: None,
})
.await;
assert!(
denied.is_err(),
"an archived Resource must not be accepted as a new Agent binding, got {denied:?}"
);
let rows: i64 = sqlx::query_scalar(
"select count(*) from agent_resource_bindings where agent_id = $1 and agent_version = 1",
)
.bind(endpoint.draft_agent_id.as_str())
.fetch_one(endpoint.registry.pool())
.await
.expect("binding rows must be queryable");
assert_eq!(rows, 0, "a refused binding must not persist any row");
// Sanity: the refused attempt must not have been a no-op for another reason.
let published = endpoint
.registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("the bound Agent version must be readable")
.expect("the bound Agent version must exist");
assert_eq!(
published.resource_bindings.len(),
3,
"the published Agent snapshot must keep its three exact Resource bindings: {published:?}"
);
}
@@ -0,0 +1,819 @@
//! Story 3.8 AC01 / AT-3.8-01: authorized discovery returns only the Published Resources bound to the
//! exact published Agent snapshot, with an opaque continuation. Draft, foreign and unbound Resources
//! never appear.
use std::{
collections::BTreeSet,
sync::atomic::{AtomicUsize, Ordering},
};
use axum::{
Json as AxumJson,
body::Body,
extract::{Path, State},
response::Response,
routing::{get, head},
};
use crank_core::resource::template::TemplateSource;
use crank_core::{
AgentStatus, HttpMethod, OperationId, OperationSafetyClass, OperationSafetyPolicy,
RestResponseDescriptor, RestTarget, Target, ids::ResourceId,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::model::CreateAgentDraftVersionRequest;
use crank_registry::model::resource::{
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
};
use crank_registry::{
AgentResourceBinding, PostgresRegistry, PublishAgentRequest, PublishRequest,
SaveAgentCatalogConfigRequest,
};
use crank_schema::SchemaKind;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use super::super::common::{
object_schema, post_jsonrpc_response, post_jsonrpc_with_headers, test_operation,
test_workspace_id,
};
use super::fixtures::*;
#[path = "list/template_discovery.rs"]
mod template_discovery;
#[tokio::test]
async fn list_serves_every_supported_revision_with_only_bound_published_resources() {
let endpoint = standard_endpoint("list_matrix").await;
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
let revisions = supported_revisions();
assert!(
revisions.contains(&MODERN_REVISION.to_owned())
&& revisions.contains(&LEGACY_REVISION.to_owned()),
"the protocol matrix must be driven by the checked-in revision oracle: {revisions:?}"
);
let mut checks = RevisionChecks::default();
for revision in revisions {
let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
let Some(result) = checks.result(&body, &revision, "resources/list") else {
continue;
};
if revision != LEGACY_REVISION {
checks.require(result["resultType"].as_str() == Some("complete"), || {
format!(
"a modern resources/list result must carry Result.resultType=\"complete\" on {revision}: {body}"
)
});
}
let Some(listed_array) = result["resources"].as_array() else {
checks.require(false, || {
format!("resources/list must carry a resources array on {revision}: {body}")
});
continue;
};
let listed: BTreeSet<String> = listed_array
.iter()
.filter_map(|resource| resource["uri"].as_str().map(str::to_owned))
.collect();
checks.require(listed == expected, || {
format!(
"revision {revision} must list exactly the bound Published Resources, got {body}"
)
});
for excluded in [
&endpoint.draft_uri,
&endpoint.unbound_uri,
&endpoint.foreign_uri,
] {
checks.require(!listed.contains(excluded), || {
format!(
"a Draft, foreign or unbound Resource ({excluded}) must not be discoverable on {revision}: {body}"
)
});
}
for resource in listed_array {
let uri = resource["uri"].as_str().unwrap_or_default();
match [&endpoint.text, &endpoint.json, &endpoint.binary]
.into_iter()
.find(|bound| bound.uri == uri)
{
None => checks.require(false, || {
format!("unexpected listed Resource {uri} on {revision}: {body}")
}),
Some(bound) => {
checks.require(
resource["name"].as_str() == Some(bound.name.as_str()),
|| {
format!(
"the listed Resource must expose the published name for {uri} on {revision}: {resource}"
)
},
);
checks.require(resource["mimeType"].as_str().is_some(), || {
format!(
"the listed Resource must expose the published MIME type for {uri} on {revision}: {resource}"
)
});
}
}
}
}
checks.finish();
}
/// The pinned 2026-07-28 `ListResourcesResult extends PaginatedResult, CacheableResult`: every modern
/// list result — an empty page, a populated page and a continued page — must carry `resultType`,
/// `ttlMs` and `cacheScope`. The legacy revision keeps its earlier shape without those members.
#[tokio::test]
async fn list_modern_results_carry_the_required_cacheable_result_fields() {
let populated = standard_endpoint("list_cacheable_populated").await;
let empty = empty_resource_endpoint("list_cacheable_empty").await;
let bound = populated.bound_uris().len();
assert!(
bound > 1,
"the fixture must paginate more than one Resource"
);
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let first =
json_body(list_resources(&populated, &revision, json!({ "limit": 1 })).await).await;
let cursor = result_of(&first, "bounded resources/list")["nextCursor"]
.as_str()
.unwrap_or_else(|| {
panic!("a bounded page must advertise a cursor on {revision}: {first}")
})
.to_owned();
let second = json_body(
list_resources(
&populated,
&revision,
json!({ "limit": 1, "cursor": cursor }),
)
.await,
)
.await;
let empty_page = json_body(
list_resources_at(
&empty.client,
&empty.mcp_url,
&empty.api_key,
&revision,
json!({}),
)
.await,
)
.await;
for (what, body, expected) in [
("populated resources/list", &first, 1usize),
("continued resources/list", &second, 1usize),
("empty resources/list", &empty_page, 0usize),
] {
require_list_result_shape(&mut checks, body, &revision, what);
let Some(result) = body.get("result") else {
continue;
};
let listed = listed_uris(result);
checks.require(listed.len() == expected, || {
format!("{what} must carry {expected} Resource(s) on {revision}: {body}")
});
}
}
checks.finish();
}
/// Story 3.8 correction (Cherry Studio 2.1.7): the client requests `resources/templates/list`
/// together with `resources/list` and drops the whole resource browser when that call fails, even
/// though the second call succeeds. This server has no dynamic Resource template, so both supported
/// revisions must answer the authenticated request with an empty `resourceTemplates` array in their
/// own result envelope instead of an era-correct "method not found".
#[tokio::test]
async fn list_resource_templates_answers_an_empty_page_on_every_revision() {
let endpoint = standard_endpoint("list_templates").await;
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let response = list_resource_templates(&endpoint, &revision).await;
let status = response.status();
let body = json_body(response).await;
checks.require(status == reqwest::StatusCode::OK, || {
format!(
"resources/templates/list must be served on {revision}, got HTTP {status}: {body}"
)
});
let Some(result) = checks.result(&body, &revision, "resources/templates/list") else {
continue;
};
checks.require(body["id"].as_i64() == Some(31), || {
format!("resources/templates/list must preserve the request id on {revision}: {body}")
});
checks.require(
result
.get("resourceTemplates")
.and_then(Value::as_array)
.is_some_and(Vec::is_empty),
|| {
format!(
"resources/templates/list must answer exactly an empty resourceTemplates array on {revision}: {body}"
)
},
);
checks.require(result.get("nextCursor").is_none(), || {
format!("an empty template page must not advertise nextCursor on {revision}: {body}")
});
if revision == LEGACY_REVISION {
for field in ["resultType", "ttlMs", "cacheScope"] {
checks.require(result.get(field).is_none(), || {
format!(
"the legacy resources/templates/list must keep its earlier shape without {field} on {revision}: {body}"
)
});
}
continue;
}
checks.require(result["resultType"].as_str() == Some("complete"), || {
format!(
"a modern resources/templates/list must carry Result.resultType=\"complete\" on {revision}: {body}"
)
});
checks.require(
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|| {
format!(
"a modern resources/templates/list must carry CacheableResult.ttlMs on {revision}: {body}"
)
},
);
checks.require(
matches!(
result.get("cacheScope").and_then(Value::as_str),
Some("public" | "private")
),
|| {
format!(
"a modern resources/templates/list must carry CacheableResult.cacheScope on {revision}: {body}"
)
},
);
}
checks.finish();
}
/// The new method is not an escape hatch: the shared modern header rule, the transport
/// authorization and the legacy initialized-session guard still decide before its handler runs.
#[tokio::test]
async fn list_resource_templates_keeps_the_existing_guards() {
let endpoint = standard_endpoint("list_templates_guards").await;
let payload = json!({
"jsonrpc": "2.0",
"id": 41,
"method": "resources/templates/list",
"params": { "_meta": modern_meta(MODERN_REVISION) }
});
for headers in [
vec![("MCP-Protocol-Version", MODERN_REVISION)],
vec![
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "resources/list"),
],
] {
let body = json_body(
post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&headers,
payload.clone(),
)
.await,
)
.await;
assert!(
body.get("result").is_none(),
"a modern resources/templates/list without its own Mcp-Method must not reach the handler ({headers:?}): {body}"
);
assert_eq!(
error_code(&body),
-32020,
"a missing or mismatched Mcp-Method stays a header mismatch ({headers:?}): {body}"
);
}
// No credential: the transport authorization still answers first.
let unauthenticated = endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "resources/templates/list")
.json(&payload)
.send()
.await
.expect("unauthenticated request must reach the server");
assert_eq!(
unauthenticated.status().as_u16(),
401,
"an unauthenticated resources/templates/list must be rejected before dispatch"
);
// A legacy session that never completed `notifications/initialized` is still refused.
let initialized = endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header("Authorization", format!("Bearer {}", endpoint.api_key))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
}))
.send()
.await
.expect("the legacy initialize must reach the server");
let session_id = initialized
.headers()
.get("MCP-Session-Id")
.expect("initialize must mint a session")
.to_str()
.expect("session id is ASCII")
.to_owned();
let body = json_body(
post_jsonrpc_response(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session_id),
None,
json!({ "jsonrpc": "2.0", "id": 42, "method": "resources/templates/list", "params": {} }),
)
.await,
)
.await;
assert!(
body.get("result").is_none(),
"a legacy resources/templates/list on an uninitialized session must not be served: {body}"
);
assert_eq!(
error_code(&body),
-32002,
"the legacy initialized-session guard keeps its answer: {body}"
);
}
fn require_list_result_shape(
checks: &mut RevisionChecks,
body: &Value,
revision: &str,
what: &str,
) {
let Some(result) = checks.result(body, revision, what) else {
return;
};
if revision == LEGACY_REVISION {
for field in ["resultType", "ttlMs", "cacheScope"] {
checks.require(result.get(field).is_none(), || {
format!(
"the legacy {what} must keep its earlier shape without {field} on {revision}: {body}"
)
});
}
return;
}
checks.require(result["resultType"].as_str() == Some("complete"), || {
format!("a modern {what} must carry Result.resultType=\"complete\" on {revision}: {body}")
});
checks.require(
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|| format!("a modern {what} must carry CacheableResult.ttlMs on {revision}: {body}"),
);
checks.require(
matches!(
result.get("cacheScope").and_then(Value::as_str),
Some("public" | "private")
),
|| format!("a modern {what} must carry CacheableResult.cacheScope on {revision}: {body}"),
);
}
/// Opacity is not enough: a continuation is bound to this workspace+Agent+catalog revision+MCP
/// revision, so a malformed, cross-revision or cross-agent cursor is a safe invalid-params answer and
/// never mixes two pages.
#[tokio::test]
async fn list_rejects_malformed_cross_revision_and_cross_agent_cursors() {
let endpoint = standard_endpoint("list_cursor_scope").await;
let other = standard_endpoint("list_cursor_other_agent").await;
for revision in supported_revisions() {
let first =
json_body(list_resources(&endpoint, &revision, json!({ "limit": 1 })).await).await;
let cursor = result_of(&first, "bounded resources/list")["nextCursor"]
.as_str()
.unwrap_or_else(|| panic!("a bounded page must advertise a cursor: {first}"))
.to_owned();
let rejected = [
("malformed", "not-a-cursor".to_owned(), &revision),
("not base64", "%%%".to_owned(), &revision),
(
"forged scope",
forge_cursor_for_other_scope(&endpoint, &revision),
&revision,
),
];
for (what, cursor_value, requested_revision) in rejected {
let body = json_body(
list_resources(
&endpoint,
requested_revision,
json!({ "limit": 1, "cursor": cursor_value }),
)
.await,
)
.await;
assert!(
body.get("result").is_none(),
"a {what} cursor must not be served a page on {revision}: {body}"
);
assert_eq!(
error_code(&body),
-32602,
"a {what} cursor must be safe invalid params on {revision}: {body}"
);
}
// A cursor minted for another MCP revision is a different scope.
let cross_revision = if revision == LEGACY_REVISION {
MODERN_REVISION
} else {
LEGACY_REVISION
};
let body = json_body(
list_resources(
&endpoint,
cross_revision,
json!({ "limit": 1, "cursor": cursor.clone() }),
)
.await,
)
.await;
assert!(
body.get("result").is_none(),
"a cursor minted for {revision} must not page the {cross_revision} revision: {body}"
);
assert_eq!(
error_code(&body),
-32602,
"a cross-revision cursor must be safe invalid params: {body}"
);
}
// A cursor of another Agent is a different scope as well.
let foreign_cursor = {
let first =
json_body(list_resources(&other, MODERN_REVISION, json!({ "limit": 1 })).await).await;
result_of(&first, "other Agent bounded resources/list")["nextCursor"]
.as_str()
.unwrap_or_else(|| panic!("the other Agent must advertise a cursor: {first}"))
.to_owned()
};
let body = json_body(
list_resources(
&endpoint,
MODERN_REVISION,
json!({ "limit": 1, "cursor": foreign_cursor }),
)
.await,
)
.await;
assert!(
body.get("result").is_none(),
"a cursor of another Agent must never page this Agent's snapshot: {body}"
);
assert_eq!(
error_code(&body),
-32602,
"a cross-agent cursor must be safe invalid params: {body}"
);
}
/// A cursor whose scope fields are well-formed but name another catalog revision: the minimal opaque
/// continuation contract binds the catalog identity, so this is a stale continuation, not a page.
fn forge_cursor_for_other_scope(endpoint: &ResourceEndpoint, revision: &str) -> String {
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
let payload = json!({
"v": 1u8,
"w": "default",
"a": endpoint.agent_id.as_str(),
"c": "agent-version-1-catalog-revision-0",
"r": revision,
"o": 1usize,
});
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("cursor payload is serializable"))
}
/// Opacity + no duplicates + one catalog revision: the cursor is an opaque continuation, not a
/// Resource URI/id, and a bounded page never mixes or repeats entries.
#[tokio::test]
async fn list_pagination_is_an_opaque_continuation_over_the_same_catalog_revision() {
let endpoint = standard_endpoint("list_pagination").await;
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
for revision in supported_revisions() {
let first =
json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await;
let first_result = result_of(&first, &format!("bounded resources/list on {revision}"));
let first_uris = listed_uris(first_result);
assert_eq!(
first_uris.len(),
2,
"resources/list limit=2 must bound the page on {revision}, got {first}"
);
let cursor = first_result["nextCursor"]
.as_str()
.unwrap_or_else(|| {
panic!("a page with more bounded Resources must advertise nextCursor on {revision}: {first}")
})
.to_owned();
for opaque in expected.iter().map(String::as_str).chain([
endpoint.text.id.as_str(),
endpoint.json.id.as_str(),
endpoint.binary.id.as_str(),
]) {
assert!(
!cursor.contains(opaque),
"the pagination cursor must be opaque, not a Resource URI/id ({opaque}): {cursor}"
);
}
let second = json_body(
list_resources(
&endpoint,
&revision,
json!({ "limit": 2, "cursor": cursor }),
)
.await,
)
.await;
let second_result = result_of(&second, &format!("continued resources/list on {revision}"));
let mut all = first_uris;
all.extend(listed_uris(second_result));
assert_eq!(
all.len(),
expected.len(),
"the continuation must not repeat or skip Resources on {revision}: {all:?}"
);
assert_eq!(
all.into_iter().collect::<BTreeSet<_>>(),
expected,
"the union of both pages must be the bound snapshot on {revision}: {second}"
);
assert!(
second_result.get("nextCursor").is_none(),
"the last page must not advertise another cursor on {revision}: {second}"
);
}
}
/// Regression for the defect the Story 3.17 real-client smoke reproduced: with a *valid* published
/// Resource template bound to the exact published Agent snapshot, `resources/list` answered
/// `-32603`/HTTP 500 for the whole page, so no client could open the template parameter form.
///
/// A template is not an artifact-backed concrete Resource — its publication has no blob and its
/// concrete URIs are the expanded ones. So the page keeps answering exactly the earlier entries,
/// while the template stays discoverable through `resources/templates/list` with its typed
/// parameters, and it is never advertised as a downloadable Resource.
#[tokio::test]
async fn list_stays_available_when_a_published_template_is_bound() {
let endpoint = standard_endpoint("list_bound_template").await;
let registry = &endpoint.registry;
let published = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("published Agent snapshot must be readable")
.expect("published Agent version 1 must exist");
// A published Resource template (Story 3.10) pointing at the already published test Operation.
let template_id = ResourceId::new("res_list_bound_template");
let template_uri = "crank://templates/regions";
let template_source = TemplateSource::parse(&json!({
"operation_id": "op_crm_resources_probe",
"operation_version": 1,
"uri_template": "crank://regions/{region}",
"parameters": [{
"name": "region",
"input_path": "input.region",
"schema": { "type": "string", "required": true }
}],
"cache": { "ttl_ms": 60000, "vary": ["region"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
}))
.expect("template fixture must satisfy the Story 3.10 source contract");
let definition =
serde_json::to_string(&template_source).expect("normalized definition must serialize");
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: template_id.clone(),
uri: template_uri.to_owned(),
name: "regions".to_owned(),
description: "Published regions template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition,
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("template Draft must be created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: template_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("template exact version must publish");
// Mixed Agent snapshot: the three artifact-backed Resources plus the one template binding.
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 2;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("a new Agent Draft must be created for the mixed Resource bindings");
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
agent_version: 2,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &[
AgentResourceBinding {
resource_id: endpoint.text.id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: endpoint.json.id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: endpoint.binary.id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: template_id.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("the template binding must be saved next to the artifact-backed Resources");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: 2,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("the mixed Agent snapshot must publish");
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
if let Some(result) = checks.result(&body, &revision, "resources/list") {
let listed: BTreeSet<String> = listed_uris(result).into_iter().collect();
checks.require(listed == expected, || {
format!(
"a bound published template must not break or change resources/list on {revision}: {body}"
)
});
checks.require(!listed.contains(template_uri), || {
format!(
"a template must not be advertised as a concrete Resource on {revision}: {body}"
)
});
}
let templates = json_body(list_resource_templates(&endpoint, &revision).await).await;
if let Some(result) = checks.result(&templates, &revision, "resources/templates/list") {
let advertised = result["resourceTemplates"]
.as_array()
.map(|items| {
items
.iter()
.find(|item| {
item["uriTemplate"].as_str() == Some("crank://regions/{region}")
})
.cloned()
})
.unwrap_or(None);
match advertised {
Some(template) => checks.require(
template["parameters"][0]["name"].as_str() == Some("region")
&& template["mimeType"].as_str() == Some("application/json"),
|| {
format!(
"template discovery must keep its typed parameters on {revision}: {template}"
)
},
),
None => checks.require(false, || {
format!(
"the bound template must stay discoverable on {revision}: {templates}"
)
}),
}
}
// Mixed pagination: the template binding must neither fail a page nor duplicate/skip entries.
let first =
json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await;
let Some(first_result) = checks.result(&first, &revision, "bounded resources/list") else {
continue;
};
let mut union: Vec<String> = listed_uris(first_result);
let mut next = first_result["nextCursor"].as_str().map(str::to_owned);
while let Some(cursor) = next {
let page = json_body(
list_resources(
&endpoint,
&revision,
json!({ "limit": 2, "cursor": cursor }),
)
.await,
)
.await;
let Some(page_result) = checks.result(&page, &revision, "continued resources/list")
else {
break;
};
union.extend(listed_uris(page_result));
next = page_result["nextCursor"].as_str().map(str::to_owned);
}
checks.require(
union.iter().cloned().collect::<BTreeSet<_>>() == expected
&& union.len() == expected.len(),
|| {
format!(
"mixed pagination must neither skip nor repeat Resources on {revision}: {union:?}"
)
},
);
}
checks.finish();
// Integrity is still enforced for a template admission: a publication whose digest no longer
// matches its own definition must fail the page instead of silently dropping the entry.
sqlx::query(
"update resource_publications set digest = $4
where workspace_id = $1 and resource_id = $2 and version = $3",
)
.bind(test_workspace_id().as_str())
.bind(template_id.as_str())
.bind(1_i32)
.bind("0".repeat(64))
.execute(registry.pool())
.await
.expect("test-owned template publication metadata must be corruptible");
let corrupted = json_body(list_resources(&endpoint, MODERN_REVISION, json!({})).await).await;
assert!(
corrupted.get("result").is_none(),
"a corrupt template publication must fail the page, not answer a partial success: {corrupted}"
);
assert_eq!(
error_code(&corrupted),
-32603,
"a corrupt template publication must stay an internal error: {corrupted}"
);
}
@@ -0,0 +1,939 @@
use super::*;
use base64::Engine as _;
use std::sync::Arc;
#[path = "template_discovery_binary.rs"]
mod binary_fixture;
use binary_fixture::{TestValkey, publish_binary_template};
async fn template_order_lookup(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
) -> AxumJson<Value> {
calls.fetch_add(1, Ordering::SeqCst);
if order_id == "00000000-0000-4000-8000-000000000001" {
tokio::time::sleep(std::time::Duration::from_millis(600)).await;
}
AxumJson(json!({ "id": order_id, "order_id": order_id, "status": "found" }))
}
async fn template_binary_lookup(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
headers: axum::http::HeaderMap,
) -> Response<Body> {
use base64::Engine as _;
calls.fetch_add(1, Ordering::SeqCst);
if headers
.get("authorization")
.and_then(|value| value.to_str().ok())
!= Some("Bearer story311-test-token")
{
return Response::builder()
.status(401)
.header("content-type", "application/json")
.body(Body::from(r#"{"error":"unauthorized"}"#))
.unwrap();
}
let payload = if order_id.ends_with("d481") {
json!({ "data_base64": "not-base64" })
} else if order_id.ends_with("d482") {
json!({ "data_base64": "AA==", "extra": "not-allowed" })
} else if order_id.ends_with("d484") {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_537])
})
} else if order_id.ends_with("d485") {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_536])
})
} else {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode([0_u8, 255, 1, 253, 254, 255])
})
};
let mime = if order_id.ends_with("d483") {
"text/plain"
} else {
"application/json"
};
Response::builder()
.status(200)
.header("content-type", mime)
.body(Body::from(serde_json::to_vec(&payload).unwrap()))
.unwrap()
}
async fn template_order_head(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
) -> Response<Body> {
calls.fetch_add(1, Ordering::SeqCst);
Response::builder()
.status(200)
.header("x_order_id", order_id)
.body(Body::empty())
.unwrap()
}
#[path = "template_discovery_cache_loss.rs"]
mod cache_loss;
/// Regression oracle for Story 3.11: a real, exact-version template bound to the published Agent
/// must be discoverable, rather than being confused with the empty-template positive control.
#[tokio::test]
async fn published_agent_discovers_its_bound_template_on_supported_revisions() {
let (valkey, port) = TestValkey::start();
let cache = Arc::new(
crank_runtime::RedisCacheStore::connect(
crank_core::CacheBackend::Valkey,
&format!("redis://127.0.0.1:{port}/0"),
)
.await
.expect("runtime must connect to test-owned Valkey"),
);
let endpoint = standard_endpoint_with_cache("bound_template_discovery", Some(cache)).await;
let registry: &PostgresRegistry = &endpoint.registry;
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("test upstream must bind a loopback port");
let upstream_address = upstream_listener.local_addr().unwrap();
let upstream_calls = Arc::new(AtomicUsize::new(0));
let upstream = axum::Router::new()
.route("/orders/{order_id}", get(template_order_lookup))
.route("/orders-binary/{order_id}", get(template_binary_lookup))
.route("/order-metadata/{order_id}", head(template_order_head))
.with_state(Arc::clone(&upstream_calls));
tokio::spawn(async move {
axum::serve(upstream_listener, upstream)
.await
.expect("test upstream must serve");
});
let mut operation = test_operation(&format!("http://{upstream_address}"), "bound_order_lookup");
operation.target = Target::Rest(RestTarget {
base_url: format!("http://{upstream_address}"),
method: HttpMethod::Get,
path_template: "/orders/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("order_id");
operation
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
operation.execution_config.timeout_ms = 300;
operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.order_id".to_owned(),
target: "$.request.path.order_id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("GET Read operation must be created through registry API");
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
.expect("GET Read operation exact version must publish");
let published = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("published Agent snapshot must be readable")
.expect("published Agent version 1 must exist");
let operation_id = operation.id.to_string();
let resource_id = ResourceId::new("res_bound_template_discovery");
let uri = "crank://orders/{order_id}";
let head_uri = "crank://orders-metadata/{order_id}";
let definition_value = json!({
"operation_id": operation_id,
"operation_version": 1,
"uri_template": uri,
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "format": "uuid" }
}],
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
});
let normalized_source = TemplateSource::parse(&definition_value)
.expect("template fixture must satisfy the Story 3.10 source contract");
let definition = serde_json::to_string(&normalized_source)
.expect("normalized definition must serialize canonically");
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: "crank://templates/order-lookup".to_owned(),
name: "order_lookup".to_owned(),
description: "Published order lookup template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition.clone(),
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("template Draft must be created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest.clone(),
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("template exact version must publish");
let mut head_operation = test_operation(
&format!("http://{upstream_address}"),
"bound_order_metadata",
);
head_operation.id = OperationId::new("op_bound_order_metadata");
head_operation.target = Target::Rest(RestTarget {
base_url: format!("http://{upstream_address}"),
method: HttpMethod::Head,
path_template: "/order-metadata/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: vec![RestResponseDescriptor {
status_code: 200,
media_type: None,
schema_variant: 0,
}],
multipart_field_mime_types: Default::default(),
});
head_operation.input_schema = object_schema("order_id");
head_operation
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
head_operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.order_id".to_owned(),
target: "$.request.path.order_id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
head_operation
.output_schema
.fields
.get_mut("id")
.unwrap()
.kind = SchemaKind::Number;
head_operation.output_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.response.data.status".to_owned(),
target: "$.output.id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
head_operation.execution_config.timeout_ms = 300;
head_operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
registry
.create_operation(&test_workspace_id(), &head_operation, Some("alice"))
.await
.expect("HEAD Read operation must be created");
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &head_operation.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
})
.await
.expect("HEAD Read operation must publish");
let head_resource_id = ResourceId::new("res_bound_template_head");
let head_definition_value = json!({
"operation_id": head_operation.id.as_str(), "operation_version": 1,
"uri_template": head_uri,
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536}, "failure":{"outcome":"error"}
});
let head_source = TemplateSource::parse(&head_definition_value)
.expect("HEAD metadata definition must be valid");
let head_definition = serde_json::to_string(&head_source).unwrap();
let head_digest = format!("{:x}", Sha256::digest(head_definition.as_bytes()));
let head_draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: head_resource_id.clone(),
uri: "crank://templates/order-metadata".to_owned(),
name: "order_metadata".to_owned(),
description: "Published order metadata template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: head_definition,
definition_digest: head_digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("HEAD template Draft must be created");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: head_resource_id.clone(),
expected_updated_at: head_draft.snapshot.resource.updated_at,
expected_version: head_draft.snapshot.version.version,
expected_digest: head_digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("HEAD template must be published");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 2;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("a new Agent Draft must be created for the exact template binding");
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
agent_version: 2,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &[
AgentResourceBinding {
resource_id: resource_id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: head_resource_id.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("exact template version must be bound to the Agent Draft");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: 2,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent snapshot with the exact template binding must publish");
let unbound_id = ResourceId::new("res_unbound_template");
let mut unbound_json = definition_value.clone();
unbound_json["uri_template"] = json!("crank://other-orders/{order_id}");
let unbound_source =
TemplateSource::parse(&unbound_json).expect("unbound template definition remains valid");
let unbound_definition = serde_json::to_string(&unbound_source).unwrap();
let unbound_digest = format!("{:x}", Sha256::digest(unbound_definition.as_bytes()));
let unbound_draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: unbound_id.clone(),
uri: "crank://templates/unbound-order".to_owned(),
name: "unbound_order".to_owned(),
description: "Published but not bound".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: unbound_definition.clone(),
definition_digest: unbound_digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("unbound template Draft must be created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: unbound_id,
expected_updated_at: unbound_draft.snapshot.resource.updated_at,
expected_version: unbound_draft.snapshot.version.version,
expected_digest: unbound_digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("unbound template must be published without an Agent binding");
// Prove the fixture is a real exact-version Published template binding before MCP is called.
let (publication, stored_definition) = registry
.resolve_resource_template_publication(test_workspace_id().as_str(), &resource_id, 1)
.await
.expect("the exact Published template source must resolve");
assert_eq!(publication.source_kind, "template");
assert_eq!(publication.version, 1);
assert_eq!(stored_definition.definition_json, definition);
assert_eq!(stored_definition.definition_digest, digest);
assert_eq!(
TemplateSource::parse(
&serde_json::from_str(&stored_definition.definition_json)
.expect("stored definition must remain JSON")
)
.expect("stored definition must remain normalized and valid"),
normalized_source
);
let published_operation = registry
.get_operation_version(&test_workspace_id(), &operation.id, 1)
.await
.expect("the exact Published Read Operation must be readable")
.expect("the exact operation version must exist");
assert_eq!(
published_operation.status,
crank_core::OperationStatus::Published
);
assert_eq!(published_operation.version, 1);
assert!(matches!(
&published_operation.snapshot.target,
Target::Rest(target)
if target.method == HttpMethod::Get
&& target.path_template == "/orders/{order_id}"
));
assert_eq!(
published_operation
.snapshot
.execution_config
.safety
.as_ref()
.map(|policy| policy.class),
Some(OperationSafetyClass::Read),
"the pinned operation must be explicitly classified as Read"
);
assert!(
published_operation
.snapshot
.execution_config
.approval_policy
.is_none(),
"the pinned Read operation must not require approval"
);
assert_eq!(
published_operation.snapshot.input_schema.fields["order_id"]
.format
.as_deref(),
Some("uuid"),
"the published input schema must match the template parameter"
);
let exact_published_agent = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 2)
.await
.expect("published Agent snapshot must be readable")
.expect("the bound Agent version must exist");
assert_eq!(
exact_published_agent.snapshot.status,
AgentStatus::Published,
"the binding must belong to a Published Agent snapshot"
);
assert_eq!(exact_published_agent.snapshot.version, 2);
assert_eq!(
exact_published_agent.resource_bindings,
vec![
AgentResourceBinding {
resource_id: resource_id.clone(),
resource_version: 1
},
AgentResourceBinding {
resource_id: head_resource_id.clone(),
resource_version: 1
},
],
"the fixture must bind the exact template version"
);
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let response = list_resource_templates(&endpoint, &revision).await;
let status = response.status();
let body = json_body(response).await;
println!("template discovery {revision}: HTTP {status} {body}");
checks.require(status == reqwest::StatusCode::OK, || {
format!("template discovery HTTP status on {revision}: HTTP {status} {body}")
});
let Some(result) = checks.result(&body, &revision, "resources/templates/list") else {
continue;
};
require_list_result_shape(&mut checks, &body, &revision, "resources/templates/list");
let Some(templates) = result.get("resourceTemplates").and_then(Value::as_array) else {
checks.require(false, || {
format!(
"resources/templates/list must return resourceTemplates on {revision}: {body}"
)
});
continue;
};
checks.require(templates.len() == 2, || {
format!("the exact bound Published templates must be listed on {revision}: {body}")
});
checks.require(
templates
.iter()
.any(|template| template["uriTemplate"] == head_uri),
|| format!("the bound HEAD metadata template must be listed on {revision}: {body}"),
);
checks.require(result.get("nextCursor").is_none(), || {
format!("a complete template page must not advertise nextCursor on {revision}: {body}")
});
if let Some(template) = templates.first() {
for (field, expected) in [
("uriTemplate", json!(uri)),
("name", json!("order_lookup")),
("mimeType", json!("application/json")),
("description", json!("Published order lookup template")),
] {
checks.require(template.get(field) == Some(&expected), || {
format!(
"template {field} must match the published definition on {revision}: {body}"
)
});
}
}
let mut cursor: Option<String> = None;
let mut paged_templates = Vec::new();
for _ in 0..10 {
let params = cursor.as_ref().map_or_else(
|| json!({ "limit": 1 }),
|cursor| json!({ "limit": 1, "cursor": cursor }),
);
let body =
json_body(list_resource_templates_with_params(&endpoint, &revision, params).await)
.await;
let Some(result) = body.get("result") else {
panic!("template page failed on {revision}: {body}");
};
paged_templates.extend(result["resourceTemplates"].as_array().unwrap().clone());
cursor = result
.get("nextCursor")
.and_then(Value::as_str)
.map(str::to_owned);
if cursor.is_none() {
break;
}
}
assert_eq!(
paged_templates.len(),
2,
"pagination must eventually yield both bound templates on {revision}: {paged_templates:?}"
);
let paged_uris: BTreeSet<String> = paged_templates
.iter()
.filter_map(|item| item["uriTemplate"].as_str().map(str::to_owned))
.collect();
assert_eq!(
paged_uris,
BTreeSet::from([uri.to_owned(), head_uri.to_owned()])
);
let invalid_cursor = json_body(
list_resource_templates_with_params(
&endpoint,
&revision,
json!({"cursor":"not-a-valid-cursor"}),
)
.await,
)
.await;
checks.require(invalid_cursor.get("result").is_none() && invalid_cursor["error"]["code"].as_i64() == Some(-32602), || {
format!("template list must reject a malformed scoped cursor on {revision}: {invalid_cursor}")
});
}
let (binary_template, auth_profile_id) = publish_binary_template(
registry,
&endpoint.agent_id,
&format!("http://{upstream_address}"),
)
.await;
let binary_bytes = [0_u8, 255, 1, 253, 254, 255];
let mut binary_cache_warmed = false;
for revision in supported_revisions() {
let exact_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
let binary_calls_before = upstream_calls.load(Ordering::SeqCst);
let body = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
assert!(
body.get("error").is_none(),
"declared binary runtime read failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], exact_uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(content["blob"].as_str().unwrap())
.unwrap(),
binary_bytes,
"binary Resource wire bytes must exactly match the REST output on {revision}"
);
assert!(
content.get("text").is_none(),
"binary content must not be represented as text"
);
let expected_calls = binary_calls_before + usize::from(!binary_cache_warmed);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the binary read must be fetched once, then served from cache across revisions"
);
binary_cache_warmed = true;
let cached = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
assert_eq!(cached["result"]["contents"][0]["blob"], content["blob"]);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the authenticated binary read must hit its own cache on {revision}"
);
let boundary_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d485";
let boundary =
json_body(read_resource(&endpoint, &revision, boundary_uri, None).await).await;
let boundary_bytes = base64::engine::general_purpose::STANDARD
.decode(boundary["result"]["contents"][0]["blob"].as_str().unwrap())
.unwrap();
assert_eq!(
boundary_bytes.len(),
65_536,
"max_bytes boundary is inclusive on {revision}"
);
for (case, uri) in [
(
"malformed base64",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d481",
),
(
"unexpected field",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d482",
),
(
"wrong MIME",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d483",
),
(
"oversize body",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d484",
),
] {
let uri = if revision == MODERN_REVISION {
uri.to_owned()
} else {
uri.replace("4372", "4373")
};
let calls_before_negative = upstream_calls.load(Ordering::SeqCst);
let rejected = json_body(read_resource(&endpoint, &revision, &uri, None).await).await;
assert!(
rejected.get("result").is_none() && rejected.get("error").is_some(),
"{case} binary result must fail closed on {revision}: {rejected}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_negative + 1,
"{case} case must reach the REST response mapper on {revision}: {uri}"
);
}
}
let calls_before_auth_profile_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let cached = json_body(
read_resource(
&endpoint,
&revision,
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
None,
)
.await,
)
.await;
assert!(
cached.get("result").is_some(),
"the exact AuthProfile-backed response must be cached before revoke on {revision}: {cached}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_auth_profile_cache_confirmation,
"the pre-revoke control must hit the live AuthProfile-backed cache on {revision}"
);
}
let calls_before_auth_profile_revoke = upstream_calls.load(Ordering::SeqCst);
sqlx::query("delete from auth_profiles where id = $1")
.bind(auth_profile_id.as_str())
.execute(registry.pool())
.await
.expect("the test-owned pinned AuthProfile is revoked");
for revision in supported_revisions() {
let uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
let revoked = json_body(read_resource(&endpoint, &revision, uri, None).await).await;
assert!(
revoked.get("result").is_none(),
"a missing pinned AuthProfile must fail closed before returning cache on {revision}: {revoked}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_auth_profile_revoke,
"revoking the pinned AuthProfile must prevent both cached return and REST dispatch"
);
}
assert_eq!(binary_template, "crank://orders-binary/{order_id}");
let order_id = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
let expanded_uri = format!("crank://orders/{order_id}");
let mut successful_reads = upstream_calls.load(Ordering::SeqCst);
let mut text_cache_filled = false;
for revision in supported_revisions() {
let response = read_resource(&endpoint, &revision, &expanded_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"dynamic template read failed on {revision}: {body}"
);
let contents = body["result"]["contents"][0]["text"]
.as_str()
.expect("JSON result must be returned as text content");
let output: Value =
serde_json::from_str(contents).expect("the upstream JSON must remain JSON content");
assert_eq!(output["id"], order_id);
assert_eq!(body["result"]["contents"][0]["uri"], expanded_uri);
if !text_cache_filled {
successful_reads += 1;
text_cache_filled = true;
}
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"the second protocol revision must return the populated cache entry without another REST call"
);
let expanded_head_uri = format!("crank://orders-metadata/{order_id}");
let response = read_resource(&endpoint, &revision, &expanded_head_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"HEAD metadata mapping failed on {revision}: {body}"
);
let contents = body["result"]["contents"][0]["text"]
.as_str()
.unwrap_or_else(|| {
panic!("explicit HEAD metadata response must contain JSON text: {body}")
});
let metadata: Value =
serde_json::from_str(contents).expect("the explicit metadata mapping remains JSON");
assert_eq!(metadata["id"], 200);
successful_reads += 1;
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads);
let traversal = "crank://orders/%2e%2e";
let body = json_body(read_resource(&endpoint, &revision, traversal, None).await).await;
assert!(
body.get("result").is_none(),
"traversal-shaped template URI must not be served on {revision}: {body}"
);
let host_injection = format!("crank://127.0.0.1/orders/{order_id}");
let body =
json_body(read_resource(&endpoint, &revision, &host_injection, None).await).await;
assert!(
body.get("result").is_none(),
"URI authority must remain fixed on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"host injection must be rejected before REST dispatch"
);
let invalid_uuid = "crank://orders/not-a-uuid";
let body = json_body(read_resource(&endpoint, &revision, invalid_uuid, None).await).await;
assert!(
body.get("result").is_none(),
"URI parameters must satisfy the exact published input schema on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"invalid URI values must be rejected before REST dispatch"
);
}
let timeout_uuid = "00000000-0000-4000-8000-000000000001";
let timeout_uri = format!("crank://orders/{timeout_uuid}");
let response = read_resource(&endpoint, MODERN_REVISION, &timeout_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"runtime failures must use an MCP error response: {body}"
);
assert!(body.get("result").is_none());
assert!(
body["error"]["data"]["request_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert!(
body["error"]["data"]["trace_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
for field in ["error_code", "stage", "retryability", "outcome_certainty"] {
assert!(
body["error"]["data"][field]
.as_str()
.is_some_and(|value| !value.is_empty()),
"structured runtime error must include {field}: {body}"
);
}
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads + 1);
assert!(!body.to_string().contains(timeout_uuid));
assert!(!body.to_string().contains("127.0.0.1"));
let calls_before_operation_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let cached =
json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
cached.get("result").is_some(),
"the exact Operation response must be available from cache before archive on {revision}: {cached}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_operation_cache_confirmation,
"the pre-archive control must hit the existing cache on {revision}"
);
}
let calls_before_operation_archive = upstream_calls.load(Ordering::SeqCst);
registry
.archive_operation(
&test_workspace_id(),
&operation.id,
&OffsetDateTime::now_utc(),
)
.await
.expect("the exact pinned Operation must be archivable for the stale-snapshot regression");
for revision in supported_revisions() {
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
body.get("result").is_none(),
"an archived source Operation must fail closed on {revision}: {body}"
);
assert!(
body["error"]["data"]["request_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert!(
body["error"]["data"]["trace_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_operation_archive,
"an archived Operation must not return its live Valkey cache entry or dispatch"
);
}
// Keep an independent published HEAD Operation eligible to verify real Valkey-loss fallback.
let calls_before_valkey_loss = upstream_calls.load(Ordering::SeqCst);
valkey.stop();
let fallback_uri = format!("crank://orders-metadata/{order_id}");
let fallback =
json_body(read_resource(&endpoint, MODERN_REVISION, &fallback_uri, None).await).await;
let fallback_text = fallback["result"]["contents"][0]["text"]
.as_str()
.expect("cache-loss fallback must preserve the declared HEAD metadata representation");
let fallback_output: Value = serde_json::from_str(fallback_text).unwrap();
assert_eq!(fallback_output["id"], 200);
assert_eq!(fallback["result"]["contents"][0]["uri"], fallback_uri);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_valkey_loss + 1,
"Valkey loss must use the eligible HEAD Operation's uncached REST path"
);
checks.finish();
// A live revoke must remove the exact template binding from future discovery.
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-list', 'story311-list')")
.bind(resource_id.as_str()).execute(registry.pool()).await
.expect("the fixture revoke must be persisted");
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-head-list', 'story311-head-list')")
.bind(head_resource_id.as_str()).execute(registry.pool()).await
.expect("the HEAD template revoke must be persisted");
let calls_after_revoke = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let body = json_body(list_resource_templates(&endpoint, &revision).await).await;
assert!(
body["result"]["resourceTemplates"]
.as_array()
.is_some_and(|items| {
items.len() == 1 && items[0]["uriTemplate"] == binary_template
}),
"revoked text templates must disappear while the independent binary template remains on {revision}: {body}"
);
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
body.get("result").is_none(),
"a revoked template must not be read on {revision}: {body}"
);
let revoked_head_uri = format!("crank://orders-metadata/{order_id}");
let body =
json_body(read_resource(&endpoint, &revision, &revoked_head_uri, None).await).await;
assert!(
body.get("result").is_none(),
"revoked HEAD metadata must not be read on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_after_revoke,
"revoked template read must not dispatch"
);
}
}
@@ -0,0 +1,308 @@
use super::*;
use std::process::Command;
pub(super) struct TestValkey(String);
impl TestValkey {
pub(super) fn start() -> (Self, u16) {
let output = Command::new("docker")
.args([
"run",
"--detach",
"--publish",
"127.0.0.1::6379",
"valkey/valkey:8-alpine",
])
.output()
.expect("Docker CLI must start the test-owned Valkey container");
assert!(
output.status.success(),
"test-owned Valkey must start: {}",
String::from_utf8_lossy(&output.stderr)
);
let id = String::from_utf8(output.stdout)
.expect("Docker container id must be UTF-8")
.trim()
.to_owned();
let valkey = Self(id);
let port_output = Command::new("docker")
.args(["port", &valkey.0, "6379/tcp"])
.output()
.expect("Docker CLI must report the test-owned port");
assert!(
port_output.status.success(),
"test-owned Valkey port must be available"
);
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
let port = address
.trim()
.rsplit(':')
.next()
.unwrap()
.parse()
.expect("Docker mapped port must be numeric");
(valkey, port)
}
pub(super) fn stop(&self) {
let output = Command::new("docker")
.args(["stop", &self.0])
.output()
.expect("Docker CLI must stop the test-owned Valkey");
assert!(output.status.success(), "test-owned Valkey must stop");
}
}
impl Drop for TestValkey {
fn drop(&mut self) {
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
}
}
pub(super) async fn publish_binary_template(
registry: &PostgresRegistry,
agent_id: &crank_core::AgentId,
base_url: &str,
) -> (String, crank_core::AuthProfileId) {
let now = OffsetDateTime::now_utc();
let secret_id = crank_core::SecretId::new("secret_story311_binary_test");
let secret = crank_core::Secret {
id: secret_id.clone(),
workspace_id: test_workspace_id(),
name: "story311 binary test credential".to_owned(),
kind: crank_core::SecretKind::Token,
status: crank_core::SecretStatus::Active,
current_version: 1,
created_at: now,
updated_at: now,
last_used_at: None,
};
let crypto =
crank_runtime::SecretCrypto::new("test-master-key-00000000000000000000000000000000")
.unwrap();
registry
.verify_or_register_master_key_identity(crank_registry::MasterKeyIdentityCandidate {
epoch: crypto.master_key_epoch(),
fingerprint: crypto.master_key_fingerprint(),
cipher_contract: crank_registry::MASTER_KEY_CIPHER_CONTRACT,
observed_at: &now,
})
.await
.expect("the test runtime master-key identity must be registered");
let ciphertext = crypto
.encrypt(&json!({"token":"story311-test-token"}))
.unwrap();
registry
.create_secret(crank_registry::CreateSecretRequest {
secret: &secret,
ciphertext: &ciphertext,
key_version: crypto.key_version(),
master_key_epoch: crypto.master_key_epoch(),
created_by: None,
})
.await
.expect("test-owned binary auth secret must be persisted encrypted");
let auth_profile_id = crank_core::AuthProfileId::new("auth_story311_binary_test");
let auth_profile = crank_core::AuthProfile {
id: auth_profile_id.clone(),
workspace_id: test_workspace_id(),
name: "story311 binary test auth".to_owned(),
kind: crank_core::AuthKind::Bearer,
config: crank_core::AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id,
}),
created_at: now,
updated_at: now,
};
registry
.save_auth_profile(crank_registry::SaveAuthProfileRequest {
workspace_id: &test_workspace_id(),
profile: &auth_profile,
})
.await
.expect("test auth profile must be saved in its workspace");
let mut operation = test_operation(base_url, "bound_order_binary");
operation.id = OperationId::new("op_bound_order_binary");
operation.target = Target::Rest(RestTarget {
base_url: base_url.to_owned(),
method: HttpMethod::Get,
path_template: "/orders-binary/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: vec![RestResponseDescriptor {
status_code: 200,
media_type: Some("application/json".to_owned()),
schema_variant: 0,
}],
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("order_id");
operation
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.order_id".to_owned(),
target: "$.request.path.order_id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
let mut output_schema = object_schema("data_base64");
output_schema.fields.insert(
"extra".to_owned(),
output_schema.fields["data_base64"].clone(),
);
output_schema.fields.get_mut("extra").unwrap().required = false;
operation.output_schema = output_schema;
operation.output_mapping = MappingSet {
rules: vec![
MappingRule {
source: "$.response.body.data_base64".to_owned(),
target: "$.output.data_base64".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
},
MappingRule {
source: "$.response.body.extra".to_owned(),
target: "$.output.extra".to_owned(),
required: false,
default_value: None,
transform: None,
condition: None,
notes: None,
},
],
};
operation.execution_config.timeout_ms = 1_000;
operation.execution_config.auth_profile_ref = Some(auth_profile_id.clone());
operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("binary GET Read operation must be created");
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
.expect("binary operation must publish");
let uri_template = "crank://orders-binary/{order_id}";
let definition_value = json!({
"operation_id": operation.id.as_str(),
"operation_version": 1,
"uri_template": uri_template,
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536},
"failure": {"outcome":"error"}
});
let source = TemplateSource::parse(&definition_value).expect("binary template source is valid");
let definition = serde_json::to_string(&source).unwrap();
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let resource_id = ResourceId::new("res_bound_template_binary");
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: "crank://templates/order-binary".to_owned(),
name: "order_binary".to_owned(),
description: "Published binary order representation".to_owned(),
kind: "binary".to_owned(),
mime_type: "application/pdf".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition,
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("binary template Draft must be created");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("binary template must publish");
let published = registry
.get_agent_version(&test_workspace_id(), agent_id, 2)
.await
.expect("version two agent must remain readable")
.expect("version two agent must be published");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 3;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("binary binding draft version must create");
let existing_publications: Vec<(String, i32)> = sqlx::query_as(
"select resource_id, version from resource_publications where workspace_id = $1 and resource_id in ('res_bound_template_discovery', 'res_bound_template_head', 'res_bound_template_binary')",
)
.bind(test_workspace_id().as_str())
.fetch_all(registry.pool())
.await
.expect("published Resource versions must be discoverable for the Agent fixture");
let resource_bindings: Vec<AgentResourceBinding> = existing_publications
.into_iter()
.map(|(resource_id, resource_version)| AgentResourceBinding {
resource_id: ResourceId::new(resource_id),
resource_version: resource_version as u32,
})
.collect();
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id,
agent_version: 3,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &resource_bindings,
expected_state: None,
})
.await
.expect("exact binary template version must bind to the Agent draft");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: 3,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent snapshot with binary binding must publish");
(uri_template.to_owned(), auth_profile_id)
}
@@ -0,0 +1,150 @@
use super::*;
/// A live cache hit must fall back to the exact REST read when the test-owned Valkey is lost.
#[tokio::test]
async fn eligible_get_resource_reads_uncached_after_valkey_loss() {
let (valkey, port) = TestValkey::start();
let cache = Arc::new(
crank_runtime::RedisCacheStore::connect(
crank_core::CacheBackend::Valkey,
&format!("redis://127.0.0.1:{port}/0"),
)
.await
.expect("runtime must connect to test-owned Valkey"),
);
let endpoint = standard_endpoint_with_cache("uncached_after_valkey_loss", Some(cache)).await;
let registry = &endpoint.registry;
let published = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("published Agent snapshot must be readable")
.expect("published Agent version 1 must exist");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 2;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("Agent version two Draft must be created for the template fixture");
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
agent_version: 2,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &[],
expected_state: None,
})
.await
.expect("Agent version two catalog must be saved");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: 2,
published_at: &now,
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent version two must be published for the template fixture");
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("test upstream must bind a loopback port");
let upstream_address = upstream_listener.local_addr().unwrap();
let upstream_calls = Arc::new(AtomicUsize::new(0));
let upstream = axum::Router::new()
.route("/orders-binary/{order_id}", get(template_binary_lookup))
.with_state(Arc::clone(&upstream_calls));
tokio::spawn(async move {
axum::serve(upstream_listener, upstream)
.await
.expect("test upstream must serve");
});
let (template, _auth_profile_id) = publish_binary_template(
&endpoint.registry,
&endpoint.agent_id,
&format!("http://{upstream_address}"),
)
.await;
assert_eq!(template, "crank://orders-binary/{order_id}");
let expected_bytes = [0_u8, 255, 1, 253, 254, 255];
let revision_uris = [
(
MODERN_REVISION,
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
),
(
LEGACY_REVISION,
"crank://orders-binary/f47ac10b-58cc-4373-a567-0e02b2c3d480",
),
];
for (revision, uri) in revision_uris {
let before_first_read = upstream_calls.load(Ordering::SeqCst);
for expected_calls in [before_first_read + 1, before_first_read + 1] {
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
assert!(
body.get("error").is_none(),
"eligible GET failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(
content["blob"]
.as_str()
.expect("binary response must carry a blob")
)
.expect("binary response must be valid base64"),
expected_bytes,
"REST bytes must remain exact on {revision}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the initial REST read increments once and its live-Valkey repeat is a hit on {revision}"
);
}
}
valkey.stop();
for (revision, uri) in revision_uris {
let before_read = upstream_calls.load(Ordering::SeqCst);
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
assert!(
body.get("error").is_none(),
"eligible uncached GET failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(
content["blob"]
.as_str()
.expect("binary response must carry a blob")
)
.expect("binary response must be valid base64"),
expected_bytes,
"REST bytes must remain exact after Valkey loss on {revision}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
before_read + 1,
"the exact eligible URI must use REST when Valkey is unavailable on {revision}"
);
}
}
@@ -0,0 +1,213 @@
//! Story 3.8 AC02 / AT-3.8-02: `resources/read` returns the exact published text/JSON/binary content
//! and MIME in the negotiated shape, with Request ID/Trace ID preserved and no content capture in
//! telemetry.
use serde_json::Value;
use super::fixtures::*;
#[allow(clippy::too_many_arguments)]
fn check_content(
checks: &mut RevisionChecks,
body: &Value,
revision: &str,
uri: &str,
expected_text: Option<&str>,
expected_blob: Option<&str>,
mime: &str,
) {
let Some(result) = checks.result(body, revision, "resources/read") else {
return;
};
if revision != LEGACY_REVISION {
// The pinned 2026-07-28 schema: `ReadResourceResult extends CacheableResult`.
checks.require(result["resultType"].as_str() == Some("complete"), || {
format!("a modern read result must carry Result.resultType=\"complete\" on {revision}: {body}")
});
checks.require(
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|| {
format!(
"a modern read result must carry CacheableResult.ttlMs on {revision}: {body}"
)
},
);
checks.require(
matches!(result.get("cacheScope").and_then(Value::as_str), Some("public" | "private")),
|| format!("a modern read result must carry CacheableResult.cacheScope on {revision}: {body}"),
);
}
let Some(contents) = result["contents"].as_array() else {
checks.require(false, || {
format!("resources/read must return contents[] on {revision}: {body}")
});
return;
};
checks.require(contents.len() == 1, || {
format!("an exact published static version must yield exactly one content entry on {revision}: {body}")
});
let Some(content) = contents.first() else {
return;
};
checks.require(content["uri"].as_str() == Some(uri), || {
format!("the read content must address the requested published URI on {revision}: {body}")
});
checks.require(content["mimeType"].as_str() == Some(mime), || {
format!("the read must return the published MIME type {mime} on {revision}: {body}")
});
if let Some(expected_text) = expected_text {
checks.require(content["text"].as_str() == Some(expected_text), || {
format!("the read must return the exact published text bytes on {revision}: {body}")
});
checks.require(content.get("blob").is_none(), || {
format!(
"a text/JSON Resource must not be converted to a base64 blob on {revision}: {body}"
)
});
}
if let Some(expected_blob) = expected_blob {
checks.require(content["blob"].as_str() == Some(expected_blob), || {
format!(
"a binary Resource must be returned as the exact base64 blob on {revision}: {body}"
)
});
checks.require(content.get("text").is_none(), || {
format!(
"binary bytes that happen to be valid UTF-8 must still be a blob (no sniffing) on {revision}: {body}"
)
});
}
}
#[tokio::test]
async fn read_serves_the_exact_published_text_for_every_supported_revision() {
let endpoint = standard_endpoint("read_text").await;
let expected = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let body =
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
check_content(
&mut checks,
&body,
&revision,
&endpoint.text.uri,
Some(&expected),
None,
"text/plain",
);
}
checks.finish();
}
/// The typed kind decides the wire conversion: text/JSON => `text`, binary => `blob` base64, with no
/// content sniffing (the binary fixture bytes are valid UTF-8 on purpose).
#[tokio::test]
async fn read_converts_json_to_text_and_binary_to_base64_without_sniffing() {
let endpoint = standard_endpoint("read_kinds").await;
let json_text = String::from_utf8(endpoint.json.bytes.clone()).expect("JSON fixture is UTF-8");
let json_blob = base64_of(&endpoint.json.bytes);
let binary_blob = base64_of(&endpoint.binary.bytes);
assert_ne!(
json_blob, binary_blob,
"the two fixtures must differ so a wrong content cannot pass"
);
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let json_wire =
json_body(read_resource(&endpoint, &revision, &endpoint.json.uri, None).await).await;
check_content(
&mut checks,
&json_wire,
&revision,
&endpoint.json.uri,
Some(&json_text),
None,
"application/json",
);
let binary_body =
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
check_content(
&mut checks,
&binary_body,
&revision,
&endpoint.binary.uri,
None,
Some(&binary_blob),
"image/png",
);
}
checks.finish();
}
/// Request/Trace identity is preserved and the Resource content is never captured into telemetry.
#[tokio::test]
async fn read_preserves_request_identity_without_capturing_content_in_telemetry() {
let endpoint = standard_endpoint("read_telemetry").await;
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
assert!(
!canary.trim().is_empty(),
"the content canary must be non-empty"
);
let logs = CapturedLogs::default();
let (body, request_id, trace_id) = {
let _capture = logs.install();
let response = read_resource(
&endpoint,
MODERN_REVISION,
&endpoint.text.uri,
Some("story38-read-corr"),
)
.await;
let request_id = response.headers()["x-request-id"]
.to_str()
.expect("x-request-id header")
.to_owned();
let trace_id = response.headers()["x-trace-id"]
.to_str()
.expect("x-trace-id header")
.to_owned();
(json_body(response).await, request_id, trace_id)
};
let mut checks = RevisionChecks::default();
check_content(
&mut checks,
&body,
MODERN_REVISION,
&endpoint.text.uri,
Some(&canary),
None,
"text/plain",
);
checks.require(request_id == "story38-read-corr", || {
format!("the read response must preserve the request id, got {request_id}")
});
checks.require(!trace_id.is_empty(), || {
"the read response must carry a trace id, got an empty header".to_owned()
});
let captured = logs.output();
checks.require(captured.contains("story38-read-corr"), || {
format!("the read telemetry must keep the Request ID, captured logs: {captured}")
});
checks.require(captured.contains("resource read outcome"), || {
format!("the read telemetry must record the read outcome event, captured logs: {captured}")
});
checks.require(
captured.contains("outcome=\"ok\"") && captured.contains("content_bytes="),
|| {
format!(
"the read telemetry must record a successful read outcome without content, captured logs: {captured}"
)
},
);
checks.require(!captured.contains(canary.trim()), || {
format!("the read telemetry must not capture Resource content, captured logs: {captured}")
});
checks.finish();
}
@@ -0,0 +1,157 @@
//! Story 3.8 / AT-3.8-05: a revoked Resource is denied on both supported revisions, and the
//! denial telemetry carries the correlation identity but never the Resource URI/name/MIME/digest
//! or any content. The positive control proves the capture sink really records an allowed read.
//!
//! The tombstone is written with SQL into the same real schema the endpoint reads (the Admin revoke
//! path is exercised by `admin-api`); everything else here is the unchanged production MCP path.
use serde_json::json;
use super::fixtures::*;
async fn seed_tombstone(endpoint: &ResourceEndpoint) {
sqlx::query(
"insert into resource_security_revocations (
workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id
) values ('ws_default', $1, now(), 'user_default_owner', 'story38-fixture', 'story38-fixture')",
)
.bind(endpoint.text.id.as_str())
.execute(endpoint.registry.pool())
.await
.expect("the fixture tombstone must be written into the live schema");
}
/// The revoked read is denied on both revisions; the captured telemetry keeps the Request ID and
/// the safe outcome only, while the allowed read is captured as a successful outcome.
#[tokio::test]
async fn story38_revoked_read_and_list_telemetry_are_content_free_on_both_revisions() {
let endpoint = standard_endpoint("revocation_telemetry").await;
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
seed_tombstone(&endpoint).await;
let denied_logs = CapturedLogs::default();
let mut denied_bodies = Vec::new();
{
let _capture = denied_logs.install();
for revision in supported_revisions() {
let response = read_resource(
&endpoint,
&revision,
&endpoint.text.uri,
Some("story38-denied-corr"),
)
.await;
denied_bodies.push((revision.clone(), json_body(response).await));
}
// The page must keep the other bound Resources while omitting the revoked one.
for revision in supported_revisions() {
let listed = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
let uris = listed["result"]["resources"]
.as_array()
.expect("resources/list must still return a page")
.iter()
.map(|resource| resource["uri"].as_str().unwrap_or_default().to_owned())
.collect::<Vec<_>>();
assert!(
!uris.contains(&endpoint.text.uri),
"{revision}: a revoked Resource must disappear from list: {uris:?}"
);
assert!(
uris.contains(&endpoint.json.uri),
"{revision}: the control Resource must stay listed: {uris:?}"
);
let text = listed.to_string();
assert!(
!text.contains(&endpoint.text.name),
"{revision}: no revoked metadata may be listed: {text}"
);
}
}
for (revision, body) in denied_bodies {
assert!(
body.get("result").is_none(),
"{revision}: a revoked read must not return content: {body}"
);
assert_eq!(
body["error"]["code"].as_i64(),
Some(-32602),
"{revision}: the pinned safe NotAvailable code must be reused: {body}"
);
assert_eq!(
body["error"]["message"].as_str(),
Some("the requested resource is not available"),
"{revision}: the pinned safe NotAvailable message must be reused: {body}"
);
let text = body.to_string();
for leak in [
canary.trim(),
&endpoint.text.name,
&endpoint.text.uri,
"text/plain",
] {
assert!(
!text.contains(leak),
"{revision}: the denial must not disclose Resource data ({leak}): {body}"
);
}
}
let captured = denied_logs.output();
assert!(
captured.contains("story38-denied-corr"),
"the denied read telemetry must keep the Request ID, captured: {captured}"
);
assert!(
captured.contains("resource read outcome") && captured.contains("outcome=\"denied\""),
"the denied read must record a safe denied outcome, captured: {captured}"
);
assert!(
captured.contains("resource list page omitted revoked resources")
&& captured.contains("outcome=\"filtered\"")
&& captured.contains("revoked_omitted=1"),
"the list page must record that one revoked entry was omitted, captured: {captured}"
);
for leak in [
canary.trim(),
endpoint.text.name.as_str(),
endpoint.text.uri.as_str(),
"text/plain",
] {
assert!(
!captured.contains(leak),
"the denial telemetry must not capture Resource data ({leak}), captured: {captured}"
);
}
// Positive control: the same sink records an allowed read as a successful outcome.
let allowed_logs = CapturedLogs::default();
let allowed = {
let _capture = allowed_logs.install();
json_body(
read_resource(
&endpoint,
MODERN_REVISION,
&endpoint.json.uri,
Some("story38-allowed-corr"),
)
.await,
)
.await
};
assert!(
allowed.get("result").is_some(),
"the control Resource must stay readable: {allowed}"
);
let allowed_captured = allowed_logs.output();
assert!(
allowed_captured.contains("story38-allowed-corr")
&& allowed_captured.contains("outcome=\"ok\"")
&& allowed_captured.contains("content_bytes="),
"the same sink must capture an allowed read outcome, captured: {allowed_captured}"
);
assert!(
!allowed_captured.contains(endpoint.text.uri.as_str()),
"an allowed read telemetry must not capture the URI either, captured: {allowed_captured}"
);
}
@@ -0,0 +1,333 @@
//! Story 3.8 AC03 / AT-3.8-03 and AC05 safe-error cases: unknown, Draft and unbound URIs stay
//! indistinguishable and leak no metadata, authorization rejects before any Resource lookup, the
//! required modern name header keeps its existing validation, and a corrupt published blob fails
//! safely instead of returning bytes.
//!
//! Both controls (`tools/list` on the same endpoint identity, modern `Mcp-Name` validation) are GREEN
//! before the build: they prove the fixture's auth and dispatch are real, so a failing Resource case
//! is a missing product capability, not a broken setup.
//!
//! NOT PROVEN HERE (needs a build seam, reported to TL): "artifact bytes are not read before
//! authorization" needs an observable artifact-read hook in the MCP app. The app currently has no
//! artifact store at all, so the suite proves the 401 happens before any Resource result but cannot
//! observe the absence of a byte read.
use serde_json::json;
use super::super::common::{initialize_session, post_jsonrpc, post_jsonrpc_with_headers};
use super::fixtures::*;
#[tokio::test]
async fn read_unknown_draft_and_unbound_uris_share_one_safe_outcome() {
let endpoint = standard_endpoint("read_safe_errors").await;
for revision in supported_revisions() {
let bodies = [
json_body(
read_resource(
&endpoint,
&revision,
"crank://resources/does-not-exist",
None,
)
.await,
)
.await,
json_body(read_resource(&endpoint, &revision, &endpoint.draft_uri, None).await).await,
json_body(read_resource(&endpoint, &revision, &endpoint.unbound_uri, None).await).await,
// A Published Resource of another workspace is not part of this Agent snapshot either.
json_body(read_resource(&endpoint, &revision, &endpoint.foreign_uri, None).await).await,
];
let codes: Vec<i64> = bodies.iter().map(error_code).collect();
assert_ne!(
codes[0], -32601,
"the read must be handled by the Resource product, not the unsupported-method answer on {revision}: {bodies:?}"
);
assert!(
codes.iter().all(|code| *code == codes[0]),
"unknown, Draft and unbound URIs must not be distinguishable by protocol outcome on {revision}: {:?} / {bodies:?}",
codes
);
for body in &bodies {
assert!(
body.get("result").is_none(),
"a denied read must not return Resource contents on {revision}: {body}"
);
let text = body.to_string();
for leak in [
endpoint.draft_name.as_str(),
endpoint.unbound_name.as_str(),
"draft text v1",
"unbound text v1",
"sha256:",
"text/plain",
] {
assert!(
!text.contains(leak),
"the safe error must not disclose Resource metadata ({leak}) on {revision}: {body}"
);
}
}
}
}
#[tokio::test]
async fn unauthenticated_read_is_rejected_before_any_resource_result() {
let endpoint = standard_endpoint("read_unauthorized").await;
let response = read_resource_without_credentials(&endpoint, &endpoint.text.uri).await;
let status = response.status().as_u16();
let body = response.text().await.unwrap();
assert_eq!(
status, 401,
"an unauthenticated resources/read must be rejected with 401 before any Resource lookup: {body}"
);
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
assert!(
!body.contains(canary.trim()),
"a rejected read must not disclose published bytes: {body}"
);
assert!(
!body.contains(endpoint.text.name.as_str()),
"a rejected read must not disclose published metadata: {body}"
);
let legacy = read_resource_without_credentials_legacy(&endpoint, &endpoint.text.uri).await;
let legacy_status = legacy.status().as_u16();
let legacy_body = legacy.text().await.unwrap();
assert_eq!(
legacy_status, 401,
"an unauthenticated legacy resources/read must be rejected with 401 as well: {legacy_body}"
);
assert!(
!legacy_body.contains(canary.trim()) && !legacy_body.contains(endpoint.text.name.as_str()),
"a rejected legacy read must not disclose published bytes or metadata: {legacy_body}"
);
}
/// AC03: no artifact byte is opened before authorization, scope, binding or size is decided. The
/// success at the end is the positive control that proves the counter actually observes reads.
#[tokio::test]
async fn read_never_touches_artifact_bytes_before_authorization_scope_or_size_denial() {
let endpoint = standard_endpoint("read_byte_ordering").await;
crank_artifacts::test_support::reset_artifact_reads();
for denied in [
read_resource_without_credentials(&endpoint, &endpoint.text.uri).await,
read_resource_without_credentials_legacy(&endpoint, &endpoint.text.uri).await,
] {
assert_eq!(
denied.status().as_u16(),
401,
"a credential-less read must be denied at the transport stage"
);
}
assert_eq!(
crank_artifacts::test_support::artifact_reads(),
0,
"an unauthenticated read must not touch artifact bytes"
);
for revision in supported_revisions() {
for uri in [
"crank://resources/does-not-exist".to_owned(),
endpoint.draft_uri.clone(),
endpoint.unbound_uri.clone(),
endpoint.foreign_uri.clone(),
] {
let body = json_body(read_resource(&endpoint, &revision, &uri, None).await).await;
assert!(
body.get("result").is_none(),
"a denied Resource read must not return contents on {revision}: {body}"
);
}
}
assert_eq!(
crank_artifacts::test_support::artifact_reads(),
0,
"unknown/Draft/unbound/foreign reads must not touch artifact bytes"
);
// Positive control: the authorized bound read does open the published bytes.
let allowed =
json_body(read_resource(&endpoint, MODERN_REVISION, &endpoint.text.uri, None).await).await;
assert!(
allowed.get("result").is_some(),
"the bound Resource must be served: {allowed}"
);
assert!(
crank_artifacts::test_support::artifact_reads() >= 1,
"the authorized read must be observable as an artifact read"
);
}
/// AC05 integrity: publication metadata that disagrees with the stored blob is denied from metadata
/// alone, before any artifact byte is opened, and discloses nothing.
///
/// The table check constraint forbids a size claim above the artifact-store ceiling, so the in-process
/// size ceiling is defense-in-depth and cannot be reproduced as an end-to-end oversize fixture.
#[tokio::test]
async fn inconsistent_publication_metadata_is_denied_before_any_artifact_read() {
let endpoint = standard_endpoint("read_oversize").await;
endpoint.inconsistent_text_publication_size().await;
crank_artifacts::test_support::reset_artifact_reads();
for revision in supported_revisions() {
let body =
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
assert!(
body.get("result").is_none(),
"an inconsistent publication must not return contents on {revision}: {body}"
);
assert_ne!(
error_code(&body),
-32601,
"the read must reach the Resource handler on {revision}: {body}"
);
let text = body.to_string();
assert!(
!text.contains(&endpoint.root.path().display().to_string()),
"the safe failure must not disclose the artifact root on {revision}: {body}"
);
assert!(
!text.contains("bound text v1"),
"the safe failure must not disclose published bytes on {revision}: {body}"
);
assert!(
!text.contains(&digest_hex(&endpoint.text.bytes)),
"the safe failure must not disclose the published digest on {revision}: {body}"
);
}
assert_eq!(
crank_artifacts::test_support::artifact_reads(),
0,
"a size/integrity denial must happen before any artifact byte is read"
);
}
/// AC05 missing artifact: the read fails safely instead of serving bytes or a path.
#[tokio::test]
async fn missing_published_artifact_fails_safely() {
let endpoint = standard_endpoint("read_missing").await;
endpoint.delete_binary_blob();
for revision in supported_revisions() {
let body =
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
assert!(
body.get("result").is_none(),
"a missing published artifact must not return contents on {revision}: {body}"
);
assert_ne!(
error_code(&body),
-32601,
"the read must reach the Resource handler on {revision}: {body}"
);
let text = body.to_string();
assert!(
!text.contains(&endpoint.root.path().display().to_string()),
"the safe failure must not disclose the artifact root on {revision}: {body}"
);
assert!(
!text.contains(&base64_of(&endpoint.binary.bytes)),
"the safe failure must not disclose the artifact reference on {revision}: {body}"
);
}
}
/// Existing modern protocol contract: `Mcp-Name` must match `params.uri` and is validated before any
/// handler. This control must stay GREEN after Resource registration (no handler may bypass it).
#[tokio::test]
async fn modern_read_name_header_is_still_validated_before_any_resource_handler() {
let endpoint = standard_endpoint("read_name_validation").await;
let headers = [
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "resources/read"),
("Mcp-Name", "crank://resources/some-other-uri"),
];
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&headers,
json!({
"jsonrpc": "2.0",
"id": 41,
"method": "resources/read",
"params": { "uri": endpoint.text.uri, "_meta": modern_meta(MODERN_REVISION) }
}),
)
.await;
let status = response.status().as_u16();
let body = json_body(response).await;
assert_eq!(
status, 400,
"a mismatched Mcp-Name must be a header-validation failure: {body}"
);
assert_eq!(
error_code(&body),
-32020,
"a mismatched Mcp-Name must keep the existing -32020 diagnostic: {body}"
);
assert!(
body.get("result").is_none(),
"a mismatched Mcp-Name must never serve Resource contents: {body}"
);
}
/// Same-endpoint positive control: the published tool catalog still works for the fixture Agent.
#[tokio::test]
async fn published_tool_listing_remains_green_on_the_same_endpoint() {
let endpoint = standard_endpoint("read_tools_control").await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let body = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({ "jsonrpc": "2.0", "id": 51, "method": "tools/list", "params": {} }),
)
.await;
let tools = body["result"]["tools"]
.as_array()
.unwrap_or_else(|| panic!("tools/list must return the published catalog: {body}"));
assert!(
tools
.iter()
.any(|tool| tool["name"].as_str() == Some(endpoint.tool_name.as_str())),
"the fixture Agent must expose its published tool {}: {body}",
endpoint.tool_name
);
}
#[tokio::test]
async fn corrupt_published_artifact_fails_safely_without_bytes_or_paths() {
let endpoint = standard_endpoint("read_corrupt").await;
endpoint.corrupt_binary_blob();
for revision in supported_revisions() {
let body =
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
assert!(
body.get("result").is_none(),
"a corrupt published artifact must not return contents on {revision}: {body}"
);
let code = error_code(&body);
assert_ne!(
code, -32601,
"the read must reach the Resource handler instead of the unsupported-method answer on {revision}: {body}"
);
let text = body.to_string();
let root = endpoint.root.path().display().to_string();
assert!(
!text.contains(&root),
"the safe failure must not disclose the artifact root on {revision}: {body}"
);
assert!(
!text.contains("PNG-but-valid-utf8-bytes"),
"the safe failure must not disclose blob bytes on {revision}: {body}"
);
}
}
@@ -1,992 +1,10 @@
#![allow(dead_code, unused_imports)]
use super::common::*;
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::{
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentBindingsRequest,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, RuntimeExecutor,
SecretCrypto,
};
use crank_schema::{Schema, SchemaKind};
use futures_util::stream;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use tokio::time::sleep;
use tracing_subscriber::fmt::MakeWriter;
use uuid::Version;
use crank_community_mcp::{
auth::{CommunityMachineCredentialVerifier, SharedMachineCredentialVerifier},
build_app,
catalog::PublishedToolCatalog,
session::{InMemorySessionStore, SharedSessionStore, TransportSessionStore},
};
use crank_observability::{
ObservabilityConfig, RedactionLimits, ServiceIdentity, build_subscriber,
};
fn test_workspace_id() -> WorkspaceId {
WorkspaceId::new("ws_default")
}
#[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> 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(())
}
}
fn test_workspace_slug() -> &'static str {
"default"
}
fn test_agent_id(agent_slug: &str) -> AgentId {
AgentId::new(format!("agent_{agent_slug}"))
}
fn build_test_app(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
) -> axum::Router {
build_test_app_with_rate_limit(
registry,
refresh_interval,
public_base_url,
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
)
}
fn build_test_app_with_rate_limit(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
rate_limit_config: RequestRateLimitConfig,
) -> axum::Router {
build_test_app_with_store(
registry,
refresh_interval,
public_base_url,
rate_limit_config,
std::sync::Arc::new(InMemorySessionStore::default()),
std::sync::Arc::new(CommunityMachineCredentialVerifier),
)
}
fn build_test_app_with_store(
registry: PostgresRegistry,
refresh_interval: Duration,
public_base_url: Option<String>,
rate_limit_config: RequestRateLimitConfig,
sessions: SharedSessionStore,
credential_verifier: SharedMachineCredentialVerifier,
) -> axum::Router {
build_app(
registry,
refresh_interval,
public_base_url,
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
RequestRateLimiter::new(rate_limit_config),
std::sync::Arc::new(InMemoryCoordinationStateStore::default()),
sessions,
credential_verifier,
)
}
#[tokio::test]
async fn initializes_lists_and_calls_published_tool_via_mcp() {
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-rest").await;
let api_key = create_platform_api_key(
&registry,
"sales-rest",
"mcp-rest",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-rest");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let tools = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}),
)
.await;
let call_result = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_create_lead",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
assert_eq!(
call_result["result"]["structuredContent"],
json!({ "id": "lead_123" })
);
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(
logs[0].log.source,
crank_core::InvocationSource::AgentToolCall
);
assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok);
assert_eq!(logs[0].log.tool_name, "crm_create_lead");
let keys = registry
.list_platform_api_keys(&test_workspace_id())
.await
.unwrap();
assert!(keys[0].api_key.last_used_at.is_some());
}
#[tokio::test]
async fn preserves_request_id_for_tool_call_invocations() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_id");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-id",
"mcp-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
Some("req_test_123"),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_test_123"
);
let trace_id = response.headers()["x-trace-id"]
.to_str()
.unwrap()
.to_owned();
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some("req_test_123"));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test]
async fn generates_request_id_for_tool_call_responses_and_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_generated_request_id");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-generated-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-generated-request-id",
"mcp-generated-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-generated-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
None,
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_generated_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
let request_id = response
.headers()
.get("x-request-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let trace_id = response
.headers()
.get("x-trace-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
assert_eq!(
uuid::Uuid::parse_str(&request_id).unwrap().get_version(),
Some(Version::SortRand)
);
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some(request_id.as_str()));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test(flavor = "current_thread")]
async fn emits_request_id_in_mcp_ingress_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_trace");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-trace").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-trace",
"mcp-request-trace",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let writer = SharedLogWriter::default();
let subscriber = build_subscriber(
ObservabilityConfig::new(
ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
"info",
RedactionLimits::default(),
),
writer.clone(),
)
.unwrap();
let dispatch = tracing::Dispatch::new(subscriber);
let _guard = tracing::dispatcher::set_default(&dispatch);
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-trace");
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
None,
Some("req_mcp_trace_123"),
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26"
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_mcp_trace_123"
);
assert_eq!(response.status(), reqwest::StatusCode::OK);
let logs = writer.output();
let event = logs
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.find(|event| event["event"] == "mcp.request.received")
.unwrap();
assert_eq!(event["service"], "mcp-server");
assert_eq!(event["request_id"], "req_mcp_trace_123");
assert_eq!(event["fields"]["agent_slug"], "sales-request-trace");
assert_eq!(event["fields"]["workspace_slug"], "default");
assert_eq!(event["fields"]["jsonrpc_method"], "initialize");
}
#[tokio::test]
async fn requires_initialized_notification_before_tool_methods() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-init",
"mcp-init",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-init");
let initialize_response = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
let session_id = initialize_response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let tools_list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.json(&json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
assert_eq!(tools_list["error"]["code"], -32002);
}
#[tokio::test]
async fn initialize_can_return_sse_response_when_client_prefers_event_stream() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-sse-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-sse-init",
"mcp-sse-init",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-sse-init"))
.header(header::ACCEPT, "text/event-stream, application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert!(response.headers().get("MCP-Session-Id").is_some());
let body = response.text().await.unwrap();
assert!(body.contains("\"jsonrpc\":\"2.0\""));
assert!(body.contains("\"protocolVersion\":\"2025-11-25\""));
}
#[tokio::test]
async fn get_opens_sse_stream_for_initialized_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse",
"mcp-get-sse",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-sse");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert_eq!(
response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap(),
initialized_session
);
}
#[tokio::test]
async fn get_returns_not_found_for_expired_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-expired-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-expired-session",
"mcp-expired-session",
&[PlatformApiKeyScope::Read],
)
.await;
let session_store = Arc::new(InMemorySessionStore::default());
let session_id = session_store
.create(
"2025-11-25",
test_workspace_slug(),
"sales-expired-session",
false,
OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(),
Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()),
)
.await
.unwrap();
session_store
.mark_initialized(
&session_id,
OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap(),
)
.await
.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
session_store,
std::sync::Arc::new(CommunityMachineCredentialVerifier),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-expired-session"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn rejects_rapid_transport_get_requests_with_429() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-rate-limit", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-rate-limit",
"mcp-get-rate-limit",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 2).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-rate-limit");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let first_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(first_response.status(), reqwest::StatusCode::OK);
let second_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_response.status(),
reqwest::StatusCode::TOO_MANY_REQUESTS
);
assert!(second_response.headers().get(header::RETRY_AFTER).is_some());
}
#[tokio::test]
async fn get_requires_session_header() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse-missing", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse-missing",
"mcp-get-sse-missing",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "req_early_mcp_error")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_early_mcp_error"
);
let invalid_response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "bad,value")
.send()
.await
.unwrap();
let generated = invalid_response.headers()["x-request-id"].to_str().unwrap();
assert_eq!(
uuid::Uuid::parse_str(generated).unwrap().get_version(),
Some(Version::SortRand)
);
}
#[tokio::test]
async fn delete_terminates_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-delete-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-delete-session",
"mcp-delete-session",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-delete-session");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let delete_response = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(delete_response.status(), reqwest::StatusCode::NO_CONTENT);
let after_delete = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(after_delete.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn initialize_accepts_json_only_response_negotiation() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-json-accept", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-json-accept",
"mcp-json-accept",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-json-accept"))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap(),
"application/json"
);
}
#[tokio::test]
async fn rejects_get_with_protocol_version_mismatch() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-bad-version", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-bad-version",
"mcp-get-bad-version",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-bad-version");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-06-18")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
}
//! Story 3.6 (kanban t_987bf309): navigation module. The transport-protocol integration tests
//! moved verbatim into thematic submodules grouped by observable contract; the duplicated local
//! fixture block was deleted in favour of the shared `common` fixtures. Bodies, literals,
//! assertions and timeouts are unchanged - only the module prefix changed.
mod legacy_lifecycle;
mod request_identity;
mod session_scope;
@@ -0,0 +1,483 @@
//! Legacy transport lifecycle and negotiation: initialized-notification gate, SSE GET/initialize,
//! expired and unknown sessions, the GET rate bucket, session-header requirement, DELETE and the
//! JSON-only response negotiation.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_community_mcp::{
auth::{CommunityMachineCredentialVerifier, SharedMachineCredentialVerifier},
build_app,
catalog::PublishedToolCatalog,
session::{InMemorySessionStore, SharedSessionStore, TransportSessionStore},
};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, RuntimeExecutor,
SecretCrypto,
};
use futures_util::stream;
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Version;
#[tokio::test]
async fn requires_initialized_notification_before_tool_methods() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-init",
"mcp-init",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-init");
let initialize_response = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
let session_id = initialize_response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let tools_list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.json(&json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
assert_eq!(tools_list["error"]["code"], -32002);
}
#[tokio::test]
async fn initialize_can_return_sse_response_when_client_prefers_event_stream() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-sse-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-sse-init",
"mcp-sse-init",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-sse-init"))
.header(header::ACCEPT, "text/event-stream, application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert!(response.headers().get("MCP-Session-Id").is_some());
let body = response.text().await.unwrap();
assert!(body.contains("\"jsonrpc\":\"2.0\""));
assert!(body.contains("\"protocolVersion\":\"2025-11-25\""));
}
#[tokio::test]
async fn get_opens_sse_stream_for_initialized_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse",
"mcp-get-sse",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-sse");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert_eq!(
response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap(),
initialized_session
);
}
#[tokio::test]
async fn get_returns_not_found_for_expired_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-expired-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-expired-session",
"mcp-expired-session",
&[PlatformApiKeyScope::Read],
)
.await;
let session_store = Arc::new(InMemorySessionStore::default());
let session_id = session_store
.create(
"2025-11-25",
test_workspace_slug(),
"sales-expired-session",
false,
OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(),
Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()),
)
.await
.unwrap();
session_store
.mark_initialized(
&session_id,
OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap(),
)
.await
.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
session_store,
std::sync::Arc::new(CommunityMachineCredentialVerifier),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-expired-session"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn rejects_rapid_transport_get_requests_with_429() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-rate-limit", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-rate-limit",
"mcp-get-rate-limit",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 2).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-rate-limit");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let first_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(first_response.status(), reqwest::StatusCode::OK);
let second_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_response.status(),
reqwest::StatusCode::TOO_MANY_REQUESTS
);
assert!(second_response.headers().get(header::RETRY_AFTER).is_some());
}
#[tokio::test]
async fn get_requires_session_header() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse-missing", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse-missing",
"mcp-get-sse-missing",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "req_early_mcp_error")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_early_mcp_error"
);
let invalid_response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "bad,value")
.send()
.await
.unwrap();
let generated = invalid_response.headers()["x-request-id"].to_str().unwrap();
assert_eq!(
uuid::Uuid::parse_str(generated).unwrap().get_version(),
Some(Version::SortRand)
);
}
#[tokio::test]
async fn delete_terminates_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-delete-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-delete-session",
"mcp-delete-session",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-delete-session");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let delete_response = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(delete_response.status(), reqwest::StatusCode::NO_CONTENT);
let after_delete = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(after_delete.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn initialize_accepts_json_only_response_negotiation() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-json-accept", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-json-accept",
"mcp-json-accept",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-json-accept"))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap(),
"application/json"
);
}
#[tokio::test]
async fn rejects_get_with_protocol_version_mismatch() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-bad-version", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-bad-version",
"mcp-get-bad-version",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-bad-version");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-06-18")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
}
@@ -0,0 +1,468 @@
//! Request identity end to end: published tool call, preservation/generation of the request id and
//! the MCP ingress log projection, including this group's only-consumer log writer fixture.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_observability::{
ObservabilityConfig, RedactionLimits, ServiceIdentity, build_subscriber,
};
use crank_registry::{
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentBindingsRequest,
};
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tracing_subscriber::fmt::MakeWriter;
use uuid::Version;
#[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> 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(())
}
}
#[tokio::test]
async fn initializes_lists_and_calls_published_tool_via_mcp() {
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-rest").await;
let api_key = create_platform_api_key(
&registry,
"sales-rest",
"mcp-rest",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-rest");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let tools = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}),
)
.await;
let call_result = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_create_lead",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
assert_eq!(
call_result["result"]["structuredContent"],
json!({ "id": "lead_123" })
);
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(
logs[0].log.source,
crank_core::InvocationSource::AgentToolCall
);
assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok);
assert_eq!(logs[0].log.tool_name, "crm_create_lead");
let keys = registry
.list_platform_api_keys(&test_workspace_id())
.await
.unwrap();
assert!(keys[0].api_key.last_used_at.is_some());
}
#[tokio::test]
async fn preserves_request_id_for_tool_call_invocations() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_id");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-id",
"mcp-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
Some("req_test_123"),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_test_123"
);
let trace_id = response.headers()["x-trace-id"]
.to_str()
.unwrap()
.to_owned();
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some("req_test_123"));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test]
async fn generates_request_id_for_tool_call_responses_and_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_generated_request_id");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-generated-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-generated-request-id",
"mcp-generated-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-generated-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
None,
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_generated_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
let request_id = response
.headers()
.get("x-request-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let trace_id = response
.headers()
.get("x-trace-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
assert_eq!(
uuid::Uuid::parse_str(&request_id).unwrap().get_version(),
Some(Version::SortRand)
);
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some(request_id.as_str()));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test(flavor = "current_thread")]
async fn emits_request_id_in_mcp_ingress_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_trace");
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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-trace").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-trace",
"mcp-request-trace",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let writer = SharedLogWriter::default();
let subscriber = build_subscriber(
ObservabilityConfig::new(
ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
"info",
RedactionLimits::default(),
),
writer.clone(),
)
.unwrap();
let dispatch = tracing::Dispatch::new(subscriber);
let _guard = tracing::dispatcher::set_default(&dispatch);
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-trace");
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
None,
Some("req_mcp_trace_123"),
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_mcp_trace_123"
);
assert_eq!(response.status(), reqwest::StatusCode::OK);
let logs = writer.output();
let event = logs
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.find(|event| event["event"] == "mcp.request.received")
.unwrap();
assert_eq!(event["service"], "mcp-server");
assert_eq!(event["request_id"], "req_mcp_trace_123");
assert_eq!(event["fields"]["agent_slug"], "sales-request-trace");
assert_eq!(event["fields"]["workspace_slug"], "default");
assert_eq!(event["fields"]["jsonrpc_method"], "initialize");
}
@@ -0,0 +1,743 @@
//! Modern identity and persisted-withdrawn-session restrictions on GET/DELETE/POST (r11/r17/r18/r29),
//! with the fixtures those scenarios own.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_community_mcp::{
auth::{CommunityMachineCredentialVerifier, SharedMachineCredentialVerifier},
build_app,
catalog::PublishedToolCatalog,
session::{InMemorySessionStore, SharedSessionStore, TransportSessionStore},
};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_registry::{
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentBindingsRequest,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, RuntimeExecutor,
SecretCrypto,
};
use futures_util::stream;
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use uuid::Version;
// ---------------------------------------------------------------------------------------------
// Review pass 2 regressions (R11): session lifecycle must not cross eras. Test-only stage.
// ---------------------------------------------------------------------------------------------
/// R11: an authenticated `DELETE` carrying the modern revision (the modern era has no session to
/// terminate, so the method is not available) or an unknown/withdrawn revision (a safe admission
/// error) must be rejected **and must not terminate the live legacy session**. A legitimate legacy
/// `DELETE` still terminates it, and the next one reports `404`.
#[tokio::test]
async fn r11_delete_without_legacy_revision_does_not_terminate_the_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-delete-lifecycle", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-delete-lifecycle",
"mcp-delete-lifecycle",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-delete-lifecycle");
let session = initialize_session(&client, &mcp_url, &api_key).await;
for (revision, expected_status) in [
("2026-07-28", reqwest::StatusCode::METHOD_NOT_ALLOWED),
("1999-01-01", reqwest::StatusCode::BAD_REQUEST),
("2025-03-26", reqwest::StatusCode::BAD_REQUEST),
] {
let rejected = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", revision)
.send()
.await
.unwrap();
assert_eq!(
rejected.status(),
expected_status,
"DELETE with revision {revision} must be rejected"
);
let list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }))
.send()
.await
.unwrap();
assert_eq!(
list.status(),
reqwest::StatusCode::OK,
"the rejected DELETE ({revision}) must not terminate the live legacy session"
);
}
let terminated = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
terminated.status(),
reqwest::StatusCode::NO_CONTENT,
"a legitimate legacy DELETE must still terminate the session"
);
let second_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_delete.status(),
reqwest::StatusCode::NOT_FOUND,
"a terminated session must report not found"
);
}
/// R11 (GET half): the modern revision has no standalone GET stream endpoint, so an explicit modern
/// identity must be answered with `405 Method Not Allowed` instead of carrying the legacy GET path.
/// The live session must stay untouched.
#[tokio::test]
async fn r11_get_with_modern_identity_is_method_not_allowed() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-modern", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-modern",
"mcp-get-modern",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-modern");
let session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
response.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern revision removed the GET stream endpoint"
);
let list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }))
.send()
.await
.unwrap();
assert_eq!(
list.status(),
reqwest::StatusCode::OK,
"a rejected modern GET must not disturb the legacy session"
);
}
// ---------------------------------------------------------------------------------------------
// Review pass 3 regressions (R17, R18). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// R17 (GET half): the legacy rate bucket must not shadow the modern era admission. The limiter is a
/// token bucket (`RequestRateLimitConfig::new(requests_per_second, burst)`) keyed per session once a
/// session carrier is present, so the handshake's `notifications/initialized` POST already consumes one
/// token from the same bucket the `GET` uses. With `burst = 3` exactly two tokens remain for the
/// sequence: a legitimate legacy GET consumes one, an explicit modern GET is rejected by the era
/// admission with `405` **without** consuming a token (proved by the next legacy GET still being
/// admitted), and the final legacy GET is limited once the bucket is empty — the legacy semantics are
/// unchanged. The `429` is asserted to come from the rate limiter (it carries `Retry-After`), not from
/// the concurrent-stream slot guard, which would make the oracle ambiguous.
#[tokio::test]
async fn r17_modern_get_is_not_shadowed_by_the_legacy_rate_bucket() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-era-limit", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-era-limit",
"mcp-era-limit",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 3).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-era-limit");
// The refill bound starts before the handshake: the session-scoped bucket is consumed by the
// handshake's `notifications/initialized` too, so the timing window must cover the whole
// token-consuming sequence (handshake + GETs), not only the part after `initialize_session` returned.
let sequence_started = std::time::Instant::now();
let session = initialize_session(&client, &mcp_url, &api_key).await;
let legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
legacy_get.status(),
reqwest::StatusCode::OK,
"the first legitimate legacy GET consumes the first bucket slot"
);
let modern_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
modern_get.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern era admission must decide before the legacy rate bucket"
);
let second_legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_legacy_get.status(),
reqwest::StatusCode::OK,
"a rejected modern GET must not consume the legacy bucket"
);
let third_legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
third_legacy_get.status(),
reqwest::StatusCode::TOO_MANY_REQUESTS,
"the legacy bucket semantics themselves stay unchanged"
);
assert!(
third_legacy_get.headers().get("retry-after").is_some(),
"the 429 must come from the request rate limiter (it carries `Retry-After`), not from the \
concurrent-stream slot guard"
);
// Timing precondition: the local token bucket refills one token per second, so the assertions above
// only hold while the whole consuming sequence — handshake included — stays inside one refill window.
// A slower sequence makes this timing oracle inconclusive and is reported as such instead of staying
// silently GREEN. No production threshold was changed for this.
assert!(
sequence_started.elapsed() < Duration::from_secs(1),
"the GET sequence including the handshake took {:?}; with a 1 token/s bucket this timing oracle \
is inconclusive",
sequence_started.elapsed()
);
}
/// R17 (DELETE half): the same ordering rule for the terminating method. The session-scoped bucket is
/// shared with the handshake's `notifications/initialized`, so with `burst = 2` exactly one token is
/// left for the sequence: under the old ordering the modern DELETE occupied it and the following
/// legitimate legacy DELETE would be limited; once the admission decides first, the modern rejection
/// consumes nothing and the legacy DELETE still returns `204`.
#[tokio::test]
async fn r17_modern_delete_is_rejected_before_the_legacy_rate_bucket() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-era-limit-delete", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-era-limit-delete",
"mcp-era-limit-delete",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 2).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-era-limit-delete");
// The refill bound starts before the handshake (see the GET regression).
let sequence_started = std::time::Instant::now();
let session = initialize_session(&client, &mcp_url, &api_key).await;
let modern_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
modern_delete.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern era admission must decide before the legacy rate bucket"
);
let legacy_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
legacy_delete.status(),
reqwest::StatusCode::NO_CONTENT,
"a rejected modern DELETE must not consume the legacy bucket"
);
// Timing precondition for the 1 token/s bucket: the bound covers the handshake and the DELETE
// sequence, so a refill inside the window is reported as an inconclusive oracle.
assert!(
sequence_started.elapsed() < Duration::from_secs(1),
"the DELETE sequence including the handshake took {:?}; with a 1 token/s bucket this timing \
oracle is inconclusive",
sequence_started.elapsed()
);
}
/// R18: a session persisted under a withdrawn revision must not be served as a live legacy session.
/// The session store is seeded directly (a withdrawn `initialize` is rejected, so an old session cannot
/// be created through the normal path) and the identity is taken from the session itself (no version
/// header).
///
/// Oracle provenance (corrected after TL review): `protocol-era-matrix.md` row 15 requires a **safe
/// structured error** for a withdrawn revision, while `405` is reserved for the modern identity
/// (row 20). A persisted `2025-03-26` session is therefore expected to be rejected with `400`, not
/// `405`; the earlier `405` expectation in this test was wrong and is preserved only as history in
/// `transport_protocol-attempt1-*.log`. The legitimate legacy path (`2025-11-25`, header absent) must
/// keep working.
#[tokio::test]
async fn r18_get_delete_reject_persisted_withdrawn_session_without_version_header() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-old-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-old-session",
"mcp-old-session",
&[PlatformApiKeyScope::Read],
)
.await;
let sessions = Arc::new(InMemorySessionStore::default());
let now = OffsetDateTime::now_utc();
let withdrawn = sessions
.create(
"2025-03-26",
test_workspace_slug(),
"sales-old-session",
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&withdrawn, now).await.unwrap();
let legacy = sessions
.create(
"2025-11-25",
test_workspace_slug(),
"sales-old-session",
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&legacy, now).await.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
sessions.clone(),
Arc::new(CommunityMachineCredentialVerifier),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-old-session");
let get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &withdrawn)
.send()
.await
.unwrap();
assert_eq!(
get.status(),
reqwest::StatusCode::BAD_REQUEST,
"a persisted withdrawn session must not open a legacy stream; matrix row 15 requires a safe error (405 belongs to the modern identity, row 20)"
);
let delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &withdrawn)
.send()
.await
.unwrap();
assert_eq!(
delete.status(),
reqwest::StatusCode::BAD_REQUEST,
"a persisted withdrawn session must not be terminated as a legacy session; matrix row 15 requires a safe error"
);
assert!(
sessions.get(&withdrawn).await.unwrap().is_some(),
"the withdrawn session state must be retained"
);
let legacy_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &legacy)
.send()
.await
.unwrap();
assert_eq!(
legacy_delete.status(),
reqwest::StatusCode::NO_CONTENT,
"the legitimate legacy path without a version header must keep working"
);
assert!(sessions.get(&legacy).await.unwrap().is_none());
}
/// Test-only counted upstream (same shape as the revision-matrix fixture): every lead request
/// increments the counter, so a rejection can be proven to have performed **no** outbound request.
async fn spawn_counted_lead_upstream(calls: Arc<std::sync::atomic::AtomicUsize>) -> String {
let handler_calls = Arc::clone(&calls);
let app = Router::new().route(
"/crm/leads",
post(move |Json(payload): Json<Value>| {
let calls = Arc::clone(&handler_calls);
async move {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Json(json!({ "id": "lead_123", "email": payload["email"] }))
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://{address}")
}
/// Shared R29 fixture: a counted upstream behind a published `crm_counted_lead` operation, a
/// transport session negotiated on a withdrawn revision (created in the shared store and marked
/// initialized, i.e. a session the server accepted while it was still inside the window), and the
/// credentials needed to POST against it.
struct WithdrawnSessionPostFixture {
client: reqwest::Client,
mcp_url: String,
api_key: String,
sessions: Arc<InMemorySessionStore>,
withdrawn: String,
calls: Arc<std::sync::atomic::AtomicUsize>,
}
async fn withdrawn_session_post_fixture(agent_slug: &str) -> WithdrawnSessionPostFixture {
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let operation = test_operation(&upstream_base_url, "crm_counted_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::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, agent_slug).await;
let api_key = create_platform_api_key(
&registry,
agent_slug,
"mcp-withdrawn-post",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let sessions = Arc::new(InMemorySessionStore::default());
let now = OffsetDateTime::now_utc();
let withdrawn = sessions
.create(
"2025-03-26",
test_workspace_slug(),
agent_slug,
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&withdrawn, now).await.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
sessions.clone(),
Arc::new(CommunityMachineCredentialVerifier),
))
.await;
WithdrawnSessionPostFixture {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, agent_slug),
api_key,
sessions,
withdrawn,
calls,
}
}
/// Shared R29 oracle (review pass 6, P7): a legacy POST whose persisted session is no longer
/// operational must be answered with the era-correct **legacy** structured error — a complete
/// JSON-RPC 2.0 envelope with the original id, a numeric code, a non-empty message, the preserved
/// request correlation and no `result` key at all — must leave the persisted session intact and must
/// not perform the outbound call.
///
/// The exact legacy code is deliberately **not** pinned: matrix row 14 records that the modern
/// `-32022` contract is not imposed on a legacy-shaped rejection, so only the modern diagnostics are
/// excluded here.
async fn assert_r29_structured_rejection(
fixture: &WithdrawnSessionPostFixture,
status: u16,
raw: &str,
correlation: &str,
) {
use std::sync::atomic::Ordering;
assert_eq!(
status, 400,
"a persisted withdrawn session must not be served (matrix row 15), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"matrix row 15 requires a safe **structured** error, but the legacy POST rejection answered \
{status} with an empty body"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!("the row-15 rejection must be a JSON-RPC error envelope, got {raw:?}: {error}")
});
assert_eq!(body["jsonrpc"], "2.0", "got {body}");
assert_eq!(
body["id"],
json!(30),
"the legacy rejection must keep the JSON-RPC request id, got {body}"
);
assert!(
body["error"]["code"].is_i64(),
"the legacy rejection must carry a numeric JSON-RPC code, got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the legacy rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the legacy rejection must preserve the request correlation, got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersionError must not be imposed on a legacy-sourced \
rejection (matrix row 14), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy-sourced rejection, got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a `result` key at all, got {body}"
);
assert!(
body["result"].is_null(),
"a rejected request must not carry a result, got {body}"
);
let retained = fixture
.sessions
.get(&fixture.withdrawn)
.await
.unwrap()
.expect("the withdrawn session must be retained");
assert!(
retained.initialized,
"the rejected request must not mutate the persisted session state"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a rejected request must not perform the outbound call"
);
}
/// R29 (header/session half): a legacy POST that names the served legacy revision in its
/// `MCP-Protocol-Version` header while the **persisted** session was negotiated on a withdrawn
/// revision. The first rejection here is the header/session-revision comparison (`app.rs` 873-875):
/// `2025-11-25` is a supported revision that contradicts the persisted `2025-03-26`.
///
/// Review pass 6 (P6) provenance correction: this is what the earlier `post_jsonrpc_response`-based
/// case actually exercised — that helper always adds the legacy version header
/// (`common.rs` 253-257), so the case never was a no-header case and the earlier "no version header"
/// claim was false. The no-header half is covered separately by
/// `r29_legacy_post_without_version_header_on_withdrawn_session_is_a_structured_error`.
#[tokio::test]
async fn r29_legacy_post_with_version_header_on_withdrawn_session_is_a_structured_error() {
let fixture = withdrawn_session_post_fixture("sales-withdrawn-post").await;
let response = post_jsonrpc_response(
&fixture.client,
&fixture.mcp_url,
&fixture.api_key,
Some(&fixture.withdrawn),
Some("r29-legacy-post"),
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "tools/call",
"params": { "name": "crm_counted_lead", "arguments": { "email": "withdrawn@example.com" } }
}),
)
.await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_r29_structured_rejection(&fixture, status, &raw, "r29-legacy-post").await;
}
/// R29 (no-header half, matrix rows 10/15): a legacy POST that carries **no** version header at all —
/// the identity comes from the persisted session itself — while that persisted session was negotiated
/// on a withdrawn revision. `post_jsonrpc_with_headers` sends only the headers passed to it, so this
/// request really omits `MCP-Protocol-Version`; the session carrier, the JSON-RPC id and the request
/// correlation are the only inputs.
///
/// Review pass 6 (P6): this is the true no-header case the earlier R29 acceptance claim was missing.
/// Honest result note: on the frozen revision this path is already answered by the structured
/// rejection introduced in the review-5 BUILD (`app.rs` 873-887), i.e. expected existing GREEN — the
/// oracle is added because the coverage claim was false, not because a RED was manufactured.
#[tokio::test]
async fn r29_legacy_post_without_version_header_on_withdrawn_session_is_a_structured_error() {
let fixture = withdrawn_session_post_fixture("sales-withdrawn-no-header").await;
let response = post_jsonrpc_with_headers(
&fixture.client,
&fixture.mcp_url,
&fixture.api_key,
&[
("MCP-Session-Id", fixture.withdrawn.as_str()),
("x-request-id", "r29-no-header-post"),
],
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "tools/call",
"params": { "name": "crm_counted_lead", "arguments": { "email": "withdrawn@example.com" } }
}),
)
.await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_r29_structured_rejection(&fixture, status, &raw, "r29-no-header-post").await;
}
+7
View File
@@ -12,6 +12,13 @@ use time::{OffsetDateTime, format_description::well_known::Rfc3339};
#[tokio::test]
async fn real_mcp_runtime_upstream_postgres_and_catalog_paths_emit_bounded_metrics() {
// Story 3.6: закрытая process identity фиксируется **до** установки recorder'а
// и любой записи. Явный binding (ре-экспорт crank-observability) заменяет
// прежнюю хрупкую фикстуру, которая намеренно ловила terminal-ошибку `init`
// на уже занятом global recorder'е и продолжала работу после неё.
crank_observability::bind_metric_service(crank_observability::MetricService::McpServer)
.expect("explicit MCP service binding before the recorder");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
recorder