Skip to main content
Glama
telegram-user-mcp

telegram-user-mcp

by VKirill
README.md
# telegram-user-mcp

An MCP server that lets AI agents work with **your own Telegram account** (not a bot): read and search chats, download attachments, and send text and files to private chats. Built on [Telethon](https://docs.telethon.dev/) (MTProto user API).

- 8 tools: status, dialogs, global search, chat history (period and text filters), chat info, download, send text, send files (albums, captions, thumbnails).
- Sending is **dry-run by default**: without `execute: true` a tool only shows the resolved recipient and files.
- Sending is limited to **private chats** (a user, or `me` for Saved Messages).
- HTTP transport with a **required bearer token**, plus a small file-exchange endpoint so agents on other machines can upload files to send and fetch downloaded ones.
- Optional **incoming-message triggers**: run a command when a matching private message arrives.
- No dependencies beyond Telethon and the Python standard library.

> [!WARNING]
> This server acts as you. Anyone with the token can read your chats and write on your behalf. Bind it to `127.0.0.1` or a private network (VPN / WireGuard) only, keep the token secret, and review what your agents send. Automating a user account is subject to [Telegram's terms](https://core.telegram.org/api/terms); avoid bulk messaging.

## How it works

```
MCP client ──HTTP + Bearer──▶ tg_mcp_http.py ──▶ tg_mcp.py ──runs──▶ client/tg.py (Telethon, one call = one process)
                                   │                                        │
                                   └── /files ◀──▶ outbox/ ◀────────────────┘ (uploads to send, downloads to fetch)

tg_triggers.py ── live updates ──▶ rules in triggers/<account>.json ──▶ your command
```

Each tool call runs `client/tg.py` in a separate process that takes an exclusive lock on the session, so calls are serialized and the session file is never written concurrently. The trigger listener uses an in-memory copy of the same auth key and never writes the session file.

## Install

Python 3.11+.

```sh
git clone https://github.com/VKirill/telegram-user-mcp /opt/telegram-user-mcp
cd /opt/telegram-user-mcp
python3 -m venv venv && venv/bin/pip install -r requirements.txt
```

### Login

Get `api_id` and `api_hash` at <https://my.telegram.org/apps>. The session and credentials live in `accounts/<account>/private/` (mode 700); nothing else is written there.

```sh
export TG_PRIVATE_DIR=/opt/telegram-user-mcp/accounts/main/private
install -d -m 700 "$TG_PRIVATE_DIR"
cat > "$TG_PRIVATE_DIR/credentials.env" <<'EOF'
TG_API_ID=1234567
TG_API_HASH=0123456789abcdef0123456789abcdef
TG_PHONE=+15550000000
EOF
chmod 600 "$TG_PRIVATE_DIR/credentials.env"

venv/bin/python client/tg.py login-start            # Telegram sends a code
echo 'TG_LOGIN_CODE=12345' > "$TG_PRIVATE_DIR/login.env"
venv/bin/python client/tg.py login-code              # the file is deleted after reading
# only if it prints password_required:
echo 'TG_2FA_PASSWORD=...' > "$TG_PRIVATE_DIR/login.env"
venv/bin/python client/tg.py login-password

venv/bin/python client/tg.py status                  # {"authorized": true, ...}
```

`TG_API_ID`, `TG_API_HASH` and `TG_PHONE` can also come from the environment. To log the session out, end it in Telegram → Settings → Devices.

### Run

```sh
install -d -m 700 private
openssl rand -hex 32 > private/mcp-token && chmod 600 private/mcp-token
TG_MCP_TOKEN_FILE=private/mcp-token venv/bin/python tg_mcp_http.py     # 127.0.0.1:12020
curl -s http://127.0.0.1:12020/health                                  # {"ok": true}
```

For a service, see [`examples/systemd/telegram-user-mcp@.service`](examples/systemd/telegram-user-mcp@.service) (`systemctl enable --now telegram-user-mcp@main`).

### Connect a client

Any MCP client with streamable-HTTP support and custom headers works, for example [`examples/mcp-client.json`](examples/mcp-client.json):

```json
{
  "mcpServers": {
    "telegram": {
      "type": "http",
      "url": "http://127.0.0.1:12020/mcp",
      "headers": { "Authorization": "Bearer ${TELEGRAM_MCP_TOKEN}" }
    }
  }
}
```

A local client can also use stdio: `venv/bin/python tg_mcp.py` (no token needed; it is your own process).

## Tools

| Tool | What it does |
|---|---|
| `telegram_status` | Is the account logged in; user id and username |
| `telegram_dialogs` | List chats, groups and channels |
| `telegram_search` | Search all chats at once (`only_private` to skip groups and channels) |
| `telegram_history` | One chat's messages, newest first; `limit`, `search`, `after`, `before` |
| `telegram_info` | Details of a chat, channel or user |
| `telegram_download` | Attachments of a post (with `album`) or a chat's latest messages; returns `download_url` per file |
| `telegram_post` | Send text to a private chat (dry-run unless `execute: true`) |
| `telegram_send_file` | Send up to 10 files to a private chat as one album, with caption and thumbnail (dry-run unless `execute: true`) |

Targets: `@username`, `t.me/...` links (public `t.me/name/123`, private `t.me/c/ID/123`, forum topics), numeric ids, `me`. Invite links are never joined automatically.

### Sending files

The file must be in the server's outbox: upload it, then pass its name.

```sh
TOKEN=...   # the server's bearer token
curl -fsS -H "Authorization: Bearer $TOKEN" -T ./clip.mp4 http://127.0.0.1:12020/files/clip.mp4
```

```json
{"name": "telegram_send_file", "arguments": {"target": "@friend", "files": ["clip.mp4"], "caption": "Look", "delete_after": true, "execute": true}}
```

Or pass `url` with a direct http(s) link and the server downloads it. Videos are sent with a player (duration and size are read by `hachoir`); `as_document: true` sends a plain file. Files outside the outbox, including symlinks to the session, are rejected.

### Fetching downloads

`telegram_download` saves into `outbox/downloads/<job>/` and returns a `download_url` per file:

```sh
curl -fsS -H "Authorization: Bearer $TOKEN" -o media.mp4 "<download_url>"
curl -fsS -H "Authorization: Bearer $TOKEN" -X DELETE http://127.0.0.1:12020/files/downloads/<job>
```

File endpoint rules: upload names are `[A-Za-z0-9._-]`, up to 150 characters, no folders; an existing file is kept unless `?overwrite=1`; up to 2000 MB per file; files older than `TG_OUTBOX_TTL_HOURS` (72) are deleted automatically.

## Triggers

`tg_triggers.py` keeps one live connection and runs a command when an incoming message matches a rule in `triggers/<account>.json` ([example](examples/triggers.example.json)):

| Field | Meaning |
|---|---|
| `name` | Rule name for logs |
| `from_ids`, `chat_ids` | Only these senders / chats (empty = any) |
| `private_only` | Only one-to-one chats |
| `pattern` | Case-insensitive regex on the message text |
| `argv` | Command to run, without a shell; gets `TG_TRIGGER_RULE`, `TG_TRIGGER_CHAT_ID`, `TG_TRIGGER_SENDER_ID`, `TG_TRIGGER_MESSAGE_ID` in the environment, never the text |
| `on_start` | Also fire once when the listener starts (catch up after downtime) |

Logs contain rule names, ids and exit codes only. Test without Telegram: `venv/bin/python tg_triggers.py --simulate <sender_id> "<text>" [--fire]`.

> [!CAUTION]
> Never run the listener with a session copied to another machine: the same key used from two IPs at once is revoked by Telegram (`AUTH_KEY_DUPLICATED`).

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `TG_MCP_TOKEN` / `TG_MCP_TOKEN_FILE` | — | Bearer token (required; `TG_MCP_ALLOW_NO_AUTH=1` disables auth for local testing) |
| `TG_MCP_HOST`, `TG_MCP_PORT` | `127.0.0.1`, `12020` | Listen address |
| `TG_MCP_PUBLIC_URL` | `http://<host>:<port>` | Base URL put into `download_url` and tool descriptions |
| `TG_MCP_TOKEN_HINT` | generic text | How your agents obtain the token, shown in tool descriptions |
| `TG_ACCOUNT_DIR` | `main` | Account name |
| `TG_ROOT` | this folder | Install root |
| `TG_PRIVATE_DIR` | `<root>/accounts/<account>/private` | Session and credentials |
| `TG_OUTBOX` | `<root>/outbox` | File exchange folder |
| `TG_OUTBOX_TTL_HOURS` | `72` | Auto-delete age for outbox files (`0` = never) |
| `TG_DEVICE_MODEL` | `telegram-user-mcp` | Device name shown in Telegram → Devices; keep it the same for the server and triggers |
| `TG_TIMEOUT` | `180` | Default per-call timeout, seconds |

## Development

```sh
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python -m unittest discover -s tests -v
(cd client && ../.venv/bin/python -m unittest discover -s tests -v)
```

Tests mock Telegram entirely; they cover link parsing, export boundaries, rich messages, outbox restrictions, auth, the file endpoint (including path traversal and symlink escapes) and tool argument mapping.

## License

[MIT](LICENSE)