Python Filename Sanitization with Fallback

Python Filename Sanitization with Fallback is a skill for Claude Code, Codex from ngpestelos/readwise-mcp-server. It costs 38 tokens per session (3,178 once invoked), scanned A, original, MIT.

A Python pattern for turning user-provided titles into valid filenames, including a fallback when a title contains no letters or numbers. It addresses cases such as emoji-only, punctuation-only, blank, or whitespace-only titles.

In plain words
What is it for?
Use it when generating filenames from titles, especially for saved documents, notes, or indexed files that may contain unusual or empty names.
Why use it?
Basic cleanup can still leave filenames that file systems or indexing tools reject. This pattern ensures the result remains usable for saving and indexing.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/ngpestelos/readwise-mcp-server/python-filename-sanitization-fallback
Any agent
npx skills add ngpestelos/readwise-mcp-server --skill python-filename-sanitization-fallback
Clone the repo
git clone --depth 1 https://github.com/ngpestelos/readwise-mcp-server

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for Python Filename Sanitization with Fallback

README.md
[![agentmods](https://agentmods.dev/badge/skills/ngpestelos/readwise-mcp-server/python-filename-sanitization-fallback.svg)](https://agentmods.dev/skills/ngpestelos/readwise-mcp-server/python-filename-sanitization-fallback)
Your own site
<a href="https://agentmods.dev/skills/ngpestelos/readwise-mcp-server/python-filename-sanitization-fallback"><img src="https://agentmods.dev/badge/skills/ngpestelos/readwise-mcp-server/python-filename-sanitization-fallback.svg" alt="Measured on agentmods" height="20"></a>
Per session 38 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,178 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00038 $0.03178
Opus 5 $0.00019 $0.01589
Sonnet 5 $0.00008 $0.00636
Haiku 4.5 $0.00004 $0.00318

Measured 4d ago against content hash 1e76ddb96b54, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

Python Filename Sanitization with Fallback scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.claude/skills/python-filename-sanitization-fallback/SKILL.md · 379 lines

How it starts

The opening of the file, as written. The whole thing — 379 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python Filename Sanitization with Fallback

Purpose

This skill provides expertise in implementing robust filename sanitization that goes beyond removing invalid characters to ensure the resulting filename meets downstream validation requirements. It addresses the critical gap where user-provided titles containing only special characters (emoji, ellipsis, whitespace) produce invalid filenames after standard sanitization.

Core Problem

Conventional Approach Limitation: Standard filename sanitization only removes invalid filesystem characters:

# Incomplete sanitization - can produce invalid names
filename = title.replace('/', '-').replace(':', ' -')
filename = re.sub(r'[<>"\\\|?*]', '', filename)

Real-World Failure Cases (from Readwise MCP Server, 2026-01-24):

  • Title: "…" → Filename: "….md" → qmd indexer error
  • Title: "🍿🍿" → Filename: "🍿🍿.md" → qmd indexer error
  • Title: "" → Filename: ".md" → qmd indexer error

Root Issue: Many indexers and tools require filenames to contain at least one alphanumeric character (/[\p{L}\p{N}]/u). Titles with only special characters fail this validation.

The Validation-Aware Pattern

Core Principle

Validate output, not just transform input. After sanitization, verify the filename meets downstream requirements; fallback to metadata-based naming when validation fails.

Implementation Pattern

def sanitize_filename(title: str, doc: Optional[Dict] = None) -> str:
    """
    Sanitize title for filename with fallback for invalid names.

    Args:
        title: The document title to sanitize
        doc: Optional document dict for fallback metadata (author, saved_at, category)

    Returns:
        Sanitized filename ending in .md, guaranteed to have alphanumeric content
    """
    # Step 1: Standard character sanitization
    filename = title.replace('/', '-').replace(':', ' -')
    filename = re.sub(r'[<>"\\\|?*]', '', filename)
    filename = filename[:100].strip()

    # Step 2: Validate output meets requirements
    if not any(c.isalnum() for c in filename):
        # Step 3: Intelligent fallback using available metadata
        if doc:
            author = doc.get('author', 'Unknown')
            # Sanitize author name (may also have special chars)
            author = re.sub(r'[<>"\\\|?*/:]', '', author)[:30].strip()

            saved_at = doc.get('saved_at', '')
            date_str = saved_at[:10] if saved_at else datetime.now().strftime('%Y-%m-%d')

            # Use category for context
            category = doc.get('category', 'Document')
            category_label = 'Tweet' if category == 'tweet' else category.capitalize()

            filename = f"{category_label} by {author} - {date_str}"
        else:
            # Generic timestamp-based fallback
            filename = f"Untitled - {datetime.now().strftime('%Y-%m-%d-%H%M%S')}"

    return filename + ".md"

Read the full file on GitHub · 379 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 379 lines · 38 tokens per session scan A 1e76ddb96b54

Subscribe to this mod's changes

Python Filename Sanitization with Fallback is a skill published in the GitHub repository ngpestelos/readwise-mcp-server (0 stars, last pushed 2mo ago), licensed MIT. It adds 38 tokens to every session and 3,178 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

agent-framework-azure-ai-py

Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.

sickn33/agentic-awesome-skills · 24 tokens

python-feature-lifecycle

Guidance for package and feature lifecycle in the Agent Framework Python codebase, including stage meanings, feature-stage decorators, feature enums, and how to move APIs from one stage to the next.

microsoft/agent-framework · 43 tokens

python-development

Coding standards, conventions, and patterns for developing Python code in the Agent Framework repository. Use this when writing or modifying Python source files in the python/ directory.

microsoft/agent-framework · 35 tokens

dd-code-generation

Use pup CLI for immediate Datadog operations or generate code for integration into applications.

DataDog/pup · 16 tokens

rocm-kernels

Provides guidance for writing and benchmarking optimized Triton kernels for AMD GPUs (MI355X, R9700) on ROCm, targeting HuggingFace diffusers (LTX-Video, SD3, FLUX) and transformers. Core kernels: RMSNorm, RoPE 3D, GEGLU, AdaLN. Includes XCD swizzle, autotune, diffusers integration patterns, and LTX-Video pipeline…

huggingface/kernels · 93 tokens

typing-exclusion-worker

Python typing exclusion worker: remove assigned mypy exclusion modules in small scoped batches, fix typing issues, run validation, and produce a structured completion summary. Use when running parallel typing-debt workers or when asked to remove modules from pyproject mypy exclusion overrides.

getsentry/skills · 57 tokens