Skip to main content

poly_mcp/modules/
context.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use tiktoken_rs::{cl100k_base, o200k_base};
6use flate2::write::{ZlibEncoder, GzEncoder};
7use flate2::Compression;
8use std::io::Write as _;
9
10pub struct ContextModule {
11    memory_store: Arc<Mutex<HashMap<String, Value>>>,
12    context_usage: Arc<Mutex<ContextUsage>>,
13    cl100k_bpe: Arc<tiktoken_rs::CoreBPE>,
14    o200k_bpe: Arc<tiktoken_rs::CoreBPE>,
15}
16
17#[derive(Default)]
18struct ContextUsage {
19    total_tokens: usize,
20    used_tokens: usize,
21}
22
23impl Default for ContextModule {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl ContextModule {
30    pub fn new() -> Self {
31        Self {
32            memory_store: Arc::new(Mutex::new(HashMap::new())),
33            context_usage: Arc::new(Mutex::new(ContextUsage::default())),
34            cl100k_bpe: Arc::new(cl100k_base().expect("Failed to load cl100k tokenizer")),
35            o200k_bpe: Arc::new(o200k_base().expect("Failed to load o200k tokenizer")),
36        }
37    }
38
39    pub fn get_tools(&self) -> Vec<Value> {
40        vec![
41            json!({
42                "name": "ctx_context",
43                "description": "Get token usage statistics (total, left, used)",
44                "inputSchema": {
45                    "type": "object",
46                    "properties": {
47                        "set_total": {
48                            "type": "number",
49                            "description": "Set the total context window size"
50                        },
51                        "add_used": {
52                            "type": "number",
53                            "description": "Add to used token count"
54                        }
55                    }
56                }
57            }),
58            json!({
59                "name": "ctx_compact",
60                "description": "Compress text using algorithms to reduce size",
61                "inputSchema": {
62                    "type": "object",
63                    "properties": {
64                        "text": {
65                            "type": "string",
66                            "description": "Text to compress"
67                        },
68                        "algorithm": {
69                            "type": "string",
70                            "enum": ["zlib", "gzip"],
71                            "description": "Compression algorithm (default: zlib)"
72                        }
73                    },
74                    "required": ["text"]
75                }
76            }),
77            json!({
78                "name": "ctx_remove",
79                "description": "Clear context and reset usage",
80                "inputSchema": {
81                    "type": "object",
82                    "properties": {
83                        "reset_memory": {
84                            "type": "boolean",
85                            "description": "Also clear memory store (default: false)"
86                        }
87                    }
88                }
89            }),
90            json!({
91                "name": "ctx_token_count",
92                "description": "Count tokens in text for various LLM providers",
93                "inputSchema": {
94                    "type": "object",
95                    "properties": {
96                        "text": {
97                            "type": "string",
98                            "description": "Text to count tokens for"
99                        },
100                        "model": {
101                            "type": "string",
102                            "enum": ["gpt-4", "gpt-3.5-turbo", "claude-3", "claude-2", "o200k"],
103                            "description": "Model to use for tokenization (default: gpt-4)"
104                        }
105                    },
106                    "required": ["text"]
107                }
108            }),
109            json!({
110                "name": "ctx_memory_store",
111                "description": "Store data in memory (process lifetime)",
112                "inputSchema": {
113                    "type": "object",
114                    "properties": {
115                        "key": {
116                            "type": "string",
117                            "description": "Key to store data under"
118                        },
119                        "value": {
120                            "description": "Value to store (any JSON type)"
121                        }
122                    },
123                    "required": ["key", "value"]
124                }
125            }),
126            json!({
127                "name": "ctx_memory_recall",
128                "description": "Retrieve stored data from memory",
129                "inputSchema": {
130                    "type": "object",
131                    "properties": {
132                        "key": {
133                            "type": "string",
134                            "description": "Key to retrieve (omit to list all keys)"
135                        }
136                    }
137                }
138            }),
139            json!({
140                "name": "ctx_estimate_cost",
141                "description": "Estimate API costs for LLM providers",
142                "inputSchema": {
143                    "type": "object",
144                    "properties": {
145                        "provider": {
146                            "type": "string",
147                            "enum": ["anthropic", "openai", "ollama", "glm"],
148                            "description": "LLM provider"
149                        },
150                        "model": {
151                            "type": "string",
152                            "description": "Model name"
153                        },
154                        "input_tokens": {
155                            "type": "number",
156                            "description": "Number of input tokens"
157                        },
158                        "output_tokens": {
159                            "type": "number",
160                            "description": "Number of output tokens"
161                        }
162                    },
163                    "required": ["provider", "model", "input_tokens", "output_tokens"]
164                }
165            }),
166        ]
167    }
168
169    pub async fn context(&self, args: Value) -> Result<Value> {
170        let mut usage = self.context_usage.lock().unwrap();
171
172        if let Some(total) = args["set_total"].as_u64() {
173            usage.total_tokens = total as usize;
174        }
175
176        if let Some(add_used) = args["add_used"].as_u64() {
177            usage.used_tokens += add_used as usize;
178        }
179
180        let left = usage.total_tokens.saturating_sub(usage.used_tokens);
181        let usage_percent = if usage.total_tokens > 0 {
182            (usage.used_tokens as f64 / usage.total_tokens as f64) * 100.0
183        } else {
184            0.0
185        };
186
187        Ok(json!({
188            "total": usage.total_tokens,
189            "used": usage.used_tokens,
190            "left": left,
191            "usage_percent": usage_percent
192        }))
193    }
194
195    pub async fn compact_context(&self, args: Value) -> Result<Value> {
196        let text = args["text"].as_str().context("Missing 'text' parameter")?;
197        let algorithm = args["algorithm"].as_str().unwrap_or("zlib");
198
199        let original_size = text.len();
200
201        let compressed = match algorithm {
202            "zlib" => {
203                let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
204                encoder.write_all(text.as_bytes())?;
205                encoder.finish()?
206            }
207            "gzip" => {
208                let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
209                encoder.write_all(text.as_bytes())?;
210                encoder.finish()?
211            }
212            _ => return Err(anyhow::anyhow!("Unknown compression algorithm: {}", algorithm)),
213        };
214
215        let compressed_size = compressed.len();
216        let compression_ratio = (compressed_size as f64 / original_size as f64) * 100.0;
217
218        // Encode compressed data as base64 for safe transport
219        use base64::{Engine, engine::general_purpose};
220        let encoded = general_purpose::STANDARD.encode(&compressed);
221
222        Ok(json!({
223            "original_size": original_size,
224            "compressed_size": compressed_size,
225            "compression_ratio_percent": compression_ratio,
226            "algorithm": algorithm,
227            "compressed_data": encoded,
228            "savings_bytes": original_size - compressed_size
229        }))
230    }
231
232    pub async fn remove_context(&self, args: Value) -> Result<Value> {
233        let reset_memory = args["reset_memory"].as_bool().unwrap_or(false);
234
235        let mut usage = self.context_usage.lock().unwrap();
236        usage.used_tokens = 0;
237
238        let memory_cleared = if reset_memory {
239            let mut store = self.memory_store.lock().unwrap();
240            let count = store.len();
241            store.clear();
242            count
243        } else {
244            0
245        };
246
247        Ok(json!({
248            "success": true,
249            "context_reset": true,
250            "memory_cleared": reset_memory,
251            "memory_items_cleared": memory_cleared
252        }))
253    }
254
255    pub async fn token_count(&self, args: Value) -> Result<Value> {
256        let text = args["text"].as_str().context("Missing 'text' parameter")?;
257        let model = args["model"].as_str().unwrap_or("gpt-4");
258
259        let token_count = match model {
260            "gpt-4" | "gpt-3.5-turbo" | "claude-3" | "claude-2" => {
261                self.cl100k_bpe.encode_with_special_tokens(text).len()
262            }
263            "o200k" => {
264                self.o200k_bpe.encode_with_special_tokens(text).len()
265            }
266            _ => {
267                // Fallback: simple word-based estimation
268                let words = text.split_whitespace().count();
269                (words as f64 * 1.3) as usize // Rough approximation
270            }
271        };
272
273        let byte_count = text.len();
274        let mut char_count = 0usize;
275        let mut word_count = 0usize;
276        let mut in_word = false;
277        for c in text.chars() {
278            char_count += 1;
279            if c.is_whitespace() {
280                in_word = false;
281            } else if !in_word {
282                in_word = true;
283                word_count += 1;
284            }
285        }
286
287        Ok(json!({
288            "token_count": token_count,
289            "char_count": char_count,
290            "byte_count": byte_count,
291            "word_count": word_count,
292            "model": model,
293            "tokens_per_word": if word_count > 0 { token_count as f64 / word_count as f64 } else { 0.0 }
294        }))
295    }
296
297    pub async fn memory_store(&self, args: Value) -> Result<Value> {
298        let key = args["key"].as_str().context("Missing 'key' parameter")?;
299        let value = args.get("value").context("Missing 'value' parameter")?;
300
301        let mut store = self.memory_store.lock().unwrap();
302        store.insert(key.to_string(), value.clone());
303
304        Ok(json!({
305            "success": true,
306            "key": key,
307            "stored": true,
308            "total_keys": store.len()
309        }))
310    }
311
312    pub async fn memory_recall(&self, args: Value) -> Result<Value> {
313        let store = self.memory_store.lock().unwrap();
314
315        if let Some(key) = args["key"].as_str() {
316            if let Some(value) = store.get(key) {
317                Ok(json!({
318                    "key": key,
319                    "value": value,
320                    "found": true
321                }))
322            } else {
323                Ok(json!({
324                    "key": key,
325                    "found": false,
326                    "error": "Key not found"
327                }))
328            }
329        } else {
330            // List all keys
331            let keys: Vec<String> = store.keys().cloned().collect();
332
333            Ok(json!({
334                "keys": keys,
335                "count": keys.len()
336            }))
337        }
338    }
339
340    pub async fn estimate_cost(&self, args: Value) -> Result<Value> {
341        let provider = args["provider"].as_str().context("Missing 'provider' parameter")?;
342        let model = args["model"].as_str().context("Missing 'model' parameter")?;
343        let input_tokens = args["input_tokens"].as_u64().context("Missing 'input_tokens' parameter")? as usize;
344        let output_tokens = args["output_tokens"].as_u64().context("Missing 'output_tokens' parameter")? as usize;
345
346        let (input_price_per_1m, output_price_per_1m) = match (provider, model) {
347            // Anthropic Claude pricing (per 1M tokens)
348            ("anthropic", "claude-opus-4") | ("anthropic", "claude-opus-4-6") => (15.0, 75.0),
349            ("anthropic", "claude-sonnet-4") | ("anthropic", "claude-sonnet-4-6") => (3.0, 15.0),
350            ("anthropic", "claude-haiku-4-5") | ("anthropic", "claude-haiku-4") => (0.80, 4.0),
351            ("anthropic", "claude-3-opus") => (15.0, 75.0),
352            ("anthropic", "claude-3-sonnet") | ("anthropic", "claude-3.5-sonnet") => (3.0, 15.0),
353            ("anthropic", "claude-3-haiku") | ("anthropic", "claude-3.5-haiku") => (0.25, 1.25),
354
355            // OpenAI pricing (per 1M tokens)
356            ("openai", "gpt-4o") => (2.50, 10.0),
357            ("openai", "gpt-4o-mini") => (0.15, 0.60),
358            ("openai", "gpt-4-turbo") => (10.0, 30.0),
359            ("openai", "gpt-4") => (30.0, 60.0),
360            ("openai", "gpt-3.5-turbo") => (0.50, 1.50),
361            ("openai", "o1") => (15.0, 60.0),
362            ("openai", "o1-mini") => (3.0, 12.0),
363            ("openai", "o3-mini") => (1.10, 4.40),
364
365            // Ollama (free/local)
366            ("ollama", _) => (0.0, 0.0),
367
368            // GLM
369            ("glm", "glm-4") => (1.0, 3.0),
370
371            _ => return Err(anyhow::anyhow!("Unknown provider/model combination: {}/{}", provider, model)),
372        };
373
374        let input_cost = (input_tokens as f64 / 1_000_000.0) * input_price_per_1m;
375        let output_cost = (output_tokens as f64 / 1_000_000.0) * output_price_per_1m;
376        let total_cost = input_cost + output_cost;
377
378        Ok(json!({
379            "provider": provider,
380            "model": model,
381            "input_tokens": input_tokens,
382            "output_tokens": output_tokens,
383            "total_tokens": input_tokens + output_tokens,
384            "input_cost_usd": input_cost,
385            "output_cost_usd": output_cost,
386            "total_cost_usd": total_cost,
387            "pricing": {
388                "input_per_1m_tokens": input_price_per_1m,
389                "output_per_1m_tokens": output_price_per_1m
390            }
391        }))
392    }
393}