Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Python CLI to Automatically Fix Broken Internal Markdown Links Using Claude 3.5 Sonnet

Tired of broken relative links in your documentation? Stop fixing them manually. Here is how to build a smart Python CLI tool that uses Claude 3.5 Sonnet to scan, resolve, and repair broken markdown links instantly.

Updated 11/13/2026

We have all been there. You are refactoring a documentation directory, moving files around to make things look tidy, and suddenly half of your relative markdown links are completely shattered. Standard markdown link checkers are great at pointing fingers and telling you that ../getting-started/setup.md is broken, but they leave the tedious work of finding the new path and updating the file entirely to you.

Fuzzy matching can help, but it quickly falls apart when files are renamed or split into multiple pages. To solve this properly, you need a tool that understands the semantic intent of the link and the overall structure of your project.

In this tutorial, we will build a local Python CLI tool that scans a directory, identifies broken internal markdown links, maps your project layout, and uses Claude 3.5 Sonnet to automatically rewrite the broken links with their correct paths.

Let’s see what makes this tool tick.

The Architecture of an Intelligent Link Repairer

Our Python CLI will operate in four distinct phases:

  1. Scan: Crawl a target directory to find all .md files and extract every internal relative link.
  2. Verify: Check which of those links point to non-existent files.
  3. Map: Create a complete, lightweight index of your workspace's valid markdown files.
  4. Repair: Pass the broken link's context, the source file's location, and the workspace map to Claude 3.5 Sonnet. The model will determine the correct relative path, and our script will overwrite the broken markdown in place.

By leveraging the structured prompt techniques we often write about, we can ensure Sonnet returns only the corrected relative path without any conversational fluff, allowing us to edit files safely and programmatically.

Set up your AI once so you repeat yourself less.

Tickd is independent and not affiliated with any AI company.

Try AI Setup Profile

Prerequisites and Setup

Before writing any code, ensure you have Python 3.8+ installed and an active Anthropic API key.

Install the necessary dependencies:

`bash pip install anthropic click `

Next, set your API key as an environment variable:

`bash export ANTHROPIC_API_KEY="your-api-key-here" `

If you run into connection errors or issues with key authentication during setup, you can check our Claude troubleshooting hub for solutions to common API client issues.

Step 1: Parsing and Verifying Links

First, we need to extract markdown links. We are looking for standard markdown links like [Link Text](path/to/file.md). We want to ignore external web URLs (e.g., https://...) and anchor-only links (e.g., #installation).

Create a file named repair_links.py. Let's write the core parsing logic:

`python import os import re from pathlib import Path

Regex to capture [Text](Relative Path) LINK_REGEX = re.compile(r'\[([^\]]+)\]\(([^\)]+)\)')

def is_external_or_anchor(link_path: str) -> bool: return ( link_path.startswith("http://") or link_path.startswith("https://") or link_path.startswith("#") )

def find_broken_links(base_dir: Path): broken_links = [] # Walk the directory to index all existing markdown files valid_files = {p.resolve() for p in base_dir.rglob("*.md")} for md_file in base_dir.rglob("*.md"): content = md_file.read_text(encoding="utf-8") matches = LINK_REGEX.findall(content) for text, link_path in matches: if is_external_or_anchor(link_path): continue # Clean up query params or hashes from the internal link clean_path = link_path.split("#")[0].split("?")[0] if not clean_path: continue # Resolve the relative path against the source file's directory target_path = (md_file.parent / clean_path).resolve() if target_path not in valid_files: broken_links.append({ "source_file": md_file, "original_link": link_path, "text": text }) return broken_links, list(valid_files) `

Step 2: Designing the Claude Repair Prompt

When a link is broken, we want to ask Sonnet to look at our workspace structure and find the correct file. To do this reliably, we must provide Claude with: 1. The path of the file containing the broken link (so it can calculate a correct relative path). 2. The broken link text and the invalid path. 3. A full list of all valid file paths in the workspace.

Here is how we structure the prompt to guarantee deterministic, parseable output from Claude without needing heavy JSON schemas or complex post-processing. We will instruct the model to return only the new relative path inside custom XML tags.

`python def build_repair_prompt(source_file: Path, broken_link: str, link_text: str, workspace_files: list[Path]) -> str: relative_workspace = [str(f.relative_to(source_file.parent)) for f in workspace_files] workspace_tree = "\n".join(relative_workspace) return f"""You are an expert developer tool specialising in fixing documentation link drift.

Context: - We have a markdown file located at: {source_file} - Inside this file, there is a broken internal link: [{link_text}]({broken_link}) - The target path {broken_link} does not exist.

Here is a list of all actual, valid markdown files in the workspace (expressed relative to the directory of {source_file}): <valid_files> {workspace_tree} </valid_files>

Your task is to identify which file from the <valid_files> list is the intended target for the broken link based on the path filename, folders, and link text.

Once you find the correct target file, calculate and return the exact relative path from {source_file.parent} to that target file.

Rules: 1. Your response must contain ONLY the corrected relative path inside <resolved_path> tags. 2. Do not include markdown code blocks, explanations, or introductory text. 3. Example Output: <resolved_path>../installation/cli.md</resolved_path> """ `

Step 3: Integrating the API Call

Now, let's write the function to send this prompt to Claude 3.5 Sonnet and extract the resolved path. If you are unfamiliar with some of the terms used here, our glossary provides quick definitions of key API concepts.

`python import anthropic

def resolve_link_with_claude(client: anthropic.Anthropic, source_file: Path, broken_link: str, link_text: str, workspace_files: list[Path]) -> str | None: prompt = build_repair_prompt(source_file, broken_link, link_text, workspace_files) try: response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=200, temperature=0.0, # Zero temperature ensures deterministic matching system="You are a precise link resolution utility. Output your answer using the requested XML tags and nothing else.", messages=[ {"role": "user", "content": prompt} ] ) content = response.content[0].text.strip() match = re.search(r"<resolved_path>(.*?)</resolved_path>", content) if match: return match.group(1).strip() except Exception as e: print(f"API Error: {e}") return None `

Step 4: Building the CLI and File Writer

With our scanning, prompt generation, and LLM call in place, we will tie everything together with a CLI interface using Python's click library. When a link is resolved, the tool will update the file contents in-place.

`python import click

def apply_fix(file_path: Path, old_link: str, new_link: str): content = file_path.read_text(encoding="utf-8") # We precisely replace the old link path while keeping the link text intact # e.g., Text -> Text escaped_old_link = re.escape(old_link) pattern = f"(?<=\])\({escaped_old_link}\)" fixed_content = re.sub(pattern, f"({new_link})", content) file_path.write_text(fixed_content, encoding="utf-8")

@click.command() @click.argument("directory", type=click.Path(exists=True, file_okay=False, path_type=Path)) @click.option("--dry-run", is_flag=True, help="Scan and suggest fixes without writing them to disk.") def main(directory: Path, dry_run: bool): """Scan and automatically repair broken internal markdown links in the target DIRECTORY.""" api_key = os.environ.get("ANTHROPIC_API_KEY") if not api_key: raise click.ClickException("ANTHROPIC_API_KEY environment variable is not set.") client = anthropic.Anthropic(api_key=api_key) click.echo(f"Scanning '{directory}' for markdown files...") broken, valid_files = find_broken_links(directory) if not broken: click.echo("🎉 No broken links found! Your docs are in pristine condition.") return click.echo(f"Found {len(broken)} broken link(s). Resolving paths using Claude 3.5 Sonnet...") for item in broken: source = item["source_file"] old_link = item["original_link"] text = item["text"] click.echo(f"\nBroken link in: {source.relative_to(directory)}") click.echo(f" ↳ {text}") new_link = resolve_link_with_claude(client, source, old_link, text, valid_files) if new_link: click.echo(f" Suggested Fix: -> ({new_link})") if not dry_run: apply_fix(source, old_link, new_link) click.echo(" Status: Fixed! ", color="green") else: click.echo(" Status: Skipped (Dry Run)") else: click.echo(" Status: Could not resolve link.", color="red")

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

Testing Your New Tool

Let’s test our setup. Create a dummy documentation structure to verify that our link repair utility works accurately:

`bash mkdir -p test_docs/intro test_docs/advanced touch test_docs/intro/getting-started.md touch test_docs/advanced/configuration.md `

Add a broken link to test_docs/intro/getting-started.md that intends to point to the configuration file, but uses an outdated, incorrect path:

`markdown # Getting Started

To configure your environment variables, check out our Configuration Guide. `

Run your script in dry-run mode first to see how Sonnet matches the broken link against your live directory layout:

`bash python repair_links.py ./test_docs --dry-run `

Claude 3.5 Sonnet will analyze the file paths and determine that ../wrong-folder/config.md should be matched with the existing ../advanced/configuration.md relative to our file path. Once confirmed, run the tool without the --dry-run flag to automatically rewrite your markdown file.

By keeping this utility in your local developer toolkit, you can maintain seamless documentation without wasting hours cross-checking folders manually.

pythonclaude-3-5-sonnetautomationdeveloper-workflow

Keep going

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