# Add a JSON Output Flag to a Cobra CLI

Yes. An agent adds an --output json flag to the commands of your Cobra CLI that print lists, keeps the text default, writes tests with fake streams, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-json-output-flag/cobra/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the CLI writes output before it adds a second format, because a JSON mode that leaks log lines into stdout is worse than none. In a CLI laid out like kubernetes-sigs/kind, `go.mod` is module `sigs.k8s.io/kind` on `github.com/spf13/cobra` v1.8.0 with a language floor of Go 1.17, while `.go-version` pins the compiler at 1.27.3. `pkg/cmd/kind/root.go` builds the root command with `SilenceUsage` and `SilenceErrors`, the persistent flags `--verbosity`/`-v` and `--quiet`/`-q`, and `cmd.SetOut(streams.Out)`; every subcommand constructor takes a `log.Logger` and a `cmd.IOStreams`, the three-field struct in `pkg/cmd/iostreams.go` that the comment says exists for embedding and unit testing. The `get` command in `pkg/cmd/kind/get/get.go` groups three subcommands. `get clusters` calls `provider.List()` and writes one name per line with `fmt.Fprintln(streams.Out, cluster)`, and when there are none it logs "No kind clusters found." through the logger rather than stdout. `get nodes` takes `--name`/`-n` and `--all-clusters`/`-A` and prints `node.String()` per node, where the `Node` interface in `pkg/cluster/nodes/types.go` also offers `Role()` and `IP()`. `get kubeconfig` prints a document that is already YAML. `version` prints `DisplayVersion()`, a single line built from the version, `runtime.Version()`, `GOOS` and `GOARCH`.

The flag goes where the commands already share code. The agent adds an `OutputFormat` type and an `AddOutputFlag(flags *pflag.FlagSet)` helper in `pkg/internal/cli`, next to `OverrideDefaultName`, which `get nodes` and `get kubeconfig` already call from their `RunE`. The helper registers `--output`/`-o` with the value `text` by default and `json` as the other choice, and a `Validate()` method returns an error for anything else before any provider call runs, so `kind get clusters -o yaml` fails with a message that names the two values instead of listing clusters and then complaining. `get kubeconfig` and the `create`, `delete`, `load`, `build` and `export` commands are left alone: the first already prints a structured document, and the rest print progress, not data.

Each command's `runE` then branches once, after the data is fetched. `get clusters -o json` encodes `[]string` with `encoding/json` and a trailing newline, and writes `[]` to stdout when there are no clusters while the existing log line still goes to the logger, so a script piping into `jq` never sees prose. `get nodes -o json` encodes a slice of `{"name", "cluster", "role"}` objects; `Role()` is read per node because the plain format never needed it, and the pull request says that this is one extra call per node. `IP()` is left out of the default object and noted as a follow-up, because the interface comment marks it as likely to change. `version -o json` encodes `{"version", "goVersion", "os", "arch"}` from the same values `DisplayVersion()` joins. In every case `text` output is byte-for-byte what it was.

Tests use the seam the code already has. For each changed command the agent writes a `_test.go` beside it, following `pkg/cmd/kind/version/version_test.go`, that builds the command with a `cmd.IOStreams` whose `Out` is a `bytes.Buffer`, runs it with `-o json`, and unmarshals the buffer; the `get` commands take a provider interface in the test so no Docker is needed. It runs `make unit`, which calls `hack/make-rules/test.sh` in `unit` mode with `-short -tags=nointegration` under `gotestsum`, and `hack/make-rules/verify/lint.sh` and the gofmt check, and pastes their tails into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add an --output / -o flag with the values text and json to the commands of this Cobra CLI that print lists or single values: get clusters, get nodes and version. Read go.mod, .go-version, Makefile, pkg/cmd/iostreams.go, pkg/cmd/kind/root.go, pkg/cmd/kind/get/ and pkg/cmd/kind/version/ first. Put the flag type, its registration and its validation in one helper in pkg/internal/cli, reject any other value before doing work, keep the text output exactly as it is, write JSON with encoding/json and a trailing newline to the command's Out stream, print an empty JSON array when there is nothing to list while keeping the existing log line on the logger, and include name, cluster and role for nodes. Leave get kubeconfig and the commands that print progress unchanged. Write unit tests that run each command with a bytes.Buffer as Out and unmarshal the JSON, run make unit and the lint and gofmt verify scripts, and open a pull request with their output. Do not change the Makefile or the workflows.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request touches `pkg/internal/cli` for the new flag helper, `pkg/cmd/kind/get/clusters/clusters.go`, `pkg/cmd/kind/get/nodes/nodes.go` and `pkg/cmd/kind/version/version.go` for the branch each takes, and adds a test file beside each. Its description shows the JSON each command prints for a cluster with one control-plane node, the error for an unknown format, and the tails of `make unit`, the lint script and the gofmt check from the sandbox.

Plain output is unchanged, which the tests assert by running each command with no flag against the same fake streams and comparing to the previous lines. The description points out that `get nodes -o json` makes one `Role()` call per node that the text format never did, and that the workflows in `.github/workflows`, named for Docker, nerdctl, Podman and a VM, are untouched.

Before merging, a reviewer decides whether `IP()` belongs in the node object now or after the interface settles, whether `--output` should also be accepted on `get kubeconfig` for symmetry even though its document is YAML already, and whether the site docs under `site/` should gain a line about the flag.

## Run it on every pull request that adds a subcommand

Once the flag exists, the risk is a new list command that forgets it. An automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a command under pkg/cmd that prints a list to its Out stream, say whether it accepts --output json and, if not, which helper to call and which test to copy" reviews each one. Automation runs are read-only, so the comment is all it posts, and only work by an owner, member or collaborator fires it.

A team with several Go CLIs can send this body once per repository from its own server, each a `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own command tree and decides which commands print data: one built on `urfave/cli` gets the same change against its own flag API, and one that already has a `--format` flag gets JSON added as a value of that flag rather than a second one.

## Why run it on Rush?

The change is small per command and easy to do inconsistently across commands: one branch writes JSON to stdout and keeps a log line on stderr, the next prints both to stdout and breaks the pipe. The agent reads how the CLI separates its streams and its logger first, puts the flag in one helper, and tests each command through the same `IOStreams` seam the code was written with.

The test and lint output stay with the run and are pasted into the pull request, so the review is of code that passed the repository's own checks rather than a diff that looks right. Several CLIs get the same flag at once, each written against its own command tree.

## Frequently asked questions

### Will my scripts that parse the plain output break?

No. Without `--output`, every command prints exactly what it printed before, and the tests compare the text format against the previous lines. JSON is only written when a script asks for it.

### Why not add the flag to every command?

Because most of them print progress, not data, and `get kubeconfig` already prints a structured document. The flag goes on the commands whose output a script would parse, and the pull request names the ones left out and why.

### Does it need Docker to run the tests?

No. The tests build each command with a `bytes.Buffer` as its `Out` stream and a provider stub for the cluster list, and `make unit` runs with `-short` and the `nointegration` tag, so nothing talks to a container runtime.

### Where does the empty-list message go in JSON mode?

To the logger, as it does today, which writes to stderr and is silenced by `--quiet`. Stdout gets `[]`, so a script that runs `kind get clusters -o json | jq length` reads zero rather than a sentence.

## More Cobra jobs

- [Generate Man Pages for a Cobra CLI](https://getrush.ai/run/add-man-page/cobra/)
- [Add an SBOM to the Release of a Cobra CLI](https://getrush.ai/run/add-sbom-to-release/cobra/)
- [Add a --version Flag to a Cobra CLI](https://getrush.ai/run/add-version-flag/cobra/)

## More jobs like this: Hand off a long task

- [Add JSON Output to a Go Command-Line Tool](https://getrush.ai/run/add-json-output/go-cli/)
- [Publish a TypeScript Library to JSR Alongside npm](https://getrush.ai/run/add-jsr-publishing/typescript-library/)
- [Add JWT Authentication to an Actix Web API](https://getrush.ai/run/add-jwt-auth/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
