Deploy a Private MCP Server on UpCloud

Deploy a Private MCP Server on UpCloud

/ #AI #Django


Run an MCP server on an UpCloud VPS, keep its HTTP endpoint off the public internet, and connect through an SSH tunnel. We will set up the Python service, restrict the SSH account, and test the tools from a local client.

An MCP server can give an AI assistant access to useful parts of your application, but it needs to keep running when you close your laptop. In this article, I am going to deploy a small Python MCP server on UpCloud and connect to it from a local client. The server will provide two tools for reading fictional operations notes, so we can concentrate on the deployment before connecting a real database.

The MCP endpoint will listen on the VPS loopback address. We will reach it through an SSH tunnel using a key that can forward traffic to that one port. SSH handles access to the tunnel and encryption between your computer and the VPS. There is no public MCP URL in this setup, and we do not need a domain name or a reverse proxy to get it working.

Decide what private means for this server

The connection runs from your local MCP client to 127.0.0.1:18000 on your computer. SSH forwards that traffic to 127.0.0.1:8000 on the UpCloud server. The server uses Streamable HTTP, the HTTP transport described in the official MCP Python SDK documentation. The application itself has no HTTP login in this example; access depends on SSH and the two machines being trusted.

Everyone who can reach the endpoint gets the same two tools and the same notes. Processes already running on the VPS can reach its loopback listener, and processes on your computer can use the local port while the tunnel is open. This is suitable for a trusted single-user computer and a server you control. It is not a way to separate customers, staff roles, or tenants inside an application.

The MCP client must run on the computer where you open the tunnel. A connector running in a cloud service cannot reach your laptop’s loopback address. Also, keeping the endpoint private does not keep tool results away from your AI provider: the host may send the returned text to its model. Choose the data you expose with that in mind.

Create the UpCloud server and restrict incoming connections

Create an Ubuntu 24.04 LTS Cloud Server in UpCloud and add your administrative SSH public key during setup. This example is a small Python service with two in-memory notes; it does not run a language model or need a GPU. A small instance with 1 GB of RAM is a starting point for the tutorial, with the size revisited when you add real tools and measure their resource use.

You can sign up through my UpCloud affiliate link. I may earn a commission if you sign up through it. UpCloud currently advertises a 14-day trial with $250 in free credits on its official affiliate page. Confirm the credit amount, eligibility, and expiry shown during signup before deploying; the credit is a trial allowance, not permanent free hosting.

The commands below assume a fresh VPS and an administrative root shell. Replace SERVER_IP with its public IPv4 address. If you use a separate sudo administrator, prefix the server administration commands with sudo. From your computer, connect with your administrative key:

ssh root@SERVER_IP

Install Python’s virtual environment support and the firewall tools on the server:

apt update
apt install -y python3-venv openssh-server ufw nano
python3 --version

Use UFW to allow SSH from your current public IPv4 address and deny other incoming connections. Replace YOUR_PUBLIC_IPV4 below with that address. Keep your existing SSH session open and test a second administrative connection after enabling the firewall, so you can fix a mistaken rule before disconnecting.

ufw default deny incoming
ufw default allow outgoing
ufw allow from YOUR_PUBLIC_IPV4 to any port 22 proto tcp
ufw enable
ufw status verbose

These commands follow Ubuntu’s UFW configuration approach. Keep IPV6=yes in /etc/default/ufw so the default deny policy also covers IPv6. This walkthrough connects using IPv4; if you want administrative IPv6 access, add a separate SSH rule for your trusted IPv6 source. When your public address changes, update the allow rule through an existing session or the provider console.

Do not add an incoming rule for port 8000. UpCloud also has a provider firewall, but its Public & Utility firewall is stateless, so a custom ruleset needs to account for reply traffic as well as incoming connections. Trial accounts have firewall restrictions. We will use UFW for the host policy here and leave the provider rules alone, while ensuring they permit SSH and the outbound package downloads needed for setup.

Create and upload the MCP application

On your computer, create a directory called private-mcp. Inside it, create requirements.txt with the official SDK version used in this article:

mcp==2.3.0

Create server.py in the same directory. The first tool lists the notes, and the second reads one by its slug. A slug is looked up in a fixed dictionary; it is never turned into a filesystem path or a shell command.

from typing import Annotated, Any

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations
from pydantic import Field

mcp = MCPServer("Private operations notes")

# Fictional notes. No secrets or executable commands are exposed by these tools.
RUNBOOKS = {
    "failed-deployment": {
        "title": "Investigating a failed deployment",
        "body": "Check the service status and recent application logs. Compare the deployed revision with the last known working release before deciding whether to roll back.",
    },
    "slow-requests": {
        "title": "Investigating slow requests",
        "body": "Check request duration, database query count, and worker saturation. Compare a slow request with a normal request before changing worker limits.",
    },
}


@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
def list_runbooks() -> dict[str, Any]:
    """List the available internal operations notes."""
    return {"runbooks": [
        {"slug": slug, "title": note["title"]}
        for slug, note in RUNBOOKS.items()
    ]}


@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
def read_runbook(slug: Annotated[str, Field(min_length=1, max_length=80)]) -> dict[str, Any]:
    """Read one named operations note. Returns text; never runs commands."""
    if slug not in RUNBOOKS:
        raise ToolError("Runbook not found.")
    return {"slug": slug, **RUNBOOKS[slug]}


if __name__ == "__main__":
    mcp.run(
        transport="streamable-http",
        host="127.0.0.1",
        port=8000,
        stateless_http=True,
        json_response=True,
        transport_security=TransportSecuritySettings(
            enable_dns_rebinding_protection=True,
            allowed_hosts=["127.0.0.1:8000", "127.0.0.1:18000"],
            allowed_origins=[],
        ),
    )

The binding to 127.0.0.1 is what keeps the listener off the public network interface. The host allowlist accepts the server’s own address and the local tunnel address that the client will use. SSH forwards the HTTP request without rewriting its Host header, which is why port 18000 appears there too. We keep DNS-rebinding protection enabled and reject requests carrying an Origin header by leaving the allowed-origin list empty. The native client used below sends no browser Origin.

The tools return short dictionaries, so JSON responses and stateless HTTP are enough for this example. We do not need persistent MCP sessions, progress events, or callbacks into the client. The read-only hints describe the tools to a host; the implementation is what actually keeps them read-only. Neither tool runs the instructions in a note.

Back in the administrative shell on the VPS, create an account for the application and its installation directory:

useradd --system --user-group --home-dir /opt/private-mcp --shell /usr/sbin/nologin mcpapp
install -d -o root -g root -m 755 /opt/private-mcp

From your computer, while inside the local private-mcp directory, upload the two files using your administrative SSH connection:

scp server.py requirements.txt root@SERVER_IP:/opt/private-mcp/

Then install the dependencies on the VPS. The application files and virtual environment stay owned by root, while the service will run as mcpapp. That account needs to read the code, but it does not need permission to rewrite it.

python3 -m venv /opt/private-mcp/.venv
/opt/private-mcp/.venv/bin/python -m pip install -r /opt/private-mcp/requirements.txt
chmod 644 /opt/private-mcp/server.py /opt/private-mcp/requirements.txt

Keep the process running with systemd

Create /etc/systemd/system/private-mcp.service on the VPS with the following contents. The absolute Python path means systemd does not depend on a shell activating the virtual environment first.

[Unit]
Description=Private MCP operations notes
After=network.target

[Service]
Type=simple
User=mcpapp
Group=mcpapp
WorkingDirectory=/opt/private-mcp
ExecStart=/opt/private-mcp/.venv/bin/python /opt/private-mcp/server.py
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONDONTWRITEBYTECODE=1
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
UMask=0077

[Install]
WantedBy=multi-user.target

The service starts under its own Unix account and restarts after a failure. The filesystem restrictions make the normal filesystem read-only inside the service and hide home directories. This works for our in-memory notes; if you add a database file, uploads, or generated reports, give the service a specific writable data directory instead of removing all of the restrictions. The options are documented in systemd’s execution settings.

systemd-analyze verify /etc/systemd/system/private-mcp.service
systemctl daemon-reload
systemctl enable --now private-mcp
systemctl status private-mcp --no-pager
ss -lntp 'sport = :8000'

The listener should be 127.0.0.1:8000. If it shows 0.0.0.0:8000 or an unrestricted IPv6 listener, stop and check the Python startup configuration. You can inspect startup errors with journalctl -u private-mcp -n 50 --no-pager. A failed import or a port already in use should be fixed here before setting up the tunnel.

Create an SSH account that can only open this tunnel

Use a separate SSH key for MCP access, rather than giving your assistant workflow the administrative key. On your computer, generate one and choose a passphrase when prompted. If this filename already exists, choose a new filename instead of overwriting it.

ssh-keygen -t ed25519 -f ~/.ssh/upcloud_mcp -C private-mcp
scp ~/.ssh/upcloud_mcp.pub root@SERVER_IP:/tmp/upcloud_mcp.pub

On the server, create the tunnel account and install its public key. The private key stays on your computer.

adduser --disabled-password --gecos "" mcptunnel
install -d -o mcptunnel -g mcptunnel -m 700 /home/mcptunnel/.ssh
install -o mcptunnel -g mcptunnel -m 600 /tmp/upcloud_mcp.pub /home/mcptunnel/.ssh/authorized_keys
rm /tmp/upcloud_mcp.pub

Create /etc/ssh/sshd_config.d/10-mcp-tunnel.conf with these rules:

Match User mcptunnel
    AuthenticationMethods publickey
    PasswordAuthentication no
    KbdInteractiveAuthentication no
    AllowTcpForwarding local
    PermitOpen 127.0.0.1:8000
    AllowStreamLocalForwarding no
    AllowAgentForwarding no
    X11Forwarding no
    PermitTTY no
    MaxSessions 0
Match all

The account authenticates with a public key and can forward TCP traffic only to 127.0.0.1:8000. MaxSessions 0 prevents shell and subsystem sessions while leaving forwarding available. Unix-socket forwarding is disabled too. These settings are described in the OpenSSH server manual; the final Match all ends the account-specific block.

Ubuntu loads configuration snippets from this directory, but existing global settings or earlier matching rules can affect the result. Check syntax and inspect the effective settings for this account before reloading SSH. Keep your administrative session open during the change, as described in Ubuntu’s OpenSSH guide.

sshd -t
sshd -T -C user=mcptunnel,host=localhost,addr=YOUR_PUBLIC_IPV4
systemctl reload ssh

In the effective output, check for authenticationmethods publickey, allowtcpforwarding local, permitopen 127.0.0.1:8000, and maxsessions 0. This account is for transporting MCP requests. Keep using the administrative account to upload code and manage the service.

Open the tunnel and call a tool

On your computer, open the tunnel in a terminal and leave it running. Verify the server’s SSH host-key fingerprint against a trusted source, such as the server console, when connecting for the first time. Do not disable host-key checking to make the connection succeed.

ssh -N \
  -i ~/.ssh/upcloud_mcp \
  -o IdentitiesOnly=yes \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 \
  -o ServerAliveCountMax=3 \
  -L 127.0.0.1:18000:127.0.0.1:8000 \
  mcptunnel@SERVER_IP

The first address is the listener on your computer; the second is the destination as seen from the VPS. Both are bound to loopback. -N requests no remote command, which is necessary for our restricted account. The keepalive options make a broken connection exit after missed responses, but they do not reconnect automatically. ExitOnForwardFailure catches failure to create the local listener; the tool call below checks whether the remote application is actually reachable.

In another local terminal, enter the private-mcp directory and prepare a client environment using Python 3.12 or newer:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt

Save this as check_mcp.py. It discovers the tools and reads one note through the forwarded HTTP connection, without involving a language model.

import asyncio
import json
import os

from mcp import Client


async def main():
    url = os.environ.get("MCP_URL", "http://127.0.0.1:18000/mcp")
    async with Client(url) as client:
        tools = await client.list_tools()
        print([tool.name for tool in tools.tools])
        result = await client.call_tool("read_runbook", {"slug": "failed-deployment"})
        if result.is_error:
            raise RuntimeError(result.content)
        print(json.dumps(result.structured_content, indent=2))


if __name__ == "__main__":
    asyncio.run(main())
python check_mcp.py

You should see list_runbooks and read_runbook, followed by the failed-deployment note. Closing the SSH tunnel should make a new client connection fail while the Python service continues running on the VPS. Opening the endpoint in a browser is not an equivalent test: a normal page request does not perform the MCP initialization and tool-call exchange.

For a locally running Claude Code installation, register the same endpoint from your project directory using the command format in its MCP documentation:

claude mcp add --transport http --scope local private-ops http://127.0.0.1:18000/mcp

Keep the tunnel open, start Claude Code, and check the server with /mcp. You can ask it to read the failed-deployment note and summarize the checks. The tools only return text, although the host may have other tools capable of taking actions. Review those permissions separately before connecting notes that contain operational instructions.

Check the restrictions and maintain the service

From your computer, a direct connection to the VPS application port must fail. A shell command through the tunnel account must fail too. Run these checks using the same server address:

curl --connect-timeout 5 http://SERVER_IP:8000/mcp
ssh -i ~/.ssh/upcloud_mcp -o IdentitiesOnly=yes mcptunnel@SERVER_IP true
ssh -i ~/.ssh/upcloud_mcp -o IdentitiesOnly=yes -W 127.0.0.1:22 mcptunnel@SERVER_IP

The last command tries forwarding to SSH itself instead of the allowed MCP destination. It should be rejected as administratively prohibited. Successful SSH authentication alone is not enough to prove the account restrictions work; these denied operations are part of the check. Repeat the direct-port check for a public IPv6 address if the VPS has one.

When changing only the Python source, upload the new file to a staging path, compile it, and replace the installed file before restarting the service. Keep a copy of the previous version so a bad change can be reversed. From your computer:

scp server.py root@SERVER_IP:/tmp/private-mcp-server.py

Then, on the VPS:

/opt/private-mcp/.venv/bin/python -m py_compile /tmp/private-mcp-server.py
cp /opt/private-mcp/server.py /opt/private-mcp/server.py.previous
install -o root -g root -m 644 /tmp/private-mcp-server.py /opt/private-mcp/server.py
systemctl restart private-mcp
systemctl status private-mcp --no-pager
journalctl -u private-mcp -n 50 --no-pager

Rerun the local client through the tunnel after restarting. Compilation only catches syntax errors; the client verifies that the process starts, tools are discoverable, and a call works. For a rollback, restore server.py.previous and restart again. This small procedure covers source changes; dependency changes need a tested environment and a rollback of those dependencies as well.

After completing setup, reboot the VPS and verify that the systemd service comes back, then reconnect the tunnel and repeat the client check. Keep the Ubuntu packages and Python dependencies updated through tested changes. If you later add persistent data, back it up and check a restore; our current example has only the two notes stored in the source file.

To revoke this tunnel access, remove the relevant public key from the account’s authorized_keys file. That prevents new connections but does not close an existing one. For this dedicated account, pkill -u mcptunnel from the administrative shell also terminates its active processes and tunnels. Use separate accounts or an identity-aware service when people need different access or individual audit records.

When you need a shared MCP service

The tunnel setup gives one trusted client environment a private route to a small server. If you need centrally managed users and multiple servers, Obot is worth looking at. Its MCP Gateway provides authentication, access policies, audit logs, and a catalog for discovering servers. That is a separate deployment step: a remote gateway cannot reach this VPS loopback listener unless you deliberately provide a network route or run the gateway alongside it.

For a shared HTTP endpoint, add verified caller identity and application-level permissions before exposing real customer records. The MCP SDK authorization guide describes HTTP token verification. A gateway policy can control access to a server, but Django still needs to decide which workspaces and records that caller may read. Keep those checks in the application when adapting a Django MCP server to this deployment.

At this point, systemd manages the application process on the VPS, SSH controls the remote route to it, and the local client can discover and call both tools. The next useful change is to replace one fictional note with a specific read operation from your own application, keeping its result small and checking the caller’s permissions wherever the data requires it.

Comments

No comments yet...

Add comment

Please log in to comment.

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.