MCP server with Telegram search and messaging capabilities
Project description
๐ Demo
- Open https://tg-mcp.redevest.ru/setup to begin the authentication flow.
- After finishing, youโll receive a ready-to-use
mcp.jsonwith your Bearer token. - Use the config with your MCP client to check out this MCP server capabilities.
๐ Table of Contents
- โจ Features
- ๐ Prerequisites
- ๐ Choose Your Installation Path
- ๐๏ธ Server Modes
- ๐ฆ PyPI Installation
- ๐ณ Docker Deployment (Production)
- ๐ง Available Tools
- ๐ Health & Session Monitoring
- ๐ Project Structure
- ๐ฆ Dependencies
- ๐ Security & Authentication
- ๐ค Contributing
- ๐ License
- ๐ Acknowledgments
โจ Features
| Feature | Description |
|---|---|
| ๐ Smart Search | Global & per-chat message search with filters |
| ๐ฌ Messaging | Send, edit, reply with formatting support |
| ๐ฅ Contacts | Search users, get profiles, manage contacts |
| ๐ฑ Phone Integration | Message by phone number, auto-contact management |
| ๐ง Low-level API | Direct MTProto access for advanced operations |
| ๐ MTProto API Endpoint | HTTP endpoint for raw Telegram API calls with entity resolution and safety guardrails |
| ๐ Multi-User Auth | Bearer token authentication with session isolation |
| ๐๏ธ Dual Transport | HTTP (multi-user) and stdio (single-user) support |
| ๐ Secure File Sending | URL downloads with SSRF protection, size limits, and local-path restrictions |
| ๐ Session Management | LRU cache, automatic cleanup, health monitoring |
| โก Performance | Async operations, parallel queries, connection pooling |
| ๐ก๏ธ Reliability | Auto-reconnect, structured logging, error handling |
| ๐ฏ AI Optimization | Literal parameter constraints guide AI model choices |
๐ Prerequisites
- Python 3.10+
- Telegram API credentials (get them here)
- MCP-compatible client (Cursor, Claude Desktop, etc.)
๐ Choose Your Installation Path
| Path | Best For | Complexity | Maintenance |
|---|---|---|---|
| ๐ฆ PyPI | Most users, quick setup | โญโญโญโญโญ Easy | ๐ง Manual updates |
| ๐ณ Docker (Production) | Production deployment | โญโญโญโญ Easy | ๐ณ Container updates |
| ๐ป Local Development | Developers, contributors | โญโญโญ Medium | ๐ง Manual updates |
Choose your path below:
๐๏ธ Server Modes
The MCP server supports three distinct operation modes:
| Mode | Transport | Authentication | Use Case |
|---|---|---|---|
| STDIO | stdio | Disabled | Development with Cursor IDE |
| HTTP_NO_AUTH | HTTP | Disabled | Development HTTP server |
| HTTP_AUTH | HTTP | Required (Bearer token) | Production deployment |
๐ฆ PyPI Installation
1. Install from PyPI
pip install fast-mcp-telegram
2. Telegram Authentication & Token Generation
The setup process creates an authenticated session and generates a unique Bearer token for your use:
fast-mcp-telegram-setup --api-id="your_api_id" --api-hash="your_api_hash" --phone-number="+123456789"
# Additional options available:
# --overwrite # Auto-overwrite existing session
# --session-name NAME # Use custom session name (advanced users)
๐ Note: The setup script automatically loads .env files from the current directory if they exist, making authentication seamless. You can create a .env file by copying .env.example and filling in your values.
๐ Prefer a browser? Run the server and open /setup to authenticate and download a readyโtoโuse mcp.json without running the CLI setup.
๐ Bearer Token Output: After successful authentication, you'll receive a Bearer token:
โ
Setup complete!
๐ Session saved to: ~/.config/fast-mcp-telegram/AbCdEfGh123456789.session
๐ Bearer Token: AbCdEfGh123456789KLmnOpQr...
๐ก Use this Bearer token for authentication when using the MCP server:
Authorization: Bearer AbCdEfGh123456789KLmnOpQr...
3. Configure Your MCP Client
For STDIO mode (development with Cursor IDE):
{
"mcpServers": {
"telegram": {
"command": "fast-mcp-telegram",
"env": {
"API_ID": "your_api_id",
"API_HASH": "your_api_hash",
"PHONE_NUMBER": "+123456789"
}
}
}
}
For HTTP_NO_AUTH mode (development HTTP server):
{
"mcpServers": {
"telegram": {
"url": "http://localhost:8000"
}
}
}
For HTTP_AUTH mode (production with Bearer token):
{
"mcpServers": {
"telegram": {
"url": "https://your-server.com",
"headers": {
"Authorization": "Bearer AbCdEfGh123456789KLmnOpQr..."
}
}
}
}
4. Start Using!
{"tool": "search_messages_globally", "params": {"query": "hello", "limit": 5}}
{"tool": "send_message", "params": {"chat_id": "me", "message": "Hello from AI!"}}
โน๏ธ Session Info:
- STDIO mode: Session saved to
~/.config/fast-mcp-telegram/telegram.session - HTTP_NO_AUTH mode: Session saved to
~/.config/fast-mcp-telegram/telegram.session - HTTP_AUTH mode: Sessions saved as
~/.config/fast-mcp-telegram/{token}.session - Session Monitoring: Use
/healthHTTP endpoint to monitor active sessions and server statistics
โ You're all set! Jump to Available Tools to explore features.
๐ Web Setup (Browser Alternative to CLI)
In addition to the CLI setup, the server now includes a built-in browser setup flow as a first-class alternative:
- Open your serverโs
/setuproute (for the demo, go tohttps://tg-mcp.redevest.ru/setup). - Enter your phone number, then the code (and 2FA if enabled).
- The server immediately generates and displays a ready-to-use
mcp.jsonwith your Bearer token and a one-click download.
This is ideal if you prefer a guided flow without running the CLI. The CLI setup remains fully supported.
๐ณ Docker Deployment (Production)
Prerequisites
- Docker & Docker Compose installed
- Telegram API credentials (get them here)
- Domain name (for Traefik reverse proxy setup)
1. Environment Setup
Create a .env file in your project directory. You can copy from the example:
cp .env.example .env
Then edit .env with your actual values:
# Telegram API Credentials
API_ID=your_api_id
API_HASH=your_api_hash
# Domain Configuration (for remote docker deployment)
DOMAIN=your-domain.com
# Server Configuration
SERVER_MODE=http-auth # stdio, http-no-auth, or http-auth
HOST=0.0.0.0 # Bind address (auto-adjusts based on server mode)
PORT=8000 # Service port
# Optional: Session Management
MAX_ACTIVE_SESSIONS=10 # LRU cache limit for concurrent sessions
# Optional: Logging
LOG_LEVEL=INFO
Note: Phone numbers are specified during setup via CLI options rather than environment variables for better security and flexibility.
2. Telegram Authentication & Token Generation
Important: The setup process creates an authenticated Telegram session file and generates a Bearer token for HTTP authentication.
# 1. Run authentication setup with your phone number
docker compose --profile setup run --rm setup --phone-number="+1234567890"
# Alternative: Use all CLI options (bypasses .env file reading)
docker compose --profile setup run --rm setup \
--api-id="your_api_id" \
--api-hash="your_api_hash" \
--phone-number="+1234567890"
# 2. Note the Bearer token output after successful setup
# ๐ Bearer Token: AbCdEfGh123456789KLmnOpQr...
# 3. Start the main MCP server (if not already running)
docker compose --profile server up -d
Setup Options:
- Default: Use
--phone-numberwith .env file for API credentials - Full CLI: Specify all credentials via command line options
- Additional options:
--overwrite,--session-nameavailable
๐ Browser alternative: After the server is reachable, open https://<DOMAIN>/setup to authenticate via web and download mcp.json (no CLI needed). For local testing, use http://localhost:8000/setup.
Profile System:
--profile setup: Runs only the Telegram authentication setup--profile server: Runs only the MCP server (after authentication)- No profile: No services start (prevents accidental startup)
Authentication Output:
- Session file:
~/.config/fast-mcp-telegram/{token}.session - Bearer token: Unique token for HTTP authentication
- Multi-user support: Each setup creates isolated session
3. Domain Configuration (Optional)
The default domain is your-domain.com. To use your own domain:
- Set up DNS: Point your domain to your server
- Configure environment: Add
DOMAIN=your-domain.comto your.envfile - Traefik network: Ensure
traefik-publicnetwork exists on your host
Example:
# In your .env file
DOMAIN=my-telegram-bot.example.com
4. Local Docker Deployment
# After completing setup, start the MCP server (if not already running)
docker compose --profile server up --build -d
# Check logs
docker compose logs -f fast-mcp-telegram
# Check health
docker compose ps
Note: Run setup with docker compose --profile setup run --rm setup --phone-number="+1234567890" to authenticate and generate a Bearer token. No server shutdown or restart required.
The service will be available at http://localhost:8000 (internal) and through Traefik if configured.
5. Remote Server Deployment
For production deployment on a remote server:
# Set up environment variables for remote deployment
export VDS_USER=your_server_user
export VDS_HOST=your.server.com
export VDS_PROJECT_PATH=/path/to/deployment
# Run the deployment script
./scripts/deploy-mcp.sh
Post-deployment setup:
- SSH to your server and run the Telegram authentication setup:
ssh your_server_user@your.server.com cd /path/to/deployment docker compose --profile setup run --rm setup --phone-number="+1234567890"
- After setup completes, start the MCP server (if not already running):
docker compose --profile server up -d
The deployment script will:
- Transfer project files to your server
- Copy environment file
- Build the Docker containers (but won't start services automatically)
6. Configure Your MCP Client
For HTTP_AUTH mode (production with Bearer token):
{
"mcpServers": {
"telegram": {
"url": "https://your-domain.com",
"headers": {
"Authorization": "Bearer AbCdEfGh123456789KLmnOpQr..."
}
}
}
}
For HTTP_NO_AUTH mode (development HTTP server):
{
"mcpServers": {
"telegram": {
"url": "http://localhost:8000"
}
}
}
โ ๏ธ Important: Replace AbCdEfGh123456789KLmnOpQr... with your actual Bearer token from the setup process.
7. Verify Deployment
# Check container status
docker compose ps
# View logs
docker compose logs fast-mcp-telegram
# Test health endpoint (includes session statistics)
curl -s https://your-domain.com/health
Environment Variables:
SERVER_MODE=http-auth- Server mode (stdio, http-no-auth, http-auth)HOST=0.0.0.0- Bind to all interfaces (auto-adjusts based on server mode)PORT=8000- Service portDOMAIN- Domain for Traefik routing and web setupAPI_ID/API_HASH- Telegram API credentials (used by setup)- Phone number provided via CLI
--phone-numberoption during setup
Docker Compose Configuration:
The docker-compose.yml automatically sets the server to http-auth mode for production deployment with Bearer token authentication.
๐ง Available Tools
๐ฏ AI-Optimized Parameter Constraints
This MCP server uses Literal parameter types to guide AI model choices and ensure valid inputs:
parse_mode: Constrained to"markdown"or"html"(no invalid values)chat_type: Limited to"private","group", or"channel"for search filters- Enhanced Validation: FastMCP automatically validates these constraints
- Better AI Guidance: AI models see only valid options, reducing errors
๐ Supported Chat ID Formats
All tools that accept a chat_id parameter support these formats:
'me'- Saved Messages (your own messages)@username- Username (without @ symbol)123456789- Numeric user ID-1001234567890- Channel ID (always starts with -100)
๐ Search Query Guidelines
Important: Telegram search has specific limitations that AI models should understand:
โ What Works:
- Exact words:
"deadline","meeting","project" - Multiple terms:
"deadline, meeting, project"(comma-separated) - Partial words:
"proj"(finds "project", "projects", etc.) - Case insensitive:
"DEADLINE"finds "deadline", "Deadline", etc.
โ What Doesn't Work:
- Wildcards:
"proj*","meet%","dead*line" - Regex patterns:
"^project","deadline$","proj.*" - Boolean operators:
"project AND deadline","meeting OR call" - Quotes for exact phrases:
"exact phrase"(treated as separate words)
๐ก Best Practices:
- Use simple, common words that are likely to appear in messages
- Try multiple related terms:
"deadline, due, urgent" - Use partial words for broader matches:
"proj"instead of"project*"
| Tool | Purpose | Key Features |
|---|---|---|
search_messages_globally |
Search messages across all chats | Global search, filters by date/chat type |
search_messages_in_chat |
Search messages within specific chat | Per-chat search, total count support |
send_message |
Send new messages | Markdown/HTML formatting, replies, file sending (URLs/local) |
edit_message |
Edit existing messages | Update message content with formatting |
read_messages |
Read specific messages by ID | Bulk reading, full metadata |
find_chats |
Find users/groups/channels (uniform entity schema) | Name/username/phone; multi-term supported |
get_chat_info |
Get user/chat profile information | Bio, status, online state |
send_message_to_phone |
Message by phone number | Auto-contact management, file sending |
invoke_mtproto |
Direct Telegram API access | Advanced operations |
POST /mtproto-api/{method} |
HTTP endpoint for raw Telegram API calls | Enhanced with entity resolution and safety guardrails |
๐ search_messages_globally
Search messages across all Telegram chats
search_messages_globally(
query: str, // Search terms (comma-separated, required)
limit?: number = 50, // Max results
chat_type?: 'private'|'group'|'channel', // Filter by chat type
min_date?: string, // ISO date format
max_date?: string // ISO date format
)
Examples:
// Global search across all chats
{"tool": "search_messages_globally", "params": {"query": "deadline", "limit": 20}}
// Multi-term global search (comma-separated)
{"tool": "search_messages_globally", "params": {"query": "project, launch", "limit": 30}}
// Partial word search (finds "project", "projects", etc.)
{"tool": "search_messages_globally", "params": {"query": "proj", "limit": 20}}
// Filtered by date and type
{"tool": "search_messages_globally", "params": {
"query": "meeting",
"chat_type": "private",
"min_date": "2024-01-01"
}}
โ Common AI Model Mistakes to Avoid:
// DON'T use wildcards - these won't work:
{"tool": "search_messages_globally", "params": {"query": "proj*"}} // โ
{"tool": "search_messages_globally", "params": {"query": "meet%"}} // โ
// DON'T use regex - these won't work:
{"tool": "search_messages_globally", "params": {"query": "^project"}} // โ
{"tool": "search_messages_globally", "params": {"query": "deadline$"}} // โ
// DO use simple terms instead:
{"tool": "search_messages_globally", "params": {"query": "proj"}} // โ
{"tool": "search_messages_globally", "params": {"query": "meet"}} // โ
{"tool": "search_messages_globally", "params": {"query": "project"}} // โ
{"tool": "search_messages_globally", "params": {"query": "deadline"}} // โ
๐ search_messages_in_chat
Search messages within a specific Telegram chat
search_messages_in_chat(
chat_id: str, // Target chat ID (see Supported Chat ID Formats above)
query?: str, // Search terms (optional, returns latest if omitted)
limit?: number = 50, // Max results
min_date?: string, // ISO date format
max_date?: string // ISO date format
)
Examples:
// Search in specific chat
{"tool": "search_messages_in_chat", "params": {"chat_id": "-1001234567890", "query": "launch"}}
// Get latest messages from Saved Messages (no query = latest messages)
{"tool": "search_messages_in_chat", "params": {"chat_id": "me", "limit": 10}}
// Multi-term search in chat (comma-separated)
{"tool": "search_messages_in_chat", "params": {"chat_id": "telegram", "query": "update, news"}}
// Partial word search in chat
{"tool": "search_messages_in_chat", "params": {"chat_id": "me", "query": "proj"}}
๐ก Search Tips:
- No query: Returns latest messages from the chat
- Simple terms: Use common words that appear in messages
- Multiple terms: Use comma-separated words for broader results
- Partial words: Use shorter forms to catch variations (e.g., "proj" finds "project", "projects")
๐ฌ send_message
Send new messages with formatting and optional files
send_message(
chat_id: str, // Target chat ID (see Supported Chat ID Formats above)
message: str, // Message content (becomes caption when files sent)
reply_to_msg_id?: number, // Reply to specific message
parse_mode?: 'markdown'|'html', // Text formatting
files?: string | string[] // File URL(s) or local path(s)
)
File Sending:
files: Single file or array of files (URLs or local paths)- URLs: Public HTTP/HTTPS URLs are supported. SSRF protections block localhost, private IP ranges, and cloud metadata endpoints by default.
- Local paths: Only in stdio mode (blocked in HTTP modes)
- Size limits: Download size capped (configurable)
- Supports: images, videos, documents, audio, and other file types
- Multiple files are sent as an album when possible
- Message becomes the file caption when files are provided
Examples:
// Send text message
{"tool": "send_message", "params": {
"chat_id": "me",
"message": "Hello from AI! ๐"
}}
// Send file from URL
{"tool": "send_message", "params": {
"chat_id": "me",
"message": "Check this document",
"files": "https://example.com/document.pdf"
}}
// Send multiple images as album
{"tool": "send_message", "params": {
"chat_id": "@channel",
"message": "Project screenshots",
"files": ["https://example.com/img1.png", "https://example.com/img2.png"]
}}
// Send local file (stdio mode only)
{"tool": "send_message", "params": {
"chat_id": "me",
"message": "Report attached",
"files": "/path/to/report.pdf"
}}
// Blocked internal URL (SSRF protection)
{"tool": "send_message", "params": {
"chat_id": "me",
"message": "This will be rejected",
"files": "https://127.0.0.1:8000/health"
}}
// Reply with formatting
{"tool": "send_message", "params": {
"chat_id": "@username",
"message": "*Important:* Meeting at 3 PM",
"parse_mode": "markdown",
"reply_to_msg_id": 67890
}}
โ๏ธ edit_message
Edit existing messages with formatting
edit_message(
chat_id: str, // Target chat ID (see Supported Chat ID Formats above)
message_id: number, // Message ID to edit (required)
message: str, // New message content
parse_mode?: 'markdown'|'html' // Text formatting
)
Examples:
// Edit existing message
{"tool": "edit_message", "params": {
"chat_id": "-1001234567890",
"message_id": 12345,
"message": "Updated: Project deadline extended"
}}
// Edit with formatting
{"tool": "edit_message", "params": {
"chat_id": "me",
"message_id": 67890,
"message": "*Updated:* Meeting rescheduled to 4 PM",
"parse_mode": "markdown"
}}
๐ read_messages
Read specific messages by ID
read_messages(
chat_id: str, // Chat identifier (see Supported Chat ID Formats above)
message_ids: number[] // Array of message IDs to retrieve
)
Examples:
// Read multiple messages from Saved Messages
{"tool": "read_messages", "params": {
"chat_id": "me",
"message_ids": [680204, 680205, 680206]
}}
// Read from a channel
{"tool": "read_messages", "params": {
"chat_id": "-1001234567890",
"message_ids": [123, 124, 125]
}}
๐ฅ find_chats
Find users, groups, and channels (uniform entity schema)
find_chats(
query: str, // Search term(s); comma-separated for multi-term
limit?: number = 20, // Max results to return
chat_type?: 'private'|'group'|'channel' // Optional filter
)
Search capabilities:
- Saved contacts - Your Telegram contacts
- Global users - Public Telegram users
- Channels & groups - Public channels and groups
- Multi-term - "term1, term2" runs parallel searches and merges/dedupes
Query formats:
- Name:
"John Doe" - Username:
"telegram"(without @) - Phone:
"+1234567890"
Examples:
// Find by username
{"tool": "find_chats", "params": {"query": "telegram"}}
// Find by name
{"tool": "find_chats", "params": {"query": "John Smith"}}
// Find by phone
{"tool": "find_chats", "params": {"query": "+1234567890"}}
// Find only channels matching a term
{"tool": "find_chats", "params": {"query": "news", "chat_type": "channel"}}
โน๏ธ get_chat_info
Get user/chat profile information (enriched with member/subscriber counts)
get_chat_info(
chat_id: str // User/channel identifier (see Supported Chat ID Formats above)
)
Returns: Bio, status, online state, profile photos, and more.
Also includes, when applicable:
members_countfor groups (regular groups and megagroups)subscribers_countfor channels (broadcast)
Counts are fetched via Telethon full-info requests and reflect current values.
๐ง Uniform Entity Schema
All tools return chat/user objects in the same schema via build_entity_dict:
{
"id": 133526395,
"title": "John Doe", // falls back to full name or @username
"type": "private", // one of: private | group | channel
"username": "johndoe", // if available
"first_name": "John", // users
"last_name": "Doe", // users
"members_count": 1234, // groups (when available)
"subscribers_count": 56789 // channels (when available)
}
find_chats returns a list of these entities. Message search results include a chat field in the same format.
Examples:
// Get user details by ID
{"tool": "get_chat_info", "params": {"chat_id": "133526395"}}
// Get details by username
{"tool": "get_chat_info", "params": {"chat_id": "telegram"}}
// Get channel information
{"tool": "get_chat_info", "params": {"chat_id": "-1001234567890"}}
๐ฑ send_message_to_phone
Message by phone number (auto-contact management) with optional files
send_message_to_phone(
phone_number: str, // Phone with country code (+1234567890)
message: str, // Message content (becomes caption when files sent)
first_name?: str = "Contact", // For new contacts
last_name?: str = "Name", // For new contacts
remove_if_new?: boolean = false, // Remove temp contact after send
parse_mode?: 'markdown'|'html', // Text formatting
files?: string | string[] // File URL(s) or local path(s)
)
Features:
- Auto-creates contact if phone not in contacts
- Optional contact cleanup after sending
- Full formatting support
- File sending support (URLs or local paths)
- Multiple files sent as album when possible
Examples:
// Basic message to new contact
{"tool": "send_message_to_phone", "params": {
"phone_number": "+1234567890",
"message": "Hello from AI! ๐ค"
}}
// Message with file
{"tool": "send_message_to_phone", "params": {
"phone_number": "+1234567890",
"message": "Check this document",
"files": "https://example.com/document.pdf"
}}
// Message with formatting and cleanup
{"tool": "send_message_to_phone", "params": {
"phone_number": "+1234567890",
"message": "*Urgent:* Meeting rescheduled to 4 PM",
"parse_mode": "markdown",
"remove_if_new": true
}}
๐ง invoke_mtproto
Direct Telegram API access
invoke_mtproto(
method_full_name: str, // Full API method name (e.g., "messages.GetHistory")
params_json: str // JSON string of method parameters
)
Use cases: Advanced operations not covered by standard tools
Examples:
// Get your own user information
{"tool": "invoke_mtproto", "params": {
"method_full_name": "users.GetFullUser",
"params_json": "{\"id\": {\"_\": \"inputUserSelf\"}}"
}}
// Get chat message history
{"tool": "invoke_mtproto", "params": {
"method_full_name": "messages.GetHistory",
"params_json": "{\"peer\": {\"_\": \"inputPeerChannel\", \"channel_id\": 123456, \"access_hash\": 0}, \"limit\": 10}"
}}
๐ MTProto API Endpoint
HTTP endpoint for raw Telegram API calls with enhanced features
The server provides a dedicated HTTP endpoint for direct MTProto method invocation with additional conveniences:
Endpoint: POST /mtproto-api/{method} (alias: POST /mtproto-api/v1/{method})
Features:
- Case-insensitive method names: Accepts
messages.getHistory,messages.GetHistory, ormessages.GetHistoryRequest - Entity resolution: Optional automatic resolution of usernames, IDs, and phone numbers to proper Telegram entities
- Safety guardrails: Dangerous methods blocked by default (e.g.,
account.DeleteAccount,messages.DeleteHistory) - Multi-mode support: Works in all server modes with appropriate authentication
Request format:
{
"params": { "peer": "@durov", "limit": 5 },
"params_json": "{...}",
"resolve": true,
"allow_dangerous": false
}
Server mode behavior:
- stdio, http-no-auth: Proceeds without Bearer token
- http-auth: Requires
Authorization: Bearer <token>; missing/invalid returns 401 JSON error
Examples (http-auth):
# Send message with entity resolution
curl -X POST "https://<DOMAIN>/mtproto-api/messages.SendMessage" \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"params": {"peer": "me", "message": "Hello from MTProto API"},
"resolve": true
}'
# Get message history with automatic peer resolution
curl -X POST "https://<DOMAIN>/mtproto-api/messages.getHistory" \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"params": {"peer": "@telegram", "limit": 3},
"resolve": true
}'
# Forward messages with list resolution
curl -X POST "https://<DOMAIN>/mtproto-api/messages.ForwardMessages" \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"params": {
"from_peer": "@sourceChannel",
"to_peer": "me",
"id": [12345, 12346]
},
"resolve": true
}'
Response format:
- Success: JSON-safe
to_dict()result (bytes are base64-encoded) - Errors: Standardized error structure with appropriate HTTP status codes
- Dangerous methods: Blocked unless
allow_dangerous=trueis explicitly set
๐ Health & Session Monitoring
Monitor server health and session statistics
For HTTP deployments, the server provides a /health endpoint for monitoring:
# Check server health and session statistics
curl -s https://your-domain.com/health
Response includes:
- Server status and transport mode
- Active session count and limits
- Per-session statistics (token prefix, last access time, connection status)
- Service metadata
Example response:
{
"status": "healthy",
"service": "telegram-mcp-server",
"transport": "http",
"active_sessions": 3,
"max_sessions": 10,
"sessions": [
{
"token_prefix": "AbCdEfGh...",
"hours_since_access": 0.25,
"is_connected": true,
"last_access": "Thu Jan 4 16:30:15 2025"
}
]
}
๐ Project Structure
fast-mcp-telegram/
โโโ src/ # Source code
โ โโโ client/ # Telegram client management
โ โโโ config/ # Configuration and logging
โ โโโ server_components/ # Server modules (auth, health, tools, web setup)
โ โโโ templates/ # Web setup interface templates
โ โโโ tools/ # MCP tool implementations
โ โโโ utils/ # Utility functions
โ โโโ cli_setup.py # CLI setup with pydantic-settings
โ โโโ server.py # Main server entry point
โโโ tests/ # Test suite
โโโ memory-bank/ # Project documentation
โโโ scripts/ # Deployment scripts
โโโ .env.example # Environment template
โโโ docker-compose.yml # Docker configuration
โโโ Dockerfile # Container build
โโโ pyproject.toml # Project configuration
โโโ README.md # This file
Session Management: Session files are stored in the standard user config directory:
- All installations:
~/.config/fast-mcp-telegram/telegram.session(persistent storage) - Multi-user deployments:
~/.config/fast-mcp-telegram/{token}.session(token-based isolation)
Security Note: Session files contain sensitive authentication data and are never committed to version control. Each environment (local, Docker, remote server) maintains its own authenticated session.
๐ฆ Dependencies
| Package | Purpose |
|---|---|
| fastmcp | MCP server framework |
| telethon | Telegram API client |
| loguru | Structured logging |
| aiohttp | Async HTTP client |
| pydantic-settings | Configuration management |
Version Management: Single source of truth in src/_version.py with automatic synchronization across build system, runtime, and Docker deployments.
๐ Security & Authentication
๐จ CRITICAL SECURITY WARNING: This MCP server supports both single-user and multi-user deployments with Bearer token authentication.
Bearer Token Authentication System
- Per-Session Authentication: Each session requires a unique Bearer token
- Session Isolation: Each token creates an isolated Telegram session
- Token Generation: Cryptographically secure 256-bit tokens via setup script
- HTTP Authentication: Mandatory Bearer tokens for HTTP transport (
Authorization: Bearer <token>) - Development Mode:
DISABLE_AUTH=truebypasses authentication for development
Multi-User Security Model
- Session Separation: Each user gets their own authenticated session file
- Token Privacy: Bearer tokens should be treated as passwords and kept secure
- Session Files: Contain complete Telegram access for the associated token
- Account Access: Anyone with a valid Bearer token can perform ANY action on that associated Telegram account
Production Security Recommendations
- Secure Token Distribution: Distribute Bearer tokens through secure channels only
- Token Rotation: Regularly generate new tokens and invalidate old ones
- Access Monitoring: Monitor session activity through
/healthHTTP endpoint - Network Security: Use HTTPS/TLS and consider IP restrictions
- Session Management: Regularly clean up unused sessions and tokens
๐ค Contributing
We welcome contributions from the community! Please see our CONTRIBUTING.md for detailed development setup, testing guidelines, and contribution process.
Quick Start for Contributors
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
For detailed development setup and contribution guidelines, please refer to CONTRIBUTING.md.
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- FastMCP - MCP server framework
- Telethon - Telegram API library
- Model Context Protocol - Protocol specification
Made with โค๏ธ for the AI automation community
mcp-name: io.github.leshchenko1979/fast-mcp-telegram
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fast_mcp_telegram-0.7.0.tar.gz.
File metadata
- Download URL: fast_mcp_telegram-0.7.0.tar.gz
- Upload date:
- Size: 83.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ee14692df8c8e11d9f265c1e4288caa74a6283e86b3c2837cc80f69e3b26a9ac
|
|
| MD5 |
d294f0f8c7aea1c8a61065b87144c185
|
|
| BLAKE2b-256 |
050d4ebc64b1d5b48864d78ed4c224c91ec8d49dab7ce923b4246c0d9faf7cca
|
Provenance
The following attestation bundles were made for fast_mcp_telegram-0.7.0.tar.gz:
Publisher:
publish.yml on leshchenko1979/fast-mcp-telegram
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fast_mcp_telegram-0.7.0.tar.gz -
Subject digest:
ee14692df8c8e11d9f265c1e4288caa74a6283e86b3c2837cc80f69e3b26a9ac - Sigstore transparency entry: 576326731
- Sigstore integration time:
-
Permalink:
leshchenko1979/fast-mcp-telegram@93ca30c1fcfd07def2d59fd0c84a4554bbd71cc4 -
Branch / Tag:
refs/tags/0.7.0 - Owner: https://github.com/leshchenko1979
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@93ca30c1fcfd07def2d59fd0c84a4554bbd71cc4 -
Trigger Event:
release
-
Statement type:
File details
Details for the file fast_mcp_telegram-0.7.0-py3-none-any.whl.
File metadata
- Download URL: fast_mcp_telegram-0.7.0-py3-none-any.whl
- Upload date:
- Size: 64.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c24101b9a607cbcca8fd3ce052ffb94319e964351cd605dba9a4657cf2f72b78
|
|
| MD5 |
a727b0e8fcad4e6b85a7389408b8050e
|
|
| BLAKE2b-256 |
e42c0e2191aa88867bd1992f6686fbfc7a9279dce9b08053b79c1fd7b46dde53
|
Provenance
The following attestation bundles were made for fast_mcp_telegram-0.7.0-py3-none-any.whl:
Publisher:
publish.yml on leshchenko1979/fast-mcp-telegram
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fast_mcp_telegram-0.7.0-py3-none-any.whl -
Subject digest:
c24101b9a607cbcca8fd3ce052ffb94319e964351cd605dba9a4657cf2f72b78 - Sigstore transparency entry: 576326737
- Sigstore integration time:
-
Permalink:
leshchenko1979/fast-mcp-telegram@93ca30c1fcfd07def2d59fd0c84a4554bbd71cc4 -
Branch / Tag:
refs/tags/0.7.0 - Owner: https://github.com/leshchenko1979
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@93ca30c1fcfd07def2d59fd0c84a4554bbd71cc4 -
Trigger Event:
release
-
Statement type: