//! 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 { 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( ®istry, &greeting_id, greeting_definition("Hello {{name}}"), ) .await; publish_prompt(®istry, &greeting_id, greeting_at).await; let review_at = create_prompt(®istry, &review_id, review_definition()).await; publish_prompt(®istry, &review_id, review_at).await; let archived_created = create_prompt(®istry, &archived_id, archived_definition()).await; let archived_at = publish_prompt(®istry, &archived_id, archived_created).await; let unbound_at = create_prompt(®istry, &unbound_id, review_definition()).await; publish_prompt(®istry, &unbound_id, unbound_at).await; create_prompt(®istry, &draft_id, draft_definition()).await; let other_at = create_prompt(®istry, &other_id, other_definition()).await; publish_prompt(®istry, &other_id, other_at).await; let agent_id = create_agent(®istry, SALES_AGENT_SLUG).await; bind_prompts( ®istry, &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(®istry, &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(®istry, OTHER_AGENT_SLUG).await; bind_prompts( ®istry, &other_agent_id, &[AgentPromptBinding { prompt_id: other_id, prompt_version: 1, }], ) .await .expect("another Agent binds its own Prompt"); publish_agent(®istry, &other_agent_id).await; let api_key = create_platform_api_key( ®istry, 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 }