use-railway
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse Railway
使用Railway
Railway resource model
Railway资源模型
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). Each environment has its own variables, config, and deployment history.staging - 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 to see the context, and , , flags to override.
railway status --json--project--environment--serviceRailway采用层级结构组织基础设施:
- Workspace 是计费与团队范围的载体,一个用户可隶属于一个或多个Workspace。
- Project 是同一Workspace下的服务集合,对应一个可部署的工作单元。
- Environment 是Project内的隔离配置平面(例如、
production)。每个环境拥有独立的变量、配置和部署历史。staging - Service 是Project内的单个可部署单元,可以是代码仓库中的应用、Docker镜像或托管数据库。
- Bucket 是Project内兼容S3的对象存储资源。Bucket在Project级别创建并部署到各个环境,每个Bucket都配有兼容S3访问的凭证(端点、访问密钥、密钥)。
- Deployment 是Service在某个环境中的特定版本发布,包含构建日志、运行时日志和状态生命周期。
大多数CLI命令基于关联的Project/Environment/Service上下文运行。使用查看当前上下文,可通过、、标志覆盖默认上下文。
railway status --json--project--environment--serviceTool routing
工具路由
Railway has three agent-facing operation paths. Choose the path that matches the job:
- Remote MCP (): account/project/service discovery, deployment state, bounded logs, simple redeploys, simple project creation, or complex Railway workflows that can be handed to
https://mcp.railway.com. Remote MCP uses Railway OAuth and does not depend on local CLI state.railway-agent - Local CLI MCP (): CLI-backed platform operations such as variables, domains, service config, templates, metrics, HTTP summaries, buckets, volumes, docs, or deploy-from-directory.
railway mcp - Railway CLI (): workflows that depend on local machine state such as current working directory deploys,
railway,railway up, SSH, database analysis scripts, local linking, interactive setup, or exact command output.railway run
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 only when neither MCP nor CLI exposes the operation, or when a reference gives a specific GraphQL fallback.
scripts/railway-api.shRailway提供三种面向agent的操作路径,需根据任务选择合适路径:
- Remote MCP():适用于账户/项目/服务发现、部署状态查询、有限日志查看、简单重新部署、简单项目创建,或可交由
https://mcp.railway.com处理的复杂Railway工作流。Remote MCP使用Railway OAuth,不依赖本地CLI状态。railway-agent - Local CLI MCP():适用于基于CLI的平台操作,如变量管理、域名配置、服务设置、模板使用、指标查看、HTTP摘要、Bucket管理、卷管理、文档查询或从目录部署。
railway mcp - Railway CLI():适用于依赖本地机器状态的工作流,如当前工作目录部署、
railway、railway up、SSH连接、数据库分析脚本、本地关联、交互式设置或精确命令输出。railway run
若存在多个可选路径,选择能保留所需上下文的路径。Remote MCP适合无需本地文件或CLI状态的OAuth范围平台操作;Local CLI MCP或CLI适合需要当前代码仓库、本地凭证、SSH、数据库脚本或Remote MCP未暴露命令的工作流。
仅当MCP和CLI均未暴露对应操作,或参考文档指定使用GraphQL回退时,才使用。
scripts/railway-api.shParsing Railway URLs
解析Railway URL
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 and . It may contain as a query parameter. If the environment ID is missing and the user specifies an environment by name (e.g., "production"), resolve it:
projectIdserviceIdenvironmentIdbash
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 .
environmentIdPrefer passing explicit IDs to CLI commands (, , ) and scripts (, , ) instead of running . This avoids modifying global state and is faster.
--project--environment--service--project-id--environment-id--service-idrailway link用户常粘贴Railway控制台URL,需先提取其中的ID:
https://railway.com/project/<PROJECT_ID>/service/<SERVICE_ID>?environmentId=<ENV_ID>
https://railway.com/project/<PROJECT_ID>/service/<SERVICE_ID>URL中始终包含和,可能包含作为查询参数的。若环境ID缺失且用户指定了环境名称(如“production”),需解析环境ID:
projectIdserviceIdenvironmentIdbash
scripts/railway-api.sh \
'query getProject($id: String!) {
project(id: $id) {
environments { edges { node { id name } } }
}
}' \
'{"id": "<PROJECT_ID>"}'通过环境名称(不区分大小写)匹配获取。
environmentId优先传递明确ID给CLI命令(、、)和脚本(、、),而非运行。这样可避免修改全局状态且速度更快。
--project--environment--service--project-id--environment-id--service-idrailway linkIntent-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 whoamipreflights.railway status - Run 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.
railway up - Announce intent before invoking: "Running — it'll sign you in if needed and deploy this directory."
railway up - Do NOT ask the user to run first. The chain handles auth as part of the deploy.
railway login - 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, source to build), runDockerfile— 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 barerailway upis 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 upis the robust form — it skips prompts and forces the create non-interactively even if harness detection misses.railway up -yis NOT the default for signup when there's something to deploy.railway login - 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 (creates new accounts on the fly through the same OAuth surface). There is no separate signup command.
railway login - 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.
在运行预检检查前,先根据用户意图进行路由。以下预检流程适用于诊断和配置工作——若用户仅需部署或注册,此流程会增加操作阻力。
从当前目录部署意图(“deploy”、“ship”、“push to Railway”、“deploy this app”):
- 跳过/
railway whoami预检步骤。railway status - 直接运行——它会自动验证身份,若用户未认证则引导登录(CLI会打开浏览器),并链式完成项目+服务创建与部署。
railway up - 执行前告知用户意图:“正在运行——若需登录会自动引导并部署当前目录。”
railway up - 请勿要求用户先运行,部署流程会自动处理身份验证。
railway login - 若环境无法打开浏览器,CLI会打印设备码登录链接并等待——需遵循设备码登录:立即转发链接(后台运行,链接一打印就立即转发给用户)。
注册意图(“sign me up”、“create my Railway account”、“register me”、“get me on Railway”):
- 若当前目录包含可部署应用(如、
package.json、requirements.txt、go.mod或可构建源码),运行Dockerfile——它会在一步操作中完成注册和部署,让用户拥有一个运行中的应用。检测到agent harness时会授权项目创建,因此直接运行railway up即可——无需额外确认提示。即使用户仅说“注册”也可使用此命令,因为部署应用是最终目标,无需让用户选择命令或仅完成登录。对于脚本或agent运行场景,railway up是更可靠的形式——它会跳过提示,即使harness检测失败也会强制非交互式创建。当有可部署内容时,railway up -y不是注册的默认选择。railway login - 仅当无内容可部署时——空目录/非应用目录,或用户明确表示仅需账户无需部署——使用(通过相同的OAuth界面即时创建新账户)。Railway没有单独的注册命令。
railway login - 注册流程最可能遇到设备码等待(全新用户在沙盒/无头agent环境中),需遵循设备码登录:立即转发链接——因代码过期导致注册失败会流失用户,需避免重试。
沙盒/远程构建意图(“give me a sandbox”、“spin up a scratch environment”、“build this remotely”、“run this remotely”):
- 加载sandbox.md并遵循其中步骤。沙盒功能需在Priority Boarding中启用——若沙盒命令因功能可用错误失败,提示用户在Priority Boarding中启用沙盒而非重试。
其他意图(查询状态、列出项目、配置变量、排查故障):
- 遵循下方的预检流程。
Preflight
预检
Before any mutation, verify the tool path and context:
bash
command -v railway # CLI installed
RAILWAY_CALLER="skill:use-railway@1.2.6" RAILWAY_AGENT_SESSION="railway-skill-$(date +%s)-$$" railway whoami --json
railway --version # check CLI versionException: and self-validate auth and run their own unauth-aware flows. Don't run before them — it adds a redundant failing call without changing what you do next. See Account creation & sign-in.
railway uprailway loginrailway whoami执行任何变更操作前,验证工具路径和上下文:
bash
command -v railway # 检查CLI是否已安装
RAILWAY_CALLER="skill:use-railway@1.2.6" RAILWAY_AGENT_SESSION="railway-skill-$(date +%s)-$$" railway whoami --json
railway --version # 检查CLI版本例外情况:和会自动验证身份并运行自身的未认证感知流程。无需在它们之前运行——这会增加一次冗余的失败调用,且不会改变后续操作。详见账户创建与登录。
railway uprailway loginrailway whoamiSkill freshness
技能版本更新
Once per session, alongside the preflight checks, verify the installed Railway agent tooling is current. Root help ends with an health section (printed to stderr, CLI 5.9+; older CLIs print nothing — skip this check rather than retrying):
Agent tooling:bash
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 () — run
rev <a> → <b> available, 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.railway skills update - Skills or MCP server missing (lines) — run
✗, then tell the user to restart their coding tool.railway setup agent -y
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 and a stable 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 preflight solely for telemetry; inline env prefixes keep the shell output concise and avoid leaking setup steps into every response.
RAILWAY_CALLER=skill:use-railway@1.2.6RAILWAY_AGENT_SESSIONexportContext resolution - URL IDs always win:
- If the user provides a Railway URL, extract IDs from it. Do NOT run ; it returns the locally linked project, which is usually unrelated.
railway status --json - If no URL is given, fall back to for the linked project/environment/service.
railway status --json - When using MCP tools after resolving local context with , 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.
railway status --json
If the CLI is missing, guide the user to install it.
bash
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 (deploy + sign up/in in one shot) or (sign up/in only; new accounts created on the fly). If not linked and no URL was provided, run .
railway uprailway loginrailway link --project <id-or-name>If a command is not recognized (for example, ), the CLI may be outdated. Upgrade with:
railway environment editbash
railway upgrade每次会话中,与预检检查一起验证已安装的Railway agent工具是否为最新版本。根级帮助的结尾包含健康检查部分(打印到stderr,CLI 5.9+版本支持;旧版本CLI无此输出——跳过此检查而非重试):
Agent tooling:bash
railway --help 2>&1 | grep -A4 "Agent tooling:"根据检查结果执行操作:
- 技能已安装且为最新版本——继续操作,无需额外处理。
- 有可用更新()——运行
rev <a> → <b> available,然后告知用户重启编码工具以加载更新后的技能。当前会话会继续使用旧版本技能直至重启:完成当前请求,若此技能的指导与更新后CLI的输出不一致,以CLI为准。railway skills update - 技能或MCP服务器缺失(标识行)——运行
✗,然后告知用户重启编码工具。railway setup agent -y
每次会话检查一次,执行操作后无需重新检查;告知用户重启即为解决方式,无需再次检查。
当Railway MCP可用且任务为平台状态读取时,使用匹配的MCP读取操作而非调用shell命令。若使用CLI路径,需运行上述CLI检查。
在此技能活跃期间调用Railway CLI命令时,需在命令前添加和为当前用户请求生成的稳定。每个用户请求生成一次会话ID,然后在同一工作流的后续Railway CLI调用中重复使用该值。无需仅为遥测单独运行预检;内联环境前缀可保持shell输出简洁,避免将设置步骤泄露到每个响应中。
RAILWAY_CALLER=skill:use-railway@1.2.6RAILWAY_AGENT_SESSIONexport上下文解析 - URL ID优先级最高:
- 若用户提供Railway URL,从中提取ID。请勿运行;它返回的是本地关联的项目,通常与当前任务无关。
railway status --json - 若未提供URL,回退到获取关联的Project/Environment/Service。
railway status --json - 使用MCP工具时,若通过解析了本地上下文,需显式传递解析后的Project、Environment和Service ID。请勿依赖MCP的隐式关联上下文;MCP可能与CLI的当前工作目录关联不共享。
railway status --json
若CLI缺失,引导用户安装:
bash
bash <(curl -fsSL https://railway.com/install.sh) --agents -y # 安装CLI并配置检测到的agents
bash <(curl -fsSL https://railway.com/install.sh) # Shell脚本(macOS、Linux、Windows通过WSL)
npm i -g @railway/cli # npm安装(macOS、Linux、Windows),要求Node.js版本16或更高
brew install railway # Homebrew安装(macOS)若未认证,查看下方账户创建与登录——CLI提供未认证的(一步完成部署+注册/登录)或(仅注册/登录;即时创建新账户)。若未关联且未提供URL,运行。
railway uprailway loginrailway link --project <id-or-name>若命令不被识别(例如),可能是CLI版本过时。运行以下命令升级:
railway environment editbash
railway upgradeAccount 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:
| Command | When to use |
|---|---|
| Agent-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 |
| Sign in — and sign up. New accounts are created on the fly through the same OAuth surface; there is no separate signup command. |
Related: 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); overrides the project name.
railway up --new--name <name>Choosing the path:
- Deploy from cwd → run (interactive) or
railway up(skips the confirm prompt). Run it yourself; don't ask the user to sign in separately first.railway up -y - New project from cwd when already signed in → .
railway up --new - Sign up with a deployable app in cwd → (signs up and deploys — bare
railway upworks for a detected agent, even if the user only said "sign me up"; addupto skip prompts / force it non-interactively). Sign in, or sign up with nothing to deploy →-y(creates new accounts on the fly).railway login
Headless / no browser:
The CLI auto-detects SSH sessions, CI, and a missing and switches to the device-code flow on its own — you almost never need to force it.
DISPLAYDo NOT pass 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 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.
--browserlessrailway loginbash
railway login --browserless # ONLY for machines with genuinely no browserForces 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, 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.
railway upDevice-code sign-in: relay the link immediately (CRITICAL):
When the CLI can't open a browser (sandboxed shell, container, SSH, no ), unauthed and 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:
DISPLAYrailway uprailway login- 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 (on newer CLIs, or
Sign in with one click: <url>/Sign in at: <url>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.Enter this code: <code> - 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.
- 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.
- 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: and will NOT open a browser for an unauthed user. emits a structured error instead:
railway up --jsonrailway up --ci--jsonjson
{"error":"Not signed in.","code":"NOT_AUTHENTICATED","hint":"Run `railway login` to authenticate, then re-run."}When you see , authenticate the user with , then retry the original command.
code: NOT_AUTHENTICATEDrailway loginFully unattended (no human at all): set (account-scoped) or (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.
RAILWAY_API_TOKENRAILWAY_TOKENRailway使用统一的OAuth流程处理登录和注册。后端会从持久化合规状态(未接受服务条款/合理使用政策的CLI客户端)检测新账户,并调整同意界面和认证后着陆页——新用户会进入“Welcome to Railway!”页面,现有用户则看到标准确认界面。CLI不会预先声明注册意图。
根据意图,有两个命令可触发此流程:
| 命令 | 使用场景 |
|---|---|
| 从当前目录进行agent友好的引导流程。未认证→打开浏览器(或设备码)进行登录/注册。若无关联项目,检测到agent harness(或使用 |
| 登录——同时支持注册。通过相同的OAuth界面即时创建新账户;没有单独的注册命令。 |
相关命令:会从当前目录创建一个全新的项目+服务并部署,即使已有关联项目(适用于已登录且用户需要新应用的场景);可覆盖项目名称。
railway up --new--name <name>路径选择:
- 从当前目录部署→运行(交互模式)或
railway up(跳过确认提示)。直接运行该命令;请勿要求用户先单独登录。railway up -y - 已登录状态下从当前目录创建新项目→。
railway up --new - 当前目录有可部署应用时注册→(完成注册和部署——检测到agent时直接运行
railway up即可,即使用户仅说“注册”;添加up参数可跳过提示/强制非交互式创建)。登录,或无内容可部署时注册→-y(即时创建新账户)。railway login
无头/无浏览器环境:
CLI会自动检测SSH会话、CI环境和缺失的,并自动切换到设备码流程——几乎无需强制启用。
DISPLAY请勿仅因你是agent或所在shell非交互式就传递参数。若用户在本地机器(本地IDE或桌面会话——常见场景),直接运行会打开用户的浏览器,这比转发设备码可靠得多(agent驱动登录的成功率约90% vs 60%)。作为编码agent不代表当前机器是无头环境。
--browserlessrailway loginbash
railway login --browserless # 仅适用于完全无浏览器的机器强制启用设备码流程(RFC 8628):打印登录链接和短码,供用户在任意设备上打开。仅在确实无浏览器的机器上使用——SSH服务器、容器、自动检测遗漏的远程VM。当进入设备码流程时,需遵循以下转发步骤:链接一打印就立即展示给用户。
存在agent harness且用户在场:当CLI检测到存在用户操作的agent harness时,会打开浏览器并跳过确认提示——agent调用会被视为同意。仍需用户在浏览器中完成OAuth认证。
railway up设备码登录:立即转发链接(至关重要):
当CLI无法打开浏览器(沙盒shell、容器、SSH、无),未认证的和会打印登录URL+短码,然后阻塞并轮询最多10分钟等待用户完成登录。代码10分钟后过期。若作为普通前台命令运行,harness会缓冲输出直到命令退出——用户永远看不到链接,因为代码已过期。这是agent驱动注册失败的首要原因。需按以下方式处理:
DISPLAYrailway uprailway login- 首选方式——后台执行(当agent环境支持后台命令和输出轮询时):
- 在后台启动命令。
- 轮询其输出。一旦出现登录块(新版本CLI显示,旧版本显示
Sign in with one click: <url>/Sign in at: <url>),立即停止所有操作并将内容原封不动转发给用户——请勿总结、缩短或延迟。若存在一键链接则优先使用;否则同时转发URL和代码。告知用户立即打开链接。Enter this code: <code> - 保持命令运行并继续轮询。当用户完成登录后,同一进程会获取会话并继续完成部署。然后根据部署规则验证结果。
- 无后台支持——设置预期,使用最长超时:
- 运行前告知用户:“这会打印一个登录链接——我一获取到就会展示给你。请尽快完成登录;代码10分钟后过期。”
- 使用harness允许的最长超时运行命令。
- 若命令在用户完成登录前超时或被终止,打印的代码不再被监控——延迟点击无效。仍需转发出现的链接供用户参考,然后立即重新运行命令并转发新的链接,告知用户始终使用最新的链接。
- 绝对不要在命令完成前静默等待再展示链接,也不要在未转发链接和给用户操作机会前就报告登录失败。
浏览器传输无需上述操作——CLI会直接在用户机器上打开浏览器。
JSON/CI模式不会自动提示:和不会为未认证用户打开浏览器。会输出结构化错误:
railway up --jsonrailway up --ci--jsonjson
{"error":"Not signed in.","code":"NOT_AUTHENTICATED","hint":"Run `railway login` to authenticate, then re-run."}当看到时,使用认证用户,然后重试原命令。
code: NOT_AUTHENTICATEDrailway login完全无人值守(无用户操作):设置(账户范围)或(项目范围),而非运行交互式登录。无令牌且无用户操作的全新用户无法完成注册——无头账户创建路径不存在。
RAILWAY_API_TOKENRAILWAY_TOKENAgent tooling
Agent工具
Use direct Railway CLI commands for deterministic operations. Use only when the user explicitly asks for Railway Agent, wants a natural-language investigation, or the task is broader than a single resource operation.
railway agentSet up Railway skills, MCP, and authentication with:
bash
railway setup agent
railway setup agent -y
railway setup agent --remoterailway setup agent -yrailway loginInstall or update MCP and skills directly when the user names a target tool:
bash
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 cursorSupported targets include , , , , , and . The flag configures instead of a local stdio server.
claude-codecursorcodexopencodecopilotfactory-droid--remotehttps://mcp.railway.comrailway mcpUse Railway Agent chat with:
bash
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 agentrailway loginRAILWAY_TOKENrailway upgrade --yes确定性操作使用直接的Railway CLI命令。仅当用户明确要求使用Railway Agent、需要自然语言调查或任务范围超出单个资源操作时,才使用。
railway agent使用以下命令设置Railway技能、MCP和认证:
bash
railway setup agent
railway setup agent -y
railway setup agent --remoterailway setup agent -yrailway login当用户指定目标工具时,直接安装或更新MCP和技能:
bash
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支持的目标包括、、、、和。标志会配置而非本地标准输入输出服务器。
claude-codecursorcodexopencodecopilotfactory-droid--remotehttps://mcp.railway.comrailway mcp使用以下命令进行Railway Agent聊天:
bash
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 agentrailway loginRAILWAY_TOKENrailway upgrade --yesCommon 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:
bash
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以下操作频率较高,无需加载参考文档即可处理。当任务为平台范围且对应MCP工具可用时,使用匹配的MCP工具;否则使用CLI:
bash
railway status --json # 当前上下文
railway whoami --json # 认证和Workspace信息
railway project list --json # 列出项目
railway service list --json # 当前环境中的服务(重试`add`前验证)
railway add --database <type> --json # 添加数据库;必须传递--json
railway add --service <name> --json # 添加空服务;必须传递--json
railway variable list --service <svc> --json # 列出变量
railway variable set KEY=value --service <svc> # 设置变量
railway logs --service <svc> --lines 200 --json # 近期日志
railway metrics --service <svc> --since 1h --json # 资源和HTTP指标摘要
railway up --detach -m "<summary>" # 部署当前目录(返回QUEUED状态——报告前需验证)
railway deployment list --json # 分离式部署后轮询最新部署状态
railway bucket list --json # 列出当前环境中的Bucket
railway bucket info --bucket <name> --json # Bucket存储和对象数量
railway bucket credentials --bucket <name> --json # 兼容S3的凭证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.
| Intent | Reference | Use for |
|---|---|---|
| Analyze a database ("analyze <url>", "analyze db", "analyze database", "analyze service", "introspect", "check my postgres/redis/mysql/mongo") | analyze-db.md | Database 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 resources | setup.md | Projects, services, databases, buckets, templates, workspaces |
| Ship code or manage releases | deploy.md | Deploy, redeploy, restart, build config, monorepo, Dockerfile |
| Change configuration | configure.md | Environments, variables, config patches, domains, networking |
| Check health or debug failures | operate.md | Status, 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.md | Create/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 community | request.md | Railway 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.
对于快速操作之外的任务,加载与用户意图匹配的参考文档。仅加载所需内容,通常一个参考文档足够,最多两个。
| 意图 | 参考文档 | 适用场景 |
|---|---|---|
| 分析数据库(“analyze <url>”、“analyze db”、“analyze database”、“analyze service”、“introspect”、“check my postgres/redis/mysql/mongo”) | analyze-db.md | 数据库自省和性能分析。analyze-db.md会引导你使用数据库特定的参考文档。当提供指向数据库服务的Railway URL并伴随“analyze”时,此路由优先级高于状态/操作路由。 |
| 创建或连接资源 | setup.md | 项目、服务、数据库、Bucket、模板、Workspace |
| 部署代码或管理版本 | deploy.md | 部署、重新部署、重启、构建配置、单仓库多项目、Dockerfile |
| 修改配置 | configure.md | 环境、变量、配置补丁、域名、网络 |
| 检查健康状态或排查故障 | operate.md | 状态、日志、指标、构建/运行时分类、恢复 |
| 使用沙盒或远程构建(“sandbox”、“scratch environment”、“ephemeral box”、“build remotely”、“remote build”、“run this remotely”) | sandbox.md | 创建/复刻沙盒、远程运行命令、远程模板构建、端口转发、销毁。需在Priority Boarding中启用沙盒功能——若不可用,提示用户启用。 |
| 请求API、文档或社区支持 | request.md | Railway GraphQL API查询/变更、指标查询、Central Station、官方文档 |
若请求涉及两个领域(例如“部署后检查是否健康”),加载两个参考文档并组合成一个响应。
Execution rules
执行规则
- Use Railway MCP for platform operations that match an available MCP tool.
- Use the local CLI for workflows that need the current repo, local shell, SSH, database scripts, or unsupported MCP coverage.
- Fall back to for operations neither MCP nor CLI exposes.
scripts/railway-api.sh - Use output where available for reliable parsing.
--json - Resolve context before mutation. Know which project, environment, and service you're acting on.
- For destructive actions (delete service, remove deployment, drop database), confirm intent and state impact before executing.
- After mutations, verify the result with a read-back command or MCP read.
- Never report a deploy as successful without observing a terminal SUCCESS. returning (it prints "Build queued") and a streaming
railway up --detachcut off by a shell timeout only confirm the build started. Pollrailway upuntil the newest deployment'srailway deployment list --jsonisstatus(report deployed), orSUCCESS/FAILED(triage per operate.md — do not claim success). A streamingCRASHEDthat exits on its own is authoritative: exit 0 = deployed, exit 1 = failed.up
- 对于匹配可用MCP工具的平台操作,使用Railway MCP。
- 对于需要当前代码仓库、本地shell、SSH、数据库脚本或MCP未覆盖场景的工作流,使用本地CLI。
- 对于MCP和CLI均未暴露的操作,回退到。
scripts/railway-api.sh - 尽可能使用输出以确保解析可靠。
--json - 执行变更前解析上下文,明确操作的Project、Environment和Service。
- 对于破坏性操作(删除服务、移除部署、删除数据库),执行前确认意图和状态影响。
- 变更后,通过读取命令或MCP读取操作验证结果。
- 未观察到终端SUCCESS状态前,请勿报告部署成功。返回(打印“Build queued”)和因shell超时中断的流式
railway up --detach仅能确认构建已启动。需轮询railway up直到最新部署的railway deployment list --json为status(报告部署完成),或SUCCESS/FAILED(根据operate.md进行分类——请勿声称成功)。流式CRASHED自行退出时具有权威性:退出码0=部署成功,退出码1=部署失败。up
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.
| Command | Why user-only |
|---|---|
| Modifies shared_preload_libraries, may restart database |
| Installs database extension |
| Removes database extension |
| Changes PostgreSQL configuration |
| Removes database extension |
| Installs database extension |
When these operations are needed:
- Explain what the command does and any side effects (e.g., restart required)
- Show the exact command the user must run
- Wait for user confirmation that they ran it
- Verify the result with a read-only query
以下命令会修改数据库状态,需用户在自己的终端中直接运行。请勿使用Bash执行这些命令。应展示命令并要求用户自行运行。
| 命令 | 需用户自行运行的原因 |
|---|---|
| 修改shared_preload_libraries,可能导致数据库重启 |
| 安装数据库扩展 |
| 移除数据库扩展 |
| 修改PostgreSQL配置 |
| 移除数据库扩展 |
| 安装数据库扩展 |
当需要执行这些操作时:
- 解释命令的作用和任何副作用(例如,需要重启)
- 展示用户必须运行的精确命令
- 等待用户确认已运行命令
- 通过只读查询验证结果
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.
多步骤工作流遵循自然链式流程:
- 添加对象存储:设置(创建Bucket)、设置(获取凭证)、配置(在应用服务中设置S3变量)
- 首次部署:设置(创建项目+服务)、配置(设置变量和源码)、部署、操作(验证健康状态)
- 修复故障:操作(分类日志)、配置(修复配置/变量)、部署(重新部署)、操作(验证恢复)
- 添加域名:配置(添加域名+设置端口)、操作(验证DNS和服务健康状态)
- 从文档到操作:请求(获取文档答案)、路由到相关操作参考文档
组合流程时,返回包含所有步骤的统一响应。请勿要求用户单独调用每个步骤。
Setup decision flow
设置决策流程
When the user wants to create or deploy something, determine the right action from current context:
- If the intent is deploy-from-cwd or signup-from-cwd, skip and run
railway whoami(orrailway up) 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, runrailway up -y; if it fails with an auth error the user has no token — route through Account creation & sign-in.railway whoami --json - Run in the current directory.
railway status --json - If linked: add a service to the existing project (). Do not create a new project unless the user explicitly says "new project" or "separate project".
railway add --service <name> - 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 to the sub-app path.
rootDirectory - Parent not linked: run and look for a project matching the directory name.
railway list --json- Match found: link to it ().
railway link --project <name> - No match: create a new project ().
railway init --name <name>
- Match found: link to it (
- Parent linked: this is likely a monorepo sub-app. Add a service and set
- 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.
当用户想要创建或部署内容时,根据当前上下文确定正确操作:
- 若意图为从当前目录部署或从当前目录注册,跳过并直接运行
railway whoami(或railway up),遵循基于意图的路由——它会一步完成注册、项目创建、服务创建和部署。对于需要先获取Workspace/账户上下文的其他设置流程,运行railway up -y;若因认证错误失败,说明用户无令牌——引导至账户创建与登录。railway whoami --json - 在当前目录运行。
railway status --json - 已关联:向现有项目添加服务()。除非用户明确表示“new project”或“separate project”,否则请勿创建新项目。
railway add --service <name> - 未关联:检查父目录()。
cd .. && railway status --json- 父目录已关联:这可能是单仓库多项目的子应用。添加服务并设置为子应用路径。
rootDirectory - 父目录未关联:运行并查找与目录名称匹配的项目。
railway list --json- 找到匹配项:关联该项目()。
railway link --project <name> - 无匹配项:创建新项目()。
railway init --name <name>
- 找到匹配项:关联该项目(
- 父目录已关联:这可能是单仓库多项目的子应用。添加服务并设置
- 当存在多个Workspace时,根据中的名称匹配。
railway whoami --json
命名规则:类似“flappy-bird”或“my-api”的应用名称是服务名称,而非项目名称。使用目录或仓库名称作为项目名称。
Response format
响应格式
For all operational responses, return:
- What was done (action and scope).
- The result (IDs, status, key output).
- 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.
对于所有操作响应,需包含:
- 已执行操作(动作和范围)。
- 执行结果(ID、状态、关键输出)。
- 后续操作建议(或任务完成确认)。
保持输出简洁。仅当有助于用户理解操作过程时,才包含命令执行证据。