//! Story 3.17: the era-neutral `completion/complete` service boundary. //! //! Both supported revisions share this one service; the wire envelope, the response mode and the //! `axum::Response` stay in the era adapters, exactly as for the Tools/Resources/Prompts services. //! //! Scope of the answer (AC1): a suggestion list is derived *only* from the typed schema of one exact //! Published Prompt argument, or of one exact parameter of one exact Published Resource template, //! that is already bound to the active published Agent snapshot. There is no lookup by a //! client-supplied id, no scan of draft/foreign/unbound rows and no search over arbitrary database //! values: a `ref` that is not part of the bound snapshot is answered with the same indistinguishable //! refusal as an unknown argument, so neither foreign Prompt names nor foreign template URIs can be //! probed through this method. Schemas without an enumeration produce an empty suggestion list //! instead of an invented one. //! //! Bounds (AC2): the argument name/value, the reference and the optional completion context are //! length/count-bounded before any catalog read, and the schema enumeration itself is read through a //! fixed cap. A truncated scan is reported honestly (`total` omitted, `hasMore: true`) rather than as //! an exact count. Every telemetry field is a count, a fixed label or the served revision — never a //! Prompt name, a URI template, an argument name or a client-supplied value, so the bounded metric //! label set cannot be widened by a request. use std::{collections::HashSet, sync::Arc}; use crank_core::resource::TemplateSource; use crank_schema::Schema; use serde::Deserialize; use serde_json::{Map, Value}; use tracing::info; use crate::{app::AppState, protocol::ServiceContext}; /// Pinned `CompleteResult.completion.values` bound (`@maxItems 100`). const MAX_COMPLETION_VALUES: usize = 100; /// Schema enumeration values inspected per request: the bound that keeps a hostile or corrupted /// schema from turning one completion request into unbounded work. const MAX_SCHEMA_VALUES: usize = 1_024; /// Bound of a completion argument name (`params.argument.name`). const MAX_ARGUMENT_NAME_BYTES: usize = 128; /// Bound of the partial token a client sends (`params.argument.value`); the pinned schema types it as /// an opaque string, so an oversized token is a malformed request, not a matching challenge. const MAX_ARGUMENT_VALUE_BYTES: usize = 1_024; /// Bound of `ref/prompt.name`. const MAX_REFERENCE_NAME_BYTES: usize = 256; /// Bound of `ref/resource.uri` (a URI template as served by `resources/templates/list`). const MAX_REFERENCE_URI_BYTES: usize = 2_048; /// Bound of the optional previously-resolved `context.arguments` map. const MAX_CONTEXT_ARGUMENTS: usize = 32; /// The one safe detail of a malformed completion request: it never echoes the offending value. const INVALID_PARAMS: &str = "invalid completion/complete parameters"; /// Parameters of a `completion/complete` command, already parsed by the adapter from the wire form. #[derive(Debug, Deserialize)] pub(crate) struct CompletionCommand { /// `ref` of the pinned schema: `{type: "ref/prompt", ...}` or `{type: "ref/resource", ...}`. #[serde(rename = "ref")] pub(crate) reference: CompletionReference, /// The argument whose value is being completed. pub(crate) argument: CompletionArgument, /// Optional previously-resolved variables. The typed schema of the addressed argument is the only /// suggestion source, so this context is validated and otherwise not used: it never widens the /// answer beyond the published enumeration. #[serde(default)] pub(crate) context: Option, } /// The typed `ref` union of the pinned completion request. #[derive(Debug, Deserialize)] #[serde(tag = "type")] pub(crate) enum CompletionReference { /// One Prompt, addressed by the name it is listed under in `prompts/list`. #[serde(rename = "ref/prompt")] Prompt { name: String }, /// One Resource template, addressed by the URI template served by `resources/templates/list`. #[serde(rename = "ref/resource")] Resource { uri: String }, } #[derive(Debug, Deserialize)] pub(crate) struct CompletionArgument { pub(crate) name: String, pub(crate) value: String, } #[derive(Debug, Default, Deserialize)] pub(crate) struct CompletionContext { #[serde(default)] pub(crate) arguments: Option>, } /// A neutral outcome of the shared completion service. pub(crate) enum CompletionOutcome { /// Bounded suggestions in schema order. `total` is absent when the enumeration scan was /// truncated, because then only a lower bound of the option count is known. Completed { values: Vec, total: Option, has_more: bool, }, /// The request is malformed or exceeds a fixed bound: one safe detail, no echoed input. InvalidParams(&'static str), /// Unknown, Draft, foreign, unbound or archived-out reference, or an argument the addressed /// schema does not declare. One outcome that cannot distinguish these cases. NotAvailable, /// The bound snapshot or the addressed typed schema could not be read safely. CatalogUnavailable, } /// Serve one `completion/complete` command for the revision the adapter negotiated (AC1/AC3). pub(crate) async fn handle_completion_command( state: &Arc, context: ServiceContext<'_>, revision: &str, command: CompletionCommand, ) -> CompletionOutcome { if command.validate().is_some() { return CompletionOutcome::InvalidParams(INVALID_PARAMS); } let catalog = match state .catalog .get_catalog(context.workspace_slug, context.agent_slug) .await { Ok(catalog) => catalog, Err(_error) => { return refused(revision, command.reference_label(), "catalog_unavailable"); } }; 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 refused(revision, command.reference_label(), "catalog_unavailable"); } }; match &command.reference { CompletionReference::Prompt { name } => { // The same exact bound snapshot `prompts/list` and `prompts/get` serve, so a Draft, // foreign or unbound Prompt has no candidates at all. let publications = match state .registry .resolve_bound_prompt_publications(&workspace_id, &catalog.prompts) .await { Ok(publications) => publications, Err(_error) => { return refused(revision, "prompt", "catalog_unavailable"); } }; // Deterministic exact binding, identical to `prompts/get`: names are not constrained // unique, so the first bound publication in `prompt_id` order is addressed. let Some(publication) = publications .iter() .find(|publication| &publication.name == name) else { return not_available(revision, "prompt"); }; let Some(argument) = publication .definition .arguments() .iter() .find(|argument| argument.name() == command.argument.name) else { return not_available(revision, "prompt"); }; let candidates = argument .enumeration() .iter() .filter_map(value_text) .collect::>(); completed(revision, "prompt", &command.argument.value, candidates) } CompletionReference::Resource { uri } => { // The same admitted bound template array `resources/templates/list` serves: revoked, // foreign and unbound templates are already filtered out by the registry adapter. let admitted = match state .registry .list_admitted_resource_templates(workspace_id.as_str(), &catalog.resources) .await { Ok(admitted) => admitted, Err(_error) => { return refused(revision, "resource", "catalog_unavailable"); } }; let mut addressable = None; for template in &admitted { // A bound definition that no longer parses is simply not addressable here; it never // turns an unrelated completion request into an error. let Ok(definition) = serde_json::from_str::(&template.source.definition_json) else { continue; }; let Ok(source) = TemplateSource::parse(&definition) else { continue; }; if &source.uri_template == uri { addressable = Some(source); break; } } let Some(source) = addressable else { return not_available(revision, "resource"); }; let Some(parameter) = source .parameters .iter() .find(|parameter| parameter.name == command.argument.name) else { return not_available(revision, "resource"); }; let Ok(schema) = serde_json::from_value::(parameter.schema.clone()) else { return refused(revision, "resource", "schema_unavailable"); }; completed( revision, "resource", &command.argument.value, schema.enum_values, ) } } } impl CompletionCommand { /// The bounded input contract of AC2: nothing here depends on catalog content, so a malformed or /// oversized request is refused before the first registry read. fn validate(&self) -> Option<&'static str> { match &self.reference { CompletionReference::Prompt { name } => { if name.is_empty() || name.len() > MAX_REFERENCE_NAME_BYTES { return Some(INVALID_PARAMS); } } CompletionReference::Resource { uri } => { if uri.is_empty() || uri.len() > MAX_REFERENCE_URI_BYTES { return Some(INVALID_PARAMS); } } } if self.argument.name.is_empty() || self.argument.name.len() > MAX_ARGUMENT_NAME_BYTES { return Some(INVALID_PARAMS); } if self.argument.value.len() > MAX_ARGUMENT_VALUE_BYTES { return Some(INVALID_PARAMS); } let arguments = self .context .as_ref() .and_then(|context| context.arguments.as_ref())?; if arguments.len() > MAX_CONTEXT_ARGUMENTS { return Some(INVALID_PARAMS); } // The pinned schema types the context values as strings; a non-string or oversized value is // malformed rather than something to coerce. for (name, value) in arguments { if name.len() > MAX_ARGUMENT_NAME_BYTES { return Some(INVALID_PARAMS); } let Some(text) = value.as_str() else { return Some(INVALID_PARAMS); }; if text.len() > MAX_ARGUMENT_VALUE_BYTES { return Some(INVALID_PARAMS); } } None } /// The fixed telemetry label of the reference kind (never the name or the URI itself). const fn reference_label(&self) -> &'static str { match self.reference { CompletionReference::Prompt { .. } => "prompt", CompletionReference::Resource { .. } => "resource", } } } /// One suggestion list from an already-authorized typed enumeration. /// /// Matching is a case-insensitive prefix test over the schema order, so the answer is deterministic /// and independent of query timing. Duplicates are collapsed before counting, the response is capped /// at the pinned 100 values, and a truncated schema scan never claims an exact `total`. fn completed( revision: &str, reference: &'static str, value: &str, candidates: Vec, ) -> CompletionOutcome { let truncated = candidates.len() > MAX_SCHEMA_VALUES; let mut seen = HashSet::new(); let mut matched = Vec::new(); for candidate in candidates.into_iter().take(MAX_SCHEMA_VALUES) { if !prefix_match(&candidate, value) { continue; } if !seen.insert(candidate.clone()) { continue; } matched.push(candidate); } let total = matched.len(); let values: Vec = matched.into_iter().take(MAX_COMPLETION_VALUES).collect(); let has_more = truncated || total > values.len(); info!( name: "mcp.completion.complete", outcome = "ok", reference, suggestion_count = values.len(), has_more, total_known = !truncated, revision, "completion outcome" ); CompletionOutcome::Completed { values, total: (!truncated).then_some(total), has_more, } } /// `true` when `value` is an ASCII-case-insensitive prefix of `candidate`. /// /// A `value` that does not end on a character boundary of `candidate` cannot be a prefix of it, so a /// non-ASCII token is matched exactly instead of being sliced mid-character. fn prefix_match(candidate: &str, value: &str) -> bool { candidate .get(..value.len()) .is_some_and(|head| head.eq_ignore_ascii_case(value)) } /// The wire-visible text of one enum entry. Only scalars have a faithful string form; an object or /// array enumeration entry is not suggested instead of being rendered as an ad-hoc serialization. fn value_text(value: &Value) -> Option { match value { Value::String(text) => Some(text.clone()), Value::Number(number) => Some(number.to_string()), Value::Bool(flag) => Some(flag.to_string()), Value::Null | Value::Array(_) | Value::Object(_) => None, } } /// One safe, indistinguishable refusal: no Prompt name, URI template, argument name or option /// count is disclosed, and the reason never distinguishes unknown from foreign/unbound. fn not_available(revision: &str, reference: &'static str) -> CompletionOutcome { refused(revision, reference, "not_available") } fn refused(revision: &str, reference: &'static str, outcome: &'static str) -> CompletionOutcome { info!( name: "mcp.completion.complete", outcome, reference, suggestion_count = 0usize, revision, "completion outcome" ); match outcome { "catalog_unavailable" | "schema_unavailable" => CompletionOutcome::CatalogUnavailable, _ => CompletionOutcome::NotAvailable, } } #[cfg(test)] #[path = "completion_tests.rs"] mod tests;