# sanitize_control_chars

> **Function** in `deepagents_code`

📖 [View in docs](https://reference.langchain.com/python/deepagents-code/unicode_security/sanitize_control_chars)

Neutralize control characters and deceptive Unicode in untrusted text.

Untrusted strings (MCP server errors, config-file contents, tool output)
can carry ANSI escape sequences, other control characters, or invisible
Unicode that corrupts the terminal, breaks out of a layout, or injects fake
lines into logs and prompts. This first removes the invisible/bidi code
points flagged by `strip_dangerous_unicode`, then replaces every remaining
Unicode "Other" (control/format) character with a space.

## Signature

```python
sanitize_control_chars(
    text: str,
    *,
    keep_newlines: bool = False,
    collapse_whitespace: bool = True,
    max_length: int | None = None,
) -> str
```

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `text` | `str` | Yes | Untrusted text to sanitize. |
| `keep_newlines` | `bool` | No | When `True`, newlines survive so multiline, scrollable surfaces keep their line structure; otherwise newlines are flattened to spaces along with the other control characters. (default: `False`) |
| `collapse_whitespace` | `bool` | No | When `True`, runs of whitespace are collapsed to a single space and surrounding whitespace is stripped. With `keep_newlines`, collapsing is applied per line so line breaks are preserved. (default: `True`) |
| `max_length` | `int \| None` | No | When set, truncate to at most this many characters, replacing the final character with an ellipsis. (default: `None`) |

## Returns

`str`

Sanitized text safe to embed in terminal output, markup substitutions,

---

[View source on GitHub](https://github.com/langchain-ai/deepagents/blob/a98f0dfa8d534d8a1885b524632400e52db22ac6/libs/code/deepagents_code/unicode_security.py#L176)