Building CLIs for agents
Make a CLI that coding agents and scripts can drive without guessing.
An agent runs your CLI like a script: it passes argv, reads stdout and stderr, and checks the exit code. It has no TTY for prompts and pays for every token it reads. Give it documented input and output shapes, self-description, and loud failures instead of waiting or guessing.
Each piece below is an opt-in Extension or command declaration. Register the agent-facing Extensions on the root, in any order:
import { Crust } from "@crustjs/core";
// `confirm` and `nextSteps` are imported with `deploy` above.
import { help, input, json, schema } from "@crustjs/extensions";
export const app = new Crust("my-cli", { description: "Deploy releases" })
.extend(help(), input(), json(), schema(), confirm(), nextSteps())
.add(deploy, status, init);The commands used below are in examples/guide/agents.ts.
How agents use your CLI
An agent either runs commands from a shell (argv, --input, --json, exit codes) or calls them as MCP tools. From a shell, it discovers commands with --help, --llms, and schema <path>, or ahead of time from an installed skill.
| Path | Fits |
|---|---|
| Shell | Any coding agent, since every one has a shell; the foundation the others build on |
| Shell + skill | Agents that load skills; the skill saves the discovery calls |
| MCP | Clients that call tools instead of running a shell |
Skills and MCP each add one .extend(). Every path reads the same command snapshot, so a command declared once reaches all of them.
Structured input
input() adds --input: every argument and flag as one JSON object, inline, from a file (@path), or from stdin (-). No quoting or ordering of argv tokens:
$ my-cli deploy --input '{"target":"staging","release":"v2"}'
Deploying v2 to staging
Next steps:
Watch the rollout:
my-cli status staging- The object is converted and validated exactly like argv.
- Arguments and flags given on argv win over its keys.
- It holds the command's own values: Extension flags such as
--jsonand--helpstay on argv. - It has the shape
schemadescribes and the MCP server accepts.
JSON output
Print for people with stdout(text), return the data, and declare .output(). json() adds --json, which prints the action's return value as one line of JSON on stdout; see its contract for printed text. Write live progress, like deploy's Deploying line, with stderr() or a spinner:
$ my-cli deploy staging --json
Deploying latest to staging # stderr
{"target":"staging","release":"latest","dryRun":false} # stdout
Next steps: # stderr, see below
Watch the rollout:
my-cli status staging- Failures become one line of JSON on stderr:
CrustError'stoJSON(), or{ "message" }for any other error. - Failures before flags are bound, such as an unknown flag, still print Core's plain
Error:line; seejson()limitations. - Exit codes don't change, so an agent still checks them first. Make messages actionable; see error handling.
Output schemas and end-to-end types
Declare the result's shape with .output(schema):
import { defineCommand } from "@crustjs/core";
import { confirm, nextSteps } from "@crustjs/extensions";
import { z } from "zod";
const deploy = defineCommand("deploy", { description: "Deploy a release" }, (cmd) =>
cmd
.use(confirm, nextSteps)
.args({ name: "target", type: "string", required: true, choices: ["staging", "prod"] })
.flags({
release: { type: "string", default: "latest", description: "Release to deploy" },
"dry-run": { type: "boolean", description: "Print what would be deployed" },
})
.output(z.object({ target: z.string(), release: z.string(), dryRun: z.boolean() }))
.action(async ({ args, flags, ctx, stdout, stderr }) => {
const { target } = args;
const { release } = flags;
// Preview before confirming, so a dry run never prompts.
if (flags["dry-run"]) {
stdout(`Would deploy ${release} to ${target}`);
return { target, release, dryRun: true };
}
if (target === "prod") {
const ask = await ctx.confirm;
await ask(`Deploy ${release} to prod?`);
}
// stderr() stays live under --json, where the result replaces stdout() text.
stderr(`Deploying ${release} to ${target}`);
const steps = await ctx.nextSteps;
steps.add(status, { args: { target } }, "Watch the rollout");
return { target, release, dryRun: false };
}),
);One declaration:
- Types: TypeScript checks the action's return value, and
app.run()typesoutcome.resultas the schema's output. - Validates: a mismatch at runtime fails with the
OUTPUTcode instead of printing a wrong shape. - Documents: when the schema library can produce JSON Schema, it reaches
schema, MCP, and skills.
Streaming
Report progress as data by writing the action as an async generator: each yield is an event and the return value is the result.
const status = defineCommand("status", { description: "Watch a rollout" }, (cmd) =>
cmd
.args({ name: "target", type: "string", required: true })
.action(async function* ({ args, stdout }) {
for (const step of ["build", "ship"]) {
stdout(`${step}: done`);
yield { step };
}
return { target: args.target, healthy: true };
}),
);People see only what the action writes. With --json, json() streams NDJSON that ends with one result or error line:
$ my-cli status prod --json
{"type":"event","data":{"step":"build"}}
{"type":"event","data":{"step":"ship"}}
{"type":"result","data":{"target":"prod","healthy":true}}A cancelled invocation (exit code 130, or 143 after SIGTERM), or a failure another Extension's onError hook claims, ends the stream without that last line (json() limitations). Check the exit status rather than waiting for it.
The same events reach run()'s onEvent callback. Under MCP, each yield sends a progress notification when the client asks for progress: it carries a count, and a string event becomes its message.
Discovery
An agent learns a CLI from what it prints about itself. Write descriptions for commands, arguments, and flags: every surface below reads them.
| Surface | When it fits |
|---|---|
--help from help() | One command, for people and agents |
--llms from schema() | The whole CLI in compact Markdown, documentation sections included; an agent's first call |
schema <path> from schema() | One command's input and output JSON Schema, before building --input or parsing --json, or for code generation |
| Skills | The same information, installed ahead of time into an agent's skill directory; the agent still runs the CLI |
| MCP | Tools for clients that call tools instead of a shell, with the same input schema and, where MCP can carry it, output schema |
All of them read the same command snapshot (descriptions, arguments and flags, .output(), sections).
$ my-cli schema deploy
{"input":{"type":"object","properties":{"target":{"type":"string","enum":["staging","prod"]},…},"required":["target"]},"output":{…}}json() and input() add "JSON output" and "JSON input" sections to root help. Document your own conventions, such as exit codes and environment variables, with documentation sections.
Dry run
A command that can preview declares its own dry-run flag and returns the preview before asking for confirmation, as deploy does above, so a dry run never prompts. Commands without the flag reject --dry-run as unknown instead of running for real:
$ my-cli deploy prod --dry-run
Would deploy latest to prodConfirmation
Ask before a change that is hard to undo, without stalling an agent. With confirm(), a command calls .use(confirm), awaits ctx.confirm for the function, and awaits that with a message before the change, as deploy does for prod.
| Caller | Result |
|---|---|
--yes, or "yes": true in --input | Confirmed up front |
| A person on a terminal | Yes/no prompt; "no" fails |
No TTY, or CI set | Fails with ConfirmationRequiredError |
On reusable commands, only those that .use(confirm) accept --yes; see where --yes is accepted. CI counts as set unless it is empty, 0, or false in any letter case, because a CI job can run on a pseudo-terminal nobody answers.
$ my-cli deploy prod < /dev/null
Error: Confirmation required: Deploy latest to prod? Pass --yes to confirm.
$ my-cli deploy prod --yes
Deploying latest to prod
Next steps:
Watch the rollout:
my-cli status prod.use(confirm) and .use(nextSteps) take the Extension itself, which uses the Contexts it provides; the app must .extend() it.
Next steps
Tell the agent what to run next. With nextSteps():
- After success, a command that
.use(nextSteps)awaitsctx.nextStepsand calls.add(command, input, description)with a command definition, asdeploydoes above. - After failure,
nextSteps({ onError })returns recovery commands for errors you recognize withinstanceof.
Steps print to stderr as runnable command lines:
$ my-cli deploy staging
Deploying latest to staging
Next steps:
Watch the rollout:
my-cli status stagingPrompts without a TTY
A prompt waits for an answer an agent can't give. Make every prompt answerable from the command line, and fail otherwise:
import { input as prompt } from "@crustjs/prompts";
const init = defineCommand("init", { description: "Create a project" }, (cmd) =>
cmd
.flags({ name: { type: "string", description: "Project name" } })
.action(async ({ flags, stdout }) => {
const name = await prompt({ message: "Project name?", initial: flags.name });
const region = await prompt({ message: "Region?", default: "us-east-1" });
stdout(`Created ${name} in ${region}`);
}),
);initialfrom a flag skips the prompt when the flag is given, on any terminal.- An explicit
defaultis returned without asking when there is no TTY.password()has nodefault. - A prompt with neither rejects with
NonInteractiveErrorwithout a TTY, so the command fails instead of hanging:
$ my-cli init < /dev/null
Error: Prompts require an interactive terminal (TTY).
$ my-cli init --name demo < /dev/null
Created demo in us-east-1Crust doesn't detect agents or add a global --no-input: the TTY check is the rule. confirm() also refuses under CI, as above.
MCP
@crustjs/mcp serves your commands as MCP tools with <cli> mcp.
- Each tool's input schema is the flat object
--inputtakes, without Extension flags such ashelp,json, orinput. - Only the application's own commands are tools; Extension commands such as
completion,schema,skills, andapiare left out unlessincludenames them. - Flags with an
envbinding are optional tool inputs: a variable set in the client'senvconfiguration reaches the server, as it would reach the CLI in a shell. .output()schemas and generator events become the tool's output schema and progress notifications.- What a call writes to stderr, next steps included, follows its result in the tool result.
Skills
@crustjs/skills renders an agent skill from your commands at build time, with output schemas, and adds a skills command that installs it into agents' skill directories.
The api command
For a CLI backed by an HTTP API, @crustjs/openapi adds a gh api-style api command: an agent can list and read the bundled OpenAPI document offline and call endpoints your commands don't wrap yet, with your CLI's base URL and auth.
With json() registered, api --list --json, api --spec <operationId> --json, and api <path> --json print JSON data on stdout: the operations, the definition with its method, path, and parameters, or the parsed response body. A non-2xx response fails with the HTTP status in the error JSON's details; see JSON output.
Checklist
- Every command, argument, and flag has a
description. - Results are returned, not only printed.
- Every command that returns data declares
.output(): typed, validated, discoverable, and no duplicate text under--json. json(),input(), andschema()are registered.- Long-running commands yield events.
- Long-running work passes
signalto what it awaits: CI cancellation, agent harnesses, andtimeoutstop a command withSIGTERM, which aborts thesignaland runs cleanup; the process then ends bySIGTERM(shells report 143). Work that ignores it runs until it finishes or a secondSIGTERMarrives, and still ends bySIGTERM. - Commands that can preview declare a
dry-runflag. - Commands that change things call
confirm()'sctx.confirmfirst, after any dry-run preview. - Error messages say what to do next; known failures have recovery steps from
nextSteps(). - Every prompt has a flag for
initialor adefault. - Optionally: an MCP server, a packaged skill, and an
apicommand.excludecommands from the MCP server that an agent should not run unattended, and set secrets throughenvbindings rather than tool arguments.