Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Represents an MCP prompt

#[cfg(feature = "server")]
use super::helpers::TypeCategory;
#[cfg(feature = "server")]
use crate::error::{Error, ErrorCode};
use crate::shared;
#[cfg(feature = "server")]
use crate::types::FromRequest;
use crate::types::request::RequestParamsMeta;
use crate::types::{Cursor, Icon};
#[cfg(feature = "server")]
use crate::types::{IntoResponse, Page, PropertyType, Request, RequestId, Response};
#[cfg(feature = "server")]
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
#[cfg(feature = "server")]
use std::future::Future;
#[cfg(feature = "server")]
use std::sync::Arc;

#[cfg(feature = "server")]
use crate::app::{
    context::Context,
    handler::{FromHandlerParams, GenericHandler, Handler, HandlerParams, RequestHandler},
};

pub use get_prompt_result::{GetPromptResult, PromptMessage};

#[cfg(feature = "server")]
mod from_request;
mod get_prompt_result;

/// List of commands for Prompts
pub mod commands {
    /// Command name that returns a list of prompts the server has.
    pub const LIST: &str = "prompts/list";

    /// Notification name that indicates that the list of prompts has changed.
    pub const LIST_CHANGED: &str = "notifications/prompts/list_changed";

    /// Command name that returns a prompt provided by the server.
    pub const GET: &str = "prompts/get";
}

/// A prompt or prompt template that the server offers.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Clone, Serialize, Deserialize)]
pub struct Prompt {
    /// The name of the prompt or prompt template.
    pub name: String,

    /// An optional description of what this prompt provides
    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub descr: Option<String>,

    /// A list of arguments to use for templating the prompt.
    #[serde(rename = "arguments", skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<PromptArgument>>,

    /// Intended for UI and end-user contexts - optimized to be human-readable and easily understood,
    /// even by those unfamiliar with domain-specific terminology.
    ///
    /// If not provided, the name should be used for display (except for Tool,
    /// where `annotations.title` should be given precedence over using `name`, if present).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Optional set of sized icons that the client can display in a user interface.
    ///
    /// Clients that support rendering icons **MUST** support at least the following MIME types:
    /// - `image/png` - PNG images (safe, universal compatibility)
    /// - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
    ///
    /// Clients that support rendering icons **SHOULD** also support:
    /// - `image/svg+xml` - SVG images (scalable but requires security precautions)
    /// - `image/webp` - WebP images (modern, efficient format)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<Icon>>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,

    /// A get prompt handler
    #[serde(skip)]
    #[cfg(feature = "server")]
    handler: Option<RequestHandler<GetPromptResult>>,

    /// A list of roles that are allowed to get the prompt
    #[serde(skip)]
    #[cfg(feature = "http-server")]
    pub(crate) roles: Option<Vec<String>>,

    /// A list of permissions that are allowed to get the prompt
    #[serde(skip)]
    #[cfg(feature = "http-server")]
    pub(crate) permissions: Option<Vec<String>>,
}

/// Describes an argument that a prompt can accept.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptArgument {
    /// The name of the argument.
    pub name: String,

    /// A human-readable description of the argument.
    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub descr: Option<String>,

    /// Whether this argument must be provided.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
}

/// Sent from the client to request a list of prompts and prompt templates the server has.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Serialize, Deserialize)]
pub struct ListPromptsRequestParams {
    /// An opaque token representing the current pagination position.
    /// If provided, the server should return results starting after this cursor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<Cursor>,
}

/// Used by the client to get a prompt provided by the server.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Serialize, Deserialize)]
pub struct GetPromptRequestParams {
    /// The name of the prompt or prompt template.
    pub name: String,

    /// Arguments to use for templating the prompt.
    #[serde(rename = "arguments", skip_serializing_if = "Option::is_none")]
    pub args: Option<HashMap<String, Value>>,

    /// Metadata related to the request that provides additional protocol-level information.
    ///
    /// > **Note:** This can include progress tracking tokens and other protocol-specific properties
    /// > that are not part of the primary request parameters.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<RequestParamsMeta>,
}

/// The server's response to a prompts/list request from the client.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.json) for details
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ListPromptsResult {
    /// A list of prompts or prompt templates that the server offers.
    pub prompts: Vec<Prompt>,

    /// An opaque token representing the pagination position after the last returned result.
    ///
    /// When a paginated result has more data available, the `next_cursor`
    /// field will contain `Some` token that can be used in subsequent requests
    /// to fetch the next page. When there are no more results to return, the `next_cursor` field
    /// will be `None`.
    #[serde(rename = "nextCursor", skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<Cursor>,
}

#[cfg(feature = "server")]
impl IntoResponse for ListPromptsResult {
    #[inline]
    fn into_response(self, req_id: RequestId) -> Response {
        match serde_json::to_value(self) {
            Ok(v) => Response::success(req_id, v),
            Err(err) => Response::error(req_id, err.into()),
        }
    }
}

#[cfg(feature = "server")]
impl From<Vec<Prompt>> for ListPromptsResult {
    #[inline]
    fn from(prompts: Vec<Prompt>) -> Self {
        Self {
            next_cursor: None,
            prompts,
        }
    }
}

#[cfg(feature = "server")]
impl From<Page<'_, Prompt>> for ListPromptsResult {
    #[inline]
    fn from(page: Page<'_, Prompt>) -> Self {
        Self {
            next_cursor: page.next_cursor,
            prompts: page.items.to_vec(),
        }
    }
}

#[cfg(feature = "server")]
impl ListPromptsResult {
    /// Create a new [`ListPromptsResult`]
    #[inline]
    pub fn new() -> Self {
        Default::default()
    }
}

#[cfg(feature = "server")]
impl FromHandlerParams for ListPromptsRequestParams {
    #[inline]
    fn from_params(params: &HandlerParams) -> Result<Self, Error> {
        let req = Request::from_params(params)?;
        Self::from_request(req)
    }
}

#[cfg(feature = "server")]
impl FromHandlerParams for GetPromptRequestParams {
    #[inline]
    fn from_params(params: &HandlerParams) -> Result<Self, Error> {
        let req = Request::from_params(params)?;
        Self::from_request(req)
    }
}

#[cfg(feature = "server")]
impl From<&str> for PromptArgument {
    #[inline]
    fn from(name: &str) -> Self {
        Self {
            name: name.into(),
            descr: None,
            required: Some(true),
        }
    }
}

#[cfg(feature = "server")]
impl From<Box<str>> for PromptArgument {
    #[inline]
    fn from(name: Box<str>) -> Self {
        Self {
            name: name.into(),
            descr: None,
            required: Some(true),
        }
    }
}

#[cfg(feature = "server")]
impl From<Value> for PromptArgument {
    #[inline]
    fn from(json: Value) -> Self {
        serde_json::from_value(json).expect("A correct PromptArgument value must be provided")
    }
}

#[cfg(feature = "server")]
impl From<String> for PromptArgument {
    #[inline]
    fn from(name: String) -> Self {
        Self {
            name,
            descr: None,
            required: Some(true),
        }
    }
}

#[cfg(feature = "server")]
impl<T: Into<String>> From<(T, T)> for PromptArgument {
    #[inline]
    fn from((name, description): (T, T)) -> Self {
        Self::required(name, description)
    }
}

#[cfg(feature = "server")]
impl<T: Into<String>> From<(T, T, bool)> for PromptArgument {
    #[inline]
    fn from((name, description, required): (T, T, bool)) -> Self {
        Self {
            name: name.into(),
            descr: Some(description.into()),
            required: Some(required),
        }
    }
}

/// Describes a generic get prompt handler
#[cfg(feature = "server")]
pub trait PromptHandler<Args>: GenericHandler<Args> {
    /// Returns a prompt arguments schema
    #[inline]
    fn args() -> Option<Vec<PromptArgument>> {
        None
    }
}

#[cfg(feature = "server")]
pub(crate) struct PromptFunc<F, R, Args>
where
    F: PromptHandler<Args, Output = R>,
    R: TryInto<GetPromptResult>,
    R::Error: Into<Error>,
    Args: TryFrom<GetPromptRequestParams, Error = Error>,
{
    func: F,
    _marker: std::marker::PhantomData<Args>,
}

#[cfg(feature = "server")]
impl<F, R, Args> PromptFunc<F, R, Args>
where
    F: PromptHandler<Args, Output = R>,
    R: TryInto<GetPromptResult>,
    R::Error: Into<Error>,
    Args: TryFrom<GetPromptRequestParams, Error = Error>,
{
    /// Creates a new [`PromptFunc`] wrapped into [`Arc`]
    pub(crate) fn new(func: F) -> Arc<Self> {
        let func = Self {
            func,
            _marker: std::marker::PhantomData,
        };
        Arc::new(func)
    }
}

#[cfg(feature = "server")]
impl<F, R, Args> Handler<GetPromptResult> for PromptFunc<F, R, Args>
where
    F: PromptHandler<Args, Output = R>,
    R: TryInto<GetPromptResult>,
    R::Error: Into<Error>,
    Args: TryFrom<GetPromptRequestParams, Error = Error> + Send + Sync,
{
    #[inline]
    fn call(&self, params: HandlerParams) -> BoxFuture<'_, Result<GetPromptResult, Error>> {
        let HandlerParams::Prompt(params) = params else {
            unreachable!()
        };
        Box::pin(async move {
            let args = Args::try_from(params)?;
            self.func.call(args).await.try_into().map_err(Into::into)
        })
    }
}

impl GetPromptRequestParams {
    /// Creates a new [`GetPromptRequestParams`] for the given tool name
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: None,
            meta: None,
        }
    }

    /// Specifies tool arguments
    pub fn with_args<Args: shared::IntoArgs>(mut self, args: Args) -> Self {
        self.args = args.into_args();
        self
    }
}

#[cfg(feature = "server")]
impl GetPromptRequestParams {
    /// Includes [`Context`] into request metadata. If metadata is `None` it creates a new.
    pub(crate) fn with_context(mut self, ctx: Context) -> Self {
        self.meta.get_or_insert_default().context = Some(ctx);
        self
    }
}

impl Debug for Prompt {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Prompt")
            .field("name", &self.name)
            .field("title", &self.title)
            .field("descr", &self.descr)
            .field("meta", &self.meta)
            .field("args", &self.args)
            .finish()
    }
}

#[cfg(feature = "server")]
impl Prompt {
    /// Creates a new [`Prompt`]
    #[inline]
    pub fn new<F, R, Args>(name: impl Into<String>, handler: F) -> Self
    where
        F: PromptHandler<Args, Output = R>,
        R: TryInto<GetPromptResult> + Send + 'static,
        R::Error: Into<Error>,
        Args: TryFrom<GetPromptRequestParams, Error = Error> + Send + Sync + 'static,
    {
        let handler = PromptFunc::new(handler);
        let args = F::args();
        Self {
            name: name.into(),
            title: None,
            descr: None,
            meta: None,
            args,
            handler: Some(handler),
            #[cfg(feature = "http-server")]
            roles: None,
            #[cfg(feature = "http-server")]
            permissions: None,
            icons: None,
        }
    }

    /// Sets a [`Prompt`] title
    pub fn with_title(&mut self, title: impl Into<String>) -> &mut Self {
        self.title = Some(title.into());
        self
    }

    /// Sets a [`Prompt`] description
    pub fn with_description(&mut self, descr: impl Into<String>) -> &mut Self {
        self.descr = Some(descr.into());
        self
    }

    /// Sets arguments for the [`Prompt`]
    pub fn with_args<T, A>(&mut self, args: T) -> &mut Self
    where
        T: IntoIterator<Item = A>,
        A: Into<PromptArgument>,
    {
        self.args = Some(args.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the [`Prompt`] icons
    pub fn with_icons(&mut self, icons: impl IntoIterator<Item = Icon>) -> &mut Self {
        self.icons = Some(icons.into_iter().collect());
        self
    }

    /// Sets a list of roles that are allowed to get the prompt
    #[cfg(feature = "http-server")]
    pub fn with_roles<T, I>(&mut self, roles: T) -> &mut Self
    where
        T: IntoIterator<Item = I>,
        I: Into<String>,
    {
        self.roles = Some(roles.into_iter().map(Into::into).collect());
        self
    }

    /// Sets a list of permissions that are allowed to get the prompt
    #[cfg(feature = "http-server")]
    pub fn with_permissions<T, I>(&mut self, permissions: T) -> &mut Self
    where
        T: IntoIterator<Item = I>,
        I: Into<String>,
    {
        self.permissions = Some(permissions.into_iter().map(Into::into).collect());
        self
    }

    /// Get prompt result
    #[inline]
    pub(crate) async fn call(&self, params: HandlerParams) -> Result<GetPromptResult, Error> {
        match self.handler {
            Some(ref handler) => handler.call(params).await,
            None => Err(Error::new(
                ErrorCode::InternalError,
                "Prompt handler not specified",
            )),
        }
    }
}

/// Prompt arguments helper
#[cfg(feature = "server")]
#[allow(missing_debug_implementations)]
pub struct PromptArguments;

#[cfg(feature = "server")]
impl PromptArguments {
    /// Deserializes a [`Vec`] of [`PromptArgument`] from a JSON string
    #[inline]
    pub fn from_json_str(json: &str) -> Vec<Value> {
        serde_json::from_str(json).expect("PromptArgument: Incorrect JSON string provided")
    }
}

#[cfg(feature = "server")]
impl PromptArgument {
    /// Creates a new [`PromptArgument`]
    pub(crate) fn new<T>() -> Self {
        Self {
            name: std::any::type_name::<T>().into(),
            descr: None,
            required: Some(true),
        }
    }

    /// Creates a new required [`PromptArgument`]
    pub fn required<T: Into<String>>(name: T, descr: T) -> Self {
        Self {
            name: name.into(),
            descr: Some(descr.into()),
            required: Some(true),
        }
    }

    /// Creates a new required [`PromptArgument`]
    pub fn optional<T: Into<String>>(name: T, descr: T) -> Self {
        Self {
            name: name.into(),
            descr: Some(descr.into()),
            required: Some(false),
        }
    }
}

macro_rules! impl_generic_prompt_handler ({ $($param:ident)* } => {
    #[cfg(feature = "server")]
    impl<Func, Fut: Send, $($param: TypeCategory,)*> PromptHandler<($($param,)*)> for Func
    where
        Func: Fn($($param),*) -> Fut + Send + Sync + Clone + 'static,
        Fut: Future + 'static,
    {
        #[inline]
        #[allow(unused_mut)]
        fn args() -> Option<Vec<PromptArgument>> {
            let mut args = Vec::new();
            $(
            {
                if $param::category() != PropertyType::None {
                    args.push(PromptArgument::new::<$param>());
                }
            }
            )*
            if args.len() == 0 {
                None
            } else {
                Some(args)
            }
        }
    }
});

impl_generic_prompt_handler! {}
impl_generic_prompt_handler! { T1 }
impl_generic_prompt_handler! { T1 T2 }
impl_generic_prompt_handler! { T1 T2 T3 }
impl_generic_prompt_handler! { T1 T2 T3 T4 }
impl_generic_prompt_handler! { T1 T2 T3 T4 T5 }