Skip to content
Back to search

telegram-mcp

Telegram MCP server powered by Telethon to let MCP clients read chats, manage groups, and send/modify messages, media, contacts, and settings.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/chigwell/telegram-mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/chigwell/telegram-mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/chigwell--telegram-mcp/badge.svg)](/listings/chigwell--telegram-mcp)

HTML

<a href="/listings/chigwell--telegram-mcp"><img src="/api/listings/chigwell--telegram-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

> Do not install this server with `uvx telegram-mcp`, `uvx --from telegram-mcp`, > or `pip install telegram-mcp`. The `telegram-mcp` name on PyPI is currently > owned by a different project and does not install this repository. Passing > `TELEGRAM_API_ID`, `TELEGRAM_API_HASH`, or `TELEGRAM_SESSION_STRING` to that > package can expose Telegram account credentials to unrelated third-party code.

1. Clone and Install

git clone https://github.com/chigwell/telegram-mcp.git
cd telegram-mcp
uv sync

2. Generate a Session String

uv run session_string_generator.py

Follow the prompts. Save the generated session string securely. A session string is convenient for initial setup and portable deployments; for a long-running server, migrate it to a persistent file session after configuring your environment (see below).

For scripted setup or operational runbooks, choose the login method explicitly:

# QR login, recommended when you already have Telegram open on another device
uv run session_string_generator.py --qr

# Phone number + verification code login
uv run session_string_generator.py --phone

Without a flag, the generator keeps the interactive method prompt.

3. Configure Environment

Copy the example file and fill in your real values:

cp .env.example .env

Single-account setup:

TELEGRAM_API_ID=your_api_id_here
TELEGRAM_API_HASH=your_api_hash_here
TELEGRAM_SESSION_STRING=your_session_string_here

Recommended: Persistent Session for Long-Running Servers

`StringSession` stores the Telegram authorization key, but not Telethon's update state. After a restart, a busy account can therefore receive a large backlog of updates. A local SQLite session persists the update cursor and entity cache, so subsequent reconnects receive only the missed delta.

Stop all running telegram-mcp processes, then migrate the string configured in `.env`:

uv run telegram-mcp-migrate-session

The command verifies the new session with Telegram and prints the exact setting to use. Update `.env` as instructed, for example:

# Remove or comment this out; it takes precedence when both are present.
# TELEGRAM_SESSION_STRING=your_session_string_here
TELEGRAM_SESSION_NAME=/absolute/path/to/telegram_mcp_session

The resulting `.session` file contains account credentials. Keep it private and do not commit it. The repository's `.gitignore` already excludes session files.

For a labeled account, use `--account` with the same label:

uv run telegram-mcp-migrate-session --account work

This reads `TELEGRAM_SESSION_STRING_WORK` and writes the corresponding `TELEGRAM_SESSION_NAME_WORK` instruction. Use `--target PATH` to choose another destination. Do not run the migration while another process is using the source session.

By default, all Telegram MCP tools are exposed. If you want to prevent MCP clients from sending messages or performing chat/account mutations, set `TELEGRAM_EXPOSED_TOOLS=read-only` to expose only tools annotated with `readOnlyHint=True`:

TELEGRAM_EXPOSED_TOOLS=read-only

If read-only is too strict but `all` is too broad, append `+` and a comma-separated list of tool names to also expose those specific write tools. Every other write tool stays unregistered:

TELEGRAM_EXPOSED_TOOLS=read-only+send_message,reply_to_message,send_file

An unknown name in the allowlist aborts startup, so a typo cannot silently degrade into a narrower surface that looks like it worked.

At startup the server prints the names of the tools the mode hides to stderr; those are the names the `+` list accepts.

This is an MCP tool-surface restriction, not a Telegram session sandbox or reduced Telegram account permission. The Telegram session string still has its normal authority inside the server process; read-only mode only prevents non-read-only tools from being registered and exposed through MCP. Accepted

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,109 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. <img src="https://capsule-render.vercel.app/api?type=waving&color=gradient&height=200&section=header&text=Telegram%20MCP%20Server&fontSize=50&fontAlignY=35&animation=fadeIn&fontColor=FFFFFF&descAlignY=55&descAlign=62" alt="Telegram MCP Server" width="100%" />
  3. </div>
  4. ![MCP Badge](https://badge.mcpx.dev)
  5. [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-green?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
  6. [![Python Lint & Format Check](https://github.com/chigwell/telegram-mcp/actions/workflows/python-lint-format.yml/badge.svg)](https://github.com/chigwell/telegram-mcp/actions/workflows/python-lint-format.yml)
  7. [![Docker Build & Compose Validation](https://github.com/chigwell/telegram-mcp/actions/workflows/docker-build.yml/badge.svg)](https://github.com/chigwell/telegram-mcp/actions/workflows/docker-build.yml)
  8. A Telegram integration for Claude, Cursor, and other MCP-compatible clients. It exposes Telegram account, chat, message, contact, media, folder, and admin operations through the [Model Context Protocol](https://modelcontextprotocol.io/) using [Telethon](https://docs.telethon.dev/).
  9. ## 🤖 MCP in Action
  10. Basic Telegram MCP usage in Claude:
  11. ![Telegram MCP in action](screenshots/1.png)
  12. Asking Claude to analyze chat history and send a response:
  13. ![Telegram MCP Request](screenshots/2.png)
  14. Message sent successfully:
  15. ![Telegram MCP Result](screenshots/3.png)
  16. ## Contents
  17. - [Skills & Practical Workflows](skills/README.md)
  18. - [What It Can Do](#what-it-can-do)
  19. - [Requirements](#requirements)
  20. - [Quick Start](#quick-start)
  21. - [MCP Client Configuration](#mcp-client-configuration)
  22. - [Multi-Account Setup](#multi-account-setup)
  23. - [Device Identity](#device-identity)
  24. - [Expected Account Check](#expected-account-check)
  25. - [Proxy Support](#proxy-support)
  26. - [File Path Security](#file-path-security)
  27. - [Chat Access Privacy (Allowlist)](#chat-access-privacy-allowlist)
  28. - [Docker](#docker)
  29. - [Development](#development)
  30. - [Security Notes](#security-notes)
  31. - [Troubleshooting](#troubleshooting)
  32. - [License](#license)
  33. ## Skills & Workflows
  34. Looking for ready-to-use workflows, prompt examples, or integration recipes?
  35. Explore the [**Skills Documentation**](skills/README.md) for step-by-step guides on:
  36. - [Summarizing unread messages safely](skills/examples/summarize-latest-unread.md)
  37. - [Drafting replies without sending](skills/examples/draft-replies-without-sending.md)
  38. - [Triaging action items & urgent requests](skills/examples/triage-and-action-items.md)
  39. - [Searching chat history and expanding context](skills/examples/search-chat-and-summarize-context.md)
  40. ## What It Can Do
  41. The server currently includes 80+ MCP tools grouped into these areas:
  42. - **Accounts:** list configured accounts and route tool calls by account label.
  43. - **Chats and groups:** list chats, inspect metadata, create groups/channels, upgrade basic groups to supergroups, join or leave chats, invite or remove users, manage admins, bans, default permissions, slow mode, topics and their allowed icons, invite links, common chats, read receipts, and message links.
  44. - **Messages:** send, schedule, edit, delete, forward, pin, unpin, mark read, reply, search, inspect context, create polls, manage reactions, inspect inline buttons, press inline callbacks, and export complete chat history or unread messages to structured JSON (export_chat_history, export_unread_messages). `send_message`, `reply_to_message`, and `edit_message` support classic formatting (`parse_mode='md'`/`'html'`) and server-side rich formatting (`parse_mode='rich'`/`'rich_markdown'`/`'rich_html'` — full Markdown/HTML with tables, headings, formulas, and collapsible sections). Rich modes require Telegram Premium on the account; Premium is re-checked on every call, and without it nothing is sent — the tool returns a structured `telegram_premium_required` result so the agent can reformat with classic modes and retry. `send_message`, `reply_to_message`, and `edit_message` also accept `format_date` to render a date as a tappable chip. `edit_message` reports an edit that changes nothing as `not modified` instead of an error. `edit_message_media` replaces the attachment for one message ID; for an album, it edits only that item and Telegram enforces media-type restrictions. Omitting `caption` preserves the existing caption and formatting; an empty caption clears it.
  45. `list_inline_buttons` describes each button by row, column and `kind` (what pressing it does), for inline buttons and reply keyboards. `press_inline_button` presses `callback` and `game` buttons, returns the bot's answer with `alert` and `url`, and refuses buttons that need the 2FA password.
  46. `get_message_reactions` returns an empty list for a message with no reactions. To reuse a custom reaction, pass the returned `custom:<document_id>` value to `send_reaction`.
  47. `vote_poll(chat_id, message_id, option_indices, account=None)` votes in an existing poll.
  48. Read the poll with `get_messages` first, then select zero-based answer indices: `[0]`
  49. for the first answer, or `[0, 2]` for the first and third in a multiple-choice poll.
  50. This may replace an existing vote; empty selections, duplicate or out-of-range
  51. indices, closed polls, and multiple answers in single-choice polls are rejected.
  52. Telegram enforces voting permissions and restrictions on changing quiz votes.
  53. In supergroups where you can post as more than one identity (for example as a channel you
  54. own), `get_send_as(chat_id)` lists the allowed senders and `set_default_send_as(chat_id,
  55. send_as)` saves which one your later messages use: `"me"` for your own account, or the ID or
  56. username of an allowed sender. The saved sender applies in all your Telegram clients.
  57. Anonymous posting as an admin is an admin right and is not changed by it.
  58. - **Contacts:** list, search, add, delete, block, unblock, import, export, look up a phone number without adding a contact, inspect direct chats, find recent contact interactions, and remember contacts by the names you actually use (see below).
  59. ### Typing indicators
  60. `send_typing(chat_id, seconds=5, topic_id=None, account=None)` sends a temporary typing
  61. indicator without sending a message. Duration must be 0.5 to 45 seconds; the tool blocks
  62. until it finishes, so call it before `send_message` or `reply_to_message`, not in parallel.
  63. It refreshes the indicator at intervals of at most four seconds and attempts to clear it
  64. on completion, failure, or cancellation. `topic_id` targets a specific forum topic.
  65. Overlapping calls for the same account, peer, and topic are rejected rather than cancelling
  66. each other's indicators. Flood waits are not slept through automatically for these RPCs;
  67. the typing phase has a 50-second timeout and cleanup a separate three-second timeout.
  68. A failed cleanup is reported explicitly. Successful RPC responses confirm Telegram accepted
  69. the requests, not that another client's UI displayed them. This is a write operation and
  70. respects the existing account routing and chat allowlist.
  71. ### Phone lookups
  72. `resolve_phone(phone)` finds the Telegram user behind a phone number without adding them to your contacts, and returns the same raw result as `resolve_username`. Pass the number in E.164 form: a leading `+` and the country code, 7 to 15 digits in total. Spaces, dashes, dots and parentheses are ignored. Local forms such as `8 999 000-11-22` or `0044 ...` are rejected before Telegram is called, because the country would have to be guessed. Telegram only answers when the owner's privacy settings let you find them by number. With several accounts configured, `account` is required, since each lookup spends that account's quota.
  73. On a FloodWait the tool returns the wait and does not retry. Telethon ignores a per-request sleep threshold, so the tool sets the client's `flood_sleep_threshold` to 0 and restores it when the lookup returns. The 0 holds for as long as the lookup takes, including Telethon's own resends: any other request on that account that gets a FloodWait in that window raises it instead of sleeping.
  74. `resolve_phone` is read-only, so it is part of `TELEGRAM_EXPOSED_TOOLS=read-only`. To hide it, exclude it by name, e.g. `TELEGRAM_EXPOSED_TOOLS=read-only-resolve_phone`.
  75. Telegram publishes no quota for phone lookups and answers bulk lookups with long FloodWaits, so you can cap them locally. Both limits are off unless set. Every lookup admitted past local validation counts, whatever happens next: a Telegram answer or error, a FloodWait raised by Telethon's local pre-check without sending, or a call cancelled while it waits for another lookup on the same account. That errs on the side of refusing. Numbers rejected locally do not count. Telethon may resend a lookup itself after a server error, timeout or DC migration; that still counts once. A refused call sends nothing and says how many seconds to wait.
  76. ```env
  77. TELEGRAM_RESOLVE_PHONE_MAX_PER_DAY=12 # lookups per rolling 24 hours (0 or unset = no cap)
  78. TELEGRAM_RESOLVE_PHONE_MIN_INTERVAL_SECONDS=5 # minimum gap between lookups (0 or unset = none)
  79. TELEGRAM_RESOLVE_PHONE_STATE_FILE=/path/to/resolve-phone.json # keep the count across restarts
  80. ```
  81. Without a state file the count lives in memory and restarts from zero with the server. The state file holds only lookup timestamps (owner-only, written atomically), is shared by every server process that points at it, and covers all accounts together. A `<state file>.lock` file next to it serialises those processes. If it exists but cannot be parsed, lookups are refused until you fix or delete it; deleting it resets the count. A malformed limit value also refuses lookups instead of running unlimited. The history keeps only the newest `max(MAX_PER_DAY, 1)` timestamps, so after raising the cap the first window counts only the lookups that were kept.
  82. ### Call history
  83. `list_calls(chat_id=None, from_date=None, to_date=None, limit=50, account=None)` lists voice and video calls, newest first, from Telegram's phone-call search filter. Each record has `peer` (`id`, `name`, and `username`/`phone` when visible), `date`, `direction` (`outgoing` or `incoming`), `duration` in seconds (0 for a call that never connected), `end_reason` (`missed`, `busy`, `hangup`, `disconnect`, another Telegram reason in lower case, or `null` when Telegram gives none) and `video`. Pass `chat_id` for one user's calls, and `from_date`/`to_date` (`YYYY-MM-DD`, UTC, both inclusive) for a date range. `limit` is 1 to 500. It is read-only, so it is part of `TELEGRAM_EXPOSED_TOOLS=read-only`.
  84. ### Remembered contacts
  85. `set_contact_alias` teaches the server what you call someone, and every tool that takes a `chat_id` understands it from then on — `send_message("андрей бекендер", ...)` just works. A contact can carry any number of aliases, which is how tags work: save both `андрей бекендер` and `бекендер` for the same person and either resolves.
  86. **Only an exact saved wording ever sends.** Similar wording (`Андрею бекендеру` for a saved `андрей бекендер`) is matched too, but only to *suggest*: the tool sends nothing and asks you to confirm the contact by name. This is deliberate — `Лена`/`Леня` and `Иван`/`Иванов` differ exactly as much as a case ending does, so a matcher confident enough to handle declensions is also confident enough to message the wrong person whenever the one you meant is not saved yet. Confirming saves that wording as its own alias, so each new phrasing costs one yes/no the first time and nothing ever again. Set `TELEGRAM_CONTACT_FUZZY=0` to drop the suggestions too.
  87. When a reference is unknown, resembles one contact, matches several, or points at a contact that no longer resolves, tools send nothing and return a structured instruction telling the agent exactly what to ask you, to save the answer with `set_contact_alias`, and to retry once. `list_contact_aliases` shows one row per person with all their aliases (use it to spot a wrong memory), `delete_contact_alias` forgets one, and repointing an alias at someone else requires `replace=True`. The save path itself refuses a target it would have to guess at: contacts are saved by @username, phone, numeric ID, or an alias already confirmed for them.
  88. Aliases live in `${XDG_STATE_HOME:-~/.local/state}/telegram-mcp/aliases.json` (owner-only, written atomically); `TELEGRAM_ALIASES_FILE` overrides the path, and a pre-existing `aliases.json` next to the code is still read as a fallback.
  89. - **Media:** send files, download media, upload files, send voice notes, stickers, GIFs, inspect message media, and transcribe voice messages/video notes (see below).
  90. ### Voice transcription
  91. `transcribe_voice(chat_id, message_id, engine=None)` turns a voice message or video note into text. Four engines are available:
  92. - `groq` (default): uploads the recording to Groq's hosted `whisper-large-v3-turbo`. Leaves the server and costs a download+upload per call, but doesn't drop the recording's last few words the way native transcription does. Requires `GROQ_API_KEY`. Groq caps the size of a single upload, so a recording above `TELEGRAM_TRANSCRIBE_GROQ_MAX_MB` (default 25, the free-tier limit) is refused locally with a `too_large` error naming its size instead of being downloaded and rejected by the API. Raise the limit if your Groq tier allows bigger files, or transcribe that message with `engine='telegram'`, which has no such cap.
  93. - `telegram`: native Telegram Premium transcription (`messages.TranscribeAudioRequest`). Free and never leaves Telegram, but empirically drops the last speech segment in roughly 2 of 3 recordings and requires Telegram Premium on the account. Long recordings come back `pending` and are polled automatically.
  94. - `openai`: any OpenAI-compatible `/audio/transcriptions` endpoint — OpenAI itself, a self-hosted [Parakeet](https://github.com/achetronic/parakeet) or [speaches](https://github.com/speaches-ai/speaches) server, LocalAI, a vLLM Whisper deployment, and so on. Set `TELEGRAM_TRANSCRIBE_OPENAI_URL` to the API base URL (e.g. `https://api.openai.com/v1`; a full `.../audio/transcriptions` URL also works), `TELEGRAM_TRANSCRIBE_OPENAI_API_KEY` for the bearer token (optional for keyless local servers), and `TELEGRAM_TRANSCRIBE_OPENAI_MODEL` (default `whisper-1`). Size cap: `TELEGRAM_TRANSCRIBE_OPENAI_MAX_MB` (default 25). For Parakeet use `TELEGRAM_TRANSCRIBE_OPENAI_URL=http://localhost:5092/v1`, the API key only if the server sets `PARAKEET_API_KEY`, and set `TELEGRAM_TRANSCRIBE_LANGUAGE` for anything that isn't English — Parakeet assumes `en` when no language is sent.
  95. - `whisper`: a local [faster-whisper](https://github.com/SYSTRAN/faster-whisper) model loaded inside the MCP server process. The audio never leaves the machine. Install the extra with `pip install "telegram-mcp[whisper] @ git+https://github.com/chigwell/telegram-mcp.git@<tag-or-commit>"` (or `uv sync --extra whisper`). `TELEGRAM_TRANSCRIBE_WHISPER_MODEL` picks the model (default `small`; e.g. `large-v3-turbo` for better quality), `TELEGRAM_TRANSCRIBE_WHISPER_DEVICE` (`auto`/`cpu`/`cuda`), `TELEGRAM_TRANSCRIBE_WHISPER_COMPUTE_TYPE` (e.g. `int8` on CPU) and `TELEGRAM_TRANSCRIBE_WHISPER_MODEL_DIR` (where models are downloaded) tune it. The model is loaded once on first use and recordings are transcribed one at a time. Not available in the Alpine Docker image; use `openai` against a Parakeet or other OpenAI-compatible server next to the container instead.
  96. `TELEGRAM_TRANSCRIBE_LANGUAGE` (ISO-639-1, e.g. `nl`) is passed as a language hint to every engine except `telegram`; unset, the engines auto-detect. `TELEGRAM_TRANSCRIBE_TIMEOUT` (default 120 seconds) bounds a single request to the HTTP engines (`groq`, `openai`).
  97. The engine is chosen per call via the `engine` argument, or otherwise defaults to `TELEGRAM_TRANSCRIBE_ENGINE` (`groq`, `telegram`, `openai` or `whisper`). Results are cached by `(chat_id, message_id, engine)` in a local SQLite file so repeat reads and repeat listings never re-transcribe the same message. Concurrent requests for the same uncached recording are collapsed too: the second one waits for the first and returns its transcript, so a burst of callers costs one paid call, not one per caller. Every transcript is returned with a `note` marking it as a machine transcript, not a verbatim quote — treat it as a paraphrase, not exact wording.
  98. `get_history`, `get_messages`, `list_messages`, `search_messages`, `search_global`, and `get_message_context` fill in already-cached transcripts for voice messages instead of leaving the text empty, controlled by `TELEGRAM_TRANSCRIBE`:
  99. - `off`: transcription is disabled at runtime. The `transcribe_voice` tool stays registered and returns `{"transcribed": false, "reason": "transcription_disabled"}` instead of transcribing, and listings never show transcripts. Use `TELEGRAM_EXPOSED_TOOLS` to hide the tool itself.
  100. - `on-demand` (default): listings show cached transcripts but never spend an API call fetching a new one.
  101. - `auto`: `get_history`, `get_messages`, `list_messages`, and `search_messages` also prefetch missing transcripts, bounded per call by `TELEGRAM_TRANSCRIBE_MAX_VOICES`/`TELEGRAM_TRANSCRIBE_MAX_SECONDS` (Groq isn't free, so this prefetch is budgeted rather than unbounded).
  102. The cache lives in `TELEGRAM_TRANSCRIPT_CACHE_DIR` (default `data/transcripts` in the working directory, or `~/.cache/telegram-mcp/transcripts` when that is not writable), written as a 700 directory / 600 file since it holds personal-chat text in plaintext — see [Docker](#docker) for why this needs its own volume mount in a container.
  103. - **Profile and privacy:** get your own account info, update profile fields, set or delete profile photos, inspect privacy settings, get user info/photos/status, and manage bot commands.
  104. - **Folders and drafts:** list, create, update, reorder, and delete Telegram folders; preview a shared folder invite (`t.me/addlist/...`) without joining it; save, list, and clear drafts.
  105. - `get_folder_limits` reports current Premium-aware folder, explicit-chat and pin limits from Telegram app config; unavailable limits are `null`.
  106. - `get_folder_snapshot` captures folder definitions/order, including title entities, display fields, flags, stable peer IDs and ordered pins, without access hashes or chat contents. Its private-folder `definition` objects can be passed as restoration patches; shared invites and account/chat state are outside this snapshot's scope.
  107. - `update_folder(folder_id, patch, expected_revision?)` edits an existing private folder in place, preserving omitted fields. Peer lists replace only the specified list; `[]` clears it. For example, `{"title": "Projects", "exclude_archived": false}` renames the folder and allows archived chats through its rules without unarchiving anything. Save a snapshot before editing and use its `revision` to reject stale plans. Shared/system folders are refused; avoid concurrent folder editors because Telegram has no atomic compare-and-swap.
  108. - **Events:** wait for incoming messages with debounce (`wait_for_new_message`, `wait_for_settled_message`), optionally for one chat only via `chat_id` — without it any unrelated conversation wakes the wait — or enable the opt-in incoming event feed for callback-style delivery (see below). Integrators that follow chats (such as chat bridges) use the per-message event log instead (see below).
  109. All tool results that include Telegram user-controlled content are sanitized and, where practical, returned as structured JSON.
  110. ### Reusing custom emoji
  111. `get_history`, `list_messages`, `search_messages`, `search_global`,
  112. `get_message_context` (including `replied_message`), `get_pinned_messages`, and
  113. `get_drafts` include `custom_emojis` when the message contains custom emoji.
  114. `get_messages` and `get_scheduled_messages` include the same metadata as a JSON
  115. list in their text output. Ordinary messages keep their existing output.
  116. ```json
  117. {"text": "🍷 News", "custom_emojis": [{"emoji": "🍷", "id": "5368324170671202286"}]}
  118. ```
  119. Each entry contains the fallback emoji and its Telegram document ID as a string.
  120. Repeated IDs appear once per message; different IDs remain separate even when
  121. their fallback emoji looks identical. This is a list of reusable emoji variants,
  122. not a map of their positions or a copy of all message formatting. Extraction uses
  123. the original Telegram entities, including `TextCustomEmoji` nodes in block-format
  124. `rich_message` content, and makes no additional API requests. Emoji
  125. joiners and flag tag characters are preserved in the fallback text.
  126. To reuse an entry, set `parse_mode="html"` in `send_message`, `reply_to_message`,
  127. or `edit_message`, and insert `<tg-emoji emoji-id="ID">EMOJI</tg-emoji>` using its
  128. `id` and `emoji`. HTML-escape the fallback and other literal text. For example,
  129. the entry above becomes `<tg-emoji emoji-id="5368324170671202286">🍷</tg-emoji>`.
  130. Telegram's account restrictions still apply to sending custom emoji.
  131. For plain-text messages, pass the entries themselves as `custom_emojis` instead,
  132. with no HTML and no escaping; the text is sent verbatim. For example,
  133. `send_message(chat_id, "🍷 News for List<int> & co", custom_emojis=[{"emoji": "🍷",
  134. "id": "5368324170671202286"}])`. The same parameter works in `reply_to_message` and
  135. `edit_message`. Every standalone occurrence of each `emoji` becomes that custom
  136. emoji, including ones inside URLs or code; to keep one plain, use
  137. `parse_mode="html"` with `<tg-emoji>` instead. An emoji inside a longer sequence
  138. (such as 👍 in 👍🏽) is not a match. Nothing is sent when an `emoji` is not found or
  139. does not look like an emoji (pure ASCII/Latin punctuation such as `#` is refused),
  140. an `id` is not a positive 64-bit integer, two marked spans overlap, or `parse_mode`
  141. is set. It combines with `format_date`.
  142. `send_file` and `send_album` take the same `parse_mode` and `custom_emojis` for their
  143. caption, which for a media group sits on its first item. Without `parse_mode` a caption is
  144. still parsed as Markdown, as before; `parse_mode="plain"` sends it verbatim, the rich modes
  145. are not supported for captions, and `custom_emojis` needs a caption.
  146. ### Tappable dates and times
  147. Passing `format_date` to `send_message`, `reply_to_message`, or `edit_message`
  148. renders a tappable date/time chip — the same entity Telegram's apps attach when
  149. you type a recognizable date. Give the date text exactly as it appears in the
  150. message: `'13/09'`, `'13/09/2026'`, or `'13/09 17:00'`. The chip opens
  151. copy-date / add-to-calendar / reminder actions. Plain-text messages only —
  152. omit `parse_mode`. For example, `send_message(chat_id, "Lunch 13/09 13:00",
  153. format_date="13/09 13:00")` sends a message whose date opens that menu.
  154. ### Incoming Event Feed (callback mode, Claude Code only)
  155. By default, an agent waits for replies by calling `wait_for_settled_message`, which blocks up to the MCP tool timeout and must be re-called — that works everywhere (Codex, Cursor, etc.) and is unchanged.
  156. Clients that can wake an agent on external output (Claude Code's persistent `Monitor` on `tail -f`) can switch to callback mode instead:
  157. 1. The agent calls `enable_incoming_feed` (or set `TELEGRAM_EVENT_FEED=1` in the environment to auto-enable). Each settled incoming burst is appended as one JSON line to `${XDG_STATE_HOME:-~/.local/state}/telegram-mcp/incoming_feed.jsonl`, created owner-only (0600). Override the path with `TELEGRAM_EVENT_FEED_FILE` — an explicit path's directory must already exist. `incoming_feed_status` reports the effective path and a ready-to-use watch command.
  158. 2. The agent arms a persistent Monitor with the `watch_command` returned by the tool. Every new line re-invokes the agent with the burst summary; no blocking tool call is held open, and the chat stays free.
  159. `disable_incoming_feed` switches back; `incoming_feed_status` reports the current mode. While the feed is enabled it consumes settled bursts, so don't combine it with `wait_for_settled_message`. Feed lines contain user-generated `name` fields — treat them as untrusted data.
  160. ### Per-message events (chat bridges)
  161. Every new message of a private chat, basic group or supergroup gets one numbered event in a bounded in-memory log (`TELEGRAM_EVENT_LOG_SIZE`, default 2000; `0` turns it off). Incoming messages count, and so do the owner's own messages sent from another device; messages this server sent itself do not. Broadcast channels are left out, and so are chats outside `TELEGRAM_ALLOWED_CHAT_IDS` when it is set. Events carry no text and nothing is written to disk.
  162. - `wait_for_events(chat_id?, after_seq, boot?, timeout, limit, account?)` long-polls: it returns as soon as there are events after `after_seq` (at most 100 s, under typical proxy timeouts; keep `timeout` under your MCP client's request timeout). `after_seq=-1` starts from now without replaying the log. An event has `seq`, `chat_id`, `chat_type`, `message_id`, `sender_id`, `sender_name`, `sender_bot`, `out`, `addressed` (private chats always, groups when Telegram marks the message as mentioning the account or replying to it; never the owner's own), `topic` (the forum topic's id, 1 for General; absent outside forums), `reply_to`, `service` and `date`; with several accounts it also names its `account`. Always pass back `boot` and `last_seq`; `reset` (the server restarted) or `gap` (the log overflowed; global, not per chat) means: read every chat you follow from your last message id, then continue.
  163. - `get_messages_after(chat_id, after_id?, limit)` returns the messages after an id, oldest first, as the `list_messages` records plus `out`, `mentioned`, `addressed`, `date`, `topic` in forums and `action` for service messages. The result has `chat_id`, `chat_type`, `has_more` (newer messages remain with `after_id`, older ones exist without it), `messages` and, in a forum, one `topics` map of topic id to title. A negative `after_id` is rejected.
  164. - `send_message` takes `reply_to` (a topic id posts in that forum topic) and names the sent message: plain sends end with `message_id=<id>`, rich sends (`rich*` parse modes) return JSON with a `message_id` key (`null` when Telegram's answer does not name it), so a bridge can recognise its own message when it comes back in history.
  165. The debounce tools above keep their private-only behaviour.
  166. **Updates missed while offline.** After a reconnect the server asks Telegram for the updates it missed (`catch_up`), so messages received during a network outage still reach the incoming feed and the event log. Telethon's own automatic reconnect does not do this, and it fetches a difference by itself only after 15 minutes without updates. On a flaky network set `TELEGRAM_CATCH_UP_INTERVAL` (seconds, e.g. `120`, at least `30`; default `0`, off) to ask for missed updates periodically; when nothing was missed the request returns an empty difference.
  167. ## Requirements
  168. - Python 3.10+
  169. - Telegram API credentials from [my.telegram.org/apps](https://my.telegram.org/apps)
  170. - A Telegram session string or file-based session
  171. - An MCP client such as Claude Desktop, Cursor, or another MCP-compatible host
  172. - Optional: [uv](https://docs.astral.sh/uv/) for local development
  173. ## Quick Start
  174. > Do not install this server with `uvx telegram-mcp`, `uvx --from telegram-mcp`,
  175. > or `pip install telegram-mcp`. The `telegram-mcp` name on PyPI is currently
  176. > owned by a different project and does not install this repository. Passing
  177. > `TELEGRAM_API_ID`, `TELEGRAM_API_HASH`, or `TELEGRAM_SESSION_STRING` to that
  178. > package can expose Telegram account credentials to unrelated third-party code.
  179. ### 1. Clone and Install
  180. ```bash
  181. git clone https://github.com/chigwell/telegram-mcp.git
  182. cd telegram-mcp
  183. uv sync
  184. ```
  185. ### 2. Generate a Session String
  186. ```bash
  187. uv run session_string_generator.py
  188. ```
  189. Follow the prompts. Save the generated session string securely. A session
  190. string is convenient for initial setup and portable deployments; for a
  191. long-running server, migrate it to a persistent file session after configuring
  192. your environment (see below).
  193. For scripted setup or operational runbooks, choose the login method explicitly:
  194. ```bash
  195. # QR login, recommended when you already have Telegram open on another device
  196. uv run session_string_generator.py --qr
  197. # Phone number + verification code login
  198. uv run session_string_generator.py --phone
  199. ```
  200. Without a flag, the generator keeps the interactive method prompt.
  201. ### 3. Configure Environment
  202. Copy the example file and fill in your real values:
  203. ```bash
  204. cp .env.example .env
  205. ```
  206. Single-account setup:
  207. ```env
  208. TELEGRAM_API_ID=your_api_id_here
  209. TELEGRAM_API_HASH=your_api_hash_here
  210. TELEGRAM_SESSION_STRING=your_session_string_here
  211. ```
  212. ### Recommended: Persistent Session for Long-Running Servers
  213. `StringSession` stores the Telegram authorization key, but not Telethon's update
  214. state. After a restart, a busy account can therefore receive a large backlog of
  215. updates. A local SQLite session persists the update cursor and entity cache, so
  216. subsequent reconnects receive only the missed delta.
  217. Stop all running telegram-mcp processes, then migrate the string configured in
  218. `.env`:
  219. ```bash
  220. uv run telegram-mcp-migrate-session
  221. ```
  222. The command verifies the new session with Telegram and prints the exact setting
  223. to use. Update `.env` as instructed, for example:
  224. ```env
  225. # Remove or comment this out; it takes precedence when both are present.
  226. # TELEGRAM_SESSION_STRING=your_session_string_here
  227. TELEGRAM_SESSION_NAME=/absolute/path/to/telegram_mcp_session
  228. ```
  229. The resulting `.session` file contains account credentials. Keep it private and
  230. do not commit it. The repository's `.gitignore` already excludes session files.
  231. For a labeled account, use `--account` with the same label:
  232. ```bash
  233. uv run telegram-mcp-migrate-session --account work
  234. ```
  235. This reads `TELEGRAM_SESSION_STRING_WORK` and writes the corresponding
  236. `TELEGRAM_SESSION_NAME_WORK` instruction. Use `--target PATH` to choose another
  237. destination. Do not run the migration while another process is using the source
  238. session.
  239. By default, all Telegram MCP tools are exposed. If you want to prevent MCP
  240. clients from sending messages or performing chat/account mutations, set
  241. `TELEGRAM_EXPOSED_TOOLS=read-only` to expose only tools annotated with
  242. `readOnlyHint=True`:
  243. ```env
  244. TELEGRAM_EXPOSED_TOOLS=read-only
  245. ```
  246. If read-only is too strict but `all` is too broad, append `+` and a
  247. comma-separated list of tool names to also expose those specific write tools.
  248. Every other write tool stays unregistered:
  249. ```env
  250. TELEGRAM_EXPOSED_TOOLS=read-only+send_message,reply_to_message,send_file
  251. ```
  252. To hide specific tools instead, append `-` and a comma-separated list to either
  253. base. It works after a `+` list too:
  254. ```env
  255. TELEGRAM_EXPOSED_TOOLS=all-delete_chat_history,delete_messages_bulk
  256. TELEGRAM_EXPOSED_TOOLS=read-only-get_participants
  257. TELEGRAM_EXPOSED_TOOLS=read-only+send_message,reply_to_message-get_participants
  258. ```
  259. An unknown name in either list aborts startup, so a typo cannot silently
  260. produce a different surface that looks like it worked. Startup also aborts on
  261. an empty list, a name in both lists, or a `-` name the base already hides (such
  262. as `read-only-send_message`), which would be a no-op. To turn off voice
  263. transcription, set `TELEGRAM_TRANSCRIBE=off` rather than `-transcribe_voice`:
  264. hiding the tool leaves listings' pending-transcript hints and `auto` prefetch in
  265. place.
  266. At startup the server prints the names of the tools the mode hides to stderr;
  267. those are the names the `+` list accepts. Tools hidden by the `-` list are
  268. printed on a separate line.
  269. This is an MCP tool-surface restriction, not a Telegram session sandbox or
  270. reduced Telegram account permission. The Telegram session string still has its
  271. normal authority inside the server process; read-only mode only prevents
  272. non-read-only tools from being registered and exposed through MCP. Accepted
  273. values are `all` (the default), `read-only`, and `read-only+<tool>,<tool>`,
  274. each optionally followed by `-<tool>,<tool>`.
  275. A separate, hardcoded allowlist restricts `send_voice`, `send_sticker`,
  276. `set_profile_photo`, and `edit_chat_photo` to their expected file extensions;
  277. `send_file` and `upload_file` accept any extension by default. Use
  278. `TELEGRAM_FILE_EXTENSIONS` to add allowlists for those two, or to tighten or
  279. replace any of the hardcoded ones, in the same `tool:.ext,.ext` shape as
  280. `TELEGRAM_EXPOSED_TOOLS`, with entries separated by `;`:
  281. ```env
  282. TELEGRAM_FILE_EXTENSIONS=send_file:.pdf,.png,.jpg;upload_file:.pdf,.png
  283. ```
  284. Naming a tool that already has a hardcoded default replaces that tool's whole
  285. set rather than adding to it; any tool left unnamed keeps its default (so
  286. leaving this unset keeps today's behavior unchanged). Extensions are
  287. case-insensitive and the leading dot is optional (`pdf` and `.pdf` are
  288. equivalent). An unknown tool name, a malformed extension, or the same tool
  289. named twice aborts startup, the same way a typo in `TELEGRAM_EXPOSED_TOOLS`
  290. does.
  291. This is defence in depth against accidents, not a security boundary. The check
  292. reads the final suffix, so an allowlist of `.pdf` still accepts
  293. `payload.exe.pdf`, and it says nothing about the bytes in the file. What it
  294. does reliably block is the careless case: extensionless secrets such as
  295. `id_rsa` or a bare `.env`. Files with ordinary extensions — `.pem`, `.key`, a
  296. `.json` token file, a `.sqlite` cookie store — are not covered unless you
  297. leave them out of the list yourself.
  298. Voice transcription (see [Voice transcription](#voice-transcription) above) is
  299. off by default in the sense that no transcript is ever fetched unless you ask
  300. for one — `transcribe_voice` is always available, and listings only pick up
  301. already-cached transcripts. Enable prefetching or pick an engine explicitly:
  302. ```env
  303. TELEGRAM_TRANSCRIBE=on-demand # off / on-demand (default) / auto
  304. TELEGRAM_TRANSCRIBE_ENGINE=groq # groq (default), telegram, openai or whisper
  305. GROQ_API_KEY=your_groq_api_key_here # required whenever engine=groq is used
  306. ```
  307. `engine=groq` requires `GROQ_API_KEY`; `engine=telegram` requires Telegram
  308. Premium on the account; `engine=openai` requires `TELEGRAM_TRANSCRIBE_OPENAI_URL`;
  309. `engine=whisper` requires the `whisper` extra. `TELEGRAM_TRANSCRIBE_MAX_VOICES` (default 5) and
  310. `TELEGRAM_TRANSCRIBE_MAX_SECONDS` (default 300) bound how much `auto` mode
  311. prefetches per listing call; `TELEGRAM_TRANSCRIPT_CACHE_DIR` (default
  312. `data/transcripts`) sets where the SQLite cache is written; `TELEGRAM_TRANSCRIBE_GROQ_MAX_MB`
  313. (default 25) is the largest recording the groq engine will upload.
  314. Telegram rate limits (`FloodWaitError`) are surfaced transparently to MCP clients and LLM agents with the exact wait duration and an explicit instruction not to retry immediately.
  315. Use `TELEGRAM_FLOOD_SLEEP_THRESHOLD` to configure Telethon's internal silent-sleep threshold (default: 60 seconds). Set to `0` to disable silent sleeping and let the agent manage all backoff pacing:
  316. ```env
  317. TELEGRAM_FLOOD_SLEEP_THRESHOLD=60 # Max seconds Telethon sleeps silently on FloodWait (default 60)
  318. ```
  319. On top of that, a proactive flood-prevention layer gates every tool call that
  320. reaches Telegram (the long-poll `wait_for_events`/`wait_for_new_message`/
  321. `wait_for_settled_message` and incoming-feed tools manage their accounts
  322. internally and are not gated): a sliding-window bucket per (account, operation
  323. category) — sends 30/min, history reads 24/30s, admin actions 10/min, username
  324. resolution 20/min, channel create/join/leave 3/5min — plus a reactive circuit
  325. breaker that suspends a tool after repeated flood waits on the same account. A
  326. deferred call returns a rate-limit message with the retry delay instead of
  327. making the Telegram request, so the agent reschedules instead of accumulating
  328. hours-long flood bans. It is on by default; disable it with:
  329. ```env
  330. TELEGRAM_FLOODGATE=0 # disable the local flood-prevention gate (default on)
  331. ```
  332. Run the server locally:
  333. ```bash
  334. uv run main.py
  335. ```
  336. ## MCP Client Configuration
  337. ### Claude Desktop extension (.mcpb)
  338. The repository ships a `manifest.json`, so it can be packed into a
  339. [Claude Desktop extension](https://github.com/modelcontextprotocol/mcpb) and
  340. installed without editing any JSON:
  341. ```bash
  342. npx @anthropic-ai/mcpb pack . telegram-mcp.mcpb
  343. ```
  344. Open the resulting `telegram-mcp.mcpb` with Claude Desktop (or drag it onto
  345. Settings → Extensions) and fill in the API ID, API hash and session string
  346. (see [Quick Start](#quick-start) for generating one). Claude Desktop installs
  347. Python and the dependencies itself via `uv`, and masks the API hash and
  348. session string as sensitive fields. The allowed-chats and files-directory fields map to
  349. `TELEGRAM_ALLOWED_CHAT_IDS` and `TELEGRAM_ALLOWED_ROOTS`. `.mcpbignore` keeps
  350. `.env`, session files and logs out of the bundle.
  351. ### Manual configuration
  352. For Claude Desktop or Cursor, point the MCP server at a cloned checkout of
  353. this project:
  354. ```json
  355. {
  356. "mcpServers": {
  357. "telegram-mcp": {
  358. "command": "uv",
  359. "args": [
  360. "--directory",
  361. "/full/path/to/telegram-mcp",
  362. "run",
  363. "main.py"
  364. ],
  365. "env": {
  366. "TELEGRAM_API_ID": "your_api_id_here",
  367. "TELEGRAM_API_HASH": "your_api_hash_here",
  368. "TELEGRAM_SESSION_STRING": "your_session_string_here"
  369. }
  370. }
  371. }
  372. }
  373. ```
  374. To expose only read-only tools in Claude Desktop or Cursor, add this to the
  375. server `env` block:
  376. ```json
  377. "TELEGRAM_EXPOSED_TOOLS": "read-only"
  378. ```
  379. Or keep read-only as the baseline and allow a few write tools on top:
  380. ```json
  381. "TELEGRAM_EXPOSED_TOOLS": "read-only+send_message,reply_to_message"
  382. ```
  383. Alternatively, install this repository directly from GitHub into a virtual
  384. environment using a specific release tag or commit:
  385. ```bash
  386. python -m venv .venv
  387. . .venv/bin/activate
  388. pip install "git+https://github.com/chigwell/telegram-mcp.git@<tag-or-commit>"
  389. ```
  390. Then configure your MCP client to run the installed console script:
  391. ```json
  392. {
  393. "mcpServers": {
  394. "telegram-mcp": {
  395. "command": "/full/path/to/.venv/bin/telegram-mcp",
  396. "env": {
  397. "TELEGRAM_API_ID": "your_api_id_here",
  398. "TELEGRAM_API_HASH": "your_api_hash_here",
  399. "TELEGRAM_SESSION_STRING": "your_session_string_here"
  400. }
  401. }
  402. }
  403. }
  404. ```
  405. Generate a session string without cloning the repo by sourcing this repository
  406. from GitHub explicitly:
  407. ```bash
  408. uvx --from "git+https://github.com/chigwell/telegram-mcp.git@<pinned-release-tag-or-commit>" telegram-mcp-generate-session
  409. ```
  410. ### Transports
  411. The server speaks three MCP transports, selected with `MCP_TRANSPORT`:
  412. | Value | Transport | Use case |
  413. | ------- | -------------------------- | --------------------------------------------------------------- |
  414. | `stdio` | stdio (default) | One dedicated server process per MCP client |
  415. | `http` | streamable HTTP | One shared server for many clients (Claude Code, Codex, Cursor) |
  416. | `sse` | SSE (legacy HTTP) | Clients that only support the deprecated SSE transport |
  417. For `http` and `sse`, the server binds `MCP_HOST`:`MCP_PORT` (default
  418. `127.0.0.1:8765`); the streamable HTTP endpoint is `/mcp`, the SSE endpoint is
  419. `/sse`.
  420. Host and Origin validation is always on for `http` and `sse`, so a web page
  421. open in your browser cannot send tool calls to the local server (cross-origin
  422. request forgery / DNS rebinding). By default only `127.0.0.1`, `localhost` and
  423. `[::1]` Host headers are accepted, and only browser pages served from those
  424. hosts; requests without an `Origin` header (regular MCP clients) are not
  425. affected. CORS preflights echo only an allowed origin, never `*`.
  426. If the server is reachable via a domain (e.g. behind a reverse proxy) rather
  427. than only `127.0.0.1`/`localhost`, set `MCP_ALLOWED_HOSTS` to the Host headers
  428. to accept, e.g. `MCP_ALLOWED_HOSTS=mcp.example.com`, and `MCP_ALLOWED_ORIGINS`
  429. to any browser origins that may call the server. Each replaces the local
  430. default list. Comma-separated; supports a `:*` suffix to allow any port.
  431. Prefer `http` when more than one MCP client (or many coding-agent sessions)
  432. will use the server: a single long-lived process holds one Telegram
  433. connection, instead of every client spawning its own Telethon session —
  434. Telegram throttles and may flag accounts that open many parallel sessions.
  435. Every tool call also has a server-side ceiling of 55 seconds, configured with
  436. `TELEGRAM_TOOL_TIMEOUT_SECONDS`. A timed-out Telegram request returns an explicit
  437. MCP error instead of leaving the client waiting indefinitely. The error says
  438. that completion is unknown: a write may already have succeeded, so check the
  439. destination before retrying. Set the value to `0` only for a deliberately
  440. unbounded operator session.
  441. Register the shared server with clients:
  442. ```bash
  443. # Claude Code
  444. claude mcp add --transport http telegram http://127.0.0.1:8765/mcp
  445. # Codex
  446. codex mcp add telegram --url http://127.0.0.1:8765/mcp
  447. ```
  448. For stdio-only clients, bridge with [mcp-remote](https://www.npmjs.com/package/mcp-remote):
  449. ```json
  450. {
  451. "mcpServers": {
  452. "telegram-mcp": {
  453. "command": "npx",
  454. "args": ["-y", "mcp-remote", "http://127.0.0.1:8765/mcp"]
  455. }
  456. }
  457. }
  458. ```
  459. ## Multi-Account Setup
  460. Use suffixed session variables to configure multiple Telegram accounts:
  461. ```env
  462. TELEGRAM_API_ID=your_api_id_here
  463. TELEGRAM_API_HASH=your_api_hash_here
  464. TELEGRAM_SESSION_STRING_WORK=session_string_for_work
  465. TELEGRAM_SESSION_STRING_PERSONAL=session_string_for_personal
  466. ```
  467. Labels are lowercased and become the `account` parameter value in tools.
  468. If `TELEGRAM_SESSION_NAME` is set as well (the Docker image and `.env.example` set it), that
  469. session becomes an extra `default` account when it is logged in; when it is not, the server
  470. skips it with a warning on stderr instead of refusing to start.
  471. - In single-account mode, `account` is optional.
  472. - In multi-account mode, write tools require `account`.
  473. - Read-only tools fan out to all accounts when `account` is omitted.
  474. Example prompts:
  475. - "List my accounts"
  476. - "Show unread messages from all accounts"
  477. ### Session pool (one account, several concurrent clients)
  478. To run several MCP clients against the **same** Telegram account at once (for
  479. example the desktop app *and* a terminal CLI), give each client its own
  480. authorized session. Telegram forbids one session (auth key) being used from two
  481. IPs simultaneously, so on a VPN or dual-stack host two local clients can collide
  482. with `AuthKeyDuplicatedError`. List several interchangeable session strings in
  483. `TELEGRAM_SESSION_STRINGS` (separated by whitespace, comma or semicolon); each
  484. process claims a free one via an advisory file lock, so clients deterministically
  485. pick distinct sessions:
  486. ```env
  487. TELEGRAM_SESSION_STRINGS=<session A> <session B> <session C>
  488. ```
  489. Generate extra sessions with `uv run session_string_generator.py`. The pool
  490. takes precedence over `TELEGRAM_SESSION_STRING` for the default account. As an
  491. extra safety net, a transient `AuthKeyDuplicatedError` at connect time (e.g.
  492. during a VPN reconnect) is retried with backoff before the server gives up.
  493. Size the pool to the number of clients you actually run concurrently. If every
  494. slot is already claimed, the server refuses to start with an explicit error
  495. rather than reusing a session another client holds — reuse would make Telegram
  496. permanently invalidate that session for both clients.
  497. - "Send this from my work account to @example"
  498. ### Sharing one session from one host
  499. Before connecting, every server process takes a per-session lock (see the
  500. `AuthKeyDuplicatedError` entry under Troubleshooting). By default it is
  501. exclusive: a second instance for the same session waits briefly for the first
  502. to exit and otherwise refuses to start. That lock can only see processes on the
  503. same host, and Telegram's rule is about IPs, not processes: instances on one
  504. host only collide when they reach Telegram from different IPs (dual-stack or
  505. split-tunnel VPN hosts). When they all share one egress IP — a laptop running
  506. several MCP clients — you can let them share the session instead of pooling:
  507. ```env
  508. TELEGRAM_SESSION_LOCK=shared
  509. ```
  510. Shared instances coexist with each other but never overlap an exclusive one.
  511. If you are not sure every client egresses from the same IP, use the pool.
  512. ## Device Identity
  513. These optional variables control how the client appears in Telegram under
  514. **Settings > Devices** (the active-sessions list):
  515. ```env
  516. TELEGRAM_DEVICE_MODEL=Telegram MCP
  517. TELEGRAM_SYSTEM_VERSION=1.0
  518. TELEGRAM_APP_VERSION=1.0
  519. TELEGRAM_LANG_CODE=en
  520. TELEGRAM_SYSTEM_LANG_CODE=en
  521. ```
  522. If left unset, Telethon falls back to the host platform (for example `arm64`).
  523. Because these values are re-sent on every connection, a long-running server
  524. would otherwise overwrite the name chosen during login on each reconnect, so
  525. set them to keep a stable, recognisable device name. The same variables are
  526. read both by the session string generator (at login) and by the server (on
  527. every connect), so set them in the same place as your other credentials.
  528. ## Expected Account Check
  529. Set `TELEGRAM_EXPECTED_USERNAME` (or `TELEGRAM_EXPECTED_USERNAME_<LABEL>` per account) and the server refuses to start when the session belongs to a different account. The comparison is case-insensitive and ignores a leading `@`. Unset means no check.
  530. ## Proxy Support
  531. Route Telegram traffic through a proxy by setting the `TELEGRAM_PROXY_*`
  532. environment variables. Supported types are `socks5`, `socks4`, `http`, and
  533. `mtproxy`.
  534. SOCKS and HTTP proxies require the optional `python-socks` package:
  535. ```bash
  536. uv sync --extra proxy
  537. # or
  538. pip install python-socks
  539. ```
  540. Single-account configuration:
  541. ```env
  542. TELEGRAM_PROXY_TYPE=socks5
  543. TELEGRAM_PROXY_HOST=127.0.0.1
  544. TELEGRAM_PROXY_PORT=1080
  545. TELEGRAM_PROXY_USERNAME=optional_user
  546. TELEGRAM_PROXY_PASSWORD=optional_pass
  547. TELEGRAM_PROXY_RDNS=true
  548. ```
  549. MTProxy:
  550. ```env
  551. TELEGRAM_PROXY_TYPE=mtproxy
  552. TELEGRAM_PROXY_HOST=mtproxy.example
  553. TELEGRAM_PROXY_PORT=443
  554. TELEGRAM_PROXY_SECRET=ee0123456789abcdef...
  555. ```
  556. Per-account overrides use the same `_<LABEL>` suffix as session variables and
  557. take precedence over the unsuffixed defaults:
  558. ```env
  559. TELEGRAM_PROXY_TYPE=socks5
  560. TELEGRAM_PROXY_HOST=127.0.0.1
  561. TELEGRAM_PROXY_PORT=1080
  562. TELEGRAM_PROXY_TYPE_WORK=http
  563. TELEGRAM_PROXY_HOST_WORK=proxy.work.example
  564. TELEGRAM_PROXY_PORT_WORK=3128
  565. ```
  566. Misconfigured proxy settings (unknown type, missing host/port, invalid port,
  567. missing MTProxy secret, or a missing `python-socks` package) cause the server
  568. to fail fast at startup with a clear error message instead of silently
  569. bypassing the proxy.
  570. ## File Path Security
  571. File-path and media tools (`send_file`, `edit_message_media`, `download_media`, `upload_file`, `send_voice`, `send_sticker`, `set_profile_photo`, `edit_chat_photo`, and `send_album`) are registered and supported, but remain strictly disabled by default until allowed roots are configured (safe-by-default to prevent unauthorized file access).
  572. `send_file` and `send_album` keep their existing success line and append `MessageIDs: [...]` when Telethon returns the sent messages. Album IDs follow the same order as `file_paths`; a `null` entry means Telethon could not map that position to a message ID. Pass a known ID to `edit_message_media` to replace that item.
  573. Allowed roots can come from:
  574. - **Environment Variable (`TELEGRAM_ALLOWED_ROOTS`):** Semicolon- (`;`) or comma- (`,`) separated paths (also supports colon `:` on POSIX systems). Ideal for Docker, headless daemon setups, and MCP clients that pass settings via environment.
  575. - **Server CLI arguments:** Positional folder paths passed to `main.py`, used as a server-side fallback.
  576. - **MCP client Roots:** Configured directly in supported MCP clients (`roots/list`).
  577. Security behavior:
  578. - Client MCP Roots replace server CLI roots when available.
  579. - Some clients (notably Cursor) return workspace roots as bare absolute paths
  580. instead of `file://` URIs. That breaks MCP SDK validation of `list_roots`;
  581. the server recovers those absolute paths from the validation error so
  582. file-path tools keep working.
  583. - Empty client Roots are treated as deny-all by default. Some clients implement
  584. the Roots capability but advertise an empty list, which disables file tools
  585. even when server CLI roots are configured. Set
  586. `TELEGRAM_ALLOW_SERVER_ROOTS_FALLBACK=1` to fall back to the server CLI roots
  587. in that case (opt-in; the default stays deny-all). The same opt-in also applies
  588. when `list_roots` fails unexpectedly and no client paths could be recovered.
  589. - `roots/list` times out after `TELEGRAM_ROOTS_TIMEOUT_SECONDS` (default 10).
  590. With server roots configured, `TELEGRAM_SERVER_ROOTS_ONLY=1` uses them directly
  591. and skips `roots/list`; client Roots are then ignored.
  592. - Paths are resolved through real paths and must stay inside an allowed root.
  593. - Traversal, wildcard-like, shell-like, and null-byte path patterns are rejected.
  594. - Relative paths resolve under the first allowed root.
  595. - Downloads default to `<first_root>/downloads/` (or directly into `<first_root>/` if the root folder is already named `downloads` / `Downloads`). Configurable via `TELEGRAM_DOWNLOAD_SUBDIR`.
  596. - Size and extension limits are enforced for sensitive media tools. `send_file`
  597. and `upload_file` have no extension limit by default; see
  598. `TELEGRAM_FILE_EXTENSIONS` above to add one.
  599. #### Clients on another machine
  600. File-path tools read and write the server's disk. When the server runs over
  601. HTTP for a client on another machine, set `TELEGRAM_MEDIA_BASE_URL` to the URL
  602. clients reach it at (for example `https://tg.example.com`, behind your reverse
  603. proxy) and configure a server allowed root:
  604. - `download_media` also returns a URL that serves the downloaded file
  605. (`<base>/media/…`); fetch it with `curl` or similar.
  606. - `prepare_upload(filename)` returns a `url` and a `file_path`. PUT the file to
  607. the url (`curl --fail -T ./report.pdf "<url>"`; streamed to disk, up to the
  608. `send_file` size limit), then pass `file_path` to `send_file`, `send_album`,
  609. `send_voice` or `send_sticker`.
  610. Both URLs carry an HMAC signature and stay inside the first server allowed root.
  611. Each expires after an hour or when the server restarts, and an upload URL takes
  612. one upload. Uploads land in `<first_root>/uploads/` and are deleted two hours
  613. later. Client MCP Roots name the client's own disk, so such a deployment
  614. usually also sets `TELEGRAM_SERVER_ROOTS_ONLY=1`.
  615. Run with allowed roots via environment variable:
  616. ```bash
  617. # Semicolon- or comma-separated roots
  618. TELEGRAM_ALLOWED_ROOTS="/data/telegram,/tmp/telegram-mcp" uv run main.py
  619. ```
  620. Or run with allowed roots via CLI positional arguments:
  621. ```bash
  622. uv run main.py /data/telegram /tmp/telegram-mcp
  623. ```
  624. From an MCP client configuration, you can pass roots via `env` or as arguments after `main.py`:
  625. ```json
  626. {
  627. "mcpServers": {
  628. "telegram-mcp": {
  629. "command": "uv",
  630. "args": [
  631. "--directory",
  632. "/full/path/to/telegram-mcp",
  633. "run",
  634. "main.py",
  635. "/data/telegram",
  636. "/tmp/telegram-mcp"
  637. ],
  638. "env": {
  639. "TELEGRAM_API_ID": "your_api_id_here",
  640. "TELEGRAM_API_HASH": "your_api_hash_here",
  641. "TELEGRAM_SESSION_STRING": "your_session_string_here"
  642. }
  643. }
  644. }
  645. }
  646. ```
  647. ## Chat Access Privacy (Allowlist)
  648. To restrict AI agents or MCP clients to specific chats only (preventing access to all private or corporate conversations), configure `TELEGRAM_ALLOWED_CHAT_IDS`:
  649. ```env
  650. # Comma-separated list of allowed chat IDs (marked form) or usernames
  651. TELEGRAM_ALLOWED_CHAT_IDS=12345678,-100123456789,-4567,@allowed_channel
  652. ```
  653. Numeric IDs are matched exactly in Telegram's marked form, the same `chat_id` the tools return: a user is `12345678`, a basic group `-4567`, a channel or supergroup `-100123456789`. Users, basic groups and channels have separate ID namespaces, so the same bare number can be three unrelated chats; an entry is never widened to another type (allowing channel `-100123456789` does not allow user `123456789`). Write groups and channels with their `-`/`-100` prefix: a bare positive number only ever means a user.
  654. When `TELEGRAM_ALLOWED_CHAT_IDS` is set:
  655. - **`list_chats` / `get_chats`:** Only chats matching the allowlist are returned; all other conversations remain completely invisible to the agent.
  656. - **Messaging & Chat Tools (`send_message`, `get_messages`, `get_chat`, `create_poll`, etc.):** Any attempt to interact with a chat outside the allowlist is rejected with a structured error message: `Access to chat '<chat_id>' is restricted by privacy policy (TELEGRAM_ALLOWED_CHAT_IDS)`.
  657. - **Search, Drafts & Calls (`search_global`, `get_drafts`, `list_calls`):** Global searches, draft listings and the call list omit unallowed conversations.
  658. - **Contact, folder & group-admin tools:** a chat named by `contact_id` or `group_id` (`get_last_interaction`, `get_contact_chats`, `invite_to_group`, `promote_admin`, `demote_admin`) is checked like `chat_id`; `get_common_chats`, `get_contact_chats`, `get_direct_chat_by_contact` and `get_folder` leave unallowed chats out of their results; `create_folder` refuses unallowed `chat_ids`.
  659. - **Incoming Events:** Notifications and debounce feeds only process events from allowed chats.
  660. If `TELEGRAM_ALLOWED_CHAT_IDS` is unset or empty, the server operates in unrestricted mode (default), preserving 100% backward compatibility.
  661. ### Forum topics
  662. An entry written as `<chat>:<topic id>` allows the chat, but only that forum topic (`1` is General). Several entries allow several topics of one chat; a plain entry for the same chat allows it whole again. Topic ids come from `list_topics`.
  663. ```env
  664. # Only the topic with id 163 of a forum supergroup, plus one whole private chat
  665. TELEGRAM_ALLOWED_CHAT_IDS=-100123456789:163,12345678
  666. ```
  667. For a chat limited to topics:
  668. - **Reading tools that keep to the topics:** `get_history` (the allowed topic is the default when there is only one), `list_messages`, `get_messages`, `search_messages`, `get_message_context`, `get_messages_after`, `list_topics` (only the allowed topics), `get_chat` (`last_message` only from an allowed topic), `open_photo`, `inspect_document`, `get_media_info`, `transcribe_voice` and `wait_for_events`. Messages of other topics are left out, and a message id from another topic is refused. `get_messages_after` also returns `next_after_id`, the newest message it read, so a reader can continue past messages it left out.
  669. - **Every other tool that takes the chat** (sending, editing, pinned and scheduled messages, members, the admin log, exports, …) is refused with `Access to chat '<chat_id>' is restricted by privacy policy (TELEGRAM_ALLOWED_CHAT_IDS): only forum topic(s) <ids> are allowed, and <tool> cannot be limited to a topic.` A tool has to be taught about topics before it can be used, so a tool that does not know about them never reaches the rest of the chat.
  670. - **Tools that read many chats:** `search_global`, `get_drafts` and the incoming event log leave out the chat's other topics.
  671. - Chat-level metadata stays visible: the title, the member count and the chat's total unread count.
  672. `TELEGRAM_BLOCKED_CHAT_IDS` takes whole chats only; a `<chat>:<topic>` entry there blocks nothing.
  673. ### Global chat blocklist
  674. Set `TELEGRAM_BLOCKED_CHAT_IDS` to a comma-separated list of marked chat IDs
  675. and/or usernames to exclude chats across all configured accounts:
  676. ```env
  677. TELEGRAM_BLOCKED_CHAT_IDS=-100123456789,-4567,12345678,@unwanted_bot
  678. ```
  679. The blocklist takes precedence over `TELEGRAM_ALLOWED_CHAT_IDS` for data returned
  680. to the agent. Messages from blocked chats are filtered from results and events;
  681. forwarding messages from those chats is also blocked. Other actions are not
  682. restricted by the blocklist. A bot's username blocks its own chat, not messages it
  683. posts elsewhere.
  684. IDs are exact, including the `-` or `-100` prefix; usernames are case-insensitive.
  685. Prefer numeric IDs for reliable blocking: usernames can change, and chats whose
  686. username cannot be checked may still appear in results. Existing export files are
  687. not filtered retroactively. Complete folder snapshots remain unavailable when a
  688. blocklist is active because they contain unfiltered chat identifiers.
  689. Global-search cursors keep Telegram's original Base64-encoded offsets and may
  690. contain a blocked chat's ID and access hash, but not message text.
  691. ## Deletion Audit Log (Recent Actions for Private Chats)
  692. To maintain an immutable, local audit trail for destructive actions (e.g. tracking when and how messages were deleted without exposing message text), the server writes an append-only JSONL log (closes #321):
  693. ```env
  694. # Optional custom path for the deletion audit log (defaults to telegram_audit.log next to the server)
  695. TELEGRAM_AUDIT_LOG=/path/to/telegram_audit.log
  696. ```
  697. - **Operations logged:** `delete_message`, `delete_messages_bulk`, and `delete_chat_history`.
  698. - **Refusals and errors logged:** Refused cross-chat deletion attempts (attempting to delete IDs outside the target chat) and permission errors (`ChatAdminRequiredError`) are recorded with full diagnostic details.
  699. - **Privacy preservation:** Only operation metadata is persisted (`timestamp`, `account`, `tool`, `chat_id`, `message_ids`, `revoke`, `outcome`). Message content and bodies are **never** logged.
  700. - **Log entry format (JSONL):**
  701. ```json
  702. {"timestamp": "2026-11-07T18:25:00.123456+00:00", "account": "work", "tool": "delete_message", "chat_id": 12345678, "message_ids": [42], "revoke": null, "outcome": "deleted"}
  703. {"timestamp": "2026-11-07T18:25:05.123456+00:00", "account": "work", "tool": "delete_messages_bulk", "chat_id": 12345678, "message_ids": [999], "revoke": true, "outcome": "refused: foreign message IDs [999]"}
  704. ```
  705. ## Docker
  706. For complete compose templates and client configurations (Claude Desktop, Cursor, etc.), see the [**Docker Deployment Guide**](examples/docker/README.md).
  707. Build the image:
  708. ```bash
  709. docker build -t telegram-mcp:latest .
  710. ```
  711. ### Shared server (recommended)
  712. Run one long-lived container serving streamable HTTP, and point every MCP
  713. client at it (see [Transports](#transports) for client registration):
  714. ```bash
  715. docker run -d --name telegram-mcp --restart unless-stopped \
  716. --env-file .env \
  717. -e MCP_TRANSPORT=http \
  718. -e MCP_HOST=0.0.0.0 \
  719. -p 127.0.0.1:8765:8765 \
  720. telegram-mcp:latest
  721. ```
  722. `MCP_HOST=0.0.0.0` binds inside the container so the published port works;
  723. `-p 127.0.0.1:8765:8765` keeps the server reachable only from the local
  724. machine — the endpoint is unauthenticated, so never publish it on a public
  725. interface.
  726. The bundled Compose file runs the same setup:
  727. ```bash
  728. docker compose up --build -d
  729. ```
  730. It also mounts `./transcript_cache` into the container at
  731. `/app/data/transcripts` so the voice-transcription SQLite cache (see
  732. [Voice transcription](#voice-transcription)) survives a rebuild instead of
  733. living in the container's writable layer. Create it once, owned by the
  734. container's `appuser` (uid 1000), before starting:
  735. ```bash
  736. mkdir -p ./transcript_cache && chown 1000:1000 ./transcript_cache
  737. ```
  738. ### One container per client (stdio)
  739. Alternatively, an MCP client can spawn a dedicated container itself:
  740. ```json
  741. {
  742. "mcpServers": {
  743. "telegram-mcp": {
  744. "command": "docker",
  745. "args": ["run", "-i", "--rm", "--env-file", "/full/path/to/.env", "telegram-mcp:latest"]
  746. }
  747. }
  748. }
  749. ```
  750. This is fine for a single client, but with several clients (or coding agents
  751. that spawn subagent sessions) each one starts its own container and its own
  752. Telegram session, which Telegram throttles; a client that exits uncleanly can
  753. also leave its container running. Prefer the shared server above in those
  754. setups.
  755. For multiple accounts, pass variables such as `TELEGRAM_SESSION_STRING_WORK` and `TELEGRAM_SESSION_STRING_PERSONAL`.
  756. ## Development
  757. The implementation is split into a small compatibility entrypoint and modular package code:
  758. ```text
  759. main.py # historical entrypoint and compatibility exports
  760. telegram_mcp/runtime.py # shared MCP setup, account routing, validation, file safety
  761. telegram_mcp/runner.py # application startup
  762. telegram_mcp/tools/ # tool modules grouped by domain
  763. sanitize.py # output sanitization helpers
  764. tests/ # pytest suite
  765. ```
  766. Run tests:
  767. ```bash
  768. uv run pytest
  769. ```
  770. Run tests with coverage:
  771. ```bash
  772. uv run pytest --cov --cov-report=term-missing --cov-report=xml
  773. ```
  774. Coverage is configured in `pyproject.toml` with an 80% minimum gate for deterministic unit-testable core modules. GitHub Actions runs the same coverage command and uploads `coverage.xml`.
  775. Run formatting checks:
  776. ```bash
  777. uv run black --check .
  778. uv run flake8 .
  779. ```
  780. ## Security Notes
  781. - Never commit `.env`, session strings, or `.session` files.
  782. - A Telegram session string grants access to the account it belongs to.
  783. - The `telegram-mcp` package name on PyPI is not controlled by this project.
  784. Avoid PyPI-based `telegram-mcp` install commands unless ownership changes and
  785. the package is verified.
  786. - This repository includes a best-effort startup guard that refuses installed
  787. `telegram-mcp` distributions without a source checkout or direct git/file
  788. install record. That guard cannot run when the unrelated PyPI package itself
  789. is launched, so use clone-based or explicit git installs.
  790. - Prefer session strings over file sessions when running multiple server instances.
  791. - By default, Telegram API calls go directly from your machine/container to Telegram.
  792. If `TELEGRAM_PROXY_*` is configured, Telegram traffic is routed through the
  793. configured SOCKS/HTTP/MTProxy proxy instead.
  794. - User-generated Telegram content is sanitized before being returned to MCP clients.
  795. ### Prompt Injection Protection
  796. Telegram messages, display names, chat titles, and button labels are untrusted content. The server mitigates prompt-injection risk with:
  797. - Structured JSON output for user-controlled data where practical.
  798. - `sanitize_user_content()`, `sanitize_name()`, and `sanitize_dict()` for control-character stripping, invisible-character stripping, and length limits.
  799. - MCP content annotations marking returned content as user audience data.
  800. - Tool descriptions that warn clients not to treat returned Telegram fields as model instructions.
  801. - No brittle keyword-based filtering.
  802. ## Troubleshooting
  803. - **No Telegram session configured:** set `TELEGRAM_SESSION_STRING`, `TELEGRAM_SESSION_NAME`, or suffixed multi-account variants.
  804. - **Session is not authorized:** run `uv run session_string_generator.py --qr` outside
  805. the MCP server when you can scan from an existing Telegram app, or
  806. `uv run session_string_generator.py --phone` when you need phone-code login.
  807. Then set `TELEGRAM_SESSION_STRING` in `.env`. The MCP server does not perform
  808. interactive phone-code login over stdio, including after a reconnect: a session
  809. terminated while the server runs fails with "not authorized after reconnect".
  810. - **Invalid API credentials:** verify `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` at [my.telegram.org/apps](https://my.telegram.org/apps).
  811. - **Database is locked:** make sure no other process is using the same file session.
  812. - **`AuthKeyDuplicatedError` / "Another telegram-mcp process is already connected with this session":** two processes tried to connect the same Telegram session at once (e.g. an MCP client restarted the connector before the old process exited), which Telegram rejects and can invalidate the session for both. The server now takes an exclusive lock per session before connecting; a second concurrent launch waits briefly (default 20s, override with `TELEGRAM_LOCK_GRACE_SECONDS`) for the first to release it and otherwise exits without ever calling `connect()`, instead of racing into a duplicate connection. Retry once only one instance is running — the refusal names the PID holding the lock. If several instances on this host are meant to share one session (all reaching Telegram from the same IP), set `TELEGRAM_SESSION_LOCK=shared`; see [Sharing one session from one host](#sharing-one-session-from-one-host).
  813. - **File tools are disabled:** pass allowed roots or configure MCP Roots in your client.
  814. - **File tools wait for `roots/list`:** configure server roots and set `TELEGRAM_SERVER_ROOTS_ONLY=1`.
  815. - **Path rejected:** ensure the path is inside an allowed root and does not use traversal or wildcard patterns.
  816. - **Auth errors after password changes:** regenerate your session string.
  817. - **Bot-only tool rejected:** regular user accounts cannot manage bot command settings.
  818. - **Need details:** check your MCP client logs, terminal output, and `mcp_errors.log`.
  819. ## Contributing
  820. 1. Fork and clone the repository.
  821. 2. Install dependencies and git hooks:
  822. - `uv sync`
  823. - `uv run pre-commit install --hook-type pre-commit --hook-type pre-push`
  824. 3. Create a focused branch.
  825. 4. Add or update tests when behavior changes.
  826. 5. Run checks locally:
  827. - `uv run pre-commit run --all-files`
  828. - `uv run pre-commit run --hook-stage pre-push --all-files`
  829. 6. Open a pull request with a concise description.
  830. ## License
  831. This project is licensed under the [Apache 2.0 License](LICENSE).
  832. ## Acknowledgements
  833. - [Telethon](https://github.com/LonamiWebs/Telethon)
  834. - [Model Context Protocol](https://modelcontextprotocol.io/)
  835. - [Claude](https://www.anthropic.com/) and [Cursor](https://cursor.so/)
  836. - [chigwell/telegram-mcp](https://github.com/chigwell/telegram-mcp) upstream project
  837. - [telethon-floodgate](https://github.com/axisrow/telethon-floodgate) by [@axisrow](https://github.com/axisrow) — flood-prevention engine, vendored under MIT (see file headers in `telegram_mcp/floodgate/`)
  838. Maintained by [@chigwell](https://github.com/chigwell) and [@l1v0n1](https://github.com/l1v0n1). PRs welcome.
  839. ## Star History
  840. [![Star History Chart](https://star-history.dera.page/svg?repos=chigwell/telegram-mcp&type=Date)](https://star-history.dera.page/#chigwell/telegram-mcp&Date)
  841. ## Contributors
  842. <a href="https://github.com/chigwell/telegram-mcp/graphs/contributors">
  843. <img src="https://contrib.rocks/image?repo=chigwell/telegram-mcp" />
  844. </a>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.