Skip to main content

poly_mcp/modules/
clipboard.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use std::fs;
6use chrono::{DateTime, Utc};
7
8#[derive(Clone, Debug)]
9struct ClipEntry {
10    content: String,
11    #[allow(dead_code)]
12    tag: String,
13    source: ClipSource,
14    timestamp: DateTime<Utc>,
15    line_count: usize,
16    byte_size: usize,
17}
18
19#[derive(Clone, Debug)]
20enum ClipSource {
21    File {
22        path: String,
23        lines: Option<Vec<(usize, usize)>>,
24    },
25    Direct,
26}
27
28pub struct ClipboardModule {
29    entries: Arc<Mutex<HashMap<String, ClipEntry>>>,
30}
31
32impl ClipboardModule {
33    pub fn new() -> Self {
34        Self {
35            entries: Arc::new(Mutex::new(HashMap::new())),
36        }
37    }
38
39    pub fn get_tools(&self) -> Vec<Value> {
40        vec![
41            json!({
42                "name": "clip_copy_file",
43                "description": "Copy text from a file into the session clipboard with a tag. Reads file content (optionally specific line ranges) and stores it for later paste operations. Saves tokens by avoiding redundant file reads.",
44                "inputSchema": {
45                    "type": "object",
46                    "properties": {
47                        "path": {
48                            "type": "string",
49                            "description": "Path to the file to copy from"
50                        },
51                        "tag": {
52                            "type": "string",
53                            "description": "Tag name to store this content under (used to retrieve it later)"
54                        },
55                        "lines": {
56                            "type": "array",
57                            "description": "Optional line ranges to copy, e.g. [[1,10], [20,30]]. Copies entire file if omitted.",
58                            "items": {
59                                "type": "array",
60                                "minItems": 2,
61                                "maxItems": 2,
62                                "items": { "type": "integer" }
63                            }
64                        }
65                    },
66                    "required": ["path", "tag"]
67                }
68            }),
69            json!({
70                "name": "clip_copy",
71                "description": "Copy arbitrary text directly into the session clipboard with a tag. Use this to store computed/generated content or text from tool outputs for later reuse without re-generating.",
72                "inputSchema": {
73                    "type": "object",
74                    "properties": {
75                        "content": {
76                            "type": "string",
77                            "description": "Text content to store"
78                        },
79                        "tag": {
80                            "type": "string",
81                            "description": "Tag name to store this content under"
82                        }
83                    },
84                    "required": ["content", "tag"]
85                }
86            }),
87            json!({
88                "name": "clip_paste_file",
89                "description": "Paste tagged clipboard content into a file. Can overwrite the entire file, append, prepend, or replace specific line ranges.",
90                "inputSchema": {
91                    "type": "object",
92                    "properties": {
93                        "tag": {
94                            "type": "string",
95                            "description": "Tag of the clipboard entry to paste"
96                        },
97                        "path": {
98                            "type": "string",
99                            "description": "Destination file path"
100                        },
101                        "mode": {
102                            "type": "string",
103                            "enum": ["overwrite", "append", "prepend", "lines"],
104                            "description": "Paste mode (default: overwrite). 'lines' uses the lines parameter to replace specific ranges."
105                        },
106                        "lines": {
107                            "type": "array",
108                            "description": "Line ranges to replace in the destination file (for mode='lines'), e.g. [[5,10]].",
109                            "items": {
110                                "type": "array",
111                                "minItems": 2,
112                                "maxItems": 2,
113                                "items": { "type": "integer" }
114                            }
115                        }
116                    },
117                    "required": ["tag", "path"]
118                }
119            }),
120            json!({
121                "name": "clip_paste",
122                "description": "Retrieve tagged clipboard content. Returns the stored text so the agent can use it without re-reading the original source. Omit tag to list all entries.",
123                "inputSchema": {
124                    "type": "object",
125                    "properties": {
126                        "tag": {
127                            "type": "string",
128                            "description": "Tag of the clipboard entry to retrieve. Omit to list all tags with metadata."
129                        }
130                    }
131                }
132            }),
133            json!({
134                "name": "clip_clear",
135                "description": "Clear one or all clipboard entries from the session.",
136                "inputSchema": {
137                    "type": "object",
138                    "properties": {
139                        "tag": {
140                            "type": "string",
141                            "description": "Tag to clear. Omit to clear all entries."
142                        }
143                    }
144                }
145            }),
146        ]
147    }
148
149    pub async fn copy_file(&self, args: Value) -> Result<Value> {
150        let path = args["path"].as_str().context("Missing 'path' parameter")?;
151        let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
152
153        let full_content = fs::read_to_string(path)
154            .with_context(|| format!("Failed to read file: {}", path))?;
155
156        let mut line_ranges: Option<Vec<(usize, usize)>> = None;
157
158        let content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
159            let all_lines: Vec<&str> = full_content.lines().collect();
160            let mut selected_lines = Vec::new();
161            let mut ranges = Vec::new();
162
163            for range in lines_array {
164                if let Some(range_arr) = range.as_array() {
165                    if range_arr.len() == 2 {
166                        let from = range_arr[0].as_u64().unwrap_or(1) as usize;
167                        let to = range_arr[1].as_u64().unwrap_or(all_lines.len() as u64) as usize;
168                        let from_idx = from.saturating_sub(1);
169                        let to_idx = to.min(all_lines.len());
170
171                        if from_idx < all_lines.len() && from_idx < to_idx {
172                            selected_lines.extend_from_slice(&all_lines[from_idx..to_idx]);
173                        }
174                        ranges.push((from, to));
175                    }
176                }
177            }
178
179            line_ranges = Some(ranges);
180            selected_lines.join("\n")
181        } else {
182            full_content
183        };
184
185        let line_count = content.lines().count();
186        let byte_size = content.len();
187
188        let entry = ClipEntry {
189            content,
190            tag: tag.to_string(),
191            source: ClipSource::File {
192                path: path.to_string(),
193                lines: line_ranges.clone(),
194            },
195            timestamp: Utc::now(),
196            line_count,
197            byte_size,
198        };
199
200        let mut entries = self.entries.lock().unwrap();
201        entries.insert(tag.to_string(), entry);
202
203        Ok(json!({
204            "success": true,
205            "tag": tag,
206            "source": path,
207            "lines": line_ranges.map(|r| r.iter().map(|(a, b)| json!([a, b])).collect::<Vec<_>>()),
208            "line_count": line_count,
209            "byte_size": byte_size,
210            "total_entries": entries.len()
211        }))
212    }
213
214    pub async fn copy(&self, args: Value) -> Result<Value> {
215        let content = args["content"].as_str().context("Missing 'content' parameter")?;
216        let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
217
218        let line_count = content.lines().count();
219        let byte_size = content.len();
220
221        let entry = ClipEntry {
222            content: content.to_string(),
223            tag: tag.to_string(),
224            source: ClipSource::Direct,
225            timestamp: Utc::now(),
226            line_count,
227            byte_size,
228        };
229
230        let mut entries = self.entries.lock().unwrap();
231        entries.insert(tag.to_string(), entry);
232
233        Ok(json!({
234            "success": true,
235            "tag": tag,
236            "source": "direct",
237            "line_count": line_count,
238            "byte_size": byte_size,
239            "total_entries": entries.len()
240        }))
241    }
242
243    pub async fn paste_file(&self, args: Value) -> Result<Value> {
244        let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
245        let path = args["path"].as_str().context("Missing 'path' parameter")?;
246        let mode = args["mode"].as_str().unwrap_or("overwrite");
247
248        let entries = self.entries.lock().unwrap();
249        let entry = entries.get(tag)
250            .with_context(|| format!("No clipboard entry with tag '{}'", tag))?;
251        let content = entry.content.clone();
252        drop(entries);
253
254        let final_content = match mode {
255            "append" => {
256                let existing = fs::read_to_string(path).unwrap_or_default();
257                format!("{}{}", existing, content)
258            }
259            "prepend" => {
260                let existing = fs::read_to_string(path).unwrap_or_default();
261                format!("{}{}", content, existing)
262            }
263            "lines" => {
264                let existing = fs::read_to_string(path).unwrap_or_default();
265                let mut all_lines: Vec<String> = existing.lines().map(|s| s.to_string()).collect();
266                let new_lines: Vec<&str> = content.lines().collect();
267                let mut new_line_idx = 0;
268
269                if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
270                    for range in lines_array {
271                        if let Some(range_arr) = range.as_array() {
272                            if range_arr.len() == 2 {
273                                let from = range_arr[0].as_u64().unwrap_or(1) as usize;
274                                let to = range_arr[1].as_u64().unwrap_or(all_lines.len() as u64) as usize;
275                                let from_idx = from.saturating_sub(1);
276                                let to_idx = to.min(all_lines.len());
277                                let range_size = to_idx.saturating_sub(from_idx);
278
279                                while all_lines.len() < to_idx {
280                                    all_lines.push(String::new());
281                                }
282
283                                for i in 0..range_size {
284                                    if new_line_idx < new_lines.len() {
285                                        all_lines[from_idx + i] = new_lines[new_line_idx].to_string();
286                                        new_line_idx += 1;
287                                    }
288                                }
289                            }
290                        }
291                    }
292                } else {
293                    return Err(anyhow::anyhow!("Mode 'lines' requires 'lines' parameter"));
294                }
295
296                all_lines.join("\n") + "\n"
297            }
298            _ => content.clone(), // overwrite
299        };
300
301        if let Some(parent) = std::path::Path::new(path).parent() {
302            fs::create_dir_all(parent)
303                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
304        }
305
306        let bytes_written = final_content.len();
307        fs::write(path, &final_content)
308            .with_context(|| format!("Failed to write to file: {}", path))?;
309
310        Ok(json!({
311            "success": true,
312            "tag": tag,
313            "destination": path,
314            "mode": mode,
315            "bytes_written": bytes_written
316        }))
317    }
318
319    pub async fn paste(&self, args: Value) -> Result<Value> {
320        let entries = self.entries.lock().unwrap();
321
322        if let Some(tag) = args["tag"].as_str() {
323            if let Some(entry) = entries.get(tag) {
324                let source = match &entry.source {
325                    ClipSource::File { path, lines } => json!({
326                        "type": "file",
327                        "path": path,
328                        "lines": lines.as_ref().map(|r| r.iter().map(|(a, b)| json!([a, b])).collect::<Vec<_>>())
329                    }),
330                    ClipSource::Direct => json!({ "type": "direct" }),
331                };
332
333                Ok(json!({
334                    "tag": tag,
335                    "content": entry.content,
336                    "source": source,
337                    "line_count": entry.line_count,
338                    "byte_size": entry.byte_size,
339                    "timestamp": entry.timestamp.to_rfc3339(),
340                    "found": true
341                }))
342            } else {
343                Ok(json!({
344                    "tag": tag,
345                    "found": false,
346                    "error": format!("No entry with tag '{}'", tag)
347                }))
348            }
349        } else {
350            let listing: Vec<Value> = entries.iter().map(|(tag, entry)| {
351                let source_type = match &entry.source {
352                    ClipSource::File { path, .. } => json!({"type": "file", "path": path}),
353                    ClipSource::Direct => json!({"type": "direct"}),
354                };
355                json!({
356                    "tag": tag,
357                    "source": source_type,
358                    "line_count": entry.line_count,
359                    "byte_size": entry.byte_size,
360                    "timestamp": entry.timestamp.to_rfc3339()
361                })
362            }).collect();
363
364            Ok(json!({
365                "entries": listing,
366                "count": listing.len()
367            }))
368        }
369    }
370
371    pub async fn clear(&self, args: Value) -> Result<Value> {
372        let mut entries = self.entries.lock().unwrap();
373
374        if let Some(tag) = args["tag"].as_str() {
375            let removed = entries.remove(tag).is_some();
376            Ok(json!({
377                "success": removed,
378                "tag": tag,
379                "removed": removed,
380                "remaining": entries.len()
381            }))
382        } else {
383            let count = entries.len();
384            entries.clear();
385            Ok(json!({
386                "success": true,
387                "cleared": count,
388                "remaining": 0
389            }))
390        }
391    }
392}