pmcp 2.2.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! OAuth 2.0 middleware for MCP servers.

use crate::error::{Error, ErrorCode, Result};
use crate::server::auth::oauth2::OAuthProvider;
use crate::server::auth::traits::AuthContext;
use crate::types::auth::{AuthInfo, AuthScheme};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;

/// Authentication middleware trait.
#[async_trait]
pub trait AuthMiddleware: Send + Sync {
    /// Authenticate a request.
    async fn authenticate(&self, auth_info: Option<&AuthInfo>) -> Result<AuthContext>;

    /// Check if authentication is required.
    fn is_required(&self) -> bool {
        true
    }
}

/// Bearer token authentication middleware.
pub struct BearerTokenMiddleware {
    /// OAuth provider.
    provider: Arc<dyn OAuthProvider>,

    /// Whether authentication is required.
    required: bool,
}

impl std::fmt::Debug for BearerTokenMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BearerTokenMiddleware")
            .field("provider", &"<dyn OAuthProvider>")
            .field("required", &self.required)
            .finish()
    }
}

impl BearerTokenMiddleware {
    /// Create a new bearer token middleware.
    pub fn new(provider: Arc<dyn OAuthProvider>) -> Self {
        Self {
            provider,
            required: true,
        }
    }

    /// Set whether authentication is required.
    pub fn with_required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }
}

#[async_trait]
impl AuthMiddleware for BearerTokenMiddleware {
    async fn authenticate(&self, auth_info: Option<&AuthInfo>) -> Result<AuthContext> {
        // Check if auth info is provided
        let Some(auth_info) = auth_info else {
            if self.required {
                return Err(Error::protocol(
                    ErrorCode::AUTHENTICATION_REQUIRED,
                    "Authentication required",
                ));
            } else {
                // Return anonymous context
                return Ok(AuthContext {
                    subject: "anonymous".to_string(),
                    scopes: vec![],
                    claims: HashMap::new(),
                    token: None,
                    client_id: Some("anonymous".to_string()),
                    expires_at: None,
                    authenticated: false,
                });
            }
        };

        // Check auth scheme
        if auth_info.scheme != AuthScheme::Bearer {
            return Err(Error::protocol(
                ErrorCode::AUTHENTICATION_REQUIRED,
                "Invalid authentication scheme",
            ));
        }

        // Get token
        let token = auth_info
            .token
            .as_ref()
            .ok_or_else(|| Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Missing token"))?;

        // Validate token
        let token_info =
            self.provider.validate_token(token).await.map_err(|_| {
                Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Invalid token")
            })?;

        // Create auth context
        Ok(AuthContext {
            subject: token_info.user_id,
            scopes: token_info.scopes,
            claims: HashMap::new(),
            token: Some(token.clone()),
            client_id: Some(token_info.client_id),
            expires_at: Some(token_info.expires_at),
            authenticated: true,
        })
    }

    fn is_required(&self) -> bool {
        self.required
    }
}

/// Client credentials authentication middleware.
pub struct ClientCredentialsMiddleware {
    /// OAuth provider.
    provider: Arc<dyn OAuthProvider>,
}

impl std::fmt::Debug for ClientCredentialsMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientCredentialsMiddleware")
            .field("provider", &"<dyn OAuthProvider>")
            .finish()
    }
}

impl ClientCredentialsMiddleware {
    /// Create a new client credentials middleware.
    pub fn new(provider: Arc<dyn OAuthProvider>) -> Self {
        Self { provider }
    }
}

#[async_trait]
impl AuthMiddleware for ClientCredentialsMiddleware {
    async fn authenticate(&self, auth_info: Option<&AuthInfo>) -> Result<AuthContext> {
        let auth_info = auth_info.ok_or_else(|| {
            Error::protocol(
                ErrorCode::AUTHENTICATION_REQUIRED,
                "Authentication required",
            )
        })?;

        // Extract client credentials from params
        let client_id = auth_info
            .params
            .get("client_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Missing client_id")
            })?;

        let client_secret = auth_info
            .params
            .get("client_secret")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Missing client_secret")
            })?;

        // Validate client
        let client =
            self.provider.get_client(client_id).await?.ok_or_else(|| {
                Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Invalid client")
            })?;

        // Verify client secret
        if client.client_secret.as_deref() != Some(client_secret) {
            return Err(Error::protocol(
                ErrorCode::AUTHENTICATION_REQUIRED,
                "Invalid client credentials",
            ));
        }

        // Create auth context (client-only, no user)
        Ok(AuthContext {
            subject: client.client_id.clone(), // Use client ID as subject for client credentials
            scopes: client.scopes,
            claims: HashMap::new(),
            token: None,
            client_id: Some(client.client_id),
            expires_at: None,
            authenticated: true,
        })
    }
}

/// Scope-based authorization middleware.
pub struct ScopeMiddleware {
    /// Inner middleware.
    inner: Box<dyn AuthMiddleware>,

    /// Required scopes.
    required_scopes: Vec<String>,

    /// Require all scopes or any scope.
    require_all: bool,
}

impl std::fmt::Debug for ScopeMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScopeMiddleware")
            .field("inner", &"<dyn AuthMiddleware>")
            .field("required_scopes", &self.required_scopes)
            .finish()
    }
}

impl ScopeMiddleware {
    /// Create a new scope middleware that requires all scopes.
    pub fn all(inner: Box<dyn AuthMiddleware>, scopes: Vec<String>) -> Self {
        Self {
            inner,
            required_scopes: scopes,
            require_all: true,
        }
    }

    /// Create a new scope middleware that requires any scope.
    pub fn any(inner: Box<dyn AuthMiddleware>, scopes: Vec<String>) -> Self {
        Self {
            inner,
            required_scopes: scopes,
            require_all: false,
        }
    }
}

#[async_trait]
impl AuthMiddleware for ScopeMiddleware {
    async fn authenticate(&self, auth_info: Option<&AuthInfo>) -> Result<AuthContext> {
        // First authenticate with inner middleware
        let context = self.inner.authenticate(auth_info).await?;

        // Check scopes
        let scope_refs: Vec<&str> = self.required_scopes.iter().map(|s| s.as_str()).collect();

        let has_required_scopes = if self.require_all {
            context.has_all_scopes(&scope_refs)
        } else {
            context.has_any_scope(&scope_refs)
        };

        if !has_required_scopes {
            return Err(Error::protocol(
                ErrorCode::PERMISSION_DENIED,
                "Insufficient scopes",
            ));
        }

        Ok(context)
    }

    fn is_required(&self) -> bool {
        self.inner.is_required()
    }
}

/// Composite middleware that tries multiple auth methods.
pub struct CompositeMiddleware {
    /// List of middleware to try in order.
    middlewares: Vec<Box<dyn AuthMiddleware>>,

    /// Whether to require at least one to succeed.
    require_any: bool,
}

impl std::fmt::Debug for CompositeMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompositeMiddleware")
            .field(
                "middlewares",
                &format!("{} middlewares", self.middlewares.len()),
            )
            .field("require_any", &self.require_any)
            .finish()
    }
}

impl CompositeMiddleware {
    /// Create a new composite middleware.
    pub fn new(middlewares: Vec<Box<dyn AuthMiddleware>>) -> Self {
        Self {
            middlewares,
            require_any: true,
        }
    }

    /// Set whether to require at least one middleware to succeed.
    pub fn with_require_any(mut self, require_any: bool) -> Self {
        self.require_any = require_any;
        self
    }
}

#[async_trait]
impl AuthMiddleware for CompositeMiddleware {
    async fn authenticate(&self, auth_info: Option<&AuthInfo>) -> Result<AuthContext> {
        let mut last_error = None;

        // Try each middleware in order
        for middleware in &self.middlewares {
            match middleware.authenticate(auth_info).await {
                Ok(context) => return Ok(context),
                Err(e) => last_error = Some(e),
            }
        }

        // If we get here, all middlewares failed
        if self.require_any {
            Err(last_error.unwrap_or_else(|| {
                Error::protocol(ErrorCode::AUTHENTICATION_REQUIRED, "Authentication failed")
            }))
        } else {
            // Return anonymous context if none required
            Ok(AuthContext {
                subject: "anonymous".to_string(),
                scopes: vec![],
                claims: HashMap::new(),
                token: None,
                client_id: Some("anonymous".to_string()),
                expires_at: None,
                authenticated: false,
            })
        }
    }

    fn is_required(&self) -> bool {
        self.require_any && self.middlewares.iter().any(|m| m.is_required())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::auth::oauth2::InMemoryOAuthProvider;

    #[tokio::test]
    async fn test_bearer_token_middleware() {
        let provider = Arc::new(InMemoryOAuthProvider::new("http://localhost:8080"));
        let middleware = BearerTokenMiddleware::new(provider.clone());

        // Test missing auth
        let result = middleware.authenticate(None).await;
        assert!(result.is_err());

        // Test invalid token
        let auth = AuthInfo::bearer("invalid-token");
        let result = middleware.authenticate(Some(&auth)).await;
        assert!(result.is_err());

        // Create valid token
        let token = provider
            .create_access_token(
                "client-123",
                "user-456",
                vec!["read".to_string(), "write".to_string()],
            )
            .await
            .unwrap();

        // Test valid token
        let auth = AuthInfo::bearer(&token.access_token);
        let context = middleware.authenticate(Some(&auth)).await.unwrap();
        assert_eq!(context.client_id, Some("client-123".to_string()));
        assert_eq!(context.subject, "user-456");
        assert!(context.has_scope("read"));
        assert!(context.has_scope("write"));
    }

    #[tokio::test]
    async fn test_scope_middleware() {
        let provider = Arc::new(InMemoryOAuthProvider::new("http://localhost:8080"));
        let bearer = Box::new(BearerTokenMiddleware::new(provider.clone()));
        let scope_middleware =
            ScopeMiddleware::all(bearer, vec!["read".to_string(), "write".to_string()]);

        // Create token with insufficient scopes
        let token = provider
            .create_access_token("client-123", "user-456", vec!["read".to_string()])
            .await
            .unwrap();

        let auth = AuthInfo::bearer(&token.access_token);
        let result = scope_middleware.authenticate(Some(&auth)).await;
        assert!(result.is_err());

        // Create token with sufficient scopes
        let token = provider
            .create_access_token(
                "client-123",
                "user-456",
                vec!["read".to_string(), "write".to_string()],
            )
            .await
            .unwrap();

        let auth = AuthInfo::bearer(&token.access_token);
        let context = scope_middleware.authenticate(Some(&auth)).await.unwrap();
        assert!(context.has_all_scopes(&["read", "write"]));
    }
}