Skip to main content

02 - Building a Claude Skill from scratch in 2 hours

Build a Claude Skill that reviews Flyway migrations: a SKILL.md, a checking script, test cases that pin its limits, and activation tests.

What do you think about this article?

02 - Building a Claude Skill from scratch in 2 hours
Claude Skills & MCPPhoto:Matheus BertelliPexels

At a Glance

Build a Claude Skill that reviews Flyway migrations: a SKILL.md, a checking script, test cases that pin its limits, and activation tests.

A useful skill is small: a SKILL.md that tells Claude when to step in and what to do, and a script that runs the part that must not depend on the model's judgment. Here we build it for a concrete task, reviewing the Flyway migration files of a PostgreSQL project, and we test it the way any other code is tested: with test cases that pass or fail. The skeleton of the SKILL.md and the meaning of its fields are in the first article; here the work is on the script, on the tests and on the way of checking that the skill starts when it should.

What goes in the script and what stays with Claude

The first design decision is where to draw the line. Recognizing a DROP COLUMN in an SQL file is a mechanical operation: written as a script it always gives the same result, costs zero tokens and can be tested. Deciding whether a rewrite is acceptable for your table is a judgment, and that is where Claude is needed. The skill exploits this split: the script produces numbered findings, Claude reads them, proposes the fixes and states what it could not check. The alternative, writing a list of rules in prose in SKILL.md and letting Claude apply them by reading the file, works, but it is not repeatable and every run pays for the rules in context.

There are five rules, all drawn from the PostgreSQL and Flyway documentation: a DROP COLUMN or DROP TABLE deletes data; a CREATE INDEX without CONCURRENTLY blocks writes to the table until the index is built; an ADD COLUMN ... NOT NULL without DEFAULT gives existing rows the value NULL, which the constraint rejects; an ALTER COLUMN ... TYPE usually rewrites the table and its indexes; an index created with CONCURRENTLY cannot run inside a transaction, while Flyway by default wraps every migration in a transaction. The third rule is a deduction from the text of the documentation, which says that without constraints the default value of an added column is NULL: I have not tested it on a PostgreSQL server, which was not started here.

The script

The file is short on purpose. Each rule is a tuple with code, severity, regular expression and reason, so adding one means adding a line and not touching the logic.

#!/usr/bin/env python3
"""Checks an SQL migration file and prints one finding per line: LINE SEVERITY RULE REASON."""
import re
import sys

REGOLE = [
    ("R1", "HIGH", re.compile(r"\bDROP\s+(COLUMN|TABLE)\b", re.I),
     "deletes data: the migration cannot be undone with another migration"),
    ("R2", "HIGH", re.compile(r"\bCREATE\s+(UNIQUE\s+)?INDEX\b(?!\s+CONCURRENTLY)", re.I),
     "without CONCURRENTLY it blocks writes to the table until the index is ready"),
    ("R3", "HIGH", re.compile(r"\bADD\s+COLUMN\b(?!.*\bDEFAULT\b).*\bNOT\s+NULL\b", re.I),
     "NOT NULL without DEFAULT fails if the table already has rows"),
    ("R4", "MEDIUM", re.compile(r"\bALTER\s+COLUMN\b.*\bTYPE\b", re.I),
     "usually rewrites the table and its indexes: check whether the type change is binary-compatible"),
    ("R5", "INFO", re.compile(r"\bCREATE\s+(UNIQUE\s+)?INDEX\s+CONCURRENTLY\b", re.I),
     "cannot run inside a transaction: Flyway must be told to disable it for this script"),
]


def controlla(testo):
    """Returns the list of findings (line, severity, rule, reason), in line order."""
    rilievi = []
    for numero, riga in enumerate(testo.splitlines(), start=1):
        istruzione = riga.split("--", 1)[0]
        for codice, gravita, schema, motivo in REGOLE:
            if schema.search(istruzione):
                rilievi.append((numero, gravita, codice, motivo))
    return rilievi


def main(argv):
    if len(argv) != 2:
        print("usage: check_migration.py <file.sql>", file=sys.stderr)
        return 2
    with open(argv[1], encoding="utf-8") as f:
        rilievi = controlla(f.read())
    for numero, gravita, codice, motivo in rilievi:
        print(f"{numero:>3} {gravita:<6} {codice} {motivo}")
    if not rilievi:
        print("no findings (this does not mean it is safe)")
    return 1 if any(r[1] == "HIGH" for r in rilievi) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))

Three choices deserve an explanation. The first is the line istruzione = riga.split("--", 1)[0]: it discards SQL comments before applying the rules, otherwise a -- DROP TABLE vecchia in a comment would produce a false alarm. The second is the negative lookaheads: in (?!\s+CONCURRENTLY) the expression looks for a CREATE INDEX not followed by CONCURRENTLY, and in R3 (?!.*\bDEFAULT\b) excludes the line that declares a default value. The third is the exit code: main returns 1 only for findings of HIGH severity, so the same script serves Claude (who reads the lines) and an automatic check (which looks at the outcome). The return 2 on the number of arguments has a precise reason: without it a forgotten path would make Python terminate with an error and code 1, the same code that means "there are high findings", and an automatic check would read it as a migration to fix instead of as wrong usage.

The last line of the output, "no findings (this does not mean it is safe)", is not a courtesy: it is the first defense against a habit that leads astray, which is reading a check that stays silent as an approval.

Testing it on files you know

To know whether the script does what it declares you need files whose answer you know. I use two, written for the occasion on an ordini table (Italian for "orders") of a test project: the first contains four defects, the second is the corrected version of the same changes.

$ cat campioni/V12__ordini_stato.sql
# Output:
# -- test project: orders table
# ALTER TABLE ordini ADD COLUMN stato text NOT NULL;
# CREATE INDEX idx_ordini_stato ON ordini (stato);
# ALTER TABLE ordini ALTER COLUMN totale TYPE numeric(12,2);
# ALTER TABLE ordini DROP COLUMN note_vecchie;

$ python3 revisione-migration/scripts/check_migration.py campioni/V12__ordini_stato.sql; echo "exit code: $?"
# Output:
#   2 HIGH   R3 NOT NULL without DEFAULT fails if the table already has rows
#   3 HIGH   R2 without CONCURRENTLY it blocks writes to the table until the index is ready
#   4 MEDIUM R4 usually rewrites the table and its indexes: check whether the type change is binary-compatible
#   5 HIGH   R1 deletes data: the migration cannot be undone with another migration
# exit code: 1

$ cat campioni/V13__ordini_stato_sicura.sql
# Output:
# ALTER TABLE ordini ADD COLUMN stato text NOT NULL DEFAULT 'nuovo';
# CREATE INDEX CONCURRENTLY idx_ordini_stato ON ordini (stato);

$ python3 revisione-migration/scripts/check_migration.py campioni/V13__ordini_stato_sicura.sql; echo "exit code: $?"
# Output:
#   2 INFO   R5 cannot run inside a transaction: Flyway must be told to disable it for this script
# exit code: 0

The first file produces four findings, one for each defect I put in it, and exit code 1. The second, which adds the column with a default value and creates the index with CONCURRENTLY, produces only the R5 note and code 0. That note is the instructive part: the index fix creates a new problem, because CREATE INDEX CONCURRENTLY cannot be run inside a transaction block (the PostgreSQL documentation says so), and Flyway by default runs every migration inside a transaction. The Flyway documentation points to the script configuration files for customizing transaction handling; the property name and the syntax must be read there, because they depend on the Flyway version you use and I have not tested them here.

The tests: pinning the limits too

A script that flags dangers must be tested like a spell checker: every rule has a case that must fire and one that must not. The file uses only the standard library unittest, so it requires nothing to install.

import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent / "revisione-migration" / "scripts"))
from check_migration import controlla  # noqa: E402


def codici(sql):
    return [r[2] for r in controlla(sql)]


class RegoleDiControllo(unittest.TestCase):
    def test_indice_senza_concurrently_e_alta(self):
        self.assertEqual(codici("CREATE INDEX idx ON t (c);"), ["R2"])

    def test_indice_concurrently_e_solo_informativo(self):
        self.assertEqual(codici("CREATE INDEX CONCURRENTLY idx ON t (c);"), ["R5"])

    def test_not_null_con_default_passa(self):
        self.assertEqual(codici("ALTER TABLE t ADD COLUMN c text NOT NULL DEFAULT 'x';"), [])

    def test_not_null_senza_default_e_alta(self):
        self.assertEqual(codici("ALTER TABLE t ADD COLUMN c text NOT NULL;"), ["R3"])

    def test_un_commento_non_conta(self):
        self.assertEqual(codici("-- DROP TABLE t;"), [])

    def test_limite_noto_istruzione_su_piu_righe(self):
        # The check works line by line: this R3 slips through. The test pins the limit.
        sql = "ALTER TABLE t ADD COLUMN\n  c text NOT NULL;"
        self.assertEqual(codici(sql), [])


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

The most useful test is the last one, test_limite_noto_istruzione_su_piu_righe (the "known limit" test): it does not verify that the script works, it documents where it does not work. A line-by-line check cannot see a statement split across two lines, and I show it right away. The test passes because the expected outcome is "no findings": if one day you replace the regular expressions with an SQL parser, that test will fail and tell you the limit has been overcome.

$ python3 -m unittest -v test_check_migration
# Output:
# test_indice_concurrently_e_solo_informativo ... ok
# test_indice_senza_concurrently_e_alta ... ok
# test_limite_noto_istruzione_su_piu_righe ... ok
# test_not_null_con_default_passa ... ok
# test_not_null_senza_default_e_alta ... ok
# test_un_commento_non_conta ... ok
# ----------------------------------------------------------------------
# OK

Six tests, all green. The name of each states the rule and the case, so a failure can be read without opening the code. Now the demonstration of the limit, with the same R3 statement written across two lines:

$ cat campioni/V16__riga_spezzata.sql
# Output:
# ALTER TABLE ordini ADD COLUMN
#   stato text NOT NULL;

$ python3 revisione-migration/scripts/check_migration.py campioni/V16__riga_spezzata.sql
# Output:
# no findings (this does not mean it is safe)

The file has the same R3 defect as the first sample, but written on two lines, and the script does not see it: it prints "no findings". It is not a hidden bug, it is the price of the regular-expression approach, and that is why the body of the skill forces Claude not to declare the migration safe. When the skill becomes a check you really trust, the next step is a parser (for example one of the existing SQL parsers for PostgreSQL), and the test on the limit is the point where you notice it.

A second skill with dynamic context

The second skill solves a different problem: you do not want to name the files to check by hand. The !`command` syntax runs a shell command before Claude reads the text and substitutes its output for the placeholder. Here the command asks git for the list of SQL files modified with respect to HEAD.

---
description: Lists the SQL files modified with respect to HEAD and passes them to the migration check. Use before opening a pull request that touches the db/ folder.
disable-model-invocation: true
allowed-tools: Bash(git diff *) Bash(python3 ${CLAUDE_PROJECT_DIR}/.claude/skills/revisione-migration/scripts/check_migration.py *)
---

## Modified SQL files

!`git diff HEAD --name-only -- '*.sql'`

For each file listed above run `python3 ${CLAUDE_PROJECT_DIR}/.claude/skills/revisione-migration/scripts/check_migration.py <file>` and summarize the findings. If the list is empty, say so and stop.

Three details decide whether it works. First, injected commands never ask for permission while the skill is being composed: Claude Code checks them against the permission rules and, outside automatic mode, cancels the entire invocation if the answer is not "allowed". That is why allowed-tools lists git diff explicitly. Second, a command that exits with a non-zero code cancels the invocation: for git diff --name-only that is fine, for a check that exits with 1 when it finds problems you would need a || true. Third, disable-model-invocation: true: this skill reads the state of the repository and should be launched by you, with /, when you think you are done.

I ran the injected command in a test repository created for the occasion, with two SQL files and one non-SQL file; it is the list Claude would receive in place of the line. The full expansion inside Claude Code was not run, because it cannot be tested without running the model: it remains a sketch to adapt.

$ git diff HEAD --name-only -- '*.sql'
# Output:
# db/V15__b.sql

The file V15__b.sql is the only one modified and not yet committed, while V14__a.sql, already committed, does not appear because we compare against HEAD. If you want to check all the migrations of the pull request, the right comparison is with the target branch, for example git diff origin/main --name-only, and the command must be adapted to your workflow.

Installing it and proving that it starts

A project skill is installed by copying the folder into .claude/skills/ and committing it: from then on anyone working in the repository sees it. Claude Code watches the skill folders and picks up changes without restarting, except when the .claude/skills/ folder did not exist when the session started: then you need /reload-skills.

mkdir -p .claude/skills
cp -r revisione-migration .claude/skills/
git add .claude/skills/revisione-migration
# in Claude Code: /revisione-migration db/migration/V12__ordini_stato.sql
# to check that the frontmatter can be read (requires a recent version of Claude Code):
claude plugin validate .claude/skills

This block is a sketch to adapt and was not run: it requires a Claude Code session. The last command, the claude one, serves to check that the frontmatter can be read, because broken YAML produces no errors but a skill with no fields. The real question remains: does the skill start when it should? The documentation recommends a comparison with and without the skill on a few realistic prompts, in new sessions, because the context accumulated while writing the skill hides the gaps in the instructions. A minimal set of prompts is this one.

Must activate the skill:
  1. Check the migration db/migration/V12__ordini_stato.sql before the merge.
  2. Can I approve this V__*.sql file?
  3. Review the Flyway SQL script I have just written.

Must not activate it:
  4. Write me a query that counts orders by status.
  5. How do I configure Flyway in pom.xml?

The first three prompts take up the words of the description ("check", "approve", "review") in different forms; the last two touch the same topics without asking for a review, and if the skill starts there as well, the description is too broad. This too is a procedure, not a result: I could not run it without calling a model. To automate it the documentation points to claude plugin eval for skills distributed in a plugin and to the skill-creator plugin, which generates prompts that should and should not activate the skill and measures the activation rate.

When something goes wrong

If the skill does not start, the documentation proposes an order of checks: verify that the description contains the words the user really writes, that the skill appears in the listing when you ask Claude which skills it has, rephrase the request, invoke it directly with /name and, if it is not recognized even so, check that the name does not contain rejected characters. If it starts too often, either narrow the description or set disable-model-invocation: true. If Claude follows it in the first response and then stops, one of the cases described by the documentation is that the body enters the conversation only once and is not reread: instructions that must hold for the whole job should be written as standing rules ("run the tests after every change") and not as isolated steps. If the rule must always hold, no wording replaces a hook; we cover that in the last article of the series.

Frequently asked questions

Why is the script in Python and not in TypeScript?

Because the skill does not impose a language: the script is run by Bash and Claude sees only what it prints. Python has the advantage of being present on almost every development machine and of having a test module in the standard library; in a Node project it is better to write the same check in JavaScript, so as not to add a dependency.

Can I put the tools in the same package as the skill?

A skill contains instructions and files; tools with a schema belong to an MCP server, which is distributed separately or inside a plugin together with the skill. How to write a server is explained in the third article.

How do I share the skill with the team?

The simplest way is to commit the folder in the repository's .claude/skills/. To distribute it to several projects the documentation points to plugins, which are the subject of the article on publishing and versioning.

What you can do now

You can split a task between a script that checks and a skill that interprets, you can write the test cases that pin down the limits of the check as well, and you know which activation tests remain to be done by hand or with the evaluation tools. You have a skill you can copy into a project and adapt by changing the rules. The next step is to understand what happens when a script is not enough for a tool: the MCP protocol, in the revision that is current today.

Later in the series you will also find skills, plugins and MCP servers in an organization.

Sources

  • Extend Claude with skills - creating the first skill, allowed-tools, command injection and its errors, change detection, testing and troubleshooting. Consulted on 2026-11-13.
  • PostgreSQL, CREATE INDEX - a normal index blocks writes, CONCURRENTLY cannot run inside a transaction block. Consulted on 2026-11-13.
  • PostgreSQL, ALTER TABLE - NULL as the default of an added column, table rewrite with ALTER COLUMN TYPE. Consulted on 2026-11-13.
  • Flyway, migrations - every migration is wrapped in a transaction by default, existence of the script configuration files. Consulted on 2026-11-13.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects