jayeshchowdary/telegram-mcp
If you are the rightful owner of telegram-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
A comprehensive Model Context Protocol (MCP) server that provides full Telegram Bot API integration with advanced features like message tracking, search, and multimedia support.
Telegram MCP Server
A comprehensive Model Context Protocol (MCP) server that provides full Telegram Bot API integration with advanced features like message tracking, search, and multimedia support.
š Features
Core Messaging
- Send text messages, photos, documents, and locations
- Edit and delete messages sent by the bot
- Forward messages between chats
- Support for HTML and Markdown formatting
- Inline keyboard markup support
Advanced Features
- Message Tracking: Local SQLite database stores all bot messages with full lifecycle tracking
- Message Search: Search through stored bot messages by content
- Chat Management: Get chat info, administrators, member counts
- Poll Support: Create regular and quiz polls with timing controls
- Location Sharing: Send static and live locations with proximity alerts
Database Integration
- Automatic storage of all bot-sent messages
- Edit history tracking with original text preservation
- Deletion tracking with timestamps
- Full-text search capabilities
- Message lifecycle management
š¦ Installation
- Clone the repository
- Follow the complete setup guide
- Configure your bot token and chat ID via environment variables
- Install dependencies:
uv sync
- Run the server:
./run_server.sh
āļø Configuration
Environment Variables
TELEGRAM_BOT_TOKEN
: Your Telegram bot token (required)TELEGRAM_CHAT_ID
: Default chat ID to use (optional)
š ļø Available Tools
Core Messaging Tools
-
send_message: Send text messages through Telegram
message
(required): The message to sendchat_id
(optional): Chat ID to send to (uses TELEGRAM_CHAT_ID if not provided)parse_mode
(optional): Parse mode for the message (default: "HTML")
-
edit_message: Edit text messages sent by the bot
text
(required): The new text content for the messagechat_id
(optional): Chat ID where the message was sentmessage_id
(optional): ID of the message to editinline_message_id
(optional): ID of the inline message to editparse_mode
(optional): Parse mode for the message (default: "HTML")disable_web_page_preview
(optional): Disable web page preview (default: False)reply_markup
(optional): JSON string of inline keyboard markup
-
delete_message: Delete messages sent by the bot
chat_id
(required): Chat ID where the message is locatedmessage_id
(required): ID of the message to delete
Multimedia Tools
-
send_photo: Send photos to a Telegram chat
chat_id
(required): Chat ID to send the photo tophoto
(required): File path or URL of the photo to sendcaption
(optional): Caption for the photo (max 1024 characters)parse_mode
(optional): Parse mode for the caption (default: "HTML")disable_notification
(optional): Whether to disable notification (default: False)reply_to_message_id
(optional): ID of the message to reply toreply_markup
(optional): JSON string of inline keyboard markup
-
send_document: Send general files (documents) to a Telegram chat
chat_id
(required): Chat ID to send the document todocument
(required): File path or URL of the document to sendcaption
(optional): Caption for the document (max 1024 characters)parse_mode
(optional): Parse mode for the caption (default: "HTML")disable_notification
(optional): Whether to disable notification (default: False)reply_to_message_id
(optional): ID of the message to reply toreply_markup
(optional): JSON string of inline keyboard markupdisable_content_type_detection
(optional): Whether to disable content type detection (default: False)thumbnail
(optional): File path or URL for document thumbnail
-
send_location: Send point on the map location to a Telegram chat
chat_id
(required): Chat ID to send the location tolatitude
(required): Latitude of the location (-90 to 90)longitude
(required): Longitude of the location (-180 to 180)horizontal_accuracy
(optional): The radius of uncertainty for the location in meters (1-1500)live_period
(optional): Period in seconds for which the location will be updated (60-86400)heading
(optional): For live locations, direction in which the user is moving in degrees (1-360)proximity_alert_radius
(optional): For live locations, maximum distance for proximity alerts in meters (1-100000)disable_notification
(optional): Whether to disable notification (default: False)reply_to_message_id
(optional): ID of the message to reply toreply_markup
(optional): JSON string of inline keyboard markup
Poll Tools
- send_poll: Send a native poll to a Telegram chat
chat_id
(required): Chat ID to send the poll toquestion
(required): Poll question (max 300 characters)options
(required): JSON array of poll options (2-10 options, each max 100 characters)allows_multiple_answers
(optional): Whether multiple answers are allowed (default: False)is_anonymous
(optional): Whether the poll is anonymous (default: True)poll_type
(optional): Poll type - "regular" or "quiz" (default: "regular")correct_option_id
(optional): 0-based identifier of correct answer for quiz pollsexplanation
(optional): Text shown when user selects wrong answer in quiz pollsexplanation_parse_mode
(optional): Parse mode for explanation (default: "HTML")open_period
(optional): Poll duration in seconds (5-600 seconds)close_date
(optional): Unix timestamp when poll should be closedis_closed
(optional): Whether the poll is immediately closed (default: False)disable_notification
(optional): Whether to disable notification (default: False)reply_to_message_id
(optional): ID of the message to reply toreply_markup
(optional): JSON string of inline keyboard markup
Chat Management Tools
-
get_chat: Get up to date information about the chat
chat_id
(required): Chat ID to get information about
-
get_chat_administrators: Get a list of administrators in a chat
chat_id
(required): Chat ID to get administrators from
-
get_chat_members_count: Get the number of members in a chat
chat_id
(required): Chat ID to get member count from
-
get_me: Get basic information about the bot
- No parameters required
-
export_chat_invite_link: Generate a new primary invite link for a chat
chat_id
(required): Chat ID to generate invite link for
-
forward_message: Forward messages of any kind
chat_id
(required): Chat ID to forward the message tofrom_chat_id
(required): Chat ID where the original message is locatedmessage_id
(required): ID of the message to forwarddisable_notification
(optional): Whether to disable notification (default: False)
Message History Tools
- get_chat_history: Get chat history messages (incoming messages only)
chat_id
(required): Chat ID to get history fromlimit
(optional): Maximum number of messages to retrieve (default: 10, max: 100)message_id
(optional): Specific message ID to start fromoffset
(optional): Identifier of the first update to be returned (default: 0)- WARNING: This only shows incoming messages (sent TO the bot), not outgoing messages (sent BY the bot)
Utility Tools
-
get_message_by_id: Get a specific message by its ID
chat_id
(required): Chat ID where the message is locatedmessage_id
(required): ID of the message to retrieve- Note: Limited to messages in recent getUpdates cache
-
get_updates: Get recent updates (messages) from Telegram to retrieve message IDs
limit
(optional): Maximum number of updates to retrieve (default: 10, max: 100)offset
(optional): Identifier of the first update to be returned (default: 0)timeout
(optional): Timeout in seconds for long polling (default: 0)
-
get_default_chat_id_tool: Get the currently set default chat ID from environment variable
šÆ Usage Instructions
Setting Up Chat ID
You can set your chat ID in two ways:
- Environment Variable: Set
TELEGRAM_CHAT_ID
environment variable (recommended for default behavior) - Explicit Parameter: Provide
chat_id
parameter in each tool call (for sending to different chats)
š„ļø Using with MCP Inspector (Local Testing)
The MCP Inspector is perfect for testing and exploring the Telegram MCP server locally.
Step 1: Start the MCP Server
# Set environment variables
export TELEGRAM_BOT_TOKEN="your_bot_token_here"
export TELEGRAM_CHAT_ID="1234567890"
# Run the server
./run_server.sh
Step 2: Start the MCP Inspector
# In a new terminal window
npx @modelcontextprotocol/inspector uv run server.py
Step 3: Test Tools in the Inspector
The inspector will open a web interface where you can:
- Browse Available Tools: See all 17 available tools with their parameters
- Test Tool Calls: Fill in parameters and execute tools
- View Responses: See detailed JSON responses from each tool
- Debug Issues: Inspect error messages and debug problems
Example Inspector Usage
Send a Message:
{
"name": "send_message",
"arguments": {
"message": "Hello from MCP Inspector!",
"chat_id": "1234567890"
}
}
Send a Photo:
{
"name": "send_photo",
"arguments": {
"chat_id": "1234567890",
"photo": "https://picsum.photos/400/300",
"caption": "Random image from Picsum!"
}
}
Create a Poll:
{
"name": "send_poll",
"arguments": {
"chat_id": "1234567890",
"question": "What's your favorite programming language?",
"options": "[\"Python\", \"JavaScript\", \"Java\", \"C++\"]",
"poll_type": "regular"
}
}
š Using with MCP Clients
MCP clients can connect to the Telegram MCP server to integrate Telegram functionality into their applications.
Client Configuration
For Claude Desktop:
Add to your claude_desktop_config.json
:
{
"mcpServers": {
"telegram-mcp": {
"command": "uv",
"args": ["run", "server.py"],
"env": {
"TELEGRAM_BOT_TOKEN": "your_bot_token_here",
"TELEGRAM_CHAT_ID": "1234567890"
}
}
}
}
For Other MCP Clients: Configure your client to connect to the MCP server using:
- Command:
uv run server.py
- Environment Variables: Set
TELEGRAM_BOT_TOKEN
and optionallyTELEGRAM_CHAT_ID
Client Usage Examples
Send a Message:
{
"name": "send_message",
"arguments": {
"message": "Hello from MCP client!",
"parse_mode": "HTML"
}
}
Send a Document:
{
"name": "send_document",
"arguments": {
"chat_id": "1234567890",
"document": "/path/to/file.pdf",
"caption": "Here's the document you requested!"
}
}
Send a Location:
{
"name": "send_location",
"arguments": {
"chat_id": "1234567890",
"latitude": "37.7749",
"longitude": "-122.4194",
"horizontal_accuracy": "10"
}
}
Get Chat Information:
{
"name": "get_chat",
"arguments": {
"chat_id": "1234567890"
}
}
Create a Quiz Poll:
{
"name": "send_poll",
"arguments": {
"chat_id": "1234567890",
"question": "What is the capital of France?",
"options": "[\"London\", \"Paris\", \"Berlin\", \"Madrid\"]",
"poll_type": "quiz",
"correct_option_id": "1",
"explanation": "Paris is the capital and largest city of France."
}
}
š Database Features
The MCP server automatically stores all bot messages in a local SQLite database (telegram_bot_messages.db
) with full lifecycle tracking. Note: Database-related tools have been temporarily disabled.
š§ Advanced Usage Patterns
Message Lifecycle Management
// 1. Send a message
{
"name": "send_message",
"arguments": {
"message": "This is a test message",
"chat_id": "1234567890"
}
}
// Response: {"success": true, "message_id": 123, ...}
// 2. Edit the message
{
"name": "edit_message",
"arguments": {
"text": "This is an edited test message",
"message_id": "123",
"chat_id": "1234567890"
}
}
// 3. Delete the message
{
"name": "delete_message",
"arguments": {
"message_id": "123",
"chat_id": "1234567890"
}
}
Poll Management
// Create a timed poll
{
"name": "send_poll",
"arguments": {
"chat_id": "1234567890",
"question": "Quick vote: Should we have a meeting today?",
"options": "[\"Yes\", \"No\", \"Maybe\"]",
"open_period": "300"
}
}
Live Location Sharing
{
"name": "send_location",
"arguments": {
"chat_id": "1234567890",
"latitude": "37.7749",
"longitude": "-122.4194",
"live_period": "3600",
"heading": "45",
"proximity_alert_radius": "1000"
}
}
ā ļø Important: Telegram API Limitations
Bot Message Visibility Issue
The Telegram Bot API has a fundamental limitation: getUpdates
only shows incoming messages (sent TO the bot), not outgoing messages (sent BY the bot).
This means:
- ā
get_chat_history
- Shows messages sent TO your bot - ā
get_message_by_id
- Limited to messages in getUpdates cache
Best Practice Workflow
For reliable bot message management:
- Send a message using
send_message
and note the returnedmessage_id
- Edit the message using
edit_message
with the storedmessage_id
- Track message IDs in your application for future reference
Example Workflow
// 1. Send message and get message_id
{
"name": "send_message",
"arguments": {
"message": "Hello! This is message #1"
}
}
// Response: {"success": true, "message_id": 123, ...}
// 2. Edit the message using the message_id
{
"name": "edit_message",
"arguments": {
"text": "Hello! This is message #1 (edited)",
"message_id": 123
}
}
Requirements
- Python 3.13+
- uv package manager
- Telegram bot token
- Valid chat ID
License
MIT
Complete Setup Guide for New Users
This section provides detailed step-by-step instructions for setting up the Telegram MCP Server on a new machine from scratch.
Step 1: Prerequisites Installation
Install Python 3.13+
- macOS: Install via Homebrew:
brew install python@3.13
- Windows: Download from python.org
- Linux: Use your package manager (e.g.,
sudo apt install python3.13
)
Install uv Package Manager
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows (PowerShell)
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# Alternative: via pip
pip install uv
Step 2: Clone the Repository
# Clone the repository
git clone <repository-url>
cd telegram-mcp
# Or download and extract the ZIP file
# Then navigate to the extracted directory
Step 3: Create a Telegram Bot
3.1 Open Telegram Application
- Launch the Telegram app on your device (mobile or desktop)
3.2 Start a Chat with BotFather
- In the search bar at the top, type
@BotFather
and select the verified account named "BotFather" - Click the "Start" button at the bottom of the chat window to initiate the conversation
3.3 Create a New Bot
- Type
/newbot
and press Enter - BotFather will prompt you to choose a name for your bot. Type your desired bot name (e.g., "MyTelegramMCPBot") and press Enter
- Next, you'll be asked to choose a username for your bot. This username must end with "bot" (e.g.,
MyTelegramMCPBot
). Type the username and press Enter
3.4 Receive the API Token
- Upon successful creation, BotFather will provide a message containing your bot's API token. It will look something like:
Use this token to access the HTTP API: 123456789:ABCDEF_your_real_token_here
- Copy this token and store it securely; you'll need it to interact with the Telegram API
Step 4: Get Your Chat ID
4.1 Find Your Chat ID
- Start a chat with your bot in Telegram
- Send any message to your bot
- Visit:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
- Look for the "chat" object and note the "id" field - this is your chat ID
Step 5: Project Setup
5.1 Install Dependencies
# Navigate to the project directory
cd telegram-mcp
# Install dependencies using uv
uv sync
5.2 Update Run Script (Important!)
The run_server.sh
script contains placeholders for your credentials. Update it:
# Edit the run_server.sh file
nano run_server.sh # or use your preferred editor
Replace the placeholders with your actual values:
#!/bin/bash
# Set Telegram bot token environment variable
export TELEGRAM_BOT_TOKEN="123456789:ABCDEF_your_real_token_here"
# Set default chat ID environment variable (optional)
export TELEGRAM_CHAT_ID="1234567890"
# Run the server using uv
uv run server.py
5.3 Make Script Executable
chmod +x run_server.sh
Step 6: Test the Server
6.1 Start the Server
./run_server.sh
You should see output like:
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā®
ā š„ļø Server name: telegram-mcp ā
ā š¦ Transport: STDIO ā
ā šļø FastMCP version: 2.12.2 ā
ā š¤ MCP SDK version: 1.13.1 ā
ā°āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāÆ
6.2 Test with MCP Client
Connect your MCP client to test the server. The server provides tools like:
send_message
- Send messages to Telegram chats and usersedit_message
- Edit text messages sent by the botget_chat_history
- Get chat history to see both incoming and outgoing messagesget_updates
- Get recent updates (messages) to retrieve message IDsget_default_chat_id_tool
- Get the currently set default chat ID
Step 7: Troubleshooting
Common Issues:
-
"TELEGRAM_BOT_TOKEN environment variable not set" error:
- Ensure your bot token is correctly set in
run_server.sh
- Check that the token is valid and not expired
- Ensure your bot token is correctly set in
-
"No chat ID provided and TELEGRAM_CHAT_ID environment variable not set" error:
- Set the
TELEGRAM_CHAT_ID
environment variable inrun_server.sh
- Or provide a
chat_id
parameter when callingsend_message
- Set the
-
"Error connecting to Telegram bot" error:
- Verify your bot token is correct
- Check that your bot is still active in BotFather
- Ensure you have internet connectivity
-
"Module not found" errors:
- Run
uv sync
to ensure all dependencies are installed - Check that you're using the correct Python version (3.13+)
- Run
-
Server won't start:
- Check that
uv
is properly installed - Verify the
run_server.sh
script is executable - Check that your bot token is valid
- Check that
Getting Help:
- Check the server logs for detailed error messages
- Verify your Telegram bot setup with BotFather
- Ensure all file permissions are correct
- Test with a simple MCP client first
Step 8: Security Best Practices
-
Never commit tokens:
- Add
run_server.sh
to.gitignore
if it contains your token - Use environment variables for production deployments
- Keep your bot token secure and private
- Add
-
Limit bot permissions:
- Only grant necessary permissions to your bot
- Regularly review your bot's settings in BotFather
-
Secure token storage:
- Consider using encrypted storage for production
- Never share your bot token publicly
Step 9: Production Deployment
For production use:
- Use environment variables instead of hardcoded tokens
- Implement proper logging and monitoring
- Set up proper backup and recovery procedures
- Monitor API usage and rate limits
File Structure
telegram-mcp/
āāā server.py # Main MCP server implementation
āāā pyproject.toml # uv project configuration
āāā uv.lock # Dependency lock file
āāā run_server.sh # Server startup script
āāā run_server_template.sh # Template for run_server.sh
āāā README.md # This file
āāā main.py # Entry point
āāā .gitignore # Git ignore rules
API Features
The server provides these Telegram API features:
- Send messages to chats and users
- Edit text messages sent by the bot
- Get chat history with both incoming and outgoing messages
- Get recent updates and message IDs
- Support for HTML and Markdown formatting
- Inline keyboard markup support
- Error handling and validation
- Default chat ID support
- Chat ID validation
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request