install-n8n-mcp.sh
#!/bin/bash

# ----------- Validate inputs -----------
if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: $0 your.domain.com port"
  exit 1
fi

DOMAIN="$1"
PORT="$2"
MCP_DIR="/root/n8n-mcp"
NODE_BIN="$(which node)"
NPM_BIN="$(which npm)"
AUTH_TOKEN=$(openssl rand -base64 32)

echo "Installing MCP for $DOMAIN on port $PORT..."

# ----------- Install dependencies -----------
apt update

if ! command -v nginx >/dev/null 2>&1; then
  apt install -y nginx
fi

if ! command -v certbot >/dev/null 2>&1; then
  apt install -y certbot python3-certbot-nginx
fi

apt install -y git curl

# ----------- Install Node.js via NVM if missing -----------
if [ -z "$NODE_BIN" ]; then
  curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  export NVM_DIR="$HOME/.nvm"
  source "$NVM_DIR/nvm.sh"
  nvm install 20
  NODE_BIN="$(which node)"
  NPM_BIN="$(which npm)"
fi

# ----------- Clone and build n8n-mcp -----------
rm -rf "$MCP_DIR"
git clone https://github.com/czlonkowski/n8n-mcp.git "$MCP_DIR"
cd "$MCP_DIR"
$NPM_BIN install
$NPM_BIN run build
$NPM_BIN run rebuild

# ----------- Create startup script -----------
cat <<EOF > "$MCP_DIR/start.sh"
#!/bin/bash
export MCP_MODE=http
export USE_FIXED_HTTP=true
export PORT=$PORT
export AUTH_TOKEN="$AUTH_TOKEN"
export BASE_URL="https://$DOMAIN"
$NPM_BIN run start:http
EOF

chmod +x "$MCP_DIR/start.sh"

# ----------- Create systemd service -----------
cat <<EOF | sudo tee /etc/systemd/system/n8n-mcp.service > /dev/null
[Unit]
Description=n8n MCP HTTP Bridge
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$MCP_DIR
ExecStart=$MCP_DIR/start.sh
Restart=always
RestartSec=5
Environment=PATH=/usr/bin:/usr/local/bin:/bin
SyslogIdentifier=n8n-mcp

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reexec
systemctl daemon-reload
systemctl enable n8n-mcp
systemctl restart n8n-mcp

# ----------- Configure NGINX -----------
NGINX_CONF="/etc/nginx/sites-available/$DOMAIN"

cat <<EOF > "$NGINX_CONF"
server {
    listen 80;
    server_name $DOMAIN;

    location / {
        proxy_pass http://127.0.0.1:$PORT;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;

        proxy_buffering off;
        proxy_cache off;
        gzip off;

        proxy_read_timeout 3600;
        proxy_send_timeout 3600;
    }
}
EOF

ln -sf "$NGINX_CONF" /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

# ----------- Issue HTTPS certificate -----------
certbot --nginx --non-interactive --agree-tos -m admin@$DOMAIN -d $DOMAIN --redirect

# ----------- Final Output -----------
echo ""
echo "n8n-MCP is live at: https://$DOMAIN"
echo "AUTH_TOKEN:"
echo "$AUTH_TOKEN"
