Skip to main content

serial_mcp/
server.rs

1//! MCP server tool surface for serial communication.
2//!
3//! Each `#[tool]` method below corresponds to one MCP tool. Tools return
4//! structured JSON via [`Json<T>`] so MCP clients can index fields directly
5//! instead of parsing free-form text.
6
7use std::borrow::Cow;
8use std::sync::Arc;
9
10use base64::Engine as _;
11use rmcp::{
12    handler::server::wrapper::Parameters, model::*, prompt, prompt_router, service::RequestContext,
13    service::SubscriptionContext, tool, tool_handler, tool_router, ErrorData as McpError, Json,
14    RoleServer, ServerHandler,
15};
16use tokio::sync::broadcast;
17
18use tracing::info;
19
20use crate::buffer_budget::BufferBudget;
21use crate::capture_store::CaptureStore;
22use crate::mcp_protocol::{cache_fields_for, ProtocolLifecycle, ProtocolPolicy};
23use crate::resource_events::{is_subscribable_uri, ResourceEvent, ResourceEventHub};
24use crate::rx_session::RxSessionManager;
25use crate::security::SecurityManager;
26use crate::serial::{ConnectionManager, PortProvider};
27use crate::tx_session::TxSessionManager;
28
29use crate::prompts::types::*;
30use crate::prompts::{diagnose, interactive};
31use crate::tools::types::*;
32use crate::tools::{control_ops, io_ops, port_ops, utility_ops};
33
34/// Helper for cursor-based pagination over a vector of items.
35///
36/// `cursor` is interpreted as a base64-encoded UTF-8 string containing an offset
37/// number (e.g. "0", "1").  Returns the sliced items and an optional next
38/// cursor when more items remain.
39fn paginate<T: Clone>(
40    all: &[T],
41    cursor: Option<String>,
42    page_size: usize,
43) -> (Vec<T>, Option<String>) {
44    let offset = cursor
45        .as_deref()
46        .and_then(|c| base64::engine::general_purpose::STANDARD.decode(c).ok())
47        .and_then(|b| String::from_utf8(b).ok())
48        .and_then(|s| s.parse::<usize>().ok())
49        .unwrap_or(0)
50        .min(all.len());
51
52    let end = offset.saturating_add(page_size).min(all.len());
53    let items = all[offset..end].to_vec();
54
55    let next_cursor = if end < all.len() {
56        let next = base64::engine::general_purpose::STANDARD.encode(end.to_string().as_bytes());
57        Some(next)
58    } else {
59        None
60    };
61
62    (items, next_cursor)
63}
64
65/// Apply the SEP-2549 cache fields to a read-resource result exactly when the
66/// peer's negotiated protocol version carries the `ImmediatePrivate` cache
67/// policy (currently only `2026-07-28`); every other peer keeps the bare
68/// result. `ttlMs: 0`, `cacheScope: "private"` mark every `resources/read`
69/// response as immediately stale and client-private.
70fn read_result_with_cache_fields(
71    result: ReadResourceResult,
72    protocol_version: Option<ProtocolVersion>,
73) -> ReadResourceResponse {
74    if crate::mcp_protocol::cache_fields_for(protocol_version) {
75        result.with_ttl_ms(0).with_cache_scope(CacheScope::Private)
76    } else {
77        result
78    }
79    .into()
80}
81
82// ---- Handler ---------------------------------------------------------------
83
84#[derive(Clone)]
85pub struct SerialHandler {
86    pub(crate) connections: Arc<ConnectionManager>,
87    security: SecurityManager,
88    /// Process-wide RX session registry (ring + pump + shared cursor). One
89    /// per server process, shared by every handler instance: modern HTTP is
90    /// stateless (a fresh `SerialHandler` serves each request), so a
91    /// handler-local registry would split the ring across requests and lose
92    /// reads. The builder default constructs one for standalone handlers.
93    pub(crate) rx_sessions: Arc<RxSessionManager>,
94    tx_sessions: Arc<TxSessionManager>,
95    budget: Arc<dyn BufferBudget>,
96    profile_store: Arc<crate::profile_store::ProfileStore>,
97    /// Process-wide capture store. Disabled unless production
98    /// `main.rs` configured `--capture-dir`; shared by every stdio/HTTP
99    /// session handler.
100    capture_store: Arc<CaptureStore>,
101    /// Process-wide injectable port enumeration used consistently by tools,
102    /// resources, and automatic profile-session identity capture.
103    port_provider: Arc<dyn PortProvider>,
104    /// Process-wide resource event hub backing modern `subscriptions/listen`.
105    /// One hub per server process, shared by every stdio/HTTP handler and
106    /// the port watcher (modern HTTP is stateless — a handler-local channel
107    /// would split publishers and listeners across handler instances).
108    resource_events: Arc<ResourceEventHub>,
109}
110
111/// Injectable configuration for [`SerialHandler`].
112///
113/// Every field has a sensible default produced by [`SerialHandlerOptions::default`].
114/// Use [`SerialHandler::builder`] to override individual fields, then `.build()`.
115#[derive(Clone)]
116pub struct SerialHandlerOptions {
117    pub connections: Arc<ConnectionManager>,
118    pub security: SecurityManager,
119    pub budget: Arc<dyn BufferBudget>,
120    /// Process-wide profile store. Defaults to an ephemeral store for
121    /// library/test construction; production `main.rs` injects a store
122    /// opened at the resolved `--profiles-path`.
123    pub profile_store: Arc<crate::profile_store::ProfileStore>,
124    /// Process-wide capture store. Defaults to disabled for
125    /// library/test construction; production `main.rs` injects a store
126    /// opened at the resolved `--capture-dir`.
127    pub capture_store: Arc<CaptureStore>,
128    /// Process-wide port enumeration. Defaults to the system provider;
129    /// tests inject a static provider.
130    pub port_provider: Arc<dyn PortProvider>,
131    /// Process-wide resource event hub for modern `subscriptions/listen`.
132    /// Defaults to a fresh hub for library/test construction; production
133    /// `main.rs` creates exactly one hub per server process.
134    pub resource_events: Arc<ResourceEventHub>,
135    /// Process-wide RX session registry (ring + pump + shared cursor).
136    /// `None` (default) lets the builder construct one for standalone
137    /// handlers; production `main.rs` and the test harness create exactly
138    /// one per server process and inject it so every stateless HTTP handler
139    /// instance shares the same ring/cursor state.
140    pub rx_sessions: Option<Arc<RxSessionManager>>,
141}
142
143impl Default for SerialHandlerOptions {
144    fn default() -> Self {
145        use crate::limits::{DEFAULT_MAX_PROGRAM_BUFFERED_BYTES, DEFAULT_MAX_TOOL_BUFFERED_BYTES};
146        Self {
147            connections: Arc::new(ConnectionManager::new()),
148            security: SecurityManager::from_patterns::<[&str; 0]>([]),
149            budget: Arc::new(crate::buffer_budget::AtomicBudget::new(
150                DEFAULT_MAX_PROGRAM_BUFFERED_BYTES,
151                DEFAULT_MAX_TOOL_BUFFERED_BYTES,
152            )),
153            profile_store: Arc::new(crate::profile_store::ProfileStore::ephemeral()),
154            capture_store: Arc::new(CaptureStore::disabled()),
155            port_provider: Arc::new(crate::serial::SystemPortProvider),
156            resource_events: Arc::new(ResourceEventHub::default()),
157            rx_sessions: None,
158        }
159    }
160}
161
162/// Builder for [`SerialHandler`]. Start with [`SerialHandler::builder`].
163#[derive(Default)]
164pub struct SerialHandlerBuilder {
165    options: SerialHandlerOptions,
166}
167
168impl SerialHandlerBuilder {
169    pub fn connections(mut self, connections: Arc<ConnectionManager>) -> Self {
170        self.options.connections = connections;
171        self
172    }
173    pub fn security(mut self, security: SecurityManager) -> Self {
174        self.options.security = security;
175        self
176    }
177    pub fn budget(mut self, budget: Arc<dyn BufferBudget>) -> Self {
178        self.options.budget = budget;
179        self
180    }
181    pub fn profile_store(mut self, profile_store: Arc<crate::profile_store::ProfileStore>) -> Self {
182        self.options.profile_store = profile_store;
183        self
184    }
185    pub fn capture_store(mut self, capture_store: Arc<CaptureStore>) -> Self {
186        self.options.capture_store = capture_store;
187        self
188    }
189    pub fn port_provider(mut self, port_provider: Arc<dyn PortProvider>) -> Self {
190        self.options.port_provider = port_provider;
191        self
192    }
193    pub fn resource_events(mut self, resource_events: Arc<ResourceEventHub>) -> Self {
194        self.options.resource_events = resource_events;
195        self
196    }
197    /// Inject the process-wide RX session registry (ring + pump + shared
198    /// cursor). One per server process; clone the same `Arc` into every
199    /// HTTP handler factory so stateless requests share ring/cursor state.
200    pub fn rx_sessions(mut self, rx_sessions: Arc<RxSessionManager>) -> Self {
201        self.options.rx_sessions = Some(rx_sessions);
202        self
203    }
204
205    /// Consume the builder and produce a [`SerialHandler`].
206    ///
207    /// Spawns the reconnect supervisor exactly once. When no
208    /// [`SerialHandlerBuilder::rx_sessions`] was injected, one manager is
209    /// constructed here for the standalone handler.
210    pub fn build(self) -> SerialHandler {
211        let SerialHandlerOptions {
212            connections,
213            security,
214            budget,
215            profile_store,
216            capture_store,
217            port_provider,
218            resource_events,
219            rx_sessions,
220        } = self.options;
221        let rx_sessions = match rx_sessions {
222            Some(manager) => manager,
223            None => Arc::new(RxSessionManager::new(
224                Arc::clone(&budget),
225                Arc::clone(&resource_events),
226            )),
227        };
228        let handler = SerialHandler {
229            connections,
230            security,
231            rx_sessions,
232            tx_sessions: Arc::new(TxSessionManager::new()),
233            budget,
234            profile_store,
235            capture_store,
236            port_provider,
237            resource_events,
238        };
239        handler.spawn_reconnect_supervisor();
240        handler
241    }
242}
243
244#[tool_router]
245impl SerialHandler {
246    /// Entry point for the builder.
247    pub fn builder() -> SerialHandlerBuilder {
248        SerialHandlerBuilder::default()
249    }
250
251    /// Default handler: default connections, empty allowlist, default budget,
252    /// profiles loaded from the default path, reconnect supervisor spawned.
253    ///
254    /// Falls back to an ephemeral (non-persistent) store with a warning when
255    /// the default path cannot be resolved or contains invalid data — for
256    /// library/test convenience. Production `main.rs` does not use this
257    /// fallback: it resolves `--profiles-path` and fails startup on invalid
258    /// persistent data.
259    pub fn new() -> Self {
260        let store = crate::profiles::default_profiles_path()
261            .map_err(|e| format!("Cannot resolve default profiles path: {e}"))
262            .and_then(crate::profile_store::ProfileStore::open);
263        let store = match store {
264            Ok(store) => Arc::new(store),
265            Err(e) => {
266                tracing::warn!("profiles store unavailable, using ephemeral store: {e}");
267                Arc::new(crate::profile_store::ProfileStore::ephemeral())
268            }
269        };
270        Self::builder().profile_store(store).build()
271    }
272
273    /// Start the background reconnect supervisor task.
274    /// Requires a Tokio runtime to be active (panics otherwise).
275    pub fn spawn_reconnect_supervisor(&self) {
276        let connections = Arc::clone(&self.connections);
277        let rx_sessions = Arc::clone(&self.rx_sessions);
278        tokio::spawn(async move {
279            loop {
280                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
281                let all = connections.list_all().await;
282                for (id, conn) in all {
283                    let state = conn.state();
284                    if state == crate::serial::ConnectionState::Disconnected {
285                        let policy = conn.reconnect_policy.lock().expect("poisoned").clone();
286                        if policy.enabled {
287                            connections
288                                .start_reconnect(&id, Arc::clone(&rx_sessions))
289                                .await;
290                        }
291                    }
292                }
293            }
294        });
295    }
296
297    #[tool(
298        description = "List all available serial ports with a profile-match preview. `profile_matches` parallels `ports` (same order) and tells you whether the server already knows each device: `selected` — a bare `open(port=...)` reuses that profile (name in `selected_profile`); `ambiguous` — equal-ranked profiles, pick one via `open_profile`; `duplicate` — another live port shares this device's identity, never auto-selected; `ineligible` — weak identity with explicitly matching candidates (`open_profile` for a deliberate choice); `none` — a bare open starts a fresh generated session. Call this FIRST, then open.",
299        title = "List Serial Ports",
300        annotations(read_only_hint = true, open_world_hint = false)
301    )]
302    async fn list_ports(&self) -> Result<Json<ListPortsResult>, String> {
303        port_ops::list_ports(&self.port_provider, &self.profile_store).await
304    }
305
306    #[tool(
307        description = "List all open serial connections held by this server",
308        title = "List Open Connections",
309        annotations(read_only_hint = true, open_world_hint = false)
310    )]
311    async fn list_connections(&self) -> Result<Json<ListConnectionsResult>, String> {
312        port_ops::list_connections(&self.connections).await
313    }
314
315    #[tool(
316        description = "Open a serial port. The common call is `open(port=...)` — baud defaults to 115200/8-N-1 and the server automatically reuses the most recently used profile for a known high-confidence device (see `list_ports` `profile_matches`) or creates a durable generated profile for a new one. Add fields only when the automatic choice is wrong: explicit fields (baud, framing/parser/protocol, ...) override the selected profile and are learned back into it. Use `open_profile` for explicit named selection.",
317        title = "Open Serial Port",
318        annotations(destructive_hint = false, open_world_hint = false)
319    )]
320    async fn open(
321        &self,
322        Parameters(args): Parameters<OpenArgs>,
323    ) -> Result<Json<OpenResult>, String> {
324        let result = port_ops::open(
325            &self.connections,
326            &self.rx_sessions,
327            &self.security,
328            &self.profile_store,
329            &self.port_provider,
330            args,
331        )
332        .await?;
333        // Publish only after the successful open: connections list + detail.
334        self.resource_events.publish_connections_changed();
335        self.resource_events
336            .publish_connection_detail_changed(&result.0.connection_id);
337        Ok(result)
338    }
339
340    #[tool(
341        description = "Close an open serial port connection",
342        title = "Close Serial Port",
343        annotations(destructive_hint = false, open_world_hint = false)
344    )]
345    async fn close(
346        &self,
347        Parameters(args): Parameters<CloseArgs>,
348    ) -> Result<Json<CloseResult>, String> {
349        let connection_id = args.connection_id.clone();
350        // Cancel any running reconnect task so it doesn't try to reopen.
351        self.connections.cancel_reconnect(&connection_id).await;
352        let result = port_ops::close(&self.connections, &self.profile_store, args).await?;
353        // Publish only after the successful close: connections list + the
354        // (now-closed) detail URI as a final hint.
355        self.resource_events.publish_connections_changed();
356        self.resource_events
357            .publish_connection_detail_changed(&connection_id);
358        // Shut down RX session (pump + consumers) for this connection.
359        self.rx_sessions.remove(&connection_id).await;
360        // Shut down TX session (worker) for this connection.
361        self.tx_sessions.remove(&connection_id).await;
362        Ok(result)
363    }
364
365    #[tool(
366        description = "Send data to a serial port (send-only). Prefer `transact` when the device responds — it writes and awaits the response in one call. `tx_framing` (line terminator, delimiter, length prefix, SLIP, COBS, start/end markers) and `protocol` presets (at_command, slip, json_lines, cobs, ndjson, nmea0183, modbus_ascii) apply only when the connection defaults don't fit; the nmea0183 preset auto-appends the *XX XOR checksum. When tx_framing is used, decoded_bytes reports the payload length before framing and bytes_written the total framed bytes.",
367        title = "Write Serial Data",
368        annotations(destructive_hint = true, open_world_hint = false)
369    )]
370    async fn write(
371        &self,
372        Parameters(args): Parameters<WriteArgs>,
373    ) -> Result<Json<WriteResult>, String> {
374        let result = io_ops::write(&self.connections, &self.tx_sessions, args).await?;
375        // A successful write changes connection state (counters); hint the
376        // detail URI. RX-side hints come from the pump.
377        self.resource_events
378            .publish_connection_detail_changed(&result.0.connection_id);
379        Ok(result)
380    }
381
382    #[tool(
383        description = "Write data, then await the response, in one call — the request/response primitive for AT/Modbus/GRBL-style traffic. Prefer `transact` over separate `write`+`read`. The read half starts at the live edge (`from: {\"type\":\"now\"}`) so it only awaits post-write bytes. Add `match` to stop on a prompt, `no_new_rx_timeout_ms`/`timeout_ms` for bounded waits; `protocol` fills framing defaults for both directions and explicit tx_framing/rx_framing/rx_parser override per direction.",
384        title = "Transact (Write + Read)",
385        annotations(destructive_hint = true, open_world_hint = false)
386    )]
387    async fn transact(
388        &self,
389        meta: RequestMetaObject,
390        ct: tokio_util::sync::CancellationToken,
391        peer: rmcp::Peer<RoleServer>,
392        Parameters(args): Parameters<TransactArgs>,
393    ) -> Result<Json<TransactResult>, String> {
394        let result = io_ops::transact(
395            &self.connections,
396            &self.tx_sessions,
397            &self.rx_sessions,
398            &self.budget,
399            meta,
400            ct,
401            peer,
402            args,
403        )
404        .await?;
405        // The write half changed connection state; hint the detail URI.
406        // RX-side hints come from the pump.
407        self.resource_events
408            .publish_connection_detail_changed(&result.0.connection_id);
409        Ok(result)
410    }
411
412    #[tool(
413        description = "Read buffered serial data or wait for unsolicited data/patterns. Returns buffered-but-unread bytes from the connection's cursor immediately (like `cat`); use `from` to replay (`{\"type\":\"buffer_start\"}`), jump to the live edge (`{\"type\":\"now\"}`), or seek an absolute offset (`{\"type\":\"offset\",\"offset\":N}`); `{\"type\":\"cursor\"}` is the default. Use `match` to wait for a pattern (checks buffered history first, then waits). Framing (`rx_framing`), parser (`rx_parser`), and `protocol` presets apply only when connection defaults don't fit; with validate:true checksum-mismatched frames are dropped and counted. Set `no_new_rx_timeout_ms` to stop on silence. Results carry from_offset/next_offset/bytes_lost/buffered_remaining/start_offset/end_offset.",
414        title = "Read Serial Data",
415        annotations(read_only_hint = true, open_world_hint = false)
416    )]
417    async fn read(
418        &self,
419        meta: RequestMetaObject,
420        ct: tokio_util::sync::CancellationToken,
421        peer: rmcp::Peer<RoleServer>,
422        Parameters(args): Parameters<ReadArgs>,
423    ) -> Result<Json<ReadResult>, String> {
424        io_ops::read(
425            &self.connections,
426            &self.rx_sessions,
427            &self.budget,
428            meta,
429            ct,
430            peer,
431            args,
432        )
433        .await
434    }
435
436    #[tool(
437        description = "Discard buffered serial data. target=input clears OS read buffer and discards all unread buffered RX data; to skip past buffered data without destroying it, use `read` with `from: {\"type\":\"now\"}` to jump to the live edge. target=output clears the OS write queue. target=both flushes output first, then performs the input-target discard (OS read buffer + retained RX backlog).",
438        title = "Flush Serial Buffers",
439        annotations(destructive_hint = true, open_world_hint = false)
440    )]
441    async fn flush(
442        &self,
443        Parameters(args): Parameters<FlushArgs>,
444    ) -> Result<Json<FlushResult>, String> {
445        let result = io_ops::flush(
446            &self.connections,
447            &self.rx_sessions,
448            &self.tx_sessions,
449            args,
450        )
451        .await?;
452        // Input-side flushes change the ring; hint detail + raw.
453        match result.0.target {
454            crate::serial::FlushTarget::Input | crate::serial::FlushTarget::Both => {
455                self.resource_events
456                    .publish_connection_detail_changed(&result.0.connection_id);
457                self.resource_events
458                    .publish_connection_raw_changed(&result.0.connection_id);
459            }
460            crate::serial::FlushTarget::Output => {}
461        }
462        Ok(result)
463    }
464
465    #[tool(
466        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.",
467        title = "Set DTR/RTS",
468        annotations(
469            destructive_hint = true,
470            idempotent_hint = true,
471            open_world_hint = false
472        )
473    )]
474    async fn set_dtr_rts(
475        &self,
476        Parameters(args): Parameters<SetDtrRtsArgs>,
477    ) -> Result<Json<SetDtrRtsResult>, String> {
478        let result = control_ops::set_dtr_rts(&self.connections, args).await?;
479        self.resource_events
480            .publish_connection_detail_changed(&result.0.connection_id);
481        Ok(result)
482    }
483
484    #[tool(
485        description = "Change hardware/software flow control mode on an open connection. Use flow_control='none' to ignore RTS/CTS for this session.",
486        title = "Set Flow Control",
487        annotations(
488            destructive_hint = true,
489            idempotent_hint = true,
490            open_world_hint = false
491        )
492    )]
493    async fn set_flow_control(
494        &self,
495        Parameters(args): Parameters<SetFlowControlArgs>,
496    ) -> Result<Json<SetFlowControlResult>, String> {
497        let result =
498            control_ops::set_flow_control(&self.connections, &self.profile_store, args).await?;
499        self.resource_events
500            .publish_connection_detail_changed(&result.0.connection_id);
501        Ok(result)
502    }
503
504    #[tool(
505        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.",
506        title = "Send BREAK",
507        annotations(destructive_hint = true, open_world_hint = false)
508    )]
509    async fn send_break(
510        &self,
511        meta: RequestMetaObject,
512        ct: tokio_util::sync::CancellationToken,
513        peer: rmcp::Peer<RoleServer>,
514        Parameters(args): Parameters<SendBreakArgs>,
515    ) -> Result<Json<SendBreakResult>, String> {
516        let result = control_ops::send_break(&self.connections, meta, ct, peer, args).await?;
517        self.resource_events
518            .publish_connection_detail_changed(&result.0.connection_id);
519        Ok(result)
520    }
521
522    #[tool(
523        description = "Inspect a connection's live configuration, RX ring state (size, offsets, cursor, buffered unread bytes, wrap loss), profile binding, and reconnect state. For diagnostics — not routine reads; read results already carry the offsets you need.",
524        title = "Get Connection Status",
525        annotations(read_only_hint = true, open_world_hint = false)
526    )]
527    async fn get_status(
528        &self,
529        Parameters(args): Parameters<GetStatusArgs>,
530    ) -> Result<Json<GetStatusResult>, String> {
531        port_ops::get_status(&self.connections, &self.rx_sessions, args).await
532    }
533
534    #[tool(
535        description = "Change baud rate, data bits, stop bits, parity, or flow control on a live connection without reopening. Omitted parameters are left unchanged. The change is learned into the bound profile (see result `profile`/`profile_persistence`).",
536        title = "Reconfigure Serial Port",
537        annotations(destructive_hint = true, open_world_hint = false)
538    )]
539    async fn reconfigure(
540        &self,
541        Parameters(args): Parameters<ReconfigureArgs>,
542    ) -> Result<Json<ReconfigureResult>, String> {
543        let result = port_ops::reconfigure(&self.connections, &self.profile_store, args).await?;
544        self.resource_events
545            .publish_connection_detail_changed(&result.0.connection_id);
546        Ok(result)
547    }
548
549    #[tool(
550        description = "List saved device profiles (selector, defaults, metadata, revision history). Cross-check with `list_ports` `profile_matches` to see which profiles match live devices before opening.",
551        title = "List Profiles",
552        annotations(read_only_hint = true, open_world_hint = false)
553    )]
554    async fn list_profiles(&self) -> Result<Json<ListProfilesResult>, String> {
555        let profiles = self.profile_store.list().await;
556        port_ops::list_profiles(&profiles)
557    }
558
559    #[tool(
560        description = "Open a device by named profile (explicit selection). Use when `list_ports` shows `ambiguous`/`ineligible`/`duplicate` matches, when device identity is weak, or to override the automatic last-used choice. The selector must match exactly one live port; the profile's defaults apply.",
561        title = "Open by Profile",
562        annotations(destructive_hint = false, open_world_hint = false)
563    )]
564    async fn open_profile(
565        &self,
566        Parameters(args): Parameters<OpenProfileArgs>,
567    ) -> Result<Json<OpenResult>, String> {
568        // Clone the profile out of the store first; do not hold a store
569        // lock while opening serial hardware.
570        let profile = self.profile_store.get(&args.profile).await;
571        let result = port_ops::open_profile(
572            &self.connections,
573            &self.rx_sessions,
574            &self.security,
575            &self.profile_store,
576            &self.port_provider,
577            profile,
578            args,
579        )
580        .await?;
581        // Publish only after the successful open: connections list + detail.
582        self.resource_events.publish_connections_changed();
583        self.resource_events
584            .publish_connection_detail_changed(&result.0.connection_id);
585        Ok(result)
586    }
587
588    #[tool(
589        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.",
590        title = "Save Profile",
591        annotations(destructive_hint = true, open_world_hint = false)
592    )]
593    async fn save_profile(
594        &self,
595        Parameters(args): Parameters<SaveProfileArgs>,
596    ) -> Result<Json<SaveProfileResult>, String> {
597        port_ops::save_profile(&self.connections, &self.profile_store, args).await
598    }
599
600    #[tool(
601        description = "Delete a profile by name, removing it from the profiles configuration file.",
602        title = "Delete Profile",
603        annotations(destructive_hint = true, open_world_hint = false)
604    )]
605    async fn delete_profile(
606        &self,
607        Parameters(args): Parameters<DeleteProfileArgs>,
608    ) -> Result<Json<DeleteProfileResult>, String> {
609        port_ops::delete_profile(&self.connections, &self.profile_store, args).await
610    }
611
612    #[tool(
613        description = "Restore a retained prior revision of a profile after a bad learned setting. `list_profiles` shows `revisions` (newest five snapshots); pass the profile's CURRENT revision as `expected_revision` to guard against concurrent modification. Restores as a NEW monotonic revision; bound connections stay on live state and become stale until reopened. Wrong expected_revision or an evicted target revision is a tool error that leaves the file unchanged.",
614        title = "Roll Back Profile",
615        annotations(destructive_hint = true, open_world_hint = false)
616    )]
617    async fn rollback_profile(
618        &self,
619        Parameters(args): Parameters<RollbackProfileArgs>,
620    ) -> Result<Json<RollbackProfileResult>, String> {
621        port_ops::rollback_profile(&self.connections, &self.profile_store, args).await
622    }
623
624    #[tool(
625        description = "Set defaults in two modes. Profile mode: `configure(profile=..., defaults=...)` writes a named profile in the profiles TOML (applied on future open_profile calls; overwrite=true replaces an existing profile). Connection mode: `configure(connection_id=..., defaults=...)` mutates framing/parser/protocol/reconnect_policy/max_buffered_bytes defaults on a live connection (does NOT persist to disk; reopen to apply rx_buffer_size, serial-line params, log_capacity, log_enabled). The `defaults` object carries the full desired state — omit fields to use their defaults.",
626        title = "Configure Defaults",
627        annotations(destructive_hint = true, open_world_hint = false)
628    )]
629    async fn configure(
630        &self,
631        Parameters(args): Parameters<ConfigureArgs>,
632    ) -> Result<Json<ConfigureResult>, String> {
633        // Connection mode mutates live defaults (detail changes). Profile
634        // mode has no live connection URI — no event.
635        let connection_id = args.connection_id.clone();
636        let result = port_ops::configure(&self.connections, &self.profile_store, args).await?;
637        if result.0.mode == "connection" {
638            if let Some(connection_id) = connection_id.as_deref() {
639                self.resource_events
640                    .publish_connection_detail_changed(connection_id);
641            }
642        }
643        Ok(result)
644    }
645
646    #[tool(
647        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.",
648        title = "Get Log",
649        annotations(read_only_hint = true, open_world_hint = false)
650    )]
651    async fn get_log(
652        &self,
653        Parameters(args): Parameters<GetLogArgs>,
654    ) -> Result<Json<GetLogResult>, String> {
655        port_ops::get_log(&self.connections, args).await
656    }
657
658    #[tool(
659        description = "Clear the event log buffer for a connection. Resets the log to empty.",
660        title = "Clear Log",
661        annotations(destructive_hint = true, open_world_hint = false)
662    )]
663    async fn clear_log(
664        &self,
665        Parameters(args): Parameters<ClearLogArgs>,
666    ) -> Result<Json<ClearLogResult>, String> {
667        let result = port_ops::clear_log(&self.connections, args).await?;
668        self.resource_events
669            .publish_connection_log_changed(&result.0.connection_id);
670        Ok(result)
671    }
672
673    #[tool(
674        description = "Export the event log for a connection to a JSONL file inside the configured capture directory. Persistent capture is DISABLED unless the server started with --capture-dir <absolute-directory>. `path` is a portable .jsonl FILENAME relative to that root — never an arbitrary path: no separators, no subdirectories, no traversal, filename only (1-120 chars, ends .jsonl). The server never overwrites an existing file (no-clobber), rejects symlink targets, enforces per-file/total-byte/file-count quotas from a fresh scan under an advisory cross-process lock, and commits the complete bounded snapshot atomically. Pre-commit failure creates no file and changes no existing capture. Success returns exact event/byte counts, the canonical absolute final path, and post-commit quota usage; on Unix a post-commit root-directory sync failure is reported in `durability_warning` (the file IS committed and counted — it is never deleted).",
675        title = "Export Log",
676        annotations(destructive_hint = false, open_world_hint = false)
677    )]
678    async fn export_log(
679        &self,
680        Parameters(args): Parameters<ExportLogArgs>,
681    ) -> Result<Json<ExportLogResult>, String> {
682        port_ops::export_log(&self.connections, &self.capture_store, args).await
683    }
684
685    #[tool(
686        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.",
687        title = "Reconnect",
688        annotations(destructive_hint = false, open_world_hint = false)
689    )]
690    async fn reconnect(
691        &self,
692        Parameters(args): Parameters<ReconnectArgs>,
693    ) -> Result<Json<ReconnectResult>, String> {
694        let result = port_ops::reconnect(&self.connections, args).await?;
695        // Reconnect/state change: hint the detail URI.
696        self.resource_events
697            .publish_connection_detail_changed(&result.0.connection_id);
698        Ok(result)
699    }
700
701    #[tool(
702        description = "Atomic boot/reset capture: purges unread OS input, marks the RX live edge under the pump gate (no pre-mark byte can leak in), optionally pulses DTR/RTS (release guaranteed on completion, cancellation, or failure), then captures ONLY post-mark bytes through the existing match/framing/parser/timeout/silence pipeline. Uses a private read cursor — the shared `read` cursor and ring history are untouched. `reset=null` = arm-only capture for externally reset devices (lines never touched). Result is bounded in memory by the connection's max_buffered_bytes; no file output. `read.from_offset` equals `mark_offset` unless the ring wrapped (then `bytes_lost` reports it). Destructive: configured reset lines may reboot hardware.",
703        title = "Capture Boot Output",
704        annotations(destructive_hint = true, open_world_hint = false)
705    )]
706    async fn capture_boot(
707        &self,
708        meta: RequestMetaObject,
709        ct: tokio_util::sync::CancellationToken,
710        peer: rmcp::Peer<RoleServer>,
711        Parameters(args): Parameters<CaptureBootArgs>,
712    ) -> Result<Json<CaptureBootResult>, String> {
713        control_ops::capture_boot(
714            &self.connections,
715            &self.rx_sessions,
716            &self.budget,
717            meta,
718            ct,
719            peer,
720            args,
721        )
722        .await
723    }
724
725    #[tool(
726        description = "Compute a checksum over caller-supplied bytes. Algorithms: xor (NMEA-0183 *XX), lrc (Modbus ASCII). Input data is decoded from the given encoding (utf8/hex/base64) before checksumming. Returns the checksum as a hex string and a raw integer. LLMs cannot reliably compute checksums by hand — use this when hand-crafting binary frames for a protocol without a preset.",
727        title = "Compute Checksum",
728        annotations(read_only_hint = true, open_world_hint = false)
729    )]
730    async fn compute_checksum(
731        &self,
732        Parameters(args): Parameters<ComputeChecksumArgs>,
733    ) -> Result<Json<ComputeChecksumResult>, String> {
734        utility_ops::compute_checksum(args).await
735    }
736}
737
738// ---- Tool catalog (tool logic extracted across src/tools/*.rs) -------------
739
740/// The full public MCP tool catalog exactly as served by `tools/list`.
741///
742/// Every `#[tool]` method's generated attribute is collected here so schema
743/// tests (`src/tools/mod.rs`) and the xtask `agent-eval` catalog metrics
744/// consume the SAME tool attributes the MCP router serves — no duplicated
745/// 25-tool enumeration can drift from the router. Keep this list in sync
746/// with the `#[tool]` methods above; `tool_catalog_has_exactly_twenty_five_tools`
747/// guards the count.
748pub fn tool_catalog() -> Vec<rmcp::model::Tool> {
749    vec![
750        SerialHandler::list_ports_tool_attr(),
751        SerialHandler::list_connections_tool_attr(),
752        SerialHandler::open_tool_attr(),
753        SerialHandler::close_tool_attr(),
754        SerialHandler::write_tool_attr(),
755        SerialHandler::transact_tool_attr(),
756        SerialHandler::read_tool_attr(),
757        SerialHandler::capture_boot_tool_attr(),
758        SerialHandler::flush_tool_attr(),
759        SerialHandler::set_dtr_rts_tool_attr(),
760        SerialHandler::set_flow_control_tool_attr(),
761        SerialHandler::send_break_tool_attr(),
762        SerialHandler::get_status_tool_attr(),
763        SerialHandler::reconfigure_tool_attr(),
764        SerialHandler::list_profiles_tool_attr(),
765        SerialHandler::open_profile_tool_attr(),
766        SerialHandler::save_profile_tool_attr(),
767        SerialHandler::delete_profile_tool_attr(),
768        SerialHandler::configure_tool_attr(),
769        SerialHandler::rollback_profile_tool_attr(),
770        SerialHandler::get_log_tool_attr(),
771        SerialHandler::clear_log_tool_attr(),
772        SerialHandler::export_log_tool_attr(),
773        SerialHandler::reconnect_tool_attr(),
774        SerialHandler::compute_checksum_tool_attr(),
775    ]
776}
777
778// ---- ServerHandler boilerplate ----------------------------------------------
779
780/// Capability set for one policy row: tools/resources/prompts/completions for
781/// every row; resource subscriptions only where the row's policy enables
782/// them. Deliberately omits MCP logging, list-change flags, tasks, and
783/// unrelated capabilities in every view.
784fn capabilities_for(policy: &ProtocolPolicy) -> ServerCapabilities {
785    let mut builder = ServerCapabilities::builder()
786        .enable_tools()
787        .enable_resources()
788        .enable_prompts()
789        .enable_completions();
790    if policy.resource_subscriptions {
791        builder = builder.enable_resources_subscribe();
792    }
793    builder.build()
794}
795
796/// Shared server info shape for one policy row: identity, instructions, the
797/// row's capability set, and the row's protocol version. All version/feature
798/// decisions come from the policy table — no hard-coded version helpers.
799fn server_info_for(policy: &ProtocolPolicy) -> ServerInfo {
800    ServerInfo::new(capabilities_for(policy))
801        .with_server_info(Implementation::new(
802            env!("CARGO_PKG_NAME"),
803            env!("CARGO_PKG_VERSION"),
804        ))
805        .with_protocol_version(policy.version.clone())
806        .with_instructions(
807            "Serial port MCP server. Normal workflow:\n\
808             1. Call `list_ports` and inspect `profile_matches` (parallel to `ports`): \
809             it previews which profile a bare `open(port=...)` would reuse.\n\
810             2. Normally call bare `open` with the port only — baud defaults to \
811             115200/8-N-1 and the server automatically reuses the most recently used \
812             high-confidence profile for a known device or creates a durable generated \
813              profile for a new one (both observable in the result's `profile`).\n\
814               3. Use `transact` for command/response, `read` for buffered or unsolicited \
815              data (with `match` to wait for a pattern), `write` for send-only.\n\
816              4. For boot/reset capture (Arduino auto-reset, power-cycle banner, boot \
817             prompt) use `capture_boot` — one call that atomically marks the live edge, \
818             optionally pulses DTR/RTS, and captures only post-mark bytes (private \
819             cursor; in-memory only). `reset=null` arms capture for externally reset \
820             devices.\n\
821              5. After durable changes inspect `profile` / `profile_persistence` on the \
822             result, or `get_status` for the live binding.\n\
823              6. Use `open_profile` only for explicit choice or weak identity; \
824             `rollback_profile` restores a retained configuration after a bad learned \
825             change.\n\
826              7. Escalate to framing/parser, cursor replay, reconnect, line control, and \
827             log tools only when the common path needs them. `export_log` persists the \
828             event log as JSONL only when the server started with `--capture-dir`; it \
829             takes a portable filename (never a path), never overwrites, and is \
830             quota-bounded.\n\
831              8. Optional wakeup: modern clients may call `subscriptions/listen` with \
832             resource URIs (`serial://ports`, `serial://connections`, or \
833             `serial://connections/{id}[/raw|/log]`) to be notified when those resources \
834             change. Notifications are hints only — `read` remains the primary lossless \
835             data path.\n\
836             Resources: serial://ports (same preview as list_ports), serial://connections, \
837             serial://connections/{id}. Prompts: diagnose_port, interactive_terminal."
838                .to_string(),
839        )
840}
841
842impl Default for SerialHandler {
843    fn default() -> Self {
844        Self::new()
845    }
846}
847
848// ---- Prompt templates ------------------------------------------------------
849
850// ---- Completion helper ------------------------------------------------------
851
852impl SerialHandler {
853    /// Generate completion suggestions for tool/resource arguments.
854    async fn get_completions(&self, r#ref: &Reference, argument: &ArgumentInfo) -> Vec<String> {
855        match r#ref {
856            Reference::Resource(resource_ref) => {
857                if resource_ref.uri == URI_PORTS && argument.name == "port" {
858                    match self.port_provider.list_available() {
859                        Ok(ports) => ports.into_iter().map(|p| p.name).collect(),
860                        Err(_) => vec![],
861                    }
862                } else {
863                    vec![]
864                }
865            }
866            Reference::Prompt(prompt_ref) => {
867                if prompt_ref.name == "diagnose_port" && argument.name == "port" {
868                    match self.port_provider.list_available() {
869                        Ok(ports) => ports.into_iter().map(|p| p.name).collect(),
870                        Err(_) => vec![],
871                    }
872                } else {
873                    vec![]
874                }
875            }
876            _ => vec![],
877        }
878    }
879}
880
881#[prompt_router]
882impl SerialHandler {
883    /// Walk through diagnosing an unknown serial port: try common baud
884    /// rates, send a benign probe, observe response, narrow down config.
885    #[prompt(
886        name = "diagnose_port",
887        description = "Step-by-step plan to identify an unknown serial device on a given port"
888    )]
889    async fn diagnose_port_prompt(
890        &self,
891        Parameters(args): Parameters<DiagnosePortArgs>,
892        _ctx: RequestContext<RoleServer>,
893    ) -> Result<GetPromptResult, McpError> {
894        Ok(diagnose::build_diagnose_prompt(args))
895    }
896
897    /// Guide an interactive serial REPL session against an already-open
898    /// connection, using `write` / `read(match=...)` or `transact` to drive
899    /// a command/response loop.
900    #[prompt(
901        name = "interactive_terminal",
902        description = "Run a REPL-style command/response session over an open serial connection"
903    )]
904    async fn interactive_terminal_prompt(
905        &self,
906        Parameters(args): Parameters<InteractiveTerminalArgs>,
907        _ctx: RequestContext<RoleServer>,
908    ) -> Result<GetPromptResult, McpError> {
909        Ok(interactive::build_interactive_prompt(args))
910    }
911}
912
913// NOTE: no `#[prompt_handler]` here — that macro *unconditionally replaces*
914// any `list_prompts`/`get_prompt` in the annotated block with generated
915// versions that leave the SEP-2549 cache fields unset (rmcp-macros 3.1.0,
916// unlike `#[tool_handler]`, does not honor existing methods). The two
917// methods are therefore written explicitly below using the SAME
918// `Self::prompt_router()` the macro would use.
919#[tool_handler]
920impl ServerHandler for SerialHandler {
921    fn get_info(&self) -> ServerInfo {
922        // Preferred-policy view. rmcp intersects `subscriptions/listen`
923        // filters against `get_info().capabilities`, so this must advertise
924        // the preferred (`2026-07-28`) resource-subscription capability;
925        // `initialize()` still returns the legacy row's view explicitly for
926        // `2025-11-25` clients.
927        server_info_for(crate::mcp_protocol::preferred_policy())
928    }
929
930    async fn initialize(
931        &self,
932        request: InitializeRequestParams,
933        context: RequestContext<RoleServer>,
934    ) -> Result<InitializeResult, McpError> {
935        // Exact policy lookup admits only the `InitializeSession` lifecycle.
936        // Modern `2026-07-28` clients negotiate via `server/discover`; a
937        // modern `initialize` (and any unknown/unsupported version) is
938        // rejected BEFORE peer bookkeeping so no session state is
939        // established for it. rmcp maps the handler's METHOD_NOT_FOUND
940        // through the transport routing of the request.
941        let Some(policy) = crate::mcp_protocol::policy_for(&request.protocol_version) else {
942            return Err(McpError::method_not_found::<InitializeResultMethod>());
943        };
944        if policy.lifecycle != ProtocolLifecycle::InitializeSession {
945            return Err(McpError::method_not_found::<InitializeResultMethod>());
946        }
947        // Preserve rmcp peer bookkeeping: the session worker's peer_info()
948        // must reflect this client's initialize parameters so subsequent
949        // requests route with the negotiated (legacy) protocol version.
950        context.peer.set_peer_info(request.clone());
951        info!("Serial MCP server initialized");
952        Ok(server_info_for(policy))
953    }
954
955    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
956        Cow::Owned(crate::mcp_protocol::supported_protocol_versions())
957    }
958
959    async fn discover(
960        &self,
961        _context: RequestContext<RoleServer>,
962    ) -> Result<DiscoverResult, McpError> {
963        Ok(DiscoverResult::from_server_info(
964            crate::mcp_protocol::supported_protocol_versions(),
965            server_info_for(crate::mcp_protocol::preferred_policy()),
966        ))
967    }
968
969    fn accepted_subscription_filter(
970        &self,
971        requested: &SubscriptionFilter,
972    ) -> Option<SubscriptionFilter> {
973        // Accept only valid, deduplicated resource subscriptions, preserving
974        // first-request order. All three list-change flags are stripped
975        // (serial-mcp never emits list-change notifications). Templates,
976        // malformed/empty ids, and unknown URIs are rejected by
977        // `is_subscribable_uri`. An empty accepted resource list becomes
978        // `None` inside the filter (no fake URI); the handler itself always
979        // remains available so rmcp acknowledges with the accepted filter.
980        let mut seen = std::collections::HashSet::new();
981        let mut accepted_uris = Vec::new();
982        if let Some(requested_uris) = requested.resource_subscriptions.as_ref() {
983            for uri in requested_uris {
984                if is_subscribable_uri(uri) && seen.insert(uri.clone()) {
985                    accepted_uris.push(uri.clone());
986                }
987            }
988        }
989        let mut builder = SubscriptionFilter::builder();
990        for uri in accepted_uris {
991            builder = builder.resource_subscription(uri);
992        }
993        Some(builder.build())
994    }
995
996    async fn listen(&self, context: SubscriptionContext) -> Result<(), McpError> {
997        // 1. Snapshot the accepted URI set (first-occurrence order).
998        //
999        // rmcp computes the accepted filter as
1000        // `requested.intersection(&candidate).intersection(&advertised)`,
1001        // both left-biased over the REQUESTED list, so a duplicate requested
1002        // URI may be echoed into `context.accepted()`. Deduplicate again
1003        // here (first-occurrence order) so normal matching and lag recovery
1004        // never emit duplicate hints because the request repeated a URI.
1005        let accepted: Vec<String> = {
1006            let mut seen = std::collections::HashSet::new();
1007            context
1008                .accepted()
1009                .resource_subscriptions
1010                .clone()
1011                .unwrap_or_default()
1012                .into_iter()
1013                .filter(|uri| seen.insert(uri.clone()))
1014                .collect()
1015        };
1016        // 2. One receiver per listener.
1017        let mut receiver = self.resource_events.subscribe();
1018        let cancelled = context.cancelled();
1019        tokio::pin!(cancelled);
1020        loop {
1021            tokio::select! {
1022                // 3. Cancellation completes the stream cleanly.
1023                _ = &mut cancelled => return Ok(()),
1024                result = receiver.recv() => {
1025                    match result {
1026                        // 4+5. Matching update -> notify; unrelated events
1027                        // are ignored.
1028                        Ok(ResourceEvent::Updated(uri)) => {
1029                            if accepted.contains(&uri) {
1030                                if let Err(error) =
1031                                    context.sink().notify_resource_updated(uri).await
1032                                {
1033                                    // Genuine sink failure (peer gone or
1034                                    // subscription ended): terminate cleanly,
1035                                    // no retry loop.
1036                                    tracing::debug!("listen: sink terminated: {error}");
1037                                    return Ok(());
1038                                }
1039                            }
1040                        }
1041                        // 6. Lag: conservatively notify every accepted URI
1042                        // once, in accepted order. Never blocks the
1043                        // publisher or pump (the hub is bounded and publish
1044                        // is synchronous).
1045                        Err(broadcast::error::RecvError::Lagged(_)) => {
1046                            for uri in &accepted {
1047                                if let Err(error) =
1048                                    context.sink().notify_resource_updated(uri.clone()).await
1049                                {
1050                                    tracing::debug!(
1051                                        "listen: sink terminated during lag recovery: {error}"
1052                                    );
1053                                    return Ok(());
1054                                }
1055                            }
1056                        }
1057                        // 7. Closed hub: complete successfully.
1058                        Err(broadcast::error::RecvError::Closed) => return Ok(()),
1059                    }
1060                }
1061            }
1062        }
1063    }
1064
1065    async fn list_resources(
1066        &self,
1067        request: Option<PaginatedRequestParams>,
1068        ctx: RequestContext<RoleServer>,
1069    ) -> Result<ListResourcesResult, McpError> {
1070        const PAGE_SIZE: usize = 100;
1071
1072        let port_count = self
1073            .port_provider
1074            .list_available()
1075            .map(|v| v.len() as u64)
1076            .unwrap_or(0);
1077        let conn_count = self.connections.count().await as u64;
1078
1079        let all = vec![
1080            Resource::new(URI_PORTS, "Available serial ports")
1081                .with_description("JSON list of serial ports the OS currently exposes.".to_string())
1082                .with_mime_type("application/json".to_string())
1083                .with_size(port_count)
1084                .with_annotations(
1085                    Annotations::default()
1086                        .with_priority(0.9)
1087                        .with_audience(vec![Role::User, Role::Assistant]),
1088                ),
1089            Resource::new(URI_CONNECTIONS, "Open serial connections")
1090                .with_description(
1091                    "JSON list of serial connections currently held open by this server."
1092                        .to_string(),
1093                )
1094                .with_mime_type("application/json".to_string())
1095                .with_size(conn_count)
1096                .with_annotations(
1097                    Annotations::default()
1098                        .with_priority(0.8)
1099                        .with_audience(vec![Role::User, Role::Assistant]),
1100                ),
1101        ];
1102        let (resources, next_cursor) = paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
1103        let mut result = ListResourcesResult::with_all_items(resources);
1104        result.next_cursor = next_cursor;
1105        if cache_fields_for(ctx.protocol_version()) {
1106            result = result.with_ttl_ms(0).with_cache_scope(CacheScope::Private);
1107        }
1108        Ok(result)
1109    }
1110
1111    async fn list_resource_templates(
1112        &self,
1113        request: Option<PaginatedRequestParams>,
1114        ctx: RequestContext<RoleServer>,
1115    ) -> Result<ListResourceTemplatesResult, McpError> {
1116        const PAGE_SIZE: usize = 100;
1117        let all = vec![
1118            ResourceTemplate::new(
1119                URI_CONNECTION_TEMPLATE,
1120                "Open serial connection by id",
1121            )
1122            .with_description(
1123                "Per-connection state. Substitute {id} with a connection_id returned by the open tool."
1124                    .to_string(),
1125            )
1126            .with_mime_type("application/json".to_string())
1127            .with_annotations(
1128                Annotations::default()
1129                    .with_priority(0.7)
1130                    .with_audience(vec![Role::User, Role::Assistant]),
1131            ),
1132            ResourceTemplate::new(
1133                URI_CONNECTION_RAW_TEMPLATE,
1134                "Raw binary data from a serial connection",
1135            )
1136            .with_description(
1137                "Base64-encoded bytes read from the connection. This resource consumes up to 256 pending bytes; substitute {id} with a connection_id."
1138                    .to_string(),
1139            )
1140            .with_mime_type("application/octet-stream".to_string())
1141            .with_annotations(
1142                Annotations::default()
1143                    .with_priority(0.6)
1144                    .with_audience(vec![Role::User, Role::Assistant]),
1145            ),
1146            ResourceTemplate::new(
1147                URI_CONNECTION_LOG_TEMPLATE,
1148                "Event log for a serial connection",
1149            )
1150            .with_description(
1151                "JSONL event log for the connection. Substitute {id} with a connection_id. Each line is a JSON object with timestamp, direction, and event fields."
1152                    .to_string(),
1153            )
1154            .with_mime_type("application/x-ndjson".to_string())
1155            .with_annotations(
1156                Annotations::default()
1157                    .with_priority(0.5)
1158                    .with_audience(vec![Role::User, Role::Assistant]),
1159            ),
1160        ];
1161        let (resource_templates, next_cursor) =
1162            paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
1163        let mut result = ListResourceTemplatesResult::with_all_items(resource_templates);
1164        result.next_cursor = next_cursor;
1165        if cache_fields_for(ctx.protocol_version()) {
1166            result = result.with_ttl_ms(0).with_cache_scope(CacheScope::Private);
1167        }
1168        Ok(result)
1169    }
1170
1171    async fn read_resource(
1172        &self,
1173        request: ReadResourceRequestParams,
1174        ctx: RequestContext<RoleServer>,
1175    ) -> Result<ReadResourceResponse, McpError> {
1176        let uri = request.uri;
1177        match parse_resource_uri(&uri) {
1178            ResourceUriKind::Ports => {
1179                let ports = self.port_provider.list_available().map_err(|e| {
1180                    McpError::internal_error(format!("Failed to list ports: {e}"), None)
1181                })?;
1182                // Same fresh profile-store preview as the `list_ports` tool,
1183                // so the resource and the tool never disagree.
1184                let profiles = self.profile_store.list_fresh().await.map_err(|e| {
1185                    McpError::internal_error(format!("Failed to read profiles: {e}"), None)
1186                })?;
1187                let profile_matches =
1188                    crate::tools::port_ops::compute_profile_matches(&ports, &profiles);
1189                let body = serde_json::to_string_pretty(&ListPortsResult {
1190                    count: ports.len(),
1191                    ports,
1192                    profile_matches,
1193                })
1194                .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
1195                Ok(read_result_with_cache_fields(
1196                    ReadResourceResult::new(vec![
1197                        ResourceContents::text(body, uri).with_mime_type("application/json")
1198                    ]),
1199                    ctx.protocol_version(),
1200                ))
1201            }
1202            ResourceUriKind::ConnectionsList => {
1203                let summaries = self.connections.list_open().await;
1204                let body = serde_json::to_string_pretty(&ConnectionsResource {
1205                    count: summaries.len(),
1206                    connections: summaries,
1207                })
1208                .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
1209                Ok(read_result_with_cache_fields(
1210                    ReadResourceResult::new(vec![
1211                        ResourceContents::text(body, uri).with_mime_type("application/json")
1212                    ]),
1213                    ctx.protocol_version(),
1214                ))
1215            }
1216            ResourceUriKind::ConnectionDetail(id) => {
1217                let conn = self.connections.get(&id).await.map_err(|_| {
1218                    McpError::resource_not_found(
1219                        "connection_not_found",
1220                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
1221                    )
1222                })?;
1223
1224                let body = serde_json::to_string_pretty(&conn.summary())
1225                    .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
1226                Ok(read_result_with_cache_fields(
1227                    ReadResourceResult::new(vec![
1228                        ResourceContents::text(body, uri).with_mime_type("application/json")
1229                    ]),
1230                    ctx.protocol_version(),
1231                ))
1232            }
1233            ResourceUriKind::ConnectionDetailRaw(id) => {
1234                let conn = self.connections.get(&id).await.map_err(|_| {
1235                    McpError::resource_not_found(
1236                        "connection_not_found",
1237                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
1238                    )
1239                })?;
1240                let raw_bytes = conn
1241                    .read_latest(256)
1242                    .await
1243                    .map_err(|e| McpError::internal_error(format!("Failed to read: {e}"), None))?;
1244                let b64 = base64::engine::general_purpose::STANDARD.encode(&raw_bytes);
1245                Ok(read_result_with_cache_fields(
1246                    ReadResourceResult::new(vec![
1247                        ResourceContents::blob(b64, uri).with_mime_type("application/octet-stream")
1248                    ]),
1249                    ctx.protocol_version(),
1250                ))
1251            }
1252            ResourceUriKind::ConnectionLog(id) => {
1253                let conn = self.connections.get(&id).await.map_err(|_| {
1254                    McpError::resource_not_found(
1255                        "connection_not_found",
1256                        Some(serde_json::json!({ "uri": uri, "connection_id": id })),
1257                    )
1258                })?;
1259                let events = conn.log().snapshot();
1260                let mut body = String::new();
1261                for event in &events {
1262                    let line = serde_json::to_string(event)
1263                        .map_err(|e| McpError::internal_error(format!("serialize: {e}"), None))?;
1264                    body.push_str(&line);
1265                    body.push('\n');
1266                }
1267                Ok(read_result_with_cache_fields(
1268                    ReadResourceResult::new(vec![
1269                        ResourceContents::text(body, uri).with_mime_type("application/x-ndjson")
1270                    ]),
1271                    ctx.protocol_version(),
1272                ))
1273            }
1274            ResourceUriKind::Unknown => Err(McpError::resource_not_found(
1275                "resource_not_found",
1276                Some(serde_json::json!({ "uri": uri })),
1277            )),
1278        }
1279    }
1280
1281    async fn complete(
1282        &self,
1283        request: CompleteRequestParams,
1284        _ctx: RequestContext<RoleServer>,
1285    ) -> Result<CompleteResult, McpError> {
1286        let suggestions = self
1287            .get_completions(&request.r#ref, &request.argument)
1288            .await;
1289        let completion = CompletionInfo::with_all_values(suggestions)
1290            .map_err(|e| McpError::internal_error(format!("Completion error: {e}"), None))?;
1291        Ok(CompleteResult::new(completion))
1292    }
1293
1294    // Explicit `tools/list` / `prompts/list` handlers. The
1295    // `#[tool_handler]` macro generates `list_tools` when absent but leaves
1296    // the SEP-2549 cache fields unset, and `#[prompt_handler]` replaces any
1297    // `list_prompts` outright; the explicit versions serve the SAME routers
1298    // (exact deterministic catalog, titles, schemas, prompt definitions)
1299    // with cursor pagination and set `ttlMs: 0` / `cacheScope: "private"`
1300    // only for the exact protocol policy that enables immediate-private
1301    // caching (currently `2026-07-28`).
1302    async fn list_tools(
1303        &self,
1304        request: Option<PaginatedRequestParams>,
1305        ctx: RequestContext<RoleServer>,
1306    ) -> Result<ListToolsResult, McpError> {
1307        const PAGE_SIZE: usize = 100;
1308        let all = Self::tool_router().list_all();
1309        let (tools, next_cursor) = paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
1310        let mut result = ListToolsResult::with_all_items(tools);
1311        result.next_cursor = next_cursor;
1312        if cache_fields_for(ctx.protocol_version()) {
1313            result = result.with_ttl_ms(0).with_cache_scope(CacheScope::Private);
1314        }
1315        Ok(result)
1316    }
1317
1318    /// Route `prompts/get` through the same `prompt_router` the
1319    /// `#[prompt_handler]` macro would use (hand-written because that macro
1320    /// replaces the method unconditionally — see the impl attribute note).
1321    async fn get_prompt(
1322        &self,
1323        request: GetPromptRequestParams,
1324        context: RequestContext<RoleServer>,
1325    ) -> Result<GetPromptResponse, McpError> {
1326        let prompt_context = rmcp::handler::server::prompt::PromptContext::new(
1327            self,
1328            request.name,
1329            request.arguments,
1330            context,
1331        );
1332        Self::prompt_router().get_prompt(prompt_context).await
1333    }
1334
1335    async fn list_prompts(
1336        &self,
1337        request: Option<PaginatedRequestParams>,
1338        ctx: RequestContext<RoleServer>,
1339    ) -> Result<ListPromptsResult, McpError> {
1340        const PAGE_SIZE: usize = 100;
1341        let all = Self::prompt_router().list_all();
1342        let (prompts, next_cursor) = paginate(&all, request.and_then(|r| r.cursor), PAGE_SIZE);
1343        let mut result = ListPromptsResult::with_all_items(prompts);
1344        result.next_cursor = next_cursor;
1345        if cache_fields_for(ctx.protocol_version()) {
1346            result = result.with_ttl_ms(0).with_cache_scope(CacheScope::Private);
1347        }
1348        Ok(result)
1349    }
1350}
1351
1352// ---- Resource URI handling --------------------------------------------------
1353
1354use crate::resources::{
1355    parse_resource_uri, ConnectionsResource, ResourceUriKind, URI_CONNECTIONS,
1356    URI_CONNECTION_LOG_TEMPLATE, URI_CONNECTION_RAW_TEMPLATE, URI_CONNECTION_TEMPLATE, URI_PORTS,
1357};
1358
1359#[cfg(test)]
1360mod tests {
1361    use super::*;
1362
1363    #[test]
1364    fn read_result_with_cache_fields_sets_fields_only_for_modern() {
1365        use rmcp::model::ReadResourceResponse;
1366
1367        let modern = read_result_with_cache_fields(
1368            ReadResourceResult::new(vec![]),
1369            Some(ProtocolVersion::V_2026_07_28),
1370        );
1371        let ReadResourceResponse::Complete(modern) = modern else {
1372            panic!("expected complete read result");
1373        };
1374        assert_eq!(modern.ttl_ms, Some(0), "modern ttlMs must be 0");
1375        assert_eq!(
1376            modern.cache_scope,
1377            Some(CacheScope::Private),
1378            "modern cacheScope must be private"
1379        );
1380
1381        let legacy = read_result_with_cache_fields(
1382            ReadResourceResult::new(vec![]),
1383            Some(ProtocolVersion::V_2025_11_25),
1384        );
1385        let ReadResourceResponse::Complete(legacy) = legacy else {
1386            panic!("expected complete read result");
1387        };
1388        assert_eq!(legacy.ttl_ms, None, "legacy must omit ttlMs");
1389        assert_eq!(legacy.cache_scope, None, "legacy must omit cacheScope");
1390    }
1391
1392    #[test]
1393    fn read_result_with_cache_fields_gives_future_version_no_fields() {
1394        // A custom future version has no policy row, so it must not inherit
1395        // modern cache fields merely because its date sorts after 2026-07-28.
1396        use rmcp::model::ReadResourceResponse;
1397
1398        let future: ProtocolVersion =
1399            serde_json::from_value(serde_json::json!("2099-01-01")).unwrap();
1400        let result = read_result_with_cache_fields(ReadResourceResult::new(vec![]), Some(future));
1401        let ReadResourceResponse::Complete(result) = result else {
1402            panic!("expected complete read result");
1403        };
1404        assert_eq!(result.ttl_ms, None, "future version must omit ttlMs");
1405        assert_eq!(
1406            result.cache_scope, None,
1407            "future version must omit cacheScope"
1408        );
1409    }
1410
1411    #[test]
1412    fn prompt_router_advertises_both_prompts() {
1413        let router = SerialHandler::prompt_router();
1414        assert!(router.has_route("diagnose_port"));
1415        assert!(router.has_route("interactive_terminal"));
1416        assert_eq!(router.list_all().len(), 2);
1417    }
1418
1419    #[test]
1420    fn paginate_handles_offset_past_end_without_panic() {
1421        let items: Vec<i32> = vec![1, 2, 3, 4, 5];
1422
1423        // Normal case: offset 0
1424        let (page, next) = paginate(&items, None, 2);
1425        assert_eq!(page, vec![1, 2]);
1426        assert!(next.is_some());
1427
1428        // Offset at end of items
1429        let cursor = base64::engine::general_purpose::STANDARD.encode("5".as_bytes());
1430        let (page, next) = paginate(&items, Some(cursor), 2);
1431        assert_eq!(page, vec![] as Vec<i32>);
1432        assert!(next.is_none());
1433
1434        // Offset past end (would have panicked before fix)
1435        let cursor = base64::engine::general_purpose::STANDARD.encode("999".as_bytes());
1436        let (page, next) = paginate(&items, Some(cursor), 2);
1437        assert_eq!(page, vec![] as Vec<i32>);
1438        assert!(next.is_none());
1439
1440        // Offset at max usize (would have overflowed before fix)
1441        let cursor = base64::engine::general_purpose::STANDARD.encode(usize::MAX.to_string());
1442        let (page, _next) = paginate(&items, Some(cursor), usize::MAX);
1443        assert_eq!(page, vec![] as Vec<i32>);
1444    }
1445
1446    use crate::buffer_budget::{AtomicBudget, BufferBudget};
1447    use crate::limits::{DEFAULT_MAX_PROGRAM_BUFFERED_BYTES, DEFAULT_MAX_TOOL_BUFFERED_BYTES};
1448    use crate::security::SecurityManager;
1449
1450    /// Assert two `SerialHandler`s have field-for-field equivalent *configuration*.
1451    fn assert_handler_configs_match(a: &SerialHandler, b: &SerialHandler) {
1452        assert_eq!(
1453            a.budget.tool_limit(),
1454            b.budget.tool_limit(),
1455            "budget.tool_limit mismatch"
1456        );
1457        assert_eq!(
1458            a.budget.program_limit(),
1459            b.budget.program_limit(),
1460            "budget.program_limit mismatch"
1461        );
1462        assert_eq!(
1463            a.security.allowlist_summary(),
1464            b.security.allowlist_summary(),
1465            "security summary mismatch"
1466        );
1467    }
1468
1469    #[tokio::test]
1470    async fn builder_default_matches_new_defaults() {
1471        let from_new = SerialHandler::new();
1472        let from_builder = SerialHandler::builder()
1473            .connections(Arc::new(ConnectionManager::new()))
1474            .security(SecurityManager::from_patterns::<[&str; 0]>([]))
1475            .build();
1476
1477        assert_handler_configs_match(&from_new, &from_builder);
1478        assert_eq!(
1479            from_builder.budget.tool_limit(),
1480            DEFAULT_MAX_TOOL_BUFFERED_BYTES
1481        );
1482        assert_eq!(
1483            from_builder.budget.program_limit(),
1484            DEFAULT_MAX_PROGRAM_BUFFERED_BYTES
1485        );
1486    }
1487
1488    #[tokio::test]
1489    async fn builder_custom_budget_overrides_default() {
1490        let budget: Arc<dyn BufferBudget> = Arc::new(AtomicBudget::new(4096, 2048));
1491        let handler = SerialHandler::builder()
1492            .connections(Arc::new(ConnectionManager::new()))
1493            .budget(budget)
1494            .build();
1495        assert_eq!(handler.budget.tool_limit(), 2048);
1496        assert_eq!(handler.budget.program_limit(), 4096);
1497    }
1498    #[tokio::test]
1499    async fn builder_injected_profile_store_is_used() {
1500        let dir = tempfile::tempdir().unwrap();
1501        let path = dir.path().join("profiles.toml");
1502        let store = Arc::new(crate::profile_store::ProfileStore::open(path).unwrap());
1503        let handler = SerialHandler::builder()
1504            .connections(Arc::new(ConnectionManager::new()))
1505            .profile_store(Arc::clone(&store))
1506            .build();
1507        // The injected store (not a fresh empty vector) is the one served.
1508        assert!(Arc::ptr_eq(&handler.profile_store, &store));
1509        assert!(handler.profile_store.list().await.is_empty());
1510
1511        // A mutation through the handler's store is visible via list().
1512        let profile = crate::profiles::Profile {
1513            name: "injected".into(),
1514            selector: Default::default(),
1515            defaults: Default::default(),
1516            metadata: Default::default(),
1517            revisions: Vec::new(),
1518        };
1519        store.upsert(profile, false).await.unwrap();
1520        let listed = handler.profile_store.list().await;
1521        assert_eq!(listed.len(), 1);
1522        assert_eq!(listed[0].name, "injected");
1523    }
1524
1525    #[tokio::test]
1526    async fn builder_default_uses_ephemeral_store() {
1527        let handler = SerialHandler::builder()
1528            .connections(Arc::new(ConnectionManager::new()))
1529            .build();
1530        assert!(
1531            handler.profile_store.path().is_none(),
1532            "builder default must be an ephemeral store"
1533        );
1534    }
1535
1536    // ---- Dual MCP lifecycle -----------------------------------------------
1537
1538    #[tokio::test]
1539    async fn supported_protocol_versions_are_exact_modern_then_legacy() {
1540        let handler = SerialHandler::builder()
1541            .connections(Arc::new(ConnectionManager::new()))
1542            .build();
1543        let versions: Vec<ProtocolVersion> = handler.supported_protocol_versions().to_vec();
1544        assert_eq!(versions.len(), 2, "exactly two supported versions");
1545        assert_eq!(versions[0], ProtocolVersion::V_2026_07_28);
1546        assert_eq!(versions[1], ProtocolVersion::V_2025_11_25);
1547    }
1548
1549    #[test]
1550    fn modern_capability_view_advertises_resource_subscriptions() {
1551        let json = serde_json::to_value(
1552            server_info_for(crate::mcp_protocol::preferred_policy()).capabilities,
1553        )
1554        .unwrap();
1555        assert_eq!(
1556            json,
1557            serde_json::json!({
1558                "completions": {},
1559                "prompts": {},
1560                "resources": {"subscribe": true},
1561                "tools": {},
1562            }),
1563            "preferred discovery view must advertise resource subscriptions"
1564        );
1565    }
1566
1567    #[test]
1568    fn legacy_capability_view_keeps_subscription_disabled() {
1569        let legacy_policy = crate::mcp_protocol::policy_for(&ProtocolVersion::V_2025_11_25)
1570            .expect("legacy policy row must exist");
1571        let json = serde_json::to_value(server_info_for(legacy_policy).capabilities).unwrap();
1572        assert_eq!(
1573            json,
1574            serde_json::json!({
1575                "completions": {},
1576                "prompts": {},
1577                "resources": {},
1578                "tools": {},
1579            }),
1580            "legacy initialize view must keep resource subscriptions disabled"
1581        );
1582    }
1583
1584    #[test]
1585    fn capability_views_omit_logging_list_change_and_tasks() {
1586        let legacy_policy = crate::mcp_protocol::policy_for(&ProtocolVersion::V_2025_11_25)
1587            .expect("legacy policy row must exist");
1588        for capabilities in [
1589            server_info_for(crate::mcp_protocol::preferred_policy()).capabilities,
1590            server_info_for(legacy_policy).capabilities,
1591        ] {
1592            let json = serde_json::to_value(&capabilities).unwrap();
1593            let object = json.as_object().expect("capabilities serialize as object");
1594            for forbidden in [
1595                "logging",
1596                "experimental",
1597                "extensions",
1598                "roots",
1599                "sampling",
1600                "elicitation",
1601            ] {
1602                assert!(
1603                    !object.contains_key(forbidden),
1604                    "capability view must not advertise `{forbidden}`: {json}"
1605                );
1606            }
1607            // tools/prompts advertise no list-change flags.
1608            assert_eq!(object["tools"], serde_json::json!({}));
1609            assert_eq!(object["prompts"], serde_json::json!({}));
1610        }
1611        // resources: preferred carries only `subscribe`, legacy only nothing —
1612        // neither advertises `listChanged`.
1613        let modern = serde_json::to_value(
1614            server_info_for(crate::mcp_protocol::preferred_policy()).capabilities,
1615        )
1616        .unwrap();
1617        assert_eq!(modern["resources"], serde_json::json!({"subscribe": true}));
1618        let legacy = serde_json::to_value(server_info_for(legacy_policy).capabilities).unwrap();
1619        assert_eq!(legacy["resources"], serde_json::json!({}));
1620    }
1621
1622    #[test]
1623    fn policy_infos_carry_their_own_protocol_version() {
1624        let legacy_policy = crate::mcp_protocol::policy_for(&ProtocolVersion::V_2025_11_25)
1625            .expect("legacy policy row must exist");
1626        assert_eq!(
1627            server_info_for(legacy_policy).protocol_version,
1628            ProtocolVersion::V_2025_11_25
1629        );
1630        assert_eq!(
1631            server_info_for(crate::mcp_protocol::preferred_policy()).protocol_version,
1632            ProtocolVersion::V_2026_07_28
1633        );
1634    }
1635
1636    #[tokio::test]
1637    async fn get_info_returns_modern_view_for_listen_intersection() {
1638        // rmcp intersects `subscriptions/listen` filters against
1639        // `get_info().capabilities`; the modern listen lifecycle requires the
1640        // modern view there while `initialize()` returns the legacy view.
1641        let handler = SerialHandler::builder()
1642            .connections(Arc::new(ConnectionManager::new()))
1643            .build();
1644        assert_eq!(
1645            serde_json::to_value(handler.get_info().capabilities).unwrap(),
1646            serde_json::json!({
1647                "completions": {},
1648                "prompts": {},
1649                "resources": {"subscribe": true},
1650                "tools": {},
1651            })
1652        );
1653        assert_eq!(
1654            handler.get_info().protocol_version,
1655            ProtocolVersion::V_2026_07_28
1656        );
1657    }
1658
1659    #[tokio::test]
1660    async fn accepted_subscription_filter_keeps_valid_dedup_and_strips_unsupported() {
1661        let handler = SerialHandler::builder()
1662            .connections(Arc::new(ConnectionManager::new()))
1663            .build();
1664        let requested = SubscriptionFilter::builder()
1665            .resource_subscriptions([
1666                "serial://ports",
1667                "serial://connections",
1668                "serial://ports", // duplicate — first order preserved
1669                "serial://connections/abc-123",
1670                "serial://connections/{id}", // template -> stripped
1671                "serial://connections/",     // empty id -> stripped
1672                "https://example.com/x",     // unknown scheme -> stripped
1673            ])
1674            .tools_list_changed()
1675            .prompts_list_changed()
1676            .resources_list_changed()
1677            .build();
1678        let accepted = handler
1679            .accepted_subscription_filter(&requested)
1680            .expect("handler always available");
1681        assert_eq!(
1682            accepted.resource_subscriptions.as_deref(),
1683            Some(
1684                [
1685                    "serial://ports".to_string(),
1686                    "serial://connections".to_string(),
1687                    "serial://connections/abc-123".to_string(),
1688                ]
1689                .as_slice()
1690            ),
1691            "valid + deduplicated URIs in first-request order"
1692        );
1693        assert!(
1694            accepted.tools_list_changed.is_none()
1695                && accepted.prompts_list_changed.is_none()
1696                && accepted.resources_list_changed.is_none(),
1697            "all list-change flags must be stripped"
1698        );
1699    }
1700
1701    #[tokio::test]
1702    async fn accepted_subscription_filter_empty_accepted_resources_is_none_not_fake_uri() {
1703        let handler = SerialHandler::builder()
1704            .connections(Arc::new(ConnectionManager::new()))
1705            .build();
1706        // Everything invalid -> accepted resource list is None.
1707        let requested = SubscriptionFilter::builder()
1708            .resource_subscriptions(["serial://connections/{id}", "https://example.com/x"])
1709            .build();
1710        let accepted = handler
1711            .accepted_subscription_filter(&requested)
1712            .expect("handler always available");
1713        assert!(accepted.resource_subscriptions.is_none());
1714
1715        // Nothing requested at all -> same empty accepted filter, and the
1716        // handler stays available (Some).
1717        let accepted_empty = handler
1718            .accepted_subscription_filter(&SubscriptionFilter::new())
1719            .expect("handler always available");
1720        assert!(accepted_empty.resource_subscriptions.is_none());
1721        assert!(
1722            accepted_empty.tools_list_changed.is_none()
1723                && accepted_empty.prompts_list_changed.is_none()
1724                && accepted_empty.resources_list_changed.is_none()
1725        );
1726    }
1727}