MCP Telegram
Supports chat summarization using Google's Gemini API as one of the available LLM providers for analyzing and summarizing Telegram conversations.
Supports chat summarization using Ollama's local LLM as one of the available LLM providers for analyzing and summarizing Telegram conversations without requiring external API keys.
Provides comprehensive Telegram integration, enabling AI assistants to manage chats, send/receive messages, search conversations, schedule messages, resolve links, backup messages, and summarize chats using Telegram's API.
mcp-telegram
MCP server for Telegram — let AI assistants interact with your Telegram account
Features
Chat Management: List, search, mute/unmute chats, organize into folders
Messages: Read, search, inspect context, send, draft, schedule, link-resolve, and backup messages
AI Summarization: Summarize chat conversations using multiple LLM providers
Secure: Session stored in macOS Keychain (file-based storage on Linux/Windows)
Two transports: local stdio (single account) or remote streamable HTTP with an embedded OAuth 2.1 server and per-user Telegram QR login — multi-user and deployable to Cloud Run (see Remote (HTTP) Mode)
Related MCP server: Better Telegram MCP
Installation
go install github.com/tolmachov/mcp-telegram@latestOr build from source:
git clone https://github.com/tolmachov/mcp-telegram.git
cd mcp-telegram
makeSetup
1. Get Telegram API Credentials
Go to my.telegram.org/apps
Create an application
Copy
api_idandapi_hash
2. Configure Environment
Store credentials (macOS Keychain; plaintext JSON at ~/.local/state/mcp-telegram/config.json with 0600 perms on Linux/Windows):
mcp-telegram config set api-id 123456789
mcp-telegram config set api-hash abcd1234efgh5678Or use a .env file:
cp .env.example .env
# Edit .env with your credentials3. Login to Telegram
mcp-telegram login --phone +1234567890You'll be prompted for a verification code sent to your Telegram.
4. Configure MCP Client
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"telegram": {
"command": "mcp-telegram",
"args": ["run"],
"env": {
"TELEGRAM_API_ID": "your_api_id",
"TELEGRAM_API_HASH": "your_api_hash"
}
}
}
}Claude Code
claude mcp add telegram -- /path/to/mcp-telegram runSet environment variables in your .env file or pass them via --env.
Available Tools
29 tools exposed to MCP clients. Messages are identified by opaque string
handles ("42" for regular, "s:42" for scheduled) — copy them back
verbatim from tool outputs to follow-up calls, never parse or construct
them manually.
If your client shows a single tool called TelegramLoginRequired and none of
the tools below, the server is up but Telegram is not authorized — see
When Telegram Isn't Authorized.
Tool | Description |
| Get current user information |
| List all chats, groups, and channels |
| Fuzzy search for chats by name |
| Get detailed information about a chat |
| Get messages from a chat (set |
| Search within one chat by substring, with optional date / sender / media / thread filters |
| Search by substring across all chats with opaque cursor-based pagination |
| Get messages around a specific anchor message in chronological order |
| Get the messages of a reply thread / comment section under a root message |
| List a forum supergroup's topics with opaque cursor-based pagination |
| Send, reply, schedule, or draft a message. |
| Edit a message; for scheduled handles, |
| Delete a message; |
| Forward a delivered message (scheduled handles are rejected) |
| Set or clear your emoji reactions on a message (empty list clears) |
| Join a channel/group/supergroup by @username, numeric ID, or invite link ( |
| Leave a channel/group/supergroup by @username or numeric ID (asks for confirmation) |
| Parse |
| Mark one or more chats as read |
| Export messages to a text file. Filters mirror the read tools: |
| Resolve @username to user/chat info |
| Mute or unmute chat notifications ( |
| AI-powered chat summarization via sampling / Gemini / Ollama / Anthropic |
| Download photo media from a media resource URI; returns MCP image content |
| List chat folders (dialog filters) with their ID, title, flags, and included/excluded/pinned chat IDs |
| Create a folder from a title plus chats and/or category flags (e.g. |
| Delete a folder by ID; chats are untouched (asks for confirmation) |
| Add chats/groups/channels to a folder by ID (@username or numeric ID) |
| Remove chats/groups/channels from a folder by ID |
Server Variants
The server implements experimental server variants
(SEP-2053): one server that offers several selectable capability sets. A client
sends hints during initialize, the server ranks the variants, and the client
picks one. Clients that don't understand the extension transparently get the
full variant, so nothing changes for them.
Variant | Status | Tools | For |
| stable (default) | all 29, full descriptions | interactive research + administration with a human |
| stable | all 29, descriptions trimmed to the first sentence (~50% smaller) | autonomous agents on a tight context budget |
| experimental | 16 Telegram read-only tools, descriptions trimmed like | read-heavy context-loading agents |
Pin a single variant with --variant (or TELEGRAM_VARIANT) for clients that
can't negotiate — e.g. --variant research exposes only the read-only subset:
mcp-telegram run --variant researchLeave it unset to expose all three and let the client choose.
Note on pinned-chat resources. In multi-variant mode (no
--variant), pinned-chat resources are exposed on every variant and kept fresh by a single poller, but proactiveresources/list_changednotifications are not delivered — the variants proxy can't forward the background watcher's notifications (an upstream library limitation). Clients pick up pin changes on their nextresources/list. Pin a single--variantto restore live notifications.
Available Resources
URI | Description |
| Current user info |
| All chats list |
| Detailed info for any chat ID via resource template |
| Last 100 messages from a pinned chat (dynamic resource, only for currently pinned chats) |
Pinned chat resources are created dynamically for each pinned chat and refreshed in the background; clients receive resources/list_changed when the set changes (except in multi-variant mode — see the note under Server Variants).
Available Prompts
3 parameterized prompts that MCP clients expose as slash-commands or quick actions.
Prompt | Arguments | Description |
|
| Walks active chats and produces a per-chat digest of key updates and action items. Read-only. |
|
| Summarizes a specific chat and lists messages that look like they need a reply. Read-only. |
|
| Searches for a message, shows a draft reply, and sends only after explicit user confirmation. |
Prompt Examples
Here are some example prompts you can use with AI assistants:
Message Management
"Check for any unread important messages in my Telegram"
"Summarize all my unread Telegram messages"
"Read and analyze my unread messages, prepare draft responses where needed"
"Check non-critical unread messages and give me a brief overview"
"Find messages mentioning 'invoice' in my work chat from last week"
"Open the context around this Telegram link: https://t.me/example/123"
Organization
"Analyze my Telegram dialogs and suggest a folder structure"
"Help me categorize my Telegram chats by importance"
"Find all work-related conversations and suggest how to organize them"
Communication
"Monitor specific chat for updates about [topic]"
"Draft a polite response to the last message in [chat]"
"Check if there are any unanswered questions in my chats"
"Resolve this Telegram message link and show me the thread context"
Backup & Export
"Backup my conversation with [contact] to a file"
"Export the last week of messages from [group]"
"Backup media-only updates too so nothing is silently skipped"
Chat Summarization
The SummarizeChat tool supports multiple LLM providers:
sampling (experimental): Uses the MCP client's LLM via MCP Sampling. Only works with clients that support sampling: VS Code, fast-agent, Continue. Does NOT work with Claude Desktop or Claude Code.
ollama: Local LLM via Ollama - no API key required
gemini: Google Gemini API
anthropic: Anthropic Claude API
Configure via environment variables:
SUMMARIZE_PROVIDER=ollama # or: sampling, gemini, anthropic
SUMMARIZE_MODEL= # provider-specific model nameCommands
# Run MCP server (used by MCP clients)
mcp-telegram run
# Login to Telegram
mcp-telegram login --phone +1234567890
# Logout and delete session
mcp-telegram logout
# Securely store config values (macOS Keychain / file on Linux)
mcp-telegram config set api-id 123456789
mcp-telegram config set api-hash abcd1234
# List stored keys
mcp-telegram config list
# Delete a stored value
mcp-telegram config delete api-idAllowed keys: api-id, api-hash, anthropic, gemini.
Credentials resolve in this priority order (higher wins): CLI flags (--api-id, --api-hash) → environment variables (including .env) → secure store values set via config set. This lets you keep stable values in the keychain and override per-run from the command line without editing the store.
Configuration Options
Environment Variable | Description | Default |
| Telegram API ID | Required |
| Telegram API Hash | Required |
| Allowed directories for backups | OS app data dir |
| LLM provider for summarization |
|
| Model name | Provider default |
| Tokens per summarization batch |
|
| Ollama API URL |
|
| Google Gemini API key | - |
| Anthropic API key | - |
| Max bytes |
|
| RPS ceiling for history-fetching calls to Telegram. Exceeding Telegram's FLOOD_WAIT thresholds pauses all tools. |
|
| Polling interval (seconds) for the pinned-chat resource watcher. |
|
| Max seconds to wait out a Telegram |
|
| MCP transport: |
|
| Listen address for the HTTP transport |
|
| HTTP authorization mode: |
|
| Public base URL (OAuth issuer); required with | - |
| Comma-separated Telegram user ids allowed to log in, or | - |
| Base64 32-byte master key(s) for tokens + session encryption (comma-separated for rotation); required with | - |
| Extra exact-match HTTPS OAuth redirect URIs (loopback and claude.ai/claude.com are always allowed) | - |
| Where per-user Telegram sessions live (GCS bucket or local dir; exactly one with | - |
Remote (HTTP) Mode
By default the server speaks the stdio transport: one local process, one Telegram account, driven by a desktop MCP client. It can instead run as a long-lived remote server over the MCP streamable HTTP transport, so a single hosted deployment serves many users — each authenticating with their own Telegram account — over the network.
stdio (default) | streamable HTTP | |
Transport | stdio pipe | HTTP on one endpoint ( |
Users | single account on the host | many, isolated per Telegram user |
Auth | none (local trust) | embedded OAuth 2.1 + Telegram QR login |
Session storage | Keychain / local file | encrypted per-user blobs in a GCS bucket or a directory |
Use for | local desktop clients | a shared or hosted server |
How authorization works
Authorization is pure Telegram — no bots, no external identity provider. The
server embeds a small OAuth 2.1 authorization server (Dynamic Client
Registration + PKCE); when a client connects it opens the authorization page,
which shows a QR code. You scan it with the Telegram app (Settings → Devices
→ Link Desktop Device), and the resulting MTProto session both proves who you
are and becomes your working session (a 2FA-password prompt appears if your
account has one). Only Telegram user ids listed in AUTH_ALLOWED_USERS may
complete the login — everyone else is rejected after the scan and their session
is discarded.
Each authorization is an independent session: it gets its own encrypted
object in the bucket and its own MCP server assembly, so one account can be
logged in from several clients at once without them contending. The server keeps
up to a few of an account's assemblies warm concurrently; an account actively
switching between more sessions than that is not rejected but pays a brief
Telegram reconnect when an idle one is rebuilt on demand. Sessions are
encrypted at rest with AES-256-GCM under a split key: the key is derived
from both AUTH_TOKEN_KEY and a random per-session key that lives only
inside the client's OAuth access/refresh token (never stored server-side). As a
result, an at-rest dump of the bucket plus the secret manager cannot, on its
own, decrypt a session — a live token is also required. (Trade-offs, stated
plainly: this does not protect against a compromise of the running server's
memory. And because the per-session key share travels inside the token, an
attacker who holds the bucket and the master key and captures one
access token can decrypt that single session — and thereby extract its
persistent MTProto auth key, which outlives the ≤55-minute token and keeps
working until the session is revoked or logged out. That exposure is confined to
the one captured session; other sessions stay protected. TLS,
Cache-Control: no-store on token/revoke responses, and never logging tokens
narrow the capture window.) Pre-existing sessions from older versions stay
readable with the master key alone and are transparently upgraded to a split-key
session on their next token refresh.
Session lifecycle is managed automatically: POST /revoke (RFC 7009) with an
access or refresh token durably marks that authorization revoked (a tombstone
stored where the Telegram client never writes) and deletes its session. The
refresh grant dies immediately and stays dead — even if a still-live client
re-stores the session object, the refresh check consults the tombstone, so
revocation cannot be undone by a resurrected blob. An already-issued access
token remains valid until it expires (≤55 minutes): revocation reliably stops
renewal, matching the standard short-lived-access / revocable-refresh model.
Revocation does not terminate the Telegram-side device authorization (it stays
in Settings → Devices until Telegram expires it). Sessions abandoned without
revocation — and old tombstones — are reclaimed by a background sweep once older
than the refresh-token TTL plus a day, past which no refresh token for the
session can still be valid.
Legacy (pre-split-key) sessions are upgraded on their next token refresh by
moving the session to a fresh split-key object and revoking the old legacy
session. Consequently, if one account was logged in from several clients before
upgrading, the first client to refresh wins the upgrade and the others re-run
the QR login on their next refresh — this avoids ever running two Telegram
clients on one auth key (which would trip AUTH_KEY_DUPLICATED).
Try it locally
# Issuer on loopback may use plain http:
mcp-telegram run --transport http --http-addr :8080 \
--auth telegram \
--auth-issuer-url http://localhost:8080 \
--auth-allowed-users 123456789 \
--auth-token-key "$(head -c 32 /dev/urandom | base64)" \
--auth-session-dir ~/.local/state/mcp-telegram/http-sessionsThen point an MCP client at http://localhost:8080/ and complete the browser
flow. --auth none (the default for HTTP) serves plain streamable HTTP with no
authentication — only safe behind a trusted proxy. Use * as the sole entry in
--auth-allowed-users to allow any Telegram account (the deployment is then
only as private as its URL; * cannot be combined with specific ids).
Deploy to Google Cloud Run
The production target is Cloud Run: one container, scale-to-zero, secrets from Secret Manager, sessions in a GCS bucket. In outline:
Create a bucket for the encrypted per-user sessions and a dedicated service account with
roles/storage.objectAdminon just that bucket.Store two secrets in Secret Manager — the Telegram
api_hashand a freshly generated 32-byteAUTH_TOKEN_KEY(head -c 32 /dev/urandom | base64) — and grant the service accountroles/secretmanager.secretAccessoron them. The token key never leaves Secret Manager in plaintext. Losing it logs everyone out (sessions become undecryptable). Leaking it alone no longer exposes split-key sessions — those also need a live client token — but treat it as highly sensitive regardless: it still mints tokens and decrypts any not-yet-upgraded legacy sessions.Deploy with
gcloud run deploy --source ., wiring the non-secret env fromdeploy/cloudrun.env.example, the two secrets via--set-secrets, and--max-instances=1(mandatory: two instances loading the same MTProto session trip Telegram'sAUTH_KEY_DUPLICATEDand forcibly log every user out).Set
AUTH_ISSUER_URLto the service URL and redeploy — tokens and session encryption are bound to the issuer value.
Copy-paste commands, the exact IAM bindings, the token/revocation model, and how to connect claude.ai / Claude Desktop / Claude Code are in deploy/README.md.
Destructive Actions
Tools like DeleteMessage request user confirmation via MCP elicitation before proceeding. If your MCP client does not support elicitation, the server proceeds automatically without a confirmation dialog.
When Telegram Isn't Authorized
Telegram sessions expire and can be revoked from Settings → Devices → Active sessions on any of your devices. When that happens — or when api-id/api-hash are missing — the server does not fail its MCP connection. Over stdio it comes up in login-required mode:
the host shows the server as connected, exposing a single tool named
TelegramLoginRequiredand no Telegram tools at all;the server instructions tell the model Telegram is unavailable and what the fix is, so the first Telegram request you make gets answered with the real reason instead of a generic failure;
calling
TelegramLoginRequiredre-checks the live state and reportsnot_configured,login_required,check_failed, orauthorized_pending_reconnect— the last one meaning you logged in elsewhere and only need to reconnect the server.
The fix is the usual one. Use the path your host actually launches — the binary is typically wired in by absolute path and not on $PATH, which is why the tool's fix_command field hands back a paste-ready command with the real path already filled in:
/path/to/mcp-telegram login --phone +1234567890
# then reconnect the MCP server (in Claude Code: /mcp → select this server → Reconnect)This is deliberate. A stdio server that refuses its MCP connection is rendered by hosts as a bare "failed" entry with the reason buried in a log file, indistinguishable from a bad binary path — so the diagnosis is delivered as server content instead, which is the only channel a stdio server has. Two paths keep fail-fast behaviour, because they have no MCP peer to tell:
the HTTP transport — the process exits non-zero so Cloud Run sees an unhealthy start rather than a listener it can never serve;
stdin attached to a TTY, i.e. you ran
mcp-telegram runyourself — the message goes to stderr and the process exits, which is what makes that command usable as a manual smoke test.
Note the boundary is the TTY, not "a human started it": with stdin piped or redirected from a file, mcp-telegram run serves login-required mode and exits 0 on EOF. Scripted health checks should call mcp-telegram login/config list, or assert on the tool list, rather than on run's exit status.
In remote (HTTP) mode none of this applies: a dead per-user session is answered with 401 plus a WWW-Authenticate challenge, which sends the MCP client back through OAuth and its QR login to mint a fresh session — no restart, no CLI.
Session Storage
macOS: Stored securely in Keychain.
Linux/Windows: Stored in
~/.local/state/mcp-telegram/session.jsonwith0600file permissions. The file is plaintext — keep the containing user account trusted, and prefer running on macOS when handling sensitive accounts.
Config values set via mcp-telegram config set (API keys, Telegram credentials) follow the same backend: Keychain on macOS, plaintext JSON on Linux/Windows.
Note on the plaintext store (Linux/Windows): the session file grants full access to your Telegram account. Place it on an encrypted filesystem (LUKS/BitLocker) and do not sync
~/.local/state/mcp-telegram(or~/.config) to an unencrypted cloud backup — a leakedsession.jsonis equivalent to a leaked login.
Development
make build # build the binary with version metadata
make lint # golangci-lint
make test # unit tests
make test-integration # end-to-end tests (need a real account + TEST_* vars)Unit tests run without credentials. The integration suite in test/ is behind
the integration build tag and drives the server over a real stdio pipe using a
second MCP implementation (mark3labs/mcp-go) as the client, to catch wire-level
interop issues. It reads the TEST_* variables documented in .env.example
(e.g. TEST_CHAT_ID, TEST_GROUP_ID) and skips any test whose variable or
Telegram credentials are unset.
License
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseAqualityDmaintenanceA comprehensive MCP server providing 35 tools for managing Telegram messages, media, and chat interactions via the Bot API. It also features a real-time monitoring system using the Telethon User API to log messages from specific channels.35Apache 2.0
- Alicense-qualityAmaintenanceProduction-grade MCP server for Telegram with dual-mode Bot API and MTProto. 6 composite tools covering messages, chats, media, contacts management with 3-tier token optimization.10Apache 2.0
- AlicenseBqualityDmaintenanceA Telegram MCP server that connects agents to a real Telegram user account via MTProto, enabling reading, searching, sending, moderating, and managing Telegram chats through natural language or automated tool calls.1009729MIT
- Flicense-qualityBmaintenanceA production-quality Telegram MCP server that sends messages via Telegram API, fixing bugs in the reference implementation. Provides tools to list dialogs, read messages, send messages, and mark chats as read.4
Related MCP Connectors
Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
MCP server for Gainium — manage trading bots, deals, and balances via AI assistants
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/tolmachov/mcp-telegram'
If you have feedback or need assistance with the MCP directory API, please join our Discord server