mcplint 0.4.0

MCP Server Testing, Fuzzing, and Security Scanning Platform
Documentation
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
//! Streaming Response Support
//!
//! Provides streaming capabilities for AI responses, allowing
//! real-time display of explanations as they are generated.

use std::pin::Pin;

use futures::Stream;
use tokio::sync::mpsc;

/// A chunk of streamed response content
#[derive(Debug, Clone)]
pub enum StreamChunk {
    /// Text content being streamed
    Text(String),
    /// Partial JSON being accumulated
    PartialJson(String),
    /// Token usage update
    TokenUpdate { input: u32, output: u32 },
    /// Stream completed successfully
    Done,
    /// Error occurred during streaming
    Error(String),
}

impl StreamChunk {
    /// Create a text chunk
    pub fn text(s: impl Into<String>) -> Self {
        StreamChunk::Text(s.into())
    }

    /// Create an error chunk
    pub fn error(s: impl Into<String>) -> Self {
        StreamChunk::Error(s.into())
    }

    /// Check if this is a terminal chunk (Done or Error)
    pub fn is_terminal(&self) -> bool {
        matches!(self, StreamChunk::Done | StreamChunk::Error(_))
    }

    /// Get the text content if this is a Text chunk
    pub fn as_text(&self) -> Option<&str> {
        match self {
            StreamChunk::Text(s) => Some(s),
            _ => None,
        }
    }
}

/// Type alias for a boxed stream of chunks
pub type ChunkStream = Pin<Box<dyn Stream<Item = StreamChunk> + Send>>;

/// Sender for streaming chunks
pub type ChunkSender = mpsc::Sender<StreamChunk>;

/// Receiver for streaming chunks
pub type ChunkReceiver = mpsc::Receiver<StreamChunk>;

/// Create a channel for streaming chunks
pub fn stream_channel(buffer_size: usize) -> (ChunkSender, ChunkReceiver) {
    mpsc::channel(buffer_size)
}

/// Accumulator for building complete response from stream
#[derive(Debug, Default)]
pub struct StreamAccumulator {
    /// Accumulated text content
    pub content: String,
    /// Total input tokens
    pub input_tokens: u32,
    /// Total output tokens
    pub output_tokens: u32,
    /// Whether the stream completed successfully
    pub completed: bool,
    /// Error message if stream failed
    pub error: Option<String>,
}

impl StreamAccumulator {
    /// Create a new accumulator
    pub fn new() -> Self {
        Self::default()
    }

    /// Process a chunk and update state
    pub fn process(&mut self, chunk: StreamChunk) {
        match chunk {
            StreamChunk::Text(text) => {
                self.content.push_str(&text);
            }
            StreamChunk::PartialJson(json) => {
                self.content = json;
            }
            StreamChunk::TokenUpdate { input, output } => {
                self.input_tokens = input;
                self.output_tokens = output;
            }
            StreamChunk::Done => {
                self.completed = true;
            }
            StreamChunk::Error(msg) => {
                self.error = Some(msg);
            }
        }
    }

    /// Get total tokens used
    pub fn total_tokens(&self) -> u32 {
        self.input_tokens + self.output_tokens
    }

    /// Check if there was an error
    pub fn has_error(&self) -> bool {
        self.error.is_some()
    }
}

/// Callback for handling stream events
pub trait StreamCallback: Send + Sync {
    /// Called when new text is received
    fn on_text(&mut self, text: &str);

    /// Called when token count is updated
    fn on_tokens(&mut self, _input: u32, _output: u32) {}

    /// Called when stream completes
    fn on_done(&mut self) {}

    /// Called when an error occurs
    fn on_error(&mut self, error: &str);
}

/// A simple callback that prints to stdout
pub struct PrintCallback {
    /// Whether to print immediately (no buffering)
    pub immediate: bool,
}

impl PrintCallback {
    pub fn new(immediate: bool) -> Self {
        Self { immediate }
    }
}

impl StreamCallback for PrintCallback {
    fn on_text(&mut self, text: &str) {
        if self.immediate {
            print!("{}", text);
            use std::io::Write;
            let _ = std::io::stdout().flush();
        }
    }

    fn on_done(&mut self) {
        if self.immediate {
            println!();
        }
    }

    fn on_error(&mut self, error: &str) {
        eprintln!("\nError: {}", error);
    }
}

/// A callback that collects all text into a string
pub struct CollectCallback {
    content: String,
}

impl CollectCallback {
    pub fn new() -> Self {
        Self {
            content: String::new(),
        }
    }

    pub fn into_content(self) -> String {
        self.content
    }
}

impl Default for CollectCallback {
    fn default() -> Self {
        Self::new()
    }
}

impl StreamCallback for CollectCallback {
    fn on_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    fn on_error(&mut self, _error: &str) {}
}

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

    #[test]
    fn stream_chunk_creation() {
        let text = StreamChunk::text("hello");
        assert!(matches!(text, StreamChunk::Text(_)));
        assert_eq!(text.as_text(), Some("hello"));

        let error = StreamChunk::error("failed");
        assert!(error.is_terminal());
    }

    #[test]
    fn accumulator_processes_chunks() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("Hello ".to_string()));
        acc.process(StreamChunk::Text("world".to_string()));
        acc.process(StreamChunk::TokenUpdate {
            input: 10,
            output: 20,
        });
        acc.process(StreamChunk::Done);

        assert_eq!(acc.content, "Hello world");
        assert_eq!(acc.total_tokens(), 30);
        assert!(acc.completed);
        assert!(!acc.has_error());
    }

    #[test]
    fn accumulator_handles_error() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("partial".to_string()));
        acc.process(StreamChunk::Error("connection lost".to_string()));

        assert_eq!(acc.content, "partial");
        assert!(acc.has_error());
        assert_eq!(acc.error, Some("connection lost".to_string()));
    }

    #[test]
    fn collect_callback() {
        let mut callback = CollectCallback::new();

        callback.on_text("Hello ");
        callback.on_text("world");
        callback.on_done();

        assert_eq!(callback.into_content(), "Hello world");
    }

    #[test]
    fn stream_chunk_is_terminal() {
        let text = StreamChunk::Text("content".to_string());
        assert!(!text.is_terminal());

        let partial = StreamChunk::PartialJson("{}".to_string());
        assert!(!partial.is_terminal());

        let token_update = StreamChunk::TokenUpdate {
            input: 5,
            output: 10,
        };
        assert!(!token_update.is_terminal());

        let done = StreamChunk::Done;
        assert!(done.is_terminal());

        let error = StreamChunk::Error("fail".to_string());
        assert!(error.is_terminal());
    }

    #[test]
    fn stream_chunk_as_text() {
        let text = StreamChunk::Text("hello".to_string());
        assert_eq!(text.as_text(), Some("hello"));

        let partial = StreamChunk::PartialJson("{}".to_string());
        assert_eq!(partial.as_text(), None);

        let token_update = StreamChunk::TokenUpdate {
            input: 5,
            output: 10,
        };
        assert_eq!(token_update.as_text(), None);

        let done = StreamChunk::Done;
        assert_eq!(done.as_text(), None);

        let error = StreamChunk::Error("fail".to_string());
        assert_eq!(error.as_text(), None);
    }

    #[test]
    fn stream_channel_creation() {
        let (sender, mut receiver) = stream_channel(10);
        assert!(sender.try_send(StreamChunk::Done).is_ok());
        assert!(receiver.try_recv().is_ok());
    }

    #[test]
    fn accumulator_partial_json() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::PartialJson(r#"{"key":"#.to_string()));
        assert_eq!(acc.content, r#"{"key":"#);

        // PartialJson replaces content, not appends
        acc.process(StreamChunk::PartialJson(r#"{"key":"value"}"#.to_string()));
        assert_eq!(acc.content, r#"{"key":"value"}"#);
    }

    #[test]
    fn accumulator_empty_chunks() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("".to_string()));
        assert_eq!(acc.content, "");

        acc.process(StreamChunk::Text("content".to_string()));
        acc.process(StreamChunk::Text("".to_string()));
        assert_eq!(acc.content, "content");
    }

    #[test]
    fn accumulator_large_chunks() {
        let mut acc = StreamAccumulator::new();

        let large_text = "x".repeat(10_000);
        acc.process(StreamChunk::Text(large_text.clone()));
        assert_eq!(acc.content.len(), 10_000);
        assert_eq!(acc.content, large_text);
    }

    #[test]
    fn accumulator_multiple_token_updates() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::TokenUpdate {
            input: 10,
            output: 20,
        });
        assert_eq!(acc.input_tokens, 10);
        assert_eq!(acc.output_tokens, 20);
        assert_eq!(acc.total_tokens(), 30);

        // Later update replaces previous values
        acc.process(StreamChunk::TokenUpdate {
            input: 15,
            output: 25,
        });
        assert_eq!(acc.input_tokens, 15);
        assert_eq!(acc.output_tokens, 25);
        assert_eq!(acc.total_tokens(), 40);
    }

    #[test]
    fn accumulator_completion_without_error() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("content".to_string()));
        acc.process(StreamChunk::Done);

        assert!(acc.completed);
        assert!(!acc.has_error());
        assert_eq!(acc.error, None);
    }

    #[test]
    fn accumulator_error_after_content() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("partial content".to_string()));
        acc.process(StreamChunk::TokenUpdate {
            input: 5,
            output: 10,
        });
        acc.process(StreamChunk::Error("network error".to_string()));

        assert_eq!(acc.content, "partial content");
        assert_eq!(acc.input_tokens, 5);
        assert_eq!(acc.output_tokens, 10);
        assert!(acc.has_error());
        assert_eq!(acc.error, Some("network error".to_string()));
        assert!(!acc.completed);
    }

    #[test]
    fn accumulator_default_state() {
        let acc = StreamAccumulator::new();

        assert_eq!(acc.content, "");
        assert_eq!(acc.input_tokens, 0);
        assert_eq!(acc.output_tokens, 0);
        assert_eq!(acc.total_tokens(), 0);
        assert!(!acc.completed);
        assert!(!acc.has_error());
        assert_eq!(acc.error, None);
    }

    #[test]
    fn accumulator_mixed_chunk_sequence() {
        let mut acc = StreamAccumulator::new();

        acc.process(StreamChunk::Text("Start ".to_string()));
        acc.process(StreamChunk::TokenUpdate {
            input: 5,
            output: 0,
        });
        acc.process(StreamChunk::Text("middle ".to_string()));
        acc.process(StreamChunk::TokenUpdate {
            input: 5,
            output: 10,
        });
        acc.process(StreamChunk::Text("end".to_string()));
        acc.process(StreamChunk::Done);

        assert_eq!(acc.content, "Start middle end");
        assert_eq!(acc.input_tokens, 5);
        assert_eq!(acc.output_tokens, 10);
        assert_eq!(acc.total_tokens(), 15);
        assert!(acc.completed);
        assert!(!acc.has_error());
    }

    #[test]
    fn print_callback_creation() {
        let callback_immediate = PrintCallback::new(true);
        assert!(callback_immediate.immediate);

        let callback_buffered = PrintCallback::new(false);
        assert!(!callback_buffered.immediate);
    }

    #[test]
    fn print_callback_handles_text() {
        let mut callback = PrintCallback::new(false);
        // Should not panic when immediate is false
        callback.on_text("test text");
        callback.on_done();
        callback.on_error("error message");
    }

    #[test]
    fn collect_callback_default() {
        let callback = CollectCallback::default();
        assert_eq!(callback.content, "");
    }

    #[test]
    fn collect_callback_empty_text() {
        let mut callback = CollectCallback::new();
        callback.on_text("");
        callback.on_text("content");
        callback.on_text("");

        assert_eq!(callback.into_content(), "content");
    }

    #[test]
    fn collect_callback_ignores_errors() {
        let mut callback = CollectCallback::new();
        callback.on_text("before error");
        callback.on_error("something went wrong");
        callback.on_text(" after error");

        assert_eq!(callback.into_content(), "before error after error");
    }

    #[test]
    fn collect_callback_multiple_done() {
        let mut callback = CollectCallback::new();
        callback.on_text("text");
        callback.on_done();
        callback.on_done();
        callback.on_text(" more");

        assert_eq!(callback.into_content(), "text more");
    }

    #[test]
    fn collect_callback_large_content() {
        let mut callback = CollectCallback::new();
        let large_text = "x".repeat(10_000);
        callback.on_text(&large_text);

        assert_eq!(callback.into_content().len(), 10_000);
    }

    #[test]
    fn stream_chunk_text_from_string() {
        let chunk = StreamChunk::text(String::from("owned"));
        assert_eq!(chunk.as_text(), Some("owned"));
    }

    #[test]
    fn stream_chunk_text_from_str() {
        let chunk = StreamChunk::text("borrowed");
        assert_eq!(chunk.as_text(), Some("borrowed"));
    }

    #[test]
    fn stream_chunk_error_from_string() {
        let chunk = StreamChunk::error(String::from("owned error"));
        assert!(chunk.is_terminal());
        assert_eq!(chunk.as_text(), None);
    }

    #[test]
    fn stream_chunk_error_from_str() {
        let chunk = StreamChunk::error("borrowed error");
        assert!(chunk.is_terminal());
    }

    #[test]
    fn print_callback_on_tokens() {
        let mut callback = PrintCallback::new(true);
        // Default implementation does nothing, should not panic
        callback.on_tokens(10, 20);
    }

    #[test]
    fn collect_callback_on_tokens() {
        let mut callback = CollectCallback::new();
        // Default implementation does nothing, should not panic
        callback.on_tokens(10, 20);
        callback.on_text("text");
        assert_eq!(callback.into_content(), "text");
    }

    #[tokio::test]
    async fn stream_channel_buffer_overflow() {
        let (sender, mut receiver) = stream_channel(2);

        // Fill buffer
        sender
            .send(StreamChunk::Text("1".to_string()))
            .await
            .unwrap();
        sender
            .send(StreamChunk::Text("2".to_string()))
            .await
            .unwrap();

        // Receive one to make room
        assert!(receiver.recv().await.is_some());

        // Can send again
        sender.send(StreamChunk::Done).await.unwrap();
    }

    #[tokio::test]
    async fn stream_channel_sender_dropped() {
        let (sender, mut receiver) = stream_channel(10);

        sender
            .send(StreamChunk::Text("before drop".to_string()))
            .await
            .unwrap();
        drop(sender);

        // Can still receive sent message
        assert!(receiver.recv().await.is_some());
        // Next receive returns None because sender was dropped
        assert!(receiver.recv().await.is_none());
    }
}