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:
- That the response was truncated (not an error)
- The exact token limit that was hit
- 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 }))