use crate::cli_util::format_duration_ms;
use anyhow::Result;
use mcpspy::core::db::TelemetryDb;
use mcpspy::core::models::{RecentCall, SchemaViolation};
use std::path::Path;
pub fn render_table(calls: &[RecentCall]) -> String {
let mut out = String::new();
out.push_str(&format!(
"{:<26} {:<16} {:<14} {:<18} {:>10} {:>8} {:>8} {:>4}\n",
"TIME", "SERVER", "METHOD", "TOOL", "DURATION", "REQ", "RESP", "ERR"
));
out.push_str(&"-".repeat(110));
out.push('\n');
if calls.is_empty() {
out.push_str("no calls recorded yet\n");
return out;
}
for c in calls {
let ts = c.started_at.format("%Y-%m-%d %H:%M:%S").to_string();
out.push_str(&format!(
"{:<26} {:<16} {:<14} {:<18} {:>10} {:>8} {:>8} {:>4}\n",
ts,
c.server_name,
c.method,
c.tool_name.as_deref().unwrap_or("-"),
format_duration_ms(c.duration_ms),
c.req_tokens,
c.resp_tokens,
if c.is_error { "yes" } else { "-" },
));
}
out
}
pub fn render_violations(violations: &[SchemaViolation]) -> String {
let mut out = String::new();
out.push_str(&format!(
"{:<26} {:<16} {:<10} {:<10} {:<24} {}\n",
"TIME", "SERVER", "DIRECTION", "ID", "CODE", "DETAIL"
));
out.push_str(&"-".repeat(100));
out.push('\n');
if violations.is_empty() {
out.push_str("no schema violations recorded\n");
return out;
}
for v in violations {
let ts = chrono::DateTime::from_timestamp_millis(v.started_at_ms)
.map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_default();
out.push_str(&format!(
"{:<26} {:<16} {:<10} {:<10} {:<24} {}\n",
ts,
v.server_name,
v.direction,
v.rpc_id.as_deref().unwrap_or("-"),
v.code,
v.detail,
));
}
out
}
pub fn run(
db_path: &str,
n: i64,
server: Option<&str>,
errors_only: bool,
violations: bool,
) -> Result<()> {
let db = TelemetryDb::open(Path::new(db_path))?;
let rt = tokio::runtime::Runtime::new()?;
if violations {
let found = rt.block_on(db.recent_violations(n, server))?;
print!("{}", render_violations(&found));
} else {
let calls = rt.block_on(db.recent_calls(n, server, errors_only))?;
print!("{}", render_table(&calls));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{TimeZone, Utc};
fn call(name: Option<&str>, err: bool) -> RecentCall {
RecentCall {
started_at: Utc.timestamp_millis_opt(1_700_000_000_000).unwrap(),
server_name: "alpha".into(),
method: "tools/call".into(),
tool_name: name.map(|s| s.to_string()),
duration_ms: 12.5,
req_tokens: 100,
resp_tokens: 200,
is_error: err,
}
}
#[test]
fn render_table_has_headers_and_rows() {
let out = render_table(&[call(Some("read_file"), false), call(None, true)]);
assert!(out.contains("TIME"), "output: {out}");
assert!(out.contains("SERVER"), "output: {out}");
assert!(out.contains("METHOD"), "output: {out}");
assert!(out.contains("TOOL"), "output: {out}");
assert!(out.contains("DURATION"), "output: {out}");
assert!(out.contains("alpha"), "output: {out}");
assert!(out.contains("read_file"), "output: {out}");
assert!(out.contains("12.50ms"), "output: {out}");
assert!(out.contains("ERR"), "output: {out}");
}
#[test]
fn render_table_handles_empty() {
let out = render_table(&[]);
assert!(out.contains("no calls"), "output: {out}");
}
fn violation(code: &str) -> mcpspy::core::models::SchemaViolation {
mcpspy::core::models::SchemaViolation {
session_id: "s".into(),
server_name: "alpha".into(),
rpc_id: Some("1".into()),
direction: "request".into(),
code: code.into(),
detail: "jsonrpc=1.0".into(),
raw_preview: None,
started_at_ms: 1_700_000_000_000,
}
}
#[test]
fn render_violations_shows_code_and_detail() {
let out = render_violations(&[violation("bad_version")]);
assert!(out.contains("TIME"), "output: {out}");
assert!(out.contains("CODE"), "output: {out}");
assert!(out.contains("bad_version"), "output: {out}");
assert!(out.contains("jsonrpc=1.0"), "output: {out}");
}
}