telegram-mcp
by dedotmoroz
README.md
# telegram-mcp
[](https://github.com/dedotmoroz/telegram-mcp/actions/workflows/ci.yml)
A small, reusable MCP server for publishing to allowlisted Telegram groups and channels. It is intentionally independent of KotCat, English lessons, and any particular prompt.
The MVP exposes one write tool:
```text
send_message(chat, text, parse_mode, idempotency_key, disable_notification)
```
## Included in the MVP
- Node.js 22 + TypeScript.
- The official MCP TypeScript SDK over Streamable HTTP at `POST /mcp`.
- Telegram Bot API `sendMessage`.
- OAuth 2.1 resource-server mode with JWT signature, issuer, audience, expiry, and scope validation.
- An explicit allowlist of Telegram destinations.
- Telegram HTML, including `<tg-spoiler>`, with valid close/reopen behavior when a long message is split.
- Persistent idempotency records that survive container restarts.
- Multi-architecture Docker image suitable for Raspberry Pi.
## Security model
The Telegram token never appears in MCP arguments or responses. Keep it in the server's `.env` file. Every requested destination must resolve to an entry in `TELEGRAM_ALLOWED_CHATS`, and production startup fails when OAuth is disabled.
This service is an OAuth **resource server**, not an authorization server. Use an OAuth provider that supports the authorization-code flow with PKCE and either Client ID Metadata Documents (CIMD) or Dynamic Client Registration (DCR). The provider must issue JWT access tokens whose:
- `iss` equals `OAUTH_ISSUER`;
- `aud` contains `OAUTH_AUDIENCE` (normally the exact public `/mcp` URL);
- `exp` is present;
- `scope` or `scp` contains `OAUTH_SCOPE`.
ChatGPT's current OAuth requirements are documented in [Authentication – Plugins](https://developers.openai.com/plugins/build/auth).
## Telegram setup
1. Create a bot with `@BotFather` and keep its token private.
2. Add the bot to the target group or channel. For a channel, grant permission to post messages.
3. Find the numeric destination ID (channel and supergroup IDs commonly start with `-100`).
4. Add an alias and ID to the allowlist:
```dotenv
TELEGRAM_ALLOWED_CHATS=english-lessons=-1001234567890,team=-1009876543210
```
The tool may use either `english-lessons` or the corresponding allowlisted ID. An arbitrary ID is rejected.
## Local development
```bash
npm install
cp .env.example .env
```
For a local smoke test, edit `.env`:
```dotenv
NODE_ENV=development
AUTH_MODE=none
TELEGRAM_BOT_TOKEN=your-real-development-token
TELEGRAM_ALLOWED_CHATS=test=-1001234567890
IDEMPOTENCY_STORE_PATH=./data/idempotency.json
```
Then run:
```bash
npm run dev
```
The endpoints are:
- `http://127.0.0.1:3000/health`
- `http://127.0.0.1:3000/mcp`
`AUTH_MODE=none` is rejected when `NODE_ENV=production`.
## Raspberry Pi deployment
The compose service binds only to loopback. Put Nginx or another TLS reverse proxy in front of it; ChatGPT must reach a public HTTPS URL.
```bash
cp .env.example .env
# Fill in Telegram and OAuth settings.
docker compose up -d --build
docker compose ps
curl http://127.0.0.1:8932/health
```
Adapt [`deploy/nginx.conf.example`](deploy/nginx.conf.example) for the real domain and certificate. Persist `/app/data`: it contains the publication journal used to suppress duplicates.
For a temporary Pi-only smoke test before OAuth is configured, keep port `8932`
bound to loopback and use the development override:
```bash
docker compose -f compose.yaml -f deploy/compose.pi-mvp.yaml up -d --build
```
Do not expose this no-authentication override through Nginx or a router.
### Private connection through OpenAI Secure MCP Tunnel
Create `.tunnel.env` beside `compose.yaml` with mode `600`:
```dotenv
CONTROL_PLANE_TUNNEL_ID=tunnel_...
CONTROL_PLANE_API_KEY=sk-...
```
Then add `deploy/compose.openai-tunnel.yaml` to the Pi Compose command. The
official tunnel client reaches `telegram-mcp` only through the internal Docker
network and opens an outbound HTTPS connection to OpenAI; no public MCP route is
required. The tunnel override also adds the internal Compose hostname to the
MCP host allowlist. When the Moldova egress override is active, only the tunnel's
OpenAI control-plane and Harpoon traffic use that proxy; calls to the local MCP
service remain inside the Docker network.
If direct access to `api.telegram.org` is blocked, set `TELEGRAM_PROXY_URL` to
an HTTP CONNECT proxy. The optional `deploy/compose.pi-moldova.yaml` override
starts an internal-only Xray sidecar using `data/xray-telegram.json`; that
configuration contains credentials and must remain uncommitted with mode `600`.
## OAuth environment variables
| Variable | Meaning |
| --- | --- |
| `MCP_ALLOWED_HOSTS` | Extra comma-separated Host header values allowed for private proxies/tunnels |
| `PUBLIC_BASE_URL` | Public HTTPS origin, without `/mcp` |
| `OAUTH_ISSUER` | Exact authorization-server issuer |
| `OAUTH_AUTHORIZATION_ENDPOINT` | Authorization-code endpoint |
| `OAUTH_TOKEN_ENDPOINT` | Token endpoint |
| `OAUTH_JWKS_URL` | JWKS used to verify access-token signatures |
| `OAUTH_REGISTRATION_ENDPOINT` | DCR endpoint; omit only when CIMD is enabled |
| `OAUTH_CIMD_SUPPORTED` | `true` if the provider accepts client metadata document URLs |
| `OAUTH_ISSUER_IDENTIFICATION_SUPPORTED` | `true` only if every authorization response includes the exact `iss` parameter |
| `OAUTH_TOKEN_ENDPOINT_AUTH_METHODS` | Comma-separated metadata values, usually `none` or `none,private_key_jwt` |
| `OAUTH_AUDIENCE` | Expected JWT audience and MCP resource identifier |
| `OAUTH_SCOPE` | Required scope; defaults to `telegram:send` |
At least one of CIMD or DCR must be configured. The authorization server must advertise PKCE `S256` and correctly preserve the OAuth `resource` value. Do not set issuer-identification support to `true` unless the provider really implements RFC 9207.
## Calling `send_message`
Example tool arguments:
```json
{
"chat": "english-lessons",
"text": "<b>Daily English</b>\n\nChoose the answer: <tg-spoiler>was</tg-spoiler>",
"parse_mode": "HTML",
"idempotency_key": "english-lesson:2026-11-26",
"disable_notification": false
}
```
Use one stable idempotency key for one logical publication. Reusing that key with identical input returns `already_published`; reusing it with different input is an error.
Messages are split at up to 4,000 visible characters by default (configurable up to Telegram's 4,096 limit). Active HTML tags are closed at the end of a part and reopened in the next part.
### Delivery ambiguity
The journal is updated before and after every Telegram request. If Telegram explicitly rejects a request, it can be retried. If the network dies while a request is in flight, the server marks delivery as uncertain and blocks automatic retry, because Telegram's `sendMessage` API has no idempotency parameter. Inspect the target chat and `data/idempotency.json` before resolving such a record manually.
Run only one service replica against a given journal volume.
## Testing scheduled ChatGPT publication
Scheduled tasks can use plugins, but write actions may pause for approval. In the
tested ChatGPT setup, the first scheduled `send_message` call displayed
`Allow once` and `Always allow`. After the user selected `Always allow`, the
publication completed and later runs could use the tool without another prompt.
This is account/workspace policy and may differ or change, so every deployment
must verify it rather than assuming unattended writes are enabled.
Recommended MVP test:
1. Deploy the service and connect its `/mcp` URL to ChatGPT as a private plugin.
2. In a normal chat, call `send_message` once and complete authentication/approval.
3. Create a temporary scheduled task that runs a minute or two later and instruct it explicitly to use this plugin and `send_message`.
4. Give the task a unique test message and a deterministic key such as `telegram-mcp-smoke:2026-11-26T18:30+03:00`.
5. Check both the Telegram destination and the scheduled run history. A completed task status alone does not prove that the message was delivered.
If the run pauses for approval, review the exact requested action. Select a
persistent approval only for a server you operate and trust, and keep the
Telegram allowlist narrow. If the UI does not offer persistent approval,
unattended writes are unavailable under that account/workspace policy. Do not
weaken authentication or the Telegram allowlist to work around product controls.
See [Scheduled tasks in ChatGPT](https://help.openai.com/en/articles/10291617-scheduled-tasks-in-chatgpt) and [Scheduled tasks in ChatGPT Work](https://learn.chatgpt.com/docs/automations?surface=app).
## Quality checks
```bash
npm run check
npm run build
ENV_FILE=.env.example docker compose config
```
## Planned tools
After the scheduled-task experiment succeeds, the same server can add `list_chats`, `send_photo`, `send_quiz`, `edit_message`, `delete_message`, and `get_chat_info` without coupling them to lesson generation.
## License
MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues