//! Story 3.14: the era-neutral `prompts/list` and `prompts/get` service boundary. //! //! Both requests are answered only from the exact Published Prompt Versions bound in the active //! published Agent snapshot (`agent_prompt_bindings`, read in the same catalog transaction). A Draft, //! a foreign workspace Prompt and an unbound Prompt are therefore not addressable at all: they are //! absent from the bound array, so nothing here looks a Prompt up by a client-supplied id. //! //! Rendering reuses the accepted typed renderer (`PromptDefinition::preview`): every argument error //! (missing, unknown, wrong type, oversized) is decided there *before* a single message is produced, //! and the error outcome carries only the typed reason and the argument name — never a message, a //! dependency payload or metadata of another Prompt (AT-3.14-02). //! //! Archive is a lifecycle state, not a revoke: the immutable publication row survives, so the exact //! bound version of an existing Agent snapshot stays listing/serving (AT-3.14-03). Security //! revocation and dependency invalidation remain separate fail-closed states and are not modelled //! here. //! //! The wire shape stays in the adapters; this module never sees the envelope, the response mode or an //! `axum::Response`. use std::sync::Arc; use std::time::Instant; use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use crank_core::ids::ResourceId; use crank_core::prompt::{MAX_TEXT_BYTES, PromptError, PromptMessage, PromptRole}; use crank_core::prompt_composition::{ self, PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass, }; use crank_core::resource::ResourceKind; use crank_core::{ExecutionOrigin, InvocationSource, OperationSafetyClass, OperationStatus}; use crank_registry::model::PromptPublicationRecord; use crank_runtime::{ ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext, }; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use tracing::info; use crate::{app::AppState, protocol::ServiceContext}; /// Upper bound of one `prompts/list` page (same shape as `resources/list`). const MAX_PROMPTS_LIST_LIMIT: usize = 100; /// Cursor format version; independent of the shared Resource tokens by the `s` surface marker. const CURSOR_VERSION: u8 = 1; /// Surface marker that keeps a `resources/list` cursor from being replayed on `prompts/list`. const PROMPTS_SURFACE: u8 = 2; /// Parameters of a `prompts/list` command, already parsed by the adapter from the wire form. #[derive(Debug, Default, Deserialize)] pub(crate) struct PromptsListCommand { #[serde(default)] pub(crate) cursor: Option, #[serde(default)] pub(crate) limit: Option, } /// Parameters of a `prompts/get` command. #[derive(Debug, Deserialize)] pub(crate) struct PromptGetCommand { pub(crate) name: String, /// Typed arguments; a non-object shape is rejected by the adapter before dispatch. #[serde(default)] pub(crate) arguments: Option>, } /// A command the shared Prompts service accepts. pub(crate) enum PromptsCommand { List(PromptsListCommand), Get(PromptGetCommand), } /// A neutral outcome of a shared Prompts command. pub(crate) enum PromptsOutcome { Listed { prompts: Vec, next_cursor: Option, }, Got { description: Option, messages: Vec, }, /// The request cannot be addressed as a page (malformed/stale/cross-scope cursor). InvalidParams(String), /// Unknown, Draft, foreign or unbound Prompt name: one safe outcome that carries no Prompt /// metadata and cannot distinguish the cases. NotAvailable, /// The bound definition rejected the supplied arguments before any rendering; only the typed /// reason and the argument name of the *bound* Prompt are carried. ArgumentsRejected { reason: &'static str, argument: Option, }, /// A pinned dependency of the bound Prompt cannot be read right now. The outcome carries only /// the declaration position: never dependency content, name or the pinned identity's metadata. DependencyUnavailable { position: usize }, /// The bound snapshot could not be read or verified. CatalogUnavailable, } /// Handle one shared Prompts command for the revision the adapter serves. pub(crate) async fn handle_prompts_command( state: &Arc, context: ServiceContext<'_>, revision: &str, command: PromptsCommand, ) -> PromptsOutcome { let catalog = match state .catalog .get_catalog(context.workspace_slug, context.agent_slug) .await { Ok(catalog) => catalog, Err(_error) => return PromptsOutcome::CatalogUnavailable, }; let workspace_id = match state .registry .published_agent_workspace_id(context.workspace_slug, context.agent_slug) .await { Ok(workspace_id) => workspace_id, Err(_error) => return PromptsOutcome::CatalogUnavailable, }; // The whole bound snapshot is resolved once: pagination addresses this immutable array, so a // page boundary cannot shift when a Draft changes underneath the request. let publications = match state .registry .resolve_bound_prompt_publications(&workspace_id, &catalog.prompts) .await { Ok(publications) => publications, Err(_error) => return PromptsOutcome::CatalogUnavailable, }; let scope = CursorScope { workspace_slug: context.workspace_slug, agent_slug: context.agent_slug, catalog_revision: &catalog.catalog_revision, revision, }; match command { PromptsCommand::List(list) => list_prompts(&publications, &scope, list), PromptsCommand::Get(get) => { get_prompt(state, &context, &workspace_id, &publications, &get).await } } } fn list_prompts( publications: &[PromptPublicationRecord], scope: &CursorScope<'_>, command: PromptsListCommand, ) -> PromptsOutcome { let start = match command.cursor.as_deref() { Some(cursor) => match decode_cursor(cursor, scope, publications.len()) { Some(offset) => offset, None => { return PromptsOutcome::InvalidParams("invalid prompts/list cursor".to_owned()); } }, None => 0, }; let limit = command .limit .unwrap_or(publications.len()) .clamp(1, MAX_PROMPTS_LIST_LIMIT); let end = start.saturating_add(limit).min(publications.len()); let prompts: Vec = publications[start..end] .iter() .map(|publication| { json!({ "name": publication.name, "description": publication.description, "arguments": publication.definition.arguments_json(), }) }) .collect(); // Discovery telemetry: counts and the served revision only — never a Prompt name or content. info!( name: "mcp.prompts.list", outcome = "ok", prompt_count = prompts.len(), bound_prompt_count = publications.len(), revision = scope.revision, "prompt list outcome" ); let next_cursor = (end < publications.len()).then(|| encode_cursor(scope, end)); PromptsOutcome::Listed { prompts, next_cursor, } } async fn get_prompt( state: &Arc, context: &ServiceContext<'_>, workspace_id: &crank_core::WorkspaceId, publications: &[PromptPublicationRecord], command: &PromptGetCommand, ) -> PromptsOutcome { // Deterministic exact binding: the bound snapshot is ordered by `prompt_id`, and MCP addresses a // Prompt by name only. The first exact bound publication of that name is served, so the answer // does not depend on query timing or map order. // shortcut: Prompt names are not constrained unique, so two bound Prompts sharing a name are // resolved by prompt_id order; upgrade to a workspace-unique name constraint if the product // needs to address both. let Some(publication) = publications .iter() .find(|publication| publication.name == command.name) else { return PromptsOutcome::NotAvailable; }; let supplied = command.arguments.clone().unwrap_or_default(); // Story 3.16: the pinned content of every declared dependency is read through the Resource // contract of 3.8/3.11 and composed by the same renderer the admin preview uses. let contents = dependency_contents(state, context, workspace_id, &publication.dependencies).await; render_publication(publication, &supplied, &contents) } /// Pure rendering step: the accepted typed renderer plus pinned dependency insertion. fn render_publication( publication: &PromptPublicationRecord, supplied: &Map, contents: &[Option>], ) -> PromptsOutcome { match prompt_composition::render( &publication.definition, &publication.dependencies, supplied, contents, ) { Ok(messages) => { info!( name: "mcp.prompts.get", outcome = "ok", message_count = messages.len(), dependency_count = publication.dependencies.len(), "prompt get outcome" ); PromptsOutcome::Got { description: Some(publication.description.clone()), messages: message_values(&messages), } } Err(PromptCompositionError::Template(error)) => reject_arguments(error, supplied), // A published definition that cannot produce its pinned content right now is a total // failure: no message list, only the declaration position (AC6, AT-3.14-02 invariant). Err(PromptCompositionError::DependencyUnavailable { position }) | Err(PromptCompositionError::DependencyCredentialFinding { position }) | Err(PromptCompositionError::DependencyAccessBypassFinding { position }) | Err(PromptCompositionError::DependencyRepresentationUnsupported { position }) => { PromptsOutcome::DependencyUnavailable { position } } Err(PromptCompositionError::DependencyUnused { position, .. }) => { PromptsOutcome::DependencyUnavailable { position } } Err(PromptCompositionError::CredentialFinding { .. }) | Err(PromptCompositionError::AccessBypassFinding { .. }) => { PromptsOutcome::CatalogUnavailable } } } /// Pinned content of every dependency, indexed by declaration position. /// /// The exact published version is re-checked at read time (revocation is a live gate), then read /// through the single immutable artifact root for a static dependency. A dynamic (template) /// dependency is read by the Story 3.11 Resource runtime — the same read path the agent uses for /// its bound templates — and is therefore never substituted with its definition text. async fn dependency_contents( state: &Arc, context: &ServiceContext<'_>, workspace_id: &crank_core::WorkspaceId, pins: &[PromptDependencyPin], ) -> Vec>> { let mut contents = Vec::with_capacity(pins.len()); for pin in pins { let resource_id = ResourceId::new(pin.resource_id.clone()); let bytes = match pin.source_class { PromptDependencySourceClass::Static => { match state .registry .resource_is_revoked(workspace_id, &resource_id) .await { Ok(false) => match state .registry .resolve_resource_publication( workspace_id.as_str(), &resource_id, pin.version, ) .await { Ok(resolved) => state .artifact_store .as_ref() .and_then(|store| store.read(&resolved.artifact_ref).ok()), Err(_) => None, }, Ok(true) | Err(_) => None, } } PromptDependencySourceClass::Dynamic => { read_pinned_template_content( state, context, workspace_id, &resource_id, pin.version, ) .await } }; contents.push(bytes); } contents } /// Story 3.16 §4/§6: content of one pinned dynamic (template) dependency. /// /// A Prompt dependency names only the exact `(resource_id, version)` of the template, so the /// declared read Operation is executed through the accepted 3.11 Resource runtime with its own /// authorization, outbound, size and cache contract and the live revocation gate, using the /// template's own parameter defaults. A parameter without a default cannot be supplied by a /// Prompt. Every failure stays `None`: the caller turns that into the structured /// `prompt_dependency_unavailable` refusal instead of inserting definition text or stale content. async fn read_pinned_template_content( state: &Arc, context: &ServiceContext<'_>, workspace_id: &crank_core::WorkspaceId, resource_id: &ResourceId, version: u32, ) -> Option> { let (publication, stored) = state .registry .resolve_resource_template_publication(workspace_id.as_str(), resource_id, version) .await .ok()?; let kind = ResourceKind::parse(&publication.kind)?; if !kind.allows_mime_type(&publication.mime_type) { return None; } let definition: Value = serde_json::from_str(&stored.definition_json).ok()?; let source = crank_core::resource::TemplateSource::parse(&definition).ok()?; let operation_id = crank_core::OperationId::new(source.operation_id.clone()); let operation_record = state .registry .get_operation_version(workspace_id, &operation_id, source.operation_version) .await .ok()??; if operation_record.status != OperationStatus::Published { return None; } match state .registry .get_operation_summary(workspace_id, &operation_id) .await { Ok(Some(summary)) if summary.status != OperationStatus::Archived => {} _ => return None, } if !crate::access::credential_allows_security_level( context.credential, operation_record.snapshot.security_level, ) { return None; } let operation = RuntimeOperation::from(operation_record.snapshot.clone()); let safety = operation .execution_config .safety .as_ref() .map(|policy| policy.class); if safety != Some(OperationSafetyClass::Read) || operation .execution_config .approval_policy .as_ref() .is_some_and(|policy| policy.required) || !matches!(&operation.target, crank_core::Target::Rest(target) if matches!(target.method, crank_core::HttpMethod::Get | crank_core::HttpMethod::Head)) { return None; } let mut input = Map::new(); for parameter in &source.parameters { let parameter_schema: crank_schema::Schema = serde_json::from_value(parameter.schema.clone()).ok()?; let value = parameter_schema.default_value.clone()?; crank_runtime::validate_resource_template_parameter(¶meter_schema, &value).ok()?; if !super::resources::set_input_path(&mut input, ¶meter.input_path, value) { return None; } } let agent_id = state .registry .published_agent_id(context.workspace_slug, context.agent_slug) .await .ok()?; let request_context = RuntimeRequestContext::from_correlation(context.correlation) .with_response_cache_scope( workspace_id.as_str().to_owned(), agent_id.as_str().to_owned(), ) .with_resource_response_cache( resource_id.as_str(), publication.version, source.cache.ttl_ms, source.cache.max_bytes, ) .with_metering_context( workspace_id.clone(), Some(agent_id.clone()), InvocationSource::AgentToolCall, ); let auth = crate::app::resolve_operation_auth(state, workspace_id, &operation.execution_config) .await .ok()?; let input = Value::Object(input); let request = RuntimeExecutionRequest::try_new( workspace_id, ExecutionOrigin::AgentSnapshot, Some(&agent_id), &operation, &input, ExecutionAuthorization::Authorized, auth.as_ref(), &request_context, Instant::now() + std::time::Duration::from_millis(operation.execution_config.timeout_ms.max(1)), ) .ok()?; // The live Resource lock is acquired only after registry/auth lookups, then held through // dispatch: a revocation before this point closes the read. let guard = state .registry .begin_authorized_resource_template_read( workspace_id.as_str(), resource_id, publication.version, ) .await .ok()?; let success = state.runtime.execute_outcome(request).await.ok()?; let max_bytes = usize::try_from(source.cache.max_bytes) .unwrap_or(crank_artifacts::MAX_ARTIFACT_BYTES) .min(crank_artifacts::MAX_ARTIFACT_BYTES); let bytes = match kind { ResourceKind::Text => success.output.as_str().map(|text| text.as_bytes().to_vec()), ResourceKind::Json if !success.output.is_null() => serde_json::to_vec(&success.output).ok(), _ => None, }?; if bytes.is_empty() || bytes.len() > max_bytes { return None; } guard.commit().await.ok()?; Some(bytes) } /// Map a renderer rejection onto the typed reasons of AT-3.14-02 without re-validating: the renderer /// decided, this only classifies its verdict, and the argument name belongs to the bound Prompt the /// client is already allowed to see in `prompts/list`. fn reject_arguments(error: PromptError, supplied: &Map) -> PromptsOutcome { match error { PromptError::MissingArgument(argument) => PromptsOutcome::ArgumentsRejected { reason: "missing_argument", argument: Some(argument), }, PromptError::UnknownArgument(argument) => PromptsOutcome::ArgumentsRejected { reason: "unknown_argument", argument: Some(argument), }, PromptError::InvalidArgument(argument) => { let oversized = supplied .get(&argument) .and_then(Value::as_str) .is_some_and(|text| text.len() > MAX_TEXT_BYTES); PromptsOutcome::ArgumentsRejected { reason: if oversized { "argument_too_large" } else { "argument_invalid" }, argument: Some(argument), } } // A stored definition that no longer parses or renders is corruption, not a client error: // it fails closed instead of being answered as an argument rejection. PromptError::InvalidDefinition | PromptError::InvalidTemplate => { PromptsOutcome::CatalogUnavailable } } } fn message_values(messages: &[PromptMessage]) -> Vec { messages .iter() .map(|message| { // Pinned `PromptMessage.content` is a `ContentBlock`, so the accepted renderer's text // becomes one `TextContent` block. `role` is served exactly as published: the accepted // product model allows `system|user|assistant`, while the pinned wire `Role` union is // `user|assistant`; a system message is therefore preserved rather than silently // remapped or dropped (flagged for the product decision in the story handoff). json!({ "role": match message.role { PromptRole::System => "system", PromptRole::User => "user", PromptRole::Assistant => "assistant", }, "content": {"type": "text", "text": message.content}, }) }) .collect() } /// The immutable scope a continuation token is bound to. A cursor from another workspace, Agent, /// catalog revision, protocol revision or surface is never mixed into a page. struct CursorScope<'a> { workspace_slug: &'a str, agent_slug: &'a str, catalog_revision: &'a str, revision: &'a str, } #[derive(Serialize, Deserialize)] struct CursorPayload { v: u8, s: u8, w: String, a: String, c: String, r: String, o: usize, } fn encode_cursor(scope: &CursorScope<'_>, offset: usize) -> String { let payload = CursorPayload { v: CURSOR_VERSION, s: PROMPTS_SURFACE, w: scope.workspace_slug.to_owned(), a: scope.agent_slug.to_owned(), c: scope.catalog_revision.to_owned(), r: scope.revision.to_owned(), o: offset, }; let encoded = serde_json::to_vec(&payload).unwrap_or_default(); URL_SAFE_NO_PAD.encode(encoded) } fn decode_cursor(raw: &str, scope: &CursorScope<'_>, len: usize) -> Option { let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?; let payload: CursorPayload = serde_json::from_slice(&bytes).ok()?; let matches = payload.v == CURSOR_VERSION && payload.s == PROMPTS_SURFACE && payload.w == scope.workspace_slug && payload.a == scope.agent_slug && payload.c == scope.catalog_revision && payload.r == scope.revision; (matches && payload.o <= len).then_some(payload.o) } #[cfg(test)] mod tests { use super::*; use crank_core::ids::PromptId; use crank_core::prompt::{PromptDefinition, PromptSensitivity}; use time::OffsetDateTime; fn publication( prompt_id: &str, name: &str, messages: &str, arguments: Value, ) -> PromptPublicationRecord { let messages: Value = serde_json::from_str(messages).expect("message fixture is JSON"); let definition = PromptDefinition::parse(&json!({ "name": name, "description": "Description", "arguments": arguments, "messages": messages, })) .expect("definition parses"); PromptPublicationRecord { prompt_id: PromptId::new(prompt_id), version: 1, name: name.to_owned(), description: "Description".to_owned(), sensitivity: PromptSensitivity::Internal, definition, dependencies: Vec::new(), published_at: OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap(), } } fn greeting() -> PromptPublicationRecord { publication( "prm_greeting", "greeting", r#"[{"role":"system","content":"Be brief."},{"role":"user","content":"Hello {{name}}"}]"#, json!([ {"name":"name","schema":{"type":"string"},"required":true}, {"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"} ]), ) } fn cursor_scope(revision: &str) -> CursorScope<'_> { CursorScope { workspace_slug: "default", agent_slug: "assistant", catalog_revision: "agent-version-1-catalog-revision-7", revision, } } fn get(name: &str, arguments: Value) -> PromptsOutcome { let publications = [greeting()]; let Some(publication) = publications .iter() .find(|publication| publication.name == name) else { return PromptsOutcome::NotAvailable; }; render_publication( publication, &arguments.as_object().cloned().unwrap_or_default(), &[], ) } /// AT-3.14-01: the list item carries the typed argument metadata and no message content. #[test] fn list_item_carries_typed_arguments_and_no_messages() { let scope = cursor_scope("2026-07-28"); let PromptsOutcome::Listed { prompts, .. } = list_prompts(&[greeting()], &scope, PromptsListCommand::default()) else { panic!("a bound page must list"); }; assert_eq!(prompts.len(), 1); assert_eq!(prompts[0]["name"], json!("greeting")); assert_eq!( prompts[0]["arguments"][0]["schema"]["type"], json!("string") ); assert_eq!(prompts[0]["arguments"][1]["default"], json!("warm")); assert!( prompts[0].get("messages").is_none(), "prompts/list must not disclose message content" ); } /// AT-3.14-04: a page is deterministic and its cursor is scoped to surface/context. #[test] fn pagination_is_deterministic_and_surface_scoped() { let items = vec![ publication( "prm_a", "a", r#"[{"role":"user","content":"A"}]"#, json!([]), ), publication( "prm_b", "b", r#"[{"role":"user","content":"B"}]"#, json!([]), ), publication( "prm_c", "c", r#"[{"role":"user","content":"C"}]"#, json!([]), ), ]; let scope = cursor_scope("2026-07-28"); let PromptsOutcome::Listed { prompts, next_cursor, } = list_prompts( &items, &scope, PromptsListCommand { cursor: None, limit: Some(2), }, ) else { panic!("first page must list"); }; assert_eq!(prompts.len(), 2); let cursor = next_cursor.expect("a further page exists"); let PromptsOutcome::Listed { prompts: second, .. } = list_prompts( &items, &scope, PromptsListCommand { cursor: Some(cursor.clone()), limit: Some(2), }, ) else { panic!("second page must list"); }; assert_eq!(second.len(), 1); assert_eq!(second[0]["name"], json!("c")); // The same cursor is refused on another revision and on a replayed page boundary of a // different Agent: a page is never mixed across scopes. assert!(matches!( list_prompts( &items, &cursor_scope("2025-11-25"), PromptsListCommand { cursor: Some(cursor.clone()), limit: Some(2), }, ), PromptsOutcome::InvalidParams(_) )); let mut other_agent = cursor_scope("2026-07-28"); other_agent.agent_slug = "other-assistant"; assert!(matches!( list_prompts( &items, &other_agent, PromptsListCommand { cursor: Some(cursor), limit: Some(2), }, ), PromptsOutcome::InvalidParams(_) )); // Malformed token: invalid params, never a first page. assert!(matches!( list_prompts( &items, &scope, PromptsListCommand { cursor: Some("not-a-cursor".to_owned()), limit: None, }, ), PromptsOutcome::InvalidParams(_) )); } /// AT-3.14-02: typed arguments render deterministically, defaults included. #[test] fn get_renders_typed_arguments_with_defaults() { let PromptsOutcome::Got { description, messages, } = get("greeting", json!({"name": "Ada"})) else { panic!("valid arguments must render"); }; assert_eq!(description.as_deref(), Some("Description")); assert_eq!(messages.len(), 2); assert_eq!(messages[0]["role"], json!("system")); assert_eq!( messages[1]["content"], json!({"type": "text", "text": "Hello Ada"}) ); assert_eq!( get("greeting", json!({"name": "Ada"})).to_owned_messages(), messages ); } /// AT-3.14-02: every argument failure is a typed rejection with no rendered message. #[test] fn get_rejects_arguments_before_rendering() { for (arguments, reason) in [ (json!({}), "missing_argument"), (json!({"name": "Ada", "extra": "x"}), "unknown_argument"), (json!({"name": 5}), "argument_invalid"), (json!({"name": "Ada", "tone": "loud"}), "argument_invalid"), ( json!({"name": "x".repeat(MAX_TEXT_BYTES + 1)}), "argument_too_large", ), ] { match get("greeting", arguments) { PromptsOutcome::ArgumentsRejected { reason: observed, argument, } => { assert_eq!(observed, reason); assert!(argument.is_some(), "the bound argument name is named"); } PromptsOutcome::Got { messages, .. } => { panic!("{reason}: no partial rendering is allowed, got {messages:?}"); } _ => panic!("{reason}: expected a typed argument rejection"), } } } /// AT-3.14-01: an unknown name is indistinguishable from Draft/foreign/unbound. #[test] fn get_unknown_name_is_not_available() { assert!(matches!( get("not-bound", json!({"name": "Ada"})), PromptsOutcome::NotAvailable )); } impl PromptsOutcome { fn to_owned_messages(&self) -> Vec { match self { Self::Got { messages, .. } => messages.clone(), _ => Vec::new(), } } } }