telegram-mcp
Provides tools for AI agents to interact with Telegram bots end-to-end, including sending commands and messages, clicking inline and reply buttons, testing bot workflows, exchanging media/files, performing inline queries, and running multi-step test suites.
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-mcpTest @my_test_bot: send /start, click the inline button, and verify the reply."
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
Autonomous Bot Testing, Automation & MTProto Control for AI Coding Agents
Disclaimer: This project is an independent open-source tool and is not affiliated with, authorized, maintained, sponsored, or endorsed by Telegram FZ-LLC, Telegram Messenger Inc., or any of their affiliates. "Telegram" is a registered trademark of its respective owners.
Environment Recommendation: We strongly recommend using the Test Server (TELEGRAM_TEST_MODE=true) for active bot development and automated verification. It carries zero risk to your main personal Telegram account. Make sure your target bot and user account are on the same environment (Test Bot โ Test Account, or Prod Bot โ Prod Account).
๐ Table of Contents
Related MCP server: telegram-bot-testing-mcp
๐ Features
๐ฌ Autonomous Bot Interaction: Send commands (
/start,/help), dispatch formatted Markdown/HTML messages, quote text, and await bot replies.๐๏ธ Keyboards & Telegram Mini Apps: Click inline keyboard buttons (
CallbackQuery), click bottom reply buttons (ReplyKeyboardMarkup), and extract authenticated Web App launch URLs (messages.RequestWebViewRequest) for Playwright/browser testing.๐ผ๏ธ Rich Media & File Verification: Upload documents, photos, audio, or circular voice notes, and download bot-generated media for visual and payload verification.
๐ณ๏ธ Native Polls & Quizzes: Dispatch single/multi-choice polls and programmatically vote or retract votes.
๐ฅ Chat Moderation & Admin Event Log: Inspect administrative audit logs (bans, kicks, permissions, title changes, deletions), create disposable test supergroups, and manage invite links.
โก Arbitrary MTProto Execution Sandbox (
telegram_execute_code): Direct access to the liveTelethon.TelegramClientinstance, raw TL functions, types, and event streams.๐ก๏ธ Dual-Mode Session Auth & Mismatch Shield: Connect using either interactive
StringSessionor existing SQLite.sessionfile paths, protected by an automatic DC environment mismatch shield.
๐๏ธ System Architecture
flowchart TD
subgraph Agents ["AI Coding Agents & IDEs"]
AgentA["Antigravity CLI (`agy`)"]
AgentB["Claude Desktop"]
AgentC["Cursor / Windsurf"]
AgentD["Cline / Roo Code"]
end
subgraph MCP ["MCP Server Layer (server.py)"]
MCPEngine["MCP Protocol Engine (JSON-RPC over stdio)"]
Tools["62 Registered MCP Tools"]
end
subgraph Service ["telegram-mcp Service Core (telegram_service.py)"]
Lock["Process Lock (/tmp/telegram-mcp.lock)"]
Shield["Environment Mismatch Shield"]
Auth["Session Manager (SQLite .session / StringSession)"]
Client["Telethon MTProto Engine"]
end
subgraph Telegram ["Telegram MTProto Network"]
TestCluster["Test Server Cluster (DC 2 Sandbox)"]
ProdCluster["Production Server Cluster (Live Network)"]
end
Agents -->|MCP Protocol / stdio| MCPEngine
MCPEngine --> Tools
Tools --> Lock
Lock --> Shield
Shield --> Auth
Auth --> Client
Client -->|TELEGRAM_TEST_MODE=true| TestCluster
Client -->|TELEGRAM_TEST_MODE=false| ProdClusterโก Companion Terminal CLI (tg-cli)
Looking for a human-friendly command-line interface to test bots, inspect chat history, and switch sessions directly from your terminal?
Check out telegram-mcp-cli:
# Install the companion CLI
pip install git+https://github.com/Telegram-mcp/telegram-mcp-cli.git
# Point directly to any existing Telethon .session file
tg-cli auth /path/to/my_account.session
# Inspect connection & environment alignment
tg-cli status
# Send commands and inspect responses
tg-cli command @BotFather /start๐ Setup & Installation
Option A: ๐ค Automated Setup via AI Agent (Recommended)
Paste this prompt directly into your AI assistant (Antigravity CLI, Cursor, Claude Code, Cline, Roo Code, or Windsurf):
Copy-Paste Prompt for your AI Assistant:
Set up the Telegram MCP server for me:
1. Clone & Navigate: Check if the repository is already present; if not, clone it and enter the directory:
git clone https://github.com/Telegram-mcp/telegram-mcp.git
cd telegram-mcp
2. Dependencies: Ensure Python 3.10+ is available and install dependencies:
pip install -r requirements.txt
3. Configuration: Copy `.env.example` to `.env`. Prompt me for my Telegram `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` (from https://my.telegram.org), and ask whether I prefer Test Server (`TELEGRAM_TEST_MODE=true`, recommended) or Production (`false`).
4. Telegram Login: Run `python3 login.py` interactively so I can authenticate, or let me specify an existing `TELEGRAM_SESSION_PATH`.
5. MCP Registration: Register this MCP server in my AI client configuration:
- Command: `python3`
- Args: `["<absolute-path-to-telegram-mcp>/server.py"]`
6. Verification: Call `telegram_status` to verify that the connection is healthy and all 62 tools are loaded.Option B: ๐ ๏ธ Manual Setup
1. Clone & Install Dependencies
git clone https://github.com/Telegram-mcp/telegram-mcp.git
cd telegram-mcp
pip install -r requirements.txt2. Configure Environment
Copy .env.example to .env:
cp .env.example .envAdd your Telegram API credentials from my.telegram.org:
TELEGRAM_API_ID=your_api_id
TELEGRAM_API_HASH=your_api_hash
TELEGRAM_TEST_MODE=true3. Configure Telegram Session
Choose either authentication method:
Method 1 (Interactive Phone/QR Login):
python3 login.pyGenerates and saves your
TELEGRAM_SESSIONstring into.env.Method 2 (Direct
.sessionSQLite File): If you already have an existing Telethon.sessionfile:TELEGRAM_SESSION_PATH=/absolute/path/to/your.session(The server will automatically load and authorize directly from your file without running
login.py).
4. Run the MCP Server
python3 server.py๐ Connecting to AI Agents
Antigravity CLI (agy)
The repository includes a pre-configured .agents/plugins/telegram-bot/ plugin. Any agy session started in this workspace automatically discovers and loads the tools.
Claude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"telegram-bot": {
"command": "python3",
"args": ["/path/to/telegram-mcp/server.py"],
"env": {
"TELEGRAM_API_ID": "your_api_id",
"TELEGRAM_API_HASH": "your_api_hash",
"TELEGRAM_SESSION": "your_session_string",
"TELEGRAM_SESSION_PATH": "/path/to/your.session",
"TELEGRAM_TEST_MODE": "false"
}
}
}
}Cursor / Cline / Roo Code / Windsurf
Add to your .cursor/mcp.json or Cline/Roo MCP settings:
{
"mcpServers": {
"telegram-bot": {
"command": "python3",
"args": ["/path/to/telegram-mcp/server.py"]
}
}
}๐ ๏ธ MCP Tools Matrix (62 Tools)
Tool Name | Parameters | Description |
|
| Sends |
|
| Sends formatted text queries or messages (Markdown/HTML). |
|
| Edits previously sent messages. |
|
| Deletes messages by ID. |
|
| Forwards messages between chats. |
|
| Sends emoji reactions (๐, ๐ฅ, โค๏ธ, etc.). |
|
| Clicks buttons in persistent bottom reply keyboards. |
|
| Single-step assertion check for automated tests. |
|
| Runs multi-step test workflows with assertions and delays. |
Tool Name | Parameters | Description |
|
| Triggers inline keyboard callback queries. |
|
| Tests |
|
| Extracts authenticated Web App launch URLs from Telegram Mini App buttons. |
|
| Explicitly waits for incoming bot replies or message edits. |
|
| Broadcasts chat presence indicators ( |
Tool Name | Parameters | Description |
|
| Sends photos, documents, audio, or circular voice notes. |
|
| Sends multiple media files grouped as an album. |
|
| Downloads media attachments from bot messages. |
|
| Downloads avatars/profile photos of users, bots, or groups. |
|
| Searches chat history filtered by specific media types. |
|
| Sends geographic coordinates or named venues. |
Tool Name | Parameters | Description |
|
| Creates native polls or quiz questions. |
|
| Votes on a poll or quiz option. |
|
| Retracts a previously cast vote. |
Tool Name | Parameters | Description |
|
| Inspects administrative audit logs of supergroups/channels. |
|
| Programmatically updates chat title or description text. |
|
| Creates disposable test supergroups, channels, or forum supergroups. |
|
| Permanently deletes a channel or supergroup. |
|
| Generates customizable chat invite links. |
|
| Joins public channels or private chats via invite links. |
|
| Leaves a channel or group. |
|
| Lists group participants with IDs, roles, and bot flags. |
|
| Inspects admin rights and restriction rules of a chat member. |
|
| Blocks a user or bot. |
|
| Unblocks a previously blocked peer. |
|
| Retrieves list of all currently blocked peers. |
Tool Name | Parameters | Description |
|
| Lists recent chats, groups, bots, and channels with unread counts. |
|
| Retrieves conversation history with full message structure. |
|
| Fetches surrounding conversation context around a message. |
|
| Searches message history by keyword. |
|
| Exports conversation history as clean Markdown or JSON for AI processing. |
|
| Clears dialog history for clean test states. |
|
| Marks messages in a chat as read. |
|
| Pins messages in bot or group chats. |
|
| Unpins messages in a chat. |
|
| Retrieves pinned messages from any chat. |
|
| Saves an uncommitted draft into the chat input field. |
|
| Schedules future automated delivery of a message. |
|
| Retrieves queued scheduled messages. |
|
| Cancels scheduled messages. |
|
| Mutes chat notifications. |
|
| Unmutes notifications. |
| None | Retrieves configured Telegram chat folders/filters. |
|
| Creates a new Telegram chat folder/filter. |
|
| Deletes a Telegram chat folder/filter by ID. |
|
| Writes directly to Telegram 'Saved Messages' cloud chat. |
|
| Reads notes and artifacts from Telegram 'Saved Messages'. |
|
| Retrieves saved contacts with privacy-masked phone numbers. |
Tool Name | Parameters | Description |
| None | Diagnostics for connection health, session mode, environment match, and user profile. |
|
| Executes arbitrary Python code with direct access to |
|
| Retrieves registered commands, description, and about text. |
|
| Inspects full user/bot profile metadata, Premium badge, and verification status. |
|
| Resolves username, phone, or ID into detailed entity metadata. |
๐งช Example Multi-Step Test Scenario
Using telegram_run_test_suite, an AI agent can execute an entire regression scenario in a single tool call:
[
{"action": "send", "text": "/start"},
{"action": "sleep", "seconds": 1.0},
{"action": "assert_reply", "contains": "Welcome to my bot!"},
{"action": "click_button", "text": "Settings"},
{"action": "sleep", "seconds": 0.5},
{"action": "assert_reply", "contains": "Notification Preferences"}
]๐ก๏ธ Security & Session Protection
Exclusive Process Lock (
/tmp/telegram-mcp.lock): Telegram permanently revokes session keys on duplicate connections (AuthKeyDuplicatedError). The server uses an OS-level flock to ensure no two processes run concurrently.Environment Mismatch Shield: Automatically inspects the Data Center IP of the session. If
TELEGRAM_TEST_MODEdoes not match the session cluster (Test vs. Production), the server halts with a clear error before Telegram rejects the key.Phone Privacy: User phone numbers are masked (
+16 ***** 4502) in all status outputs and logs.
๐ฌ Running Unit Tests
Run the test suite with pytest:
pip install -r requirements-dev.txt
python3 -m pytest tests -v๐ License
This project is open source under the MIT License.
Related MCP Connectors
Multi-tenant Telegram gateway for AI agents โ HTTP+stdio, 8 tools, MTProto User API
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
- openhelmOAuthai.openhelm
Autonomous cloud agent tasks: real browser + your tools, structured evidence-backed results.
Browser-based QA for AI-built software. Test pages with real browsers via agents.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables AI agents to interact with Telegram via MTProto, supporting high-performance communication and seamless integration.1-
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to test Telegram bots by driving the official Telegram Web client in a real browser, allowing visual verification of bot responses, inline keyboards, and Mini Apps.2MIT
- AlicenseNot gradedqualityAmaintenanceEnables AI agents to operate a Telegram account through the same commands as the terminal client: messaging, chat management, voice transcription, calls, stickers, and privacy settings.1MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to autonomously interact with, test, click inline buttons on, and verify Telegram bots end-to-end via MTProto.MIT