forked from paiml/rust-mcp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path55_server_middleware.rs
More file actions
168 lines (146 loc) Β· 5.94 KB
/
55_server_middleware.rs
File metadata and controls
168 lines (146 loc) Β· 5.94 KB
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
//! Example 55: Server HTTP Middleware Demo
//!
//! Demonstrates server HTTP middleware with:
//! - ServerHttpLoggingMiddleware with redaction
//! - Custom HTTP middleware (CORS)
//! - Query redaction and sensitive header protection
//! - Body gating for safe content types
//! - Complete server setup
use async_trait::async_trait;
use pmcp::error::Result;
use pmcp::server::http_middleware::{
ServerHttpContext, ServerHttpLoggingMiddleware, ServerHttpMiddleware,
ServerHttpMiddlewareChain, ServerHttpResponse,
};
use pmcp::server::streamable_http_server::{StreamableHttpServer, StreamableHttpServerConfig};
use pmcp::types::capabilities::ServerCapabilities;
use pmcp::{RequestHandlerExtra, Server, ToolHandler};
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::sync::Mutex;
/// Simple echo tool for testing
struct EchoTool;
#[async_trait]
impl ToolHandler for EchoTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
Ok(json!({
"echo": args,
"timestamp": std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
}))
}
}
/// Custom CORS middleware for browser clients
#[derive(Debug, Clone)]
struct CorsMiddleware {
allowed_origins: Vec<String>,
}
#[async_trait]
impl ServerHttpMiddleware for CorsMiddleware {
async fn on_response(
&self,
response: &mut ServerHttpResponse,
_context: &ServerHttpContext,
) -> Result<()> {
// Add CORS headers
response.add_header(
"Access-Control-Allow-Origin",
&self.allowed_origins.join(", "),
);
response.add_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.add_header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, MCP-Session-ID",
);
response.add_header("Access-Control-Max-Age", "86400");
tracing::info!("CORS headers added for origins: {:?}", self.allowed_origins);
Ok(())
}
fn priority(&self) -> i32 {
90 // Run after logging (priority 50)
}
}
#[tokio::main]
async fn main() -> Result<()> {
// Initialize logging
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.with_target(false)
.init();
tracing::info!("π Starting Server Middleware Demo");
// Step 1: Create HTTP middleware chain
tracing::info!("π¦ Creating HTTP middleware chain...");
let mut http_chain = ServerHttpMiddlewareChain::new();
// Add logging middleware with secure defaults
let logging = ServerHttpLoggingMiddleware::new()
.with_level(tracing::Level::INFO)
.with_redact_query(true) // Strip query parameters from logs
.with_max_body_bytes(1024); // Log first 1KB of body
http_chain.add(Arc::new(logging));
// Add custom CORS middleware
http_chain.add(Arc::new(CorsMiddleware {
allowed_origins: vec![
"http://localhost:3000".to_string(),
"https://example.com".to_string(),
],
}));
tracing::info!("β
HTTP middleware chain configured:");
tracing::info!(" 1. ServerHttpLoggingMiddleware (priority 50)");
tracing::info!(" - Redacts: authorization, cookie, x-api-key");
tracing::info!(" - Query stripping enabled");
tracing::info!(" - Body logging: first 1KB only");
tracing::info!(" 2. CorsMiddleware (priority 90)");
tracing::info!(" - Allows: localhost:3000, example.com");
// Step 2: Build server with HTTP middleware
tracing::info!("π§ Building server...");
let server = Server::builder()
.name("middleware-demo-server")
.version("1.0.0")
.capabilities(ServerCapabilities::tools_only())
.tool("echo", EchoTool)
.with_http_middleware(Arc::new(http_chain))
.build()?;
// Step 3: Create HTTP server config (middleware retrieved from server)
let config = StreamableHttpServerConfig {
http_middleware: server.http_middleware(),
session_id_generator: Some(Box::new(|| {
format!("demo-session-{}", uuid::Uuid::new_v4())
})),
enable_json_response: true,
..Default::default()
};
let server = Arc::new(Mutex::new(server));
let http_server =
StreamableHttpServer::with_config("127.0.0.1:8080".parse().unwrap(), server, config);
// Step 4: Start server
tracing::info!("π Starting HTTP server...");
let (addr, handle) = http_server.start().await?;
tracing::info!("β
Server listening on: http://{}", addr);
tracing::info!("");
tracing::info!("π Server Features:");
tracing::info!(" β HTTP logging with sensitive data redaction");
tracing::info!(" β CORS headers for browser clients");
tracing::info!(" β Query parameter stripping");
tracing::info!(" β Body gating (safe content types only)");
tracing::info!(" β Session management");
tracing::info!("");
tracing::info!("π¬ Test the server with:");
tracing::info!(" curl -X POST http://{}/messages \\", addr);
tracing::info!(" -H 'Content-Type: application/json' \\");
tracing::info!(" -d '{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{{}},\"clientInfo\":{{\"name\":\"test\",\"version\":\"1.0.0\"}}}}}}'");
tracing::info!("");
tracing::info!("π‘ Features demonstrated:");
tracing::info!(" β HTTP middleware chain");
tracing::info!(" β ServerHttpLoggingMiddleware with redaction");
tracing::info!(" β Custom CORS middleware");
tracing::info!(" β Sensitive header protection");
tracing::info!(" β Query parameter stripping");
tracing::info!(" β Body logging with size limits");
tracing::info!("");
tracing::info!("Press Ctrl+C to stop the server");
// Wait for server to finish
let _ = handle.await;
Ok(())
}