How to create Claude Code skills for reliable agent workflows

Create a Claude Code skill by putting a SKILL.md file in .claude/skills/<skill-name>/ in your project. Give it a description that identifies the right tasks, then test whether Claude selects it and whether its instructions improve the work.

The file is the easy part. Reliability comes from running representative tasks in fresh environments, inspecting the execution trace and resulting files, and comparing them with runs where the skill is unavailable.

1. Choose between a skill, a tool, and a prompt

A skill is a reusable bundle of instructions for a recurring workflow. It can tell Claude how to investigate a bug, choose checks, and report uncertainty. It does not grant permissions or guarantee that a command or integration exists.

Approach Best use Execution and trade-off
One-off prompt A task unlikely to recur Quick to write, but the workflow is not packaged for reuse
Skill A repeatable, multi-step workflow Supplies instructions and references; still depends on available tools and permissions
Client tool A discrete operation such as querying an internal API Your application executes the call and returns the result
Server tool A supported operation such as web search or code execution Anthropic infrastructure executes the tool; availability depends on the environment

Skills and tools can work together: the skill describes the workflow, while tools perform individual operations. The same skill content can be used across Claude Code, Claude.ai, and the API when the target environment supports its dependencies. Don't assume a local test command or repository file exists elsewhere. See the official skills documentation before adapting a skill to another surface.

2. Establish a baseline

Before writing instructions, run representative tasks without the skill. Record the prompt, starting files, available tools, actions, and outcome. Choose cases that expose different failures. For a debugging workflow, use:

  • A reproducible failure with a test and permission to fix it.
  • An incomplete report that requires a question rather than a guessed diagnosis.
  • An unrelated request that should not activate the debugging skill.

Keep another case back for regression testing. Otherwise, you may tune the skill to a few examples without improving work outside them.

Compare baseline and skill-enabled runs from equivalent starting files, using the same model, tools, and permissions. Remove the skill from the baseline environment; automatic discovery could otherwise contaminate the comparison. Record actual tool calls and file changes, not just the final answer.

3. Write a focused debugging skill

From your project root:

bash
mkdir -p .claude/skills/systematic-debugging

Create .claude/skills/systematic-debugging/SKILL.md:

markdown
---
name: systematic-debugging
description: Investigates failing tests, errors, and reported software regressions using evidence before proposing or making a fix.
---

## Systematic debugging

## Establish the problem

Identify expected behavior, actual behavior, and reproduction steps.
If essential context is missing, ask for it rather than guessing.
If the user requests an explanation only, do not change files.

## Reproduce

Run the most focused available reproduction when permitted.
Record the command and result. If reproduction is blocked, report the
blocker and label any further diagnosis as a hypothesis.

## Hypothesize and gather evidence

Rank plausible causes and state what evidence would distinguish them.
Inspect the relevant code and results before selecting a cause.
Do not move to a fix until the evidence supports it.

## Fix and verify

When a fix is requested and supported by evidence, make a focused change.
Run the original reproduction and relevant tests when available and permitted.
Do not claim a check passed if it was not run or did not pass.

## Report

Summarize the cause, evidence, changes, checks, and remaining uncertainty.
If a tool or service is unavailable, report the blocker and the next check.

The description says what the skill does and when it applies. Write it in the third person, using language a developer would naturally use in a request. The description supports discovery; it does not prove that a skill was selected.

Keep the main file focused. Put detailed, conditional guidance under a references/ directory and link to it directly from SKILL.md. Keep essential boundaries, such as reporting unrun tests honestly, in the main file. For more on precise instructions, see advanced prompt engineering.

4. Use phase gates during a real investigation

The following is an illustrative run, not a claim about an actual project.

A test expects a price of 100 with a 20 percent discount to produce 80, but it produces -1900.

  1. Reproduce. Run the focused test and capture the failure. If the test cannot run because a dependency is missing, don't claim the bug is fixed.
  2. Hypothesize. Rank a missing percentage conversion first because the result is consistent with multiplying by 1 - 20. Rank an incorrect test expectation second. Rank a rounding issue lower because it does not explain the magnitude.
  3. Gather evidence. Inspect the calculation and the documented input contract. If the code uses price * (1 - percent) and the contract says the input is a whole percentage, the first hypothesis is supported.
  4. Fix. Change the calculation to divide percent by 100. Do not make the change if the evidence instead shows callers already pass fractions.
  5. Verify. Rerun the original test and relevant checks. Report the observed results; a plausible patch is not a verified fix.

These gates help distinguish a blocked run from a failed skill. Instructions still do not enforce permissions or replace code review.

5. Run a live skill evaluation

The following small harness runs Claude Code against isolated, illustrative files. It checks a positive debugging request, a negative trigger request, tool calls, the test result, and a baseline without the skill. It captures fresh JSON traces on every run rather than scoring manually entered observations.

Requirements:

  • Python, Claude Code, and an authenticated account with access to the selected model.
  • A version of Claude Code supporting -p, --output-format stream-json, --verbose, --setting-sources, and --allowedTools.
  • A dedicated test account or configuration without another copy of systematic-debugging. Run in a disposable environment without production secrets or access to shared services.

The harness gives Claude permission to edit its temporary fixture and run Python commands. Tool permissions are not an operating-system sandbox. Use a container or other isolation appropriate to your environment.

Create eval/cases.json:

json
[
  {
    "id": "fix-discount",
    "kind": "fix",
    "prompt": "Debug the failing discount test, fix the cause, and verify it. Run python3 -m unittest test_bug.",
    "expect_skill": true,
    "expected_tool_calls": ["Skill", "Bash"],
    "regression_markers": ["reproduce_then_verify", "tests_pass"]
  },
  {
    "id": "unrelated",
    "kind": "unrelated",
    "prompt": "What is 2 + 2? Answer only with the number.",
    "expect_skill": false,
    "expected_tool_calls": [],
    "regression_markers": ["no_file_changes"]
  }
]

Save this as eval/run.py:

python
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SKILL = ROOT / ".claude/skills/systematic-debugging/SKILL.md"
CASES = json.loads((ROOT / "eval/cases.json").read_text())
TRACES = ROOT / "eval/traces"
TRACES.mkdir(parents=True, exist_ok=True)

APP = """\
def discount(price, percent):
    return price * (1 - percent)
"""

TEST = """\
import unittest
from app import discount

class DiscountTest(unittest.TestCase):
    def test_whole_percent(self):
        self.assertEqual(discount(100, 20), 80)

if __name__ == "__main__":
    unittest.main()
"""

def test_fixture(work):
    return subprocess.run(
        [sys.executable, "-m", "unittest", "test_bug"],
        cwd=work, capture_output=True, text=True, timeout=30
    )

def blocks(events):
    for event in events:
        message = event.get("message", {})
        content = message.get("content", [])
        if isinstance(content, list):
            for block in content:
                if isinstance(block, dict):
                    yield block

def run_case(case, enabled):
    mode = "skill" if enabled else "baseline"
    trace_path = TRACES / f"{mode}-{case['id']}.jsonl"
    trace_path.unlink(missing_ok=True)

    with tempfile.TemporaryDirectory(prefix="skill-eval-") as tmp:
        work = Path(tmp)
        (work / "app.py").write_text(APP)
        (work / "test_bug.py").write_text(TEST)

        if enabled:
            dest = work / ".claude/skills/systematic-debugging"
            dest.mkdir(parents=True)
            dest.joinpath("SKILL.md").write_text(SKILL.read_text())

        # The independent pre-check confirms the fixture starts broken.
        if test_fixture(work).returncode == 0:
            raise RuntimeError("Fixture unexpectedly passes before the run")

        cmd = [
            "claude", "-p", case["prompt"],
            "--output-format", "stream-json",
            "--verbose",
            "--setting-sources", "project",
            "--allowedTools",
            "Skill,Read,Edit,Write,Bash(python3 *)",
        ]
        try:
            run = subprocess.run(
                cmd, cwd=work, capture_output=True, text=True,
                timeout=300, env=os.environ.copy()
            )
        except subprocess.TimeoutExpired:
            raise RuntimeError(f"{mode}/{case['id']}: Claude timed out")

        trace_path.write_text(run.stdout)
        if run.returncode != 0:
            raise RuntimeError(
                f"{mode}/{case['id']}: Claude failed: {run.stderr}"
            )

        try:
            events = [json.loads(line) for line in run.stdout.splitlines()]
        except json.JSONDecodeError as exc:
            raise RuntimeError(f"Invalid trace: {trace_path}") from exc

        if not events or not any(
            e.get("type") == "result" and not e.get("is_error", False)
            for e in events
        ):
            raise RuntimeError(f"Missing successful result: {trace_path}")

        content = list(blocks(events))
        calls = [b for b in content if b.get("type") == "tool_use"]
        results = {
            b.get("tool_use_id"): b
            for b in content if b.get("type") == "tool_result"
        }

        skill_calls = [
            c for c in calls
            if c.get("name") == "Skill"
            and c.get("input", {}).get("skill", "").lstrip("/")
                == "systematic-debugging"
        ]
        selected = any(
            c.get("id") in results
            and not results[c["id"]].get("is_error", False)
            for c in skill_calls
        )

        # Fail closed if the baseline has a leaked copy of the skill.
        if not enabled and skill_calls:
            raise RuntimeError(f"Baseline contaminated: {trace_path}")

        names = {c.get("name") for c in calls}
        changed = (
            (work / "app.py").read_text() != APP
            or (work / "test_bug.py").read_text() != TEST
        )

        if case["kind"] == "fix":
            observations = []
            for call in calls:
                if call.get("name") != "Bash":
                    continue
                command = call.get("input", {}).get("command", "")
                if "python3 -m unittest test_bug" not in command:
                    continue
                result = results.get(call.get("id"))
                if result is not None:
                    observations.append(json.dumps(result))

            failed_then_passed = any(
                "FAILED" in before and "OK" in after
                for i, before in enumerate(observations)
                for after in observations[i + 1:]
            )
            functional = (
                changed
                and (work / "test_bug.py").read_text() == TEST
                and test_fixture(work).returncode == 0
                and failed_then_passed
            )
        elif case["kind"] == "unrelated":
            final = next(
                (e.get("result", "") for e in reversed(events)
                 if e.get("type") == "result"),
                ""
            )
            functional = not changed and final.strip() == "4"
        else:
            raise RuntimeError(f"Unknown case kind: {case['kind']}")

        expected_tools = set(case["expected_tool_calls"])
        if not enabled:
            expected_tools.discard("Skill")

        return {
            "selected": selected,
            "functional": functional,
            "tools_ok": expected_tools.issubset(names),
            "trace": str(trace_path),
        }

def main():
    if not SKILL.is_file():
        raise RuntimeError(f"Missing skill: {SKILL}")

    failures = []
    baseline_score = skill_score = 0

    for case in CASES:
        baseline = run_case(case, False)
        enabled = run_case(case, True)
        baseline_score += int(baseline["functional"])
        skill_score += int(enabled["functional"])

        print(case["id"], "baseline:", baseline, "skill:", enabled)
        if enabled["selected"] != case["expect_skill"]:
            failures.append(f"{case['id']}: unexpected skill selection")
        if not enabled["functional"] or not enabled["tools_ok"]:
            failures.append(f"{case['id']}: functional or tool check failed")

    print(f"Functional score: baseline={baseline_score}, skill={skill_score}")
    if skill_score < baseline_score:
        failures.append("Skill regressed against baseline")
    if failures:
        raise RuntimeError("; ".join(failures))

if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError) as exc:
        print(exc, file=sys.stderr)
        sys.exit(1)

Run it from the project root:

bash
python3 eval/run.py

The positive case requires a visible successful Skill call, a Bash call that sees the test fail and then pass, and an independent test run against the changed files. The negative case requires no skill selection, no changes to the fixture files, and the expected answer. The harness prints the baseline score beside the skill score; equal scores show no measured improvement on these cases.

The evaluation is deliberately strict. A different but valid test command, a changed trace format, or a model choosing not to use the skill can cause it to fail. Inspect eval/traces/ before changing the assertions. The harness checks only the named fixture files for unwanted changes and does not prove that a fix generalizes. Trace files may contain prompts and tool output; protect or redact them before sharing.

6. Put the live evaluation in CI

For example, create .github/workflows/skill-eval.yml:

yaml
name: Skill evaluation

on:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  evaluate:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install Claude Code
        run: npm install --global @anthropic-ai/claude-code

      - name: Run live evaluation
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: python3 eval/run.py

This example uses a manually started workflow so a pull request cannot automatically run arbitrary changed instructions with a secret. Restrict who can start it and which code it evaluates. Pin the CLI, model, runner dependencies, and action revisions in your own environment before using results as a merge gate. Confirm the credential method and CLI options for your installed version.

Run normal application tests and review alongside this evaluation. A passing skill test does not establish that the application is correct. Expand the case set over time using failures from real work; the continuous model evaluation guide covers maintaining evaluation sets.

7. Share and govern the skill

Commit .claude/skills/systematic-debugging/ with the project and review changes through pull requests. Assign an owner for the instructions and evaluation cases. A useful review asks:

  • Does the description activate on the intended tasks without catching unrelated work?
  • Do the trace and file assertions cover the reported failure and a held-out regression case?
  • Are new commands, dependencies, references, and bundled scripts safe and necessary?
  • Are blocked operations reported honestly, and are edits limited to authorized work?
  • Has the owner reviewed the baseline comparison and ordinary CI results?

Use an explicit team version convention in release notes or a separate manifest. For example, label a clarification that leaves expected behavior unchanged 1.0.1; label a new verification requirement 1.1.0; label a change that removes an established workflow 2.0.0. These are illustrative team rules, not versions enforced by Claude Code.

For organization-wide provisioning, Anthropic's organization-management documentation states that Team or Enterprise is required as of November 2026. Skills also require code execution to be enabled. Test a skill before provisioning it broadly, scope specialized skills to appropriate groups, and, on Enterprise, enable scanning for third-party skills and plugins. Scanning complements review; it does not make unfamiliar instructions or scripts trustworthy.

The members' bonus adds a formal fixture schema, an extended debugging test case, and patterns for delegation and parallel tool calls.