//! 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());
}
}