Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Local CLI Tool with Claude 3.5 Sonnet to Auto-Fix Failed Terminal Commands

Tired of copying and pasting ugly bash errors into a browser tab? Build a lightweight, local Python wrapper that intercepts terminal failures, gets Claude 3.5 Sonnet to diagnose the issue, and executes the corrected command with a single keystroke.

Updated 11/14/2026

We have all been there. You copy a complex Docker command from a readme, paste it into your terminal, and hit enter, only for it to blow up with a wall of unhelpful red text. Your muscle memory kicks in: you drag your cursor over the terminal history, copy the error, open a browser tab, navigate to an LLM interface, paste the error, write some context, and wait for a fix.

It is tedious, repetitive, and entirely unnecessary.

Instead of wasting time acting as a human clipboard, you can build a lightweight local Python CLI wrapper that does this for you. By wrapping your terminal execution, we can intercept shell failures, capture the exit codes and stderr, send them straight to the API of Claude 3.5 Sonnet, and present a proposed fix that you can execute with a single keystroke.

Here is how to build a local terminal auto-fixer to get your development loop ticking over beautifully.

The Architecture of a Command Wrapper

There are two main ways to build an auto-fixer: analysing your shell's history after a failure, or wrapping command execution. We are going with the wrapper approach (e.g., fix <command>). Why? Because reading shell history across different shells (Zsh, Bash, Fish) is notoriously fragile, and capturing actual system state is much easier when your script spawns the process itself.

Our tool will: 1. Accept any shell command as an argument. 2. Run the command in a subprocess, piping stdout and stderr to your screen in real time. 3. If the command exits with a non-zero code, capture the error output along with local environment clues (OS, shell, current working directory). 4. Package this context into a structured prompt for Claude 3.5 Sonnet. 5. Stream the explanation and the suggested replacement command. 6. Prompt you to execute the fix immediately.

Set up your AI once so you repeat yourself less.

Tickd is independent and not affiliated with any AI company.

Try AI Setup Profile

Step 1: Setting Up the Project

To build this, you will need Python 3.8+ installed, along with an Anthropic API key.

First, create a new directory for your utility and set up a virtual environment:

`bash mkdir terminal-fixer cd terminal-fixer python3 -m venv .venv source .venv/bin/activate pip install anthropic `

Create a file named fix.py. This will house our entire utility. We want to keep dependencies light, so we will use Python's built-in subprocess, os, and sys modules, relying only on the official anthropic library for our AI integration. If you run into any dependency or setup snags with the Anthropic SDK, you can troubleshoot them on our Claude troubleshooting hub.

Step 2: Running Subprocesses and Capturing Disasters

We need to run the target command exactly as if the user typed it directly into their terminal. This means handling interactive outputs and standard streams correctly.

Add the following base structure to fix.py:

`python import os import sys import subprocess from anthropic import Anthropic

def run_command(command): print(f"\033[90mRunning: {command}\033[0m") # Run command through the user's default shell shell = os.environ.get("SHELL", "/bin/bash") # We use subprocess.run and capture output only on failure to keep the screen clean result = subprocess.run( command, shell=True, executable=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Print output so the user still sees what happened if result.stdout: print(result.stdout, end="") if result.stderr: print(result.stderr, file=sys.stderr, end="") return result `

By using subprocess.run with shell=True and specifying the user's current shell, we preserve alias expansion and environment variables. If the command succeeds (exit code 0), our script simply exits. If it fails, we keep the stdout and stderr in memory, ready for Sonnet.

Step 3: Designing the Sonnet Prompt

When a command fails, sending just the error message is rarely enough. Claude needs context: What OS are you running? What is your shell? What directory are you in? Are there specific files nearby?

To keep our prompts structured and avoid bloated, conversational responses, we will use XML tags. (If you want to master this prompt style, check out our guide on writing structured inputs at our prompt generator and technique resource).

Here is how we will structure the prompt builder in fix.py:

`python def get_fix_from_llm(command, stdout, stderr): client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")) os_name = sys.platform shell_name = os.environ.get("SHELL", "unknown").split("/")[-1] cwd = os.getcwd() directory_contents = ", ".join(os.listdir(cwd)[:20]) # Limit to first 20 files for token safety system_prompt = ( "You are an expert systems administrator and developer assistant. " "Your job is to diagnose failed terminal commands and provide a single, exact " "working replacement command, along with a brutally concise, one-sentence explanation of what went wrong." ) user_content = f""" <context> Operating System: {os_name} Shell: {shell_name} Current Directory: {cwd} Files in Directory: {directory_contents} </context> <failed_execution> Command Attempted: {command} STDOUT: {stdout} STDERR: {stderr} </failed_execution> Provide your response in this exact format: REASON: <One-sentence explanation of the failure> FIX: <The absolute, exact corrected command to run. No markdown block styling around this line.> """ response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=300, system=system_prompt, messages=[{"role": "user", "content": user_content}], temperature=0.0 ) return response.content[0].text `

We set temperature to 0.0 here because we do not want creative, hallucinated terminal flags. We want the most deterministic, technically accurate solution possible.

Step 4: The Interactive CLI Loop

Now, we need to stitch the runner and the LLM together. If Claude returns a proposed command, we should show the reasoning, clearly print the fix in a contrasting colour, and ask the user if they want to run it.

`python def main(): if len(sys.argv) < 2: print("Usage: fix <command>") sys.exit(1) # Combine all arguments into a single shell command string target_command = " ".join(sys.argv[1:]) if not os.environ.get("ANTHROPIC_API_KEY"): print("Error: ANTHROPIC_API_KEY environment variable is not set.") sys.exit(1) result = run_command(target_command) if result.returncode != 0: print("\n\033[93m[!] Command failed. Querying Claude 3.5 Sonnet for a fix...\033[0m") try: raw_response = get_fix_from_llm(target_command, result.stdout, result.stderr) # Parse our strict response format lines = raw_response.strip().split("\n") reason = "" proposed_fix = "" for line in lines: if line.startswith("REASON:"): reason = line.replace("REASON:", "").strip() elif line.startswith("FIX:"): proposed_fix = line.replace("FIX:", "").strip() if proposed_fix: print(f"\n\033[96mReason:\033[0m {reason}") print(f"\033[92mProposed Fix:\033[0m \033[1m{proposed_fix}\033[0m\n") confirm = input("Do you want to run this command? [y/N]: ").strip().lower() if confirm in ["y", "yes"]: # Run the suggested fix run_command(proposed_fix) else: print("Aborted.") else: print("Could not extract a clean fix from the model response:") print(raw_response) except Exception as e: print(f"Failed to contact Anthropic API: {e}") sys.exit(1)

if __name__ == "__main__": main() `

Step 5: Testing and Integration

To make this easy to use everywhere, expose it as a global shell alias. Add this to your shell profile (e.g., ~/.zshrc or ~/.bashrc):

`bash alias fix="python3 /path/to/your/terminal-fixer/fix.py" `

Reload your terminal configuration (source ~/.zshrc), make sure your ANTHROPIC_API_KEY is exported, and test it out with a common typo or directory mismatch. For example, try to list a directory that doesn't exist, or run a Docker command with a syntax error:

`bash fix ls --wrong-flag `

You will see the original error, a rapid diagnosis from Claude, and an interactive prompt offering the corrected command.

Keeping It Safe

Executing LLM-generated shell commands carries risks. Sonnet is incredibly capable, but it does not know if a command has unintended destructive consequences in your environment. Always read the Proposed Fix line before hitting y—never run destructive utilities (like rm -rf) proposed by an external API without manual review.

pythonclaude-3-5-sonnetcli-tooldeveloper-workflowterminal

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.