use crate::capture::LineSelection;
use crate::config::Config;
use crate::executor;
use crate::redaction::{
ManualRedactionSpec, ManualRedactions, REDACTION_DISABLED_MSG, RedactionEngine, RedactionMap,
explicit_request_is_blocked, resolve_should_redact,
};
use crate::renderer::{
ChromeOptions, ComposeLayout, ExtendedRenderOptions, RedactionRequest, RenderContext, Renderer,
TextOptions, fallback_output_name,
};
use rmcp::{
ErrorData as McpError, ServerHandler, handler::server::router::tool::ToolRouter,
handler::server::wrapper::Parameters, model::*, schemars, service::ServiceExt, tool,
tool_handler, tool_router, transport::io::stdio,
};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ExecuteAndScreenshotParams {
pub command: String,
#[serde(default)]
pub cols: Option<u16>,
#[serde(default)]
pub rows: Option<u16>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub show_prompt: Option<bool>,
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub commands: Option<Vec<String>>,
#[serde(default)]
pub chrome: Option<String>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub timestamp: Option<bool>,
#[serde(default)]
pub rounded: Option<bool>,
#[serde(default)]
pub redact: Option<bool>,
#[serde(default)]
pub redaction_rules: Option<Vec<String>>,
#[serde(default)]
pub redactions: Option<Vec<ManualRedactionSpec>>,
#[serde(default)]
pub redact_text: Option<bool>,
#[serde(default)]
pub show_labels: Option<bool>,
#[serde(default)]
pub strip_ansi: Option<bool>,
#[serde(default)]
pub output_name: Option<String>,
#[serde(default)]
pub auto_crop: Option<bool>,
#[serde(default)]
pub head_lines: Option<usize>,
#[serde(default)]
pub tail_lines: Option<usize>,
}
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ExecuteAndScreenshotRequest {
#[serde(default)]
pub command: Option<String>,
#[serde(default)]
pub commands: Option<Vec<String>>,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default)]
pub cols: Option<u16>,
#[serde(default)]
pub rows: Option<u16>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub show_prompt: Option<bool>,
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub chrome: Option<String>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub timestamp: Option<bool>,
#[serde(default)]
pub rounded: Option<bool>,
#[serde(default)]
pub redact: Option<bool>,
#[serde(default)]
pub redaction_rules: Option<Vec<String>>,
#[serde(default)]
pub redactions: Option<Vec<ManualRedactionSpec>>,
#[serde(default)]
pub redact_text: Option<bool>,
#[serde(default)]
pub show_labels: Option<bool>,
#[serde(default)]
pub strip_ansi: Option<bool>,
#[serde(default)]
pub output_name: Option<String>,
#[serde(default)]
pub auto_crop: Option<bool>,
#[serde(default)]
pub head_lines: Option<usize>,
#[serde(default)]
pub tail_lines: Option<usize>,
}
impl From<ExecuteAndScreenshotParams> for ExecuteAndScreenshotRequest {
fn from(params: ExecuteAndScreenshotParams) -> Self {
let command = params.commands.is_none().then_some(params.command);
Self {
command,
commands: params.commands,
cwd: None,
cols: params.cols,
rows: params.rows,
timeout_secs: params.timeout_secs,
show_prompt: params.show_prompt,
theme: params.theme,
chrome: params.chrome,
title: params.title,
timestamp: params.timestamp,
rounded: params.rounded,
redact: params.redact,
redaction_rules: params.redaction_rules,
redactions: params.redactions,
redact_text: params.redact_text,
show_labels: params.show_labels,
strip_ansi: params.strip_ansi,
output_name: params.output_name,
auto_crop: params.auto_crop,
head_lines: params.head_lines,
tail_lines: params.tail_lines,
}
}
}
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RenderAnsiParams {
pub input_path: String,
#[serde(default)]
pub cols: Option<u16>,
#[serde(default)]
pub rows: Option<u16>,
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub chrome: Option<String>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub timestamp: Option<bool>,
#[serde(default)]
pub rounded: Option<bool>,
#[serde(default)]
pub strip_ansi: Option<bool>,
#[serde(default)]
pub output_name: Option<String>,
#[serde(default)]
pub auto_crop: Option<bool>,
#[serde(default)]
pub redact: Option<bool>,
#[serde(default)]
pub redaction_rules: Option<Vec<String>>,
#[serde(default)]
pub redactions: Option<Vec<ManualRedactionSpec>>,
#[serde(default)]
pub redact_text: Option<bool>,
#[serde(default)]
pub show_labels: Option<bool>,
#[serde(default)]
pub head_lines: Option<usize>,
#[serde(default)]
pub tail_lines: Option<usize>,
}
#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum RedactionSpec {
Pattern {
pattern: String,
#[serde(default)]
replacement: Option<String>,
#[serde(default)]
keep_prefix: Option<usize>,
#[serde(default)]
keep_suffix: Option<usize>,
},
Coordinate {
row: u16,
col_start: u16,
col_end: u16,
#[serde(default)]
label: Option<String>,
},
}
impl From<RedactionSpec> for ManualRedactionSpec {
fn from(spec: RedactionSpec) -> Self {
match spec {
RedactionSpec::Pattern {
pattern,
replacement,
keep_prefix,
keep_suffix,
} => ManualRedactionSpec::Pattern {
pattern,
replacement,
keep_prefix,
keep_suffix,
color: None,
},
RedactionSpec::Coordinate {
row,
col_start,
col_end,
label,
} => ManualRedactionSpec::Coordinate {
row,
col_start,
col_end,
label,
color: None,
},
}
}
}
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RedactScreenshotParams {
pub screenshot_path: String,
pub redactions: Vec<RedactionSpec>,
#[serde(default)]
pub redact_text: Option<bool>,
#[serde(default)]
pub show_labels: Option<bool>,
#[serde(default)]
pub strip_ansi: Option<bool>,
}
impl RedactScreenshotParams {
pub fn into_request(self) -> RedactScreenshotRequest {
self.into()
}
}
impl From<RedactScreenshotParams> for RedactScreenshotRequest {
fn from(params: RedactScreenshotParams) -> Self {
Self {
screenshot_path: params.screenshot_path,
redactions: params
.redactions
.into_iter()
.map(ManualRedactionSpec::from)
.collect(),
redact_text: params.redact_text,
show_labels: params.show_labels,
strip_ansi: params.strip_ansi,
}
}
}
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RedactScreenshotRequest {
pub screenshot_path: String,
pub redactions: Vec<ManualRedactionSpec>,
#[serde(default)]
pub redact_text: Option<bool>,
#[serde(default)]
pub show_labels: Option<bool>,
#[serde(default)]
pub strip_ansi: Option<bool>,
}
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ComposeScreenshotsParams {
pub paths: Vec<String>,
#[serde(default)]
pub layout: Option<String>,
#[serde(default)]
pub divider: Option<u32>,
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub chrome: Option<String>,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub output: Option<String>,
}
#[derive(Clone)]
struct CachedRender {
data: Vec<u8>,
context: RenderContext,
serial: u64,
}
const MAX_CACHE_ENTRIES: usize = 32;
const MAX_CACHE_BYTES: usize = 32 * 1024 * 1024;
fn cache_key(path: &Path) -> String {
std::fs::canonicalize(path)
.unwrap_or_else(|_| path.to_path_buf())
.display()
.to_string()
}
fn evict_cache(cache: &mut HashMap<String, CachedRender>) {
let over_budget = |cache: &HashMap<String, CachedRender>| {
cache.len() > MAX_CACHE_ENTRIES
|| cache.values().map(|c| c.data.len()).sum::<usize>() > MAX_CACHE_BYTES
};
while over_budget(cache) && cache.len() > 1 {
let oldest = cache
.iter()
.min_by_key(|(_, c)| c.serial)
.map(|(k, _)| k.clone());
match oldest {
Some(key) => {
cache.remove(&key);
}
None => break,
}
}
}
#[derive(Clone)]
pub struct ScreenshotServer {
config: Arc<Config>,
renderer: Arc<Renderer>,
render_cache: Arc<Mutex<HashMap<String, CachedRender>>>,
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl ScreenshotServer {
pub fn new(config: Config, renderer: Renderer) -> Self {
Self {
config: Arc::new(config),
renderer: Arc::new(renderer),
render_cache: Arc::new(Mutex::new(HashMap::new())),
tool_router: Self::tool_router(),
}
}
fn remember_render(&self, path: &Path, data: &[u8], context: RenderContext) {
let mut cache = match self.render_cache.lock() {
Ok(cache) => cache,
Err(_) => {
tracing::warn!("Render cache lock poisoned; screenshot will not be re-renderable");
return;
}
};
let key = cache_key(path);
let serial = cache.values().map(|c| c.serial).max().unwrap_or(0) + 1;
cache.insert(
key,
CachedRender {
data: data.to_vec(),
context,
serial,
},
);
evict_cache(&mut cache);
}
fn resolve_redaction(
&self,
redact: Option<bool>,
rules: Option<&Vec<String>>,
show_labels: bool,
) -> Result<Option<RedactionEngine>, McpError> {
let redact_flag = redact == Some(true) || rules.is_some();
let no_redact_flag = redact == Some(false);
if explicit_request_is_blocked(&self.config.redaction, redact_flag, no_redact_flag) {
return Err(McpError::invalid_params(
REDACTION_DISABLED_MSG.to_string(),
None,
));
}
if !resolve_should_redact(&self.config.redaction, redact_flag, no_redact_flag) {
return Ok(None);
}
match RedactionEngine::from_config_with_labels(&self.config.redaction, show_labels) {
Ok(engine) => {
if let Some(rules) = rules {
engine
.validate_rule_names(rules)
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
}
Ok(Some(engine))
}
Err(e) if redact_flag => Err(McpError::internal_error(
format!("redaction was requested but could not be enabled: {}", e),
None,
)),
Err(e) => {
tracing::warn!("Auto-redaction disabled: {}", e);
Ok(None)
}
}
}
#[tool(name = "execute_and_screenshot")]
pub async fn execute_and_screenshot_tool(
&self,
Parameters(params): Parameters<ExecuteAndScreenshotRequest>,
) -> Result<CallToolResult, McpError> {
self.execute_and_screenshot_impl(params).await
}
pub async fn execute_and_screenshot(
&self,
Parameters(params): Parameters<ExecuteAndScreenshotParams>,
) -> Result<CallToolResult, McpError> {
self.execute_and_screenshot_impl(params.into()).await
}
async fn execute_and_screenshot_impl(
&self,
params: ExecuteAndScreenshotRequest,
) -> Result<CallToolResult, McpError> {
let cols = params.cols.unwrap_or(self.config.default_cols);
let rows = params.rows.unwrap_or(self.config.default_rows);
validate_dimensions(cols, rows)?;
let timeout = Duration::from_secs(
params
.timeout_secs
.unwrap_or(self.config.default_timeout_secs),
);
let lines = line_selection(params.head_lines, params.tail_lines)?;
let show_labels = params.show_labels.unwrap_or(true);
let manual = manual_redactions(params.redactions.as_deref(), params.redact, show_labels)?;
let show_prompt = params.show_prompt.unwrap_or(true);
let commands = request_commands(params.command, params.commands)?;
let working_dir = params
.cwd
.as_deref()
.map(|path| executor::resolve_working_directory(Path::new(path)))
.transpose()
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let command_refs: Vec<&str> = commands.iter().map(|s| s.as_str()).collect();
let chrome_options = chrome_options_from_params(
&self.config,
params.chrome,
params.title,
params.timestamp,
params.rounded,
commands.first().map(String::as_str),
);
let result = if show_prompt {
executor::execute_command_in_dir(
&command_refs,
&self.config.shell,
rows,
cols,
timeout,
working_dir.as_deref(),
)
.await
} else {
executor::execute_command_simple_in_dir(
&commands.join("\n"),
&self.config.shell,
rows,
cols,
timeout,
working_dir.as_deref(),
)
.await
};
let exec_result = result.map_err(|e| {
McpError::internal_error(format!("Command execution failed: {}", e), None)
})?;
let theme_name = params.theme.as_deref();
let redaction_engine =
self.resolve_redaction(params.redact, params.redaction_rules.as_ref(), show_labels)?;
let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
engine,
rules: params.redaction_rules.clone(),
});
let text_options = TextOptions {
strip_ansi: params.strip_ansi.unwrap_or(false),
redact_text: params.redact_text.unwrap_or(false),
embed_description: self.config.embed_description,
from_screen: show_prompt,
};
let output_name = params.output_name.clone().unwrap_or_else(|| {
let fallback_dir = working_dir
.as_deref()
.map(std::path::PathBuf::from)
.or_else(|| std::env::current_dir().ok());
fallback_output_name(fallback_dir.as_deref(), &commands.join(" "))
});
let (image_path, plain_text, redactions, context) = self
.renderer
.render_bytes_with_extended_options(
&exec_result.raw_output,
cols,
rows,
&self.config.output_dir,
Some(output_name.as_str()),
theme_name,
chrome_options.as_ref(),
redaction_request.as_ref(),
text_options,
params.auto_crop.unwrap_or(true),
ExtendedRenderOptions::default()
.with_lines(lines)
.with_optional_manual(manual.as_ref()),
)
.map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;
let truncated = context.truncated;
self.remember_render(&image_path, &exec_result.raw_output, context);
let exit_info = if exec_result.timed_out {
"TIMED OUT".to_string()
} else {
match exec_result.exit_code {
Some(code) => format!("exit code: {}", code),
None => "exit code: unknown".to_string(),
}
};
let mut content = vec![
ContentBlock::text(format!("Screenshot saved to: {}", image_path.display())),
ContentBlock::text(format!("Status: {}", exit_info)),
];
if !redactions.is_empty() {
let summary = redactions
.iter()
.map(|(name, count)| format!("{}x {}", count, name))
.collect::<Vec<_>>()
.join(", ");
content.push(ContentBlock::text(format!("Redacted: {}", summary)));
}
if truncated {
content.push(ContentBlock::text(truncation_notice(
self.renderer.effective_scrollback_lines(rows, cols),
)));
}
content.push(ContentBlock::text(format!(
"--- Terminal Output ---\n{}",
plain_text
)));
Ok(CallToolResult::success(content))
}
#[tool(name = "render_ansi")]
pub async fn render_ansi(
&self,
Parameters(params): Parameters<RenderAnsiParams>,
) -> Result<CallToolResult, McpError> {
let cols = params.cols.unwrap_or(self.config.default_cols);
let rows = params.rows.unwrap_or(self.config.default_rows);
validate_dimensions(cols, rows)?;
let lines = line_selection(params.head_lines, params.tail_lines)?;
let show_labels = params.show_labels.unwrap_or(true);
let manual = manual_redactions(params.redactions.as_deref(), params.redact, show_labels)?;
let theme_name = params.theme.as_deref();
let chrome_options = chrome_options_from_params(
&self.config,
params.chrome,
params.title,
params.timestamp,
params.rounded,
None,
);
let data = std::fs::read(¶ms.input_path).map_err(|e| {
McpError::internal_error(
format!("Failed to read file '{}': {}", params.input_path, e),
None,
)
})?;
let output_name = params.output_name.clone().or_else(|| {
std::path::Path::new(¶ms.input_path)
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
});
let redaction_engine =
self.resolve_redaction(params.redact, params.redaction_rules.as_ref(), show_labels)?;
let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
engine,
rules: params.redaction_rules.clone(),
});
let (image_path, plain_text, redactions, context) = self
.renderer
.render_bytes_with_extended_options(
&data,
cols,
rows,
&self.config.output_dir,
output_name.as_deref(),
theme_name,
chrome_options.as_ref(),
redaction_request.as_ref(),
TextOptions {
strip_ansi: params.strip_ansi.unwrap_or(false),
redact_text: params.redact_text.unwrap_or(false),
embed_description: self.config.embed_description,
from_screen: false,
},
params.auto_crop.unwrap_or(true),
ExtendedRenderOptions::default()
.with_lines(lines)
.with_optional_manual(manual.as_ref()),
)
.map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;
let truncated = context.truncated;
self.remember_render(&image_path, &data, context);
let mut content = vec![ContentBlock::text(format!(
"Screenshot saved to: {}",
image_path.display()
))];
if !redactions.is_empty() {
let summary = redactions
.iter()
.map(|(name, count)| format!("{}x {}", count, name))
.collect::<Vec<_>>()
.join(", ");
content.push(ContentBlock::text(format!("Redacted: {}", summary)));
}
if truncated {
content.push(ContentBlock::text(truncation_notice(
self.renderer.effective_scrollback_lines(rows, cols),
)));
}
content.push(ContentBlock::text(format!(
"--- Terminal Output ---\n{}",
plain_text
)));
Ok(CallToolResult::success(content))
}
#[tool(name = "redact_screenshot")]
pub async fn redact_screenshot_tool(
&self,
Parameters(params): Parameters<RedactScreenshotRequest>,
) -> Result<CallToolResult, McpError> {
self.redact_screenshot_impl(params).await
}
pub async fn redact_screenshot(
&self,
Parameters(params): Parameters<RedactScreenshotParams>,
) -> Result<CallToolResult, McpError> {
self.redact_screenshot_impl(params.into()).await
}
async fn redact_screenshot_impl(
&self,
params: RedactScreenshotRequest,
) -> Result<CallToolResult, McpError> {
let png_path = std::path::PathBuf::from(¶ms.screenshot_path);
let key = cache_key(&png_path);
let cached = {
let cache = self.render_cache.lock().map_err(|_| {
McpError::internal_error("Render cache lock poisoned".to_string(), None)
})?;
cache.get(&key).cloned()
};
let CachedRender { data, context, .. } = cached.ok_or_else(|| {
McpError::invalid_params(
format!(
"No in-memory record for screenshot '{}'. It must have been produced \
by this server instance in the current session (records are lost on \
restart and are not created by the CLI).",
key
),
None,
)
})?;
let show_labels = params.show_labels.unwrap_or(true);
let manual = ManualRedactions::new(¶ms.redactions, show_labels)
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let screen = self.renderer.capture_for(&data, &context);
let (rendered_rows, rendered_cols) = self.renderer.rendered_bounds_for(&screen, &context);
manual
.validate_bounds(rendered_rows, rendered_cols)
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let mut map = RedactionMap::default();
manual.apply_to(&screen, &mut map);
drop(screen);
let (plain_text, audit) = self
.renderer
.render_redaction_to_with_context(
&data,
&context,
&map,
&png_path,
TextOptions {
strip_ansi: params.strip_ansi.unwrap_or(false),
redact_text: params.redact_text.unwrap_or(false),
embed_description: self.config.embed_description,
from_screen: context.meta.from_screen,
},
)
.map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;
let mut content = vec![ContentBlock::text(format!(
"Redacted screenshot saved to: {}",
png_path.display()
))];
if !audit.is_empty() {
let summary = audit
.iter()
.map(|(name, count)| format!("{}x {}", count, name))
.collect::<Vec<_>>()
.join(", ");
content.push(ContentBlock::text(format!("Redacted: {}", summary)));
}
content.push(ContentBlock::text(format!(
"--- Terminal Output ---\n{}",
plain_text
)));
Ok(CallToolResult::success(content))
}
#[tool(name = "compose_screenshots")]
pub async fn compose_screenshots(
&self,
Parameters(params): Parameters<ComposeScreenshotsParams>,
) -> Result<CallToolResult, McpError> {
if params.paths.len() < 2 {
return Err(McpError::invalid_params(
"compose_screenshots requires at least two image paths".to_string(),
None,
));
}
let layout = ComposeLayout::parse(params.layout.as_deref().unwrap_or("vertical"))
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
let divider = params.divider.unwrap_or(2);
let paths: Vec<std::path::PathBuf> =
params.paths.iter().map(std::path::PathBuf::from).collect();
let output = params.output.as_ref().map(std::path::PathBuf::from);
let chrome_options =
chrome_options_from_params(&self.config, params.chrome, params.title, None, None, None);
let path = self
.renderer
.compose_screenshots(
&paths,
layout,
divider,
params.theme.as_deref(),
chrome_options.as_ref(),
&self.config.output_dir,
output.as_deref(),
self.config.embed_description,
)
.map_err(|e| McpError::internal_error(format!("Compose failed: {}", e), None))?;
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"Composed screenshot saved to: {}",
path.display()
))]))
}
}
impl ScreenshotServer {
pub fn tool_definitions() -> Vec<Tool> {
Self::tool_router().list_all()
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for ScreenshotServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::from_build_env())
.with_instructions(
"Terminal screenshot MCP server. Use execute_and_screenshot to run \
commands and capture PNG screenshots of the terminal output, including \
the user's real shell prompt before each command, colors, and full ANSI \
rendering; the final prompt is removed automatically. Set its \
`cwd` when directory context belongs in the screenshot; if the path is \
incidental, use a short staging directory or hide the prompt. Never \
print or synthesize a prompt in the command. Use render_ansi to render \
previously captured terminal output from a file. Both take an optional \
`redactions` list (regex patterns and/or cell ranges) to mask sensitive \
data as the image is rendered. Use redact_screenshot \
to selectively redact an existing screenshot by regex pattern or cell \
coordinates (run execute_and_screenshot first without redaction, inspect \
the plain text, then redact what is sensitive). Use compose_screenshots \
to place two or more screenshots side by side or stacked into one image.",
)
}
}
pub async fn run_mcp_server(config: Config, renderer: Renderer) -> anyhow::Result<()> {
tracing::info!("Starting termshot MCP server (stdio transport)");
let server = ScreenshotServer::new(config, renderer);
let service = server.serve(stdio()).await?;
service.waiting().await?;
Ok(())
}
fn request_commands(
command: Option<String>,
commands: Option<Vec<String>>,
) -> Result<Vec<String>, McpError> {
let resolved = match (command, commands) {
(Some(_), Some(commands)) => commands,
(Some(command), None) => vec![command],
(None, Some(commands)) => commands,
(None, None) => {
return Err(McpError::invalid_params(
"Missing command: pass `command` or a non-empty `commands` list.".to_string(),
None,
));
}
};
if resolved.is_empty() || resolved.iter().any(|command| command.trim().is_empty()) {
return Err(McpError::invalid_params(
"`command` and every entry in `commands` must contain a shell command.".to_string(),
None,
));
}
Ok(resolved)
}
fn line_selection(head: Option<usize>, tail: Option<usize>) -> Result<LineSelection, McpError> {
LineSelection::from_head_tail(head, tail)
.map_err(|e| McpError::invalid_params(e.to_string(), None))
}
const MANUAL_REDACTION_CONFLICT_MSG: &str = "`redactions` conflicts with `redact: false`: the request asks for manual masking \
and for redaction to be off at once. Drop `redact` (manual redactions apply on \
their own) or drop `redactions`. This mirrors the CLI, where `--redaction` \
conflicts with `--no-redact`.";
fn manual_redactions(
specs: Option<&[ManualRedactionSpec]>,
redact: Option<bool>,
show_labels: bool,
) -> Result<Option<ManualRedactions>, McpError> {
let specs = match specs {
Some(specs) if !specs.is_empty() => specs,
_ => return Ok(None),
};
if redact == Some(false) {
return Err(McpError::invalid_params(
MANUAL_REDACTION_CONFLICT_MSG.to_string(),
None,
));
}
ManualRedactions::new(specs, show_labels)
.map(Some)
.map_err(|e| McpError::invalid_params(e.to_string(), None))
}
fn truncation_notice(effective_lines: usize) -> String {
format!(
"Warning: output exceeded the {}-line scrollback, so the oldest lines were dropped \
before rendering. Raise `max_scrollback_lines` in the server config to keep more \
(a wide terminal caps it), or pass head_lines/tail_lines to select one end.",
effective_lines
)
}
const MIN_DIM: u16 = 1;
const MAX_DIM: u16 = 500;
fn validate_dimensions(cols: u16, rows: u16) -> Result<(), McpError> {
for (label, value) in [("cols", cols), ("rows", rows)] {
if !(MIN_DIM..=MAX_DIM).contains(&value) {
return Err(McpError::invalid_params(
format!(
"{} must be between {} and {} (got {})",
label, MIN_DIM, MAX_DIM, value
),
None,
));
}
}
Ok(())
}
fn chrome_options_from_params(
config: &Config,
chrome: Option<String>,
title: Option<String>,
timestamp: Option<bool>,
rounded: Option<bool>,
inferred_title: Option<&str>,
) -> Option<ChromeOptions> {
let has_overrides =
chrome.is_some() || title.is_some() || timestamp.is_some() || rounded.is_some();
let mut options = ChromeOptions::from_config(&config.chrome);
if let Some(preset) = chrome {
options.enabled = preset != "none";
options.preset = preset;
}
if let Some(title) = title {
options.title = Some(title);
} else if options.enabled {
options.title = inferred_title.map(str::to_owned);
}
if let Some(timestamp) = timestamp {
options.timestamp = timestamp;
}
if let Some(rounded) = rounded {
options.rounded = rounded;
}
if !(has_overrides || options.enabled && inferred_title.is_some()) {
return None;
}
Some(options)
}