# Read Typer CLI Options From Environment Variables

Yes. An agent adds envvar settings to a Typer CLI's options so each can come from the environment, keeps flags winning, tests the order and opens a PR.

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

## What the agent does

The agent first lists which settings can already come from the environment, and by what route, because a CLI that mixes routes confuses the people deploying it. In a Typer app like fastapi/fastapi-cli, `src/fastapi_cli/cli.py` defines `dev` and `run`, and in both the `port` parameter is declared with `typer.Option(help=..., envvar="PORT")`. That is the only option Typer itself reads from the environment. A second variable, `FASTAPI_PUBLIC_URL`, is read with `os.getenv` in the body of each command and passed to `_run`, so it works but has no flag and never appears in `--help`. A third, `FASTAPI_ENV`, is written by `dev` with `os.environ.setdefault` for the app to read, and is not an option at all. Everything else a container image would want to set, `--host`, `--workers`, `--root-path`, `--proxy-headers` and `--forwarded-allow-ips`, is flag-only.

Before naming anything it checks what the layer underneath already reads, so no setting ends up with two names. `_run` hands `workers` and `forwarded_allow_ips` to `uvicorn.run` as `None` when no flag was given, and Uvicorn's own `Config` then falls back to `WEB_CONCURRENCY` and `FORWARDED_ALLOW_IPS` from the environment. Those two are left to keep working exactly as they do. For them the agent attaches the same variable name to the Typer option, which changes no behaviour and makes the existing variable show up in the help text. `host` and `root_path` have no such fallback and get new names with the project's `FASTAPI_` prefix, alongside the unprefixed `PORT` that many hosting platforms inject. `FASTAPI_PUBLIC_URL` becomes a real `--public-url` option with that variable attached, so the `os.getenv` calls go away and the value has one source.

Typer's rules for environment values then decide how the tests are written, and the agent confirms each rule by running it. A flag on the command line beats the variable, which beats the default. A value that cannot be parsed, such as a non-numeric `WEB_CONCURRENCY`, exits with a usage error and status 2 before any server starts. Boolean options accept `false` and `0` as off. A list option such as `--reload-dir`, typed `list[Path]`, splits its variable on the operating system's path separator and not on spaces, which is a surprise worth a line in the documentation if it is given a variable. Each option with a variable shows it in `--help` as `[env var: NAME]` next to its default.

The tests extend what is in `tests/test_cli.py`, which already patches `uvicorn.run`, invokes the app through `CliRunner` with `env={"PORT": "8111"}` and asserts on `mock_run.call_args.kwargs`. For every new variable the agent adds the same three cases: variable alone, variable with a contradicting flag, and an invalid value. The file's autouse fixture removes `FASTAPI_ENV` before each test; the agent extends it to clear the new names too, so a developer's shell cannot leak into the suite. It runs `bash scripts/test.sh` and `bash scripts/lint.sh`, which cover `mypy`, `ty` and `ruff`, adds a table of variables to the `fastapi run` section of `README.md` and an entry to `release-notes.md`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Let this Typer CLI read its server options from environment variables. Read pyproject.toml, src/fastapi_cli/cli.py, tests/test_cli.py, tests/conftest.py, README.md, release-notes.md and the scripts directory first. List every environment variable the CLI reads today and how (Typer envvar, os.getenv in a command body, or passed through to Uvicorn), and check Uvicorn's Config for variables it already falls back to, so no setting gets a second name. Then: attach envvar to host, root_path, workers, proxy_headers and forwarded_allow_ips on both dev and run where they exist, reusing WEB_CONCURRENCY and FORWARDED_ALLOW_IPS for the two Uvicorn already reads and a FASTAPI_ prefix for the rest; turn FASTAPI_PUBLIC_URL into a real --public-url option with that envvar and remove the os.getenv calls. Do not change any default or any existing variable's behaviour. Confirm by running them how Typer treats precedence, invalid values, booleans and list options from the environment, and write tests in the existing style (patch uvicorn.run, CliRunner with env=...) for each variable: variable alone, variable overridden by a flag, invalid value. Extend the autouse fixture to clear the new variables. Run scripts/test.sh and scripts/lint.sh, add a table of variables to the README and a release note, and open a pull request.",
  "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

A pull request that touches the option declarations of `dev` and `run` in `src/fastapi_cli/cli.py`, removes two `os.getenv` calls, adds the new test cases and fixture lines in `tests/test_cli.py`, and documents the variables in `README.md` and `release-notes.md`. Its description has one table: each option, its variable, whether the name is new or was already honoured by Uvicorn, and its default. Below it are the `--help` output for `run` with the `[env var: ...]` annotations and the output of the test and lint scripts. The repository's test workflow runs its matrix of operating systems and Python versions on the pull request.

A reviewer weighs the names more than the code, since environment variables are an interface that is hard to rename later. They check that nothing which worked before stops working: `PORT`, `FASTAPI_PUBLIC_URL`, `WEB_CONCURRENCY` and `FORWARDED_ALLOW_IPS` each keep their meaning. They look at the one behaviour that does shift, that an invalid `WEB_CONCURRENCY` is now rejected by Typer with a usage error where Uvicorn previously raised on it, and decide if that is the better failure. And they confirm no boolean was given a variable whose unset and empty states mean different things.

## Run it on every terminal hand-off

The request usually comes from whoever is writing the Dockerfile or the platform manifest and finds they can set the port by variable but not the host. They send this body from the terminal with the repository in `resources` and go on with the deployment work; the answer comes back as a pull request, not as a conversation. Add a `request_id`, a UUID, so a retried start returns the run already begun.

When the turn ends, `GET /o/{org}/sessions/{id}` names the pull request, and the session's sandbox parks with the project installed. A follow-up message to it can ask for one more option to be covered, for the variable table to be moved into the project's main documentation, or for a quick check of how the new variables behave under a specific process manager's environment file, without reinstalling anything.

## Why run it on Rush?

The facts this change rests on are behaviours of two libraries, and they are cheaper to observe than to remember: what Typer does with an unparseable value, how it splits a list, which variables Uvicorn reads on its own. In its own sandbox the agent runs each case against the versions in `uv.lock` and keeps the commands and results in the run's record, so the table in the pull request is backed by observed output for this lockfile, not by documentation for some other release.

It also keeps a deployment-facing change honest about compatibility. The run exercises the old variables before and after the edit with the same test cases, so the claim that nothing existing changed is a test result a reviewer can read. For a tool that many images already start with `PORT` set, that record is the part of the pull request that matters most.

## Frequently asked questions

### Which wins, the flag or the environment variable?

The flag. Typer resolves an option from the command line first, then from its environment variable, then from the default. The new tests assert that order for every option by setting the variable and passing a contradicting flag in the same invocation.

### Will the variables show up in --help?

Yes. Typer annotates each option that has one, in the form `[env var: PORT; default: 8000]`. That is one reason to move `FASTAPI_PUBLIC_URL` from an `os.getenv` call to a real option: today it is invisible in the help output.

### What happens if a variable holds a bad value?

Typer validates it like a flag value. A non-integer where an integer is expected stops the command with a usage error and exit status 2, naming the variable, before the server is started. The pull request lists this for each typed option.

### Why reuse WEB_CONCURRENCY instead of adding FASTAPI_WORKERS?

Uvicorn already reads `WEB_CONCURRENCY` when no worker count is passed, and deployments rely on it. Attaching that same name to the Typer option documents it in the help text without creating a second variable whose precedence against the first would need explaining.

## More Typer jobs

- [Fix a Failing CI Run for a Typer CLI](https://getrush.ai/run/fix-failing-ci/typer/)
- [Review Pull Requests on a Typer CLI](https://getrush.ai/run/review-pull-requests/typer/)
- [Write CLI Tests for a Typer App](https://getrush.ai/run/write-cli-tests/typer/)

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

- [Add Error Boundaries to a React Router App](https://getrush.ai/run/add-error-boundaries/react-router/)
- [Add Error Boundaries to a Vue App](https://getrush.ai/run/add-error-boundaries/vue/)
- [Add Error Handling to a grammY Bot](https://getrush.ai/run/add-error-handling/grammy/)

## 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/)
