mcpspy 0.2.2

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! Live ratatui dashboard (`mcpspy top`).
//!
//! Pure formatting helpers live here alongside the interactive event loop so
//! the data-to-text transformation can be tested without a terminal.

#[cfg(any(feature = "tui", test))]
use crate::cli_util::{format_duration_ms, format_token_count};
use anyhow::Result;
#[cfg(feature = "tui")]
use mcpspy::core::db::TelemetryDb;
#[cfg(any(feature = "tui", test))]
use mcpspy::core::models::{RecentCall, ServerSummary, ToolSummary};
#[cfg(feature = "tui")]
use std::io::stdout;
#[cfg(feature = "tui")]
use std::path::Path;
#[cfg(feature = "tui")]
use std::time::Duration;

/// Format the per-server section as display lines (with token-burn bars).
#[cfg(any(feature = "tui", test))]
pub fn server_lines(servers: &[ServerSummary]) -> Vec<String> {
    let totals: Vec<i64> = servers
        .iter()
        .map(|s| s.total_req_tokens + s.total_resp_tokens)
        .collect();
    let max = totals.iter().copied().max().unwrap_or(1).max(1);

    servers
        .iter()
        .zip(totals)
        .map(|(s, total)| {
            let bar_len = (total * 24 / max) as usize;
            let bar = "█".repeat(bar_len.max(1));
            format!(
                "{:<18} {:>4} calls  req {}  resp {}  {:<24} p50 {}  p95 {}  err {}",
                s.server_name,
                s.total_calls,
                format_token_count(s.total_req_tokens),
                format_token_count(s.total_resp_tokens),
                bar,
                format_duration_ms(s.p50_duration_ms),
                format_duration_ms(s.p95_duration_ms),
                s.error_count,
            )
        })
        .collect()
}

/// Format the per-tool section as display lines.
#[cfg(any(feature = "tui", test))]
pub fn tool_lines(tools: &[ToolSummary]) -> Vec<String> {
    tools
        .iter()
        .map(|t| {
            let total = t.total_req_tokens + t.total_resp_tokens;
            format!(
                "{:<16} {:<20} {:>4} calls  {} tok  avg {}  p50 {}",
                t.server_name,
                t.tool_name,
                t.total_calls,
                format_token_count(total),
                format_duration_ms(t.avg_duration_ms),
                format_duration_ms(t.p50_duration_ms),
            )
        })
        .collect()
}

/// Format the recent-calls section as display lines.
#[cfg(any(feature = "tui", test))]
pub fn recent_lines(calls: &[RecentCall]) -> Vec<String> {
    calls
        .iter()
        .map(|c| {
            let ts = c.started_at.format("%H:%M:%S").to_string();
            format!(
                "{} {:<14} {:<18} {:<10} req {} resp {}",
                ts,
                c.server_name,
                c.tool_name.as_deref().unwrap_or(&c.method),
                format_duration_ms(c.duration_ms),
                format_token_count(c.req_tokens),
                format_token_count(c.resp_tokens),
            )
        })
        .collect()
}

/// Run the interactive dashboard until `q` is pressed (`c` clears the view).
#[cfg(feature = "tui")]
pub fn run_tui(db_path: &str) -> Result<()> {
    use crossterm::event::{self, Event, KeyCode, KeyEventKind};
    use crossterm::execute;
    use crossterm::terminal::{
        EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
    };
    use ratatui::Terminal;
    use ratatui::backend::CrosstermBackend;
    use ratatui::layout::{Constraint, Layout};
    use ratatui::style::{Color, Modifier, Style};
    use ratatui::text::Line;
    use ratatui::widgets::{Block, Borders, Paragraph};

    let db = TelemetryDb::open(Path::new(db_path))?;
    let rt = tokio::runtime::Runtime::new()?;

    enable_raw_mode()?;
    execute!(stdout(), EnterAlternateScreen)?;
    let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;

    let result = (|| -> Result<()> {
        let mut cleared = false;
        loop {
            if event::poll(Duration::from_millis(100))? {
                match event::read()? {
                    Event::Key(key) if key.kind == KeyEventKind::Press => match key.code {
                        KeyCode::Char('q') => break,
                        KeyCode::Char('c') => {
                            cleared = true;
                            terminal.clear()?;
                        }
                        _ => {}
                    },
                    _ => {}
                }
            }

            let since_ms = chrono::Utc::now().timestamp_millis() - 86_400_000;
            let servers = rt.block_on(db.server_summary(None, Some(since_ms)))?;
            let tools = rt.block_on(db.tool_summary(None, Some(since_ms)))?;
            let calls = rt.block_on(db.recent_calls(12, None, false))?;

            terminal.draw(|frame| {
                let chunks = Layout::vertical([
                    Constraint::Length(1),
                    Constraint::Percentage(35),
                    Constraint::Percentage(35),
                    Constraint::Min(1),
                ])
                .split(frame.area());

                let title = Paragraph::new(
                    Line::from(" mcpspy — live MCP traffic ").style(
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    ),
                );
                frame.render_widget(title, chunks[0]);

                let s_lines: Vec<Line> = if cleared {
                    Vec::new()
                } else {
                    server_lines(&servers).into_iter().map(Line::from).collect()
                };
                frame.render_widget(
                    Paragraph::new(s_lines)
                        .block(Block::default().borders(Borders::ALL).title(" Servers ")),
                    chunks[1],
                );

                let t_lines: Vec<Line> = if cleared {
                    Vec::new()
                } else {
                    tool_lines(&tools).into_iter().map(Line::from).collect()
                };
                frame.render_widget(
                    Paragraph::new(t_lines)
                        .block(Block::default().borders(Borders::ALL).title(" Tools ")),
                    chunks[2],
                );

                let r_lines: Vec<Line> = if cleared {
                    Vec::new()
                } else {
                    recent_lines(&calls).into_iter().map(Line::from).collect()
                };
                frame.render_widget(
                    Paragraph::new(r_lines).block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(" Recent calls  (q quit · c clear) "),
                    ),
                    chunks[3],
                );
            })?;

            std::thread::sleep(Duration::from_millis(200));
        }
        Ok(())
    })();

    execute!(stdout(), LeaveAlternateScreen)?;
    disable_raw_mode()?;
    result
}

#[cfg(not(feature = "tui"))]
pub fn run_tui(_db_path: &str) -> Result<()> {
    anyhow::bail!("`top` requires the `tui` feature")
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{TimeZone, Utc};

    fn server(name: &str, calls: i64, tok: i64) -> ServerSummary {
        ServerSummary {
            server_name: name.into(),
            total_calls: calls,
            total_req_tokens: tok,
            total_resp_tokens: tok * 2,
            avg_duration_ms: 12.5,
            p95_duration_ms: 45.0,
            p50_duration_ms: 12.5,
            error_count: 1,
        }
    }

    fn tool(name: &str) -> ToolSummary {
        ToolSummary {
            server_name: "alpha".into(),
            tool_name: name.into(),
            total_calls: 5,
            total_req_tokens: 600,
            total_resp_tokens: 1_700,
            avg_duration_ms: 8.0,
            p95_duration_ms: 20.0,
            p50_duration_ms: 12.5,
            error_count: 0,
        }
    }

    #[test]
    fn server_lines_include_name_and_bar() {
        let lines = server_lines(&[server("alpha", 10, 1_200), server("beta", 5, 600)]);
        assert_eq!(lines.len(), 2);
        assert!(lines[0].contains("alpha"), "line: {}", lines[0]);
        assert!(lines[0].contains("█"), "line: {}", lines[0]);
        assert!(lines[0].contains("1.2k"), "line: {}", lines[0]);
        assert!(lines[0].contains("p50"), "line: {}", lines[0]);
        assert!(lines[1].contains("beta"), "line: {}", lines[1]);
    }

    #[test]
    fn tool_lines_include_tool_name_and_tokens() {
        let lines = tool_lines(&[tool("read_file")]);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("read_file"), "line: {}", lines[0]);
        assert!(lines[0].contains("2.3k"), "line: {}", lines[0]);
    }

    #[test]
    fn recent_lines_include_method_and_latency() {
        let calls = vec![RecentCall {
            started_at: Utc.timestamp_millis_opt(1_700_000_000_000).unwrap(),
            server_name: "alpha".into(),
            method: "tools/call".into(),
            tool_name: Some("read_file".into()),
            duration_ms: 12.5,
            req_tokens: 100,
            resp_tokens: 200,
            is_error: false,
        }];
        let lines = recent_lines(&calls);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("read_file"), "line: {}", lines[0]);
        assert!(lines[0].contains("12.50ms"), "line: {}", lines[0]);
    }
}