better-telegram-mcp

Production-grade MCP server for Telegram with dual-mode Bot API + MTProto, 6 composite tools

Better Telegram MCP

mcp-name: io.github.n24q02m/better-telegram-mcp

CI codecov PyPI Docker License: MIT Python Telegram MCP semantic-release Renovate

better-telegram-mcp MCP server

Production-grade MCP server for Telegram with dual-mode support: Bot API (via httpx) for quick bot integrations and MTProto (via Telethon) for full user-account access including message search, history browsing, contact management, and group creation.

Features

  • 6 mega-tools with action dispatch: messages, chats, media, contacts, config, help
  • Dual mode: Bot API (httpx) for bots, MTProto (Telethon) for user accounts
  • 3-tier token optimization: Only 6 tools registered instead of 30+ individual endpoints
  • Tool annotations: Each tool declares readOnlyHint, destructiveHint, idempotentHint, openWorldHint
  • MCP Resources: Documentation available as telegram://docs/* resources
  • Auto-detect mode: Set bot token for bot mode, or API credentials for user mode
  • Web-based OTP auth: Browser-based authentication with remote relay support for headless environments

Why Better?

Featurebetter-telegram-mcpOther Telegram MCP servers
Dual mode (Bot + User/MTProto)YBot only
Composite mega-tools (6 vs 30+)YIndividual tools
Tool annotations (read-only, destructive hints)YN
MCP Resources (docs as resources)YN
Web-based OTP auth (no CLI needed)YCLI only
Remote auth relay (headless SSH/Docker)YN
Security hardening (SSRF, path traversal)YN
Docker multi-arch (amd64 + arm64)Yamd64 only

Token Optimization

Instead of registering 30+ individual tools, Better Telegram MCP uses a 3-tier mega-tool pattern:

TierDescriptionExample
6 mega-toolsAction dispatch via action parametermessages(action="send", ...)
Tool annotationsHints for AI model behaviorreadOnlyHint=False, destructiveHint=True
MCP ResourcesDocumentation as resourcestelegram://docs/messages

This reduces token overhead by ~80% compared to registering each action as a separate tool.

MCP Resources

URIContent
telegram://docs/messagesMessage operations reference
telegram://docs/chatsChat management reference
telegram://docs/mediaMedia send/download reference
telegram://docs/contactsContact management reference
telegram://statsAll documentation combined

Quick Start

Bot Mode

  1. Open Telegram, search for @BotFather
  2. Send /newbot, follow prompts to name your bot
  3. Copy the token (format: 123456789:ABCdefGHI-JKLmnoPQRstUVwxyz)
  4. Run:
TELEGRAM_BOT_TOKEN=123456:ABC-DEF uvx --python 3.13 better-telegram-mcp

User Mode

  1. Go to https://my.telegram.org, login with your phone number
  2. Click "API development tools", create an app
  3. Note your api_id (integer) and api_hash (32-char hex string)
  4. Add to your MCP config with all required env vars (see examples below)
  5. Start using — on first run, a local web page opens in your browser for OTP authentication:
    • Click "Send OTP Code" to receive a code in your Telegram app
    • Enter the OTP code on the web page
    • If 2FA is enabled, enter your password on the same page
    • Headless (Docker/SSH): use curl to hit the same endpoints (URL shown in logs/error messages)
  6. Done — session file persists at ~/.better-telegram-mcp/<name>.session, no more auth needed on subsequent runs

Security: The session file has 600 permissions (owner-only). Treat it like a password — anyone with this file can access your Telegram account.

Configuration

All configuration is via environment variables with TELEGRAM_ prefix:

VariableRequiredDefaultDescription
TELEGRAM_BOT_TOKENBot mode-Bot token from @BotFather
TELEGRAM_API_IDUser mode-API ID from my.telegram.org
TELEGRAM_API_HASHUser mode-API hash from my.telegram.org
TELEGRAM_PHONEUser mode-Phone number with country code (e.g., +84912345678). Required for web auth UI.
TELEGRAM_AUTH_URLNohttps://better-telegram-mcp.n24q02m.comAuth server URL. Use local for localhost mode, or a custom URL for self-hosted relay.
TELEGRAM_SESSION_NAMENodefaultSession file name (for multiple accounts)
TELEGRAM_DATA_DIRNo~/.better-telegram-mcpData directory for session files

Mode detection: If TELEGRAM_API_ID + TELEGRAM_API_HASH are set, user mode is used (priority). Otherwise, TELEGRAM_BOT_TOKEN is used for bot mode. No silent fallback between modes.

MCP Config Examples

Claude Code

# Bot mode
claude mcp add telegram -e TELEGRAM_BOT_TOKEN=123456:ABC-DEF -- uvx --python 3.13 better-telegram-mcp

# User mode (auto-auth on first run)
claude mcp add telegram -e TELEGRAM_API_ID=12345 -e TELEGRAM_API_HASH=abc123 -e TELEGRAM_PHONE=+1234567890 -- uvx --python 3.13 better-telegram-mcp

Claude Desktop / Cursor

Bot mode:

{
  "mcpServers": {
    "telegram": {
      "command": "uvx",
      "args": ["--python", "3.13", "better-telegram-mcp"],
      "env": {
        "TELEGRAM_BOT_TOKEN": "123456:ABC-DEF"
      }
    }
  }
}

User mode:

{
  "mcpServers": {
    "telegram": {
      "command": "uvx",
      "args": ["--python", "3.13", "better-telegram-mcp"],
      "env": {
        "TELEGRAM_API_ID": "12345678",
        "TELEGRAM_API_HASH": "your-api-hash-from-my-telegram-org",
        "TELEGRAM_PHONE": "+1234567890"
      }
    }
  }
}

VS Code Copilot

Add to .vscode/mcp.json:

{
  "servers": {
    "telegram": {
      "command": "uvx",
      "args": ["--python", "3.13", "better-telegram-mcp"],
      "env": {
        "TELEGRAM_BOT_TOKEN": "123456:ABC-DEF"
      }
    }
  }
}

Docker

# Bot mode
docker run -i --rm -e TELEGRAM_BOT_TOKEN=123456:ABC-DEF n24q02m/better-telegram-mcp

# User mode (auto-auth on first run, mount session dir for persistence)
docker run -i --rm \
  -e TELEGRAM_API_ID=12345 \
  -e TELEGRAM_API_HASH=abcdef123456 \
  -e TELEGRAM_PHONE=+84912345678 \
  -v ~/.better-telegram-mcp:/data \
  n24q02m/better-telegram-mcp

Docker config for MCP clients:

{
  "mcpServers": {
    "telegram": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-e", "TELEGRAM_BOT_TOKEN",
        "n24q02m/better-telegram-mcp"
      ],
      "env": {
        "TELEGRAM_BOT_TOKEN": "123456:ABC-DEF"
      }
    }
  }
}

Note: For user mode in Docker, mount the session directory with -v ~/.better-telegram-mcp:/data so the session persists across container restarts. On first run, the auth web server starts on localhost — use port mapping (-p 8080:PORT) or curl to complete auth.

Mode Capabilities

FeatureBot ModeUser Mode
Send messagesYY
Edit messagesYY
Delete messagesYY
Forward messagesYY
Pin messagesYY
React to messagesYY
Search messages-Y
Browse history-Y
List chats-Y
Get chat infoYY
Create groups/channels-Y
Join/Leave chatsPartialY
Manage membersYY
Admin promotionYY
Chat settingsYY
Forum topicsPartialY
Send media (photo/file/voice/video)YY
Download media-Y
List contacts-Y
Search contacts-Y
Add contacts-Y
Block/Unblock users-Y

Tool Reference

Use the help tool for full documentation:

help(topic="messages")  # Message operations
help(topic="chats")     # Chat management
help(topic="media")     # Media send/download
help(topic="contacts")  # Contact management
help(topic="all")       # Everything

Troubleshooting

ErrorCauseFix
No Telegram credentials foundNeither bot token nor API credentials setSet TELEGRAM_BOT_TOKEN or TELEGRAM_API_ID + TELEGRAM_API_HASH
Invalid bot tokenToken revoked or wrongRegenerate via /token in @BotFather
not authenticatedSession not yet authorizedOpen the auth URL shown in error message (browser or curl)
PhoneNumberInvalidErrorWrong phone formatInclude country code with + (e.g., +84912345678)
SessionPasswordNeededError2FA enabledEnter 2FA password on the web auth page
FloodWaitErrorToo many auth attemptsWait the indicated seconds before retrying
requires user modeAction not available in bot modeSwitch to user mode (API ID + Hash)
Session lost after Docker restartData volume not mountedAdd -v ~/.better-telegram-mcp:/data
OTP sent but where?Code goes to Telegram appCheck the Telegram app on your phone (not SMS). Look for a message from "Telegram" with a login code.
Headless auth?No browser availableUse curl: curl -X POST http://127.0.0.1:PORT/send-code then curl -X POST http://127.0.0.1:PORT/verify -d '{"code":"12345"}'

Self-Hosting Auth Relay

By default, OTP authentication uses the hosted relay at better-telegram-mcp.n24q02m.com. To self-host:

# Build and run the auth relay server
cd auth-relay
docker build -t telegram-auth-relay .
docker run -d -p 8080:8080 --name telegram-auth-relay telegram-auth-relay

Then set the MCP server to use your relay:

{
  "env": {
    "TELEGRAM_AUTH_URL": "https://your-domain.com"
  }
}

Or use TELEGRAM_AUTH_URL=local for localhost-only mode (no remote relay).

ModeTELEGRAM_AUTH_URLUse case
Remote (default)https://better-telegram-mcp.n24q02m.comHeadless, SSH, any browser
Self-hostedhttps://your-domain.comCustom deployment
LocallocalDesktop, offline, no remote

Build from Source

git clone https://github.com/n24q02m/better-telegram-mcp.git
cd better-telegram-mcp
uv sync --group dev
uv run ruff check .
uv run pytest
uv run better-telegram-mcp

Compatible With

Claude Desktop Claude Code Cursor VS Code Copilot Antigravity Gemini CLI OpenAI Codex OpenCode

Also by n24q02m

ServerDescriptionInstall
better-notion-mcpNotion API for AI agentsnpx -y @n24q02m/better-notion-mcp@latest
better-email-mcpEmail (IMAP/SMTP) for AI agentsnpx -y @n24q02m/better-email-mcp@latest
wet-mcpWeb search, extraction, library docsuvx --python 3.13 wet-mcp@latest
mnemo-mcpPersistent AI memory with hybrid searchuvx mnemo-mcp@latest
better-godot-mcpGodot Engine for AI agentsnpx -y @n24q02m/better-godot-mcp@latest

Contributing

See CONTRIBUTING.md.

Privacy

See PRIVACY.md.

Changelog

See CHANGELOG.md.

License

MIT - See LICENSE.

Máy chủ liên quan