1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
use anyhow::Result;
use rmcp::{
ServerHandler,
model::*,
service::{RequestContext, RoleServer},
};
use serde_json::json;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::info;
use crate::transcriber::{TranscriberEngine, TranscriptionOptions, WhisperModel};
use crate::utils::paths::get_default_output_dir;
#[derive(Clone)]
pub struct VideoTranscriberServer {
transcriber: Arc<Mutex<TranscriberEngine>>,
}
impl Default for VideoTranscriberServer {
fn default() -> Self {
Self::new()
}
}
impl VideoTranscriberServer {
pub fn new() -> Self {
Self {
transcriber: Arc::new(Mutex::new(TranscriberEngine::new())),
}
}
}
impl ServerHandler for VideoTranscriberServer {
fn get_info(&self) -> ServerInfo {
// rmcp 1.x marks InitializeResult as #[non_exhaustive], so the
// `ServerInfo { instructions, capabilities, ..Default::default() }`
// struct expression no longer compiles. Mutate a default instance
// instead — same behaviour, allowed by the non_exhaustive rules.
let mut info = ServerInfo::default();
info.instructions = Some(
"High-performance video transcription server using whisper.cpp.\n\
Transcribes videos from 1000+ platforms or local files - 6x faster than Python whisper!"
.into(),
);
info.capabilities = ServerCapabilities::builder().enable_tools().build();
info
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult {
tools: vec![
// rmcp 1.x marked Tool as #[non_exhaustive], so we construct
// via Tool::new(name, description, input_schema) instead of a
// struct expression. Cleaner anyway — drops a lot of
// `..: None` boilerplate per tool.
Tool::new(
"transcribe_video",
"Transcribe videos from 1000+ platforms (YouTube, Vimeo, TikTok, Twitter, etc.) or local video files using whisper.cpp (4-10x faster than Python whisper!). Downloads/extracts audio and generates transcript in TXT, JSON, and Markdown formats.",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "Video URL from any supported platform OR absolute/relative path to a local video file (mp4, avi, mov, mkv, etc.)"
},
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
},
"model": {
"type": "string",
"enum": ["tiny", "base", "small", "medium", "large"],
"description": "Whisper model to use. Larger models are more accurate but slower. Default: 'base'"
},
"language": {
"type": "string",
"description": "Language code (ISO 639-1: en, es, fr, de, etc.) or 'auto' for automatic detection. Default: 'auto'"
}
},
"required": ["url"]
}))
.unwrap(),
),
),
Tool::new(
"check_dependencies",
"Check if all required dependencies (yt-dlp, ffmpeg, whisper models) are installed",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {}
}))
.unwrap(),
),
),
Tool::new(
"list_supported_sites",
"List all video platforms supported by yt-dlp (1000+ sites including YouTube, Vimeo, TikTok, Twitter, Facebook, Instagram, educational platforms, and more)",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {}
}))
.unwrap(),
),
),
Tool::new(
"list_transcripts",
"List all available transcripts in the output directory, sorted by modification time (newest first)",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
},
"limit": {
"type": "number",
"description": "Optional limit on number of transcripts to return (newest first). If not specified, returns all transcripts."
}
}
}))
.unwrap(),
),
),
Tool::new(
"get_latest_transcript",
"Get the path and details of the most recently created/modified transcript. Useful to avoid accidentally reading old transcripts.",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
}
}
}))
.unwrap(),
),
),
Tool::new(
"delete_transcript",
"Delete a specific transcript by video ID. This removes all associated files (txt, json, md).",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"video_id": {
"type": "string",
"description": "The video ID of the transcript to delete (e.g., 'dQw4w9WgXcQ')"
},
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
}
},
"required": ["video_id"]
}))
.unwrap(),
),
),
Tool::new(
"cleanup_old_transcripts",
"Delete transcripts older than a specified number of days. Helps manage disk space.",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"days": {
"type": "number",
"description": "Delete transcripts older than this many days (e.g., 30 for month-old transcripts)"
},
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
}
},
"required": ["days"]
}))
.unwrap(),
),
),
Tool::new(
"delete_all_transcripts",
"Delete ALL transcripts in the output directory. Use with caution - this cannot be undone!",
Arc::new(
serde_json::from_value(json!({
"type": "object",
"properties": {
"output_dir": {
"type": "string",
"description": format!("Optional output directory path. Defaults to {}", get_default_output_dir().display())
},
"confirm": {
"type": "boolean",
"description": "Must be set to true to confirm deletion of all transcripts"
}
},
"required": ["confirm"]
}))
.unwrap(),
),
),
],
next_cursor: None,
meta: None,
})
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResult, ErrorData> {
match request.name.as_ref() {
"transcribe_video" => {
let args = request.arguments.as_ref().ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing arguments".to_string(),
None,
)
})?;
let url = args
.get("url")
.and_then(|v| v.as_str())
.ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing 'url' parameter".to_string(),
None,
)
})?
.to_string();
let output_dir = args
.get("output_dir")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| get_default_output_dir().to_string_lossy().to_string());
let model = args
.get("model")
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<WhisperModel>().ok())
.unwrap_or(WhisperModel::Base);
let language = args
.get("language")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let options = TranscriptionOptions {
url,
output_dir,
model,
language,
};
info!("🎬 Starting transcription...");
let transcriber = self.transcriber.lock().await;
match transcriber.transcribe(options).await {
Ok(result) => {
let text = format!(
"✅ Video transcribed successfully!\n\n\
**Video Details:**\n\
- Title: {}\n\
- Platform: {}\n\
- Duration: {}s\n\n\
**Transcription Settings:**\n\
- Model: {:?}\n\
- Engine: whisper.cpp (Rust)\n\n\
**Output Files:**\n\
- Text: {}\n\
- JSON: {}\n\
- Markdown: {}\n\n\
**Transcript Preview:**\n\
{}\n\n\
**Full transcript has {} words.**",
result.metadata.title,
result.metadata.platform,
result.metadata.duration,
result.model_used,
result.files.txt,
result.files.json,
result.files.md,
result.transcript_preview,
result.word_count
);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
Err(e) => Err(ErrorData::new(
ErrorCode::INTERNAL_ERROR,
format!("Transcription failed: {}", e),
None,
)),
}
}
"check_dependencies" => {
let transcriber = self.transcriber.lock().await;
match transcriber.check_dependencies() {
Ok(status) => {
let text = format!("✅ Dependency Check:\n\n{}", status);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
Err(e) => Err(ErrorData::new(
ErrorCode::INTERNAL_ERROR,
format!("Dependency check failed: {}", e),
None,
)),
}
}
"list_supported_sites" => {
let text = "📺 Supported Video Platforms (1000+ total)\n\n\
**Popular platforms include:**\n\
- YouTube\n\
- Vimeo\n\
- TikTok\n\
- Twitter/X\n\
- Facebook\n\
- Instagram\n\
- Twitch\n\
- Dailymotion\n\
- Reddit\n\
- LinkedIn\n\
- Many educational and conference platforms\n\n\
**Total: 1000+ supported extractors**\n\n\
You can transcribe videos from any of these platforms!";
Ok(CallToolResult::success(vec![Content::text(text)]))
}
"list_transcripts" => {
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
let output_dir = request
.arguments
.as_ref()
.and_then(|args| args.get("output_dir"))
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(get_default_output_dir);
let limit = request
.arguments
.as_ref()
.and_then(|args| args.get("limit"))
.and_then(|v| v.as_u64())
.map(|n| n as usize);
if !output_dir.exists() {
let text = format!(
"📂 No transcripts directory found at: {}\n\nTranscribe your first video to create it!",
output_dir.display()
);
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
let mut video_groups: HashMap<String, Vec<String>> = HashMap::new();
if let Ok(entries) = fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if filename.ends_with(".txt") || filename.ends_with(".md") {
let video_id =
filename.split('-').next().unwrap_or("unknown").to_string();
video_groups
.entry(video_id)
.or_default()
.push(filename.to_string());
}
}
}
if video_groups.is_empty() {
let text = format!(
"📂 No transcripts found in {}\n\nTranscribe a video to get started!",
output_dir.display()
);
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
// Collect video data with timestamps for sorting
let mut video_data: Vec<(String, Vec<String>, u64, PathBuf)> = Vec::new();
for (video_id, files) in video_groups.iter() {
let main_file = files
.iter()
.find(|f| f.ends_with(".txt"))
.unwrap_or(&files[0]);
let full_path = output_dir.join(main_file);
if let Ok(metadata) = fs::metadata(&full_path) {
let modified = metadata
.modified()
.ok()
.and_then(|t| {
use std::time::SystemTime;
let duration = t.duration_since(SystemTime::UNIX_EPOCH).ok()?;
Some(duration.as_secs())
})
.unwrap_or(0);
video_data.push((video_id.clone(), files.clone(), modified, full_path));
}
}
// Sort by modification time (newest first)
video_data.sort_by_key(|b| std::cmp::Reverse(b.2));
// Apply limit if specified
let videos_to_show = if let Some(lim) = limit {
&video_data[..video_data.len().min(lim)]
} else {
&video_data[..]
};
let mut list_items = Vec::new();
for (i, (video_id, files, modified, full_path)) in videos_to_show.iter().enumerate()
{
let main_file = files
.iter()
.find(|f| f.ends_with(".txt"))
.unwrap_or(&files[0]);
if let Ok(metadata) = fs::metadata(full_path) {
let size_kb = metadata.len() as f64 / 1024.0;
let title = main_file
.replace(&format!("{}-", video_id), "")
.replace(".txt", "")
.replace(".md", "")
.replace(".json", "")
.replace("-", " ");
let extensions: Vec<&str> = files
.iter()
.filter_map(|f| f.split('.').next_back())
.collect();
list_items.push(format!(
"{}. **{}**\n Video ID: {}\n Files: {} ({})\n Size: {:.2} KB\n Modified: {}\n Path: {}",
i + 1,
title,
video_id,
files.len(),
extensions.join(", "),
size_kb,
format_timestamp(*modified),
full_path.display()
));
}
}
let total_count = video_data.len();
let showing_count = videos_to_show.len();
let summary = if showing_count < total_count {
format!(
"showing {} most recent out of {} total",
showing_count, total_count
)
} else {
format!("{} videos", total_count)
};
let text = format!(
"📚 Available transcripts ({}):\n\n{}\n\n💡 Tip: You can read any transcript by asking me to read the file path shown above.",
summary,
list_items.join("\n\n")
);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
"get_latest_transcript" => {
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
let output_dir = request
.arguments
.as_ref()
.and_then(|args| args.get("output_dir"))
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(get_default_output_dir);
if !output_dir.exists() {
let text = format!(
"📂 No transcripts directory found at: {}\n\nTranscribe your first video to create it!",
output_dir.display()
);
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
let mut video_groups: HashMap<String, Vec<String>> = HashMap::new();
if let Ok(entries) = fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if filename.ends_with(".txt") || filename.ends_with(".md") {
let video_id =
filename.split('-').next().unwrap_or("unknown").to_string();
video_groups
.entry(video_id)
.or_default()
.push(filename.to_string());
}
}
}
if video_groups.is_empty() {
let text = format!(
"📂 No transcripts found in {}\n\nTranscribe a video to get started!",
output_dir.display()
);
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
// Find the most recent transcript
let mut latest_transcript: Option<(String, Vec<String>, u64, PathBuf)> = None;
for (video_id, files) in video_groups.iter() {
let main_file = files
.iter()
.find(|f| f.ends_with(".txt"))
.unwrap_or(&files[0]);
let full_path = output_dir.join(main_file);
if let Ok(metadata) = fs::metadata(&full_path) {
let modified = metadata
.modified()
.ok()
.and_then(|t| {
use std::time::SystemTime;
let duration = t.duration_since(SystemTime::UNIX_EPOCH).ok()?;
Some(duration.as_secs())
})
.unwrap_or(0);
if let Some((_, _, latest_time, _)) = &latest_transcript {
if modified > *latest_time {
latest_transcript =
Some((video_id.clone(), files.clone(), modified, full_path));
}
} else {
latest_transcript =
Some((video_id.clone(), files.clone(), modified, full_path));
}
}
}
if let Some((video_id, files, modified, full_path)) = latest_transcript {
let main_file = files
.iter()
.find(|f| f.ends_with(".txt"))
.unwrap_or(&files[0]);
if let Ok(metadata) = fs::metadata(&full_path) {
let size_kb = metadata.len() as f64 / 1024.0;
let title = main_file
.replace(&format!("{}-", video_id), "")
.replace(".txt", "")
.replace(".md", "")
.replace(".json", "")
.replace("-", " ");
let extensions: Vec<&str> = files
.iter()
.filter_map(|f| f.split('.').next_back())
.collect();
// Find paths for all file types
let txt_path = output_dir.join(
files
.iter()
.find(|f| f.ends_with(".txt"))
.unwrap_or(&files[0]),
);
let md_path = files
.iter()
.find(|f| f.ends_with(".md"))
.map(|f| output_dir.join(f));
let json_path = files
.iter()
.find(|f| f.ends_with(".json"))
.map(|f| output_dir.join(f));
let mut file_paths = format!("- Text: {}", txt_path.display());
if let Some(md) = md_path {
file_paths.push_str(&format!("\n- Markdown: {}", md.display()));
}
if let Some(json) = json_path {
file_paths.push_str(&format!("\n- JSON: {}", json.display()));
}
let text = format!(
"📄 **Latest Transcript:**\n\n\
**Title:** {}\n\
**Video ID:** {}\n\
**Modified:** {}\n\
**Size:** {:.2} KB\n\
**Files:** {} ({})\n\n\
**File Paths:**\n{}\n\n\
💡 Tip: Use the text file path above to read or summarize this transcript.",
title,
video_id,
format_timestamp(modified),
size_kb,
files.len(),
extensions.join(", "),
file_paths
);
Ok(CallToolResult::success(vec![Content::text(text)]))
} else {
Err(ErrorData::new(
ErrorCode::INTERNAL_ERROR,
"Failed to read latest transcript metadata".to_string(),
None,
))
}
} else {
let text = "📂 No transcripts found.".to_string();
Ok(CallToolResult::success(vec![Content::text(text)]))
}
}
"delete_transcript" => {
use std::fs;
use std::path::PathBuf;
let args = request.arguments.as_ref().ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing arguments".to_string(),
None,
)
})?;
let video_id = args
.get("video_id")
.and_then(|v| v.as_str())
.ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing 'video_id' parameter".to_string(),
None,
)
})?;
let output_dir = args
.get("output_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(get_default_output_dir);
if !output_dir.exists() {
let text = "📂 No transcripts directory found.".to_string();
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
// Find all files matching the video_id
let mut deleted_files = Vec::new();
if let Ok(entries) = fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if filename.starts_with(&format!("{}-", video_id))
&& fs::remove_file(&path).is_ok()
{
deleted_files.push(path.display().to_string());
}
}
}
if deleted_files.is_empty() {
let text = format!("⚠️ No transcripts found for video ID: {}", video_id);
Ok(CallToolResult::success(vec![Content::text(text)]))
} else {
let text = format!(
"🗑️ Deleted {} file(s) for video ID '{}':\n\n{}",
deleted_files.len(),
video_id,
deleted_files
.iter()
.map(|f| format!("- {}", f))
.collect::<Vec<_>>()
.join("\n")
);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
}
"cleanup_old_transcripts" => {
use std::fs;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
let args = request.arguments.as_ref().ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing arguments".to_string(),
None,
)
})?;
let days = args.get("days").and_then(|v| v.as_u64()).ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing or invalid 'days' parameter".to_string(),
None,
)
})?;
let output_dir = args
.get("output_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(get_default_output_dir);
if !output_dir.exists() {
let text = "📂 No transcripts directory found.".to_string();
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
let cutoff_time = SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60);
let mut deleted_files = Vec::new();
if let Ok(entries) = fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Ok(metadata) = fs::metadata(&path)
&& let Ok(modified) = metadata.modified()
&& modified < cutoff_time
&& fs::remove_file(&path).is_ok()
{
deleted_files.push(path.display().to_string());
}
}
}
if deleted_files.is_empty() {
let text = format!("✅ No transcripts older than {} days found.", days);
Ok(CallToolResult::success(vec![Content::text(text)]))
} else {
let text = format!(
"🗑️ Deleted {} file(s) older than {} days:\n\n{}",
deleted_files.len(),
days,
deleted_files
.iter()
.map(|f| format!("- {}", f))
.collect::<Vec<_>>()
.join("\n")
);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
}
"delete_all_transcripts" => {
use std::fs;
use std::path::PathBuf;
let args = request.arguments.as_ref().ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Missing arguments".to_string(),
None,
)
})?;
let confirm = args
.get("confirm")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if !confirm {
let text = "⚠️ Deletion not confirmed. Set 'confirm' to true to delete all transcripts.".to_string();
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
let output_dir = args
.get("output_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(get_default_output_dir);
if !output_dir.exists() {
let text = "📂 No transcripts directory found.".to_string();
return Ok(CallToolResult::success(vec![Content::text(text)]));
}
let mut deleted_count = 0;
if let Ok(entries) = fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && fs::remove_file(&path).is_ok() {
deleted_count += 1;
}
}
}
if deleted_count == 0 {
let text = "📂 No transcripts found to delete.".to_string();
Ok(CallToolResult::success(vec![Content::text(text)]))
} else {
let text = format!(
"🗑️ Deleted ALL transcripts: {} file(s) removed from {}",
deleted_count,
output_dir.display()
);
Ok(CallToolResult::success(vec![Content::text(text)]))
}
}
_ => Err(ErrorData::new(
ErrorCode::METHOD_NOT_FOUND,
format!("Unknown tool: {}", request.name),
None,
)),
}
}
}
fn format_timestamp(timestamp: u64) -> String {
use chrono::{DateTime, TimeZone, Utc};
let dt: DateTime<Utc> = Utc.timestamp_opt(timestamp as i64, 0).unwrap();
dt.format("%Y-%m-%d").to_string()
}