Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp): cap tool-result size before it enters conversation history
thinhlpg2629cbf0df73
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 4735fcbff..c03f96f81 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -26,6 +26,7 @@ use crate::core::server::proxy::router_upstream;use crate::core::server::MlxBackendSession;use crate::core::{mcp::models::McpSettings,+ mcp::truncate::truncate_tool_result,state::{ProviderConfig, SharedMcpServers},};@@ -506,7 +507,13 @@ pub(crate) async fn execute_mcp_tool_calls(mcp_servers: &SharedMcpServers,mcp_settings: &Arc<Mutex<McpSettings>>,) -> Vec<(String, String)> {- let timeout_duration = mcp_settings.lock().await.tool_call_timeout_duration();+ let (timeout_duration, tool_output_cap) = {+ let settings = mcp_settings.lock().await;+ (+ settings.tool_call_timeout_duration(),+ settings.tool_output_cap(None),+ )+ };let servers = mcp_servers.lock().await;let mut results = Vec::with_capacity(tool_calls.len());@@ -570,7 +577,9 @@ pub(crate) async fn execute_mcp_tool_calls(};let tool_result_string = match result {- Ok(res) => mcp_call_result_to_string(&res),+ // Same cap as the desktop path: this string is appended to the agent's+ // message history, so an unbounded result would blow the context here too.+ Ok(res) => mcp_call_result_to_string(&truncate_tool_result(&res, tool_output_cap)),Err(e) => format!("ERROR: {e}"),};diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex 9413d5fd2..70b36fdb4 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -8,6 +8,7 @@ use tokio::time::timeout;use super::{constants::DEFAULT_MCP_CONFIG,helpers::{restart_active_mcp_servers, start_mcp_server, terminate_browser_mcp},+ truncate::truncate_tool_result,};use crate::core::{app::commands::get_jan_data_folder_path,@@ -389,6 +390,9 @@ pub async fn get_server_summaries(/// * `server_name` - Optional name of the server to call the tool from (for disambiguation)/// * `arguments` - Optional map of argument names to values/// * `cancellation_token` - Optional token to allow cancellation from JS side+/// * `max_output_chars` - Optional caller-derived per-result character budget+/// (the desktop chat derives one from the active model's context window);+/// combined with the `maxToolOutputChars` setting, tighter wins////// # Returns/// * `Result<CallToolResult, String>` - Result of the tool call if successful, or error message if failed@@ -407,8 +411,15 @@ pub async fn call_tool(server_name: Option<String>,arguments: Option<Map<String, Value>>,cancellation_token: Option<String>,+ max_output_chars: Option<u64>,) -> Result<CallToolResult, String> {- let timeout_duration = tool_call_timeout(&state).await;+ let (timeout_duration, tool_output_cap) = {+ let settings = state.mcp_settings.lock().await;+ (+ settings.tool_call_timeout_duration(),+ settings.tool_output_cap(max_output_chars),+ )+ };// Set up cancellation if token is providedlet (cancel_tx, cancel_rx) = oneshot::channel::<()>();@@ -508,7 +519,10 @@ pub async fn call_tool(}cleanup_cancellation_token(&state, &cancellation_token).await;- return result;+ // Cap here rather than at each caller: this is the single point every+ // desktop MCP tool result passes through on its way into conversation+ // history, so an unbounded result can never reach the model.+ return result.map(|res| truncate_tool_result(&res, tool_output_cap));}// No server had the tool — check if it's because of transport errorsdiff --git a/src-tauri/src/core/mcp/constants.rs b/src-tauri/src/core/mcp/constants.rsindex 55941f379..0a16efe81 100644--- a/src-tauri/src/core/mcp/constants.rs+++ b/src-tauri/src/core/mcp/constants.rs@@ -1,6 +1,13 @@// Default MCP runtime settingspub const DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS: u64 = 30;+/// Per-tool-result character cap applied before the result enters conversation+/// history. A single unbounded result (a full browser page snapshot, say) can+/// otherwise consume the whole model context. Roughly 12k tokens at ~3.5+/// chars/token: large enough for a real page, small enough to leave room for+/// the conversation. `0` disables the cap.+pub const DEFAULT_MCP_MAX_TOOL_OUTPUT_CHARS: u64 = 40_000;+// Browser MCP teardown: how long to wait for the port to free, and the poll cadence.pub const MCP_PORT_FREE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2000);pub const MCP_PORT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);@@ -63,6 +70,7 @@ pub const DEFAULT_MCP_CONFIG: &str = r#"{"enableSmartToolRouting": true,"useLightweightRouterModel": false,"routerModelProvider": "",- "routerModelId": ""+ "routerModelId": "",+ "maxToolOutputChars": 40000}}"#;diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rsindex 7e28ea4a0..a6f1060da 100644--- a/src-tauri/src/core/mcp/mod.rs+++ b/src-tauri/src/core/mcp/mod.rs@@ -13,6 +13,7 @@ pub mod models;pub mod oauth;#[cfg(not(feature = "cli"))]pub mod progress;+pub mod truncate;#[cfg(test)]#[cfg(not(feature = "cli"))]diff --git a/src-tauri/src/core/mcp/models.rs b/src-tauri/src/core/mcp/models.rsindex 2326b2b2c..9bd4a9c39 100644--- a/src-tauri/src/core/mcp/models.rs+++ b/src-tauri/src/core/mcp/models.rs@@ -85,6 +85,10 @@ fn default_router_model_id() -> String {String::new()}+fn default_max_tool_output_chars() -> u64 {+ super::constants::DEFAULT_MCP_MAX_TOOL_OUTPUT_CHARS+}+/// Runtime MCP settings that can be adjusted via UI#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -105,6 +109,9 @@ pub struct McpSettings {pub router_model_provider: String,#[serde(default = "default_router_model_id")]pub router_model_id: String,+ /// Per-tool-result character cap; `0` disables it.+ #[serde(default = "default_max_tool_output_chars")]+ pub max_tool_output_chars: u64,}impl Default for McpSettings {@@ -118,6 +125,7 @@ impl Default for McpSettings {use_lightweight_router_model: false,router_model_provider: String::new(),router_model_id: String::new(),+ max_tool_output_chars: super::constants::DEFAULT_MCP_MAX_TOOL_OUTPUT_CHARS,}}}@@ -127,6 +135,22 @@ impl McpSettings {pub fn tool_call_timeout_duration(&self) -> std::time::Duration {std::time::Duration::from_secs(self.tool_call_timeout_seconds.max(1))}++ /// Effective per-tool-result character cap. `0` means uncapped.+ ///+ /// `override_chars` is the caller's own budget - the desktop chat derives one+ /// from the active model's context window, which the backend cannot see. The+ /// tighter of the two wins. A user setting of `0` disables capping outright,+ /// and an absent or `0` override simply leaves the setting in charge.+ pub fn tool_output_cap(&self, override_chars: Option<u64>) -> u64 {+ if self.max_tool_output_chars == 0 {+ return 0;+ }+ match override_chars {+ Some(o) if o > 0 => o.min(self.max_tool_output_chars),+ _ => self.max_tool_output_chars,+ }+ }}/// Tool with server informationdiff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rsindex c1f72d5ea..f0bc94c65 100644--- a/src-tauri/src/core/mcp/tests.rs+++ b/src-tauri/src/core/mcp/tests.rs@@ -655,6 +655,10 @@ fn test_mcp_settings_default_matches_constants() {assert!(!s.use_lightweight_router_model);assert!(s.router_model_provider.is_empty());assert!(s.router_model_id.is_empty());+ assert_eq!(+ s.max_tool_output_chars,+ constants::DEFAULT_MCP_MAX_TOOL_OUTPUT_CHARS+ );}#[test]@@ -671,6 +675,40 @@ fn test_mcp_settings_tool_call_timeout_duration_enforces_minimum() {assert_eq!(s.tool_call_timeout_duration(), Duration::from_secs(600));}+#[test]+fn test_mcp_settings_tool_output_cap_takes_the_tighter_of_setting_and_override() {+ use super::models::McpSettings;+ let s = McpSettings {+ max_tool_output_chars: 40_000,+ ..McpSettings::default()+ };++ // No caller budget: the user's setting governs.+ assert_eq!(s.tool_output_cap(None), 40_000);+ // A tighter model-derived budget wins.+ assert_eq!(s.tool_output_cap(Some(8_000)), 8_000);+ // A looser one cannot raise the user's ceiling.+ assert_eq!(s.tool_output_cap(Some(500_000)), 40_000);+ // A 0 override means "no derived budget", not "uncapped".+ assert_eq!(s.tool_output_cap(Some(0)), 40_000);+}++#[test]+fn test_mcp_settings_zero_max_tool_output_chars_disables_capping() {+ use super::models::McpSettings;+ let s = McpSettings {+ max_tool_output_chars: 0,+ ..McpSettings::default()+ };++ assert_eq!(s.tool_output_cap(None), 0);+ assert_eq!(+ s.tool_output_cap(Some(8_000)),+ 0,+ "an explicit opt-out is not overridden by a derived budget"+ );+}+#[test]fn test_mcp_settings_deserialize_uses_defaults_for_missing_fields() {use super::models::McpSettings;@@ -696,6 +734,7 @@ impl PartialEq for super::models::McpSettings {&& self.use_lightweight_router_model == other.use_lightweight_router_model&& self.router_model_provider == other.router_model_provider&& self.router_model_id == other.router_model_id+ && self.max_tool_output_chars == other.max_tool_output_chars}}diff --git a/src-tauri/src/core/mcp/truncate.rs b/src-tauri/src/core/mcp/truncate.rsnew file mode 100644index 000000000..f38e775bd--- /dev/null+++ b/src-tauri/src/core/mcp/truncate.rs@@ -0,0 +1,240 @@+//! Size cap for MCP tool results.+//!+//! A tool result is injected verbatim into conversation history, so one call to+//! a tool that dumps a whole page (Jan Browser MCP's snapshot, for instance) can+//! exhaust the model's context on its own, regardless of how large that context+//! is. Everything that hands an MCP result to a model funnels through here first+//! so the payload is bounded and the clipping is announced rather than silent.++use rmcp::model::{CallToolResult, Content};++/// Total text characters carried by a result, across every text block.+fn total_text_chars(result: &CallToolResult) -> usize {+ result+ .content+ .iter()+ .filter_map(|c| c.as_text())+ .map(|t| t.text.chars().count())+ .sum()+}++fn truncation_marker(retained: usize, total: usize) -> String {+ format!(+ "[Tool output truncated: {retained} of {total} characters retained. \+Increase \"Max tool output characters\" in Settings > MCP Servers to retain more.]"+ )+}++/// Cap the combined text of `result` at `max_chars`, appending a marker block+/// that reports how much was kept.+///+/// The budget spans all text blocks rather than each block individually, since+/// the model receives their concatenation. Blocks are filled in order: earlier+/// ones survive intact, the block that crosses the budget is cut mid-way, and+/// later ones are dropped. Non-text blocks (images, resources, audio) are never+/// counted or altered - they aren't the payload that blows up, and clipping+/// their base64 would corrupt them.+///+/// `max_chars == 0` disables the cap, which is how a user opts out.+pub fn truncate_tool_result(result: &CallToolResult, max_chars: u64) -> CallToolResult {+ if max_chars == 0 {+ return result.clone();+ }+ let max_chars = max_chars as usize;++ let total = total_text_chars(result);+ if total <= max_chars {+ return result.clone();+ }++ let mut used = 0usize;+ let mut new_content: Vec<Content> = Vec::with_capacity(result.content.len() + 1);++ for block in &result.content {+ let Some(text) = block.as_text() else {+ // Non-text block: pass through untouched.+ new_content.push(block.clone());+ continue;+ };++ if used >= max_chars {+ continue; // Budget spent; this block and the rest are dropped.+ }++ let len = text.text.chars().count();+ let keep = len.min(max_chars - used);+ used += keep;++ if keep == len {+ new_content.push(block.clone());+ } else {+ new_content.push(Content::text(+ text.text.chars().take(keep).collect::<String>(),+ ));+ }+ }++ new_content.push(Content::text(truncation_marker(used, total)));++ CallToolResult {+ content: new_content,+ structured_content: result.structured_content.clone(),+ is_error: result.is_error,+ meta: result.meta.clone(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn text_result(parts: &[&str]) -> CallToolResult {+ CallToolResult::success(parts.iter().map(|p| Content::text(*p)).collect())+ }++ fn texts(result: &CallToolResult) -> Vec<String> {+ result+ .content+ .iter()+ .filter_map(|c| c.as_text())+ .map(|t| t.text.clone())+ .collect()+ }++ /// The web layer reads `content[].text` off the serialized result and feeds+ /// it straight into conversation history, so the cap has to hold on the wire,+ /// not just in the struct.+ #[test]+ fn serialized_result_the_web_layer_receives_is_bounded() {+ // Stand-in for a Jan Browser MCP page snapshot: one enormous text block.+ let snapshot = CallToolResult::success(vec![Content::text(+ "<div>page</div>".repeat(100_000),+ )]);++ let capped = truncate_tool_result(&snapshot, 40_000);+ let wire = serde_json::to_value(&capped).expect("serializes");++ let blocks = wire["content"].as_array().expect("content array");+ let wire_chars: usize = blocks+ .iter()+ .filter_map(|b| b["text"].as_str())+ .map(|t| t.chars().count())+ .sum();++ assert!(+ wire_chars < 41_000,+ "1.5M-char snapshot reached the model as {wire_chars} chars"+ );+ assert!(blocks+ .last()+ .and_then(|b| b["text"].as_str())+ .is_some_and(|t| t.contains("truncated")));+ }++ #[test]+ fn small_output_passes_through_untouched() {+ let result = text_result(&["hello world"]);+ let capped = truncate_tool_result(&result, 100);++ assert_eq!(texts(&capped), vec!["hello world".to_string()]);+ assert_eq!(capped.content.len(), 1, "no marker on untruncated output");+ }++ #[test]+ fn output_exactly_at_cap_is_not_truncated() {+ let result = text_result(&["0123456789"]);+ let capped = truncate_tool_result(&result, 10);++ assert_eq!(texts(&capped), vec!["0123456789".to_string()]);+ assert_eq!(capped.content.len(), 1);+ }++ #[test]+ fn oversized_output_is_capped_to_max_chars() {+ let result = text_result(&["x".repeat(5_000).as_str()]);+ let capped = truncate_tool_result(&result, 100);++ let retained: usize = capped+ .content+ .iter()+ .take(capped.content.len() - 1)+ .filter_map(|c| c.as_text())+ .map(|t| t.text.chars().count())+ .sum();+ assert_eq!(retained, 100);+ }++ #[test]+ fn truncation_marker_reports_retained_and_total() {+ let result = text_result(&["y".repeat(5_000).as_str()]);+ let capped = truncate_tool_result(&result, 100);++ let marker = texts(&capped).pop().expect("marker block");+ assert!(marker.contains("truncated"), "marker text: {marker}");+ assert!(marker.contains("100 of 5000"), "marker text: {marker}");+ assert!(+ marker.contains("Max tool output characters"),+ "marker points the user at the setting: {marker}"+ );+ }++ #[test]+ fn multi_block_budget_spans_all_text_blocks() {+ let result = text_result(&["aaaa", "bbbb", "cccc"]);+ let capped = truncate_tool_result(&result, 6);++ let blocks = texts(&capped);+ // First block intact, second cut mid-way, third dropped, marker appended.+ assert_eq!(blocks[0], "aaaa");+ assert_eq!(blocks[1], "bb");+ assert_eq!(blocks.len(), 3, "third block dropped, marker added: {blocks:?}");+ assert!(blocks[2].contains("6 of 12"), "marker text: {}", blocks[2]);+ }++ #[test]+ fn non_text_blocks_survive_truncation() {+ let result = CallToolResult::success(vec![+ Content::text("z".repeat(1_000)),+ Content::image("ZmFrZQ==".to_string(), "image/png".to_string()),+ ]);+ let capped = truncate_tool_result(&result, 10);++ assert!(+ capped.content.iter().any(|c| c.as_image().is_some()),+ "image block must not be dropped by the text cap"+ );+ assert_eq!(texts(&capped)[0].chars().count(), 10);+ }++ #[test]+ fn zero_max_chars_disables_the_cap() {+ let result = text_result(&["w".repeat(10_000).as_str()]);+ let capped = truncate_tool_result(&result, 0);++ assert_eq!(texts(&capped)[0].chars().count(), 10_000);+ assert_eq!(capped.content.len(), 1);+ }++ #[test]+ fn error_flag_and_structured_content_are_preserved() {+ let mut result = text_result(&["e".repeat(500).as_str()]);+ result.is_error = Some(true);+ result.structured_content = Some(serde_json::json!({ "code": 42 }));++ let capped = truncate_tool_result(&result, 10);++ assert_eq!(capped.is_error, Some(true));+ assert_eq!(+ capped.structured_content,+ Some(serde_json::json!({ "code": 42 }))+ );+ }++ #[test]+ fn multibyte_text_is_cut_on_char_boundaries() {+ let result = text_result(&["日本語テキスト".repeat(100).as_str()]);+ let capped = truncate_tool_result(&result, 5);++ assert_eq!(texts(&capped)[0], "日本語テキ");+ }+}