Anthropic’s Official Skill Practice Guide: How to Write, Refine, and Verify That It Helps

Following official examples of PDF form filling and data querying, this guide clarifies how a Skill evolves from real task failures into a reusable methodology.

By Anthropic10-04 · 18 min

Anthropic released an official Agent Skill authoring best practices guide dedicated to exploring how to write Skills that Claude can reliably discover and efficiently invoke. When starting out, many developers tend to write Skills as exhaustive "business operations manuals."

You might have experienced a similar progression: the first time Claude missed a detail during task execution, you immediately added a rule to the file; the next time it overlooked an edge case, you appended another background explanation. Over time, the main instruction file grew to over a thousand lines, packed with library introductions, parameter tables, and general precautions. An excessively long main file does not necessarily degrade the model's fundamental reasoning capabilities, but the context window remains a finite, shared resource. Once lengthy instructions and general domain knowledge are fully loaded, they compete for attention with conversation history and the active task, making it harder for the model to locate critical instructions and introducing unnecessary inference overhead.

In the official best practices, a core principle emerges: an effective Skill does not need to treat the model like a novice with zero common sense; instead, it should provide targeted operational guidance for specific scenarios.

To gauge whether a Skill is genuinely effective, stacking up rules is no proof of success. The real test is: Without this Skill, on which specific tasks does the model exhibit gaps or omissions? After adding these instructions, are the problems effectively resolved? And are the objectives achieved using concise phrasing and unambiguous workflows?


When Does Claude Read Skills, and When Does It Look Up Reference Materials?

To write an effective Skill, one must first understand how the model loads and reads files.

In interactions with Claude, the context window is a shared resource. In every conversation, the system prompt, chat history, the user's current query, and base metadata for all available Skills compete for this limited attention space. Stuffing extensive background and implementation details into the context all at once creates unnecessary space contention.

When designing Skills, the official architecture uses a three-tier loading mechanism based on progressive disclosure:

  1. Tier 1: Metadata Preloading
    When a session initializes, Claude does not read the full body of any Skill. It only preloads the name (name) and description (description) from the header of each installed Skill into the system prompt. At this stage, the model holds a global index of available capabilities.
  2. Tier 2: On-Demand Main File Invocation (SKILL.md)
    Only when a user's query matches the description of a specific Skill does Claude load the primary SKILL.md file via a file read command. If the task requires only baseline operations, the model executes using only this main document.
  3. Tier 3: Reference Materials Read as Needed (Reference Files & Scripts)
    When a task requires deeper domain rules, complete API specifications, or specialized workflows, Claude follows links within the main file to read secondary reference documents or invoke accompanying scripts directly.

This architecture determines the core structure of a Skill file: the main file should remain concise and summarized, primarily providing quick-start guidance and directory routing to guide the model toward deeper knowledge only when required.

Internal structural schematic of a single SKILL.md file
Skeletal design of a single SKILL.md file: Top metadata (YAML frontmatter) is registered by the system at launch, while the body retains only quick-start instructions and core routing links. Note that capitalized letters and spaces shown in the diagram's name field serve only as structural illustrations; official textual specifications mandate that this field use only lowercase letters, numbers, and hyphens.

When writing header metadata, two practical details are essential:

  • Naming specifications (name): Must be 64 characters or fewer and contain only lowercase letters, numbers, and hyphens (e.g., pdf-processing), with no XML tags or reserved keywords (such as anthropic or claude). If uppercase letters or spaces appear in official diagram illustrations, they serve merely as structural schematics; actual authoring must adhere strictly to lowercase and hyphenated conventions.
  • Descriptions (description) should specify trigger scenarios in an objective, third-person voice: Descriptions are limited to 1,024 characters, must be non-empty, and must not contain XML tags. At startup, Claude relies primarily on this description to select and route among candidate Skills. Writing "You can use this tool to process Excel" or "I can help you organize documents" introduces perspective inconsistencies once injected into the system prompt. A more reliable approach uses an objective, third-person perspective with explicit trigger scenarios and keywords, for example: "Extracts text and tables from PDFs, fills forms, and merges documents. Use when processing PDF files, or when the user mentions PDFs, forms, or document extraction."

Reading Only Financial Materials When Querying Financial Data

Official recommendations suggest keeping the body of the primary SKILL.md document within 500 lines to maintain strong operational performance. This represents a best practice recommendation for maintainability and focus rather than an enforced platform limit; once content approaches or exceeds this threshold, it is better organized into independent reference files.

For file decomposition, official guidance recommends a "one level deep" linking approach: all secondary reference files should ideally be linked directly from the primary SKILL.md, avoiding nested, multi-tier hierarchies.

Progressive disclosure and multi-file bundling schematic
Progressive disclosure organizational structure: The primary SKILL.md acts as a central hub, pointing to separate functional modules (such as reference.md and forms.md) via direct links. The model navigates unidirectionally based on task requirements, avoiding aimless traversal across multiple sub-levels.

Why avoid deep nesting?
If a documentation structure has SKILL.md referencing advanced.md, which in turn points to details.md, Claude may issue partial preview commands like head -100 on deeply nested references rather than reading the full file, resulting in incomplete context retrieval. Direct, single-level links help guide the model to load target contents more fully when needed. However, single-level linking is an organizational recommendation and does not guarantee complete file ingestion in every instance. Therefore, official guidelines further suggest adding a Table of Contents at the top of reference files exceeding 100 lines, enabling the model to grasp the file's overall structure and navigate accurately to relevant sections even during quick partial previews.

The recommended pattern divides material by domain, branched directly from the main file. Consider the official hypothetical BigQuery data analysis example:

  • bigquery-skill/
    • SKILL.md (Overview and quick navigation hub)
    • reference/finance.md (Revenue and billing metrics)
    • reference/sales.md (Opportunities and sales funnels)
    • reference/product.md (API call volumes and feature usage statistics)

When a user asks "How are revenue metrics calculated?", Claude first checks the main file. Seeing that only financial metrics are needed, it reads exclusively reference/finance.md. At this point, only the financial documentation actually retrieved is added to the context; unread sales and product documents remain on the filesystem without incurring context overhead. This pattern delivers deep domain expertise on demand while eliminating unnecessary context consumption.

After setting up a multi-file system, observe the model's access patterns during real interactions to evaluate whether structural divisions are sound:

  • Missing important links: If the model fails to follow links from the main document to relevant reference modules, this usually suggests that entry points are insufficiently prominent or navigation instructions lack clarity;
  • Repeatedly reading the same reference: If certain reference documents are fetched repeatedly across multiple tasks, they may contain frequently needed shared knowledge worth considering for inclusion in the main file;
  • Leaving files completely unread: If an auxiliary document is never accessed, it may be unnecessary for the target domain, or the main file may lack clear trigger cues. Re-run comparable tasks after making adjustments to observe whether the model locates the necessary files and whether task outcomes improve.

Prepare Scripts in Advance for Repetitive Deterministic Operations

Across many tasks, we can either provide textual instructions for Claude to write and run code on the fly, or bundle ready-made utility scripts within the Skill directory. How should responsibilities be divided?

Official guidance recommends: for deterministic, error-prone operations, prioritize pre-built utility scripts for the model to invoke directly, rather than having the model generate code from scratch each time.

Bundling executable scripts within a Skill
Workflow for bundled executable scripts: Documentation directs the model to invoke pre-written Python utilities via the command line, directly producing structured output. Running a script does not require reading its full source code into the model's attention window.

Using pre-built utility scripts provides several distinct benefits:

  1. Conserving context and generation time: When executing terminal commands (such as extracting form fields: python scripts/analyze_form.py input.pdf > fields.json), the model typically only needs to ingest the script's printed output. It does not need to generate code repeatedly or read the entire script source into context. This does not preclude reading code entirely; official guidance notes that documentation should clarify intent: standard utilities are primarily meant to be "executed," whereas scripts containing critical algorithmic logic can be explicitly designated for the model to "read as reference."
  2. Solve, don't defer: Scripts should handle errors explicitly and provide clear diagnostic output. Official documentation used creating an empty default file or providing alternatives when a file is missing as an illustrative code example. This illustrates defensive error-handling patterns rather than a rule that every scenario calls for creating blank files; the core requirement is that scripts handle failures explicitly with actionable diagnostic messages, rather than surfacing obscure native stack traces for the model to guess at.
  3. Eliminating voodoo constants: Key parameters configured within scripts should include clear rationales and comments. For instance, if setting a 30-second timeout with 3 retries, annotate that "standard HTTP requests typically return within 30 seconds, and 3 retries balance responsiveness against transient network jitter," avoiding arbitrary magic numbers lacking justification.
  4. Clarifying runtime environments and dependency requirements: While generic explanations (such as defining what a PDF is) should be trimmed, required packages and execution constraints must be stated explicitly. Whether a platform allows internet access or runtime dependency installation depends on the active execution environment. Documentation must therefore list required dependencies clearly (e.g., specifying pypdf and compatible installation steps) so they can be prepared in the target environment.
  5. Providing default paths with explicit exceptions instead of overloading choices: Official guidance advises against presenting an extensive catalog of optional libraries (such as listing pypdf, pdfplumber, PyMuPDF, and pdf2image simultaneously for the model to evaluate). A clearer approach defines a default path with explicit triggers for exceptions: recommend pdfplumber by default for standard text extraction; specify pdf2image paired with pytesseract as the explicit exception when encountering scanned PDFs that require OCR. The default path tells the model what to use first; the exception condition clarifies when to switch approaches.

Leave Room for Judgment in Code Reviews, Write Explicit Steps for Database Migrations

How detailed should a Skill be? The answer lies in matching the appropriate degrees of freedom to the task's fragility and variability.

Official guidelines visualize model exploration like a robot's navigational path:

  • A narrow bridge with cliffs on both sides (low degrees of freedom): Only one safe path exists; operations are fragile and prone to failure, demanding strict instructions and deterministic scripts. For database migrations, documentation should prescribe an exact command: python scripts/migrate.py --verify --backup, explicitly forbidding command modifications or unvetted flags to preserve consistency across critical workflows.
  • Parameterized patterns (medium degrees of freedom): Recommended paradigms exist, but configuration varies based on input. For analytical reporting, provide parameterized function templates (such as generate_report(data, format="markdown", include_charts=True)) or report skeletons, allowing the model to adapt presentation details to actual data shapes.
  • An open field without hazards (high degrees of freedom): Multiple valid paths reach the goal, depending on context and trade-offs. For code reviews, use bulleted lists defining review dimensions (analyzing architecture and organization, inspecting potential defects and edge cases, suggesting readability improvements, verifying project conventions), allowing the model to synthesize assessments based on the actual codebase.

In workflow design, degree-of-freedom calibrations often pair with conditional branching. The official DOCX processing example distinguishes "creating from scratch" from "modifying existing documents": when generating a brand-new document, build it entirely using specialized libraries (like docx-js); for minor edits to existing documents, avoid full reconstruction by unpacking and editing the underlying word/document.xml directly, running validation scripts immediately afterward to verify structural compliance before repackaging for testing. Distinguishing these two paths prevents inefficient, formatting-destructive full rebuilds during simple edit tasks.

Output formatting rules should similarly reflect downstream consumption. If output will be ingested programmatically—such as a fixed-schema API payload—prescribe rigid templates so downstream systems know where to extract fields. If report sections vary based on findings, supply a default structure while identifying which sections are flexible. How strictly format is defined depends entirely on how the output is subsequently used.

Paired input-output examples effectively communicate stylistic expectations and level of detail. The official Git commit message example illustrates:

Input: Added user authentication with JWT tokens

Output:

feat(auth): implement JWT-based authentication

Add login endpoint and token validation middleware

This example demonstrates both the type(scope): brief description subject format and the inclusion of specific technical changes in the body. Compared to simply stating "commit messages must be concise and standardized," paired examples make compliant output immediately recognizable to the model.


Filling 50 PDF Fields: Check the Plan First, Then Check the Final Product

In tasks involving batch modifications or irreversible changes, directing the model to alter target files immediately risks field mismatches, overwritten formatting, or interrupted execution. Official documentation frames a hypothetical scenario: updating 50 fields in a PDF form from tabular data. Without validation steps, the model may reference non-existent fields, populate conflicting values, or omit mandatory inputs.

For such tasks, official guidelines recommend a "Plan → Validate → Execute" workflow pattern, organizing the process into a structured feedback loop:

  1. Analyze source and visual analysis: Run an analysis tool to extract form fields and coordinates, generating a structured representation, such as python scripts/analyze_form.py input.pdf yielding fields.json. For complex layouts, official guidance suggests incorporating visual analysis: implement and run python scripts/pdf_to_images.py form.pdf to render PDF pages as images, allowing the model to visually inspect field positions, field types, and overall page structure across pages. Conversion scripts must be supplied independently. Page images help the model understand "where fields sit and how the page looks," while structured verification checks field mappings and conflicts against explicit rules; both work in tandem.
  2. Create plan: Have the model map input data into an independent plan file (e.g., editing fields.json or creating changes.json). Before the source file is touched, all mappings and modifications reside within this plan file, enabling low-cost iteration and adjustment.
  3. Validate plan: Run a dedicated validation script against the plan file (e.g., python scripts/validate_fields.py fields.json). Here, plan validation focuses on verifying the legality of proposed field mappings and change logic—checking for references to non-existent fields, value conflicts, or missing mandatory fields (whereas in another official example, validate_boxes.py checks for overlapping bounding boxes). If issues arise, the script outputs concrete diagnostics (such as "Field signature_date not found; available fields are: customer_name, order_total, signature_date_signed").
  4. Fix errors: The model adjusts the plan file based on explicit validation feedback and re-runs validation, forming a correction loop.
  5. Execute: Only after plan validation passes completely does the model invoke execution scripts to write modifications to the target file, such as python scripts/fill_form.py input.pdf fields.json output.pdf.
  6. Verify output: Execution must never be assumed successful by default. A finished-output verification script (such as python scripts/verify_output.py output.pdf) must inspect the final document after writing; if verification fails, return to the planning stage to investigate and correct the problem.

These script names illustrate step-by-step responsibilities. In practice, corresponding scripts must be implemented for specific forms; isolated examples from the documentation cannot simply be assembled into an off-the-shelf bundle.

Introducing an intermediate plan file transforms an unpredictable generation process into an inspectable intermediate state verifiable by deterministic programs. Plan validation verifies intended field mappings and proposed changes, whereas final-output verification inspects the actual document after writes are applied; until source files are altered, plans can be revised repeatedly.

This "validation → correction → repetition" feedback loop extends beyond code-centric tasks. In pure text and non-code domains, it remains a core design mechanism for enhancing output quality:

  • Research synthesis workflows: In the official no-code analysis example, research is broken into 5 explicit stages: reading all source documents, identifying core themes, cross-checking evidence, generating a structured summary, and verifying citation sources. If citations prove incomplete during the final step, the workflow returns to cross-checking evidence to backfill citations before re-verification;
  • Style guide compliance: For written content, reference documents (like STYLE_GUIDE.md) serve as "validators." Models are instructed to draft content and self-review against an explicit checklist: verifying terminological consistency, checking that examples match standard formats, and ensuring mandatory sections are present. If non-compliant sections appear, the model flags them, applies revisions, and re-evaluates against the checklist until all criteria are satisfied. Even without scripts, evaluation criteria can be explicitly formulated with requirements for iterative revision. A model reviewing text against a specification requires semantic judgment, whereas program verification mechanically evaluates fields and structures against programmatic rules; each catches different categories of errors.

Switch to a Fresh Session to See If the Skill Can Guide It Independently

When authoring and refining Skills, official guidance places special emphasis on building evaluations first, avoiding ungrounded documentation that lacks targeted relevance.

Testing a newly authored Skill in the same conversation where it was created skews results: the model's performance is influenced by accumulated background context from earlier dialogue, making it difficult to evaluate the Skill's independent guidance capability. Consequently, official practices recommend separating iterative workflows across two distinct roles: Claude A, assisting with authoring and structural design, and Claude B, running tests inside an independent, fresh session. Testing does not require switching accounts or restarting physical environments—only opening a clean conversation window (a fresh instance) free from prior interaction history.

The iterative workflow follows a straightforward sequence:
Identify real task gaps and establish baselines → Draft and prune the Skill with Claude A → Test with Claude B in a fresh session → Collect execution discrepancies and return to Claude A for tuning

This process breaks down into essential stages:

1. Identify Task Gaps and Establish an Evaluation Baseline

Before writing extensive documentation, execute representative tasks to observe baseline performance without the Skill. Record specific failure points: not knowing specific database table names, omitting filter clauses, or selecting improper processing tools. Using these documented gaps, assemble at least 3 test scenarios as an initial evaluation baseline.

To establish clear expectations, official documentation provides a structured evaluation sample defining inputs and expected behaviors in JSON:

{
  "skills": ["pdf-processing"],
  "query": "Extract all text from this PDF file and save it to output.txt",
  "files": ["test-files/document.pdf"],
  "expected_behavior": [
    "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
    "Extracts text content from all pages in the document without missing any pages",
    "Saves the extracted text to a file named output.txt in a clear, readable format"
  ]
}

Success criteria here are explicit: read every page and save extracted content to output.txt. These criteria must be validated against actual generated files. The documentation provides a schema for evaluation cases rather than a built-in evaluation test runner; test execution and verification must be managed independently.

2. Draft Initial Content and Prune with Claude A

After completing a representative task in an active dialogue, extract background assets offering recurring value (such as table names, field definitions, and business rules). Then, direct Claude A to organize them into a standardized SKILL.md. Claude models naturally understand Skill formatting conventions without requiring specialized meta-prompts.

Pruning must remain tightly coupled with evaluation: focus instructions strictly on addressing observed gaps, writing only the minimal instructions necessary to resolve them. After generating a draft and removing general domain explanations and redundant text, re-run previously established baseline test cases to confirm the pruned Skill still meets expectations. For example, after removing a general explanation of "what win rate means," check whether the model still generates the report using the correct tables and filter conditions; if key behavior remains intact, that explanatory paragraph need not remain in the main file.

3. Test with Claude B in a Fresh Session

Mount the Skill in a clean, blank session and direct Claude B to execute the business task. When evaluating the Skill's independent efficacy, avoid real-time human prompting during the run to observe whether the model locates information and complies with rules based solely on documentation. (In routine production workflows, ongoing human collaboration is entirely natural.)

In the official BigQuery analysis teaching example, this A/B iteration unfolds through concrete steps:

  • During an initial data exploration session, the author guides Claude A through the analysis, extracting core assets: dataset table names, column definitions, query conventions, and a business rule mandating that "internal test accounts must be filtered out."
  • Claude A drafts the Skill, breaking detailed table schemas out into reference/ files.
  • Next, in a fresh session, Claude B is instructed to generate a "regional sales report" using the Skill. In this teaching example, while Claude B can write query code, it still forgets to filter out test accounts under specific conditions.
  • The author notes this specific behavioral discrepancy, brings it back to Claude A, and discusses refinements: "Claude B omitted the test account filter when generating regional reports. Is the rule insufficiently prominent? Should we strengthen phrasing to an explicit 'MUST filter,' or adjust its placement?"
  • After updating the Skill based on these findings, another fresh session runs a similar task to verify whether the filter condition is consistently applied.

When a model misses the test account filter, determine at which step it diverged before deciding what to modify. Synthesizing official recommendations across triggering, navigation, and iteration yields the following diagnostic sequence:

  • Skill never triggered: Check metadata description first; verify whether keywords cover task phrasing, trigger conditions are unambiguous, and third-person phrasing is used;
  • Skill triggered but key references missed: Inspect navigation and file architecture in SKILL.md; ensure critical reference documents use direct single-level links with prominent descriptions and routing cues;
  • References loaded but rules still overlooked: Check rule placement within documents; determine whether rules appear early, use explicit phrasing, or need restructuring into sequential workflows and checklists;
  • Execution succeeded but final output is flawed: Inspect input data, tool-level error handling, and whether intermediate plan validation or final output verification steps are missing.

4. Test Across Target Models

Passing initial 3 baseline scenarios does not guarantee universal correctness across open-ended tasks; ongoing observation in practical business contexts remains essential. Furthermore, Skill performance depends heavily on the underlying model and must be evaluated across all targeted deployments:

  • Claude Haiku (lightweight and cost-efficient): Verify whether operational instructions are sufficiently comprehensive and explicit;
  • Claude Sonnet (balanced capabilities): Confirm instructions remain clear, concise, and computationally efficient;
  • Claude Opus (deep reasoning): Ensure documentation is succinct, avoiding over-explanation that introduces prompt bloat.

Different models exhibit varied sensitivity to instructional density; passing tests on one model does not imply identical performance across others.


Practical Recommendations: A Ready-to-Use Skill Self-Check Checklist

Synthesizing checklists from official guidance, developers can evaluate and refine Skills against these practical criteria before delivery:

  • Metadata specifications: Keep name within 64 characters using only lowercase letters, numbers, and hyphens; formulate description in an objective, third-person perspective detailing capabilities alongside explicit trigger scenarios and keywords.
  • Main file size and progressive disclosure: Aim to keep the SKILL.md body within 500 lines, omitting generic educational concepts; assign descriptive names to auxiliary files (such as form_validation_rules.md rather than ambiguous names like doc2.md); state installation instructions and runtime constraints for required libraries, confirming capabilities against actual execution environments; include a Table of Contents for reference files exceeding 100 lines.
  • File paths and reference depth: Maintain direct, single-level links from the main file for all reference documents (one level deep); format all file paths with forward slashes / (avoiding backslashes \, even in Windows environments).
  • Terminological consistency and avoiding date-based forks: Maintain consistent terminology across documents (e.g., standardizing on "API endpoint" or "field" throughout); avoid transient date-based branching rules like "use legacy before date X, use new after date X"; if historical workflows must be retained, isolate them in a dedicated "Old patterns" section.
  • Tool invocations and MCP conventions: If a Skill invokes Model Context Protocol (MCP) tools, use the fully qualified ServerName:tool_name format (e.g., BigQuery:bigquery_schema in official examples) to prevent invocation failures caused by missing server prefixes.
  • Script design and error handling: Provide pre-built utility scripts for deterministic or error-prone tasks, prioritizing execution by the model; ensure scripts handle errors explicitly with actionable diagnostic messages; supply clear rationales for parameters and eliminate uncommented magic numbers.
  • Guards for high-risk and batch operations: For batch updates or structural alterations, implement an intermediate feedback loop combining plan files (e.g., JSON) with programmatic validation, followed by final-output verification after writes.
  • Empirical testing and multi-model verification: Establish baseline tasks comparing performance without the Skill; evaluate actual execution inside fresh, independent sessions; verify outcomes across all targeted models (such as Haiku, Sonnet, and Opus).

Appendix: Skill Iterative Improvement Record Template

The following plain-text template provides a structured log for recording Skill iterations. Derived from iterative testing methodologies in official best practices, it serves as a reusable record for developers tracking real model behavior during Skill development and maintenance (copy and populate according to specific test scenarios):


              Skill Iterative Improvement Record
   (Note: Synthesized from official evaluation and iteration guidelines for practical reuse)


[Test Task]:
(e.g., Generate last quarter's regional sales report, aggregating total contract volume across sales regions)

[Baseline Result Without Skill]:
(e.g., Model writes basic SQL without the Skill, but does not know internal core table names)

[Expected Pass Criteria]:
(e.g., Accurately references sales table names, includes date range filters, and explicitly excludes internal test accounts)

[Did Skill Trigger?]:
(e.g., Yes; execution trace shows model loaded SKILL.md for this Skill)

[Actual Files Read / Tools Invoked]:
(e.g., Read SKILL.md and reference/sales.md; did not invoke external scripts)

[Observed Failure / Discrepancy]:
(e.g., In a fresh session with the initial Skill draft, the model located correct tables but omitted the WHERE filter excluding internal test accounts)

[Rule or File Modified]:
(e.g., Updated SKILL.md to move "filter test accounts" from an endnote into core query specifications, strengthening phrasing from "recommended" to "MUST filter test accounts")

[Verification Basis Before and After Edit]:
(e.g., Compared the WHERE clause in generated SQL queries before and after the modification to confirm presence of account_type != 'test')

[Fresh Session Outcome]:
(e.g., Launched a new session to re-run the same task; generated SQL correctly included WHERE account_type != 'test')

[Next Optimization Steps]:
(e.g., Run test cases on Claude Haiku and Opus respectively, checking whether Haiku requires more granular field mapping documentation)

Source
Skill authoring best practicesAnthropic·Read the source
↑ End of article
✓ This article is free to read in full

Members can copy or download the full Markdown, and let their AI subscribe and ask.

Read the original ↗
📮 New explainers, straight to your inbox

Found this useful? Leave your email — every new explainer, the moment it's out. Unsubscribe anytime.