Skip to main content
MindStudio
Pricing
Blog About
My Workspace

How to Run Claude Code on a VPS with Mobile Access via Telegram

Run Claude Code on a VPS with Tmux for always-on sessions and control it from your phone via Telegram. Here's the full setup guide for 24/7 AI workflows.

MindStudio Team RSS
How to Run Claude Code on a VPS with Mobile Access via Telegram

Why Running Claude Code on a Laptop Isn’t Enough

If you’ve used Claude Code for anything serious, you’ve probably hit the same wall: you close your laptop, and the session dies. Your agent was halfway through refactoring a codebase, and now it’s gone.

Claude Code on a VPS with Tmux solves this. You get persistent, always-on sessions that keep running regardless of whether your laptop is open. Pair that with a Telegram bot, and you can monitor progress, send prompts, and check output from your phone while you’re at the gym, in a meeting, or on a flight.

This guide walks through the full setup — from provisioning a server to building the Telegram interface that puts Claude in your pocket.


What You’ll Need Before Starting

Before touching any server, gather these:

  • A VPS — DigitalOcean, Hetzner, Vultr, or Linode all work. A $6–12/month droplet (2GB RAM, 1 vCPU) is enough for most Claude Code tasks. Hetzner’s CX22 is a popular choice for the price.
  • Anthropic API key — Claude Code requires this. Get it from your Anthropic Console account.
  • Telegram account — You’ll create a bot through BotFather (takes two minutes).
  • Basic SSH comfort — You don’t need to be a Linux expert, but you should know how to connect to a server and run commands.

The whole setup takes 30–45 minutes the first time.


Set Up Your VPS

Provision the Server

Spin up a Ubuntu 22.04 LTS instance. This is the most stable base for this stack. Most providers let you add an SSH key during setup — do that instead of relying on a password.

Once it’s running, connect:

ssh root@YOUR_SERVER_IP

Create a Non-Root User

Running everything as root is a security risk. Create a dedicated user:

adduser claude-user
usermod -aG sudo claude-user

Then switch to that user for everything that follows:

su - claude-user

Update the System

Before installing anything:

sudo apt update && sudo apt upgrade -y

Install Node.js and Claude Code

Install Node.js

Claude Code requires Node.js 18 or higher. The cleanest way to install it on Ubuntu is via the NodeSource repository:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

Verify the install:

node --version
npm --version

Install Claude Code

npm install -g @anthropic-ai/claude-code

Set Your Anthropic API Key

Add the key to your shell profile so it persists across sessions:

echo 'export ANTHROPIC_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc

Test that Claude Code runs:

claude --version

If you see a version number, the install worked.


Configure Tmux for Persistent Sessions

Tmux keeps your terminal sessions alive even when you disconnect from the VPS. Without it, any SSH drop — intentional or not — kills your Claude Code process.

Install Tmux

sudo apt install tmux -y

Basic Tmux Concepts You Need

  • Session — A persistent workspace. You can detach and reattach without losing anything.
  • Window — A tab within a session.
  • Pane — A split within a window.

The key commands:

ActionCommand
Create a new named sessiontmux new -s session-name
Detach from a sessionCtrl+B, then D
List all sessionstmux ls
Reattach to a sessiontmux attach -t session-name
Kill a sessiontmux kill-session -t session-name

Create a Claude Session

tmux new -s claude

You’re now inside a Tmux session. Start Claude Code:

claude

You’ll see Claude Code’s interactive prompt. Now detach without killing it:

Press Ctrl+B, then D.

You’re back at the regular shell. The Claude session is still running in the background. You can verify:

tmux ls

Output will show something like claude: 1 windows (created Mon Jan 6 10:00:00 2025).

This is the foundation of the whole setup. Claude runs indefinitely on the VPS, and you can reattach from any SSH connection at any time.

Keep Tmux Sessions Alive After Reboots

By default, a VPS reboot kills all Tmux sessions. If uptime matters to you, there are two options:

Option 1: Tmux Plugin Manager + tmux-resurrect This plugin saves and restores sessions across reboots. Install Tmux Plugin Manager and add set -g @plugin 'tmux-plugins/tmux-resurrect' to your ~/.tmux.conf.

Option 2: Systemd service Create a systemd unit that starts your Tmux session and Claude Code on boot. More setup, but more reliable for production use. Covered in the troubleshooting section below.


Build the Telegram Bot

Now for the part that makes this actually useful: a Telegram bot that lets you interact with your Claude session from your phone.

Create the Bot

  1. Open Telegram and search for @BotFather.
  2. Send /newbot.
  3. Give it a name and username (e.g., MyClaude_bot).
  4. BotFather returns a token — save this. It looks like 123456789:ABCdefGHIjklMNOpqrsTUVwxyz.
In 60 minutes, you'll know Hermes
The free Hermes Agent crash courseReserve your spot

Get Your Telegram User ID

You need your personal Telegram user ID so the bot only responds to you (not random people who find it).

Search for @userinfobot in Telegram and start it. It will reply with your numeric user ID. Save that too.

Install Python and Dependencies

The bot is written in Python. Install it on the VPS:

sudo apt install python3 python3-pip -y
pip3 install python-telegram-bot

Write the Bot Script

Create the bot file:

nano ~/telegram_claude_bot.py

Paste this:

import subprocess
import time
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

# Configuration
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
ALLOWED_USER_ID = 123456789  # Your Telegram user ID
TMUX_SESSION = "claude"

logging.basicConfig(level=logging.INFO)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Claude Code controller active.\n\n"
        "Commands:\n"
        "/status — see current terminal output\n"
        "/clear — clear the terminal\n"
        "Any other message is sent directly to Claude."
    )

async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != ALLOWED_USER_ID:
        return
    result = subprocess.run(
        ['tmux', 'capture-pane', '-t', TMUX_SESSION, '-p'],
        capture_output=True, text=True
    )
    output = result.stdout.strip()
    if output:
        # Telegram has a 4096 character limit per message
        await update.message.reply_text(output[-4000:])
    else:
        await update.message.reply_text("No output captured.")

async def clear_terminal(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != ALLOWED_USER_ID:
        return
    subprocess.run(['tmux', 'send-keys', '-t', TMUX_SESSION, 'clear', 'Enter'])
    await update.message.reply_text("Terminal cleared.")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != ALLOWED_USER_ID:
        return
    
    text = update.message.text
    
    # Send the message to the tmux session
    subprocess.run(['tmux', 'send-keys', '-t', TMUX_SESSION, text, 'Enter'])
    
    await update.message.reply_text(f"Sent: {text}")
    
    # Wait for Claude to start responding, then capture output
    time.sleep(3)
    result = subprocess.run(
        ['tmux', 'capture-pane', '-t', TMUX_SESSION, '-p'],
        capture_output=True, text=True
    )
    output = result.stdout.strip()
    if output:
        await update.message.reply_text(output[-4000:])

def main():
    app = Application.builder().token(BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("status", status))
    app.add_handler(CommandHandler("clear", clear_terminal))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    app.run_polling()

if __name__ == "__main__":
    main()

Replace YOUR_BOT_TOKEN_HERE with your actual token and 123456789 with your Telegram user ID. Save and exit (Ctrl+X, then Y).

Run the Bot in Its Own Tmux Session

Don’t run the bot in the same session as Claude Code. Create a separate session:

tmux new -s telegram-bot
python3 ~/telegram_claude_bot.py

Detach with Ctrl+B, then D.

Now open Telegram on your phone, find your bot, and send /start. You should see the welcome message.


Connect Mobile to Claude Code

With both Tmux sessions running, the workflow looks like this:

  1. Open Telegram on your phone.
  2. Send a prompt to your bot: "Refactor the auth module in /app/src/auth.py to use JWT instead of sessions"
  3. The bot forwards it to the Claude session.
  4. Three seconds later, you get the current terminal output back.
  5. Use /status anytime to check what Claude is up to.

Tips for Working with Claude Over Telegram

Keep prompts self-contained. Since you can’t see Claude’s full context on mobile, write prompts that don’t depend on remembered context from earlier in the chat.

Use /status liberally. Claude Code can take a while on larger tasks. Poll the status every minute or two rather than waiting passively.

Plans first. Then code.

PROJECTYOUR APP
SCREENS12
DB TABLES6
BUILT BYREMY
1280 px · TYP.
yourapp.msagent.ai
A · UI · FRONT END

Remy writes the spec, manages the build, and ships the app.

Set up a Telegram channel for logs. Instead of (or in addition to) polling, you can configure the bot to push output to a private Telegram channel on a timer. This creates a passive log stream you can scroll through.

Be specific about file paths. Vague instructions like “fix the bug” don’t give Claude Code enough to work with. Always include the file path and a clear description of the problem.


Run Everything Automatically on Boot

If your VPS reboots (scheduled maintenance, unexpected crash), you want things to come back up without you manually SSH-ing in.

Create a Startup Script

nano ~/start_sessions.sh
#!/bin/bash
# Start Claude session
tmux new-session -d -s claude -x 220 -y 50
tmux send-keys -t claude "claude" Enter

# Start Telegram bot session
tmux new-session -d -s telegram-bot -x 220 -y 50
tmux send-keys -t telegram-bot "python3 /home/claude-user/telegram_claude_bot.py" Enter

Make it executable:

chmod +x ~/start_sessions.sh

Add to Crontab

crontab -e

Add this line:

@reboot /home/claude-user/start_sessions.sh

Now on every reboot, both sessions come back up automatically.


Troubleshooting Common Issues

”tmux: no server running”

This means Tmux isn’t running at all. Run ~/start_sessions.sh to start everything fresh, or manually create the sessions:

tmux new -s claude

Bot Responds But Nothing Happens in Claude

Check that the session name in your bot script matches the actual Tmux session name. Run tmux ls to see exactly what sessions exist.

Claude Code Exits Unexpectedly

Claude Code sometimes exits if it hits a rate limit or encounters an unexpected error. Add a simple loop to your startup script to restart it automatically:

tmux send-keys -t claude "while true; do claude; echo 'Claude exited, restarting in 5s...'; sleep 5; done" Enter

Telegram Messages Arriving Out of Order

The time.sleep(3) in the bot is a rough wait. For longer-running Claude tasks, increase this to 5–10 seconds or use /status manually instead of relying on the auto-capture.

VPS Running Out of Memory

Claude Code can be memory-hungry on large tasks. Monitor usage:

free -h
htop

If you’re consistently near the limit, upgrade to a 4GB RAM tier. On Hetzner, this is still under $10/month.


Extend the Setup with MindStudio

Once Claude Code is running 24/7 on your VPS, the natural next question is: what else can it do beyond coding?

This is where the MindStudio Agent Skills Plugin becomes useful. It’s an npm package (@mindstudio-ai/agent) that lets Claude Code call over 120 typed capabilities as simple method calls — things like agent.sendEmail(), agent.searchGoogle(), agent.generateImage(), and agent.runWorkflow().

Install it in any project directory on your VPS:

npm install @mindstudio-ai/agent

Then Claude Code can use these capabilities directly in scripts it writes and runs. Instead of wiring up API clients, authentication, and retry logic manually, Claude calls a single method and MindStudio handles the infrastructure layer.

For example, you could have Claude Code:

  • Pull a brief from a Google Doc, write code to satisfy it, then email the result — all in one unattended workflow
  • Search for recent documentation, incorporate changes into a codebase, and push a commit
  • Trigger downstream automation workflows you’ve already built in MindStudio

Remy is new. The platform isn't.

Remy
Product Manager Agent
THE PLATFORM
200+ models 1,000+ integrations Managed DB Auth Payments Deploy
BUILT BY MINDSTUDIO
Shipping agent infrastructure since 2021

Remy is the latest expression of years of platform work. Not a hastily wrapped LLM.

If you’d rather build the Telegram-to-AI interface without managing a VPS at all, MindStudio also lets you build webhook-triggered AI agents with no infrastructure setup. You can connect a Telegram webhook to a fully stateful agent in a few clicks. Either approach gets you to mobile-accessible AI — it just depends on how much control you want over the stack.

You can try MindStudio free at mindstudio.ai.


Frequently Asked Questions

How much does it cost to run Claude Code on a VPS?

The server itself runs $5–15/month depending on the provider and plan. Hetzner is the most cost-effective option for European data centers; DigitalOcean and Vultr are slightly pricier but have more global regions. Your biggest variable cost is the Anthropic API usage, which depends entirely on how many tokens you send and receive. Heavy daily usage can run $20–50/month in API costs; light use is much less.

Is it safe to run Claude Code via Telegram like this?

The main risk is someone other than you triggering the bot. The ALLOWED_USER_ID check in the bot script handles this — only messages from your Telegram account are processed. For extra security, set your bot to private in BotFather settings and don’t share the bot username publicly. You should also make sure your VPS has a firewall configured (UFW is straightforward on Ubuntu) and that you’re using SSH keys rather than passwords.

Can I run multiple Claude Code sessions at the same time?

Yes. Create multiple Tmux sessions with different names (claude-project1, claude-project2, etc.) and update the bot to accept a session selector as part of the command. The bot script can be extended with a /session command to switch between active sessions. Memory is the practical limit — each active Claude Code session uses roughly 200–500MB depending on context size.

What happens if Claude Code gets stuck or goes into an infinite loop?

Use the Telegram bot to send an interrupt: send the text q or exit to the session, which often stops a running task in Claude Code. If that doesn’t work, you can send C-c (as the literal key sequence via tmux: tmux send-keys -t claude C-c) to send a keyboard interrupt. As a last resort, kill and restart the session entirely via /clear and a restart command.

Does this work with other AI coding tools?

The Tmux-based architecture works with anything that runs in a terminal. Aider, Continue, and Cursor’s CLI mode can all be swapped in for Claude Code. The Telegram bot doesn’t care what’s running in the session — it just forwards text and captures output. You’d need to adjust prompting style for each tool, but the plumbing stays the same.

Do I need to keep SSH open for the sessions to stay alive?

No. That’s the whole point of Tmux. Once you detach from a session, it runs independently on the server. You can close your SSH connection entirely, shut your laptop, and the Claude session keeps running. When you want to check in, SSH back in and reattach with tmux attach -t claude.


Key Takeaways

  • Claude Code on a VPS with Tmux gives you persistent, always-on sessions that survive disconnects and reboots — something you can’t get from a local setup.
  • The Telegram bot acts as a lightweight mobile interface: send prompts, check status, and monitor output without needing a laptop or SSH client.
  • The full stack (VPS + Tmux + Claude Code + Telegram bot) takes about 45 minutes to set up and costs under $20/month in infrastructure.
  • Startup automation via cron ensures everything comes back after reboots without manual intervention.
  • The MindStudio Agent Skills Plugin extends what Claude Code can do once it’s running — giving it access to email, web search, image generation, and custom workflow triggers as native method calls.

Other agents ship a demo. Remy ships an app.

UI
React + Tailwind ✓ LIVE
API
REST · typed contracts ✓ LIVE
DATABASE
real SQL, not mocked ✓ LIVE
AUTH
roles · sessions · tokens ✓ LIVE
DEPLOY
git-backed, live URL ✓ LIVE

Real backend. Real database. Real auth. Real plumbing. Remy has it all.

If you want the power of an always-on AI coding agent without managing the infrastructure yourself, MindStudio lets you build and deploy AI agents visually — no VPS required.

Related Articles

How to Use the /goal and /loop Commands in Claude Code for Autonomous Long-Running Tasks

Combine /goal and /loop in Claude Code to create tasks that run on a schedule and won't stop until your end condition is met. Here's how to set it up.

Claude Automation Workflows

How to Build an AI Operating System Using the Four C's Framework

The Four C's—Context, Connections, Capabilities, and Cadence—are the building blocks of a personal AI OS. Learn how to implement each layer with Claude Code.

Claude Workflows Automation

How to Build an AI Second Brain with Claude Fable 5 and Claude Code

Learn how to build a personal AI operating system using Claude Fable 5, the Four C's framework, and Claude Code skills for maximum productivity.

Claude Workflows Automation

Claude Code Skills for Non-Technical Teams: How to Build, Name, and Structure Them

Learn how to build Claude Code skills that non-engineers can actually use—with the right name, description, and reference file structure.

Claude Workflows Automation

How to Build a Personal AI Operating System in Claude Code: Step-by-Step Setup Guide

Context, Connections, Capabilities, Cadence — the four-step framework for turning Claude Code into a personal AI OS that runs automations while you sleep.

Workflows Claude Automation

How to Bypass Browser Automation Blocks on LinkedIn and Instagram with Claude Computer Use

Social platforms block traditional automation, but Claude computer use mimics human interaction. Learn how to set it up and what to watch out for.

Claude Automation Workflows

Presented by MindStudio

No spam. Unsubscribe anytime.