Telegram MCP
by architawr
README.md
# Telegram MCP
[](https://github.com/architawr/telegram-mcp/actions/workflows/ci.yml)
[Русская версия](README.ru.md)
A local [Model Context Protocol](https://modelcontextprotocol.io) server that
gives AI agents (Claude Code, Claude Desktop, Codex) access to **your own
personal Telegram account** — reading chats, sending messages, pressing inline
buttons, waiting for replies, managing folders and mute, checking phone numbers
and running consent-based campaigns.
It is an MTProto *user* client (built on [mtcute](https://mtcute.dev)), not a
Bot API bot. It runs locally on your computer, talks to Telegram and nothing else, and is
built around one idea: **the agent acts with your authority, so the runtime
enforces the boundaries** — a pinned account, a stop list, pacing, daily caps,
hard stops on `FLOOD_WAIT`, and an append-only journal of every action.
> **Use it only with your own account and only for messages people expect.**
> Unsolicited messages and bulk outreach violate Telegram's terms and get
> accounts restricted or banned. The session file is a full key to your
> account — protect it like a password.
## Platform support
| Platform | Status |
|---|---|
| macOS, Apple Silicon | **Supported and tested** end-to-end on a MacBook Air 13″ (2025, Apple M4, 24 GB), macOS 26.5 |
| Windows 10/11, x64 | **Supported, not tested on real hardware.** Unit tests and the build run in CI on `windows-latest`; the installer, the scheduled-task daemon and a live Telegram session have not been tried yet. Reports welcome |
| Linux | Not packaged: no installer or service unit yet |
Runtime: [Bun](https://bun.sh) 1.3.14.
## Tools
| Group | Tools |
|---|---|
| Account | `telegram_authorization_status`, `telegram_account_status` |
| Reading | `dialogs_list`, `dialogs_getInfo`, `messages_getHistory`, `messages_search`, `messages_getRecent` |
| Acting | `messages_sendText`, `messages_clickInlineButton`, `wait_for_reply` |
| Phone check | `contacts_lookupPhone` |
| Folders & mute | `folders_list`, `folders_create`, `folders_addChat`, `folders_detachChat`, `chats_getMuteState`, `chats_mute`, `chats_unmute` |
| Campaigns | `campaign_prepare`, `campaign_start`, `campaign_status`, `campaign_pause`, `campaign_cancel` |
Deliberately **absent** (not disabled — not built): delete, leave, block,
forward, edit, mark-as-read, deleting or renaming folders, writing contacts,
editing the stop list, fetching web pages. A self-test in the binary fails the
build if any of them reappears.
## Safety model
There are no confirmation dialogs. Your request to the agent is the
authorization; the tool call is the act. What the runtime guarantees instead:
- **Pinned account.** The server refuses to start if the session belongs to any
user other than `ownerId` in `config.json`.
- **Stop list.** Chats in `stopList` (plus every recorded opt-out) are refused
for actions and silently absent from listings. No tool can extend or shrink
it — you edit it by hand.
- **Pacing classes.** `soft` (bots, existing dialogs, groups) and `cold` (first
message to a stranger) have separate intervals and daily caps; phone checks
have their own `lookup` budget. Limits are account-wide, so parallel agents or
campaigns never send faster.
- **Hard stops.** A `FLOOD_WAIT` blocks every Telegram RPC until it expires,
even across restarts. A send whose outcome is unknown is marked `ambiguous`,
is never retried, and stops campaigns until the daemon is restarted.
- **Untrusted text.** Everything other people wrote is returned wrapped in
`<telegram-message>`-style elements, and the server instructs the agent to
treat it as data, never as instructions (prompt-injection defence).
- **Frozen campaigns.** `campaign_prepare` freezes exact `recipient + text`
pairs and returns a SHA-256; `campaign_start` refuses on any mismatch. Groups
and channels cannot be campaign recipients.
- **Journal.** Every read, send, click and setting change is appended to a local
SQLite journal; sends are stored with their exact text, reads without content.
- **No other egress.** Proxy variables are cleared and `PATH` is pinned by the
launcher; tests fail if any module imports an HTTP or network client.
See [docs/design.ru.md](docs/design.ru.md) (Russian) for the reasoning and
[docs/authorization.md](docs/authorization.md) for the authorization contract.
## Architecture
```
agent session ─┐
agent session ─┼─ launcher.sh (stdio proxy) ──unix socket──► daemon ──MTProto──► Telegram
agent session ─┘ (launchd)
```
- **One daemon per account**, run by launchd (`local.telegram-mcp`) on macOS or
a per-user scheduled task (`TelegramMCP`) on Windows. It owns the
session file and its singleton lock, the single Telegram connection, the
policy layer, pacing and the journal. It starts at login and is restarted if
it exits.
- **Every agent session** runs a thin stdio proxy (`launcher.sh` on macOS,
`telegram-mcp.exe --connect` on Windows) into the daemon. The proxy reads no
secrets and never opens the session, so any number of sessions can use
Telegram at once.
- On macOS the daemon listens on `session/telegram-mcp.sock`, mode `0600`
inside the `0700` session directory: only your user can connect — the same
user that can read the session file anyway. On Windows it is a named pipe
`\\.\pipe\telegram-mcp-<hash>`, and the installation directory is
restricted to your user and SYSTEM.
- The socket is up before Telegram connects, so tools are always listed; while
the daemon is connecting or waiting out a `FLOOD_WAIT`, a tool call returns
the reason and the next retry time.
- A daemon restart does not drop agent sessions: the proxy reconnects and
replays the MCP handshake. A request in flight at that moment gets an
explicit "outcome unknown" error and is not retried.
## Setup on macOS
### 1. Get Telegram API credentials
Create an application at <https://my.telegram.org> → *API development tools*
and note the `api_id` and `api_hash`.
### 2. Build
```bash
git clone https://github.com/architawr/telegram-mcp.git
cd telegram-mcp
scripts/build-release.sh
```
The build requires exactly Bun 1.3.14 and performs a frozen install without
lifecycle scripts, `bun audit`, typecheck, tests, an offline self-test, an
arm64 build, ad-hoc code signing, and SHA-256 manifests of all inputs and of
the release.
### 3. Prepare the installation directory
```bash
APP="$HOME/Library/Application Support/TelegramMCP"
mkdir -p "$APP/secrets" && chmod 700 "$APP" "$APP/secrets"
printf '%s' 'YOUR_API_ID' > "$APP/secrets/api_id"
printf '%s' 'YOUR_API_HASH' > "$APP/secrets/api_hash"
chmod 600 "$APP/secrets/"*
install -m 600 config.example.json "$APP/config.json"
```
Edit `$APP/config.json` and set `ownerId` to your numeric Telegram user ID.
If you don't know it, leave any number — the next step tells you the right one.
### 4. Sign in once
```bash
TELEGRAM_MCP_CONFIG="$APP/config.json" ./dist/telegram-mcp --login
```
Enter your phone number, the login code and, if enabled, your 2FA password.
This creates the session file. If `ownerId` does not match the account, the
command prints the right value — put it into `config.json`. `--login` never
overwrites an existing session. The MCP server itself never asks for codes or
passwords.
### 5. Install
```bash
./install.sh # every agent host found on this Mac
./install.sh --target=claude-code # Claude Code CLI only (user scope)
./install.sh --target=claude # Claude Desktop only
./install.sh --target=codex # Codex only (project-scoped workspace)
```
The installer verifies checksums and the signature, installs a versioned
release and switches the `current` symlink atomically, registers the MCP server
with the chosen hosts (backing up their configs first and never writing secrets
into them), installs and starts the launchd daemon, and waits for its socket.
It never creates, copies or replaces the session or the API credentials.
Restart your agent app afterwards (for Claude Desktop: Cmd+Q, then reopen).
### 6. Verify
```bash
launchctl print gui/$(id -u)/local.telegram-mcp | grep -E 'state|pid'
tail "$HOME/Library/Application Support/TelegramMCP/logs/daemon.log"
claude mcp get telegram # Claude Code
```
Then ask the agent to call `telegram_authorization_status`: it must report
`ownerAuthorized: true` and your user ID.
## Setup on Windows
> Not tested on real hardware yet — see [Platform support](#platform-support).
Requires [Bun](https://bun.sh) 1.3.14 and PowerShell. Get the API credentials
as in step 1 above, then:
```powershell
git clone https://github.com/architawr/telegram-mcp.git
cd telegram-mcp
bun install --frozen-lockfile --ignore-scripts
bun run build:windows # dist\telegram-mcp.exe
$App = "$env:LOCALAPPDATA\TelegramMCP"
New-Item -ItemType Directory -Force "$App\secrets" | Out-Null
Set-Content -NoNewline "$App\secrets\api_id" 'YOUR_API_ID'
Set-Content -NoNewline "$App\secrets\api_hash" 'YOUR_API_HASH'
Copy-Item config.example.json "$App\config.json" # then set ownerId
.\dist\telegram-mcp.exe --login --config "$App\config.json"
powershell -ExecutionPolicy Bypass -File .\install.ps1 # -Target claude-code | claude | all
```
`install.ps1` copies the binary to `%LOCALAPPDATA%\TelegramMCP\bin`, restricts
the directory to your user, registers the scheduled task `TelegramMCP`
(started at logon, restarted on failure), and registers the server with
Claude Code (`claude mcp add --scope user`) and/or Claude Desktop
(`%APPDATA%\Claude\claude_desktop_config.json`). Codex is not wired up on
Windows yet. The daemon log is `%LOCALAPPDATA%\TelegramMCP\logs\daemon.log`.
## Configuration
`config.json` lives in the installation directory. Relative paths are resolved against
its directory, so the whole installation can be moved to another Mac.
```json
{
"ownerId": "1234567890",
"sessionPath": "./session/session",
"statePath": "./state",
"secrets": { "apiIdFile": "./secrets/api_id", "apiHashFile": "./secrets/api_hash" },
"limits": {
"soft": { "minIntervalMs": 1000, "dailyMax": 1000 },
"cold": { "minIntervalMs": 5000, "dailyMax": 30 },
"lookup": { "minIntervalMs": 5000, "dailyMax": 100 },
"maxCampaignRecipients": 500
},
"stopList": { "chatIds": [], "usernames": [] }
}
```
- The file must be a regular file owned by you with no group or other access;
unknown keys, malformed values and out-of-range limits are refused.
- `launcher.sh` takes the config only from its own directory and ignores an
inherited `TELEGRAM_MCP_CONFIG`, so an agent host cannot repoint it.
- Cold sends spend both the `cold` and the `soft` daily cap; phone checks spend
`lookup` and `soft`.
- Switching accounts means a new `config.json` and a new session — no code
changes.
## Operating
| Task | macOS | Windows |
|---|---|---|
| Restart the daemon (also clears an ambiguous-send stop) | `launchctl kickstart -k gui/$(id -u)/local.telegram-mcp` | `schtasks /End /TN TelegramMCP` then `schtasks /Run /TN TelegramMCP` |
| Stop it | `launchctl bootout gui/$(id -u)/local.telegram-mcp` | `schtasks /End /TN TelegramMCP` |
| Logs | `~/Library/Application Support/TelegramMCP/logs/daemon.log` | `%LOCALAPPDATA%\TelegramMCP\logs\daemon.log` |
| Update | `git pull && scripts/build-release.sh && ./install.sh` | `git pull`, `bun run build:windows`, `.\install.ps1` |
Agent sessions reconnect on their own after a restart or an update. To add a
chat to the stop list, edit `stopList` in `config.json` and restart the daemon.
The legacy single-process mode (one process per agent session, exclusive lock)
is still available as `launcher.sh --stdio`.
### Uninstall
```bash
launchctl bootout gui/$(id -u)/local.telegram-mcp
rm ~/Library/LaunchAgents/local.telegram-mcp.plist
claude mcp remove telegram --scope user # and/or remove it from Claude Desktop / Codex configs
# Delete "$HOME/Library/Application Support/TelegramMCP" only if you no longer
# need the session and the journal.
```
On Windows: `Unregister-ScheduledTask -TaskName TelegramMCP`, remove the
registration from Claude, then delete `%LOCALAPPDATA%\TelegramMCP` if you no
longer need it.
Consider also terminating the session in Telegram → Settings → Devices.
## Host notes
- **Claude Code** — registered in user scope (`~/.claude.json`), so every
session in any directory sees it.
- **Claude Desktop** — `claude_desktop_config.json` has no project scope, so
the registration is app-wide. Cloud (Cowork) tasks cannot reach a local stdio
server.
- **Codex** — the installer removes any global registration and creates a
project-scoped config in a dedicated trusted workspace
(`TelegramMCP/workspace`), with MCP content excluded from Codex memories.
- The installed workspace contains `AGENTS.md` and `CLAUDE.md` with operating
rules for agents; [docs/prompt-example.ru.md](docs/prompt-example.ru.md) is an example owner prompt (Russian).
## Development
```bash
bun install --frozen-lockfile --ignore-scripts
bun run typecheck
bun test
bun run self-test
```
Tests never reach Telegram: the client is faked. CI runs them on macOS and
Windows on every push. `scripts/live-smoke.ts` is a
manual end-to-end check against an installed launcher.
## License
[MIT](LICENSE)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues