//! Published Prompts fixture using the existing observed HTTP app and disposable PostgreSQL. use super::*; use crank_core::prompt::{PromptDefinition, PromptSensitivity}; use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::PromptId}; use crank_registry::model::{ AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest, SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest, }; use crank_registry::{CreateAgentRequest, PublishAgentRequest}; use crank_runtime::{ InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto, }; pub(super) fn definition(name: &str, content: &str) -> PromptDefinition { PromptDefinition::parse(&json!({ "name":name, "description":format!("Published {name}"), "arguments":[ {"name":"name","schema":{"type":"string"},"required":true}, {"name":"count","schema":{"type":"integer"},"required":false,"default":2}, {"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true}, {"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"} ], "messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}] })).unwrap() } pub(super) struct Endpoint { pub registry: crank_registry::PostgresRegistry, pub counters: Arc, pub key: String, pub url: String, pub archived_at: time::OffsetDateTime, server: tokio::task::JoinHandle<()>, } impl Drop for Endpoint { fn drop(&mut self) { self.server.abort(); } } impl Endpoint { pub async fn started() -> Self { crank_test_support::postgres_schema_url_for_task("prompts_owner", "t_160a763a").await; let registry = test_registry().await; let mut archived_at = test_time(); for (id, name, publish) in [ ("prm_a", "greeting", true), ("prm_b", "archived-prompt", true), ("prm_c", "unbound-prompt", true), ("prm_d", "draft-prompt", false), ("prm_e", "other-agent-prompt", true), ] { let row = registry .create_prompt_draft(CreatePromptDraftRequest { workspace_id: workspace_id(), prompt_id: PromptId::new(id), sensitivity: PromptSensitivity::Internal, definition: definition( name, "Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}", ), created_at: time::OffsetDateTime::now_utc(), }) .await .unwrap(); if publish { let row = registry .publish_prompt_draft(PublishPromptRequest { workspace_id: workspace_id(), prompt_id: PromptId::new(id), expected_updated_at: row.updated_at, published_at: time::OffsetDateTime::now_utc(), }) .await .unwrap(); if id == "prm_b" { archived_at = row.updated_at; } } } for (id, slug) in [ (agent_id(), AGENT_SLUG), ( crank_core::AgentId::new("agent_other_prompts"), "other-prompts", ), ] { registry .create_agent(CreateAgentRequest { agent: &Agent { id: id.clone(), workspace_id: workspace_id(), slug: slug.into(), display_name: "SDK Prompts".into(), description: String::new(), status: AgentStatus::Draft, current_draft_version: 1, latest_published_version: None, created_at: test_time(), updated_at: test_time(), published_at: None, }, version: &AgentVersion { agent_id: id, version: 1, status: AgentStatus::Draft, instructions: json!({}), tool_selection_policy: ToolSelectionPolicy::default(), created_at: test_time(), }, bindings: &[], }) .await .unwrap(); } let other_agent = crank_core::AgentId::new("agent_other_prompts"); registry .save_agent_catalog_config_editable_with_prompts( SaveAgentCatalogConfigRequest { workspace_id: &workspace_id(), agent_id: &other_agent, agent_version: 1, bindings: &[], tool_selection_policy: &ToolSelectionPolicy::default(), resource_bindings: &[], expected_state: None, }, &[AgentPromptBinding { prompt_id: PromptId::new("prm_e"), prompt_version: 1, }], ) .await .unwrap(); registry .publish_agent(PublishAgentRequest { workspace_id: &workspace_id(), agent_id: &other_agent, version: 1, published_at: &test_time(), published_by: Some("alice"), expected_state: None, }) .await .unwrap(); registry .save_agent_catalog_config_editable_with_prompts( SaveAgentCatalogConfigRequest { workspace_id: &workspace_id(), agent_id: &agent_id(), agent_version: 1, bindings: &[], tool_selection_policy: &ToolSelectionPolicy::default(), resource_bindings: &[], expected_state: None, }, &[ AgentPromptBinding { prompt_id: PromptId::new("prm_a"), prompt_version: 1, }, AgentPromptBinding { prompt_id: PromptId::new("prm_b"), prompt_version: 1, }, ], ) .await .unwrap(); 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 .unwrap(); let archived_at = registry .archive_prompt_draft(ArchivePromptRequest { workspace_id: workspace_id(), prompt_id: PromptId::new("prm_b"), expected_updated_at: archived_at, archived_at: time::OffsetDateTime::now_utc(), }) .await .unwrap() .updated_at; // A mutable v2 draft must not change the bound v1 rendering or discovery metadata. let draft = registry .get_prompt_draft(&workspace_id(), &PromptId::new("prm_a")) .await .unwrap(); registry .update_prompt_draft(UpdatePromptDraftRequest { workspace_id: workspace_id(), prompt_id: PromptId::new("prm_a"), sensitivity: PromptSensitivity::Internal, definition: definition("changed-draft", "Changed {{name}}"), expected_updated_at: draft.updated_at, updated_at: time::OffsetDateTime::now_utc(), }) .await .unwrap(); let key = create_api_key(®istry).await; let counters = Arc::new(CounterSet::default()); let app = crate::build_app( registry.clone(), Duration::ZERO, None, 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()), Arc::new(InMemoryCoordinationStateStore::default()), Arc::new(crate::session::InMemorySessionStore::default()), Arc::new(crate::auth::CommunityMachineCredentialVerifier), ); let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({ let counters = counters.clone(); move |request: axum::extract::Request, next: axum::middleware::Next| { let counters = counters.clone(); async move { observe_body(next.run(request).await, counters) } } })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!( "http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}", listener.local_addr().unwrap() ); let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); Self { registry, counters, key, url, archived_at, server, } } pub async fn post( &self, revision: &str, session: Option<&str>, body: &Value, sse: bool, ) -> reqwest::Response { let mut request = reqwest::Client::new() .post(&self.url) .bearer_auth(&self.key) .header( "Accept", if sse { "text/event-stream, application/json" } else { "application/json" }, ) .header("x-request-id", "sdk-prompts-wire") .header( "traceparent", "00-11111111111111111111111111111111-2222222222222222-01", ) .header("MCP-Protocol-Version", revision); if let Some(session) = session { request = request.header("MCP-Session-Id", session); } if revision == MODERN_REVISION { request = request.header("Mcp-Method", body["method"].as_str().unwrap()); if let Some(name) = body["params"]["name"].as_str() { request = request.header("Mcp-Name", name); } } request.json(body).send().await.unwrap() } pub async fn session(&self, revision: &str) -> Option { if revision == MODERN_REVISION { return None; } let response = self .post(revision, None, &legacy_initialize(1), false) .await; assert_eq!(response.status(), 200); let session = response.headers()["MCP-Session-Id"] .to_str() .unwrap() .to_owned(); assert_eq!( json_body(response).await["result"]["protocolVersion"], revision ); assert_eq!( self.post(revision, Some(&session), &initialized_notification(), false) .await .status(), 202 ); Some(session) } }