TE

Telegram MCP Server: Paginated Messaging via Telethon

Enable paginated chat reading, message retrieval, and sending on Telegram via an MCP server integrated with Telethon.

Quick Install
npx -y @chigwell/telegram-mcp

Overview

This MCP (Model Context Protocol) server exposes Telegram messaging capabilities through a small HTTP API backed by Telethon. It implements paginated reading of chat history, message retrieval by ID, and message sending. The server translates MCP-style tool calls into Telethon operations so language models or other agents can request contextual chat data and post messages without handling the Telegram client directly.

This is useful when you want to integrate Telegram chat context into an assistant or pipeline that expects the Model Context Protocol (MCP) tools surface. The server handles authentication with Telegram, paging through long chat histories, and returning structured message objects suitable for downstream processing or model input.

Features

  • Paginated chat reading (forward and backward) to fetch conversation slices
  • Retrieve a single message by ID with metadata
  • Send messages (plain text and simple replies)
  • Telethon-based Telegram client (supports user sessions and bot tokens)
  • MCP-compatible tool descriptions and JSON responses for easy agent integration
  • Simple HTTP interface suitable for local or containerized deployment

Installation / Configuration

Prerequisites: Python 3.9+, pip, a Telegram API ID and API hash (from https://my.telegram.org), and either a user Telethon session or a bot token.

Clone and install:

git clone https://github.com/chigwell/telegram-mcp.git
cd telegram-mcp
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Environment variables

export TELEGRAM_API_ID="123456"
export TELEGRAM_API_HASH="your_api_hash"
# Either provide a Telethon session file path or a bot token:
export TELEGRAM_SESSION="session_name"   # for user accounts
# or
export TELEGRAM_BOT_TOKEN="123456:ABC-DEF..."

Run the server (example with Uvicorn):

uvicorn telegram_mcp.server:app --host 0.0.0.0 --port 8080 --reload

On first run with a user session, Telethon will prompt for phone/2FA in the console to create the session file.

Security note: do not expose this server publicly without authentication; it can be used to read/write Telegram chats.

Available Tools / Resources

The server exposes the following high-level tools (HTTP endpoints). These mirror MCP “tools” that an agent can call.

EndpointMethodPurpose
/mcp/toolsGETList available tool definitions (MCP-style)
/mcp/paginate_messagesPOSTFetch a paginated slice of messages from a chat
/mcp/get_messagePOSTRetrieve a single message by ID
/mcp/send_messagePOSTSend a message to a chat

Example responses are JSON objects with fields like id, sender_id, text, date (ISO), and attachments metadata.

Useful links:

  • GitHub: https://github.com/chigwell/telegram-mcp
  • Telethon docs: https://docs.telethon.dev
  • MCP / tool integration pattern (see your agent framework docs)

API Examples

Paginated fetch (POST /mcp/paginate_messages):

Request body:

{
  "chat": "username_or_chat_id",
  "limit": 50,
  "anchor_message_id": 0,
  "direction": "backward"
}

Sample curl:

curl -X POST http://localhost:8080/mcp/paginate_messages \
  -H "Content-Type: application/json" \
  -d '{"chat":"@mychannel","limit":30,"direction":"backward"}'

Response (trimmed):

{
  "messages": [
    {"id":12345,"sender_id":111,"text":"Hello","date":"2024-04-01T12:00:00Z"},
    {"id":12344,"sender_id":222,"text":"Hi","date":"2024-04-01T11:59:00Z"}
  ],
  "has_more": true,
  "next_anchor": 12344
}

Get single message (POST /mcp/get_message):

curl -X POST http://localhost:8080/mcp/get_message \
  -H "Content-Type: application/json" \
  -d '{"chat":"@mychannel","message_id":12345}'

Send message (POST /mcp/send_message):

curl -X POST http://localhost:8080/mcp/send_message \
  -H "Content-Type: application/json" \
  -d '{"chat":"@mychannel","text":"Automated reply","reply_to_id":12345}'

Response:

{"message_id":12346,"date":"2024-04-01T12:01:00Z"}

Use Cases

  • Agent context retrieval: An assistant can request the last N messages from a chat to ground a reply. Using pagination avoids sending entire histories at once.
  • Moderation tooling: A moderation pipeline can walk backwards through chat history, sampling messages and extracting metadata for automated review.
  • Conversation summarization: Fetch a slice of messages, pass them to an LLM for summarization, and optionally send the summary back to the chat using the send_message tool.
  • Scripting and exports: Build a small exporter that pages through messages and writes them to a file or database for archival or analytics.
  • Interactive bots: Use a supervised agent to send messages programmatically while keeping chat context retrievable for decision-making.

Notes and Best Practices

  • Respect Telegram rate limits and API terms: paginate responsibly and avoid bulk scraping.
  • Prefer use of a bot token when functionality is limited to bot permissions; use user sessions only when necessary.
  • Secure the server behind an auth layer if you intend to use it in production (API keys, mutual TLS, or internal network).
  • Attachments and media are returned as metadata; downloading media should be implemented carefully (streaming, size limits).

For implementation details and examples, see the repository: https://github.com/chigwell/telegram-mcp.