serial-mcp 0.7.2

MCP server for serial port communication. 22 tools (list/open/read/write/subscribe/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/get_log/clear_log/export_log/reconnect/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
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
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! MCP server tool surface for serial communication.
//!
//! Each `#[tool]` method below corresponds to one MCP tool. Tools return
//! structured JSON via [`Json<T>`] so MCP clients can index fields directly
//! instead of parsing free-form text.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use base64::Engine as _;
use rmcp::{
    handler::server::wrapper::Parameters, model::*, prompt, prompt_handler, prompt_router,
    service::RequestContext, tool, tool_handler, tool_router, ErrorData as McpError, Json,
    RoleServer, ServerHandler,
};

use tracing::{debug, info};

use crate::buffer_budget::BufferBudget;
use crate::rx_session::RxSessionManager;
use crate::security::SecurityManager;
use crate::serial::{ConnectionManager, PortInfo};
use crate::tx_session::TxSessionManager;

use crate::prompts::types::*;
use crate::prompts::{diagnose, interactive};
use crate::tools::types::*;
use crate::tools::{control_ops, io_ops, port_ops, stream_ops};

/// Helper for cursor-based pagination over a vector of items.
///
/// `cursor` is interpreted as a base64-encoded UTF-8 string containing an offset
/// number (e.g. "0", "1").  Returns the sliced items and an optional next
/// cursor when more items remain.
fn paginate<T: Clone>(
    all: &[T],
    cursor: Option<String>,
    page_size: usize,
) -> (Vec<T>, Option<String>) {
    let offset = cursor
        .as_deref()
        .and_then(|c| base64::engine::general_purpose::STANDARD.decode(c).ok())
        .and_then(|b| String::from_utf8(b).ok())
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(0)
        .min(all.len());

    let end = offset.saturating_add(page_size).min(all.len());
    let items = all[offset..end].to_vec();

    let next_cursor = if end < all.len() {
        let next = base64::engine::general_purpose::STANDARD.encode(end.to_string().as_bytes());
        Some(next)
    } else {
        None
    };

    (items, next_cursor)
}

// ---- Handler ---------------------------------------------------------------

pub type StreamRegistry = Arc<tokio::sync::Mutex<HashMap<String, stream_ops::StreamHandle>>>;

#[derive(Clone)]
pub struct SerialHandler {
    pub(crate) connections: Arc<ConnectionManager>,
    streams: StreamRegistry,
    security: SecurityManager,
    subscribers: Arc<tokio::sync::Mutex<HashMap<String, usize>>>,
    rx_sessions: Arc<RxSessionManager>,
    tx_sessions: Arc<TxSessionManager>,
    budget: Arc<dyn BufferBudget>,
    profiles: Arc<tokio::sync::RwLock<Vec<crate::profiles::Profile>>>,
    profiles_path: PathBuf,
}

/// Injectable configuration for [`SerialHandler`].
///
/// Every field has a sensible default produced by [`SerialHandlerOptions::default`].
/// Use [`SerialHandler::builder`] to override individual fields, then `.build()`.
#[derive(Clone)]
pub struct SerialHandlerOptions {
    pub connections: Arc<ConnectionManager>,
    pub streams: StreamRegistry,
    pub security: SecurityManager,
    pub budget: Arc<dyn BufferBudget>,
    // profiles / profiles_path are intentionally NOT here: they are applied
    // post-build via `with_profiles`, matching today's flow.
}

impl Default for SerialHandlerOptions {
    fn default() -> Self {
        use crate::limits::{DEFAULT_MAX_PROGRAM_BUFFERED_BYTES, DEFAULT_MAX_TOOL_BUFFERED_BYTES};
        Self {
            connections: Arc::new(ConnectionManager::new()),
            streams: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
            security: SecurityManager::from_patterns::<[&str; 0]>([]),
            budget: Arc::new(crate::buffer_budget::AtomicBudget::new(
                DEFAULT_MAX_PROGRAM_BUFFERED_BYTES,
                DEFAULT_MAX_TOOL_BUFFERED_BYTES,
            )),
        }
    }
}

/// Builder for [`SerialHandler`]. Start with [`SerialHandler::builder`].
#[derive(Default)]
pub struct SerialHandlerBuilder {
    options: SerialHandlerOptions,
}

impl SerialHandlerBuilder {
    pub fn connections(mut self, connections: Arc<ConnectionManager>) -> Self {
        self.options.connections = connections;
        self
    }
    pub fn streams(mut self, streams: StreamRegistry) -> Self {
        self.options.streams = streams;
        self
    }
    pub fn security(mut self, security: SecurityManager) -> Self {
        self.options.security = security;
        self
    }
    pub fn budget(mut self, budget: Arc<dyn BufferBudget>) -> Self {
        self.options.budget = budget;
        self
    }

    /// Consume the builder and produce a [`SerialHandler`].
    ///
    /// Spawns the reconnect supervisor exactly once.
    pub fn build(self) -> SerialHandler {
        let SerialHandlerOptions {
            connections,
            streams,
            security,
            budget,
        } = self.options;
        let handler = SerialHandler {
            connections,
            streams,
            security,
            subscribers: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
            rx_sessions: Arc::new(RxSessionManager::new()),
            tx_sessions: Arc::new(TxSessionManager::new()),
            budget,
            profiles: Arc::new(tokio::sync::RwLock::new(Vec::new())),
            profiles_path: crate::profiles::default_profiles_path(),
        };
        handler.spawn_reconnect_supervisor();
        handler
    }
}

#[tool_router]
impl SerialHandler {
    /// Entry point for the builder.
    pub fn builder() -> SerialHandlerBuilder {
        SerialHandlerBuilder::default()
    }

    /// Default handler: default connections, empty allowlist, default budget,
    /// profiles loaded from the default path, reconnect supervisor spawned.
    pub fn new() -> Self {
        let path = crate::profiles::default_profiles_path();
        let profiles = crate::profiles::load_profiles(&path);
        Self::builder().build().with_profiles(path, profiles)
    }

    /// Replace the loaded profiles with the given vector and path.
    /// (Unchanged from today — kept as a post-build setter.)
    pub fn with_profiles(mut self, path: PathBuf, profiles: Vec<crate::profiles::Profile>) -> Self {
        self.profiles = Arc::new(tokio::sync::RwLock::new(profiles));
        self.profiles_path = path;
        self
    }

    /// Start the background reconnect supervisor task.
    /// Requires a Tokio runtime to be active (panics otherwise).
    pub fn spawn_reconnect_supervisor(&self) {
        let connections = Arc::clone(&self.connections);
        let rx_sessions = Arc::clone(&self.rx_sessions);
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                let all = connections.list_all().await;
                for (id, conn) in all {
                    let state = conn.state();
                    if state == crate::serial::ConnectionState::Disconnected {
                        let policy = conn.reconnect_policy.lock().expect("poisoned").clone();
                        if policy.enabled {
                            connections
                                .start_reconnect(&id, Arc::clone(&rx_sessions))
                                .await;
                        }
                    }
                }
            }
        });
    }

    #[tool(
        description = "List all available serial ports on the system",
        title = "List Serial Ports",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    async fn list_ports(&self) -> Result<Json<ListPortsResult>, String> {
        port_ops::list_ports().await
    }

    #[tool(
        description = "List all open serial connections held by this server",
        title = "List Open Connections",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    async fn list_connections(&self) -> Result<Json<ListConnectionsResult>, String> {
        port_ops::list_connections(&self.connections).await
    }

    #[tool(
        description = "Open a serial port connection with specified configuration",
        title = "Open Serial Port",
        annotations(destructive_hint = false, open_world_hint = false)
    )]
    async fn open(
        &self,
        Parameters(args): Parameters<OpenArgs>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<Json<OpenResult>, String> {
        let result = port_ops::open(&self.connections, &self.security, args).await?;
        let connection_id = result.0.connection_id.clone();
        self.notify_resource_changed(&connection_id, &ctx).await;
        Ok(result)
    }

    #[tool(
        description = "Close an open serial port connection",
        title = "Close Serial Port",
        annotations(destructive_hint = false, open_world_hint = false)
    )]
    async fn close(
        &self,
        Parameters(args): Parameters<CloseArgs>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<Json<CloseResult>, String> {
        let connection_id = args.connection_id.clone();
        // Cancel any running reconnect task so it doesn't try to reopen.
        self.connections.cancel_reconnect(&connection_id).await;
        let result = port_ops::close(&self.connections, args).await?;
        // Shut down RX session (pump + consumers) for this connection.
        // This closes the pump channel, causing the subscribe task's
        // event_rx.recv() to return None, which exits the loop and
        // triggers flush_partial for any buffered partial frame.
        self.rx_sessions.remove(&connection_id).await;
        // Shut down TX session (worker) for this connection.
        self.tx_sessions.remove(&connection_id).await;
        // Wait for the subscribe task to finish naturally (flush partial,
        // emit stop notification) before cleaning up.
        if let Some(handle) = self.streams.lock().await.remove(&connection_id) {
            handle.join_without_abort().await;
        }
        self.notify_resource_changed(&connection_id, &ctx).await;
        Ok(result)
    }

    #[tool(
        description = "Write data to a serial port connection. Use tx_framing to apply frame boundaries (line terminator, delimiter, length prefix, SLIP, COBS, or start/end markers) around the decoded payload. Use protocol to select a built-in preset (at_command, slip, json_lines, cobs, ndjson, nmea0183, modbus_ascii) that fills in framing defaults. Explicit tx_framing wins over the preset. When tx_framing is used, decoded_bytes reports the payload length before framing, and bytes_written reports the total framed bytes sent.",
        title = "Write Serial Data",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn write(
        &self,
        Parameters(args): Parameters<WriteArgs>,
    ) -> Result<Json<WriteResult>, String> {
        io_ops::write(&self.connections, &self.tx_sessions, args).await
    }

    #[tool(
        description = "Read data from a serial port connection. Returns only future bytes — data received after the call starts, not previously buffered data. With no options, reads available bytes with timeout and burst-settle. With match, accumulates until a pattern is found. With rx_framing, splits the byte stream into structured frames (line, delimiter, length-prefixed, SLIP, COBS, start/end marker). With rx_parser, interprets frame content (AT commands, JSON lines, shell prompts). rx_parser is a sibling to rx_framing. Use protocol to select a built-in preset (at_command, slip, json_lines, cobs, ndjson, nmea0183, modbus_ascii) that fills in rx_framing and rx_parser defaults; explicit fields win. Match and rx_framing can be combined. A malformed SLIP escape sequence or COBS code byte surfaces as a framing_error. Set no_new_rx_timeout_ms to stop when no new bytes arrive within the specified silence window.",
        title = "Read Serial Data",
        annotations(read_only_hint = true, open_world_hint = false),
        execution(task_support = "optional")
    )]
    async fn read(
        &self,
        meta: Meta,
        ct: tokio_util::sync::CancellationToken,
        peer: rmcp::Peer<RoleServer>,
        Parameters(args): Parameters<ReadArgs>,
    ) -> Result<Json<ReadResult>, String> {
        io_ops::read(
            &self.connections,
            &self.rx_sessions,
            &self.budget,
            meta,
            ct,
            peer,
            args,
        )
        .await
    }

    #[tool(
        description = "Discard buffered serial data. target=input clears OS read buffer (data the device sent that the app hasn't consumed); target=output clears the OS write queue; target=both clears both.",
        title = "Flush Serial Buffers",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn flush(
        &self,
        Parameters(args): Parameters<FlushArgs>,
    ) -> Result<Json<FlushResult>, String> {
        io_ops::flush(&self.connections, &self.tx_sessions, args).await
    }

    #[tool(
        description = "Set the DTR and RTS modem-control lines. Common patterns: pulse DTR low for Arduino auto-reset; hold both low to enter ESP32 bootloader.",
        title = "Set DTR/RTS",
        annotations(
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn set_dtr_rts(
        &self,
        Parameters(args): Parameters<SetDtrRtsArgs>,
    ) -> Result<Json<SetDtrRtsResult>, String> {
        control_ops::set_dtr_rts(&self.connections, args).await
    }

    #[tool(
        description = "Change hardware/software flow control mode on an open connection. Use flow_control='none' to ignore RTS/CTS for this session.",
        title = "Set Flow Control",
        annotations(
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn set_flow_control(
        &self,
        Parameters(args): Parameters<SetFlowControlArgs>,
    ) -> Result<Json<SetFlowControlResult>, String> {
        control_ops::set_flow_control(&self.connections, args).await
    }

    #[tool(
        description = "Assert a BREAK condition on the TX line for duration_ms milliseconds (default 250ms), then release it. Used to signal attention on some legacy serial protocols.",
        title = "Send BREAK",
        annotations(destructive_hint = true, open_world_hint = false),
        execution(task_support = "optional")
    )]
    async fn send_break(
        &self,
        meta: Meta,
        ct: tokio_util::sync::CancellationToken,
        peer: rmcp::Peer<RoleServer>,
        Parameters(args): Parameters<SendBreakArgs>,
    ) -> Result<Json<SendBreakResult>, String> {
        control_ops::send_break(&self.connections, meta, ct, peer, args).await
    }

    #[tool(
        description = "Subscribe to a connection: starts a background stream that forwards received bytes as MCP `notifications/message` events with logger=\"serial:<connection_id>\". When timeout_ms is set, the stream auto-stops after that duration. When omitted, the stream runs until unsubscribe, connection close, or error. Set no_new_rx_timeout_ms to stop after a period of silence. With match, detects the first byte pattern. With rx_framing, emits per-frame notifications with structured data (line, delimiter, length-prefixed, SLIP, start/end marker). With rx_parser, interprets frame content (AT commands, JSON lines, shell prompts) — rx_parser is a sibling to rx_framing. A malformed SLIP escape sequence emits a final notification with stop_reason=framing_error and an error field. Replaces any prior subscription on the same connection. A final notification with stop_reason, truncated, bytes_observed, bytes_returned, elapsed_ms is emitted when the stream ends.",
        title = "Subscribe to RX Stream",
        annotations(
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        ),
        execution(task_support = "optional")
    )]
    async fn subscribe(
        &self,
        meta: Meta,
        ct: tokio_util::sync::CancellationToken,
        peer: rmcp::Peer<RoleServer>,
        Parameters(args): Parameters<SubscribeArgs>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<Json<SubscribeResult>, String> {
        stream_ops::subscribe(
            &self.connections,
            &self.rx_sessions,
            &self.budget,
            &self.streams,
            args,
            meta,
            ct,
            peer,
            ctx,
        )
        .await
    }

    #[tool(
        description = "Cancel an active RX subscription on a connection. No-op if no subscription exists.",
        title = "Unsubscribe from RX Stream",
        annotations(
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn unsubscribe(
        &self,
        Parameters(args): Parameters<UnsubscribeArgs>,
    ) -> Result<Json<UnsubscribeResult>, String> {
        stream_ops::unsubscribe(&self.connections, &self.rx_sessions, &self.streams, args).await
    }

    #[tool(
        description = "Get the current status and configuration of an open serial connection",
        title = "Get Connection Status",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    async fn get_status(
        &self,
        Parameters(args): Parameters<GetStatusArgs>,
    ) -> Result<Json<GetStatusResult>, String> {
        port_ops::get_status(&self.connections, args).await
    }

    #[tool(
        description = "Reconfigure serial parameters (baud rate, data bits, stop bits, parity, flow control) on a live connection without closing and reopening it. Omitted parameters are left unchanged.",
        title = "Reconfigure Serial Port",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn reconfigure(
        &self,
        Parameters(args): Parameters<ReconfigureArgs>,
    ) -> Result<Json<ReconfigureResult>, String> {
        port_ops::reconfigure(&self.connections, args).await
    }

    #[tool(
        description = "List all configured serial device profiles. Profiles define selector rules and default settings so agents can open devices by name instead of fragile port paths.",
        title = "List Profiles",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    async fn list_profiles(&self) -> Result<Json<ListProfilesResult>, String> {
        let profiles = self.profiles.read().await;
        port_ops::list_profiles(&profiles)
    }

    #[tool(
        description = "Open a serial port by profile name rather than raw port path. The server matches the profile's selector against live ports and applies the profile's default configuration.",
        title = "Open by Profile",
        annotations(destructive_hint = false, open_world_hint = false)
    )]
    async fn open_profile(
        &self,
        Parameters(args): Parameters<OpenProfileArgs>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<Json<OpenResult>, String> {
        let profiles = self.profiles.read().await;
        let result =
            port_ops::open_profile(&self.connections, &self.security, &profiles, args).await?;
        let connection_id = result.0.connection_id.clone();
        self.notify_resource_changed(&connection_id, &ctx).await;
        Ok(result)
    }

    #[tool(
        description = "Save a new profile by snapshotting an open connection's port identity and current serial configuration. Use this after opening a device to create a reusable profile that can be selected by name in later sessions.",
        title = "Save Profile",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn save_profile(
        &self,
        Parameters(args): Parameters<SaveProfileArgs>,
    ) -> Result<Json<SaveProfileResult>, String> {
        port_ops::save_profile(&self.connections, &self.profiles, &self.profiles_path, args).await
    }

    #[tool(
        description = "Delete a profile by name, removing it from the profiles configuration file.",
        title = "Delete Profile",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn delete_profile(
        &self,
        Parameters(args): Parameters<DeleteProfileArgs>,
    ) -> Result<Json<DeleteProfileResult>, String> {
        port_ops::delete_profile(&self.profiles, &self.profiles_path, args).await
    }

    #[tool(
        description = "Retrieve the event log for an open serial connection. Returns timestamped JSONL entries for RX data, TX data, matches, errors, and lifecycle events. Use since_ms to filter by time and limit to cap the number of entries returned.",
        title = "Get Log",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    async fn get_log(
        &self,
        Parameters(args): Parameters<GetLogArgs>,
    ) -> Result<Json<GetLogResult>, String> {
        port_ops::get_log(&self.connections, args).await
    }

    #[tool(
        description = "Clear the event log buffer for a connection. Resets the log to empty.",
        title = "Clear Log",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn clear_log(
        &self,
        Parameters(args): Parameters<ClearLogArgs>,
    ) -> Result<Json<ClearLogResult>, String> {
        port_ops::clear_log(&self.connections, args).await
    }

    #[tool(
        description = "Export the event log for a connection to a JSONL file on disk. Each line is a JSON object representing one log entry.",
        title = "Export Log",
        annotations(destructive_hint = true, open_world_hint = false)
    )]
    async fn export_log(
        &self,
        Parameters(args): Parameters<ExportLogArgs>,
    ) -> Result<Json<ExportLogResult>, String> {
        port_ops::export_log(&self.connections, args).await
    }

    #[tool(
        description = "Attempt to reconnect a disconnected serial connection. Rebuilds the port stream from the original configuration, preserving connection_id, counters, and log buffer. Succeeds immediately if already connected.",
        title = "Reconnect",
        annotations(destructive_hint = false, open_world_hint = false)
    )]
    async fn reconnect(
        &self,
        Parameters(args): Parameters<ReconnectArgs>,
    ) -> Result<Json<ReconnectResult>, String> {
        port_ops::reconnect(&self.connections, args).await
    }
}

// ---- Tool helpers (extracted to src/tools/helpers.rs) -----------------------

// ---- ServerHandler boilerplate ----------------------------------------------

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

// ---- Prompt templates ------------------------------------------------------

// ---- Completion helper ------------------------------------------------------

impl SerialHandler {
    /// Generate completion suggestions for tool/resource arguments.
    async fn get_completions(&self, r#ref: &Reference, argument: &ArgumentInfo) -> Vec<String> {
        match r#ref {
            Reference::Resource(resource_ref) => {
                if resource_ref.uri == URI_PORTS && argument.name == "port" {
                    match PortInfo::list_available() {
                        Ok(ports) => ports.into_iter().map(|p| p.name).collect(),
                        Err(_) => vec![],
                    }
                } else {
                    vec![]
                }
            }
            Reference::Prompt(prompt_ref) => {
                if prompt_ref.name == "diagnose_port" && argument.name == "port" {
                    match PortInfo::list_available() {
                        Ok(ports) => ports.into_iter().map(|p| p.name).collect(),
                        Err(_) => vec![],
                    }
                } else {
                    vec![]
                }
            }
        }
    }

    async fn notify_resource_changed(&self, connection_id: &str, ctx: &RequestContext<RoleServer>) {
        if let Err(e) = ctx.peer.notify_resource_list_changed().await {
            debug!("Failed to notify resource list changed: {e}");
        }
        let conn_uri = format!("{URI_CONNECTION_PREFIX}{connection_id}");
        let subs = self.subscribers.lock().await;
        let should_notify = subs.get(&conn_uri).is_some_and(|count| *count > 0);
        drop(subs);
        if should_notify {
            if let Err(e) = ctx
                .peer
                .notify_resource_updated(rmcp::model::ResourceUpdatedNotificationParam::new(
                    conn_uri,
                ))
                .await
            {
                debug!("Failed to notify resource updated: {e}");
            }
        }
    }
}

#[prompt_router]
impl SerialHandler {
    /// Walk through diagnosing an unknown serial port: try common baud
    /// rates, send a benign probe, observe response, narrow down config.
    #[prompt(
        name = "diagnose_port",
        description = "Step-by-step plan to identify an unknown serial device on a given port"
    )]
    async fn diagnose_port_prompt(
        &self,
        Parameters(args): Parameters<DiagnosePortArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<GetPromptResult, McpError> {
        Ok(diagnose::build_diagnose_prompt(args))
    }

    /// Guide an interactive serial REPL session against an already-open
    /// connection, using `write` / `wait_for` to drive a command/response
    /// loop.
    #[prompt(
        name = "interactive_terminal",
        description = "Run a REPL-style command/response session over an open serial connection"
    )]
    async fn interactive_terminal_prompt(
        &self,
        Parameters(args): Parameters<InteractiveTerminalArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<GetPromptResult, McpError> {
        Ok(interactive::build_interactive_prompt(args))
    }
}

#[tool_handler]
#[prompt_handler]
impl ServerHandler for SerialHandler {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_tool_list_changed()
                .enable_resources()
                .enable_resources_list_changed()
                .enable_resources_subscribe()
                .enable_prompts()
                .enable_logging()
                .enable_completions()
                .build(),
        )
        .with_server_info(Implementation::new(
            env!("CARGO_PKG_NAME"),
            env!("CARGO_PKG_VERSION"),
        ))
        .with_protocol_version(ProtocolVersion::V_2025_11_25)
        .with_instructions(
            "A serial port communication MCP server. Use list_ports to discover available serial ports, then open connections to communicate with serial devices. Resources: serial://ports, serial://connections, serial://connections/{id}. Prompts: diagnose_port, interactive_terminal. Subscribe to live RX bytes with the subscribe tool; the server emits notifications/message events with logger=\"serial:<connection_id>\"."
                .to_string(),
        )
    }

    async fn initialize(
        &self,
        _req: InitializeRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, McpError> {
        info!("Serial MCP server initialized");
        Ok(self.get_info())
    }

    async fn list_resources(
        &self,
        request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, McpError> {
        const PAGE_SIZE: usize = 100;

        let port_count = PortInfo::list_available()
            .map(|v| v.len() as u32)
            .unwrap_or(0);
        let conn_count = self.connections.count().await as u32;

        let all = vec![
            RawResource::new(URI_PORTS, "Available serial ports")
                .with_description("JSON list of serial ports the OS currently exposes.".to_string())
                .with_mime_type("application/json".to_string())
                .with_size(port_count)
                .with_priority(0.9)
                .with_audience(vec![Role::User, Role::Assistant]),
            RawResource::new(URI_CONNECTIONS, "Open serial connections")
                .with_description(
                    "JSON list of serial connections currently held open by this server."
                        .to_string(),
                )
                .with_mime_type("application/json".to_string())
                .with_size(conn_count)
                .with_priority(0.8)
                .with_audience(vec![Role::User, Role::Assistant]),
        ];
        let (resources, next_cursor) = paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
        Ok(ListResourcesResult {
            resources,
            next_cursor,
            meta: None,
        })
    }

    async fn list_resource_templates(
        &self,
        request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, McpError> {
        const PAGE_SIZE: usize = 100;
        let all = vec![
            RawResourceTemplate::new(
                URI_CONNECTION_TEMPLATE,
                "Open serial connection by id",
            )
            .with_description(
                "Per-connection state. Substitute {id} with a connection_id returned by the open tool."
                    .to_string(),
            )
            .with_mime_type("application/json".to_string())
            .with_priority(0.7)
            .with_audience(vec![Role::User, Role::Assistant]),
            RawResourceTemplate::new(
                URI_CONNECTION_RAW_TEMPLATE,
                "Raw binary data from a serial connection",
            )
            .with_description(
                "Base64-encoded bytes read from the connection. This resource consumes up to 256 pending bytes; substitute {id} with a connection_id."
                    .to_string(),
            )
            .with_mime_type("application/octet-stream".to_string())
            .with_priority(0.6)
            .with_audience(vec![Role::User, Role::Assistant]),
            RawResourceTemplate::new(
                URI_CONNECTION_LOG_TEMPLATE,
                "Event log for a serial connection",
            )
            .with_description(
                "JSONL event log for the connection. Substitute {id} with a connection_id. Each line is a JSON object with timestamp, direction, and event fields."
                    .to_string(),
            )
            .with_mime_type("application/x-ndjson".to_string())
            .with_priority(0.5)
            .with_audience(vec![Role::User, Role::Assistant]),
        ];
        let (resource_templates, next_cursor) =
            paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
        Ok(ListResourceTemplatesResult {
            resource_templates,
            next_cursor,
            meta: None,
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResult, McpError> {
        let uri = request.uri;
        match parse_resource_uri(&uri) {
            ResourceUriKind::Ports => {
                let ports = PortInfo::list_available().map_err(|e| {
                    McpError::internal_error(format!("Failed to list ports: {e}"), None)
                })?;
                let body = serde_json::to_string_pretty(&ListPortsResult {
                    count: ports.len(),
                    ports,
                })
                .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
                Ok(ReadResourceResult::new(vec![ResourceContents::text(
                    body, uri,
                )
                .with_mime_type("application/json")]))
            }
            ResourceUriKind::ConnectionsList => {
                let summaries = self.connections.list_open().await;
                let body = serde_json::to_string_pretty(&ConnectionsResource {
                    count: summaries.len(),
                    connections: summaries,
                })
                .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
                Ok(ReadResourceResult::new(vec![ResourceContents::text(
                    body, uri,
                )
                .with_mime_type("application/json")]))
            }
            ResourceUriKind::ConnectionDetail(id) => {
                let conn = self.connections.get(&id).await.map_err(|_| {
                    McpError::resource_not_found(
                        "connection_not_found",
                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
                    )
                })?;

                let body = serde_json::to_string_pretty(&conn.summary())
                    .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
                Ok(ReadResourceResult::new(vec![ResourceContents::text(
                    body, uri,
                )
                .with_mime_type("application/json")]))
            }
            ResourceUriKind::ConnectionDetailRaw(id) => {
                let conn = self.connections.get(&id).await.map_err(|_| {
                    McpError::resource_not_found(
                        "connection_not_found",
                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
                    )
                })?;
                let raw_bytes = conn
                    .read_latest(256)
                    .await
                    .map_err(|e| McpError::internal_error(format!("Failed to read: {e}"), None))?;
                let b64 = base64::engine::general_purpose::STANDARD.encode(&raw_bytes);
                Ok(ReadResourceResult::new(vec![ResourceContents::blob(
                    b64, uri,
                )
                .with_mime_type("application/octet-stream")]))
            }
            ResourceUriKind::ConnectionLog(id) => {
                let conn = self.connections.get(&id).await.map_err(|_| {
                    McpError::resource_not_found(
                        "connection_not_found",
                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
                    )
                })?;
                let events = conn.log().snapshot();
                let mut body = String::new();
                for event in &events {
                    let line = serde_json::to_string(event)
                        .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
                    body.push_str(&line);
                    body.push('\n');
                }
                Ok(ReadResourceResult::new(vec![ResourceContents::text(
                    body, uri,
                )
                .with_mime_type("application/x-ndjson")]))
            }
            ResourceUriKind::Unknown => Err(McpError::resource_not_found(
                "resource_not_found",
                Some(serde_json::json!({ "uri": uri })),
            )),
        }
    }

    async fn complete(
        &self,
        request: CompleteRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CompleteResult, McpError> {
        let suggestions = self
            .get_completions(&request.r#ref, &request.argument)
            .await;
        let completion = CompletionInfo::with_all_values(suggestions)
            .map_err(|e| McpError::internal_error(format!("Completion error: {e}"), None))?;
        Ok(CompleteResult::new(completion))
    }

    async fn subscribe(
        &self,
        request: SubscribeRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<(), McpError> {
        let uri = request.uri;
        let mut subscribers = self.subscribers.lock().await;
        *subscribers.entry(uri.clone()).or_insert(0) += 1;
        debug!("Client subscribed to resource {}", uri);
        Ok(())
    }

    async fn unsubscribe(
        &self,
        request: UnsubscribeRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<(), McpError> {
        let uri = request.uri;
        let mut subscribers = self.subscribers.lock().await;
        if let Some(count) = subscribers.get_mut(&uri) {
            *count = count.saturating_sub(1);
            if *count == 0 {
                subscribers.remove(&uri);
            }
        }
        debug!("Client unsubscribed from resource {}", uri);
        Ok(())
    }
}

// ---- Resource URI handling --------------------------------------------------

use crate::resources::{
    parse_resource_uri, ConnectionsResource, ResourceUriKind, URI_CONNECTIONS,
    URI_CONNECTION_LOG_TEMPLATE, URI_CONNECTION_PREFIX, URI_CONNECTION_RAW_TEMPLATE,
    URI_CONNECTION_TEMPLATE, URI_PORTS,
};

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

    #[test]
    fn prompt_router_advertises_both_prompts() {
        let router = SerialHandler::prompt_router();
        assert!(router.has_route("diagnose_port"));
        assert!(router.has_route("interactive_terminal"));
        assert_eq!(router.list_all().len(), 2);
    }

    #[test]
    fn paginate_handles_offset_past_end_without_panic() {
        let items: Vec<i32> = vec![1, 2, 3, 4, 5];

        // Normal case: offset 0
        let (page, next) = paginate(&items, None, 2);
        assert_eq!(page, vec![1, 2]);
        assert!(next.is_some());

        // Offset at end of items
        let cursor = base64::engine::general_purpose::STANDARD.encode("5".as_bytes());
        let (page, next) = paginate(&items, Some(cursor), 2);
        assert_eq!(page, vec![] as Vec<i32>);
        assert!(next.is_none());

        // Offset past end (would have panicked before fix)
        let cursor = base64::engine::general_purpose::STANDARD.encode("999".as_bytes());
        let (page, next) = paginate(&items, Some(cursor), 2);
        assert_eq!(page, vec![] as Vec<i32>);
        assert!(next.is_none());

        // Offset at max usize (would have overflowed before fix)
        let cursor = base64::engine::general_purpose::STANDARD.encode(usize::MAX.to_string());
        let (page, _next) = paginate(&items, Some(cursor), usize::MAX);
        assert_eq!(page, vec![] as Vec<i32>);
    }

    use crate::buffer_budget::{AtomicBudget, BufferBudget};
    use crate::limits::{DEFAULT_MAX_PROGRAM_BUFFERED_BYTES, DEFAULT_MAX_TOOL_BUFFERED_BYTES};
    use crate::security::SecurityManager;

    /// Assert two `SerialHandler`s have field-for-field equivalent *configuration*.
    fn assert_handler_configs_match(a: &SerialHandler, b: &SerialHandler) {
        assert_eq!(
            a.budget.tool_limit(),
            b.budget.tool_limit(),
            "budget.tool_limit mismatch"
        );
        assert_eq!(
            a.budget.program_limit(),
            b.budget.program_limit(),
            "budget.program_limit mismatch"
        );
        assert_eq!(
            a.security.allowlist_summary(),
            b.security.allowlist_summary(),
            "security summary mismatch"
        );
    }

    #[tokio::test]
    async fn builder_default_matches_new_defaults() {
        let from_new = SerialHandler::new();
        let from_builder = SerialHandler::builder()
            .connections(Arc::new(ConnectionManager::new()))
            .security(SecurityManager::from_patterns::<[&str; 0]>([]))
            .build();

        assert_handler_configs_match(&from_new, &from_builder);
        assert_eq!(
            from_builder.budget.tool_limit(),
            DEFAULT_MAX_TOOL_BUFFERED_BYTES
        );
        assert_eq!(
            from_builder.budget.program_limit(),
            DEFAULT_MAX_PROGRAM_BUFFERED_BYTES
        );
    }

    #[tokio::test]
    async fn builder_custom_budget_overrides_default() {
        let budget: Arc<dyn BufferBudget> = Arc::new(AtomicBudget::new(4096, 2048));
        let handler = SerialHandler::builder()
            .connections(Arc::new(ConnectionManager::new()))
            .budget(budget)
            .build();
        assert_eq!(handler.budget.tool_limit(), 2048);
        assert_eq!(handler.budget.program_limit(), 4096);
    }
    #[tokio::test]
    async fn builder_custom_streams_preserved() {
        let streams: StreamRegistry = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
        let handler = SerialHandler::builder()
            .connections(Arc::new(ConnectionManager::new()))
            .streams(Arc::clone(&streams))
            .build();
        // Same Arc pointer must be retained (injectable, not copied).
        assert!(
            Arc::ptr_eq(&handler.streams, &streams),
            "streams Arc not retained"
        );
    }

    #[tokio::test]
    async fn builder_with_profiles_applies_path_and_profiles() {
        let path = std::path::PathBuf::from("/nonexistent/test-profiles.json");
        let handler = SerialHandler::builder()
            .connections(Arc::new(ConnectionManager::new()))
            .build()
            .with_profiles(path.clone(), Vec::new());
        assert_eq!(handler.profiles_path, path);
        assert!(handler.profiles.read().await.is_empty());
    }
}