telegram-search-mcp
Provides tools to search Telegram messages, fetch recent messages, find chats and channels, and extract text from attached documents (PDF, TXT, MD, CSV) using a personal Telegram account.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@telegram-search-mcp search my Telegram for messages mentioning 'meeting tomorrow'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
๐ telegram-search-mcp
An MCP server that gives Claude (or any MCP-compatible client) the ability to search Telegram messages and read documents attached to those messages โ using your personal Telegram account via Telethon.
This server uses the Telegramuser API (MTProto), not the Bot API. It reads your account's chats just like the official Telegram client does.
โจ Features
Tool | Description |
| Keyword search inside any chat or channel |
| Fetch recent messages from a chat |
| Find chats, channels, groups by name |
| Download and extract text from attached files (PDF, TXT, MD, CSV) |
All message results include a has_document field โ so Claude knows when to call get_message_document automatically.
Related MCP server: telegram-mcp
๐ Requirements
Python 3.10+
Telegram API credentials from my.telegram.org/apps
You need to create an application onmy.telegram.org/apps to get your api_id and api_hash. This is free and takes ~1 minute.
๐ Installation
git clone https://github.com/KolyaMetallist/telegram-search-mcp.git
cd telegram-search-mcp
./install.shThe script auto-detects uv and falls back to pip/venv. It creates .venv, installs all dependencies including pdfplumber, and prints the exact next steps.
โก With uv (recommended)
uv installs packages 10-100ร faster than pip. One-time install: curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv .venv
source .venv/bin/activate
uv pip install -e ".[pdf]"Or run without activating the venv at all:
uv run --extra pdf python main.py --login
uv run --extra pdf python main.py๐ With pip
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[pdf]"โ๏ธ Configuration
Set environment variables before running. Add them to ~/.zshrc or ~/.bashrc so you don't have to repeat this:
Variable | Required | Description |
| โ | Integer API ID from my.telegram.org |
| โ | API Hash from my.telegram.org |
| โ | Custom session file path (default: |
# Add to ~/.zshrc or ~/.bashrc
export TELEGRAM_API_ID=12345678
export TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890Never commit yourapi_id or api_hash to version control. The .gitignore already excludes .env files.
๐ First Login
Run once to authenticate your account:
source .venv/bin/activate
python main.py --loginTelethon will prompt for your phone number, the SMS code, and your 2FA password if enabled. The session is saved locally at ~/.local/state/telegram-search-mcp/session.session โ you won't need to log in again.
The session file grants full access to your Telegram account. Keep it secure and never share it. It is excluded from git via.gitignore.
โถ๏ธ Running the Server
stdio โ for Claude Desktop, Claude Code, Codemie command mode:
python main.py
# or
python -m telegram_search_mcpSSE โ HTTP server for Codemie URL mode or any web client:
python main.py --sse # port 8000
python main.py --sse --port 9000 # custom portStop with Ctrl+C โ the server shuts down cleanly (SIGINT and SIGTERM both handled).
๐ MCP Client Configuration
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"telegram-search": {
"command": "/path/to/telegram-search-mcp/.venv/bin/python",
"args": ["/path/to/telegram-search-mcp/main.py"],
"env": {
"TELEGRAM_API_ID": "your_api_id",
"TELEGRAM_API_HASH": "your_api_hash"
}
}
}
}Codemie โ command mode
{
"command": "/path/to/.venv/bin/python",
"args": ["/path/to/telegram-search-mcp/main.py"]
}Add TELEGRAM_API_ID and TELEGRAM_API_HASH via the "Add Environment Variables" section.
Codemie โ SSE / URL mode
Start the server first, then set MCP-Connect URL to http://localhost:8000/sse.
python main.py --sse --port 8000๐ฌ Usage Examples
Once connected, ask Claude:
"Find messages about Python in @some_channel"
"Search dialogs for 'Bulgaria Ukraine'"
"Get the document attached to message 432583 in @Autochat_Bulgaria_Ukraine and summarize it"
"Show me the last 20 messages in @my_group and extract any PDFs"
๐๏ธ Architecture
The project follows SOLID, DRY, KISS, and YAGNI principles with these GoF patterns:
Pattern | Where |
Factory Method |
|
Strategy |
|
Registry |
|
Template Method |
|
Facade | MCP tools hide Telethon complexity behind simple dicts |
๐ Package layout
src/telegram_search_mcp/
config.py Config dataclass (from env)
client.py ClientFactory
auth.py AuthManager โ login without mcp-telegram
server.py build_server() โ wires all ToolSets
cli.py main() entry point
extractors/ DocumentExtractor ABC, PDFExtractor, PlainTextExtractor, ExtractorRegistry
tools/ ToolSet ABC, DialogTools, MessageTools, DocumentToolsโ Adding a new extractor
Create src/telegram_search_mcp/extractors/<name>.py extending DocumentExtractor, register in ExtractorRegistry.default(). No other files change.
class DocxExtractor(DocumentExtractor):
@property
def supported_mimes(self): return ("application/vnd.openxmlformats-officedocument.wordprocessingml.document",)
@property
def supported_extensions(self): return (".docx",)
async def extract(self, data, filename): ...โ Adding a new tool set
Create src/telegram_search_mcp/tools/<name>.py extending ToolSet, implement register(mcp), add to list in server.py.
๐งช Tests
source .venv/bin/activate
python -m pytest tests/ -v52 unit tests, zero network calls โ all Telegram interactions are mocked.
๐ค Contributing
Contributions are welcome! Here's how to get started:
Fork the repository and clone your fork
Create a branch for your change:
git checkout -b feat/my-featureInstall dev dependencies:
uv pip install -e ".[pdf,dev]"Make your changes โ add or update tests when behavior changes
Run the test suite before opening a PR:
python -m pytest tests/ -vOpen a pull request with a concise description of what changed and why
For new file-type extractors or tool sets, see theArchitecture section โ the design is intentionally extension-friendly.
Please keep PRs focused: one feature or fix per PR. If you're unsure whether something is in scope, open an issue first.
๐ License
This project is licensed under the Apache License 2.0 โ see the LICENSE file for details.
Apache 2.0 was chosen over MIT because it includes an explicit patent grant, which is better for an open-source tool used in corporate environments.
Available Tools
4 toolsget_message_documentA
Download and extract text from a document attached to a specific message.
Args: entity: Chat username (e.g. @some_channel), chat ID. message_id: The ID of the message that contains the document.
Returns: Dict with filename, mime_type, size_bytes, and content (extracted text), or an error field if extraction is not possible.
Inputs: entity (required), message_id (required).
get_messagesA
Get recent messages from a Telegram chat/channel/group.
Args: entity: Chat username (e.g. @some_channel), chat ID, or title. limit: Number of messages to retrieve (default 20, max 100).
Returns: List of recent messages with id, date, sender, text, has_document.
Inputs: entity (required), limit. Returns: result
search_dialogsA
Search for chats, channels, or groups by name.
Args: query: Part of the name to search for. limit: Max results (default 10).
Returns: List of matching dialogs with id, name, username, type.
Inputs: query (required), limit. Returns: result
search_messagesA
Search messages by keyword inside a specific Telegram chat/channel/group.
Args: entity: Chat username (e.g. @some_channel), chat ID, or title fragment. query: Keyword or phrase to search for. limit: Max results to return (default 30, max 100).
Returns: List of matching messages with id, date, sender, text, has_document.
Inputs: query (required), entity (required), limit. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 4 tools
Each tool targets a distinct resource/action: dialog lookup, message listing, message search, and document extraction. get_messages and search_messages overlap only superficially because one returns recent unfiltered messages and the other returns keyword-filtered results.
All tools use lower_snake_case and follow a consistent verb_noun pattern such as search_dialogs, get_messages, search_messages, and get_message_document. The verbs match the operations clearly, and the nouns identify the resource being acted on.
Four tools is a tight, well-scoped set for a read-only Telegram search/retrieval server. Each tool earns its place in the workflow of finding a dialog, reading or searching messages, and extracting document text.
The read-oriented workflow is well covered: discover dialogs, list recent messages, search messages by keyword, and extract document text. Minor gaps such as global message search and pagination/offset support mean some advanced retrieval tasks may require workarounds.
Maintenance
Related MCP Connectors
Your personal Telegram account for AI: read, search and sum up chats. QR login, no API key.
Search, read and reply to your Telegram Business chats, transcribed voice included.
Extract public Telegram channel messages, media metadata, crypto addresses, and RAG Markdown.
Search and reason over your Obsidian-style Markdown vault, right from ChatGPT.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables interaction with Telegram chat history, including text, photos, and documents, via the GramJS MTProto userbot. It provides tools for searching chats, syncing message history, and downloading media files for local analysis.7-
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with a user's Telegram account: list chats, read history, search, and send messages through Telegram's MTProto API.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to search and act on Telegram conversations, groups, channels, files, and links, with semantic search, AI-powered knowledge extraction, human-in-the-loop approvals, and PostgreSQL/pgvector persistence.Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to search and analyze a Telegram account as a read-only knowledge source, allowing chat discovery, message search, history reading, contact inspection, and media download without exposing any mutating Telegram tools.13Apache 2.0