allframe-mcp 0.1.21

MCP (Model Context Protocol) server for AllFrame - Expose APIs as LLM-callable tools
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
//! STDIO transport for MCP Server with debugging support
//!
//! This module provides a production-ready stdio transport with:
//! - Structured logging via tracing
//! - Request/response tracing for debugging
//! - Graceful shutdown handling
//! - Built-in diagnostic tools
//!
//! # Usage
//!
//! ```rust,no_run
//! use allframe_core::router::Router;
//! use allframe_mcp::{McpServer, StdioTransport, StdioConfig};
//!
//! #[tokio::main]
//! async fn main() {
//!     let router = Router::new();
//!     let mcp = McpServer::with_router(router);
//!
//!     let config = StdioConfig::default()
//!         .with_debug_tool(true);
//!
//!     StdioTransport::new(mcp, config)
//!         .serve()
//!         .await;
//! }
//! ```

use std::{
    io::{stdin, stdout, BufRead, Write},
    sync::atomic::{AtomicU64, Ordering},
    time::Instant,
};

use serde_json::{json, Value};

use crate::McpServer;

/// Configuration for the STDIO transport
#[derive(Debug, Clone)]
pub struct StdioConfig {
    /// Server name reported in initialize response
    pub server_name: String,
    /// Server version reported in initialize response
    pub server_version: String,
    /// Protocol version to advertise
    pub protocol_version: String,
    /// Whether to include the allframe/debug tool
    pub include_debug_tool: bool,
    /// Log file path (if set, logs go to file instead of stderr)
    pub log_file: Option<String>,
}

impl Default for StdioConfig {
    fn default() -> Self {
        Self {
            server_name: "allframe-mcp".to_string(),
            server_version: env!("CARGO_PKG_VERSION").to_string(),
            protocol_version: "2024-11-05".to_string(),
            include_debug_tool: false,
            log_file: std::env::var("ALLFRAME_MCP_LOG_FILE").ok(),
        }
    }
}

impl StdioConfig {
    /// Enable the built-in debug tool
    pub fn with_debug_tool(mut self, enabled: bool) -> Self {
        self.include_debug_tool = enabled;
        self
    }

    /// Set the server name
    pub fn with_server_name(mut self, name: impl Into<String>) -> Self {
        self.server_name = name.into();
        self
    }

    /// Set a log file path
    pub fn with_log_file(mut self, path: impl Into<String>) -> Self {
        self.log_file = Some(path.into());
        self
    }
}

/// STDIO transport for MCP server with debugging support
pub struct StdioTransport {
    mcp: McpServer,
    config: StdioConfig,
    start_time: Instant,
    request_count: AtomicU64,
}

impl StdioTransport {
    /// Create a new STDIO transport
    pub fn new(mcp: McpServer, config: StdioConfig) -> Self {
        Self {
            mcp,
            config,
            start_time: Instant::now(),
            request_count: AtomicU64::new(0),
        }
    }

    /// Serve MCP protocol over stdio
    pub async fn serve(self) {
        self.log_startup();

        let stdin = stdin();
        let mut stdout = stdout();

        // Set up shutdown signal handling
        let shutdown = async {
            #[cfg(unix)]
            {
                use tokio::signal::unix::{signal, SignalKind};
                let mut sigterm = signal(SignalKind::terminate()).ok();
                let mut sigint = signal(SignalKind::interrupt()).ok();

                tokio::select! {
                    _ = async { if let Some(ref mut s) = sigterm { s.recv().await } else { std::future::pending().await } } => {
                        self.log_info("Received SIGTERM");
                    }
                    _ = async { if let Some(ref mut s) = sigint { s.recv().await } else { std::future::pending().await } } => {
                        self.log_info("Received SIGINT");
                    }
                }
            }
            #[cfg(not(unix))]
            {
                tokio::signal::ctrl_c().await.ok();
                self.log_info("Received shutdown signal");
            }
        };

        // Run the main loop with shutdown handling
        tokio::select! {
            _ = self.run_loop(&stdin, &mut stdout) => {}
            _ = shutdown => {
                self.log_info("Shutting down gracefully");
            }
        }

        self.log_shutdown();
    }

    async fn run_loop(&self, stdin: &std::io::Stdin, stdout: &mut std::io::Stdout) {
        for line in stdin.lock().lines() {
            let line = match line {
                Ok(l) => l,
                Err(e) => {
                    self.log_error(&format!("Error reading line: {}", e));
                    continue;
                }
            };

            // Skip empty lines
            if line.trim().is_empty() {
                continue;
            }

            self.request_count.fetch_add(1, Ordering::SeqCst);
            let request_id = self.request_count.load(Ordering::SeqCst);

            self.log_request(request_id, &line);

            // Parse request
            let request: Value = match serde_json::from_str(&line) {
                Ok(r) => r,
                Err(e) => {
                    self.log_error(&format!("Parse error: {}", e));
                    let error = json!({
                        "jsonrpc": "2.0",
                        "error": {
                            "code": -32700,
                            "message": "Parse error"
                        },
                        "id": null
                    });
                    self.write_response(stdout, &error, request_id);
                    continue;
                }
            };

            // Handle request
            let response = self.handle_request(request).await;

            // Check if this was a notification (no response needed)
            if let Some(resp) = response {
                self.write_response(stdout, &resp, request_id);
            }
        }
    }

    fn write_response(&self, stdout: &mut std::io::Stdout, response: &Value, request_id: u64) {
        match serde_json::to_string(&response) {
            Ok(json_str) => {
                self.log_response(request_id, &json_str);
                if let Err(e) = writeln!(stdout, "{}", json_str) {
                    self.log_error(&format!("Error writing response: {}", e));
                }
                if let Err(e) = stdout.flush() {
                    self.log_error(&format!("Error flushing stdout: {}", e));
                }
            }
            Err(e) => {
                self.log_error(&format!("Error serializing response: {}", e));
            }
        }
    }

    async fn handle_request(&self, request: Value) -> Option<Value> {
        let method = request["method"].as_str().unwrap_or("");
        let id = request.get("id").cloned();

        // Handle notifications (no id = notification, no response needed)
        match method {
            // Notifications that don't require responses
            "initialized" | "notifications/initialized" => {
                self.log_info("Client initialized connection");
                return None;
            }
            "notifications/cancelled" => {
                self.log_info("Request cancelled by client");
                return None;
            }
            _ => {}
        }

        let result = match method {
            // Initialize
            "initialize" => {
                self.log_info("Initializing MCP connection");
                json!({
                    "protocolVersion": self.config.protocol_version,
                    "capabilities": {
                        "tools": {}
                    },
                    "serverInfo": {
                        "name": self.config.server_name,
                        "version": self.config.server_version
                    }
                })
            }

            // List available tools
            "tools/list" => {
                let mut tools: Vec<Value> = self
                    .mcp
                    .list_tools()
                    .iter()
                    .map(|t| {
                        json!({
                            "name": t.name,
                            "description": t.description,
                            "inputSchema": serde_json::from_str::<Value>(&t.input_schema)
                                .unwrap_or_else(|_| json!({"type": "object"}))
                        })
                    })
                    .collect();

                // Add debug tool if enabled
                if self.config.include_debug_tool {
                    tools.push(json!({
                        "name": "allframe/debug",
                        "description": "Get AllFrame MCP server diagnostics and status information",
                        "inputSchema": {
                            "type": "object",
                            "properties": {},
                            "additionalProperties": false
                        }
                    }));
                }

                json!({ "tools": tools })
            }

            // Call a tool
            "tools/call" => {
                let params = &request["params"];
                let name = params["name"].as_str().unwrap_or("");
                let arguments = params.get("arguments").cloned().unwrap_or(json!({}));

                self.log_info(&format!("Calling tool: {}", name));

                // Handle built-in debug tool
                if name == "allframe/debug" && self.config.include_debug_tool {
                    let diagnostics = self.get_diagnostics();
                    return Some(json!({
                        "jsonrpc": "2.0",
                        "result": {
                            "content": [{
                                "type": "text",
                                "text": serde_json::to_string_pretty(&diagnostics).unwrap()
                            }]
                        },
                        "id": id
                    }));
                }

                match self.mcp.call_tool(name, arguments).await {
                    Ok(result) => {
                        json!({
                            "content": [{
                                "type": "text",
                                "text": result.to_string()
                            }]
                        })
                    }
                    Err(e) => {
                        self.log_error(&format!("Tool error: {}", e));
                        json!({
                            "isError": true,
                            "content": [{
                                "type": "text",
                                "text": format!("Error: {}", e)
                            }]
                        })
                    }
                }
            }

            // Ping
            "ping" => {
                json!({})
            }

            // Unknown method
            _ => {
                self.log_warn(&format!("Unknown method: {}", method));
                return Some(json!({
                    "jsonrpc": "2.0",
                    "error": {
                        "code": -32601,
                        "message": format!("Method not found: {}", method)
                    },
                    "id": id
                }));
            }
        };

        // Return successful response
        Some(json!({
            "jsonrpc": "2.0",
            "result": result,
            "id": id
        }))
    }

    fn get_diagnostics(&self) -> Value {
        json!({
            "server": {
                "name": self.config.server_name,
                "version": self.config.server_version,
                "protocol_version": self.config.protocol_version
            },
            "runtime": {
                "uptime_seconds": self.start_time.elapsed().as_secs(),
                "request_count": self.request_count.load(Ordering::SeqCst),
                "tool_count": self.mcp.tool_count(),
                "pid": std::process::id()
            },
            "build": {
                "pkg_version": env!("CARGO_PKG_VERSION"),
                "debug_tool_enabled": self.config.include_debug_tool
            }
        })
    }

    // Logging methods that work with or without tracing feature

    fn log_startup(&self) {
        let msg = format!(
            "MCP Server starting: name={}, version={}, pid={}, tools={}",
            self.config.server_name,
            self.config.server_version,
            std::process::id(),
            self.mcp.tool_count()
        );

        #[cfg(feature = "tracing")]
        tracing::info!("{}", msg);

        #[cfg(not(feature = "tracing"))]
        eprintln!("[INFO] {}", msg);
    }

    fn log_shutdown(&self) {
        let msg = format!(
            "MCP Server shutting down: uptime={}s, requests={}",
            self.start_time.elapsed().as_secs(),
            self.request_count.load(Ordering::SeqCst)
        );

        #[cfg(feature = "tracing")]
        tracing::info!("{}", msg);

        #[cfg(not(feature = "tracing"))]
        eprintln!("[INFO] {}", msg);
    }

    fn log_request(&self, id: u64, content: &str) {
        // Truncate long requests for logging
        let truncated = if content.len() > 500 {
            format!("{}...(truncated)", &content[..500])
        } else {
            content.to_string()
        };

        #[cfg(feature = "tracing")]
        tracing::debug!(request_id = id, request = %truncated, "Received MCP request");

        #[cfg(not(feature = "tracing"))]
        if std::env::var("ALLFRAME_MCP_DEBUG").is_ok() {
            eprintln!("[DEBUG] req#{}: {}", id, truncated);
        }
    }

    fn log_response(&self, id: u64, content: &str) {
        let truncated = if content.len() > 500 {
            format!("{}...(truncated)", &content[..500])
        } else {
            content.to_string()
        };

        #[cfg(feature = "tracing")]
        tracing::debug!(request_id = id, response = %truncated, "Sending MCP response");

        #[cfg(not(feature = "tracing"))]
        if std::env::var("ALLFRAME_MCP_DEBUG").is_ok() {
            eprintln!("[DEBUG] res#{}: {}", id, truncated);
        }
    }

    fn log_info(&self, msg: &str) {
        #[cfg(feature = "tracing")]
        tracing::info!("{}", msg);

        #[cfg(not(feature = "tracing"))]
        eprintln!("[INFO] {}", msg);
    }

    fn log_warn(&self, msg: &str) {
        #[cfg(feature = "tracing")]
        tracing::warn!("{}", msg);

        #[cfg(not(feature = "tracing"))]
        eprintln!("[WARN] {}", msg);
    }

    fn log_error(&self, msg: &str) {
        #[cfg(feature = "tracing")]
        tracing::error!("{}", msg);

        #[cfg(not(feature = "tracing"))]
        eprintln!("[ERROR] {}", msg);
    }
}

/// Initialize tracing with file output if ALLFRAME_MCP_LOG_FILE is set
#[cfg(feature = "tracing")]
pub fn init_tracing() {
    use tracing_subscriber::EnvFilter;

    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));

    if let Ok(log_file) = std::env::var("ALLFRAME_MCP_LOG_FILE") {
        // Log to file
        let file = std::fs::File::create(&log_file).expect("Failed to create log file");

        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_writer(file)
            .with_ansi(false)
            .init();
    } else {
        // Log to stderr
        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_writer(std::io::stderr)
            .with_ansi(false)
            .init();
    }
}

#[cfg(not(feature = "tracing"))]
pub fn init_tracing() {
    // No-op when tracing feature is disabled
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_config_default() {
        let config = StdioConfig::default();
        assert_eq!(config.server_name, "allframe-mcp");
        assert!(!config.include_debug_tool);
    }

    #[test]
    fn test_config_builder() {
        let config = StdioConfig::default()
            .with_debug_tool(true)
            .with_server_name("my-server")
            .with_log_file("/tmp/mcp.log");

        assert!(config.include_debug_tool);
        assert_eq!(config.server_name, "my-server");
        assert_eq!(config.log_file, Some("/tmp/mcp.log".to_string()));
    }
}