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
//! Represents an MCP resource

#[cfg(feature = "server")]
use crate::app::{
    context::Context,
    handler::{FromHandlerParams, HandlerParams},
};
#[cfg(feature = "server")]
use crate::error::Error;
#[cfg(feature = "server")]
use crate::types::request::FromRequest;
use crate::types::request::RequestParamsMeta;
use crate::types::{Annotations, Cursor, Icon};
#[cfg(feature = "server")]
use crate::types::{IntoResponse, Page, Request, RequestId, Response};
use serde::{Deserialize, Serialize};

pub use read_resource_result::{
    BlobResourceContents, EmptyResourceContents, JsonResourceContents, ReadResourceResult,
    ResourceContents, TextResourceContents,
};
pub use template::{
    ListResourceTemplatesRequestParams, ListResourceTemplatesResult, ResourceTemplate,
};
pub use uri::Uri;

#[cfg(all(feature = "server", feature = "di"))]
pub(crate) use from_request::{Payload, ResourceArgument, Source};

#[cfg(feature = "server")]
pub(crate) use route::Route;

#[cfg(feature = "server")]
mod from_request;
mod read_resource_result;
#[cfg(feature = "server")]
pub(crate) mod route;
pub(crate) mod template;
mod uri;

/// List of commands for Resources
pub mod commands {
    /// Command name that returns a list of resources available on MCP server
    pub const LIST: &str = "resources/list";

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

    /// Command name that returns a list of resource templates available on MCP server.
    pub const TEMPLATES_LIST: &str = "resources/templates/list";

    /// Command name that returns the resource data
    pub const READ: &str = "resources/read";

    /// Command name that subscribes to resource updates.
    pub const SUBSCRIBE: &str = "resources/subscribe";

    /// Command name that unsubscribes from resource updates.
    pub const UNSUBSCRIBE: &str = "resources/unsubscribe";

    /// Notification name that indicates that the resource has been updated.
    pub const UPDATED: &str = "notifications/resources/updated";
}

/// Represents a known resource that the server is capable of reading.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Resource {
    /// The URI of this resource.
    pub uri: Uri,

    /// A human-readable name for this resource.
    pub name: String,

    /// A description of what this resource represents.
    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub descr: Option<String>,

    /// The MIME type of this resource, if known.
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime: Option<String>,

    /// The resource size in bytes, if known
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<usize>,

    /// 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 annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// 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<serde_json::Value>,
}

/// Sent from the client to request a list of resources the server has.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ListResourcesRequestParams {
    /// 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>,
}

/// Sent from the client to the server to read a specific resource URI.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Serialize, Deserialize)]
pub struct ReadResourceRequestParams {
    /// The URI of the resource to read. The URI can use any protocol;
    /// it is up to the server how to interpret it.
    pub uri: Uri,

    /// 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>,

    /// Path arguments extracted from [`Uri`]
    #[serde(skip)]
    #[cfg(feature = "server")]
    pub(crate) args: Option<Box<[String]>>,
}

/// The server's response to a resources/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 ListResourcesResult {
    /// A list of resources that the server offers.
    pub resources: Vec<Resource>,

    /// 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>,
}

/// Sent from the client to request resources/updated notifications
/// from the server whenever a particular resource changes.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Serialize, Deserialize)]
pub struct SubscribeRequestParams {
    /// The URI of the resource to subscribe to.
    /// The URI can use any protocol; it is up to the server how to interpret it.
    pub uri: Uri,
}

/// Sent from the client to request not receiving updated notifications
/// from the server whenever a primitive resource changes.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Serialize, Deserialize)]
pub struct UnsubscribeRequestParams {
    /// The URI of the resource to unsubscribe from.
    /// The URI can use any protocol; it is up to the server how to interpret it.
    pub uri: Uri,
}

impl<T: Into<Uri>> From<T> for SubscribeRequestParams {
    #[inline]
    fn from(uri: T) -> Self {
        Self { uri: uri.into() }
    }
}

impl<T: Into<Uri>> From<T> for UnsubscribeRequestParams {
    #[inline]
    fn from(uri: T) -> Self {
        Self { uri: uri.into() }
    }
}

#[cfg(feature = "server")]
impl IntoResponse for ListResourcesResult {
    #[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<const N: usize> From<[Resource; N]> for ListResourcesResult {
    #[inline]
    fn from(resources: [Resource; N]) -> Self {
        Self {
            next_cursor: None,
            resources: resources.to_vec(),
        }
    }
}

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

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

#[cfg(feature = "server")]
impl FromHandlerParams for ListResourcesRequestParams {
    #[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 ReadResourceRequestParams {
    #[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 SubscribeRequestParams {
    #[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 UnsubscribeRequestParams {
    #[inline]
    fn from_params(params: &HandlerParams) -> Result<Self, Error> {
        let req = Request::from_params(params)?;
        Self::from_request(req)
    }
}

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

impl From<Uri> for Resource {
    #[inline]
    fn from(uri: Uri) -> Self {
        Self {
            name: uri.to_string(),
            title: None,
            descr: None,
            mime: None,
            size: None,
            annotations: None,
            meta: None,
            icons: None,
            uri,
        }
    }
}

impl From<String> for Resource {
    #[inline]
    fn from(uri: String) -> Self {
        Self {
            name: uri.clone(),
            title: None,
            uri: uri.into(),
            descr: None,
            mime: None,
            size: None,
            annotations: None,
            icons: None,
            meta: None,
        }
    }
}

impl From<Uri> for ReadResourceRequestParams {
    #[inline]
    fn from(uri: Uri) -> Self {
        Self {
            meta: None,
            #[cfg(feature = "server")]
            args: None,
            uri,
        }
    }
}

#[cfg(feature = "server")]
impl ReadResourceRequestParams {
    /// 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
    }

    /// Includes path arguments extracted from [`Uri`]
    #[cfg(feature = "server")]
    pub(crate) fn with_args(mut self, args: Box<[String]>) -> Self {
        self.args = Some(args);
        self
    }
}

#[cfg(feature = "server")]
impl Resource {
    /// Creates a new [`Resource`]
    #[inline]
    pub fn new<U: Into<Uri>, S: Into<String>>(uri: U, name: S) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            title: None,
            descr: None,
            mime: None,
            size: None,
            annotations: None,
            icons: None,
            meta: None,
        }
    }

    /// Sets a name for a resource
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Sets a description for a resource
    pub fn with_descr(mut self, description: impl Into<String>) -> Self {
        self.descr = Some(description.into());
        self
    }

    /// Sets a MIME type for a resource
    pub fn with_mime(mut self, mime: impl Into<String>) -> Self {
        self.mime = Some(mime.into());
        self
    }

    /// Sets a resource size
    pub fn with_size(mut self, size: usize) -> Self {
        self.size = Some(size);
        self
    }

    /// Sets annotations for the client
    pub fn with_annotations<F>(mut self, config: F) -> Self
    where
        F: FnOnce(Annotations) -> Annotations,
    {
        self.annotations = Some(config(Default::default()));
        self
    }

    /// Sets a title for a resource
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

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

#[cfg(test)]
mod tests {}