Skip to content

Repository files navigation

TeleBotHost MCP Server

Deploy with VercelMCPTypeScriptNode.js

A Model Context Protocol server for the TeleBotHost Developer API — 68 tools to manage Telegram bots from AI assistants like Claude, Cursor, and Copilot.


Features

  • 68 Tools — Full coverage of the TeleBotHost Developer API + 3 docs search tools
  • Multi-Platform — Deploys on Vercel, Render, Railway, Fly.io, or any Node host
  • Secure — Bearer token auth, optional MCP endpoint protection, key-tier awareness (sk_* vs pub_*)
  • Resilient — Automatic 429 retry with exponential backoff, rate-limit header tracking
  • Binary-Safe — Base64-encoded ZIP download/upload for download_bot and import_bot
  • Safe by Design — Broadcast tool requires explicit confirm: true flag
  • Tested — Compliance test suite verifies MCP spec adherence (scripts/test-mcp.sh)
  • Type-Safe — Strict TypeScript throughout, clean compile
  • Zero-Config — Single env var (TELEBOTHOST_API_KEY) to get started

Table of Contents


Architecture

┌─────────────────┐ POST /api/mcp ┌─────────────────────┐ Bearer sk_* ┌─────────────────────┐
│ │ JSON-RPC 2.0 │ MCP Server │ HTTPS │ TeleBotHost API │
│ Claude Desktop │ ───────────────────▶ │ (stateless) │ ───────────────────▶ │ api.telebothost.com│
│ Cursor │ │ 68 tools │ │ │
│ Continue │ ◀─────────────────── │ JSON-RPC router │ ◀─────────────────── │ 64 endpoints │
│ Cline │ JSON response │ TBH API client │ JSON │ │
└─────────────────┘ └─────────────────────┘ └─────────────────────┘
│
▼
┌─────────────────┐
│ Vercel │ ← api/mcp.ts (serverless)
│ OR Render │ ← server.ts (Node HTTP)
│ OR Railway │
│ OR Fly.io │
└─────────────────┘

Transport: Streamable HTTP (stateless JSON-RPC 2.0 over HTTP POST) Runtime: Node.js 20+ · TypeScript 5.9 · @modelcontextprotocol/sdk 1.x


Quick Start

1. Get your TeleBotHost API key

  1. Log in to TeleBotHost
  2. Go to Developer SettingsAPI Keys
  3. Generate a key:
    • sk_*Secret key (full write access) — keep private
    • pub_*Public key (read-only) — safe for client-side

2. Deploy (pick a platform)

PlatformOne-clickDifficulty
VercelDeploy with VercelEasiest
RenderBlueprint readyEasy
Railwayrailway upMedium
Fly.iofly launchMedium
Self-hostnpm startMedium

3. Connect your AI client

See Connecting Your AI Client below.


Deployment

Vercel (Recommended)

One-click deploy:

Deploy with Vercel

Manual deploy:

# Clone
git clone https://github.com/telebothost/mcp-server.git
cd telebothost-mcp
npm install
# Set env var
vercel env add TELEBOTHOST_API_KEY production
# Paste your sk_* key when prompted# Deploy
vercel --prod

Your MCP endpoint: https://your-project.vercel.app/api/mcp


Render

This repo includes a render.yaml blueprint.

Option A — Dashboard (easiest):

  1. Push this repo to your GitHub
  2. Go to Render DashboardNewBlueprint
  3. Select your repo — Render auto-detects render.yaml
  4. Add TELEBOTHOST_API_KEY as a secret env var
  5. Click Apply

Option B — CLI:

# Install Render CLI
npm i -g @render-ai/render-cli
# Link & deploy
render blueprint deploy

Your MCP endpoint: https://telebothost-mcp.onrender.com/api/mcp


Railway / Fly.io / Self-Host

These platforms use the generic Node server (server.ts) via npm start.

# Clone & install
git clone https://github.com/telebothost/mcp-server.git
cd telebothost-mcp
npm install
# Set env varsexport TELEBOTHOST_API_KEY=sk_your_key_here
# Optional: export MCP_AUTH_TOKEN=your_mcp_protection_token# Start
npm start
# → [telebothost-mcp v1.0.0] MCP server listening on :3000

Railway:

railway init
railway up
# Set TELEBOTHOST_API_KEY in Railway dashboard

Fly.io:

fly launch --no-deploy
fly secrets set TELEBOTHOST_API_KEY=sk_your_key_here
fly deploy

Docker (any host):

docker build -t telebothost-mcp .
docker run -p 3000:3000 -e TELEBOTHOST_API_KEY=sk_xxx telebothost-mcp

Endpoint: http://localhost:3000/api/mcp


Connecting Your AI Client

Once deployed, point any MCP-compatible client at your endpoint. Pass your TeleBotHost API key in the X-Tbh-Api-Key header so each call uses your own TBH quota — the server never stores your key.

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
"mcpServers": {
"telebothost": {
"url": "https://your-deployed-url/api/mcp",
"transport": "http",
"headers": {
"X-Tbh-Api-Key": "sk_your_telebothost_key_here"
}
}
}
}

Cursor

Settings → MCP → Add Server:

{
"mcpServers": {
"telebothost": {
"url": "https://your-deployed-url/api/mcp",
"headers": {
"X-Tbh-Api-Key": "sk_your_telebothost_key_here"
}
}
}
}

VS Code (with Cline / Continue)

Add to your MCP settings:

{
"mcp.servers": {
"telebothost": {
"url": "https://your-deployed-url/api/mcp",
"headers": {
"X-Tbh-Api-Key": "sk_your_telebothost_key_here"
}
}
}
}

With MCP_AUTH_TOKEN protection (server-side access control)

If the server has MCP_AUTH_TOKEN set (to restrict WHO can call the MCP), add both headers:

{
"mcpServers": {
"telebothost": {
"url": "https://your-deployed-url/api/mcp",
"headers": {
"Authorization": "Bearer your-mcp-auth-token",
"X-Tbh-Api-Key": "sk_your_telebothost_key_here"
}
}
}
}
  • Authorization: Bearer ... → authenticates you to the MCP server (the MCP_AUTH_TOKEN)
  • X-Tbh-Api-Key: ... → your TeleBotHost API key (forwarded to TBH API)

Test with curl

# List all tools (no TBH key needed)
curl -X POST https://your-deployed-url/api/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'# Call a public tool (no TBH key needed)
curl -X POST https://your-deployed-url/api/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_status","arguments":{}}}'# Call an authenticated tool (pass your TBH key)
curl -X POST https://your-deployed-url/api/mcp \
-H "Content-Type: application/json" \
-H "X-Tbh-Api-Key: sk_your_key_here" \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_bots","arguments":{}}}'

API Key Resolution (Priority Order)

When a tools/call request arrives, the server resolves the TBH API key in this order:

PrioritySourceWhen to use
1X-Tbh-Api-Key headerRecommended — each user passes their own key per-request
2Authorization: Bearer sk_* headerOnly used if MCP_AUTH_TOKEN is NOT set (otherwise Authorization is for MCP auth)
3TELEBOTHOST_API_KEY env varServer-side fallback for single-user / self-hosted setups

Best practice: Don't set TELEBOTHOST_API_KEY on the server. Let each client pass X-Tbh-Api-Key so everyone uses their own TBH quota.


Available Tools (68)

Health (1)

ToolDescription
get_statusAPI health & version probe

Public Discovery (9) — no auth required

ToolDescription
get_public_userGet a user's public profile
list_public_user_botsList a user's published bots & templates
get_public_user_botGet a published bot by Telegram username
get_public_user_bot_readmeGet published bot README only
list_templatesBrowse shareable bot templates
get_templateGet a template by ID
get_template_readmeGet template README
list_public_store_botsBrowse community store (public)
get_public_store_botGet a store listing (public)
get_public_adsFetch active ads feed (public)

Bot Lifecycle (20) — sk_* key required for writes

ToolDescription
list_botsList your bots + statistics
register_botRegister a new bot
delete_botsSoft-delete bots (10-day backup)
list_deleted_botsList soft-deleted bots
recover_deleted_botRecover a soft-deleted bot
purge_deleted_botPermanently delete from backup
pin_botsPin / unpin bots
get_botGet single bot details
update_botUpdate bot config
export_botGenerate temp JWT download URL
download_botDownload bot ZIP (base64-encoded binary)
import_botImport bot from base64-encoded ZIP
clone_botClone a bot or template
clone_bot_as_childClone as child (inherits env/commands)
list_bot_childrenList child bots of a parent
transfer_botTransfer bot to another user
reset_botReset logs & sessions
toggle_bot_templateToggle template status
get_bot_readmeGet bot README (owner)
update_bot_readmeUpdate README (template only)

Bot Storage (4)

ToolDescription
get_bot_storage_statsSync/async storage size & metrics
get_bot_storage_keysList storage keys (no values)
clear_bot_storageClear all storage (irreversible)
migrate_bot_storageMigrate sync → async storage

Broadcasts (6)

ToolDescription
start_broadcastStart a broadcast (confirm=true required)
get_broadcast_statsReal-time broadcast progress
stop_broadcastStop an active broadcast
modify_broadcastModify message body mid-run
delete_broadcastDelete broadcast history record
list_broadcastsList broadcasts for a bot

Commands (13) — full CRUD + folder management

ToolDescription
list_commandsList commands & folders
create_commandCreate a new command
get_commandGet a single command by ID
update_commandUpdate command code, answer, aliases, folder
delete_commandSoft-delete a command (7-day recovery)
delete_commandsBatch soft-delete commands
permanently_delete_commandPermanently delete a soft-deleted command
list_deleted_commandsList soft-deleted commands
recover_deleted_commandRecover a deleted command
list_command_foldersList command folders
create_command_folderCreate a command folder
update_command_folderRename a command folder
delete_command_folderDelete a folder (unassigns commands)

Environment Variables (5)

ToolDescription
list_env_varsList all env vars for a bot
create_env_varCreate an env var
get_env_varGet a single env var
update_env_varUpdate an env var
delete_env_varDelete an env var

Logs & Analytics (3)

ToolDescription
get_bot_logsGet runtime/error logs
clear_bot_logsClear all logs (irreversible)
get_bot_analyticsUser growth, activity & chat-type stats

Community Store (2)

ToolDescription
list_store_botsBrowse store (authenticated)
install_store_botInstall a store bot

Quota (1)

ToolDescription
get_quotaCheck daily / per-minute / monthly limits

Docs Search (3) — no auth required

ToolDescription
search_tbh_api_docsSearch TeleBotHost Developer API (OpenAPI spec) by keyword
search_tbl_docsSearch TBL scripting language documentation
search_telegram_docsSearch Telegram Bot API docs at core.telegram.org

MCP Protocol

This server implements the Model Context ProtocolStreamable HTTP transport in stateless mode — perfect for serverless platforms.

JSON-RPC 2.0 Methods Supported

MethodBehavior
initializeReturns protocolVersion: 2024-11-05, server capabilities, and server info
notifications/initializedReturns HTTP 202 (acknowledged, no body)
pingReturns empty {result: {}} — health check
tools/listReturns all 68 tool definitions (name, description, inputSchema)
tools/callExecutes a tool by name with arguments; returns {content, isError}

Stateless Design

Each HTTP request creates a fresh server instance — no session persistence, no in-memory state. This means:

  • Works on Vercel serverless, AWS Lambda, Cloudflare Workers
  • Horizontally scalable (any number of replicas)
  • No cold-start session affinity issues
  • No server-initiated notifications (clients must poll)
  • No SSE streaming (single JSON response per request)

Request/Response Format

Request:

POST /api/mcp HTTP/1.1Content-Type: application/json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_bots",
"arguments": {}
}
}

Success response:

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{ "type": "text", "text": "{...bot data as JSON...}" }]
}
}

Error response (tool-level):

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{ "type": "text", "text": "TeleBotHost API error 403: ..." }],
"isError": true
}
}

Error response (protocol-level):

{
"jsonrpc": "2.0",
"id": 1,
"error": { "code": -32601, "message": "Method not found: foo/bar" }
}

Error Handling

The server implements a layered error handling strategy:

Layer 1: Protocol Errors (JSON-RPC)

Returned as {error: {code, message}} per the JSON-RPC 2.0 spec:

CodeMeaningWhen
-32700Parse errorInvalid JSON in request body
-32600Invalid RequestMissing jsonrpc: "2.0" or method
-32601Method not foundUnknown JSON-RPC method
-32602Invalid paramsUnknown tool name
-32603Internal errorUnexpected exception in handler

Layer 2: Tool Errors (MCP isError)

When a tool executes but the upstream TBH API returns an error, the response includes isError: true with the error details in the content text field. The AI client can read this and decide how to proceed (retry, ask user, etc.).

{
"content": [{
"type": "text",
"text": "TeleBotHost API error 429: Rate limit exceeded. Retry after 60s."
}],
"isError": true
}

Layer 3: Automatic Retry

HTTP 429 responses from the TBH API are automatically retried up to 3 times with exponential backoff:

AttemptDelay
12s (or Retry-After header)
24s
38s

After 3 retries, the 429 is surfaced as a tool error.

Layer 4: Cloudflare Detection

The TBH API is behind Cloudflare, which may challenge datacenter IPs. The client detects Cloudflare challenge responses (HTTP 403 + cf_chl in body) and returns a user-friendly message instead of the raw HTML challenge page.


Testing

Tool Coverage Check

npm run test:coverage
# → Asserts exactly 68 tools, unique snake_case names, required tools present

Compliance Test Suite

The repo includes a bash-based compliance test suite that verifies MCP spec adherence:

# Test against local server
npm start &
sleep 2
npm run test:mcp
# Test against production
MCP_URL=https://tbh-mcp.vercel.app/api/mcp npm run test:mcp
# With auth token
MCP_URL=https://your-url/api/mcp MCP_TOKEN=xxx npm run test:mcp
# Bash variant (optional)
MCP_URL=http://localhost:3000/api/mcp ./scripts/test-mcp.sh

What it verifies:

  1. initialize handshake returns correct protocol version & server info
  2. ping returns a result
  3. tools/list returns exactly 68 tools
  4. All tools have name + description + inputSchema
  5. All tools use clean names (no telebothost_ prefix)
  6. tools/call rejects unknown tools with error -32602
  7. Invalid JSON returns -32700 parse error
  8. GET method returns HTTP 405 (only POST allowed)
  9. All required tools are present (10 critical tools checked)

CI (.github/workflows/ci.yml) runs typecheck, coverage, smoke tests, and a Docker build on every push/PR to main.

Type Safety

npm run typecheck
# → tsc --noEmit (strict mode, zero errors)

Manual Smoke Test

# Initialize
curl -X POST $MCP_URL -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'# List tools
curl -X POST $MCP_URL -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'# Call a tool
curl -X POST $MCP_URL -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_status","arguments":{}}}'

API Coverage

This MCP server covers 100% of the TeleBotHost Developer API — every endpoint in the OpenAPI 3.0.3 spec is mapped to a tool.

GroupEndpointsToolsCoverage
Health11100%
Public Discovery1010100%
Bot Lifecycle2020100%
Bot Storage44100%
Broadcasts66100%
Commands + Folders1313100%
Env Vars55100%
Logs & Analytics33100%
Community Store22100%
Quota (helper)1N/A (reuses GET /bot)
Docs Search3N/A (fetches external docs)
Total6468Full coverage

Binary Endpoints (Expert Implementation)

Two endpoints involve binary data (ZIP files) which MCP's JSON model doesn't natively support. They're handled via base64 encoding:

EndpointToolApproach
GET /bot/downloaddownload_botDownloads ZIP as ArrayBuffer, returns base64-encoded string with metadata (size, content-type, filename)
POST /bot/importimport_botAccepts base64-encoded ZIP, decodes to Uint8Array, uploads as multipart/form-data

Example download_bot response:

{
"success": true,
"content_type": "application/zip",
"filename": "my-bot.zip",
"size_bytes": 4523,
"size_kb": 4.42,
"encoding": "base64",
"base64": "UEsDBBQACAgA..."
}

The AI client can then write the base64 to a file and decode it to get the actual ZIP.


Environment Variables

VariableRequiredDescription
TELEBOTHOST_API_KEYNo (optional)Server-side fallback TBH API key. Recommended: leave unset — let each client pass X-Tbh-Api-Key header per-request. Only set this for single-user self-hosted setups.
MCP_AUTH_TOKENNoIf set, clients must send Authorization: Bearer <token> to access the MCP itself (separate from TBH API key). Use to restrict WHO can call your MCP.
TELEBOTHOST_API_BASENoOverride API base URL (default: https://api.telebothost.com/api/v1)
PORTNoPort for server.ts (default: 3000, auto-set by Render/Railway/Fly)

Two Layers of Auth (Important!)

This MCP has two independent auth layers — don't confuse them:

LayerHeaderEnv VarPurpose
MCP access controlAuthorization: Bearer <MCP_AUTH_TOKEN>MCP_AUTH_TOKENRestrict WHO can call your MCP endpoint
TeleBotHost API authX-Tbh-Api-Key: <sk_*>TELEBOTHOST_API_KEY (fallback)Authenticate to the upstream TBH API

Typical setups:

  1. Public MCP, per-user TBH keys (recommended for shared deployments):

    • Don't set MCP_AUTH_TOKEN, don't set TELEBOTHOST_API_KEY
    • Each client passes X-Tbh-Api-Key: sk_their_own_key in their MCP config
    • Server stores no secrets
  2. Protected MCP, per-user TBH keys (recommended for team deployments):

    • Set MCP_AUTH_TOKEN on server
    • Don't set TELEBOTHOST_API_KEY
    • Clients pass both Authorization: Bearer <mcp_token> AND X-Tbh-Api-Key: sk_their_own_key
  3. Personal MCP, server-side key (simplest for solo use):

    • Set TELEBOTHOST_API_KEY on server
    • Don't set MCP_AUTH_TOKEN
    • Clients don't need any headers (server uses its env var for all calls)

Rate Limits

The TeleBotHost API enforces plan-based limits. This MCP server automatically retries on HTTP 429 with exponential backoff (up to 3 retries).

PlanDailyPer-minMonthly
FREE / FREEMIUM1,0001515,000
PREMIUM5,0006075,000
ELITE10,000120150,000

pub_* keys are always capped at 1,000/day, 15/min, 15,000/month regardless of plan.

Use get_quota to check remaining quota at any time.


Local Development

# Install deps
npm install
# Set env vars
cp .env.example .env
# Edit .env with your TELEBOTHOST_API_KEY# Run locally (generic Node server)
npm run dev
# → http://localhost:3000/api/mcp# OR run as Vercel dev (simulates serverless)
npm run vercel:dev
# Type-check
npm run typecheck
# Test
curl -X POST http://localhost:3000/api/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'

Project Structure

telebothost-mcp/
├── api/
│ ├── index.ts # GET / → Docs page (root)
│ ├── docs.ts # GET /docs → Docs page (alias)
│ ├── health.ts # GET /api/health → JSON health probe
│ └── mcp.ts # POST /api/mcp → MCP JSON-RPC endpoint
├── lib/
│ ├── types.ts # Shared types & TbhApiError
│ ├── client.ts # TeleBotHost API client (auth, retry, binary, errors)
│ ├── tools.ts # All 68 MCP tool definitions
│ └── docs.ts # HTML docs page generator
├── scripts/
│ ├── test-mcp.mjs # Compliance test suite (cross-platform)
│ ├── test-mcp.sh # Compliance test suite (bash)
│ └── check-coverage.ts # Asserts tool count / uniqueness
├── .github/
│ └── workflows/
│ └── ci.yml # Typecheck + coverage + smoke tests
├── server.ts # Generic Node HTTP server (Render/Railway/Fly)
├── Dockerfile # Container image for any host
├── .dockerignore
├── render.yaml # Render.com Blueprint config
├── vercel.json # Vercel serverless config + routes
├── .env.example # Environment variable template
├── .nvmrc # Node version pin
├── package.json
├── tsconfig.json
├── LICENSE
├── CONTRIBUTING.md
└── README.md

Endpoints

MethodPathDescription
GET/Documentation page (HTML) — tool list, quick start, configs
GET/docsAlias for /
GET/api/healthJSON health probe — {"status":"ok","tools":68,...}
POST/api/mcpMCP JSON-RPC endpoint (initialize, tools/list, tools/call)

Roadmap

  • v1.0.0 — Initial release: 46 tools, Vercel deployment
  • v1.1.0 — Cleaner tool names (dropped telebothost_ prefix)
  • v1.2.0 — 100% API coverage: download_bot & import_bot (binary base64), compliance test suite, multi-platform deploy configs
  • v1.3.0 — Per-request API key via X-Tbh-Api-Key header — multi-user support, each user uses own TBH quota
  • v2.0.0 — 68 tools: full CRUD for commands + folders, env vars, logs, analytics, docs search (TBH API, TBL lang, Telegram Bot API)
  • v2.1.0 — Docker support, GitHub Actions CI, automated coverage check in CI
  • v2.2.0 — SSE streaming transport for stateful deployments (Render/Railway)
  • v3.0.0 — Tool-level RBAC, audit logging, multi-region deployment guide

Contributing

Contributions welcome! See CONTRIBUTING.md for setup, conventions, and PR guidelines.

Adding a new tool

  1. Open lib/tools.ts
  2. Add a ToolDef to the appropriate group
  3. Use a clear snake_case name, short description, JSON-Schema input
  4. Run npm run typecheck
  5. Open a PR

Acknowledgements

Special thanks to Cyber (@CyberXCoding) for creating the base version of this MCP server that this project was built upon.


License

MIT © Muiz Ahmed (mmuizahmed)


Links


Built for the TeleBotHost community by Muiz Ahmed

About

MCP server for the TeleBotHost Developer API - 68 tools to manage Telegram bots via AI assistants like Claude, Cursor, and Copilot

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages