mcpspy 0.2.0

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! Fast token estimator and payload previewer.
//!
//! Estimates token count at roughly 4 characters per token plus JSON
//! structural overhead. Not a replacement for a real tokenizer, but
//! sufficient for comparative token-burn auditing across MCP calls.

use crate::redactor::preview_global;

/// Estimated token count for a string (~4 chars/token + JSON overhead).
#[derive(Debug, Clone, Copy, Default)]
pub struct TokenEstimate {
    pub chars: usize,
    pub estimated_tokens: u64,
}

/// Fast token estimator: ~4 characters per token, with a small JSON
/// structural overhead per structural character.
#[derive(Debug, Clone, Default)]
pub struct TokenEstimator {
    chars_per_token: f64,
    json_overhead_per_struct_char: f64,
}

impl TokenEstimator {
    /// Create a new estimator with default settings (~4 chars/token).
    pub fn new() -> Self {
        Self {
            chars_per_token: 4.0,
            json_overhead_per_struct_char: 0.25,
        }
    }

    /// Estimate tokens for a raw string payload.
    pub fn estimate(&self, text: &str) -> TokenEstimate {
        let chars = text.chars().count();
        // Count JSON structural characters for slight overhead
        let struct_chars = text
            .chars()
            .filter(|c| matches!(c, '{' | '}' | '[' | ']' | ':' | ','))
            .count();
        let base = chars as f64 / self.chars_per_token;
        let overhead = struct_chars as f64 * self.json_overhead_per_struct_char;
        let estimated_tokens = (base + overhead).ceil().max(1.0) as u64;
        TokenEstimate {
            chars,
            estimated_tokens,
        }
    }

    /// Estimate tokens and return a redacted, truncated preview.
    pub fn estimate_with_preview(
        &self,
        text: &str,
        max_preview: usize,
    ) -> (TokenEstimate, Option<String>) {
        let estimate = self.estimate(text);
        let preview = preview_global(text, max_preview);
        (estimate, preview)
    }
}

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

    #[test]
    fn estimates_tokens_for_short_text() {
        let e = TokenEstimator::new();
        let t = e.estimate("hello");
        // 5 chars / 4 = 1.25 -> ceil = 2
        assert_eq!(t.estimated_tokens, 2);
    }

    #[test]
    fn estimates_tokens_for_empty_text() {
        let e = TokenEstimator::new();
        let t = e.estimate("");
        assert_eq!(t.estimated_tokens, 1); // min 1
    }

    #[test]
    fn json_overhead_increases_estimate() {
        let e = TokenEstimator::new();
        let plain = e.estimate("hello world");
        let json = e.estimate(r#"{"hello":"world"}"#);
        assert!(json.estimated_tokens >= plain.estimated_tokens);
    }

    #[test]
    fn preview_is_redacted() {
        let e = TokenEstimator::new();
        let (_est, preview) =
            e.estimate_with_preview("sk-abcdef1234567890abcdef1234567890abcdef", 100);
        assert!(preview.is_some());
        assert!(!preview.unwrap().contains("sk-abcdef"));
    }
}