Skip to main content
Glama
KolyaMetallist

telegram-search-mcp

๐Ÿ” telegram-search-mcp

MCP Version Python Tests License Telethon MCP pytest uv Last commit Stars

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.

NOTE

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

search_messages

Keyword search inside any chat or channel

get_messages

Fetch recent messages from a chat

search_dialogs

Find chats, channels, groups by name

get_message_document

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

IMPORTANT

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.sh

The script auto-detects uv and falls back to pip/venv. It creates .venv, installs all dependencies including pdfplumber, and prints the exact next steps.

TIP

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

TELEGRAM_API_ID

โœ…

Integer API ID from my.telegram.org

TELEGRAM_API_HASH

โœ…

API Hash from my.telegram.org

TELEGRAM_SESSION_PATH

โž–

Custom session file path (default: ~/.local/state/telegram-search-mcp/session)

# Add to ~/.zshrc or ~/.bashrc
export TELEGRAM_API_ID=12345678
export TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890
WARNING

Never 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 --login

Telethon 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.

CAUTION

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_mcp

SSE โ€” HTTP server for Codemie URL mode or any web client:

python main.py --sse              # port 8000
python main.py --sse --port 9000  # custom port

Stop 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

ClientFactory.create(), ExtractorRegistry.default()

Strategy

DocumentExtractor ABC โ†’ PDFExtractor, PlainTextExtractor

Registry

ExtractorRegistry.find(mime, filename)

Template Method

ToolSet.register(mcp) โ€” each subclass adds its own tools

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/ -v

52 unit tests, zero network calls โ€” all Telegram interactions are mocked.


๐Ÿค Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repository and clone your fork

  2. Create a branch for your change: git checkout -b feat/my-feature

  3. Install dev dependencies:

    uv pip install -e ".[pdf,dev]"
  4. Make your changes โ€” add or update tests when behavior changes

  5. Run the test suite before opening a PR:

    python -m pytest tests/ -v
  6. Open a pull request with a concise description of what changed and why

NOTE

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 tools
get_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.

ParametersJSON Schema
NameRequiredDescriptionDefault
entityYes
message_idYes

TDQS

A4.2/5.0
Behavior4/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
entityYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
queryYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
queryYes
entityYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior4/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters5/5

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.

Purpose5/5

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.

Usage Guidelines4/5

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

A4.2/5.0
Disambiguation5/5

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.

Naming Consistency5/5

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.

Tool Count5/5

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.

Completeness4/5

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

ActivityMaintained
ResponsivenessNo issues

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

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables 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
    53
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables Claude to interact with your Telegram account, including reading messages, searching conversations, and sending messages.
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to interact with a user's Telegram account: list chats, read history, search, and send messages through Telegram's MTProto API.
    1
    MIT

Latest Blog Posts

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