Skip to main content
Glama
Telegram User MCP

Telegram User MCP

by pewpewgogo
README.md
# Telegram user account

An MCP server and Cursor / Grok Bot plugin that reads and sends Telegram messages as a person's own account. It speaks MTProto through [teleproto](https://docs.teleproto.dev), the maintained GramJS-compatible library. It does not use the Bot API, and it does not use a bot token.

Source: https://github.com/pewpewgogo/grokbot-telegram. Author: [Volodya Plotvinov / DevLaunch](https://devlaunch.uk). License: MIT.

A StringSession from the login script is a full login. Anyone who has it can read chats and send messages as that account, including private chats. Store it like a password. Revoke it in Telegram under Settings, Devices, and replace it if it leaks.

## Tools

| Tool | What it does |
| --- | --- |
| `get_me` | Who the session is signed in as. No phone number. |
| `list_dialogs` | Chats, newest first. Optional title filter, folder (`all`, `main`, `archived`), and `next_cursor`. |
| `list_unread` | Chats with unread messages or mentions, from a bounded scan. |
| `read_messages` | Messages in one chat, newest first. Page with `next_cursor` or `offset_id`. |
| `search_messages` | Text search in one chat, or global when `chat` is omitted. |
| `get_chat_info` | Title, kind, username, and public flags. |
| `list_contacts` | The account's saved contacts. A query matches that address book only. |
| `resolve_username` | Turn a public `@username` into an id. |
| `get_channel_posts` | Posts in a channel or supergroup. |
| `send_message` | Text, with optional `reply_to` and `parse_mode`. |
| `forward_message` | Forward one message. The original sender stays visible. |
| `mark_read` | Mark one chat read, optionally up to `max_id`. |

`send_message` and `forward_message` default to a dry run. The descriptions tell the calling agent to show the exact draft and wait for a yes before setting `dry_run` to false. There is no bulk-send tool.

Chat arguments are `me`, a `@username`, or a numeric id from `list_dialogs`. Phone numbers are not accepted as chat ids.

## Skills

Generic instructions for the agent, with no personal chats or account details:

- `telegram-user-account` — when to call which tool, and how to handle auth and flood waits.
- `summarize-unread` — digest unread chats without sending.
- `draft-and-send` — show a draft, then send only after an explicit yes.
- `search-telegram-history` — search one chat or the whole account and page the results.

A short always-on rule in `rules/telegram-account-safety.mdc` repeats the confirmation requirement.

## Create a session

1. Open [my.telegram.org/apps](https://my.telegram.org/apps) while logged into the Telegram account you want to connect. Create an application and copy the numeric **api_id** and the **api_hash**. This is a user application, not a bot token from BotFather.
2. Install and log in from this directory. The interactive script prompts for the phone, the login code, and the two-factor password only if Telegram asks. It can also prompt for an email if Telegram asks for one on a new sign-in.

```bash
npm ci
export TELEGRAM_API_ID="123456"
export TELEGRAM_API_HASH="your-api-hash"
npm run login
```

In interactive mode, stdout prints only the session string. Everything else goes to stderr. Do not pass the hash, the code, or the password as command-line arguments. You can also set `TELEGRAM_PHONE`, `TELEGRAM_CODE`, and, only when the account has a password, `TELEGRAM_2FA_PASSWORD`. Unset those after the script finishes.

Non-interactive file mode never prints the session. Set the api id, api hash, and phone, plus a code file and an output path. The script asks Telegram to send the login code, then polls until `TELEGRAM_CODE_FILE` contains it. If the account has a two-factor password, set `TELEGRAM_PASSWORD_FILE` as well. The StringSession is written to `TELEGRAM_SESSION_OUT` with mode `600`.

```bash
export TELEGRAM_API_ID="123456"
export TELEGRAM_API_HASH="your-api-hash"
export TELEGRAM_PHONE="+15551212"
export TELEGRAM_CODE_FILE="/tmp/telegram-code"
export TELEGRAM_PASSWORD_FILE="/tmp/telegram-password"   # only if 2FA is enabled
export TELEGRAM_SESSION_OUT="/tmp/telegram-session"
npm run login
# after Telegram sends the code:
printf '%s\n' '12345' > /tmp/telegram-code
# if Telegram asks for the password:
printf '%s\n' 'your-password' > /tmp/telegram-password
```

Delete the code and password files after login. Copy the session file into your secret store, then delete it too. Polling waits three minutes by default (`TELEGRAM_LOGIN_TIMEOUT_MS`).

Login uses the same `TELEGRAM_TRANSPORT` setting as the server, described below. On a network that intercepts raw MTProto, set `TELEGRAM_TRANSPORT=websocket` before `npm run login`.

Put the three values in a secret store:

```bash
TELEGRAM_API_ID
TELEGRAM_API_HASH
TELEGRAM_STRING_SESSION
```

teleproto reads a legacy GramJS or Telethon StringSession and saves new sessions in its own version-prefixed form. Either form works with this server. The login client identifies itself as **Telegram User MCP** in Telegram's active sessions, so you can recognize it and log it out.

The process never writes these values to logs. Error text is scrubbed if a secret would otherwise appear. Logs go to stderr because stdout is the MCP protocol stream.

## Run over stdio

```bash
npm run build
npm start
```

`npm start` speaks MCP on stdin and stdout. A host such as Cursor or a Grok Bot cloud computer should launch `node bin/start.mjs` (or `node dist/index.js` after a build) with the three variables in the environment. On first launch, `bin/start.mjs` runs `npm ci` and `npm run build` if `dist/` is missing, and it keeps that output off stdout. Set `TELEGRAM_MCP_SKIP_INSTALL=1` to fail instead of installing. Build once yourself if you do not want the first tool call to wait on npm.

Optional pacing:

| Variable | Default | Meaning |
| --- | --- | --- |
| `TELEGRAM_MIN_INTERVAL_MS` | `400` | Minimum gap between Telegram calls. |
| `TELEGRAM_FLOOD_RETRY_MAX_SECONDS` | `3` | A `FloodWait` or slow-mode wait this short is slept once and retried. Longer waits return `FLOOD_WAIT` and `retry_after_seconds`. |
| `TELEGRAM_DIALOG_SCAN_CAP` | `200` | Dialogs scanned by unread listing and title search. Maximum `500`. |

The client sets GramJS-style `floodSleepThreshold` to `0`, so the library does not hide a long wait inside the tool call.

### How the process reaches Telegram

`TELEGRAM_TRANSPORT` is `tcp` or `websocket`. The default is `tcp`.

| Value | Behavior |
| --- | --- |
| `tcp` | Direct MTProto over TCP, which is what Telegram's own clients use. If that handshake is rejected the way an intercepting proxy rejects it (`Invalid intermediate packet length`), the process disconnects and tries once over WebSocket. The TCP probe makes two attempts, then gives up on that socket. |
| `websocket` | Secure WebSocket only. Use this when TCP port 443 is intercepted and you do not want to wait for the probe. |

The login script reads the same variable. A rejected TCP handshake falls back only before the login code is requested, so a bad code is not sent again over the other transport.

## Run over HTTP

```bash
TELEGRAM_MCP_TRANSPORT=http \
TELEGRAM_MCP_HOST=127.0.0.1 \
TELEGRAM_MCP_PORT=8787 \
npm start
```

- `GET /health` returns `{"ok":true}` and does not need the bearer token.
- `POST /mcp` is the Streamable HTTP MCP endpoint.
- Binding anything other than `127.0.0.1`, `localhost`, or `::1` requires `TELEGRAM_MCP_AUTH_TOKEN`. Clients send `Authorization: Bearer <token>`.
- Loopback binds also check the `Host` and `Origin` headers so a browser page cannot use DNS rebinding against the local port. Requests with no `Origin` are allowed.
- Put a TLS reverse proxy in front of any non-local deployment. This server does not terminate TLS.

Point an MCP client at `http://127.0.0.1:8787/mcp`.

### Docker

`compose.yaml` publishes the port on loopback only and refuses to start until the session variables and `TELEGRAM_MCP_AUTH_TOKEN` are set in the environment. The image runs as a non-root user. Secrets are runtime environment variables, not image build arguments.

```bash
export TELEGRAM_API_ID="123456"
export TELEGRAM_API_HASH="your-api-hash"
export TELEGRAM_STRING_SESSION="your-session"
export TELEGRAM_MCP_AUTH_TOKEN="a-long-random-token"
docker compose up --build
```

The MCP URL on the host is `http://127.0.0.1:8787/mcp`.

## Plugin format

**Assumption:** Grok Bot's Connect apps install Cursor Marketplace plugins. This repo follows that Cursor plugin layout, documented at [cursor.com/docs/reference/plugins](https://cursor.com/docs/reference/plugins):

```text
.cursor-plugin/plugin.json    manifest, including secret variable names
mcp.json                      stdio server command
skills/*/SKILL.md             agent skills
rules/*.mdc                   safety rule
assets/logo.svg
```

`mcp.json` starts `node ${CURSOR_PLUGIN_ROOT}/bin/start.mjs` and passes `TELEGRAM_API_ID`, `TELEGRAM_API_HASH`, `TELEGRAM_STRING_SESSION`, and `TELEGRAM_TRANSPORT` from the plugin setup fields. The manifest declares those names under `variables`. The three secrets are required. `TELEGRAM_TRANSPORT` is optional and defaults to `tcp`; leave it blank or set `websocket` when direct TCP is intercepted. The values are not in the repo. In Cursor they are set under Plugins, Configure.

A second manifest is included for the Grok Build plugin directory, which looks for `plugin.json`, then `.grok-plugin/plugin.json`, and loads MCP config from `.mcp.json`:

```text
.grok-plugin/plugin.json
.mcp.json
```

`.mcp.json` runs `node bin/start.mjs` with the working directory at the plugin root, because that layout does not document `${CURSOR_PLUGIN_ROOT}`. If a marketplace accepts only one of these trees, use the Cursor manifest for Grok Bot and the Cursor Marketplace.

There is no root `plugin.json`. Cursor would treat that as an Agent Plugin manifest and might ignore `.cursor-plugin/plugin.json`.

### Submit it

1. The public repository is https://github.com/pewpewgogo/grokbot-telegram. Do not commit `.env` or a session string.
2. For the Cursor Marketplace, and therefore Grok Bot Connect apps, submit the repository at [cursor.com/marketplace/publish](https://cursor.com/marketplace/publish). The checklist there asks for a valid manifest, a description, a logo in the repo, a README, and every `${VAR}` in `mcp.json` declared under `variables`.
3. A hosted MCP URL, from the Docker service behind TLS, is what a form that asks for an MCP server URL wants. The SpaceXAI plugin form is the other public route that lists Grok Bot; it asks for a public GitHub repository or an MCP URL, plus a logo URL and testing steps. Use the same publisher terms that form links.
4. For the Grok Build catalog, vendor or reference this repo from [github.com/xai-org/plugin-marketplace](https://github.com/xai-org/plugin-marketplace) and point the marketplace entry at this plugin. That catalog uses the `.grok-plugin` files above.

Try it after install by asking the bot who the connected Telegram account is (`get_me`), then for a summary of unread chats. Sending should stop on a dry-run draft until you confirm the text.

## Development

Node.js 22 or newer.

```bash
npm ci
npm test
npm run build
```

Tests call the tool handlers with a fake Telegram gateway, plus tests for config, flood-wait mapping, cursors, and the HTTP health and auth gate. They do not log in and they do not open a network connection to Telegram.

## Limits

The server will not delete messages, leave or join chats, import contacts, or send one message to many recipients. Each message body returned to the agent is capped at 4000 characters. Sends are capped at Telegram's 4096-character text limit. Page sizes are 1 to 100.