Crust logoCrust

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:

cli.ts
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.

PathFits
ShellAny coding agent, since every one has a shell; the foundation the others build on
Shell + skillAgents that load skills; the skill saves the discovery calls
MCPClients 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 --json and --help stay on argv.
  • It has the shape schema describes 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's toJSON(), or { "message" } for any other error.
  • Failures before flags are bound, such as an unknown flag, still print Core's plain Error: line; see json() 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):

deploy.ts
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() types outcome.result as the schema's output.
  • Validates: a mismatch at runtime fails with the OUTPUT code 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.

SurfaceWhen 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
SkillsThe same information, installed ahead of time into an agent's skill directory; the agent still runs the CLI
MCPTools 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 prod

Confirmation

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.

CallerResult
--yes, or "yes": true in --inputConfirmed up front
A person on a terminalYes/no prompt; "no" fails
No TTY, or CI setFails 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) awaits ctx.nextSteps and calls .add(command, input, description) with a command definition, as deploy does above.
  • After failure, nextSteps({ onError }) returns recovery commands for errors you recognize with instanceof.

Steps print to stderr as runnable command lines:

$ my-cli deploy staging
Deploying latest to staging
Next steps:
  Watch the rollout:
    my-cli status staging

Prompts 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}`);
		}),
);
  • initial from a flag skips the prompt when the flag is given, on any terminal.
  • An explicit default is returned without asking when there is no TTY. password() has no default.
  • A prompt with neither rejects with NonInteractiveError without 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-1

Crust 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 --input takes, without Extension flags such as help, json, or input.
  • Only the application's own commands are tools; Extension commands such as completion, schema, skills, and api are left out unless include names them.
  • Flags with an env binding are optional tool inputs: a variable set in the client's env configuration 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(), and schema() are registered.
  • Long-running commands yield events.
  • Long-running work passes signal to what it awaits: CI cancellation, agent harnesses, and timeout stop a command with SIGTERM, which aborts the signal and runs cleanup; the process then ends by SIGTERM (shells report 143). Work that ignores it runs until it finishes or a second SIGTERM arrives, and still ends by SIGTERM.
  • Commands that can preview declare a dry-run flag.
  • Commands that change things call confirm()'s ctx.confirm first, 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 initial or a default.
  • Optionally: an MCP server, a packaged skill, and an api command. exclude commands from the MCP server that an agent should not run unattended, and set secrets through env bindings rather than tool arguments.

On this page