Telegram MCP — Next Generation
This server provides a production-oriented Telegram MCP integration with 129 tools across read, write, media, and local SQLite caching capabilities, governed by configurable tool tiers and safety gates.
Contacts & identity: list/search contacts, resolve usernames, get current account profile.
Chats & discovery: list chats with filters, get chat details, search public channels/groups globally.
Messages: retrieve paginated messages, search within chats, send, edit, reply to, delete, pin/unpin, and mark messages as read.
Media & files: send local files, download media, inspect media metadata; paths are restricted to configured MCP/server roots.
Offline cache: sync chat history into local SQLite/FTS5, search cached messages offline, and inspect cache health.
Safety & configuration: tool tiers (
essential,core,standard,full), independent write/destructive-operation gates, concurrency limits, bounded retries, and fail-closed filesystem handling.
Provides tools for interacting with Telegram, enabling AI agents to manage accounts, chats, contacts, messages, groups, media, profiles, folders, and incoming events through the Telegram API.
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 MCP — Next Generation Search my cached Telegram messages for the word 'deploy'."
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 MCP — Next Generation
A production-oriented Telegram integration for MCP-compatible clients, maintained by LoneVertex and built on Telethon and the Model Context Protocol. This repository preserves the upstream Telegram capability surface while adding explicit tool tiers, fail-closed mutation controls, keyed concurrency limits, bounded retries, local SQLite/FTS5 caching, safer media paths, package entrypoints, and reproducible CI.
Default posture: local stdio,
essentialtool tier, no Telegram writes, no destructive operations, and no unverified filesystem roots.
Project governance: Contributing · Security Policy · Apache License 2.0
What is included
The implementation registers 129 tools: the upstream 125 tools covering accounts, chats, contacts, messages, groups, media, profiles, folders, and incoming events, plus check_cache_health (with backward-compatible cache_health alias), search_cached_messages, and sync_chat_cache. The upstream provenance is preserved at commit 52cca204d945e4ec292801a9d972334c0c2a4b63; the next-generation package is version 4.3.1.
Tier | Purpose | Default | Tool Count |
| Highly coherent curated lifecycle suite (read, write, pin, media, cache) with zero dead-end references | Yes | 22 |
| Extended read-only account, chat, message, search, profile, media, contact, folder, and local-cache tools | No | 36 |
| Core plus common message/media sends, replies, forwards, reactions, drafts, aliases, and event waits | No | 69 |
| All 129 tools, including full administrative and destructive operations | No | 129 |
Set TELEGRAM_MCP_TIER to select a tier. Tier selection controls which tools are registered. TELEGRAM_SEND_ENABLED independently controls whether write operations can execute, and TELEGRAM_DESTRUCTIVE_ENABLED is a second gate for destructive/admin actions. The server returns a structured nothing_sent or nothing_done response when a gate blocks a call.
Related MCP server: telegram-mcp
Quick start
Use Python 3.11 or 3.12. Obtain Telegram API credentials from my.telegram.org/apps, and generate an authorized session outside the MCP process using the included session generator.
git clone https://github.com/LoneVertex/telegram-mcp-nextgen.git
cd telegram-mcp-nextgen
python -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# edit .env with TELEGRAM_API_ID, TELEGRAM_API_HASH, and an authorized session
telegram-mcpFor package development and release validation:
pip install -e '.[dev]'
pytest -q
ruff check telegram_mcp/config.py telegram_mcp/core telegram_mcp/db telegram_mcp/models
mypy --explicit-package-bases telegram_mcp/config.py telegram_mcp/core telegram_mcp/db telegram_mcp/models
python -m buildThe server is intentionally non-interactive. Use telegram-mcp-generate-session before startup and keep the resulting session string private. Never commit .env, a Telethon .session file, API hashes, or session strings.
Configuration
The complete secret-free template is in .env.example. The important controls are summarized below.
Variable | Safe default | Meaning |
|
| Registered tool tier: |
|
| Global write-operation gate |
|
| Additional gate for delete, ban, leave, and similar operations |
|
| Persistent state root |
| Derived | SQLite cache path; must remain beneath |
|
| Maximum bounded FloodWait/transient retry attempts |
|
| Maximum provider-requested wait accepted for retry |
|
| Per-account token-bucket burst capacity |
|
| Per-account token refill rate |
|
| Maximum downloaded media size |
|
| Maximum uploaded media size |
Configuration construction is side-effect free. Credentials and authorization are checked when a live client starts, not when local tooling imports the package. Runtime state is created under owner-only directories when a cache or session operation requires it.
MCP clients and transports
See config/mcp-configs.md for secret-free examples for desktop MCP clients. Local stdio is preferred. Streamable HTTP is available for a long-lived local service:
MCP_TRANSPORT=http
MCP_HOST=127.0.0.1
MCP_PORT=8765Do not expose the unauthenticated HTTP endpoint directly to the public internet. If a reverse proxy is used, configure authentication, TLS, allowed hosts, allowed origins, and network controls. The server retains MCP DNS-rebinding protection when MCP_ALLOWED_HOSTS is configured.
Concurrency and reliability
Each account is protected by a keyed async mutex and token bucket. Calls sharing an account are serialized at the adapter boundary, while read-only multi-account fan-out remains possible across distinct account labels. FloodWait and transient connection failures use one bounded retry policy with exponential backoff and jitter. Session-level advisory locks remain in place to prevent duplicate processes from concurrently using the same Telegram auth key.
The local cache uses SQLite WAL mode, foreign keys, short-lived connections, explicit transactions, indexes for chat/date/sender/topic access, and FTS5 for search. Synchronization stores checkpoints and uses upserts so edits are reflected instead of duplicated. SQLite work, directory creation, and integrity checks are executed in worker threads rather than blocking the event loop.
Media and filesystem safety
File tools require client MCP Roots or explicit server-side roots. Empty or unverifiable roots produce deny-all behavior unless TELEGRAM_ALLOW_SERVER_ROOTS_FALLBACK=true is intentionally enabled. Paths are resolved beneath configured roots, traversal and NUL bytes are rejected, symlink escapes are rejected, media size limits are enforced, and generated files use owner-only permissions. The new security primitives support chunked reads and atomic output replacement.
Telegram text, captions, names, button labels, media metadata, and incoming event fields are untrusted user content. Sanitization and audience annotations are preserved from upstream; models must not treat those fields as instructions.
Docker
The image uses a two-stage Python 3.12 build, runs as UID 10001, keeps state in /var/lib/telegram-mcp, and receives credentials only at runtime.
cp .env.example .env
# edit .env
podman compose up --build
# or: docker compose up --buildCompose binds HTTP to 127.0.0.1:8765, uses a persistent named volume, drops Linux capabilities, enables no-new-privileges, mounts a read-only root filesystem, and supplies a constrained /tmp. The container build was not run in the sandbox used for this delivery because Docker was unavailable; the CI workflow validates it on a Docker-capable runner.
Development and release gates
The consolidated workflow in .github/workflows/ci.yml runs on Python 3.11 and 3.12, executes the inherited upstream regression suite plus next-generation tests, runs strict Ruff checks on the new production layers, runs explicit-package-base mypy checks, compiles the package, builds a wheel/sdist, audits declared dependencies, and validates the Docker image and Compose configuration. The upstream live Telegram adapters remain covered by their inherited mocked regression suite; local reliability/security modules have dedicated tests and coverage.
Ownership, compatibility, and provenance
Project maintenance: LoneVertex.
The root main.py, upstream tool module names, session generator, account labels, proxy settings, MCP transport variables, legacy exposure filter, and upstream Apache-2.0 license are retained for compatibility. The new package entrypoint is telegram_mcp.runner:main, and python -m telegram_mcp is supported. Upstream source and attribution remain visible in Git history and AUDIT_REPORT.md.
Troubleshooting
If startup reports that no session is configured, generate an authorized session and set TELEGRAM_SESSION_STRING or a valid file-session name. If a write returns MutationDisabled, set TELEGRAM_SEND_ENABLED=true and restart; for deletion or administration, also set TELEGRAM_DESTRUCTIVE_ENABLED=true. If a file tool reports that roots are unavailable, configure client MCP Roots or pass a server-side allowed root as a positional argument. If a FloodWait exceeds the configured maximum, the call is intentionally returned rather than sleeping indefinitely. Use check_cache_health (or cache_health) to inspect local SQLite/FTS5 integrity without contacting Telegram.
References
License
Apache License 2.0. See LICENSE.
Available Tools
22 toolscheck_cache_healthInspect Local SQLite Cache HealthARead-onlyIdempotent
Inspect local SQLite/FTS5 archive integrity, database size, and active tool tier diagnostics. Use to verify cache readiness before running local searches. Operates entirely offline without Telegram API calls.
Inputs: no named parameters. Returns: object
delete_messageDelete Single Message from ChatADestructiveIdempotent
Delete a single message from a chat by message ID. Destructive operation requiring TELEGRAM_SEND_ENABLED=true and TELEGRAM_DESTRUCTIVE_ENABLED=true.
Inputs: chat_id (required), message_id (required), account. Returns: result
download_mediaDownload Media Attachment to Local DiskAIdempotent
Download an attachment or media file from a message to the local filesystem. Destination path must resolve within configured MCP allowed roots. To check metadata before downloading, use get_media_info.
Inputs: chat_id (required), message_id (required), account, file_path. Returns: result
edit_messageEdit Text of Sent Telegram MessageAIdempotent
Edit the text content of an existing message previously sent by this account. Mutation operation requiring TELEGRAM_SEND_ENABLED=true. Cannot edit messages sent by other users.
Inputs: chat_id (required), new_text (required), message_id (required), account, +1 more. Returns: result
get_chatGet Chat Details and MetadataARead-onlyIdempotent
Retrieve core metadata, title, member count, and type for a specific chat or channel. Use when inspecting a known chat ID or @username.
Inputs: chat_id (required), account. Returns: result
get_meGet Current Account Profile and IdentityARead-onlyIdempotent
Retrieve detailed profile identity of the current Telegram user account (ID, name, username, phone). Use when verifying account identity, session details, or caller permissions.
Inputs: account. Returns: result
get_media_infoInspect Media Metadata in MessageARead-onlyIdempotent
Inspect media metadata (file size, dimensions, mime type, duration) attached to a specific message. Use before downloading or viewing to verify file attributes and dimensions.
Inputs: chat_id (required), message_id (required), account. Returns: result
get_messagesGet Paginated Messages from ChatARead-onlyIdempotent
Retrieve paginated messages from a specific chat starting from an offset or limit. Use for sequential message retrieval. To search text across messages, use search_messages.
Inputs: chat_id (required), page, account, page_size. Returns: result
list_chatsList All Telegram Chats and ChannelsARead-onlyIdempotent
List all accessible chats, groups, channels, and direct dialogs with pagination support. Use when locating specific conversations by title or type.
Inputs: limit, account, archived, chat_type, +3 more. Returns: result
list_contactsList Telegram Account ContactsARead-onlyIdempotent
List all registered Telegram contacts in your account address book with IDs and phone numbers. Use when finding contacts to message. To search contacts by query, use search_contacts.
Inputs: account. Returns: result
mark_as_readMark Messages in Chat as ReadAIdempotent
Mark all messages or messages up to a specific ID in a chat as read. Mutation operation requiring TELEGRAM_SEND_ENABLED=true. Clears unread badge counter.
Inputs: chat_id (required), account. Returns: result
pin_messagePin Message to Top of ChatAIdempotent
Pin a message to the top of a chat or supergroup for high visibility. Mutation operation requiring TELEGRAM_SEND_ENABLED=true and admin permissions in supergroups/channels. To unpin, use unpin_message.
Inputs: chat_id (required), message_id (required), account. Returns: result
reply_to_messageReply Directly to Existing MessageA
Send a message in direct reply to a specific message ID in a chat. Mutation operation requiring TELEGRAM_SEND_ENABLED=true. To send a standalone message, use send_message.
Inputs: text (required), chat_id (required), message_id (required), account, +1 more. Returns: result
resolve_usernameResolve Telegram Username to Entity IDARead-onlyIdempotent
Resolve a public @username to its underlying Telegram entity ID and object type (User, Channel, Group). Use before calling ID-based tools when only a username handle is known.
Inputs: username (required), account. Returns: result
search_cached_messagesSearch Local Offline SQLite Message ArchiveARead-onlyIdempotent
Search the local FTS5 SQLite archive for messages without making live Telegram API requests. Use for instantaneous, rate-limit-free search over synchronized messages. To sync messages into cache first, use sync_chat_cache.
Inputs: query (required), chat_id (required), limit, offset. Returns: result
search_contactsSearch Telegram Contact DirectoryARead-onlyIdempotent
Search your Telegram contacts directory by name, phone number, or username. Use when looking up a specific person. To view the entire directory, use list_contacts.
Inputs: query (required), account. Returns: result
search_messagesSearch Messages Within Specific ChatARead-onlyIdempotent
Search for text keywords within a specific Telegram chat or supergroup. Use when finding past conversations in a single chat. To search the offline cache without live Telegram API calls, use search_cached_messages.
Inputs: query (required), chat_id (required), limit, account. Returns: result
search_public_chatsSearch Public Channels and Groups GloballyARead-onlyIdempotent
Search Telegram globally for public channels, supergroups, and bots matching query terms. Use when discovering new public communities. To search within your existing chats, use list_chats or search_messages.
Inputs: query (required), limit, account. Returns: result
send_fileUpload and Send Document or FileA
Upload and send a local document or file to a chat. File path must resolve within configured MCP allowed roots. Requires TELEGRAM_SEND_ENABLED=true.
Inputs: chat_id (required), file_path (required), account, caption, +1 more. Returns: result
send_messageSend Text Message to Telegram ChatA
Send a text message to a specified Telegram chat, group, channel, or user. Mutation operation requiring TELEGRAM_SEND_ENABLED=true. For replying to an existing message, prefer reply_to_message.
Inputs: chat_id (required), message (required), account, parse_mode. Returns: result
sync_chat_cacheSynchronize Chat History to Local ArchiveARead-onlyIdempotent
Synchronize remote Telegram chat messages into the local SQLite/FTS5 offline cache database. Use before performing offline text searches or when populating local message archives. To search already synced messages without Telegram API calls, use search_cached_messages. To verify database integrity and index status, use check_cache_health.
Inputs: chat_id (required), mode, limit, account. Returns: object
unpin_messageUnpin Specific Message in ChatADestructiveIdempotent
Unpin a specific message from a chat or supergroup. Mutation operation requiring TELEGRAM_SEND_ENABLED=true. To pin a message, use pin_message.
Inputs: chat_id (required), message_id (required), account. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 22 tools
Every tool targets a distinct combination of resource and action, and descriptions explicitly cross-reference alternatives (e.g., get_messages vs search_messages, send_message vs reply_to_message, list_contacts vs search_contacts). Even the cached-search and live-search tools are clearly separated by offline/online behavior.
All tool names consistently follow a snake_case verb_noun pattern, such as list_chats, get_messages, send_message, pin_message, and search_contacts. Minor multi-word phrases like check_cache_health or mark_as_read still fit the same readable convention without stylistic mixing.
At 22 tools, the surface is noticeably heavy and borders on too many for the core purpose of interacting with Telegram. Each tool does add some distinct capability, but the cache-management cluster and multiple search variants contribute to a feeling of over-expansion.
The toolset covers the primary Telegram workflows well: reading chats and messages, sending/editing/deleting messages, replying, pinning, marking as read, file/media handling, contact lookup, public chat discovery, and offline cache search. Minor gaps such as forward_message, chat member management, and leaving chats mean it is not fully comprehensive for every possible account-level action.
Maintenance
Related MCP Connectors
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
Hosted Telegram MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Managed MCP gateway with OAuth, per-agent permissions, shared accounts and activity logs.
Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API
Related MCP Servers
- FlicenseBqualityDmaintenanceEnables MCP clients to interact with Telegram user accounts, providing tools for messaging, contacts, groups, channels, and media management through the Telegram API.853-
- AlicenseBqualityCmaintenanceEnables MCP clients to operate a Telegram account as a userbot, providing tools for reading and sending messages, searching chats and contacts, managing media, and performing other account actions via MTProto with a locally encrypted session.28MIT
- AlicenseAqualityCmaintenanceEnables local, privacy-first control of a personal Telegram account through MCP, using TDLib to read chats, send and reply to messages, search, transfer files, and interact with approved inline buttons.20MIT
- AlicenseNot gradedqualityCmaintenanceEnables MCP-compatible clients such as Claude and Cursor to access and manage Telegram accounts, chats, messages, contacts, media, folders, and admin operations through exposed tools.Apache 2.0