Sanitize tool outputs to prevent prompt injection#89
Merged
chigwell merged 1 commit intochigwell:mainfrom Apr 28, 2026
Merged
Conversation
c056626 to
1b1e452
Compare
Author
|
black applied |
1b1e452 to
74dab31
Compare
chigwell
approved these changes
Apr 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
MCP tool results are fed directly into the LLM context window. Without protection, malicious Telegram content (messages, display names, chat titles, sticker pack names, button labels) could manipulate the LLM's behavior through prompt injection. While MCP Content Annotations (
audience=["user"]) signal that content is user-generated, clients are not required to honor them, so additional layers are needed.Solution
Six-layer approach:
format_tool_result()(json.dumps) in 25+ tool functions - structural boundary between field names and user valuessanitize.pymodule:sanitize_user_content(),sanitize_name(),sanitize_dict()- strips Unicode control chars, zero-width/invisible chars, bidi overrides, collapses excessive whitespace, truncates long contentaudience=["user"], signaling to MCP clients that content is user-generated datasanitize_dict()recursively sanitizes all string values in raw Telegram API responses (e.g.to_dict()) at any nesting depthKey changes
sanitize.py(new) - 4 functions, stdlib only, no dependenciestest_sanitize.py(new) - 33 tests covering control chars, zero-width, bidi, truncation, nested dicts, format_tool_resultmain.py- sanitization applied at key choke points (get_sender_name,format_entity,format_message) + all tool functions returning user contentDockerfile-COPY sanitize.pyREADME.md- "Prompt Injection Protection" sectionTests