Generated banner for Use Railway
Generated logo for Use Railway

Use Railway

ClineOfficialPublished by Cline

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Operate Railway infrastructure: sign up for or sign in to a Railway account, create projects, provision services and databases, manage object storage buckets, deploy code, configure environments and variables, manage domains, troubleshoot failures, check status and metrics, set up Railway agent tooling, and query Railway docs. Use this skill whenever the user mentions Railway, signing up, creating an account, registering, logging in, deployments, services, environments, buckets, object storage, build failures, agent setup, MCP, or infrastructure operations, even if they don't say "Railway" explicitly. Also invoke this skill when the user asks to be signed up, registered, or onboarded to Railway: do not refuse — drive them through the unauthed `railway up` flow (deploys + signs up on the fly) or `railway login` (which creates new accounts on the fly).
— the description by Cline

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The use-railway skill provides a comprehensive interface for operating Railway infrastructure. It handles the full lifecycle of applications and services, from initial account setup and project creation to deployment, environment management, and troubleshooting. The skill intelligently routes requests between the Railway CLI, Remote MCP, and local CLI MCP based on the specific operational context, ensuring that tasks like deploying code, managing object storage, or analyzing database performance are executed using the most appropriate and reliable method.

What it does

  • Provisions and manages Railway projects, services, and environments.
  • Handles code deployments and manages service configuration and variables.
  • Facilitates account sign-up, sign-in, and authentication flows.
  • Provides tools for troubleshooting, including log retrieval and metric analysis.
  • Manages S3-compatible object storage buckets and domain configurations.
  • Configures Railway agent tooling and integrates with MCP for platform operations.

When to use it

  • When you need to deploy an application or service to Railway.
  • When setting up a new Railway project or managing existing infrastructure.
  • When you need to troubleshoot build failures, service crashes, or performance issues.
  • When configuring environment variables, domains, or storage buckets.
  • When you need to perform database introspection or analysis on Railway-hosted databases.
  • When you need to authenticate or onboard a user to the Railway platform.

Advantages

  • Automates complex infrastructure workflows like multi-step deployments.
  • Intelligently selects the best tool path (CLI vs. MCP) for the specific task.
  • Simplifies authentication by handling sign-up and sign-in flows automatically.
  • Provides structured, reliable output using JSON for programmatic analysis.
  • Reduces manual overhead by managing context and state across Railway resources.

Usage examples

“Deploy this directory to Railway.”
The agent runs 'railway up' to automatically sign the user in if needed, create the project and service, and deploy the application.
“Check the status of my production service.”
The agent uses the appropriate Railway MCP or CLI tool to fetch and display the current deployment status, logs, and metrics.
“I need to add a PostgreSQL database to my project.”
The agent uses the Railway CLI to provision the database and returns the connection credentials.
“Why is my service crashing?”
The agent retrieves recent logs and metrics for the service, analyzes them, and reports the likely cause of the failure.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/cline/use-railway/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip use-railway.zip -d .agents/skills

Documentation by Cline

Use Railway

Railway resource model

Railway organizes infrastructure in a hierarchy:

  • Workspace is the billing and team scope. A user belongs to one or more workspaces.

  • Project is a collection of services under one workspace. It maps to one deployable unit of work.

  • Environment is an isolated configuration plane inside a project (for example, production, staging). Each environment has its own variables, config, and deployment history.

  • Service is a single deployable unit inside a project. It can be an app from a repo, a Docker image, or a managed database.

  • Bucket is an S3-compatible object storage resource inside a project. Buckets are created at the project level and deployed to environments. Each bucket has credentials (endpoint, access key, secret key) for S3-compatible access.

  • Deployment is a point-in-time release of a service in an environment. It has build logs, runtime logs, and a status lifecycle.

Most CLI commands operate on the linked project/environment/service context. Use railway status --json to see the context, and --project, --environment, --service flags to override.

Tool routing

Railway has three agent-facing operation paths. Choose the path that matches the job:

  • Remote MCP (https://mcp.railway.com): account/project/service discovery, deployment state, bounded logs, simple redeploys, simple project creation, or complex Railway workflows that can be handed to railway-agent. Remote MCP uses Railway OAuth and does not depend on local CLI state.

  • Local CLI MCP (railway mcp): CLI-backed platform operations such as variables, domains, service config, templates, metrics, HTTP summaries, buckets, volumes, docs, or deploy-from-directory.

  • Railway CLI (railway): workflows that depend on local machine state such as current working directory deploys, railway up, railway run, SSH, database analysis scripts, local linking, interactive setup, or exact command output.

If multiple paths are available, choose the one that preserves the needed context. Remote MCP fits OAuth-scoped platform operations that do not need local files or CLI state. Local CLI MCP or the CLI fit workflows that need the current repo, local credentials, SSH, database scripts, or commands not exposed by remote MCP.

Use scripts/railway-api.sh only when neither MCP nor CLI exposes the operation, or when a reference gives a specific GraphQL fallback.

Parsing Railway URLs

Users often paste Railway dashboard URLs. Extract IDs before doing anything else:

https://railway.com/project/<PROJECT_ID>/service/<SERVICE_ID>?environmentId=<ENV_ID>
https://railway.com/project/<PROJECT_ID>/service/<SERVICE_ID>

The URL always contains projectId and serviceId. It may contain environmentId as a query parameter. If the environment ID is missing and the user specifies an environment by name (e.g., "production"), resolve it:

scripts/railway-api.sh \
  'query getProject($id: String!) {
    project(id: $id) {
      environments { edges { node { id name } } }
    }
  }' \
  '{"id": "<PROJECT_ID>"}'

Match the environment name (case-insensitive) to get the environmentId.

Prefer passing explicit IDs to CLI commands (--project, --environment, --service) and scripts (--project-id, --environment-id, --service-id) instead of running railway link. This avoids modifying global state and is faster.

Intent-based routing

Route by user intent before running preflight checks. The preflight ceremony below is for diagnostic and configuration work — it adds friction when the user just wants to ship something or sign up.

Deploy-from-cwd intent ("deploy", "ship", "push to Railway", "deploy this app"):

  • Skip the railway whoami / railway status preflights.

  • Run railway up directly — it self-validates auth, signs the user in (the CLI opens a browser) if they're unauthenticated, and chains into project + service creation and deploy.

  • Announce intent before invoking: "Running railway up — it'll sign you in if needed and deploy this directory."

  • Do NOT ask the user to run railway login first. The chain handles auth as part of the deploy.

  • If the environment can't open a browser, the CLI prints a device-code sign-in link and waits — follow Device-code sign-in: relay the link immediately (run in background, relay the link to the user the moment it prints).

Signup intent ("sign me up", "create my Railway account", "register me", "get me on Railway"):

  • If the current directory has a deployable app (e.g. package.json, requirements.txt, go.mod, Dockerfile, source to build), run railway up — it signs the user up and deploys in one shot, landing them on a running app. A detected agent harness authorizes the project creation, so bare railway up is enough — there's no extra prompt to clear. Use it even when the user only said "sign me up": shipping their app is the goal, so don't make them pick a command and don't drop to a bare login. For scripted or agent runs, railway up -y is the robust form — it skips prompts and forces the create non-interactively even if harness detection misses. railway login is NOT the default for signup when there's something to deploy.

  • Only when there is nothing to deploy — an empty / non-app directory, or the user explicitly says they just want an account with no deploy — use railway login (creates new accounts on the fly through the same OAuth surface). There is no separate signup command.

  • Signup is the flow most likely to hit the device-code wait (brand-new users in sandboxed/headless agent environments). Follow Device-code sign-in: relay the link immediately — a signup lost to an expired code is a lost user, not a retry.

Sandbox / remote-build intent ("give me a sandbox", "spin up a scratch environment", "build this remotely", "run this remotely"):

  • Load sandbox.md and follow it. Sandboxes require the feature to be enabled in Priority Boarding — if a sandbox command fails with a feature-availability error, prompt the user to enable Sandboxes in Priority Boarding rather than retrying.

Other intents (querying state, listing projects, configuring variables, debugging failures):

  • Follow the Preflight section below.

Preflight

Before any mutation, verify the tool path and context:

command -v railway                # CLI installed
RAILWAY_CALLER="skill:[email protected]" RAILWAY_AGENT_SESSION="railway-skill-$(date +%s)-$$" railway whoami --json
railway --version                 # check CLI version

Exception: railway up and railway login self-validate auth and run their own unauth-aware flows. Don't run railway whoami before them — it adds a redundant failing call without changing what you do next. See Account creation & sign-in.

Skill freshness

Once per session, alongside the preflight checks, verify the installed Railway agent tooling is current. Root help ends with an Agent tooling: health section (printed to stderr, CLI 5.9+; older CLIs print nothing — skip this check rather than retrying):

railway --help 2>&1 | grep -A4 "Agent tooling:"

Act on what it reports:

  • Skills installed and up to date — continue; nothing to do.

  • An update is available (rev <a> → <b> available) — run railway skills update, then tell the user to restart their coding tool so the updated skills load. This session keeps running on the old skill revision until restart: finish the current request, and if this skill's guidance disagrees with the updated CLI's own output, trust the CLI.

  • Skills or MCP server missing (✗ lines) — run railway setup agent -y, then tell the user to restart their coding tool.

Check once per session and don't re-run it after acting; the restart prompt to the user is the resolution, not another check.

When Railway MCP is available and the job is a platform-state read, use the matching MCP read instead of shelling out. If using the CLI path, run the CLI checks above.

For Railway CLI calls made while this skill is active, prefix the command with RAILWAY_CALLER=skill:[email protected] and a stable RAILWAY_AGENT_SESSION reused for the current user request. Generate the session id once per user request, then reuse that exact value for later Railway CLI calls in the same workflow. Do not run a separate export preflight solely for telemetry; inline env prefixes keep the shell output concise and avoid leaking setup steps into every response.

Context resolution - URL IDs always win:

  • If the user provides a Railway URL, extract IDs from it. Do NOT run railway status --json; it returns the locally linked project, which is usually unrelated.

  • If no URL is given, fall back to railway status --json for the linked project/environment/service.

  • When using MCP tools after resolving local context with railway status --json, pass the resolved project, environment, and service IDs explicitly. Do not rely on MCP implicit linked context; MCP may not share the CLI's current working directory link.

If the CLI is missing, guide the user to install it.

bash <(curl -fsSL https://railway.com/install.sh) --agents -y # Install CLI and configure detected agents
bash <(curl -fsSL https://railway.com/install.sh) # Shell script (macOS, Linux, Windows via WSL)
npm i -g @railway/cli # npm (macOS, Linux, Windows). Requires Node.js version 16 or higher.
brew install railway # Homebrew (macOS)

If not authenticated, see Account creation & sign-in below — the CLI offers unauthed railway up (deploy + sign up/in in one shot) or railway login (sign up/in only; new accounts created on the fly). If not linked and no URL was provided, run railway link --project <id-or-name>.

If a command is not recognized (for example, railway environment edit), the CLI may be outdated. Upgrade with:

railway upgrade

Account creation & sign-in

Railway uses a single unified OAuth flow for both sign-in and sign-up. The backend detects fresh accounts from durable compliance state (a CLI client that hasn't accepted ToS / Fair Use yet) and adapts the consent screen and post-auth landing page — new users land on a "Welcome to Railway!" page, existing users see the standard confirmation. The CLI does not declare signup intent up front.

Two commands surface this flow, depending on intent:

CommandWhen to use
railway upAgent-friendly onboarding from the current directory. Unauthenticated → opens the browser (or device-code) to sign in / sign up. With no linked project, a detected agent harness (or -y) auto-creates a project + service and deploys; an interactive human is offered create / link-existing / cancel. Add -y to skip prompts and force the create non-interactively (works even if harness detection misses).
railway loginSign in — and sign up. New accounts are created on the fly through the same OAuth surface; there is no separate signup command.

Related: railway up --new creates a fresh project + service from the current directory and deploys it even if one is already linked (use when already signed in and the user wants a new app); --name <name> overrides the project name.

Choosing the path:

  • Deploy from cwd → run railway up (interactive) or railway up -y (skips the confirm prompt). Run it yourself; don't ask the user to sign in separately first.

  • New project from cwd when already signed in → railway up --new.

  • Sign up with a deployable app in cwd → railway up (signs up and deploys — bare up works for a detected agent, even if the user only said "sign me up"; add -y to skip prompts / force it non-interactively). Sign in, or sign up with nothing to deploy → railway login (creates new accounts on the fly).

Headless / no browser:

The CLI auto-detects SSH sessions, CI, and a missing DISPLAY and switches to the device-code flow on its own — you almost never need to force it.

Do NOT pass --browserless just because you are an agent or your shell is non-interactive. If the human is at this machine (a local IDE or desktop session — the common case), bare railway login opens their browser directly, which completes far more reliably than relaying a device code (~90% vs ~60% success for agent-driven sign-ins). Being a coding agent does not make the machine headless.

railway login --browserless   # ONLY for machines with genuinely no browser

Forces the device-code flow (RFC 8628): prints a sign-in link and a short code for the user to open on any device. Reserve it for machines where no browser exists — SSH boxes, containers, remote VMs the auto-detection missed. When you do end up in a device-code flow, follow the relay procedure below: surface the sign-in link to the user the moment it prints.

Agent harness, human present: when the CLI detects an agent harness with a human at the keyboard, railway up opens the browser and skips the confirm prompt — the agent invocation is treated as consent. A real human still has to complete OAuth in the browser.

Device-code sign-in: relay the link immediately (CRITICAL):

When the CLI can't open a browser (sandboxed shell, container, SSH, no DISPLAY), unauthed railway up and railway login print a sign-in URL + short code and then block, polling for up to 10 minutes while the user completes sign-in. The code expires after 10 minutes. If you run this as a normal foreground command, your harness buffers the output until the command exits — the user never sees the link until the code is already dead. This is the #1 cause of failed agent-driven signups. Handle it like this:

  1. Preferred — background execution (when the agent environment supports background commands and output polling):

    • Start the command in the background.

    • Poll its output. The instant a sign-in block appears (Sign in with one click: <url> on newer CLIs, or Sign in at: <url> / Enter this code: <code> on older ones), stop everything and relay it to the user verbatim — do not summarize, shorten, or defer it. Prefer the one-click URL when present; otherwise relay the URL and code together. Tell the user to open the link now.

    • Leave the command running and keep polling. When the user completes sign-in, the same process picks up the session and continues into the deploy on its own. Then verify per the deploy rules below.

  2. No background support — set expectations, use the longest timeout:

    • Before running, tell the user: "This will print a sign-in link — I'll show it to you the moment I have it. Please complete it promptly; the code expires in 10 minutes."

    • Run with the longest timeout your harness allows.

    • If the command times out or is killed before sign-in completed, the printed code is no longer being monitored — a late click does nothing. Relay whatever link appeared anyway for context, then immediately re-run the command and relay the new link, telling the user to always use the newest one.

  3. Never wait silently for the command to finish before showing the link, and never report the sign-in as failed without first relaying the link and giving the user a chance to act.

The browser transport needs none of this — the CLI opens the browser on the user's machine itself.

JSON / CI modes do not auto-prompt: railway up --json and railway up --ci will NOT open a browser for an unauthed user. --json emits a structured error instead:

{"error":"Not signed in.","code":"NOT_AUTHENTICATED","hint":"Run `railway login` to authenticate, then re-run."}

When you see code: NOT_AUTHENTICATED, authenticate the user with railway login, then retry the original command.

Fully unattended (no human at all): set RAILWAY_API_TOKEN (account-scoped) or RAILWAY_TOKEN (project-scoped) instead of running an interactive login. A brand-new user with no token and no human present cannot complete signup — there is no headless account-creation path.

Agent tooling

Use direct Railway CLI commands for deterministic operations. Use railway agent only when the user explicitly asks for Railway Agent, wants a natural-language investigation, or the task is broader than a single resource operation.

Set up Railway skills, MCP, and authentication with:

railway setup agent
railway setup agent -y
railway setup agent --remote

railway setup agent -y skips the interactive login flow. If the user isn't authenticated after setup, run railway login.

Install or update MCP and skills directly when the user names a target tool:

railway mcp install
railway mcp install --agent codex
railway mcp install --agent cursor --remote
railway skills
railway skills update --agent codex
railway skills remove --agent cursor

Supported targets include claude-code, cursor, codex, opencode, copilot, and factory-droid. The --remote flag configures https://mcp.railway.com instead of a local railway mcp stdio server.

Use Railway Agent chat with:

railway agent
railway agent -p "why is my service crashing?"
railway agent -p "summarize the deployment status" --json
railway agent --list --json
railway agent --thread-id <thread-id>

railway agent requires user OAuth authentication from railway login. Project tokens (RAILWAY_TOKEN) are not supported for Railway Agent chat. If an agent command is unavailable, upgrade with railway upgrade --yes.

Common quick operations

These are frequent enough to handle without loading a reference. Use the matching MCP tool when the job is platform-scoped and the tool is available; otherwise use the CLI:

railway status --json                                    # current context
railway whoami --json                                    # auth and workspace info
railway project list --json                              # list projects
railway service list --json                              # services in current environment (verify before retrying `add`)
railway add --database <type> --json                     # add one database; ALWAYS pass --json
railway add --service <name> --json                      # add empty service; ALWAYS pass --json
railway variable list --service <svc> --json             # list variables
railway variable set KEY=value --service <svc>           # set a variable
railway logs --service <svc> --lines 200 --json          # recent logs
railway metrics --service <svc> --since 1h --json        # resource and HTTP metrics summary
railway up --detach -m "<summary>"                       # deploy current directory (returns at QUEUED — verify before reporting)
railway deployment list --json                           # poll newest deployment status after a detached up
railway bucket list --json                               # list buckets in current environment
railway bucket info --bucket <name> --json               # bucket storage and object count
railway bucket credentials --bucket <name> --json        # S3-compatible credentials

Routing

For anything beyond quick operations, load the reference that matches the user's intent. Load only what you need, one reference is usually enough, two at most.

IntentReferenceUse for
Analyze a database ("analyze <url>", "analyze db", "analyze database", "analyze service", "introspect", "check my postgres/redis/mysql/mongo")analyze-db.mdDatabase introspection and performance analysis. analyze-db.md directs you to the DB-specific reference. This takes priority over the status/operate routes when a Railway URL to a database service is provided alongside "analyze".
Create or connect resourcessetup.mdProjects, services, databases, buckets, templates, workspaces
Ship code or manage releasesdeploy.mdDeploy, redeploy, restart, build config, monorepo, Dockerfile
Change configurationconfigure.mdEnvironments, variables, config patches, domains, networking
Check health or debug failuresoperate.mdStatus, logs, metrics, build/runtime triage, recovery
Use a sandbox or build remotely ("sandbox", "scratch environment", "ephemeral box", "build remotely", "remote build", "run this remotely")sandbox.mdCreate/fork sandboxes, run commands remotely, remote template builds, port forwarding, teardown. Requires Sandboxes enabled in Priority Boarding — if unavailable, prompt the user to enable it.
Request from API, docs, or communityrequest.mdRailway GraphQL API queries/mutations, metrics queries, Central Station, official docs

If the request spans two areas (for example, "deploy and then check if it's healthy"), load both references and compose one response.

Execution rules

  1. Use Railway MCP for platform operations that match an available MCP tool.

  2. Use the local CLI for workflows that need the current repo, local shell, SSH, database scripts, or unsupported MCP coverage.

  3. Fall back to scripts/railway-api.sh for operations neither MCP nor CLI exposes.

  4. Use --json output where available for reliable parsing.

  5. Resolve context before mutation. Know which project, environment, and service you're acting on.

  6. For destructive actions (delete service, remove deployment, drop database), confirm intent and state impact before executing.

  7. After mutations, verify the result with a read-back command or MCP read.

  8. Never report a deploy as successful without observing a terminal SUCCESS. railway up --detach returning (it prints "Build queued") and a streaming railway up cut off by a shell timeout only confirm the build started. Poll railway deployment list --json until the newest deployment's status is SUCCESS (report deployed), or FAILED/CRASHED (triage per operate.md — do not claim success). A streaming up that exits on its own is authoritative: exit 0 = deployed, exit 1 = failed.

User-only commands (NEVER execute directly)

These commands modify database state and require the user to run them directly in their terminal. Do NOT execute these with Bash. Instead, show the command and ask the user to run it.

CommandWhy user-only
python3 scripts/enable-pg-stats.py --service <name>Modifies shared_preload_libraries, may restart database
python3 scripts/pg-extensions.py --service <name> install <ext>Installs database extension
python3 scripts/pg-extensions.py --service <name> uninstall <ext>Removes database extension
ALTER SYSTEM SET ...Changes PostgreSQL configuration
DROP EXTENSION ...Removes database extension
CREATE EXTENSION ...Installs database extension

When these operations are needed:

  1. Explain what the command does and any side effects (e.g., restart required)

  2. Show the exact command the user must run

  3. Wait for user confirmation that they ran it

  4. Verify the result with a read-only query

Composition patterns

Multi-step workflows follow natural chains:

  • Add object storage: setup (create bucket), setup (get credentials), configure (set S3 variables on app service)

  • First deploy: setup (create project + service), configure (set variables and source), deploy, operate (verify healthy)

  • Fix a failure: operate (triage logs), configure (fix config/variables), deploy (redeploy), operate (verify recovery)

  • Add a domain: configure (add domain + set port), operate (verify DNS and service health)

  • Docs to action: request (fetch docs answer), route to the relevant operational reference

When composing, return one unified response covering all steps. Don't ask the user to invoke each step separately.

Setup decision flow

When the user wants to create or deploy something, determine the right action from current context:

  1. If the intent is deploy-from-cwd or signup-from-cwd, skip railway whoami and run railway up (or railway up -y) directly per Intent-based routing — it handles signup, project creation, service creation, and deploy in one chain. For other setup flows that need workspace/account context first, run railway whoami --json; if it fails with an auth error the user has no token — route through Account creation & sign-in.

  2. Run railway status --json in the current directory.

  3. If linked: add a service to the existing project (railway add --service <name>). Do not create a new project unless the user explicitly says "new project" or "separate project".

  4. If not linked: check the parent directory (cd .. && railway status --json).

    • Parent linked: this is likely a monorepo sub-app. Add a service and set rootDirectory to the sub-app path.

    • Parent not linked: run railway list --json and look for a project matching the directory name.

      • Match found: link to it (railway link --project <name>).

      • No match: create a new project (railway init --name <name>).

  5. When multiple workspaces exist, match by name from railway whoami --json.

Naming heuristic: app names like "flappy-bird" or "my-api" are service names, not project names. Use the directory or repo name for the project.

Response format

For all operational responses, return:

  1. What was done (action and scope).

  2. The result (IDs, status, key output).

  3. What to do next (or confirmation that the task is complete).

Keep output concise. Include command evidence only when it helps the user understand what happened.

Files

scripts/analyze-mysql.py

#!/usr/bin/env python3
"""
MySQL analysis for Railway deployments.

Produces a comprehensive report covering:
- Deployment status & resource metrics (CPU, memory, disk)
- Connection overview
- Query throughput & efficiency
- InnoDB buffer pool & row operations
- Lock contention
- Top queries (from performance_schema)
- Table sizes
- Active processes
- Recommendations

Usage:
    analyze-mysql.py --service <name>
    analyze-mysql.py --service <name> --json
    analyze-mysql.py --service <name> --step ssh-test
"""

import argparse
import json
import os
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple

import dal
from dal import (
    LOG_LINES_DEFAULT, ProgressTimer, RailwayContext,
    _init_context, progress, run_railway_command, run_ssh_query,
    get_railway_status, get_deployment_status,
    get_all_metrics_from_api, _analyze_window, _build_metrics_history,
    get_recent_logs,
    _safe_int, _safe_float, _format_uptime, _trend_indicator,
)


# ---------------------------------------------------------------------------
# Result container
# ---------------------------------------------------------------------------

@dataclass
class MySQLAnalysisResult:
    """Container for MySQL analysis results."""
    service: str
    db_type: str
    timestamp: str
    deployment_status: str = "UNKNOWN"

    # Resource metrics from Railway API
    disk_usage: Optional[Dict[str, Any]] = None
    cpu_memory: Optional[Dict[str, Any]] = None
    metrics_history: Optional[Dict[str, Any]] = None

    # MySQL data
    overview: Optional[Dict[str, Any]] = None
    query_throughput: Optional[Dict[str, Any]] = None
    innodb_row_ops: Optional[Dict[str, Any]] = None
    query_efficiency: Optional[Dict[str, Any]] = None
    innodb_buffer_pool: Optional[Dict[str, Any]] = None
    innodb_io: Optional[Dict[str, Any]] = None
    network: Optional[Dict[str, Any]] = None
    locks: Optional[Dict[str, Any]] = None
    table_cache: Optional[Dict[str, Any]] = None
    top_queries: List[Dict[str, Any]] = field(default_factory=list)
    top_queries_status: Optional[str] = None
    tables: List[Dict[str, Any]] = field(default_factory=list)
    active_processes: List[Dict[str, Any]] = field(default_factory=list)

    # Logs
    recent_logs: List[str] = field(default_factory=list)
    recent_errors: List[str] = field(default_factory=list)

    # Metadata
    collection_status: Dict[str, Dict[str, Any]] = field(default_factory=dict)
    errors: List[str] = field(default_factory=list)
    recommendations: List[Dict[str, str]] = field(default_factory=list)


# ---------------------------------------------------------------------------
# MySQL-specific helpers
# ---------------------------------------------------------------------------

def run_mysql_query(service: str, query: str, timeout: int = 30) -> Tuple[int, str]:
    """Run a MySQL query via SSH and return (returncode, output).

    Uses -B (batch) mode which produces tab-separated output with headers.
    Filters out the mysql CLI password warning.
    """
    import base64
    query = " ".join(query.split())
    # Base64-encode the query to avoid all shell quoting issues
    # (single quotes in SQL IN clauses break bash -c '...' wrapping)
    encoded = base64.b64encode(query.encode()).decode()
    command = (
        f'''bash +H -c 'echo {encoded} | base64 -d | MYSQL_PWD="$MYSQLPASSWORD" mysql -h localhost -P 3306 '''
        f'''-u "$MYSQLUSER" -D "$MYSQLDATABASE" --default-character-set=utf8mb4 '''
        f'''-B' '''
    )
    code, stdout, stderr = run_ssh_query(service, command, timeout)
    # Filter out the password warning from stdout (mysql sometimes writes it there)
    lines = []
    for line in stdout.split("\n"):
        if "Using a password on the command line" in line:
            continue
        lines.append(line)
    stdout = "\n".join(lines)
    if code != 0:
        # Also filter warning from stderr
        stderr_clean = "\n".join(
            l for l in stderr.split("\n")
            if "Using a password on the command line" not in l
        )
        return code, stderr_clean or stdout
    return 0, stdout


def parse_mysql_batch(output: str) -> List[Dict[str, str]]:
    """Parse MySQL -B (batch/tab-separated) output into list of dicts.

    First line is column headers, subsequent lines are values.
    """
    lines = [l for l in output.strip().split("\n") if l.strip()]
    if len(lines) < 1:
        return []
    headers = lines[0].split("\t")
    rows = []
    for line in lines[1:]:
        values = line.split("\t")
        if len(values) == len(headers):
            rows.append(dict(zip(headers, values)))
    return rows


def parse_mysql_kv(output: str) -> Dict[str, str]:
    """Parse MySQL SHOW output (Variable_name / Value pairs) into a dict."""
    rows = parse_mysql_batch(output)
    result: Dict[str, str] = {}
    for row in rows:
        name = row.get("Variable_name", "")
        value = row.get("Value", "")
        if name:
            result[name] = value
    return result


# ---------------------------------------------------------------------------
# Railway context / status / metrics helpers
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# MySQL queries
# ---------------------------------------------------------------------------

QUERY_GLOBAL_STATUS = """SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected','Threads_running','Max_used_connections','Questions','Slow_queries','Com_select','Com_insert','Com_update','Com_delete','Innodb_buffer_pool_read_requests','Innodb_buffer_pool_reads','Innodb_buffer_pool_pages_data','Innodb_buffer_pool_pages_free','Innodb_buffer_pool_pages_dirty','Innodb_row_lock_waits','Innodb_row_lock_time','Uptime','Bytes_received','Bytes_sent','Connections','Aborted_clients','Aborted_connects','Innodb_rows_read','Innodb_rows_inserted','Innodb_rows_updated','Innodb_rows_deleted','Innodb_data_reads','Innodb_data_writes','Innodb_buffer_pool_bytes_data','Innodb_buffer_pool_bytes_dirty','Created_tmp_disk_tables','Created_tmp_tables','Handler_read_rnd_next','Handler_read_first','Handler_read_key','Select_full_join','Select_range','Sort_merge_passes','Table_locks_waited','Table_locks_immediate','Open_tables','Opened_tables')"""

QUERY_VARIABLES = """SHOW VARIABLES WHERE Variable_name IN ('max_connections','innodb_buffer_pool_size','long_query_time','version','table_open_cache','performance_schema')"""

QUERY_TABLE_SIZES = """SELECT TABLE_NAME, TABLE_ROWS, DATA_LENGTH, INDEX_LENGTH, DATA_LENGTH + INDEX_LENGTH AS TOTAL_SIZE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TOTAL_SIZE DESC LIMIT 15"""

QUERY_PROCESSLIST = """SHOW PROCESSLIST"""

QUERY_TOP_QUERIES = """SELECT DIGEST, LEFT(DIGEST_TEXT, 200) AS DIGEST_TEXT, COUNT_STAR, ROUND(SUM_TIMER_WAIT/1000000000, 2) AS TOTAL_LATENCY_MS, ROUND(AVG_TIMER_WAIT/1000000000, 2) AS AVG_LATENCY_MS, SUM_ROWS_EXAMINED, SUM_ROWS_SENT, SUM_CREATED_TMP_DISK_TABLES, SUM_NO_INDEX_USED FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST IS NOT NULL AND COUNT_STAR > 0 ORDER BY SUM_TIMER_WAIT DESC LIMIT 15"""


# ---------------------------------------------------------------------------
# MySQL data collection
# ---------------------------------------------------------------------------

def collect_mysql_data(service: str, timeout: int = 30) -> Dict[str, Any]:
    """Collect all MySQL metrics via SSH.

    Batches queries into two SSH calls for efficiency:
      1. SHOW GLOBAL STATUS + SHOW VARIABLES
      2. Table sizes + processlist + top queries (performance_schema)

    Returns a dict with raw parsed data keyed by section.
    """
    data: Dict[str, Any] = {
        "global_status": {},
        "variables": {},
        "tables": [],
        "processlist": [],
        "top_queries": [],
        "errors": [],
    }

    # --- Batch 1: SHOW GLOBAL STATUS; SHOW VARIABLES ---
    batch1_query = QUERY_GLOBAL_STATUS + "; " + QUERY_VARIABLES
    code, output = run_mysql_query(service, batch1_query, timeout=timeout)
    if code != 0:
        data["errors"].append(f"Batch 1 (status/variables) failed: {output}")
    else:
        # MySQL concatenates the two result sets; split them by detecting
        # a second header line starting with Variable_name
        sections = _split_mysql_resultsets(output, "Variable_name")
        if len(sections) >= 1:
            data["global_status"] = parse_mysql_kv(sections[0])
        if len(sections) >= 2:
            data["variables"] = parse_mysql_kv(sections[1])

    # --- Batch 2: tables + processlist + top queries ---
    batch2_query = QUERY_TABLE_SIZES + "; " + QUERY_PROCESSLIST + "; " + QUERY_TOP_QUERIES
    code, output = run_mysql_query(service, batch2_query, timeout=timeout)
    if code != 0:
        # Top queries may fail if performance_schema is off; try without
        batch2_fallback = QUERY_TABLE_SIZES + "; " + QUERY_PROCESSLIST
        code2, output2 = run_mysql_query(service, batch2_fallback, timeout=timeout)
        if code2 != 0:
            data["errors"].append(f"Batch 2 (tables/processlist) failed: {output}")
        else:
            sections = _split_mysql_resultsets_multi(output2, [
                "TABLE_NAME",
                "Id",
            ])
            if len(sections) >= 1:
                data["tables"] = parse_mysql_batch(sections[0])
            if len(sections) >= 2:
                data["processlist"] = parse_mysql_batch(sections[1])
    else:
        sections = _split_mysql_resultsets_multi(output, [
            "TABLE_NAME",
            "Id",
            "DIGEST",
        ])
        if len(sections) >= 1:
            data["tables"] = parse_mysql_batch(sections[0])
        if len(sections) >= 2:
            data["processlist"] = parse_mysql_batch(sections[1])
        if len(sections) >= 3:
            data["top_queries"] = parse_mysql_batch(sections[2])

    return data


def _split_mysql_resultsets(output: str, header_key: str) -> List[str]:
    """Split concatenated MySQL batch output into sections by header line."""
    lines = output.strip().split("\n")
    sections: List[List[str]] = []
    current: List[str] = []

    for line in lines:
        if line.startswith(header_key + "\t") or line.strip() == header_key:
            if current:
                sections.append("\n".join(current))
            current = [line]
        else:
            current.append(line)
    if current:
        sections.append("\n".join(current))

    return sections


def _split_mysql_resultsets_multi(output: str, header_keys: List[str]) -> List[str]:
    """Split concatenated MySQL batch output into sections by multiple different header keys."""
    lines = output.strip().split("\n")
    sections: List[List[str]] = []
    current: List[str] = []
    expected_idx = 0

    for line in lines:
        # Check if this line starts a new result set
        matched = False
        if expected_idx < len(header_keys):
            key = header_keys[expected_idx]
            if line.startswith(key + "\t") or line.strip() == key:
                if current:
                    sections.append("\n".join(current))
                current = [line]
                expected_idx += 1
                matched = True
        # Also check remaining headers in case we skipped one
        if not matched:
            for idx in range(expected_idx, len(header_keys)):
                key = header_keys[idx]
                if line.startswith(key + "\t") or line.strip() == key:
                    if current:
                        sections.append("\n".join(current))
                    current = [line]
                    expected_idx = idx + 1
                    matched = True
                    break
        if not matched:
            current.append(line)

    if current:
        sections.append("\n".join(current))

    return sections


# ---------------------------------------------------------------------------
# Parse collected data into result
# ---------------------------------------------------------------------------

def parse_mysql_data(data: Dict[str, Any], result: MySQLAnalysisResult) -> None:
    """Transform raw MySQL data into structured result sections."""
    gs = data.get("global_status", {})
    vs = data.get("variables", {})

    # --- Overview ---
    version = vs.get("version", "unknown")
    uptime_sec = _safe_int(gs.get("Uptime"))
    threads_connected = _safe_int(gs.get("Threads_connected"))
    threads_running = _safe_int(gs.get("Threads_running"))
    max_used_connections = _safe_int(gs.get("Max_used_connections"))
    max_connections = _safe_int(vs.get("max_connections"), 1)
    aborted_clients = _safe_int(gs.get("Aborted_clients"))
    aborted_connects = _safe_int(gs.get("Aborted_connects"))
    connection_usage_pct = round(max_used_connections / max_connections * 100, 1) if max_connections > 0 else 0

    result.overview = {
        "version": version,
        "uptime_seconds": uptime_sec,
        "uptime_human": _format_uptime(uptime_sec),
        "threads_connected": threads_connected,
        "threads_running": threads_running,
        "max_used_connections": max_used_connections,
        "max_connections": max_connections,
        "connection_usage_percent": connection_usage_pct,
        "aborted_clients": aborted_clients,
        "aborted_connects": aborted_connects,
    }

    # --- Query Throughput ---
    questions = _safe_int(gs.get("Questions"))
    slow_queries = _safe_int(gs.get("Slow_queries"))
    long_query_time = vs.get("long_query_time", "10")
    com_select = _safe_int(gs.get("Com_select"))
    com_insert = _safe_int(gs.get("Com_insert"))
    com_update = _safe_int(gs.get("Com_update"))
    com_delete = _safe_int(gs.get("Com_delete"))

    result.query_throughput = {
        "questions": questions,
        "slow_queries": slow_queries,
        "long_query_time": long_query_time,
        "com_select": com_select,
        "com_insert": com_insert,
        "com_update": com_update,
        "com_delete": com_delete,
    }

    # --- InnoDB Row Operations ---
    result.innodb_row_ops = {
        "rows_read": _safe_int(gs.get("Innodb_rows_read")),
        "rows_inserted": _safe_int(gs.get("Innodb_rows_inserted")),
        "rows_updated": _safe_int(gs.get("Innodb_rows_updated")),
        "rows_deleted": _safe_int(gs.get("Innodb_rows_deleted")),
    }

    # --- Query Efficiency ---
    created_tmp_disk = _safe_int(gs.get("Created_tmp_disk_tables"))
    created_tmp = _safe_int(gs.get("Created_tmp_tables"))
    tmp_disk_pct = round(created_tmp_disk / created_tmp * 100, 1) if created_tmp > 0 else 0
    handler_rnd_next = _safe_int(gs.get("Handler_read_rnd_next"))
    handler_first = _safe_int(gs.get("Handler_read_first"))
    handler_key = _safe_int(gs.get("Handler_read_key"))
    scan_total = handler_rnd_next + handler_first + handler_key
    table_scan_pct = round((handler_rnd_next + handler_first) / scan_total * 100, 1) if scan_total > 0 else 0
    select_full_join = _safe_int(gs.get("Select_full_join"))
    select_range = _safe_int(gs.get("Select_range"))
    sort_merge_passes = _safe_int(gs.get("Sort_merge_passes"))

    result.query_efficiency = {
        "created_tmp_disk_tables": created_tmp_disk,
        "created_tmp_tables": created_tmp,
        "tmp_disk_table_percent": tmp_disk_pct,
        "handler_read_rnd_next": handler_rnd_next,
        "handler_read_first": handler_first,
        "handler_read_key": handler_key,
        "table_scan_percent": table_scan_pct,
        "select_full_join": select_full_join,
        "select_range": select_range,
        "sort_merge_passes": sort_merge_passes,
    }

    # --- InnoDB Buffer Pool ---
    read_requests = _safe_int(gs.get("Innodb_buffer_pool_read_requests"))
    reads = _safe_int(gs.get("Innodb_buffer_pool_reads"))
    hit_ratio = round((read_requests - reads) / read_requests * 100, 2) if read_requests > 0 else 0
    pool_size = _safe_int(vs.get("innodb_buffer_pool_size"))
    bytes_data = _safe_int(gs.get("Innodb_buffer_pool_bytes_data"))
    bytes_dirty = _safe_int(gs.get("Innodb_buffer_pool_bytes_dirty"))
    usage_pct = round(bytes_data / pool_size * 100, 1) if pool_size > 0 else 0
    pages_free = _safe_int(gs.get("Innodb_buffer_pool_pages_free"))
    pages_data = _safe_int(gs.get("Innodb_buffer_pool_pages_data"))
    pages_dirty = _safe_int(gs.get("Innodb_buffer_pool_pages_dirty"))

    result.innodb_buffer_pool = {
        "hit_ratio": hit_ratio,
        "read_requests": read_requests,
        "reads": reads,
        "buffer_pool_size": pool_size,
        "bytes_data": bytes_data,
        "bytes_dirty": bytes_dirty,
        "usage_percent": usage_pct,
        "pages_data": pages_data,
        "pages_free": pages_free,
        "pages_dirty": pages_dirty,
    }

    # --- InnoDB I/O ---
    result.innodb_io = {
        "data_reads": _safe_int(gs.get("Innodb_data_reads")),
        "data_writes": _safe_int(gs.get("Innodb_data_writes")),
    }

    # --- Network ---
    result.network = {
        "bytes_received": _safe_int(gs.get("Bytes_received")),
        "bytes_sent": _safe_int(gs.get("Bytes_sent")),
    }

    # --- Locks ---
    row_lock_waits = _safe_int(gs.get("Innodb_row_lock_waits"))
    row_lock_time = _safe_int(gs.get("Innodb_row_lock_time"))
    table_locks_waited = _safe_int(gs.get("Table_locks_waited"))
    table_locks_immediate = _safe_int(gs.get("Table_locks_immediate"))
    lock_total = table_locks_waited + table_locks_immediate
    table_lock_contention = round(table_locks_waited / lock_total * 100, 2) if lock_total > 0 else 0

    result.locks = {
        "row_lock_waits": row_lock_waits,
        "row_lock_time": row_lock_time,
        "table_locks_waited": table_locks_waited,
        "table_locks_immediate": table_locks_immediate,
        "table_lock_contention": table_lock_contention,
    }

    # --- Table Cache ---
    open_tables = _safe_int(gs.get("Open_tables"))
    opened_tables = _safe_int(gs.get("Opened_tables"))
    table_open_cache = _safe_int(vs.get("table_open_cache"))
    cache_utilization_pct = round(open_tables / table_open_cache * 100, 1) if table_open_cache > 0 else 0
    opens_per_sec = round(opened_tables / uptime_sec, 2) if uptime_sec > 0 else 0

    result.table_cache = {
        "open_tables": open_tables,
        "opened_tables": opened_tables,
        "table_open_cache": table_open_cache,
        "cache_utilization_percent": cache_utilization_pct,
        "opens_per_second": opens_per_sec,
    }

    # --- Top Queries ---
    for row in data.get("top_queries", []):
        result.top_queries.append({
            "digest": row.get("DIGEST", ""),
            "digest_text": row.get("DIGEST_TEXT", ""),
            "count_star": _safe_int(row.get("COUNT_STAR")),
            "total_latency_ms": _safe_float(row.get("TOTAL_LATENCY_MS")),
            "avg_latency_ms": _safe_float(row.get("AVG_LATENCY_MS")),
            "rows_examined": _safe_int(row.get("SUM_ROWS_EXAMINED")),
            "rows_sent": _safe_int(row.get("SUM_ROWS_SENT")),
            "tmp_disk_tables": _safe_int(row.get("SUM_CREATED_TMP_DISK_TABLES")),
            "no_index_used": _safe_int(row.get("SUM_NO_INDEX_USED")),
        })

    if result.top_queries:
        result.top_queries_status = "ok"
    else:
        perf_schema = vs.get("performance_schema", "").upper()
        if perf_schema == "OFF":
            result.top_queries_status = "performance_schema_disabled"
        elif perf_schema == "ON":
            result.top_queries_status = "no_queries_recorded"
        else:
            result.top_queries_status = "unknown"

    # --- Tables ---
    for row in data.get("tables", []):
        result.tables.append({
            "name": row.get("TABLE_NAME", ""),
            "rows": _safe_int(row.get("TABLE_ROWS")),
            "data_length": _safe_int(row.get("DATA_LENGTH")),
            "index_length": _safe_int(row.get("INDEX_LENGTH")),
            "total_size": _safe_int(row.get("TOTAL_SIZE")),
        })

    # --- Active Processes ---
    for row in data.get("processlist", []):
        result.active_processes.append({
            "id": row.get("Id", ""),
            "user": row.get("User", ""),
            "db": row.get("db", ""),
            "command": row.get("Command", ""),
            "time": _safe_int(row.get("Time")),
            "state": row.get("State", ""),
            "info": row.get("Info", ""),
        })


# ---------------------------------------------------------------------------
# Formatting helpers
# ---------------------------------------------------------------------------

def _format_count(n: int) -> str:
    """Format large numbers with K/M/G suffix."""
    if n >= 1_000_000_000:
        return f"{n / 1_000_000_000:.1f}G"
    if n >= 1_000_000:
        return f"{n / 1_000_000:.1f}M"
    if n >= 1_000:
        return f"{n / 1_000:.1f}K"
    return str(n)


def _format_bytes(b: int) -> str:
    """Format bytes to human-readable."""
    if b >= 1_073_741_824:
        return f"{b / 1_073_741_824:.1f} GB"
    if b >= 1_048_576:
        return f"{b / 1_048_576:.1f} MB"
    if b >= 1_024:
        return f"{b / 1_024:.1f} KB"
    return f"{b} B"


def _status_ok_warn_crit(value: float, warn_threshold: float, crit_threshold: float) -> str:
    if value >= crit_threshold:
        return "CRITICAL"
    if value >= warn_threshold:
        return "WARN"
    return "OK"


# ---------------------------------------------------------------------------
# Recommendations
# ---------------------------------------------------------------------------

def generate_recommendations(result: MySQLAnalysisResult) -> List[Dict[str, str]]:
    recs: List[Dict[str, str]] = []

    # Collection failures — surface critical issues when SSH/introspection failed
    if result.collection_status:
        failed = {k: v for k, v in result.collection_status.items()
                  if v.get("status") in ("failed", "error")}
        ssh_sources = {"mysql_query"}
        ssh_failed = {k: v for k, v in failed.items() if k in ssh_sources}
        if ssh_failed:
            sources = ", ".join(ssh_failed.keys())
            errors = "; ".join(v.get("error", "unknown") for v in ssh_failed.values())
            recs.append({
                "severity": "critical",
                "category": "collection",
                "message": f"SSH introspection failed — unable to collect {sources}. "
                           f"Error: {errors}. "
                           f"Analysis is incomplete: InnoDB buffer pool, query throughput, "
                           f"locks, and tuning parameters could not be evaluated.",
            })

    def rec(severity: str, message: str):
        recs.append({"severity": severity, "message": message})

    ov = result.overview or {}
    qt = result.query_throughput or {}
    qe = result.query_efficiency or {}
    bp = result.innodb_buffer_pool or {}
    lk = result.locks or {}
    tc = result.table_cache or {}

    # Connection usage
    conn_pct = ov.get("connection_usage_percent", 0)
    max_conn = ov.get("max_connections", 0)
    if conn_pct >= 90:
        rec("critical", f"Connection usage critical at {conn_pct}%. Approaching max_connections ({max_conn}).")
    elif conn_pct >= 70:
        rec("warning", f"Connection usage at {conn_pct}%. Consider increasing max_connections.")

    # Buffer pool hit ratio
    hit_ratio = bp.get("hit_ratio", 100)
    if hit_ratio < 95:
        rec("critical", f"Buffer pool hit ratio at {hit_ratio}%. Increase innodb_buffer_pool_size.")
    elif hit_ratio < 99:
        rec("warning", f"Buffer pool hit ratio at {hit_ratio}% -- room for improvement with more RAM.")

    # Buffer pool usage
    bp_usage = bp.get("usage_percent", 0)
    if bp_usage > 95:
        rec("warning", f"Buffer pool {bp_usage}% full. Data pages may be evicted under load.")

    # Temp tables to disk
    tmp_pct = qe.get("tmp_disk_table_percent", 0)
    created_disk = qe.get("created_tmp_disk_tables", 0)
    created_total = qe.get("created_tmp_tables", 0)
    if tmp_pct > 25:
        rec("warning", f"{tmp_pct}% of temp tables going to disk. Increase tmp_table_size/max_heap_table_size or optimize queries.")
    elif tmp_pct > 10:
        rec("info", f"Temp tables to disk at {tmp_pct}%. Watch for queries creating large temporary results.")

    # Table scan ratio
    scan_pct = qe.get("table_scan_percent", 0)
    if scan_pct > 75:
        rec("critical", f"Table scan ratio at {scan_pct}%. Most reads are full scans -- add indexes.")
    elif scan_pct > 50:
        rec("warning", f"Table scan ratio at {scan_pct}%. Consider indexing frequently queried columns.")

    # Full joins
    full_joins = qe.get("select_full_join", 0)
    if full_joins > 100:
        rec("warning", f"{_format_count(full_joins)} full joins detected. These scan entire tables -- add indexes to join columns.")

    # Sort merge passes
    sort_passes = qe.get("sort_merge_passes", 0)
    if sort_passes > 0:
        rec("info", f"Sort merge passes ({_format_count(sort_passes)}). Increase sort_buffer_size or optimize queries.")

    # Row lock waits
    row_lock_waits = lk.get("row_lock_waits", 0)
    if row_lock_waits > 1000:
        rec("warning", f"InnoDB row lock waits ({_format_count(row_lock_waits)}). Check for lock contention in concurrent writes.")
    elif row_lock_waits > 0:
        rec("info", f"InnoDB row lock waits ({_format_count(row_lock_waits)}). Check for lock contention in concurrent writes.")

    # Table lock contention
    tl_contention = lk.get("table_lock_contention", 0)
    if tl_contention > 5:
        rec("warning", f"Table lock contention at {tl_contention}%. May indicate MyISAM tables -- convert to InnoDB.")

    # Slow queries
    slow = qt.get("slow_queries", 0)
    threshold = qt.get("long_query_time", "10")
    if slow > 0:
        rec("info", f"{_format_count(slow)} slow queries (threshold: {threshold}s). Review with performance_schema or slow query log.")

    # Aborted clients
    aborted_clients = ov.get("aborted_clients", 0)
    if aborted_clients > 0:
        rec("info", f"{_format_count(aborted_clients)} aborted clients. Applications may not be closing connections properly.")

    # Aborted connects
    aborted_connects = ov.get("aborted_connects", 0)
    if aborted_connects > 0:
        rec("info", f"{_format_count(aborted_connects)} aborted connection attempts. Check authentication issues or connection limits.")

    # No index used in top queries
    if result.top_queries:
        no_index_count = sum(1 for q in result.top_queries if q.get("no_index_used", 0) > 0)
        if no_index_count > 0:
            rec("warning", f"Top queries using no index ({no_index_count} of {len(result.top_queries)}). Missing indexes are likely impacting performance.")

    # Table cache
    tc = result.table_cache or {}
    opens_per_sec = tc.get("opens_per_second", 0)
    cache_util = tc.get("cache_utilization_percent", 0)
    if cache_util >= 95:
        rec("warning", f"Table cache {cache_util}% full ({tc.get('open_tables')}/{tc.get('table_open_cache')}). Increase table_open_cache.")
    if opens_per_sec > 5:
        rec("warning", f"Table opens at {opens_per_sec}/sec — cache may be undersized. Increase table_open_cache.")

    # Top queries diagnostic
    if not result.top_queries:
        if result.top_queries_status == "performance_schema_disabled":
            pass  # Off by default on Railway; overhead (~400MB+) is too high to recommend casually
        elif result.top_queries_status == "no_queries_recorded":
            rec("info", "performance_schema is ON but no queries recorded. Database may be idle or recently restarted.")

    return recs


# ---------------------------------------------------------------------------
# Report formatter
# ---------------------------------------------------------------------------

def format_report(result: MySQLAnalysisResult) -> str:
    lines: List[str] = []

    def heading(title: str, level: int = 2):
        prefix = "#" * level
        lines.append(f"\n{prefix} {title}")

    def table_row(*cells: str):
        lines.append("| " + " | ".join(cells) + " |")

    def table_sep(ncols: int):
        lines.append("| " + " | ".join(["---"] * ncols) + " |")

    # Title
    lines.append(f"# MySQL Analysis: {result.service}")
    lines.append(f"Timestamp: {result.timestamp}")
    lines.append(f"Deployment: {result.deployment_status}")

    # --- Resource Overview (from Railway API) ---
    if result.cpu_memory or result.disk_usage:
        heading("Resource Overview")
        table_row("Metric", "Value")
        table_sep(2)
        if result.cpu_memory:
            cm = result.cpu_memory
            if "cpu_percent" in cm:
                trend = _trend_indicator(result.metrics_history, "cpu")
                lines.append(f"| CPU | {cm['cpu_percent']}% vCPU{trend} |")
            if "memory_gb" in cm:
                trend = _trend_indicator(result.metrics_history, "memory")
                mem_str = f"{cm['memory_gb']} GB"
                if "memory_limit_gb" in cm and cm["memory_limit_gb"] > 0:
                    pct = round(cm["memory_gb"] / cm["memory_limit_gb"] * 100, 1)
                    mem_str += f" / {cm['memory_limit_gb']} GB ({pct}%)"
                lines.append(f"| Memory | {mem_str}{trend} |")
        if result.disk_usage:
            trend = _trend_indicator(result.metrics_history, "disk")
            lines.append(f"| Disk | {result.disk_usage.get('used', 'N/A')}{trend} |")

    # --- Overview ---
    ov = result.overview
    if ov:
        heading("Overview")
        table_row("Metric", "Value", "Status")
        table_sep(3)
        table_row("Version", str(ov["version"]), "")
        table_row("Uptime", ov["uptime_human"], "")
        conn_status = _status_ok_warn_crit(ov["connection_usage_percent"], 70, 90)
        table_row(
            "Connections",
            f"{ov['connection_usage_percent']}% ({ov['max_used_connections']}/{ov['max_connections']})",
            conn_status,
        )
        table_row("Threads Running", str(ov["threads_running"]), "")
        aborted_c_status = "WARN" if ov["aborted_clients"] > 0 else "OK"
        table_row("Aborted Clients", _format_count(ov["aborted_clients"]), aborted_c_status)
        aborted_conn_status = "WARN" if ov["aborted_connects"] > 0 else "OK"
        table_row("Aborted Connects", _format_count(ov["aborted_connects"]), aborted_conn_status)

    # --- Query Throughput ---
    qt = result.query_throughput
    if qt:
        heading("Query Throughput")
        table_row("Metric", "Value", "Status")
        table_sep(3)
        table_row("Total Queries", _format_count(qt["questions"]), "")
        slow_status = "WARN" if qt["slow_queries"] > 0 else "OK"
        table_row("Slow Queries", f"{_format_count(qt['slow_queries'])} (> {qt['long_query_time']}s threshold)", slow_status)
        table_row("SELECT", _format_count(qt["com_select"]), "")
        table_row("INSERT", _format_count(qt["com_insert"]), "")
        table_row("UPDATE", _format_count(qt["com_update"]), "")
        table_row("DELETE", _format_count(qt["com_delete"]), "")

    # --- InnoDB Row Operations ---
    ro = result.innodb_row_ops
    if ro:
        heading("InnoDB Row Operations")
        table_row("Operation", "Count")
        table_sep(2)
        table_row("Rows Read", _format_count(ro["rows_read"]))
        table_row("Rows Inserted", _format_count(ro["rows_inserted"]))
        table_row("Rows Updated", _format_count(ro["rows_updated"]))
        table_row("Rows Deleted", _format_count(ro["rows_deleted"]))

    # --- Query Efficiency ---
    qe = result.query_efficiency
    if qe:
        heading("Query Efficiency")
        table_row("Metric", "Value", "Status")
        table_sep(3)
        tmp_status = _status_ok_warn_crit(qe["tmp_disk_table_percent"], 10, 25)
        table_row(
            "Temp Tables to Disk",
            f"{qe['tmp_disk_table_percent']}% ({_format_count(qe['created_tmp_disk_tables'])}/{_format_count(qe['created_tmp_tables'])})",
            tmp_status,
        )
        scan_status = _status_ok_warn_crit(qe["table_scan_percent"], 50, 75)
        table_row("Table Scan Ratio", f"{qe['table_scan_percent']}%", scan_status)
        fj_status = "WARN" if qe["select_full_join"] > 100 else "OK"
        table_row("Full Joins", _format_count(qe["select_full_join"]), fj_status)
        table_row("Sort Merge Passes", _format_count(qe["sort_merge_passes"]), "")

    # --- InnoDB Buffer Pool ---
    bp = result.innodb_buffer_pool
    if bp:
        heading("InnoDB Buffer Pool")
        table_row("Metric", "Value", "Status")
        table_sep(3)
        hr_status = _status_ok_warn_crit(100 - bp["hit_ratio"], 1, 5)  # inverted: lower hit = worse
        table_row("Cache Hit Ratio", f"{bp['hit_ratio']}%", hr_status)
        usage_status = _status_ok_warn_crit(bp["usage_percent"], 90, 95)
        table_row(
            "Pool Usage",
            f"{bp['usage_percent']}% ({_format_bytes(bp['bytes_data'])}/{_format_bytes(bp['buffer_pool_size'])})",
            usage_status,
        )
        table_row("Dirty Pages", _format_bytes(bp["bytes_dirty"]), "")
        table_row("Free Pages", _format_count(bp["pages_free"]), "")

    # --- Network ---
    nw = result.network
    if nw:
        heading("Network")
        table_row("Metric", "Value")
        table_sep(2)
        table_row("Bytes Received", _format_bytes(nw["bytes_received"]))
        table_row("Bytes Sent", _format_bytes(nw["bytes_sent"]))

    # --- Locks ---
    lk = result.locks
    if lk:
        heading("Locks")
        table_row("Metric", "Value", "Status")
        table_sep(3)
        table_row("Row Lock Waits", _format_count(lk["row_lock_waits"]), "")
        table_row("Row Lock Time (ms)", _format_count(lk["row_lock_time"]), "")
        tl_status = _status_ok_warn_crit(lk["table_lock_contention"], 1, 5)
        table_row("Table Lock Contention", f"{lk['table_lock_contention']}%", tl_status)

    # --- Table Cache ---
    tc = result.table_cache
    if tc:
        heading("Table Cache")
        table_row("Metric", "Value")
        table_sep(2)
        table_row("Open Tables", f"{_format_count(tc['open_tables'])} / {_format_count(tc.get('table_open_cache', 0))}")
        table_row("Cache Utilization", f"{tc.get('cache_utilization_percent', 0)}%")
        table_row("Table Opens/sec", f"{tc.get('opens_per_second', 0)}")

    # --- Top Queries ---
    if result.top_queries:
        heading("Top Queries (by total latency)")
        table_row("Query", "Calls", "Avg Latency", "Total Latency", "Rows Examined", "Rows Sent")
        table_sep(6)
        for q in result.top_queries[:15]:
            digest = q["digest_text"][:60] + "..." if len(q["digest_text"]) > 60 else q["digest_text"]
            # Escape pipe chars in query text
            digest = digest.replace("|", "\\|")
            table_row(
                digest,
                _format_count(q["count_star"]),
                f"{q['avg_latency_ms']:.1f}ms",
                f"{q['total_latency_ms']:.1f}ms",
                _format_count(q["rows_examined"]),
                _format_count(q["rows_sent"]),
            )
    else:
        heading("Top Queries (by total latency)")
        if result.top_queries_status == "performance_schema_disabled":
            lines.append("performance_schema is disabled — no query-level data available.")
            lines.append("Note: enabling it requires ~400MB+ additional memory; only advisable on larger instances.")
        elif result.top_queries_status == "no_queries_recorded":
            lines.append("No queries recorded. Database may be idle or recently restarted.")
        else:
            lines.append("No query data available.")
        lines.append("")

    # --- Tables ---
    if result.tables:
        heading("Tables (by size)")
        table_row("Table", "Rows", "Data", "Indexes", "Total")
        table_sep(5)
        for t in result.tables[:15]:
            table_row(
                t["name"],
                _format_count(t["rows"]),
                _format_bytes(t["data_length"]),
                _format_bytes(t["index_length"]),
                _format_bytes(t["total_size"]),
            )

    # --- Active Queries ---
    if result.active_processes:
        heading("Active Queries")
        # Filter out system processes
        user_procs = [p for p in result.active_processes if p["command"] != "Daemon"]
        if user_procs:
            table_row("User", "Database", "Command", "Time (s)", "Query")
            table_sep(5)
            for p in user_procs[:20]:
                info = (p["info"] or "")[:80]
                info = info.replace("|", "\\|")
                table_row(
                    p["user"],
                    p["db"] or "",
                    p["command"],
                    str(p["time"]),
                    info,
                )
        else:
            lines.append("\nNo active user queries.")

    # --- Infrastructure Metrics ---
    if result.metrics_history:
        windows = result.metrics_history.get("windows", {})
        for window_label, window_data in windows.items():
            mh = window_data.get("metrics", {})
            if not mh:
                continue
            lines.append(f"## Infrastructure Metrics ({window_label})")
            lines.append("| Metric | Current | Min | Max | Avg | Trend |")
            lines.append("|--------|---------|-----|-----|-----|-------|")
            for key in ["cpu", "memory", "disk", "network_rx", "network_tx"]:
                if key in mh:
                    entry = mh[key]
                    trend = entry.get("trend", {})
                    trend_str = trend.get("direction", "N/A")
                    change = trend.get("change_pct", 0)
                    if change != 0:
                        trend_str += f" ({change:+.1f}%)"
                    lines.append(
                        f"| {key.replace('_', ' ').title()} "
                        f"| {entry['current']}{entry['unit']} "
                        f"| {entry['min']}{entry['unit']} "
                        f"| {entry['max']}{entry['unit']} "
                        f"| {entry['avg']}{entry['unit']} "
                        f"| {trend_str} |"
                    )
            lines.append("")

    # --- Collection Errors ---
    if result.errors:
        heading("Collection Errors")
        for err in result.errors:
            lines.append(f"- {err}")

    # --- Recommendations ---
    heading("Recommendations")
    if result.recommendations:
        for r in result.recommendations:
            severity = r["severity"].upper()
            lines.append(f"- **[{severity}]** {r['message']}")
    else:
        lines.append("No issues detected.")

    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------------------
# Main analysis function
# ---------------------------------------------------------------------------

def analyze_mysql(service: str, timeout: int = 60, quiet: bool = False,
                  skip_logs: bool = False, metrics_hours: int = 168,
                  project_id: Optional[str] = None,
                  environment_id: Optional[str] = None,
                  service_id: Optional[str] = None) -> MySQLAnalysisResult:
    """Run complete MySQL analysis."""
    if not quiet:
        print(f"Analyzing mysql database: {service}", file=sys.stderr)

    result = MySQLAnalysisResult(
        service=service,
        db_type="mysql",
        timestamp=datetime.now(timezone.utc).isoformat(),
    )

    # === CONTEXT ===
    if not quiet:
        print("  [0/5] Getting Railway context...", file=sys.stderr, flush=True)
    dal._progress_timer.start()

    if environment_id and service_id:
        dal._ctx = RailwayContext(project_id=project_id, environment_id=environment_id, service_id=service_id)
        if not quiet:
            print(f"        using explicit IDs (env={environment_id[:8]}..., svc={service_id[:8]}...)", file=sys.stderr, flush=True)
    else:
        railway_status = get_railway_status()
        if railway_status:
            dal._ctx = RailwayContext(
                project_id=railway_status.get("projectId"),
                environment_id=railway_status.get("environmentId"),
                service_id=railway_status.get("serviceId"),
            )
        environment_id = dal._ctx.environment_id
        service_id = dal._ctx.service_id

    # === DEPLOYMENT STATUS ===
    progress(1, 5, "Fetching deployment status...", quiet)
    result.deployment_status = get_deployment_status(service, service_id=service_id)

    # === SSH PRE-CHECK ===
    progress(2, 5, "Testing SSH connectivity...", quiet)
    ssh_available = False
    ssh_stderr = ""
    ssh_attempts = [30, 60, 90]
    for attempt, attempt_timeout in enumerate(ssh_attempts, 1):
        ssh_code, ssh_stdout, ssh_stderr = run_ssh_query(service, "echo ok", timeout=attempt_timeout)
        if ssh_code == 0 and "ok" in ssh_stdout:
            ssh_available = True
            if not quiet:
                for line in ssh_stderr.splitlines():
                    if line.startswith("Using SSH key:"):
                        print(f"        {line}", file=sys.stderr, flush=True)
                        break
            break
        if not quiet:
            remaining = len(ssh_attempts) - attempt
            if remaining > 0:
                print(f"        SSH attempt {attempt}/{len(ssh_attempts)} failed ({ssh_stderr or 'no response'}), retrying with {ssh_attempts[attempt]}s timeout...", file=sys.stderr, flush=True)
            else:
                print(f"        SSH attempt {attempt}/{len(ssh_attempts)} failed ({ssh_stderr or 'no response'}), giving up", file=sys.stderr, flush=True)

    # === PARALLEL EXECUTION ===
    progress(3, 5, "Running analysis (metrics, queries, logs in parallel)...", quiet)

    def task_metrics():
        if environment_id and service_id:
            return get_all_metrics_from_api(environment_id, service_id, hours=metrics_hours)
        return None

    def task_mysql_queries():
        if not ssh_available:
            return {"errors": [f"SSH not available: {ssh_stderr or 'connection failed'}"]}
        data = collect_mysql_data(service, timeout=timeout)
        if data.get("errors") and not data.get("global_status"):
            # Retry once
            data = collect_mysql_data(service, timeout=timeout)
        return data

    def task_logs():
        if skip_logs:
            return []
        return get_recent_logs(service, lines=LOG_LINES_DEFAULT,
                               environment_id=environment_id,
                               service_id=service_id)

    with ThreadPoolExecutor(max_workers=3) as executor:
        future_metrics = executor.submit(task_metrics)
        future_mysql = executor.submit(task_mysql_queries)
        future_logs = executor.submit(task_logs)

        metrics_result = future_metrics.result()
        mysql_data = future_mysql.result()
        logs_result = future_logs.result()

    # Process metrics
    if metrics_result:
        result.disk_usage = metrics_result.get("disk_usage")
        result.cpu_memory = metrics_result.get("cpu_memory")
        result.metrics_history = metrics_result.get("metrics_history")
        result.collection_status["metrics_api"] = {"status": "success"}
    else:
        result.collection_status["metrics_api"] = {
            "status": "error",
            "error": "Metrics API returned no data",
        }

    # Process MySQL data
    progress(4, 5, "Processing results...", quiet)
    mysql_errors = mysql_data.get("errors", [])
    if mysql_data.get("global_status"):
        parse_mysql_data(mysql_data, result)
        result.collection_status["mysql_query"] = {"status": "success"}
        if mysql_errors:
            result.collection_status["mysql_query"]["warnings"] = mysql_errors
    else:
        error_msg = "; ".join(mysql_errors) if mysql_errors else "No data returned"
        if not ssh_available:
            error_msg = f"SSH failed after {len(ssh_attempts)} attempts: {ssh_stderr or 'connection failed'}"
        result.errors.append(f"MySQL data collection failed: {error_msg}")
        result.collection_status["mysql_query"] = {
            "status": "error",
            "error": error_msg,
        }

    # Process logs
    if skip_logs:
        result.collection_status["logs_api"] = {"status": "skipped", "reason": "skip_logs flag set"}
    elif logs_result:
        result.recent_logs = logs_result
        result.collection_status["logs_api"] = {"status": "success", "lines": len(logs_result)}
        result.recent_errors = [
            line for line in result.recent_logs
            if "ERROR" in line.upper() or "FATAL" in line.upper()
        ][:100]
    else:
        result.recent_logs = []
        result.collection_status["logs_api"] = {
            "status": "error",
            "error": "Logs API returned no data",
        }

    # === RECOMMENDATIONS ===
    progress(5, 5, "Generating recommendations...", quiet)
    result.recommendations = generate_recommendations(result)

    if not quiet:
        total = dal._progress_timer.total_elapsed()
        print(f"Done.{total}", file=sys.stderr)

    return result


# ---------------------------------------------------------------------------
# Single-step debugging
# ---------------------------------------------------------------------------

def run_single_step(args) -> int:
    """Run a single collection step for debugging."""
    service = args.service
    _init_context(args)
    environment_id = dal._ctx.environment_id
    service_id = dal._ctx.service_id

    if args.step == "ssh-test":
        print(f"Testing SSH to service: {service}", file=sys.stderr)
        code, stdout, stderr = run_ssh_query(service, "echo ok", timeout=45)
        print(f"Exit code: {code}")
        print(f"Stdout: {stdout.strip()}")
        if stderr:
            print(f"Stderr: {stderr.strip()}")
        return 0 if (code == 0 and "ok" in stdout) else 1

    elif args.step == "query":
        print(f"Running MySQL queries on: {service}", file=sys.stderr)
        data = collect_mysql_data(service, timeout=args.timeout)
        print(json.dumps(data, indent=2, default=str))
        return 0 if data.get("global_status") else 1

    elif args.step == "logs":
        print(f"Fetching logs for: {service}", file=sys.stderr)
        logs = get_recent_logs(service, lines=LOG_LINES_DEFAULT,
                               environment_id=environment_id,
                               service_id=service_id)
        print(f"Lines fetched: {len(logs)}")
        for line in logs:
            print(line)
        return 0

    elif args.step == "metrics":
        print(f"Fetching metrics for: {service}", file=sys.stderr)
        if environment_id and service_id:
            metrics = get_all_metrics_from_api(environment_id, service_id)
            if metrics:
                print(json.dumps(metrics, indent=2))
            else:
                print("Metrics API returned no data")
                return 1
        else:
            print("Missing environment_id or service_id from railway config")
            return 1
        return 0

    return 1


# ---------------------------------------------------------------------------
# Main entry point
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(
        description="MySQL analysis for Railway services.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("--service", required=True, help="Service name")
    parser.add_argument("--json", action="store_true",
                        help="Output as JSON")
    parser.add_argument("--timeout", type=int, default=60,
                        help="Timeout in seconds for SSH queries (default: 60)")
    parser.add_argument("--quiet", "-q", action="store_true",
                        help="Suppress progress messages")
    parser.add_argument("--skip-logs", action="store_true",
                        help="Skip log fetching for faster analysis")
    parser.add_argument("--metrics-hours", type=int, default=168,
                        help="Hours of metrics history to fetch (default: 168, max: 168)")
    parser.add_argument("--step", choices=["ssh-test", "query", "logs", "metrics"],
                        help="Run a single collection step for debugging")
    parser.add_argument("--project-id", help="Project ID (bypasses railway link)")
    parser.add_argument("--environment-id", help="Environment ID (bypasses railway link)")
    parser.add_argument("--service-id", help="Service ID (bypasses railway link)")

    args = parser.parse_args()

    # Single-step debugging mode
    if args.step:
        return run_single_step(args)

    # Run analysis
    result = analyze_mysql(
        args.service,
        timeout=args.timeout,
        quiet=args.quiet,
        skip_logs=args.skip_logs,
        metrics_hours=min(args.metrics_hours, 168),
        project_id=args.project_id,
        environment_id=args.environment_id,
        service_id=args.service_id,
    )

    # Output
    if args.json:
        print(json.dumps(asdict(result), indent=2))
    else:
        print(format_report(result))

    return 0


if __name__ == "__main__":
    sys.exit(main())

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs an MCP server, Needs network access, Needs a command-line tool, Needs Python, Needs Node.js

Security

What our scanner noticed· Medium risk

  • References to credential files
  • Instructions that use the network
  • Downloads piped into a shell
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Cline
Publisher
Cline (Official)
Source
cline/skills · skills/use-railway · commit 2637846
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Cline.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download use-railway.zip