# Build a Small CLI Tool

> How to build a small command-line tool that is safe to run, with flags, a dry run, clear errors and exit codes, for your AI interview.

**In short:** A small CLI is a program you run from a terminal with a few typed options. Build it to check its inputs, preview risky steps with a dry run, and end with an exit code that tells the truth.

AI and LLM interview question Q400, Forward Deployed Engineering and applied AI. Beginner, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/build-a-small-cli-tool

## Say it in 30 seconds

A small CLI is a program you run from a terminal with a few typed options. I build one by checking every input before any work starts. Anything that writes or sends gets a dry run first, which prints the plan and changes nothing. Errors go to the error stream, and the program ends with an exit code. Zero means it worked. Any other number means it failed, so whatever runs the job can alert someone.

## Say it in 2 minutes

Picture the tool before you write it. Decide what goes in, what comes out, and what the person running it sees when something goes wrong. For a claims team, the input is a priority level, the output is a list of tickets, and the failure cases are an empty queue or a broken connection. Write those down first, because they become the flags and exit codes.

Next, make it safe to run twice. Anything that writes or sends gets a dry run flag that prints the plan and changes nothing. Check every value before any work starts, so a bad flag stops the run early. Keep keys in environment variables (settings the computer passes in), never in the file, because files get copied.

Then make failure loud. Error messages go to the error stream, and the program ends with an exit code: zero when it worked, any other number when it did not. The scheduler reads that number and decides whether to alert someone. A quiet failure that exits with zero is the worst case, because the claims are missing and nobody knows why.

Finally, test the parser and the exit codes with unittest, and give the help text the same care as the code. The person who runs this at six in the morning is usually a different person from the one who wrote it, so the tool has to explain itself.

## What is a small CLI tool, in plain words?

A CLI, or command-line interface, is a program you run from a terminal. You type its name and a few options, it does one job, prints what it did and says whether it worked. There is no window and no button.

Picture a night-shift records clerk. The ward manager gives them a fixed checklist: the same steps every night, the same kind of input, and a clear yes or no at the end. A good CLI works the same way. It is quiet when all is well and clear when something is wrong.

Here is the real case. A claims support team wants escalated tickets sent to their claims system each morning. An engineer runs a script by hand, once. Two months later a scheduler (the tool that starts a job at set times) runs it every night, and people who never saw the code depend on it. That is when it has to become a proper tool.

- **CLI:** A program you run from a terminal, with typed options.
- **Flag:** An option you type, like --dry-run. It changes what the program does.
- **Dry run:** A preview. The program prints what it would do and changes nothing.
- **Exit code:** A number the program hands back when it ends. Zero means it worked.
- **Error stream:** The separate output (stderr) for error messages, apart from normal output.

## What should a tool check before it does anything?

Three common causes of CLI failures are a bad value nobody checked, a risky step with no preview, and a failure that looks like a success. Design against all three before you write the job itself.

- **Input: Check it first.** Validate every flag and file path before any work starts. A bad value stops the run with a clear message, and nothing is changed.
- **Action: Preview the risky step.** Anything that writes or sends gets a --dry-run flag. It prints the plan and changes nothing.
- **Outcome: Fail loudly.** A failed run that looks like a success is the worst case. The claims are missing and nobody knows why.

*Diagram, One run of the export tool: One run of the tool, read left to right. A bad flag stops it before any work, and a dry run prints the plan and sends nothing.*
1. You type the command and its flags.
2. Good flags pass on to the dry-run check.
3. Not a dry run: the tickets are sent.
4. A run that sends tickets ends with exit code 0.
5. A dry run that finds tickets also ends with exit code 0, having sent nothing.

The tool we will look at exports escalated tickets from a made-up queue. It has a priority filter and a dry run, and it ends with an exit code.

> **Tip:** Asked how you would build one? Name the failure cases first, then the normal run.

## How do you read the flags and show help?

Python has a built-in module for this called argparse. It reads the flags, checks their types, and builds the help screen from the text you give each flag.

The code below is the whole tool, 29 lines. Save it as export_tickets.py and run it with python3 export_tickets.py --min-priority 2 --dry-run. The output under the code is what it printed.

```python
import argparse
import sys

# Made-up escalation queue: (ticket, priority where 1 is most urgent, owning team, issue)
QUEUE = [
    ("T-2041", 1, "Payments", "Refund stuck after bank timeout"),
    ("T-2042", 3, "Onboarding", "Address change not saved"),
    ("T-2043", 2, "Claims", "Photo upload fails on mobile app"),
    ("T-2044", 1, "Claims", "Claim paid twice, same policy"),
]

def main(argv):
    parser = argparse.ArgumentParser(description="Export escalated support tickets.")
    parser.add_argument("--min-priority", type=int, default=2,
                        help="include tickets up to this priority (1 is most urgent)")
    parser.add_argument("--dry-run", action="store_true",
                        help="show what would be sent, send nothing")
    args = parser.parse_args(argv)
    picked = [t for t in QUEUE if t[1] <= args.min_priority]
    if not picked:
        print("No tickets match, nothing exported.", file=sys.stderr)
        return 1
    verb = "would send" if args.dry_run else "sent"
    for ticket, priority, team, issue in picked:
        print(f"{verb} {ticket} (P{priority}) to {team}: {issue}")
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
```

Output:

```text
would send T-2041 (P1) to Payments: Refund stuck after bank timeout
would send T-2043 (P2) to Claims: Photo upload fails on mobile app
would send T-2044 (P1) to Claims: Claim paid twice, same policy
```

A flag with a bad value stops before any work. The argparse module also generates help for you, so running the command with --help shows the manual for free. Each flag's help text is what your teammate reads at night, so write it in plain words.

Bigger tools split their work into subcommands. The Python docs use the svn program as an example, with checkout and commit as its subcommands, and each subcommand has its own flags.

## How do exit codes and error messages work?

When a program ends, it hands the system one number. Python's sys.exit does this. Passing it any other object, such as a message, prints that message to the error stream, and the exit code becomes 1.

> "If it is an integer, zero is considered "successful termination" and any nonzero value is considered "abnormal termination" by shells and the like." (Python documentation, sys.exit)
>
> "Unix programs generally use 2 for command line syntax errors and 1 for all other kinds of errors." (Python documentation, sys.exit)

The number is the handoff. A scheduler, or a CI pipeline (the automatic build and test runner), reads it and decides whether the job passed or needs a person. A program that prints done and exits with zero after half its tickets failed has broken that handoff.

*Diagram, What the scheduler does with the exit code: The tool reports one number when it finishes. The scheduler reads that number and decides whether the run passed or needs a person.*
1. The tool finishes and hands over one number.
2. Zero: the scheduler marks the run as done.
3. Any other number: the scheduler can alert the support lead.

Errors go to the error stream, and the exit code tells the truth.

### How would you ship this tool to a team that didn't write it?

A forward deployed engineer, someone who builds small tools inside a customer's team, would ship this to a claims team. The team will run it every night and never open the code, so the tool has to explain itself.

1. **Write the help text for a tired reader:** Say what each flag does in plain words. The help screen is the manual they will use at six in the morning.
2. **Test the parser and the exit codes:** Write tests that run the tool with a bad flag and with an empty queue. Python's unittest module, from the standard library, runs them.
3. **Keep keys out of the code:** Read the API key, the password a service gives your program, from an environment variable (a setting the computer passes in) or a secret store (a locked vault for passwords). Never type it into a file in the project.
4. **Dry run for the first week:** Run with --dry-run until the output matches what the team expects, then turn the sending on.
5. **Name who gets the alert:** Write down who is told when the exit code is not zero, and what they should do first.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: a program you run from a terminal, with typed options.
- [ ] Check the inputs first, and stop before any work when they are wrong.
- [ ] A dry run for anything that writes or sends.
- [ ] Errors to the error stream, and an exit code that tells the truth.
- [ ] Help text and tests, so someone else can run the tool.
- [ ] Keys from the environment, never typed into the code.

**Common traps**

- Trap: "Print a message and carry on when something fails." Better: Exit with a non-zero code. Otherwise the scheduler thinks the run worked.
- Trap: "I will hardcode the API key to save time." Better: Read it from the environment. A key in the code ends up in every copy of the file.
- Trap: "It works on my laptop, so it is done." Better: Run it the way the team will: from the scheduler, with the real flags, and check the exit code.

## Can you spot the problem?

**Spot the problem:** Which line, if someone added it to a claims export tool, would hide a failure from the scheduler?

A. parser.add_argument("--dry-run", action="store_true")
B. print("No tickets match, nothing exported.", file=sys.stderr)
C. except Exception: pass  # a failed send is ignored
D. sys.exit(main(sys.argv[1:]))

**Answer:** C. The except line swallows the error, so the run carries on and ends with exit code 0. Let the error reach the top, print it to the error stream, and return 1, so the scheduler can alert someone.

**Quick check:** A nightly export must alert the support lead when it fails. Which design does that?

A. Print a yellow warning and keep the exit code at 0
B. Return exit code 1 on failure, and let the scheduler alert
C. Catch every error and return an empty list
D. Send errors to normal output, mixed in with the ticket rows

**Answer:** B. The scheduler reads the exit code and can alert on it. A printed warning is easy to miss, and an exit code of 0 looks like a success.

## Can you answer these from memory?

**Flash cards**

- **What is a CLI?** A program you run from a terminal with a few typed options.
- **What does --dry-run do?** Prints the plan and changes nothing. Use it before any run that writes or sends.
- **What does exit code 0 mean?** The run worked. Any other number means it did not.
- **Where do error messages go?** The error stream (stderr), kept apart from normal output.
- **Who writes the help screen?** argparse builds it from the help text you give each flag.
- **Where do API keys go?** In environment variables or a secret store, never in the code.

## Likely follow-up questions

- Q399 Parse a messy CSV/JSON file with edge cases. https://designervenkat.online/interview/ai/parse-a-messy-csv-json-file-with-edge-cases
- Q397 Take-home: a document agent with retrieval and tools. https://designervenkat.online/interview/ai/take-home-a-document-agent-with-retrieval-and-tools
- Q398 Take-home: messy data → records, with low-confidence flags. https://designervenkat.online/interview/ai/take-home-messy-data-records-with-low-confidence-flags
- Q401 Re-engineering round: fix bugs in unfamiliar code. https://designervenkat.online/interview/ai/re-engineering-round-fix-bugs-in-unfamiliar-code
- Q402 Learning round: pick up a new codebase or API fast. https://designervenkat.online/interview/ai/learning-round-pick-up-a-new-codebase-or-api-fast
