Skip to main content

truncate_if_needed

Function truncate_if_needed 

Source
pub fn truncate_if_needed(text: &str) -> Cow<'_, str>
Expand description

Truncate plain text to MAX_RESPONSE_BYTES if it exceeds the cap.

When truncation occurs, appends a clear notice telling the agent:

  1. That the response was truncated (not an error)
  2. The exact token limit that was hit
  3. How to get the full data (use pagination/filters)

§Truncation boundary

Truncation finds the last valid UTF-8 boundary within the content budget. The returned string, including the notice, never exceeds MAX_RESPONSE_BYTES.

§CUSTOMIZE: Returning the raw truncated string outside MCP JSON

This function returns a String, not a Value. The caller wraps it as appropriate:

// In a CLI/log helper:
let raw = serde_json::to_string(&result)?;
let output = token_limit::truncate_if_needed(&raw);
// output is now a plain string for non-MCP presentation:
Ok(json!({ "data": output }))