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 "Install 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-mcpsearch 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 Server
๐ 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.
| Name | Required | Description | Default |
|---|---|---|---|
| entity | Yes | ||
| message_id | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It discloses the return structure (filename, mime_type, size_bytes, content) and notes that an error field is returned if extraction is not possible. This gives the agent a clear model of expected behavior, though it does not cover edge cases like permission failures or unsupported file types.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and well-structured: a one-sentence summary followed by concise Args and Returns sections. Every sentence adds value, and the main purpose is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with only two required parameters and no output schema, this description is largely complete. It explains both parameters and describes the return payload. It could be slightly richer by mentioning likely failure modes or prerequisites, but nothing essential is missing for correct invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must add meaning. It does: 'entity' is explained as chat username or chat ID with an example, and 'message_id' is described as the ID of the message containing the document. This goes well beyond the bare schema types and titles.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action: 'Download and extract text from a document attached to a specific message.' This identifies the resource (document attached to a message) and the operation (download/extract text), and it is distinct from sibling tools like search_dialogs, get_messages, and search_messages.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The usage context is implied by the description: use this when you need the text content of a document attached to a specific message. However, it does not explicitly state when to prefer this tool over siblings or provide any when-not-to-use guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| entity | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the burden. It discloses the return shape, accepted entity formats, and limit bounds, which is useful. It does not mention ordering, authorization needs, or error behavior, but for a read-only retrieval tool the gaps are moderate.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and well-structured: purpose, then Args, then Returns. Every sentence provides useful information with no repetition or filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple two-parameter read operation with an output schema, the description covers inputs, defaults, max, and return fields. It omits ordering and failure handling, but those are not critical for selecting and invoking the tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description compensates meaningfully: entity accepts a username, chat ID, or title; limit has a default of 20 and a max of 100. This adds significant meaning beyond the raw schema types.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb and resource: 'Get recent messages from a Telegram chat/channel/group.' It clearly indicates the tool retrieves rather than searches, but it does not explicitly distinguish itself from sibling tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no explicit guidance about when to use this tool versus search_messages, search_dialogs, or get_message_document. The description implies it is for fetching recent messages from a known entity, but it provides no exclusions or alternative conditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| query | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It does add useful behavior details: query is a partial name match, limit caps results, and the result is a list of matching dialogs with specific fields. However, it does not disclose case sensitivity, empty-result behavior, ordering, or any read-only guarantee. This is adequate but not thorough for a tool with zero annotation support.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and well-structured: a one-sentence summary is front-loaded, followed by concise Args and Returns sections. Every sentence adds value and there is no redundant or filler content. The structure makes it easy for an agent to quickly extract the tool's behavior.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a two-parameter search tool with an output schema, the description covers the essential inputs and the shape of results. It is complete enough to call correctly. Minor gaps include the absence of explicit routing between dialog search and message search, and edge-case behavior, but these do not prevent effective use.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It does: query is defined as 'Part of the name to search for,' and limit is defined as 'Max results (default 10).' This adds meaningful semantics beyond the raw schema, including the partial-match behavior and the cap semantics. It does not mention whether username is also matched, but the key parameters are clearly explained.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb ('Search') and a concrete resource ('chats, channels, or groups') with a clear scope ('by name'). This differentiates it from sibling tools such as search_messages, which targets message content, and get_messages, which retrieves messages. The output return list of dialogs with id, name, username, type further reinforces the purpose.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool: when you need to find chats, channels, or groups by name. However, it does not explicitly mention alternatives, such as 'use search_messages to search within messages,' nor does it state when this tool should not be used. Usage context is clear but the guidance on choosing between siblings is left implicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| query | Yes | ||
| entity | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden. It clearly implies a read-only operation, explains that results are capped at 100, and lists the returned message fields. It doesn't discuss authentication or edge cases like case-sensitivity, but the core behavior is well disclosed.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and well-structured: a one-sentence purpose, concise Args section, and Return section. Every line adds needed information and the most important scope statement is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple three-parameter tool with an output schema, this description is nearly complete. It covers entity addressing, query semantics, limit behavior, and return fields. It only lacks explicit guidance for ambiguous title fragments or when to prefer a sibling tool, which are minor gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, yet the description fully documents every parameter: entity accepts username, ID, or title fragment; query is a keyword or phrase; limit has a default of 30 and max of 100. This adds substantial meaning beyond the bare input schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description starts with a specific action: searching messages by keyword inside a specific Telegram chat/channel/group. This clearly distinguishes it from siblings like search_dialogs (search dialogs) and get_messages (fetch messages) without needing to inspect schemas.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The scope is explicit: this tool is for keyword search within a single entity, not across all chats or for retrieving messages without a query. No alternative tools are named or excluded, which prevents a 5, but the intended context is clear.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
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
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Search and reason over your Obsidian-style Markdown vault, right from ChatGPT.
Telegram: FASTEST real time Telegram API. Retrieve channel's info and messages in milliseconds..
Telegram CRM: manage contacts, conversations, tickets, campaigns and analytics.
Search 1.2M+ Telegram channels, 245k+ chats, 160k+ bots โ no account, no key, no install.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables 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.753MIT
- FlicenseNot gradedqualityDmaintenanceEnables Claude to interact with your Telegram account, including reading messages, searching conversations, and sending messages.
- FlicenseNot gradedqualityDmaintenanceEnables Claude to interact with Telegram, including listing chats, reading messages, sending messages, searching, and managing contacts.1
- 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.1MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/KolyaMetallist/telegram-search-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server