Skip to main content

stateknot_integrations/
mcp_server_prompt.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Immutable, authorization-first MCP 2026-07-28 Prompt and Completion surface.
5
6use std::{
7    borrow::Cow,
8    collections::{BTreeMap, HashMap, HashSet},
9    fmt,
10    sync::Arc,
11};
12
13use rmcp::{
14    ErrorData, RoleServer, ServerHandler,
15    model::{
16        CompleteRequestParams, CompleteResult, CompletionInfo, DiscoverResult,
17        GetPromptRequestParams, GetPromptResponse, GetPromptResult, Implementation,
18        ListPromptsResult, PaginatedRequestParams, Prompt, PromptArgument, PromptMessage,
19        PromptsCapability, ProtocolVersion, Reference, Role, ServerCapabilities, ServerConfig,
20    },
21    service::RequestContext,
22};
23use serde_json::{Map, Value};
24use stateknot_core::{BoxFuture, Digest};
25use thiserror::Error;
26use tokio_util::sync::CancellationToken;
27
28use crate::{
29    McpServerApplicationOptions, McpServerCacheScope, McpServerContent, McpServerInputRequired,
30    McpServerPrincipal, mcp_server_principal,
31    mcp_server_tool::{append_digest_part, validate_inbound_mrtr},
32};
33
34const MEBIBYTE: usize = 1024 * 1024;
35const MAX_NAME_BYTES: usize = 64;
36const MAX_DISPLAY_BYTES: usize = 16 * 1024;
37const MAX_ARGUMENTS: usize = 128;
38const MAX_ARGUMENT_VALUE_BYTES: usize = 64 * 1024;
39const MAX_SCOPE_COUNT: usize = 128;
40const MAX_SCOPE_BYTES: usize = 256;
41const MAX_MESSAGES: usize = 256;
42const MAX_RESULT_BYTES: usize = 32 * MEBIBYTE;
43const MAX_COMPLETION_VALUES: usize = 100;
44const MAX_COMPLETION_VALUE_BYTES: usize = 4096;
45
46/// One bounded Prompt argument definition.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct McpServerPromptArgument {
49    name: Arc<str>,
50    title: Option<Arc<str>>,
51    description: Option<Arc<str>>,
52    required: bool,
53}
54
55impl McpServerPromptArgument {
56    /// Creates a portable argument name.
57    pub fn new(name: impl Into<String>) -> Result<Self, McpServerPromptDefinitionError> {
58        let name = name.into();
59        validate_name(&name)?;
60        Ok(Self {
61            name: Arc::from(name),
62            title: None,
63            description: None,
64            required: false,
65        })
66    }
67
68    /// Adds a human-readable title.
69    pub fn with_title(
70        mut self,
71        value: impl Into<String>,
72    ) -> Result<Self, McpServerPromptDefinitionError> {
73        self.title = Some(Arc::from(validate_display(value.into())?));
74        Ok(self)
75    }
76
77    /// Adds a human-readable description.
78    pub fn with_description(
79        mut self,
80        value: impl Into<String>,
81    ) -> Result<Self, McpServerPromptDefinitionError> {
82        self.description = Some(Arc::from(validate_display(value.into())?));
83        Ok(self)
84    }
85
86    /// Marks the argument as required or optional.
87    #[must_use]
88    pub const fn with_required(mut self, value: bool) -> Self {
89        self.required = value;
90        self
91    }
92
93    /// Returns the programmatic name.
94    #[must_use]
95    pub fn name(&self) -> &str {
96        &self.name
97    }
98
99    /// Returns whether the argument is required.
100    #[must_use]
101    pub const fn required(&self) -> bool {
102        self.required
103    }
104
105    fn to_protocol(&self) -> PromptArgument {
106        let mut argument = PromptArgument::new(self.name.to_string()).with_required(self.required);
107        argument.title = self.title.as_deref().map(str::to_owned);
108        argument.description = self.description.as_deref().map(str::to_owned);
109        argument
110    }
111}
112
113/// One immutable Prompt definition.
114#[derive(Clone, Debug)]
115pub struct McpServerPromptDefinition {
116    name: Arc<str>,
117    title: Option<Arc<str>>,
118    description: Option<Arc<str>>,
119    arguments: Arc<[McpServerPromptArgument]>,
120    required_scopes: Arc<[Box<str>]>,
121}
122
123impl McpServerPromptDefinition {
124    /// Creates a portable Prompt name with no arguments.
125    pub fn new(name: impl Into<String>) -> Result<Self, McpServerPromptDefinitionError> {
126        let name = name.into();
127        validate_name(&name)?;
128        Ok(Self {
129            name: Arc::from(name),
130            title: None,
131            description: None,
132            arguments: Arc::from([]),
133            required_scopes: Arc::from([]),
134        })
135    }
136
137    /// Adds a display title.
138    pub fn with_title(
139        mut self,
140        value: impl Into<String>,
141    ) -> Result<Self, McpServerPromptDefinitionError> {
142        self.title = Some(Arc::from(validate_display(value.into())?));
143        Ok(self)
144    }
145
146    /// Adds a display description.
147    pub fn with_description(
148        mut self,
149        value: impl Into<String>,
150    ) -> Result<Self, McpServerPromptDefinitionError> {
151        self.description = Some(Arc::from(validate_display(value.into())?));
152        Ok(self)
153    }
154
155    /// Adds unique bounded argument definitions.
156    pub fn with_arguments(
157        mut self,
158        arguments: impl IntoIterator<Item = McpServerPromptArgument>,
159    ) -> Result<Self, McpServerPromptDefinitionError> {
160        let arguments = arguments.into_iter().collect::<Vec<_>>();
161        if arguments.len() > MAX_ARGUMENTS {
162            return Err(McpServerPromptDefinitionError::TooManyArguments);
163        }
164        let mut names = HashSet::with_capacity(arguments.len());
165        if arguments
166            .iter()
167            .any(|argument| !names.insert(argument.name().to_owned()))
168        {
169            return Err(McpServerPromptDefinitionError::DuplicateArgument);
170        }
171        self.arguments = arguments.into();
172        Ok(self)
173    }
174
175    /// Requires every listed OAuth-style scope for discovery and rendering.
176    pub fn with_required_scopes(
177        mut self,
178        scopes: impl IntoIterator<Item = impl Into<String>>,
179    ) -> Result<Self, McpServerPromptDefinitionError> {
180        self.required_scopes = validate_scopes(scopes)?;
181        Ok(self)
182    }
183
184    /// Returns the exact Prompt name.
185    #[must_use]
186    pub fn name(&self) -> &str {
187        &self.name
188    }
189
190    /// Returns arguments in registered order.
191    pub fn arguments(&self) -> impl ExactSizeIterator<Item = &McpServerPromptArgument> {
192        self.arguments.iter()
193    }
194
195    /// Returns required scopes in canonical order.
196    pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
197        self.required_scopes.iter().map(AsRef::as_ref)
198    }
199
200    fn to_protocol(&self) -> Prompt {
201        let arguments = (!self.arguments.is_empty()).then(|| {
202            self.arguments
203                .iter()
204                .map(McpServerPromptArgument::to_protocol)
205                .collect()
206        });
207        let mut prompt = Prompt::new(
208            self.name.to_string(),
209            self.description.as_deref().map(str::to_owned),
210            arguments,
211        );
212        prompt.title = self.title.as_deref().map(str::to_owned);
213        prompt
214    }
215}
216
217/// Invalid Prompt definition.
218#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
219#[non_exhaustive]
220pub enum McpServerPromptDefinitionError {
221    /// Name was outside the portable MCP grammar.
222    #[error("invalid MCP prompt or argument name")]
223    InvalidName,
224    /// Display text was empty, padded, oversized, or control-containing.
225    #[error("invalid MCP prompt display text")]
226    InvalidDisplayText,
227    /// Too many arguments were supplied.
228    #[error("too many MCP prompt arguments")]
229    TooManyArguments,
230    /// An argument name appeared twice.
231    #[error("duplicate MCP prompt argument")]
232    DuplicateArgument,
233    /// Too many required scopes were supplied.
234    #[error("too many required MCP prompt scopes")]
235    TooManyScopes,
236    /// A required scope was invalid.
237    #[error("invalid required MCP prompt scope")]
238    InvalidScope,
239    /// A required scope appeared twice.
240    #[error("duplicate required MCP prompt scope")]
241    DuplicateScope,
242}
243
244fn validate_name(value: &str) -> Result<(), McpServerPromptDefinitionError> {
245    if value.is_empty()
246        || value.len() > MAX_NAME_BYTES
247        || !value
248            .bytes()
249            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'/' | b'-'))
250    {
251        return Err(McpServerPromptDefinitionError::InvalidName);
252    }
253    Ok(())
254}
255
256fn validate_display(value: String) -> Result<String, McpServerPromptDefinitionError> {
257    if value.is_empty()
258        || value.len() > MAX_DISPLAY_BYTES
259        || value.trim() != value
260        || value.chars().any(char::is_control)
261    {
262        return Err(McpServerPromptDefinitionError::InvalidDisplayText);
263    }
264    Ok(value)
265}
266
267fn validate_scopes(
268    scopes: impl IntoIterator<Item = impl Into<String>>,
269) -> Result<Arc<[Box<str>]>, McpServerPromptDefinitionError> {
270    let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
271    if scopes.len() > MAX_SCOPE_COUNT {
272        return Err(McpServerPromptDefinitionError::TooManyScopes);
273    }
274    if scopes.iter().any(|scope| {
275        scope.is_empty()
276            || scope.len() > MAX_SCOPE_BYTES
277            || scope
278                .bytes()
279                .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
280    }) {
281        return Err(McpServerPromptDefinitionError::InvalidScope);
282    }
283    scopes.sort_unstable();
284    if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
285        return Err(McpServerPromptDefinitionError::DuplicateScope);
286    }
287    Ok(scopes
288        .into_iter()
289        .map(String::into_boxed_str)
290        .collect::<Vec<_>>()
291        .into())
292}
293
294/// Prompt count ceiling.
295#[derive(Clone, Copy, Debug, Eq, PartialEq)]
296pub struct McpServerPromptCatalogLimits {
297    maximum_prompts: usize,
298}
299
300impl McpServerPromptCatalogLimits {
301    /// Absolute Prompt count ceiling.
302    pub const HARD_MAXIMUM_PROMPTS: usize = 4096;
303
304    /// Constructs a positive bounded count.
305    pub const fn new(maximum_prompts: usize) -> Result<Self, McpServerPromptCatalogLimitsError> {
306        if maximum_prompts == 0 {
307            return Err(McpServerPromptCatalogLimitsError::ZeroLimit);
308        }
309        if maximum_prompts > Self::HARD_MAXIMUM_PROMPTS {
310            return Err(McpServerPromptCatalogLimitsError::AboveHardMaximum);
311        }
312        Ok(Self { maximum_prompts })
313    }
314}
315
316impl Default for McpServerPromptCatalogLimits {
317    fn default() -> Self {
318        Self {
319            maximum_prompts: 1024,
320        }
321    }
322}
323
324/// Invalid Prompt catalog limits.
325#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
326#[non_exhaustive]
327pub enum McpServerPromptCatalogLimitsError {
328    /// Prompt count must be positive.
329    #[error("MCP prompt catalog limit must be positive")]
330    ZeroLimit,
331    /// Prompt count exceeded the hard ceiling.
332    #[error("MCP prompt catalog limit exceeds the hard maximum")]
333    AboveHardMaximum,
334}
335
336/// Startup-only Prompt catalog builder.
337#[derive(Debug)]
338pub struct McpServerPromptCatalogBuilder {
339    limits: McpServerPromptCatalogLimits,
340    prompts: BTreeMap<String, McpServerPromptDefinition>,
341}
342
343impl McpServerPromptCatalogBuilder {
344    /// Creates an empty builder.
345    #[must_use]
346    pub fn new(limits: McpServerPromptCatalogLimits) -> Self {
347        Self {
348            limits,
349            prompts: BTreeMap::new(),
350        }
351    }
352
353    /// Registers one unique Prompt.
354    pub fn register(
355        &mut self,
356        definition: McpServerPromptDefinition,
357    ) -> Result<(), McpServerPromptCatalogError> {
358        if self.prompts.len() == self.limits.maximum_prompts {
359            return Err(McpServerPromptCatalogError::TooManyPrompts);
360        }
361        if self.prompts.contains_key(definition.name()) {
362            return Err(McpServerPromptCatalogError::DuplicatePrompt);
363        }
364        self.prompts
365            .insert(definition.name().to_owned(), definition);
366        Ok(())
367    }
368
369    /// Freezes a non-empty stable-order catalog.
370    pub fn build(self) -> Result<McpServerPromptCatalog, McpServerPromptCatalogError> {
371        if self.prompts.is_empty() {
372            return Err(McpServerPromptCatalogError::Empty);
373        }
374        let mut material = Vec::new();
375        for prompt in self.prompts.values() {
376            append_digest_part(&mut material, prompt.name().as_bytes());
377            for argument in prompt.arguments() {
378                append_digest_part(&mut material, argument.name().as_bytes());
379                material.push(u8::from(argument.required()));
380            }
381        }
382        let digest = digest_hex(material);
383        Ok(McpServerPromptCatalog {
384            inner: Arc::new(McpServerPromptCatalogInner {
385                prompts: self.prompts,
386                digest: Arc::from(digest),
387            }),
388        })
389    }
390}
391
392impl Default for McpServerPromptCatalogBuilder {
393    fn default() -> Self {
394        Self::new(McpServerPromptCatalogLimits::default())
395    }
396}
397
398/// Immutable Prompt catalog.
399#[derive(Clone)]
400pub struct McpServerPromptCatalog {
401    inner: Arc<McpServerPromptCatalogInner>,
402}
403
404struct McpServerPromptCatalogInner {
405    prompts: BTreeMap<String, McpServerPromptDefinition>,
406    digest: Arc<str>,
407}
408
409impl McpServerPromptCatalog {
410    /// Returns an exact definition.
411    #[must_use]
412    pub fn get(&self, name: &str) -> Option<&McpServerPromptDefinition> {
413        self.inner.prompts.get(name)
414    }
415
416    /// Returns the Prompt count.
417    #[must_use]
418    pub fn len(&self) -> usize {
419        self.inner.prompts.len()
420    }
421
422    /// Returns whether the catalog is empty.
423    #[must_use]
424    pub fn is_empty(&self) -> bool {
425        self.inner.prompts.is_empty()
426    }
427
428    fn contains_scoped_prompts(&self) -> bool {
429        self.inner
430            .prompts
431            .values()
432            .any(|value| !value.required_scopes.is_empty())
433    }
434}
435
436impl fmt::Debug for McpServerPromptCatalog {
437    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
438        formatter
439            .debug_struct("McpServerPromptCatalog")
440            .field("prompts", &self.len())
441            .field("catalog_digest", &self.inner.digest)
442            .finish()
443    }
444}
445
446/// Invalid Prompt catalog mutation or build.
447#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
448#[non_exhaustive]
449pub enum McpServerPromptCatalogError {
450    /// At least one Prompt is required.
451    #[error("MCP prompt catalog is empty")]
452    Empty,
453    /// A name appeared twice.
454    #[error("duplicate MCP prompt")]
455    DuplicatePrompt,
456    /// Prompt count reached its configured ceiling.
457    #[error("too many MCP prompts")]
458    TooManyPrompts,
459}
460
461/// Role for one returned Prompt message.
462#[derive(Clone, Copy, Debug, Eq, PartialEq)]
463#[non_exhaustive]
464pub enum McpServerPromptRole {
465    /// User message.
466    User,
467    /// Assistant message.
468    Assistant,
469}
470
471/// One bounded Prompt message.
472#[derive(Clone, Debug)]
473pub struct McpServerPromptMessage {
474    role: McpServerPromptRole,
475    content: McpServerContent,
476}
477
478impl McpServerPromptMessage {
479    /// Creates a message from validated `StateKnot` content.
480    #[must_use]
481    pub const fn new(role: McpServerPromptRole, content: McpServerContent) -> Self {
482        Self { role, content }
483    }
484
485    fn to_protocol(&self) -> PromptMessage {
486        let role = match self.role {
487            McpServerPromptRole::User => Role::User,
488            McpServerPromptRole::Assistant => Role::Assistant,
489        };
490        PromptMessage::new(role, self.content.protocol_clone())
491    }
492}
493
494/// Bounded complete Prompt result.
495#[derive(Clone, Debug)]
496pub struct McpServerPromptResult {
497    description: Option<Arc<str>>,
498    messages: Arc<[McpServerPromptMessage]>,
499}
500
501impl McpServerPromptResult {
502    /// Creates a non-empty bounded message sequence.
503    pub fn new(
504        messages: impl IntoIterator<Item = McpServerPromptMessage>,
505    ) -> Result<Self, McpServerPromptResultError> {
506        let messages = messages.into_iter().collect::<Vec<_>>();
507        if messages.is_empty() {
508            return Err(McpServerPromptResultError::Empty);
509        }
510        if messages.len() > MAX_MESSAGES {
511            return Err(McpServerPromptResultError::TooManyMessages);
512        }
513        if messages
514            .iter()
515            .try_fold(0_usize, |total, message| {
516                total.checked_add(message.content.wire_bytes())
517            })
518            .is_none_or(|total| total > MAX_RESULT_BYTES)
519        {
520            return Err(McpServerPromptResultError::TooLarge);
521        }
522        Ok(Self {
523            description: None,
524            messages: messages.into(),
525        })
526    }
527
528    /// Adds a bounded result description.
529    pub fn with_description(
530        mut self,
531        value: impl Into<String>,
532    ) -> Result<Self, McpServerPromptResultError> {
533        self.description =
534            Some(Arc::from(validate_display(value.into()).map_err(|_| {
535                McpServerPromptResultError::InvalidDescription
536            })?));
537        Ok(self)
538    }
539
540    fn into_protocol(self) -> GetPromptResult {
541        let mut result = GetPromptResult::new(
542            self.messages
543                .iter()
544                .map(McpServerPromptMessage::to_protocol)
545                .collect(),
546        );
547        result.description = self.description.as_deref().map(str::to_owned);
548        result
549    }
550}
551
552/// Invalid Prompt result.
553#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
554#[non_exhaustive]
555pub enum McpServerPromptResultError {
556    /// A complete Prompt requires at least one message.
557    #[error("MCP prompt result is empty")]
558    Empty,
559    /// Too many messages were returned.
560    #[error("too many MCP prompt messages")]
561    TooManyMessages,
562    /// Aggregate content exceeded a hard ceiling.
563    #[error("MCP prompt result is too large")]
564    TooLarge,
565    /// Result description was invalid.
566    #[error("invalid MCP prompt result description")]
567    InvalidDescription,
568}
569
570/// Complete or input-required Prompt outcome.
571#[derive(Clone, Debug)]
572#[non_exhaustive]
573pub enum McpServerPromptOutcome {
574    /// Rendering completed.
575    Complete(McpServerPromptResult),
576    /// Client-side MRTR input is required.
577    InputRequired(McpServerInputRequired),
578}
579
580impl From<McpServerPromptResult> for McpServerPromptOutcome {
581    fn from(value: McpServerPromptResult) -> Self {
582        Self::Complete(value)
583    }
584}
585
586impl From<McpServerInputRequired> for McpServerPromptOutcome {
587    fn from(value: McpServerInputRequired) -> Self {
588        Self::InputRequired(value)
589    }
590}
591
592/// StateKnot-owned inbound Prompt render request.
593#[derive(Clone, Debug)]
594pub struct McpServerPromptRender {
595    name: Arc<str>,
596    arguments: Arc<Map<String, Value>>,
597    input_responses: Arc<BTreeMap<String, Value>>,
598    request_state: Option<Arc<str>>,
599}
600
601impl McpServerPromptRender {
602    /// Returns the Prompt name.
603    #[must_use]
604    pub fn name(&self) -> &str {
605        &self.name
606    }
607
608    /// Returns syntactically decoded, initially untrusted arguments.
609    #[must_use]
610    pub fn arguments(&self) -> &Map<String, Value> {
611        &self.arguments
612    }
613
614    /// Returns untrusted MRTR responses.
615    #[must_use]
616    pub fn input_responses(&self) -> &BTreeMap<String, Value> {
617        &self.input_responses
618    }
619
620    /// Returns untrusted echoed request state.
621    #[must_use]
622    pub fn request_state(&self) -> Option<&str> {
623        self.request_state.as_deref()
624    }
625}
626
627/// Authenticated Prompt execution context.
628#[derive(Clone, Debug)]
629pub struct McpServerPromptContext {
630    principal: McpServerPrincipal,
631    client_capabilities: Arc<Value>,
632    cancellation: CancellationToken,
633    request_state_binding: Arc<[u8]>,
634}
635
636impl McpServerPromptContext {
637    /// Returns the authenticated principal.
638    #[must_use]
639    pub const fn principal(&self) -> &McpServerPrincipal {
640        &self.principal
641    }
642
643    /// Returns request-scoped client capabilities.
644    #[must_use]
645    pub fn client_capabilities(&self) -> &Value {
646        &self.client_capabilities
647    }
648
649    /// Returns principal/Prompt/arguments-bound request-state associated data.
650    #[must_use]
651    pub fn request_state_binding(&self) -> &[u8] {
652        &self.request_state_binding
653    }
654
655    /// Returns whether cancellation was observed.
656    #[must_use]
657    pub fn is_cancelled(&self) -> bool {
658        self.cancellation.is_cancelled()
659    }
660
661    /// Waits for cooperative cancellation.
662    pub async fn cancelled(&self) {
663        self.cancellation.cancelled().await;
664    }
665}
666
667/// Renders one Prompt after authorization and argument validation.
668pub trait McpServerPromptRenderer: Send + Sync + 'static {
669    /// Renders a bounded request.
670    fn render(
671        &self,
672        request: McpServerPromptRender,
673        context: McpServerPromptContext,
674    ) -> BoxFuture<'_, Result<McpServerPromptOutcome, McpServerPromptRendererError>>;
675}
676
677/// Renderer failure category without arbitrary diagnostic leakage.
678#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
679#[non_exhaustive]
680pub enum McpServerPromptRendererError {
681    /// The Prompt is not available.
682    #[error("MCP prompt was not found")]
683    NotFound,
684    /// A dependency is unavailable.
685    #[error("MCP prompt dependency is unavailable")]
686    Unavailable,
687    /// A renderer invariant failed.
688    #[error("MCP prompt rendering failed internally")]
689    Internal,
690    /// Cooperative cancellation was observed.
691    #[error("MCP prompt rendering was cancelled")]
692    Cancelled,
693}
694
695/// Owned facts for decoded Prompt authorization.
696#[derive(Clone, Debug)]
697pub struct McpServerPromptAuthorizationRequest {
698    principal: McpServerPrincipal,
699    request: McpServerPromptRender,
700    definition: Option<McpServerPromptDefinition>,
701}
702
703impl McpServerPromptAuthorizationRequest {
704    /// Returns the authenticated principal.
705    #[must_use]
706    pub const fn principal(&self) -> &McpServerPrincipal {
707        &self.principal
708    }
709
710    /// Returns the untrusted decoded request.
711    #[must_use]
712    pub const fn request(&self) -> &McpServerPromptRender {
713        &self.request
714    }
715
716    /// Returns the exact registered definition, if one exists.
717    #[must_use]
718    pub const fn definition(&self) -> Option<&McpServerPromptDefinition> {
719        self.definition.as_ref()
720    }
721}
722
723/// Decoded Prompt authorization policy.
724pub trait McpServerPromptAuthorization: Send + Sync + 'static {
725    /// Authorizes before existence or argument diagnostics are disclosed.
726    fn authorize(
727        &self,
728        request: McpServerPromptAuthorizationRequest,
729    ) -> BoxFuture<'_, Result<(), McpServerPromptAuthorizationError>>;
730}
731
732/// Explicit policy that admits every scope-qualified render.
733#[derive(Clone, Copy, Debug, Default)]
734pub struct AllowMcpServerPromptAuthorization;
735
736impl McpServerPromptAuthorization for AllowMcpServerPromptAuthorization {
737    fn authorize(
738        &self,
739        _request: McpServerPromptAuthorizationRequest,
740    ) -> BoxFuture<'_, Result<(), McpServerPromptAuthorizationError>> {
741        Box::pin(async { Ok(()) })
742    }
743}
744
745/// Public-safe Prompt authorization failure.
746#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
747#[non_exhaustive]
748pub enum McpServerPromptAuthorizationError {
749    /// Policy denied rendering.
750    #[error("MCP prompt rendering is forbidden")]
751    Forbidden,
752    /// Policy authority is unavailable.
753    #[error("MCP prompt authorization is unavailable")]
754    Unavailable,
755}
756
757/// Completion target without an SDK type in the public API.
758#[derive(Clone, Debug, Eq, PartialEq)]
759#[non_exhaustive]
760pub enum McpServerCompletionReference {
761    /// Prompt name.
762    Prompt(Box<str>),
763    /// Resource template URI.
764    ResourceTemplate(Box<str>),
765}
766
767/// Authenticated, bounded Completion request.
768#[derive(Clone, Debug)]
769pub struct McpServerCompletionRequest {
770    principal: McpServerPrincipal,
771    reference: McpServerCompletionReference,
772    argument_name: Box<str>,
773    argument_value: Box<str>,
774    context_arguments: Arc<BTreeMap<String, String>>,
775}
776
777impl McpServerCompletionRequest {
778    /// Returns the authenticated principal.
779    #[must_use]
780    pub const fn principal(&self) -> &McpServerPrincipal {
781        &self.principal
782    }
783
784    /// Returns the target Prompt or Resource template.
785    #[must_use]
786    pub const fn reference(&self) -> &McpServerCompletionReference {
787        &self.reference
788    }
789
790    /// Returns the argument being completed.
791    #[must_use]
792    pub fn argument_name(&self) -> &str {
793        &self.argument_name
794    }
795
796    /// Returns the current prefix/value.
797    #[must_use]
798    pub fn argument_value(&self) -> &str {
799        &self.argument_value
800    }
801
802    /// Returns previously resolved string arguments.
803    #[must_use]
804    pub fn context_arguments(&self) -> &BTreeMap<String, String> {
805        &self.context_arguments
806    }
807}
808
809/// Bounded Completion result.
810#[derive(Clone, Debug, Eq, PartialEq)]
811pub struct McpServerCompletionResult {
812    values: Arc<[Box<str>]>,
813    total: Option<u32>,
814    has_more: bool,
815}
816
817impl McpServerCompletionResult {
818    /// Creates at most 100 unique values with consistent pagination metadata.
819    pub fn new(
820        values: impl IntoIterator<Item = impl Into<String>>,
821        total: Option<u32>,
822        has_more: bool,
823    ) -> Result<Self, McpServerCompletionResultError> {
824        let values = values.into_iter().map(Into::into).collect::<Vec<_>>();
825        if values.len() > MAX_COMPLETION_VALUES {
826            return Err(McpServerCompletionResultError::TooManyValues);
827        }
828        if values.iter().any(|value| {
829            value.len() > MAX_COMPLETION_VALUE_BYTES || value.chars().any(char::is_control)
830        }) {
831            return Err(McpServerCompletionResultError::InvalidValue);
832        }
833        let mut unique = HashSet::with_capacity(values.len());
834        if values.iter().any(|value| !unique.insert(value.as_str())) {
835            return Err(McpServerCompletionResultError::DuplicateValue);
836        }
837        let value_count =
838            u32::try_from(values.len()).expect("MCP completion result contains at most 100 values");
839        if total.is_some_and(|total| total < value_count)
840            || (has_more && total == Some(value_count))
841        {
842            return Err(McpServerCompletionResultError::InvalidPagination);
843        }
844        Ok(Self {
845            values: values
846                .into_iter()
847                .map(String::into_boxed_str)
848                .collect::<Vec<_>>()
849                .into(),
850            total,
851            has_more,
852        })
853    }
854
855    fn into_protocol(self) -> CompleteResult {
856        let values = self.values.iter().map(ToString::to_string).collect();
857        let completion = CompletionInfo::with_pagination(values, self.total, self.has_more)
858            .expect("StateKnot completion limits are within the MCP hard maximum");
859        CompleteResult::new(completion)
860    }
861}
862
863/// Invalid Completion output.
864#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
865#[non_exhaustive]
866pub enum McpServerCompletionResultError {
867    /// More than 100 values were supplied.
868    #[error("too many MCP completion values")]
869    TooManyValues,
870    /// One value was oversized or control-containing.
871    #[error("invalid MCP completion value")]
872    InvalidValue,
873    /// One value appeared more than once.
874    #[error("duplicate MCP completion value")]
875    DuplicateValue,
876    /// Total and has-more metadata were inconsistent.
877    #[error("invalid MCP completion pagination")]
878    InvalidPagination,
879}
880
881/// Produces Completion suggestions and owns their authorization.
882pub trait McpServerCompletionProvider: Send + Sync + 'static {
883    /// Completes one bounded request.
884    fn complete(
885        &self,
886        request: McpServerCompletionRequest,
887    ) -> BoxFuture<'_, Result<McpServerCompletionResult, McpServerCompletionError>>;
888}
889
890/// Completion failure category.
891#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
892#[non_exhaustive]
893pub enum McpServerCompletionError {
894    /// Target or argument is not available in this authorization context.
895    #[error("MCP completion target is unavailable")]
896    NotFoundOrForbidden,
897    /// Provider dependency is unavailable.
898    #[error("MCP completion provider is unavailable")]
899    Unavailable,
900    /// Provider invariant failed.
901    #[error("MCP completion failed internally")]
902    Internal,
903}
904
905/// Prompt-only production handler. Use the composite application to combine
906/// it with Tools and Resources.
907#[derive(Clone)]
908pub struct McpServerPromptService {
909    catalog: McpServerPromptCatalog,
910    options: McpServerApplicationOptions,
911    renderer: Arc<dyn McpServerPromptRenderer>,
912    authorization: Arc<dyn McpServerPromptAuthorization>,
913    completion: Option<Arc<dyn McpServerCompletionProvider>>,
914}
915
916impl McpServerPromptService {
917    /// Creates a service with explicit renderer and authorization policy.
918    pub fn new<R, A>(
919        catalog: McpServerPromptCatalog,
920        options: McpServerApplicationOptions,
921        renderer: R,
922        authorization: A,
923    ) -> Result<Self, McpServerPromptServiceBuildError>
924    where
925        R: McpServerPromptRenderer,
926        A: McpServerPromptAuthorization,
927    {
928        Self::with_shared(
929            catalog,
930            options,
931            Arc::new(renderer),
932            Arc::new(authorization),
933        )
934    }
935
936    /// Creates a service with already shared boundaries.
937    pub fn with_shared(
938        catalog: McpServerPromptCatalog,
939        options: McpServerApplicationOptions,
940        renderer: Arc<dyn McpServerPromptRenderer>,
941        authorization: Arc<dyn McpServerPromptAuthorization>,
942    ) -> Result<Self, McpServerPromptServiceBuildError> {
943        if catalog.contains_scoped_prompts()
944            && matches!(options.cache_scope, McpServerCacheScope::Public)
945        {
946            return Err(McpServerPromptServiceBuildError::PublicCacheWithScopedPrompts);
947        }
948        Ok(Self {
949            catalog,
950            options,
951            renderer,
952            authorization,
953            completion: None,
954        })
955    }
956
957    /// Adds a Completion provider.
958    #[must_use]
959    pub fn with_completion_provider<C>(mut self, completion: C) -> Self
960    where
961        C: McpServerCompletionProvider,
962    {
963        self.completion = Some(Arc::new(completion));
964        self
965    }
966
967    /// Adds an already shared Completion provider.
968    #[must_use]
969    pub fn with_shared_completion_provider(
970        mut self,
971        completion: Arc<dyn McpServerCompletionProvider>,
972    ) -> Self {
973        self.completion = Some(completion);
974        self
975    }
976
977    fn scope_tag(&self, principal: &McpServerPrincipal) -> String {
978        if matches!(self.options.cache_scope, McpServerCacheScope::Public) {
979            return "public".to_owned();
980        }
981        let mut material = principal.subject().as_bytes().to_vec();
982        for scope in principal.scopes() {
983            append_digest_part(&mut material, scope.as_bytes());
984        }
985        digest_hex(material)
986    }
987
988    fn page(
989        &self,
990        principal: &McpServerPrincipal,
991        cursor: Option<&str>,
992    ) -> Result<(Vec<Prompt>, Option<String>), ErrorData> {
993        let scope = self.scope_tag(principal);
994        let visible = self
995            .catalog
996            .inner
997            .prompts
998            .values()
999            .filter(|definition| {
1000                definition
1001                    .required_scopes()
1002                    .all(|required| principal.has_scope(required))
1003            })
1004            .collect::<Vec<_>>();
1005        let start = cursor.map_or(Ok(0), |value| self.parse_cursor(value, &scope))?;
1006        if start > visible.len() {
1007            return Err(invalid_cursor());
1008        }
1009        let end = start
1010            .saturating_add(self.options.page_size)
1011            .min(visible.len());
1012        let values = visible[start..end]
1013            .iter()
1014            .map(|value| value.to_protocol())
1015            .collect();
1016        let next = (end < visible.len())
1017            .then(|| format!("v1.{}.{}.{}", self.catalog.inner.digest, scope, end));
1018        Ok((values, next))
1019    }
1020
1021    fn parse_cursor(&self, cursor: &str, scope: &str) -> Result<usize, ErrorData> {
1022        if cursor.len() > 192 {
1023            return Err(invalid_cursor());
1024        }
1025        let mut parts = cursor.split('.');
1026        let valid = parts.next() == Some("v1")
1027            && parts.next() == Some(self.catalog.inner.digest.as_ref())
1028            && parts.next() == Some(scope);
1029        let offset = parts.next().and_then(|value| value.parse().ok());
1030        if !valid || offset.is_none() || parts.next().is_some() {
1031            return Err(invalid_cursor());
1032        }
1033        Ok(offset.expect("validated cursor offset exists"))
1034    }
1035
1036    async fn dispatch_prompt(
1037        &self,
1038        request: GetPromptRequestParams,
1039        context: RequestContext<RoleServer>,
1040    ) -> Result<GetPromptResponse, ErrorData> {
1041        validate_name(&request.name).map_err(|_| unavailable_prompt())?;
1042        let principal = mcp_server_principal(&context)
1043            .cloned()
1044            .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1045        let definition = self.catalog.get(&request.name).cloned();
1046        if definition.as_ref().is_some_and(|definition| {
1047            definition
1048                .required_scopes()
1049                .any(|scope| !principal.has_scope(scope))
1050        }) {
1051            return Err(unavailable_prompt());
1052        }
1053        let input_responses = request.input_responses.unwrap_or_default();
1054        validate_inbound_mrtr(&input_responses, request.request_state.as_deref())?;
1055        let render = McpServerPromptRender {
1056            name: Arc::from(request.name),
1057            arguments: Arc::new(request.arguments.unwrap_or_default()),
1058            input_responses: Arc::new(input_responses),
1059            request_state: request.request_state.map(Arc::from),
1060        };
1061        let authorization = McpServerPromptAuthorizationRequest {
1062            principal: principal.clone(),
1063            request: render.clone(),
1064            definition: definition.clone(),
1065        };
1066        match self.authorization.authorize(authorization).await {
1067            Ok(()) => {}
1068            Err(McpServerPromptAuthorizationError::Forbidden) => {
1069                return Err(unavailable_prompt());
1070            }
1071            Err(McpServerPromptAuthorizationError::Unavailable) => {
1072                return Err(ErrorData::internal_error(
1073                    "MCP prompt authorization is unavailable",
1074                    None,
1075                ));
1076            }
1077        }
1078        let Some(definition) = definition else {
1079            return Err(unavailable_prompt());
1080        };
1081        validate_arguments(&definition, render.arguments())?;
1082        let execution_context = prompt_context(&context, principal, &render)?;
1083        match self.renderer.render(render, execution_context).await {
1084            Ok(McpServerPromptOutcome::Complete(result)) => Ok(result.into_protocol().into()),
1085            Ok(McpServerPromptOutcome::InputRequired(result)) => Ok(result.into_protocol().into()),
1086            Err(McpServerPromptRendererError::NotFound) => Err(unavailable_prompt()),
1087            Err(McpServerPromptRendererError::Unavailable) => Err(ErrorData::internal_error(
1088                "MCP prompt dependency is unavailable",
1089                None,
1090            )),
1091            Err(McpServerPromptRendererError::Internal) => Err(ErrorData::internal_error(
1092                "MCP prompt rendering failed",
1093                None,
1094            )),
1095            Err(McpServerPromptRendererError::Cancelled) => Err(ErrorData::internal_error(
1096                "MCP prompt rendering was cancelled",
1097                None,
1098            )),
1099        }
1100    }
1101
1102    async fn dispatch_completion(
1103        &self,
1104        request: CompleteRequestParams,
1105        context: RequestContext<RoleServer>,
1106    ) -> Result<CompleteResult, ErrorData> {
1107        let Some(provider) = &self.completion else {
1108            return Err(ErrorData::invalid_params(
1109                "Completion is not available",
1110                None,
1111            ));
1112        };
1113        let principal = mcp_server_principal(&context)
1114            .cloned()
1115            .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1116        let reference = match request.r#ref {
1117            Reference::Prompt(value) => {
1118                validate_name(&value.name).map_err(|_| unavailable_completion())?;
1119                if let Some(definition) = self.catalog.get(&value.name)
1120                    && definition
1121                        .required_scopes()
1122                        .any(|scope| !principal.has_scope(scope))
1123                {
1124                    return Err(unavailable_completion());
1125                }
1126                McpServerCompletionReference::Prompt(value.name.into_boxed_str())
1127            }
1128            Reference::Resource(value) => {
1129                if value.uri.is_empty()
1130                    || value.uri.len() > 4096
1131                    || value.uri.chars().any(char::is_control)
1132                {
1133                    return Err(unavailable_completion());
1134                }
1135                McpServerCompletionReference::ResourceTemplate(value.uri.into_boxed_str())
1136            }
1137            _ => return Err(unavailable_completion()),
1138        };
1139        validate_completion_string(&request.argument.name)?;
1140        validate_completion_string(&request.argument.value)?;
1141        let context_arguments = request
1142            .context
1143            .and_then(|value| value.arguments)
1144            .unwrap_or_default();
1145        if context_arguments.len() > MAX_ARGUMENTS
1146            || context_arguments.iter().any(|(name, value)| {
1147                validate_completion_string(name).is_err()
1148                    || validate_completion_string(value).is_err()
1149            })
1150        {
1151            return Err(ErrorData::invalid_params(
1152                "Invalid completion context",
1153                None,
1154            ));
1155        }
1156        let completion_request = McpServerCompletionRequest {
1157            principal,
1158            reference,
1159            argument_name: request.argument.name.into_boxed_str(),
1160            argument_value: request.argument.value.into_boxed_str(),
1161            context_arguments: Arc::new(context_arguments.into_iter().collect()),
1162        };
1163        match provider.complete(completion_request).await {
1164            Ok(result) => Ok(result.into_protocol()),
1165            Err(McpServerCompletionError::NotFoundOrForbidden) => Err(unavailable_completion()),
1166            Err(McpServerCompletionError::Unavailable) => Err(ErrorData::internal_error(
1167                "MCP completion provider is unavailable",
1168                None,
1169            )),
1170            Err(McpServerCompletionError::Internal) => {
1171                Err(ErrorData::internal_error("MCP completion failed", None))
1172            }
1173        }
1174    }
1175}
1176
1177impl fmt::Debug for McpServerPromptService {
1178    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1179        formatter
1180            .debug_struct("McpServerPromptService")
1181            .field("catalog", &self.catalog)
1182            .field("options", &self.options)
1183            .field("renderer", &"[RENDERER]")
1184            .field("authorization", &"[POLICY]")
1185            .field("completion", &self.completion.is_some())
1186            .finish_non_exhaustive()
1187    }
1188}
1189
1190impl ServerHandler for McpServerPromptService {
1191    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
1192        Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
1193    }
1194
1195    fn get_info(&self) -> ServerConfig {
1196        let mut capabilities = ServerCapabilities::default();
1197        capabilities.prompts = Some(PromptsCapability::default());
1198        if self.completion.is_some() {
1199            capabilities.completions = Some(Map::new());
1200        }
1201        let mut info = ServerConfig::new(capabilities).with_server_info(Implementation::new(
1202            self.options.server_name.to_string(),
1203            self.options.server_version.to_string(),
1204        ));
1205        if let Some(instructions) = &self.options.instructions {
1206            info = info.with_instructions(instructions.to_string());
1207        }
1208        info
1209    }
1210
1211    async fn discover(
1212        &self,
1213        _context: RequestContext<RoleServer>,
1214    ) -> Result<DiscoverResult, ErrorData> {
1215        Ok(
1216            DiscoverResult::from_server_info(vec![ProtocolVersion::V_2026_07_28], self.get_info())
1217                .with_ttl_ms(self.options.cache_ttl_ms)
1218                .with_cache_scope(self.options.cache_scope.into()),
1219        )
1220    }
1221
1222    async fn list_prompts(
1223        &self,
1224        request: Option<PaginatedRequestParams>,
1225        context: RequestContext<RoleServer>,
1226    ) -> Result<ListPromptsResult, ErrorData> {
1227        let principal = mcp_server_principal(&context)
1228            .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1229        let (prompts, next_cursor) = self.page(
1230            principal,
1231            request.as_ref().and_then(|value| value.cursor.as_deref()),
1232        )?;
1233        let mut result = ListPromptsResult::with_all_items(prompts)
1234            .with_ttl_ms(self.options.cache_ttl_ms)
1235            .with_cache_scope(self.options.cache_scope.into());
1236        result.next_cursor = next_cursor;
1237        Ok(result)
1238    }
1239
1240    async fn get_prompt(
1241        &self,
1242        request: GetPromptRequestParams,
1243        context: RequestContext<RoleServer>,
1244    ) -> Result<GetPromptResponse, ErrorData> {
1245        self.dispatch_prompt(request, context).await
1246    }
1247
1248    async fn complete(
1249        &self,
1250        request: CompleteRequestParams,
1251        context: RequestContext<RoleServer>,
1252    ) -> Result<CompleteResult, ErrorData> {
1253        self.dispatch_completion(request, context).await
1254    }
1255}
1256
1257/// Invalid Prompt service configuration.
1258#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1259#[non_exhaustive]
1260pub enum McpServerPromptServiceBuildError {
1261    /// Scope-filtered Prompts require principal-private caching.
1262    #[error("scope-restricted MCP prompts require a private catalog cache")]
1263    PublicCacheWithScopedPrompts,
1264}
1265
1266fn validate_arguments(
1267    definition: &McpServerPromptDefinition,
1268    arguments: &Map<String, Value>,
1269) -> Result<(), ErrorData> {
1270    if arguments.len() > MAX_ARGUMENTS {
1271        return Err(invalid_arguments());
1272    }
1273    let definitions = definition
1274        .arguments()
1275        .map(|value| (value.name(), value))
1276        .collect::<HashMap<_, _>>();
1277    if arguments.iter().any(|(name, value)| {
1278        !definitions.contains_key(name.as_str())
1279            || value.as_str().is_none_or(|value| {
1280                value.len() > MAX_ARGUMENT_VALUE_BYTES || value.chars().any(char::is_control)
1281            })
1282    }) || definitions
1283        .values()
1284        .any(|definition| definition.required() && !arguments.contains_key(definition.name()))
1285    {
1286        return Err(invalid_arguments());
1287    }
1288    Ok(())
1289}
1290
1291fn prompt_context(
1292    context: &RequestContext<RoleServer>,
1293    principal: McpServerPrincipal,
1294    request: &McpServerPromptRender,
1295) -> Result<McpServerPromptContext, ErrorData> {
1296    let capabilities = serde_json::to_value(context.client_capabilities().unwrap_or_default())
1297        .map_err(|_| ErrorData::internal_error("Failed to retain client capabilities", None))?;
1298    let arguments = serde_json_canonicalizer::to_vec(&Value::Object((*request.arguments).clone()))
1299        .map_err(|_| ErrorData::internal_error("Failed to bind MCP request state", None))?;
1300    let mut binding = b"stateknot/mcp-server/request-state/prompt/v1".to_vec();
1301    append_digest_part(&mut binding, principal.subject().as_bytes());
1302    append_digest_part(&mut binding, request.name().as_bytes());
1303    append_digest_part(&mut binding, &arguments);
1304    Ok(McpServerPromptContext {
1305        principal,
1306        client_capabilities: Arc::new(capabilities),
1307        cancellation: context.ct.clone(),
1308        request_state_binding: Digest::sha256(binding).as_bytes().to_vec().into(),
1309    })
1310}
1311
1312fn validate_completion_string(value: &str) -> Result<(), ErrorData> {
1313    if value.len() > MAX_ARGUMENT_VALUE_BYTES || value.chars().any(char::is_control) {
1314        return Err(ErrorData::invalid_params(
1315            "Invalid completion argument",
1316            None,
1317        ));
1318    }
1319    Ok(())
1320}
1321
1322fn digest_hex(value: impl AsRef<[u8]>) -> String {
1323    let digest = Digest::sha256(value).to_string();
1324    digest
1325        .strip_prefix("sha256:")
1326        .expect("StateKnot SHA-256 digest has stable prefix")
1327        .to_owned()
1328}
1329
1330fn invalid_cursor() -> ErrorData {
1331    ErrorData::invalid_params("Invalid prompt catalog cursor", None)
1332}
1333
1334fn unavailable_prompt() -> ErrorData {
1335    ErrorData::invalid_params("Unknown or unavailable prompt", None)
1336}
1337
1338fn invalid_arguments() -> ErrorData {
1339    ErrorData::invalid_params("Prompt arguments are invalid", None)
1340}
1341
1342fn unavailable_completion() -> ErrorData {
1343    ErrorData::invalid_params("Unknown or unavailable completion target", None)
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348    use std::sync::atomic::{AtomicUsize, Ordering};
1349
1350    use bytes::Bytes;
1351    use http::{Request, StatusCode};
1352    use http_body_util::{BodyExt as _, Full};
1353    use serde_json::json;
1354    use tower_service::Service as _;
1355
1356    use super::*;
1357    use crate::{McpServerAuthentication, McpServerHttpOptions, McpServerHttpService};
1358
1359    #[derive(Clone)]
1360    struct GreetingRenderer {
1361        calls: Arc<AtomicUsize>,
1362    }
1363
1364    impl McpServerPromptRenderer for GreetingRenderer {
1365        fn render(
1366            &self,
1367            request: McpServerPromptRender,
1368            _context: McpServerPromptContext,
1369        ) -> BoxFuture<'_, Result<McpServerPromptOutcome, McpServerPromptRendererError>> {
1370            self.calls.fetch_add(1, Ordering::SeqCst);
1371            let name = request
1372                .arguments()
1373                .get("name")
1374                .and_then(Value::as_str)
1375                .unwrap_or_default()
1376                .to_owned();
1377            Box::pin(async move {
1378                let content = McpServerContent::text(format!("Hello {name}"))
1379                    .map_err(|_| McpServerPromptRendererError::Internal)?;
1380                McpServerPromptResult::new([McpServerPromptMessage::new(
1381                    McpServerPromptRole::User,
1382                    content,
1383                )])
1384                .map(Into::into)
1385                .map_err(|_| McpServerPromptRendererError::Internal)
1386            })
1387        }
1388    }
1389
1390    #[derive(Clone, Copy)]
1391    struct NameCompletion;
1392
1393    impl McpServerCompletionProvider for NameCompletion {
1394        fn complete(
1395            &self,
1396            request: McpServerCompletionRequest,
1397        ) -> BoxFuture<'_, Result<McpServerCompletionResult, McpServerCompletionError>> {
1398            let prefix = request.argument_value().to_owned();
1399            Box::pin(async move {
1400                McpServerCompletionResult::new([format!("{prefix}da")], Some(1), false)
1401                    .map_err(|_| McpServerCompletionError::Internal)
1402            })
1403        }
1404    }
1405
1406    fn service(calls: &Arc<AtomicUsize>) -> McpServerHttpService<McpServerPromptService> {
1407        let argument = McpServerPromptArgument::new("name")
1408            .unwrap()
1409            .with_required(true);
1410        let prompt = McpServerPromptDefinition::new("greeting")
1411            .unwrap()
1412            .with_arguments([argument])
1413            .unwrap();
1414        let mut builder = McpServerPromptCatalogBuilder::default();
1415        builder.register(prompt).unwrap();
1416        let options = McpServerApplicationOptions::new(
1417            "stateknot-prompt-test",
1418            "0.0.0",
1419            10,
1420            std::time::Duration::from_secs(60),
1421            McpServerCacheScope::Private,
1422        )
1423        .unwrap();
1424        let handler = McpServerPromptService::new(
1425            builder.build().unwrap(),
1426            options,
1427            GreetingRenderer {
1428                calls: calls.clone(),
1429            },
1430            AllowMcpServerPromptAuthorization,
1431        )
1432        .unwrap()
1433        .with_completion_provider(NameCompletion);
1434        McpServerHttpService::new(
1435            handler,
1436            McpServerHttpOptions::loopback(32126).unwrap(),
1437            McpServerAuthentication::anonymous_loopback(),
1438        )
1439        .unwrap()
1440    }
1441
1442    fn request(method: &str, mut params: Value) -> Request<Full<Bytes>> {
1443        let name = params
1444            .get("name")
1445            .and_then(Value::as_str)
1446            .map(str::to_owned);
1447        params.as_object_mut().unwrap().insert(
1448            "_meta".to_owned(),
1449            json!({
1450                "io.modelcontextprotocol/protocolVersion": "2026-07-28",
1451                "io.modelcontextprotocol/clientInfo": { "name": "test", "version": "0" },
1452                "io.modelcontextprotocol/clientCapabilities": {}
1453            }),
1454        );
1455        let body = serde_json::to_vec(&json!({
1456            "jsonrpc": "2.0", "id": 1, "method": method, "params": params
1457        }))
1458        .unwrap();
1459        let mut builder = Request::builder()
1460            .method("POST")
1461            .uri("http://127.0.0.1:32126/mcp")
1462            .header("host", "127.0.0.1:32126")
1463            .header("origin", "http://127.0.0.1:32126")
1464            .header("content-type", "application/json")
1465            .header("accept", "application/json, text/event-stream")
1466            .header("mcp-protocol-version", "2026-07-28")
1467            .header("mcp-method", method);
1468        if let Some(name) = name {
1469            builder = builder.header("mcp-name", name);
1470        }
1471        builder.body(Full::new(Bytes::from(body))).unwrap()
1472    }
1473
1474    async fn invoke(
1475        service: &mut McpServerHttpService<McpServerPromptService>,
1476        method: &str,
1477        params: Value,
1478    ) -> (StatusCode, Value) {
1479        let response = service.call(request(method, params)).await.unwrap();
1480        let status = response.status();
1481        let bytes = response.into_body().collect().await.unwrap().to_bytes();
1482        (status, serde_json::from_slice(&bytes).unwrap())
1483    }
1484
1485    #[test]
1486    fn prompt_catalog_rejects_duplicate_arguments() {
1487        let argument = McpServerPromptArgument::new("same").unwrap();
1488        assert!(matches!(
1489            McpServerPromptDefinition::new("prompt")
1490                .unwrap()
1491                .with_arguments([argument.clone(), argument]),
1492            Err(McpServerPromptDefinitionError::DuplicateArgument)
1493        ));
1494    }
1495
1496    #[tokio::test]
1497    async fn prompt_arguments_are_validated_before_rendering() {
1498        let calls = Arc::new(AtomicUsize::new(0));
1499        let mut service = service(&calls);
1500        let (status, invalid) = invoke(
1501            &mut service,
1502            "prompts/get",
1503            json!({ "name": "greeting", "arguments": {} }),
1504        )
1505        .await;
1506        assert_eq!(status, StatusCode::BAD_REQUEST);
1507        assert_eq!(invalid.pointer("/error/code"), Some(&json!(-32602)));
1508        assert_eq!(calls.load(Ordering::SeqCst), 0);
1509
1510        let (status, result) = invoke(
1511            &mut service,
1512            "prompts/get",
1513            json!({ "name": "greeting", "arguments": { "name": "Ada" } }),
1514        )
1515        .await;
1516        assert_eq!(status, StatusCode::OK);
1517        assert_eq!(
1518            result.pointer("/result/messages/0/content/text"),
1519            Some(&json!("Hello Ada"))
1520        );
1521        assert_eq!(calls.load(Ordering::SeqCst), 1);
1522
1523        let (status, completion) = invoke(
1524            &mut service,
1525            "completion/complete",
1526            json!({
1527                "ref": { "type": "ref/prompt", "name": "greeting" },
1528                "argument": { "name": "name", "value": "A" }
1529            }),
1530        )
1531        .await;
1532        assert_eq!(status, StatusCode::OK);
1533        assert_eq!(
1534            completion.pointer("/result/completion/values/0"),
1535            Some(&json!("Ada"))
1536        );
1537    }
1538}