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
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:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -0,0 +1,962 @@
|
||||
//! Fixtures and helpers of the in-crate section 7.2 test seam (`app::dispatch_observer`).
|
||||
//!
|
||||
//! This file is the `support` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there). It holds everything the observed tests need but no test itself: the real router harness,
|
||||
//! the counted session store, the counted loopback upstream, the registry/operation/agent fixtures
|
||||
//! and the shared assertions. It lives one directory above `src/app/` for the same reason the
|
||||
//! `tests` module does — `scripts/check-execution-boundaries.py` reserves that prefix for service
|
||||
//! modules without an HTTP client or a persistence dependency. Everything here is `#[cfg(test)]`.
|
||||
|
||||
//! Behavioural harness of the BUILD-internal semantic observer (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! This file is the `tests` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there), so the module path — and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` — is unchanged. It is not a
|
||||
//! separate crate target and it is `#[cfg(test)]`-only.
|
||||
//!
|
||||
//! Why the file is not under `src/app/`: `scripts/check-execution-boundaries.py` treats the whole
|
||||
//! `crates/crank-community-mcp/src/app/` prefix as service-module scope and forbids an HTTP-client
|
||||
//! (`reqwest`) or persistence (`sqlx`/migration) dependency there. This harness needs both — a real
|
||||
//! PostgreSQL schema through `crank_test_support::postgres_schema_url` and a real request through the
|
||||
//! served router — so the harness sits one directory above the scoped prefix while the observer
|
||||
//! itself (markers, scope, counters, no dependency) stays at the approved `src/app/` path.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{Json, Router, extract::State, http::header, routing::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, PlatformApiKeyKind,
|
||||
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
|
||||
ToolSelectionPolicy, WorkspaceId,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreatePlatformApiKeyRequest, PostgresRegistry, PublishAgentRequest,
|
||||
PublishRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use super::{observe, observe_with_registration};
|
||||
use crate::{
|
||||
auth::CommunityMachineCredentialVerifier,
|
||||
build_app,
|
||||
protocol::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, CapabilityRegistry,
|
||||
FeatureSet, HeaderSet, Kind, METHOD_DESCRIPTORS, MethodDescriptor, MethodHandler, Roster,
|
||||
},
|
||||
session::{InMemorySessionStore, SessionState, SessionStoreError, TransportSessionStore},
|
||||
};
|
||||
|
||||
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) const TOOL_NAME: &str = "create_lead";
|
||||
pub(super) const WORKSPACE_SLUG: &str = "default";
|
||||
pub(super) const AGENT_SLUG: &str = "dispatch-observer";
|
||||
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";
|
||||
|
||||
/// One observed endpoint: the real router, the observer that counts its own requests and the counted
|
||||
/// loopback upstream that every real tool execution must reach.
|
||||
pub(super) struct Harness {
|
||||
client: reqwest::Client,
|
||||
mcp_url: String,
|
||||
api_key: String,
|
||||
counters: Arc<CounterSet>,
|
||||
session_counters: Arc<SessionCounters>,
|
||||
upstream_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
pub(super) struct Upstream {
|
||||
base_url: String,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
/// The session-store operations of the observed requests (section 7.2 honest naming: these count
|
||||
/// *session-store operations*, never dispatch, era or service entries).
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SessionCounters {
|
||||
get: AtomicUsize,
|
||||
create: AtomicUsize,
|
||||
mark_initialized: AtomicUsize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct SessionOps {
|
||||
pub(super) get: usize,
|
||||
pub(super) create: usize,
|
||||
pub(super) mark_initialized: usize,
|
||||
}
|
||||
|
||||
impl SessionCounters {
|
||||
pub(super) fn snapshot(&self) -> SessionOps {
|
||||
SessionOps {
|
||||
get: self.get.load(Ordering::SeqCst),
|
||||
create: self.create.load(Ordering::SeqCst),
|
||||
mark_initialized: self.mark_initialized.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The observed session store: one real `InMemorySessionStore` plus per-operation counters, so a
|
||||
/// request that touches the session store before (or instead of) the expected path is visible.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CountedSessionStore {
|
||||
inner: InMemorySessionStore,
|
||||
counters: Arc<SessionCounters>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for CountedSessionStore {
|
||||
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.create.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.get.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner.get(session_id).await
|
||||
}
|
||||
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
session_id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
self.counters
|
||||
.mark_initialized
|
||||
.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
|
||||
}
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
pub(super) async fn started() -> Self {
|
||||
Self::started_with_registration(None).await
|
||||
}
|
||||
|
||||
/// One observed endpoint, optionally served with an explicit registration snapshot (F5: the
|
||||
/// add/remove proof runs against this real router, not against a registry unit query).
|
||||
pub(super) async fn started_with_registration(
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Self {
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_counted_upstream().await;
|
||||
let operation = test_operation(&upstream.base_url);
|
||||
let workspace_id = workspace_id();
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the operation must be created");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id,
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("the operation must be published");
|
||||
publish_agent(®istry, &operation).await;
|
||||
let api_key = create_api_key(®istry).await;
|
||||
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let session_counters = Arc::new(SessionCounters::default());
|
||||
let sessions = Arc::new(CountedSessionStore {
|
||||
inner: InMemorySessionStore::default(),
|
||||
counters: Arc::clone(&session_counters),
|
||||
});
|
||||
let app = observe_requests(
|
||||
build_app(
|
||||
registry,
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000")
|
||||
.expect("a valid test master key"),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(
|
||||
RequestRateLimitConfig::new(10_000, 10_000).expect("a valid rate limit"),
|
||||
),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
sessions,
|
||||
Arc::new(CommunityMachineCredentialVerifier),
|
||||
),
|
||||
Arc::clone(&counters),
|
||||
registration,
|
||||
);
|
||||
let base_url = spawn_server(app).await;
|
||||
|
||||
Self {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: format!("{base_url}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}"),
|
||||
api_key,
|
||||
counters,
|
||||
session_counters,
|
||||
upstream_calls: upstream.calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn snapshot(&self) -> Snapshot {
|
||||
self.counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn session_ops(&self) -> SessionOps {
|
||||
self.session_counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn upstream_calls(&self) -> usize {
|
||||
self.upstream_calls.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(super) async fn post(&self, headers: &[(&str, &str)], body: &Value) -> reqwest::Response {
|
||||
let mut request = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key));
|
||||
for (name, value) in headers {
|
||||
request = request.header(*name, *value);
|
||||
}
|
||||
request
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.expect("the observed request must complete")
|
||||
}
|
||||
|
||||
/// A legacy session, primed through the real lifecycle methods.
|
||||
pub(super) async fn initialize_legacy_session(&self) -> String {
|
||||
let response = self
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"the legacy initialize must succeed"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
|
||||
let initialized = self
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session_id.as_str()),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": {}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
initialized.status().as_u16(),
|
||||
202,
|
||||
"the initialized notification must be acknowledged"
|
||||
);
|
||||
session_id
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the request-scoped observer (and, when given, the F5 registration snapshot) around every
|
||||
/// request of this router.
|
||||
///
|
||||
/// The layer runs inside the request task and awaits the inner service, so the markers deep in the
|
||||
/// handler see exactly this request's counters and the dispatch asks exactly this request's
|
||||
/// registration. Nothing global is mutated.
|
||||
pub(super) fn observe_requests(
|
||||
app: Router,
|
||||
counters: Arc<CounterSet>,
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Router {
|
||||
app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = Arc::clone(&counters);
|
||||
let registration = registration.clone();
|
||||
async move {
|
||||
match registration {
|
||||
Some(registration) => {
|
||||
observe_with_registration(
|
||||
registration,
|
||||
observe(counters, next.run(request)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => observe(counters, next.run(request)).await,
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn spawn_server(app: Router) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("a loopback listener must bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("a bound listener has an address");
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
/// The counted loopback upstream: every arrival is one real outbound tool execution.
|
||||
pub(super) async fn spawn_counted_upstream() -> Upstream {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let state = Arc::clone(&calls);
|
||||
let app = Router::new()
|
||||
.route("/crm/leads", post(create_lead))
|
||||
.with_state(state);
|
||||
Upstream {
|
||||
base_url: spawn_server(app).await,
|
||||
calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create_lead(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Json<Value> {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
// The fixture echoes the request's own payload in its identifier, so every valid call has a
|
||||
// *distinguishable* scoped output: two valid calls can never be confused with one another
|
||||
// (section 7.2 requires a scoped output per case, not one shared constant).
|
||||
let email = payload["email"].as_str().unwrap_or("unknown").to_owned();
|
||||
Json(json!({ "id": format!("lead_for_{email}"), "email": payload["email"] }))
|
||||
}
|
||||
|
||||
pub(super) async fn test_registry() -> PostgresRegistry {
|
||||
let database_url = crank_test_support::postgres_schema_url("crank_dispatch_observer").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("the test PostgreSQL must accept connections");
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("the migrations must apply");
|
||||
PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("the registry must connect")
|
||||
}
|
||||
|
||||
pub(super) fn test_time() -> OffsetDateTime {
|
||||
OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).expect("a pinned timestamp")
|
||||
}
|
||||
|
||||
pub(super) fn workspace_id() -> WorkspaceId {
|
||||
WorkspaceId::new("ws_default")
|
||||
}
|
||||
|
||||
pub(super) fn agent_id() -> AgentId {
|
||||
AgentId::new(format!("agent_{AGENT_SLUG}"))
|
||||
}
|
||||
|
||||
pub(super) async fn publish_agent(
|
||||
registry: &PostgresRegistry,
|
||||
operation: &Operation<Schema, MappingSet>,
|
||||
) {
|
||||
let agent = Agent {
|
||||
id: agent_id(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: "Dispatch observer agent".to_owned(),
|
||||
description: "Curated MCP toolset".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
};
|
||||
let bindings = vec![AgentOperationBinding {
|
||||
operation_id: operation.id.clone(),
|
||||
operation_version: 1,
|
||||
tool_name: operation.name.clone(),
|
||||
tool_title: operation.tool_description.title.clone(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}];
|
||||
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be created");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be published");
|
||||
}
|
||||
|
||||
pub(super) async fn create_api_key(registry: &PostgresRegistry) -> String {
|
||||
let secret = format!("crk_dispatch_observer_{}", uuid::Uuid::now_v7().simple());
|
||||
let api_key = PlatformApiKey {
|
||||
id: PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
workspace_id: workspace_id(),
|
||||
agent_id: Some(agent_id()),
|
||||
key_kind: PlatformApiKeyKind::McpClient,
|
||||
name: "dispatch-observer".to_owned(),
|
||||
prefix: secret.chars().take(16).collect(),
|
||||
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
status: PlatformApiKeyStatus::Active,
|
||||
created_at: test_time(),
|
||||
last_used_at: None,
|
||||
expires_at: None,
|
||||
allowed_origins: Vec::new(),
|
||||
};
|
||||
registry
|
||||
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||
api_key: &api_key,
|
||||
secret_hash: &hash_access_secret(&secret),
|
||||
})
|
||||
.await
|
||||
.expect("the API key must be created");
|
||||
secret
|
||||
}
|
||||
|
||||
pub(super) fn hash_access_secret(secret: &str) -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes()))
|
||||
}
|
||||
|
||||
pub(super) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
|
||||
Operation {
|
||||
id: OperationId::new(format!("op_{TOOL_NAME}")),
|
||||
name: TOOL_NAME.to_owned(),
|
||||
display_name: "Create Lead".to_owned(),
|
||||
category: "sales".to_owned(),
|
||||
protocol: Protocol::Rest,
|
||||
security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
status: OperationStatus::Published,
|
||||
version: 1,
|
||||
target: Target::Rest(RestTarget {
|
||||
base_url: base_url.to_owned(),
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/crm/leads".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: object_schema("email"),
|
||||
output_schema: object_schema("id"),
|
||||
input_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.email".to_owned(),
|
||||
target: "$.request.body.email".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
output_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.response.body.id".to_owned(),
|
||||
target: "$.output.id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
execution_config: ExecutionConfig {
|
||||
timeout_ms: 1_000,
|
||||
retry_policy: None,
|
||||
response_cache: None,
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: ToolDescription {
|
||||
title: "Create Lead".to_owned(),
|
||||
description: "Creates a CRM lead".to_owned(),
|
||||
tags: Vec::new(),
|
||||
examples: Vec::new(),
|
||||
},
|
||||
samples: None,
|
||||
generated_draft: None,
|
||||
config_export: None,
|
||||
wizard_state: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: Some(test_time()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn object_schema(field_name: &str) -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::from([(
|
||||
field_name.to_owned(),
|
||||
Schema {
|
||||
kind: SchemaKind::String,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
)]),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn modern_meta() -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-dispatch-observer", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn legacy_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": { "name": TOOL_NAME, "arguments": { "email": email } }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `initialize` request body (the valid request form of the lifecycle operation).
|
||||
pub(super) fn legacy_initialize(id: u64) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `notifications/initialized` notification body (the valid notification form).
|
||||
///
|
||||
/// The `params` carry a valid `InitializeParams` payload so that the *only* difference from its
|
||||
/// request-shaped negative is the presence of `id`: a wire name must never be served as the other
|
||||
/// lifecycle action because of the envelope kind (G2).
|
||||
pub(super) fn initialized_notification() -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn modern_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"_meta": modern_meta(),
|
||||
"name": TOOL_NAME,
|
||||
"arguments": { "email": email }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) 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()),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn modern_headers() -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
|
||||
("Mcp-Method", "tools/call".to_owned()),
|
||||
("Mcp-Name", TOOL_NAME.to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.expect("the observed response body must be readable");
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// Compare the marker deltas of one observed request with the section 7.2 table row.
|
||||
pub(super) fn assert_deltas(case: &str, before: Snapshot, after: Snapshot, expected: Snapshot) {
|
||||
let actual = Snapshot::new(
|
||||
after.admission - before.admission,
|
||||
after.era_modern - before.era_modern,
|
||||
after.era_legacy - before.era_legacy,
|
||||
after.tools_service - before.tools_service,
|
||||
);
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: admission/era-modern/era-legacy/tools-service deltas must be \
|
||||
(admission, era_modern, era_legacy, tools_service) = {expected:?}, got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn assert_no_result(case: &str, body: &Value) {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{case}: a rejected request must not return a result, got {body}"
|
||||
);
|
||||
assert!(
|
||||
!body["error"].is_null(),
|
||||
"{case}: a rejected request must return a JSON-RPC error, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Compare the session-store operation deltas of one observed request.
|
||||
///
|
||||
/// Section 7.2 honest naming: these counters count *session-store operations* (`get`/`create`/
|
||||
/// `mark_initialized`), never dispatch, era-adapter or service entries — an in-service branch can
|
||||
/// reject before any outbound call, so no conclusion about a service entry is drawn from them.
|
||||
pub(super) fn assert_session_ops(
|
||||
case: &str,
|
||||
before: SessionOps,
|
||||
after: SessionOps,
|
||||
expected: SessionOps,
|
||||
) {
|
||||
let actual = SessionOps {
|
||||
get: after.get - before.get,
|
||||
create: after.create - before.create,
|
||||
mark_initialized: after.mark_initialized - before.mark_initialized,
|
||||
};
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: session-store operation deltas (get, create, mark_initialized) must be {expected:?}, \
|
||||
got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The scoped output of one valid call: the fixture echoes the request's own payload.
|
||||
pub(super) fn assert_scoped_output(case: &str, body: &Value, email: &str) {
|
||||
assert_eq!(
|
||||
body["result"]["structuredContent"]["id"],
|
||||
format!("lead_for_{email}"),
|
||||
"{case}: the valid call must return *its own* scoped output, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, the request's own scoped output and the admission's session reads.
|
||||
pub(super) async fn run_valid_legacy_call(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
id: u64,
|
||||
email: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&legacy_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
// A legacy request that carries a session is read by the admission (revision check) and again by
|
||||
// the adapter's session requirement: two reads, no creation and no mutation of the session.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `initialize` request: mints its own session, enters its own era-adapter, never
|
||||
/// touches the Tools service and makes no outbound call (the request-form control of G2).
|
||||
pub(super) async fn run_valid_legacy_initialize(harness: &Harness, id: u64, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&legacy_initialize(id),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy initialize must be served"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("a valid initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
assert!(
|
||||
!session_id.is_empty(),
|
||||
"{case}: the minted session id must not be empty"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
body["result"]["protocolVersion"], LEGACY_REVISION,
|
||||
"{case}: the initialize result must name the negotiated revision, got {body}"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The initialize request itself carries no session carrier, so the admission never reads the
|
||||
// store: the one operation is the session creation of the lifecycle handler.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 1,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `notifications/initialized` on an existing session: acknowledged, its own
|
||||
/// era-adapter, no Tools service, no outbound call, exactly one session initialization (G2 control).
|
||||
pub(super) async fn run_valid_initialized_notification(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
202,
|
||||
"{case}: the initialized notification must be acknowledged"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The admission's revision check reads the carried session, and the lifecycle handler reads it
|
||||
// once more before marking it initialized.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid modern `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, its own scoped output and *no* session-store operation at all (the modern era is stateless).
|
||||
pub(super) async fn run_valid_modern_call(harness: &Harness, id: u64, email: &str, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&modern_headers()),
|
||||
&modern_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid modern call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_eq!(body["result"]["resultType"], "complete");
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 1, 0, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The inert private registration used by the F5 add/remove proof (never registered in production).
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The inert private capability and method used only by the F5 proof (never registered in production).
|
||||
pub(super) fn inert_registration_extra() -> (CapabilityIdDescriptor, MethodDescriptor) {
|
||||
(
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_test_capability", &[("enabled", true)])),
|
||||
revisions: &[MODERN_REVISION, LEGACY_REVISION],
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: INERT_METHOD_NAME,
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HeaderSet(&[]),
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) const INERT_METHOD_NAME: &str = "inert/echo";
|
||||
|
||||
/// See [`inert_registration_extra`]: the "remove" case is the production registration itself (no inert
|
||||
/// capability, no inert method); the "add" case is the same tables plus the inert descriptor pair.
|
||||
pub(super) fn registration_without_inert_method() -> CapabilityRegistry {
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS)
|
||||
.expect("the production tables are a valid registration")
|
||||
}
|
||||
|
||||
pub(super) fn registration_with_inert_method() -> CapabilityRegistry {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert_registration_extra().0);
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(inert_registration_extra().1);
|
||||
CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the inert method descriptor is a valid registration")
|
||||
}
|
||||
|
||||
// Re-exported for the sibling `tests` module.
|
||||
pub(super) use super::{CounterSet, Snapshot};
|
||||
Reference in new issue
Block a user