rust-mcp-sdk 0.9.0

An asynchronous SDK and framework for building MCP-Servers and MCP-Clients, leveraging the rust-mcp-schema for type safe MCP Schema Objects.
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! # CORS Middleware
//!
//! A configurable CORS middleware that follows the
//! [WHATWG CORS specification](https://fetch.spec.whatwg.org/#http-cors-protocol).
//!
//! ## Features
//! - Full preflight (`OPTIONS`) handling
//! - Configurable origins: `*`, explicit list, or echo
//! - Credential support (with correct `Access-Control-Allow-Origin` behavior)
//! - Header/method validation
//! - `Access-Control-Expose-Headers` support

use crate::{
    mcp_http::{types::GenericBody, GenericBodyExt, McpAppState, Middleware, MiddlewareNext},
    mcp_server::error::TransportServerResult,
};
use http::{
    header::{
        self, HeaderName, HeaderValue, ACCESS_CONTROL_ALLOW_CREDENTIALS,
        ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
        ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_HEADERS,
        ACCESS_CONTROL_REQUEST_METHOD,
    },
    Method, Request, Response, StatusCode,
};
use rust_mcp_transport::MCP_SESSION_ID_HEADER;
use std::{collections::HashSet, sync::Arc};

/// Configuration for CORS behavior.
///
/// See [MDN CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for details.
#[derive(Clone)]
pub struct CorsConfig {
    /// Which origins are allowed to make requests.
    pub allow_origins: AllowOrigins,

    /// HTTP methods allowed in preflight and actual requests.
    pub allow_methods: Vec<Method>,

    /// Request headers allowed in preflight.
    pub allow_headers: Vec<HeaderName>,

    /// Whether to allow credentials (cookies, HTTP auth, etc).
    ///
    /// **Important**: When `true`, `allow_origins` cannot be `Any` - browsers reject `*`.
    pub allow_credentials: bool,

    /// How long (in seconds) the preflight response can be cached.
    pub max_age: Option<u32>,

    /// Headers that should be exposed to the client JavaScript.
    pub expose_headers: Vec<HeaderName>,
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self {
            allow_origins: AllowOrigins::Any,
            allow_methods: vec![Method::GET, Method::POST, Method::OPTIONS],
            allow_headers: vec![
                header::CONTENT_TYPE,
                header::AUTHORIZATION,
                HeaderName::from_static(MCP_SESSION_ID_HEADER),
            ],
            allow_credentials: false,
            max_age: Some(86_400), // 24 hours
            expose_headers: vec![],
        }
    }
}

/// Policy for allowed origins.
#[derive(Clone, Debug)]
pub enum AllowOrigins {
    /// Allow any origin (`*`).
    ///
    /// **Cannot** be used with `allow_credentials = true`.
    Any,

    /// Allow only specific origins.
    List(HashSet<String>),

    /// Echo the `Origin` header back (required when `allow_credentials = true`).
    Echo,
}

/// CORS middleware implementing the `Middleware` trait.
///
/// Handles both **preflight** (`OPTIONS`) and **actual** requests,
/// adding appropriate CORS headers and rejecting invalid origins/methods/headers.
#[derive(Clone, Default)]
pub struct CorsMiddleware {
    config: Arc<CorsConfig>,
}

impl CorsMiddleware {
    /// Create a new CORS middleware with custom config.
    pub fn new(config: CorsConfig) -> Self {
        Self {
            config: Arc::new(config),
        }
    }

    /// Create a permissive CORS config - useful for public APIs or local dev.
    ///
    /// Allows all common methods, credentials, and common headers.
    pub fn permissive() -> Self {
        Self::new(CorsConfig {
            allow_origins: AllowOrigins::Any,
            allow_methods: vec![
                Method::GET,
                Method::POST,
                Method::PUT,
                Method::DELETE,
                Method::PATCH,
                Method::OPTIONS,
                Method::HEAD,
            ],
            allow_headers: vec![
                header::CONTENT_TYPE,
                header::AUTHORIZATION,
                header::ACCEPT,
                header::ORIGIN,
            ],
            allow_credentials: true,
            max_age: Some(86_400),
            expose_headers: vec![],
        })
    }

    // Internal: resolve allowed origin header value
    fn resolve_allowed_origin(&self, origin: &str) -> Option<String> {
        match &self.config.allow_origins {
            AllowOrigins::Any => {
                // Only return "*" if credentials are not allowed
                if self.config.allow_credentials {
                    // rule MDN , RFC 6454
                    // If Access-Control-Allow-Credentials: true is set,
                    // then Access-Control-Allow-Origin CANNOT be *.
                    // It MUST be the exact origin (e.g., https://example.com).
                    Some(origin.to_string())
                } else {
                    Some("*".to_string())
                }
            }
            AllowOrigins::List(allowed) => {
                if allowed.contains(origin) {
                    Some(origin.to_string())
                } else {
                    None
                }
            }
            AllowOrigins::Echo => Some(origin.to_string()),
        }
    }

    // Build preflight response (204 No Content)
    fn preflight_response(&self, origin: &str) -> Response<GenericBody> {
        let allowed_origin = self.resolve_allowed_origin(origin);
        let mut resp = Response::builder()
            .status(StatusCode::NO_CONTENT)
            .body(GenericBody::empty())
            .expect("preflight response is static");

        let headers = resp.headers_mut();

        if let Some(origin) = allowed_origin {
            headers.insert(
                ACCESS_CONTROL_ALLOW_ORIGIN,
                HeaderValue::from_str(&origin).expect("origin is validated"),
            );
        }

        if self.config.allow_credentials {
            headers.insert(
                ACCESS_CONTROL_ALLOW_CREDENTIALS,
                HeaderValue::from_static("true"),
            );
        }

        if let Some(age) = self.config.max_age {
            headers.insert(
                ACCESS_CONTROL_MAX_AGE,
                HeaderValue::from_str(&age.to_string()).expect("u32 is valid"),
            );
        }

        let methods = self
            .config
            .allow_methods
            .iter()
            .map(|m| m.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        headers.insert(
            ACCESS_CONTROL_ALLOW_METHODS,
            HeaderValue::from_str(&methods).expect("methods are static"),
        );

        let headers_list = self
            .config
            .allow_headers
            .iter()
            .map(|h| h.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        headers.insert(
            ACCESS_CONTROL_ALLOW_HEADERS,
            HeaderValue::from_str(&headers_list).expect("headers are static"),
        );

        resp
    }

    // Add CORS headers to normal response
    fn add_cors_to_response(
        &self,
        mut resp: Response<GenericBody>,
        origin: &str,
    ) -> Response<GenericBody> {
        let allowed_origin = self.resolve_allowed_origin(origin);
        let headers = resp.headers_mut();

        if let Some(origin) = allowed_origin {
            headers.insert(
                ACCESS_CONTROL_ALLOW_ORIGIN,
                HeaderValue::from_str(&origin).expect("origin is validated"),
            );
        }

        if self.config.allow_credentials {
            headers.insert(
                ACCESS_CONTROL_ALLOW_CREDENTIALS,
                HeaderValue::from_static("true"),
            );
        }

        if !self.config.expose_headers.is_empty() {
            let expose = self
                .config
                .expose_headers
                .iter()
                .map(|h| h.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            headers.insert(
                ACCESS_CONTROL_EXPOSE_HEADERS,
                HeaderValue::from_str(&expose).expect("expose headers are static"),
            );
        }

        resp
    }
}

// Middleware trait implementation
#[async_trait::async_trait]
impl Middleware for CorsMiddleware {
    /// Process a request, handling preflight or adding CORS headers.
    ///
    /// - For `OPTIONS` with `Access-Control-Request-Method`: performs preflight.
    /// - For other requests: passes to `next`, then adds CORS headers.
    async fn handle<'req>(
        &self,
        req: Request<&'req str>,
        state: Arc<McpAppState>,
        next: MiddlewareNext<'req>,
    ) -> TransportServerResult<Response<GenericBody>> {
        let origin = req
            .headers()
            .get(header::ORIGIN)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());

        // Preflight: OPTIONS + Access-Control-Request-Method
        if *req.method() == Method::OPTIONS {
            let requested_method = req
                .headers()
                .get(ACCESS_CONTROL_REQUEST_METHOD)
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse::<Method>().ok());

            let requested_headers = req
                .headers()
                .get(ACCESS_CONTROL_REQUEST_HEADERS)
                .and_then(|v| v.to_str().ok())
                .map(|s| {
                    s.split(',')
                        .map(|h| h.trim().to_ascii_lowercase())
                        .collect::<HashSet<_>>()
                })
                .unwrap_or_default();

            let origin = match origin {
                Some(o) => o,
                None => {
                    // Some tools send preflight without Origin - allow if Any
                    if matches!(self.config.allow_origins, AllowOrigins::Any)
                        && !self.config.allow_credentials
                    {
                        return Ok(self.preflight_response("*"));
                    } else {
                        return Ok(GenericBody::build_response(
                            StatusCode::BAD_REQUEST,
                            "CORS origin missing in preflight".to_string(),
                            None,
                        ));
                    }
                }
            };

            // Validate origin
            if self.resolve_allowed_origin(&origin).is_none() {
                return Ok(GenericBody::build_response(
                    StatusCode::FORBIDDEN,
                    "CORS origin not allowed".to_string(),
                    None,
                ));
            }

            // Validate method
            if let Some(m) = requested_method {
                if !self.config.allow_methods.contains(&m) {
                    return Ok(GenericBody::build_response(
                        StatusCode::METHOD_NOT_ALLOWED,
                        "CORS method not allowed".to_string(),
                        None,
                    ));
                }
            }

            // Validate headers
            let allowed = self
                .config
                .allow_headers
                .iter()
                .map(|h| h.as_str().to_ascii_lowercase())
                .collect::<HashSet<_>>();

            if !requested_headers.is_subset(&allowed) {
                return Ok(GenericBody::build_response(
                    StatusCode::BAD_REQUEST,
                    "CORS header not allowed".to_string(),
                    None,
                ));
            }

            // All good - return preflight
            return Ok(self.preflight_response(&origin));
        }

        // Normal request: forward to next handler
        let mut resp = next(req, state).await?;
        if let Some(origin) = origin {
            if self.resolve_allowed_origin(&origin).is_some() {
                resp = self.add_cors_to_response(resp, &origin);
            }
        }

        Ok(resp)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        id_generator::{FastIdGenerator, UuidGenerator},
        mcp_http::{types::GenericBodyExt, MiddlewareNext},
        mcp_icon,
        mcp_server::{ServerHandler, ToMcpServerHandler},
        schema::{Implementation, InitializeResult, ProtocolVersion, ServerCapabilities},
        session_store::InMemorySessionStore,
    };
    use http::{header, Request, Response, StatusCode};
    use std::time::Duration;

    type TestResult = Result<(), Box<dyn std::error::Error>>;
    struct TestHandler;
    impl ServerHandler for TestHandler {}

    fn app_state() -> Arc<McpAppState> {
        let handler = TestHandler {};

        Arc::new(McpAppState {
            session_store: Arc::new(InMemorySessionStore::new()),
            id_generator: Arc::new(UuidGenerator {}),
            stream_id_gen: Arc::new(FastIdGenerator::new(Some("s_"))),
            server_details: Arc::new(InitializeResult {
                capabilities: ServerCapabilities {
                    ..Default::default()
                },
                instructions: None,
                meta: None,
                protocol_version: ProtocolVersion::V2025_06_18.to_string(),
                server_info: Implementation {
                    name: "server".to_string(),
                    title: None,
                    version: "0.1.0".to_string(),
                    description: Some("test server, by Rust MCP SDK".to_string()),
                    icons: vec![mcp_icon!(
                        src = "https://raw.githubusercontent.com/rust-mcp-stack/rust-mcp-sdk/main/assets/rust-mcp-icon.png",
                        mime_type = "image/png",
                        sizes = ["128x128"],
                        theme = "dark"
                    )],
                    website_url: Some("https://github.com/rust-mcp-stack/rust-mcp-sdk".to_string()),
                },
            }),
            handler: handler.to_mcp_server_handler(),
            ping_interval: Duration::from_secs(15),
            transport_options: Arc::new(rust_mcp_transport::TransportOptions::default()),
            enable_json_response: false,
            event_store: None,
            task_store:None,
            client_task_store:None,
            message_observer:None
        })
    }

    fn make_handler<'req>(status: StatusCode, body: &'static str) -> MiddlewareNext<'req> {
        Box::new(move |_, _| {
            let resp = Response::builder()
                .status(status)
                .body(GenericBody::from_string(body.to_string()))
                .unwrap();
            Box::pin(async { Ok(resp) })
        })
    }

    #[tokio::test]
    async fn test_preflight_allowed() -> TestResult {
        let cors = CorsMiddleware::permissive();
        let handler = make_handler(StatusCode::OK, "should not see");

        let req = Request::builder()
            .method(Method::OPTIONS)
            .uri("/")
            .header(header::ORIGIN, "https://example.com")
            .header(ACCESS_CONTROL_REQUEST_METHOD, "POST")
            .header(
                ACCESS_CONTROL_REQUEST_HEADERS,
                "content-type, authorization",
            )
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;

        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert_eq!(
            resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN],
            "https://example.com"
        );
        assert_eq!(
            resp.headers()[ACCESS_CONTROL_ALLOW_METHODS],
            "GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD"
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_preflight_disallowed_origin() -> TestResult {
        let mut allowed = HashSet::new();
        allowed.insert("https://trusted.com".to_string());

        let cors = CorsMiddleware::new(CorsConfig {
            allow_origins: AllowOrigins::List(allowed),
            allow_methods: vec![Method::GET],
            allow_headers: vec![],
            allow_credentials: false,
            max_age: None,
            expose_headers: vec![],
        });

        let handler = make_handler(StatusCode::OK, "irrelevant");

        let req = Request::builder()
            .method(Method::OPTIONS)
            .uri("/")
            .header(header::ORIGIN, "https://evil.com")
            .header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
            .body("")?;

        let result: Response<GenericBody> = cors.handle(req, app_state(), handler).await.unwrap();
        let (parts, _body) = result.into_parts();
        assert_eq!(parts.status, 403);
        Ok(())
    }

    #[tokio::test]
    async fn test_normal_request_with_origin() -> TestResult {
        let cors = CorsMiddleware::permissive();
        let handler = make_handler(StatusCode::OK, "hello");

        let req = Request::builder()
            .method(Method::GET)
            .uri("/")
            .header(header::ORIGIN, "https://client.com")
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;

        assert_eq!(resp.status(), StatusCode::OK);

        assert_eq!(
            resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN],
            "https://client.com"
        );
        assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_CREDENTIALS], "true");
        Ok(())
    }

    #[tokio::test]
    async fn test_wildcard_with_no_credentials() -> TestResult {
        let cors = CorsMiddleware::new(CorsConfig {
            allow_origins: AllowOrigins::Any,
            allow_methods: vec![Method::GET],
            allow_headers: vec![],
            allow_credentials: false,
            max_age: None,
            expose_headers: vec![],
        });

        let handler = make_handler(StatusCode::OK, "ok");

        let req = Request::builder()
            .method(Method::GET)
            .uri("/")
            .header(header::ORIGIN, "https://any.com")
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;
        assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "*");
        Ok(())
    }

    #[tokio::test]
    async fn test_no_wildcard_with_credentials() -> TestResult {
        let cors = CorsMiddleware::new(CorsConfig {
            allow_origins: AllowOrigins::Any,
            allow_methods: vec![Method::GET],
            allow_headers: vec![],
            allow_credentials: true, // This should prevent "*"
            max_age: None,
            expose_headers: vec![],
        });

        let handler = make_handler(StatusCode::OK, "ok");

        let req = Request::builder()
            .method(Method::GET)
            .uri("/")
            .header(header::ORIGIN, "https://any.com")
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;

        // Should NOT have "*" even though config says Any
        let origin_header = resp
            .headers()
            .get(ACCESS_CONTROL_ALLOW_ORIGIN)
            .expect("CORS header missing");
        assert_eq!(origin_header, "https://any.com");

        // And credentials should be allowed
        assert_eq!(
            resp.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .unwrap(),
            "true"
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_echo_origin_with_credentials() -> TestResult {
        let cors = CorsMiddleware::new(CorsConfig {
            allow_origins: AllowOrigins::Echo,
            allow_methods: vec![Method::GET],
            allow_headers: vec![],
            allow_credentials: true,
            max_age: None,
            expose_headers: vec![],
        });

        let handler = make_handler(StatusCode::OK, "ok");

        let req = Request::builder()
            .method(Method::GET)
            .uri("/")
            .header(header::ORIGIN, "https://dynamic.com")
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;
        assert_eq!(
            resp.headers()[ACCESS_CONTROL_ALLOW_ORIGIN],
            "https://dynamic.com"
        );
        assert_eq!(resp.headers()[ACCESS_CONTROL_ALLOW_CREDENTIALS], "true");
        Ok(())
    }

    #[tokio::test]
    async fn test_expose_headers() -> TestResult {
        let cors = CorsMiddleware::new(CorsConfig {
            allow_origins: AllowOrigins::Any,
            allow_methods: vec![Method::GET],
            allow_headers: vec![],
            allow_credentials: false,
            max_age: None,
            expose_headers: vec![HeaderName::from_static("x-ratelimit-remaining")],
        });

        let handler = make_handler(StatusCode::OK, "ok");

        let req = Request::builder()
            .method(Method::GET)
            .uri("/")
            .header(header::ORIGIN, "https://client.com")
            .body("")?;

        let resp = cors.handle(req, app_state(), handler).await?;
        assert_eq!(
            resp.headers()[ACCESS_CONTROL_EXPOSE_HEADERS],
            "x-ratelimit-remaining"
        );
        Ok(())
    }
}