This resume is also available in English.

8. Security and working with AI11 / 12 · All columns

Columns › 8. Security and working with AI › Part 57

Building Your Own AI Skill from Scratch: Doing It Right, and Turning Your Project’s Git Repo into a Claude Code Skill

從零做自己的 AI skill:正確做法,以及把專案 git 做成 Claude Code skill

Build your first Claude Code skill from the concepts up: what a skill is, when it is read and where it lives; a right-versus-wrong table of practices; then extract the conventions from a project’s git repo into an add-an-endpoint skill for the shop, with templates and a Go checker, and share it by committing it to the repo or packaging it as a plugin for other repos.

  • Claude Code
  • Skill
  • AI
  • Git
In this article
  1. What this article solves
  2. Step 1: The concepts — what a skill is and when it is read
  3. Step 2: Where it lives — personal, project or plugin
  4. Step 3: What doing it right looks like — one table
  5. Step 4: Find the real conventions in the project’s git repo
  6. Step 5: ① Create the folder, ② write the description, ③ write the steps and done criteria
  7. Step 6: ④ Add conventions and templates
  8. Step 7: ⑤ Add a checker
  9. Step 8: ⑥ Try it locally and ⑦ test triggering
  10. Step 9: ⑧ Commit to git so the team gets it on clone
  11. Step 10: Package a plugin and marketplace for other repos
  12. Common pitfalls
  13. Key takeaways
  14. References
  15. Next

The previous article, “AI as Your Second Brain: Organising Knowledge in Obsidian So Claude Code Can Use It”, made a project’s knowledge and decisions readable by the agent every time it starts work. This article handles something smaller and more concrete: turning a procedure you keep re-explaining into a skill. It is the beginner’s article. It starts from what a skill actually is, builds a first working skill step by step, explains what doing it correctly looks like, and finally covers how to use the project’s own git repo as the source of the skill and how to share it through git with the team and with other repos. Choosing existing skills, chaining skills into a workflow and measuring their effect are advanced topics left for the next article.

What this article solves

The shop’s order service keeps needing new APIs: cancel an order, partially refund it, list its items. This is a good job for Claude Code, but the results differ every time:

  • Inconsistent error format. The project rule is that every error returns {"error":{"code":"...","message":"..."}}, yet a new endpoint sometimes uses http.Error and returns plain text, which the front end’s error handling cannot parse.
  • Missing pieces. The handler is written but the route is never registered; or the route is there but the test is not; and docs/api/order.md goes un-updated eight times out of ten.
  • Everyone explains it differently. Some people remember to say “another user’s order must return 404”; others don’t. With the same agent, the result depends on who is giving the instructions.

“Building Go Microservices with Claude Code: Rules, Permissions and Security Review” already wrote a new-endpoint skill a few lines long. It says “follow the same structure” without saying what the structure is, so the agent has to guess, and the guesses produce the inconsistencies above. This article turns it into a complete skill whose content is not written from memory but extracted from the actual code in the repo.

This article will:

  1. Explain what a skill is and when Claude reads it (with concept diagrams).
  2. Show the three places a skill can live and which situation each suits.
  3. Set out correct and incorrect practices in one comparison table, with the reason for each.
  4. Find the real conventions in the project’s git repo and turn them into reference files, templates and a checker.
  5. Build shop-add-endpoint in eight steps (each with an illustration).
  6. Commit it to the repo so the team gets it on clone, or package it as a plugin and marketplace for other repos.
① Folder name = folder ② Description what and when ③ Steps + done a checkable end ④ Conventions quoted from repo ⑤ Checker code decides facts ⑥ Try it auto + slash ⑦ Trigger tests should / should not ⑧ Share git or plugin Missed or wrong trigger → back to ② and fix the description

Figure: Steps 5 to 9 walk through these eight steps in order. ② The description and ⑦ Trigger tests are highlighted because they decide whether the skill is used at the right moment; if the trigger tests fail, go back to ② and fix the description.

Step 1: The concepts — what a skill is and when it is read

A skill is a folder. It contains at least a SKILL.md; everything else is optional:

A skill = one folder; only SKILL.md is required shop-add-endpoint/ SKILL.md references/ templates/ scripts/ The instructions When to use it (description), steps, done criteria Convention details Read only when a step needs them: error format, naming Templates A real handler and test copied from the repo Checker Runs and hands back only OK / FAIL Like a job card for a new colleague: when to use it, how to do it, what done looks like

Figure: SKILL.md is the instructions: when to use it, the steps and the done criteria; references/ holds details, templates/ holds files to copy, and scripts/ holds checkers. Think of it as a job card for a new colleague.

SKILL.md has two parts: YAML at the top wrapped in --- (the frontmatter), whose most important fields are name and description, followed by ordinary Markdown with the steps for Claude. The smallest skill looks like this:

---
name: shop-add-endpoint
description: Add an HTTP API endpoint to a shop Go service. Use when asked to "add an API".
---

1. Read the existing endpoints in internal/<service>/.
2. Write the handler and test with the same structure.

That already works: Claude Code discovers it automatically, and you can invoke it directly with /shop-add-endpoint. Everything after this only makes it more reliable.

The biggest difference between a skill and a saved prompt is that a skill loads in layers.

① Always present: every skill’s name + description shop-add-endpoint: add or change an HTTP API endpoint in a shop Go service… shop-release-check: check whether a service can be released… …one entry per skill; more skills, more space A request matches, or /shop-add-endpoint is typed ② The full SKILL.md enters the conversation Steps, done criteria, which file to read when; it stays once loaded When a step needs it ③ On demand references/*.md Enters only when read templates/*.go Read when copying scripts/check-endpoint Runs; only its output enters Lower layers are bigger and load less often, so keep SKILL.md short and push detail down The checker’s source code never needs to enter the conversation

Figure: The first layer, every skill’s name and description, is present in every conversation; the second layer, the full SKILL.md, loads only when a request matches the description or the slash command is typed; reference files and templates are read when a step needs them, and only a checker’s output enters the conversation.

This design drives every writing decision that follows:

  • The description is always there, so make it short and precise. Install twenty skills and twenty descriptions occupy the context every time.
  • Once loaded, SKILL.md stays in the conversation, and Claude Code does not re-read the file later. So keep it short, and write rules that apply to the whole task.
  • Push detail down. Content needed only by one step, such as the error-code table or naming rules, goes in references/, and the step says when to read it.
  • Scripts are cheapest. A checker’s source code never needs to enter the conversation; only what it prints does.

Why the description matters so much becomes clear from triggering. When Claude decides whether to load a skill, the description is all it has:

“Add a partial-refund API to order” “Debug payment’s webhook 500s” /shop-add-endpoint order "GET …" Compare with every skill’s description Slash command: no matching, loads directly Loads shop-add-endpoint Loads nothing Debugging, not a new endpoint Before loading, Claude sees only the description: if it isn’t there, the body is never read

Figure: “Add a partial-refund API to order” matches the description and loads shop-add-endpoint; “Debug payment’s webhook 500s” is debugging, does not match and loads nothing; typing the slash command skips the matching and loads it directly.

So if the description doesn’t mention it, the body is never read, however good it is; if the description is too broad, the skill turns up when it isn’t wanted. Step 5 deals with the description in detail.

One last concept: skills are not a Claude Code-only format. The official documentation says Claude Code skills follow the Agent Skills open standard (agentskills.io), which works across multiple AI tools; Claude Code adds some fields of its own on top, such as controlling who can invoke a skill or running it in a subagent. Outside Claude Code, only the standard’s fields are allowed (name, description, license, compatibility, metadata, allowed-tools). If your skill will be used by other tools, keep its frontmatter to those.

Step 2: Where it lives — personal, project or plugin

Where a skill lives decides who gets it and how it is updated:

Personal ~/.claude/skills/<name>/ Who gets it Only you, every project here How it updates Takes effect on save Good for Personal habits, drafts Invoked as /<name> Project (git) .claude/skills/<name>/ Who gets it Everyone who clones the repo How it updates git pull, reviewed in PRs Good for Conventions tied to this repo Invoked as /<name> plugin <plugin>/skills/<name>/ Who gets it Installers, across repos How it updates Bump version; users update Good for Practices shared across repos Invoked as /<plugin>:<name> Same name: organisation > personal > project; plugin skills carry a prefix and never collide

Figure: The personal folder is for you on this machine; a project’s .claude/skills/ travels with git to everyone who clones it; a plugin is distributed to many repos through a marketplace and is invoked with the plugin name as a prefix.

LocationPathFitsDoes not fit
Personal~/.claude/skills/<name>/SKILL.mdHabits only you use; skills you are still experimenting withPractices the team must share: nobody else gets them or reviews them
Project (git).claude/skills/<name>/SKILL.mdConventions tied to this repo’s code, such as adding an endpointUse across ten repos: ten copies soon drift apart
Plugin<plugin>/skills/<name>/SKILL.mdPractices shared across repos, with one version and update pathOnly one repo uses it: an extra marketplace and versioning layer

A few rules worth knowing (all from the official documentation):

  • Precedence when names collide is organisation (deployed by an administrator) > personal > project. A same-named skill in your ~/.claude/skills/ overrides the one in the repo. So give team skills a project prefix: shop-add-endpoint, not add-endpoint.
  • Plugin skills are namespaced and invoked as /plugin-name:skill-name, so they never collide with anyone else’s.
  • Project skills are discovered from the start directory up to the repository root; subdirectories of a monorepo can have their own .claude/skills/.
  • Changes take effect immediately: Claude Code watches skill directories, so there is no restart; if a new skill doesn’t appear, run /reload-skills.

This article’s example lives in the project first (Step 9) and becomes a plugin only when other repos need it (Step 10). That is the recommended order: polish it in one repo, then spread it. Starting with a plugin means shipping an unproven practice to everyone.

Step 3: What doing it right looks like — one table

Read the rules before building; every later step uses them. The second column is the correct practice, the third the common mistake, and the last column the reason. The reasons matter more than the rules: when you meet a case the table doesn’t cover, decide by the reason.

RuleRightWrongWhy
Description says what and when“Add or change an HTTP API endpoint… use when asked to ‘add an API’. Not for debugging”“API helper”, “a powerful dev tool”Before loading, Claude sees only the description; no trigger words means no use, no boundary means misuse
One skill, one jobshop-add-endpoint only adds endpointsshop-dev covers endpoints, migrations, deploys and debuggingThe description grows broad and competes with other skills; once loaded, most of it is irrelevant
Keep SKILL.md shortOnly boundaries, steps, done criteria and which file to read when (official advice: under 500 lines)Pasting the whole developer handbookEvery line stays in the conversation once loaded; the longer it is, the easier important rules are missed
Detail in reference files, one level deepSKILL.md → references/error-codes.mdA reference file saying “see another reference file”, and so onThe Agent Skills spec advises file references only one level below SKILL.md; deep chains get read halfway
Say when to read each file“Before returning an error, read references/error-codes.md”A closing list: “References: a.md, b.md, c.md”Claude can’t tell which step needs which file, so it reads all of them or none
Content from real codeQuoted from cancel.go and httpjson.go, each rule citing its sourceAn “ideal” set of conventions written from memoryClaude reads the repo’s code too; when the skill and the code disagree, it can only guess which to follow
Deterministic checks in codecheck-endpoint checks route, test, error format and docs, and sets the exit code“Please make sure you wrote a test and registered the route”A model can say “confirmed” without confirming; a FAIL can’t be talked round, and CI can run the same tool
Checkable done criteria“check-endpoint all OK, go test -race passes, output pasted”“Make sure the quality is good when finished”If you can’t say what done looks like, the agent stops when it looks roughly right
Least tool permissionallowed-tools lists only specific read-only or local commandsBash(*), or allowing git pushTools in allowed-tools run without asking in that turn; the wider the list, the less stands in the way of a mistake
No secretsSteps that need credentials name the command; credentials come from the environment or a secret storeTokens or internal credentials written into SKILL.mdThe skill is committed to the repo, visible to anyone who can read it, and its content is sent to the model
Test with should and should-not promptsA few prompts that should and should not trigger, each run several timesTyping /name once to see that it runsThe slash command skips description matching; only plain-language prompts show whether automatic triggering works
Iterate from real failuresAdd “Step 5: write docs/api” after seeing the agent skip the docsWriting fifty rules up frontA rule that has never been broken only takes space; when each rule maps to a real failure, you know which can go
Prefixed name matching the foldershop-add-endpoint/, name: shop-add-endpointFolder endpoint, name: Endpoint HelperThe spec requires lowercase letters, digits and hyphens matching the folder; a prefix stops personal skills overriding it

Several of these are discussed in more depth in “Getting More from AI Agent Skills: Choosing, Writing and Chaining Them into a Workflow” (how to write descriptions, security, measurement); this article uses only what a beginner needs.

Step 4: Find the real conventions in the project’s git repo

“Turning a project’s git repo into a skill” means two things: first, the content comes from the repo — conventions, templates and checks are extracted from real code and history; second, git stores and shares it — the skill is committed to the repo, or packaged as a plugin for other repos to install. This step does the first; Steps 9 and 10 do the second.

Project git repo (the source) The skill folder routes.go, httpjson.go git log -- internal/order grep -rn writeError cancel.go, cancel_test.go The “must” conventions references/conventions.md references/error-codes.md templates/handler*.go scripts/check-endpoint quote + cite tabulate copy as is turn into code Keep in sync: a convention changes in code → the same PR changes the skill CI diffs templates against their sources and runs check-endpoint on an existing endpoint

Figure: The left side is the source of truth, the right side the skill folder. Conventions are quoted from code with sources cited, error codes are tabulated from a search, a representative endpoint is copied as the template, and the “must” conventions become a checker; when the code changes, the same PR updates the skill.

First find a representative endpoint. Not the newest (it may not have settled) or the most complex (too many exceptions), but one everyone agrees is written correctly, recently changed and reviewed. Use git to find it:

# Which order endpoints changed in the last year, and who changed them
git log --since=1.year --format='%h %an %s' -- internal/order/

# How errors are returned: where each error code appears
grep -rn 'writeError(' internal/

# Is anyone still using http.Error (this is what the skill will forbid)
grep -rn 'http.Error(' internal/

# Where routes are registered
grep -rn 'HandleFunc(' internal/order/

These commands answer four questions: what the convention is, whether there are exceptions, whether the exceptions are old or new, and which file to copy. Suppose they show that cancel.go was rewritten and reviewed last month, and only two old files still use http.Error (with a ticket already open to fix them). Then cancel.go is the template, and http.Error is the style to forbid explicitly.

Read the commit messages and PR discussions too. A decision such as “another user’s order returns 404, not 403” is at most one comment in the code; the reasoning lives in the original PR. Put the reasoning in the reference file so that when Claude meets a similar but not identical case (someone else’s refund, say), it knows how to generalise.

Below are the endpoint-related files in the shop’s internal/order/ (only the parts this article uses; Order, ErrNotFound, ErrConflict and UserIDFrom in order.go follow the earlier articles in the series). First, httpjson.go, the single exit for error responses:

// internal/order/httpjson.go
package order

import (
	"encoding/json"
	"net/http"
)

// Every error response is {"error":{"code":"...","message":"..."}}.
type errorBody struct {
	Error errorDetail `json:"error"`
}

type errorDetail struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

// writeError is the only way to return an error; code is snake_case for programs to check.
func writeError(w http.ResponseWriter, status int, code, msg string) {
	writeJSON(w, status, errorBody{Error: errorDetail{Code: code, Message: msg}})
}

Routes are registered in one place, and handlers depend on one small interface (the approach from “Layered Architecture and Dependency Injection in Go”):

// internal/order/routes.go
package order

import (
	"context"
	"log/slog"
	"net/http"
)

type orderService interface {
	Cancel(ctx context.Context, userID, orderID int64) (Order, error)
}

type Handler struct {
	svc    orderService
	logger *slog.Logger
}

func NewHandler(svc orderService, logger *slog.Logger) *Handler {
	return &Handler{svc: svc, logger: logger}
}

// Routes is the only place the order service registers routes.
func (h *Handler) Routes(mux *http.ServeMux) {
	mux.HandleFunc("POST /orders/{id}/cancel", h.cancel)
}

The representative endpoint, cancel.go: check identity, parse the parameter, call the service, and map each error to a status and an error code:

// internal/order/cancel.go
package order

import (
	"errors"
	"net/http"
	"strconv"
)

// cancel cancels an unpaid order. Only the order’s owner may cancel it.
func (h *Handler) cancel(w http.ResponseWriter, r *http.Request) {
	userID, ok := UserIDFrom(r.Context())
	if !ok {
		writeError(w, http.StatusUnauthorized, "unauthenticated", "login required")
		return
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil || id <= 0 {
		writeError(w, http.StatusBadRequest, "invalid_id", "id must be a positive integer")
		return
	}

	o, err := h.svc.Cancel(r.Context(), userID, id)
	switch {
	case errors.Is(err, ErrNotFound):
		// Another user's order also gets 404, so its existence is not revealed.
		writeError(w, http.StatusNotFound, "not_found", "order not found")
		return
	case errors.Is(err, ErrConflict):
		writeError(w, http.StatusConflict, "conflict", "order cannot be cancelled in its current state")
		return
	case err != nil:
		h.logger.ErrorContext(r.Context(), "cancel order", "order_id", id, "err", err)
		writeError(w, http.StatusInternalServerError, "internal", "internal error")
		return
	}
	writeJSON(w, http.StatusOK, o)
}

Its test calls the handler through the real routes (for the reason, see “Testing in Go: Table-Driven Tests, httptest and Integration Tests”: bypass the ServeMux and PathValue returns an empty string), and the fake service uses function fields so each case decides what to return:

// internal/order/cancel_test.go
package order

import (
	"context"
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"testing"
)

type fakeService struct {
	cancel func(ctx context.Context, userID, orderID int64) (Order, error)
}

func (f fakeService) Cancel(ctx context.Context, userID, orderID int64) (Order, error) {
	return f.cancel(ctx, userID, orderID)
}

// newTestMux tests through the real routes so PathValue and method matching work.
func newTestMux(svc orderService) *http.ServeMux {
	mux := http.NewServeMux()
	NewHandler(svc, slog.New(slog.NewTextHandler(io.Discard, nil))).Routes(mux)
	return mux
}

func TestHandler_cancel(t *testing.T) {
	ok := func(_ context.Context, userID, orderID int64) (Order, error) {
		return Order{ID: orderID, UserID: userID, Total: 1500, Status: "cancelled"}, nil
	}
	fail := func(err error) func(context.Context, int64, int64) (Order, error) {
		return func(context.Context, int64, int64) (Order, error) { return Order{}, err }
	}

	tests := []struct {
		name     string
		path     string
		login    bool
		svc      func(context.Context, int64, int64) (Order, error)
		wantCode int
		wantErr  string
	}{
		{"ok", "/orders/42/cancel", true, ok, http.StatusOK, ""},
		{"not logged in", "/orders/42/cancel", false, ok, http.StatusUnauthorized, "unauthenticated"},
		{"bad id", "/orders/abc/cancel", true, ok, http.StatusBadRequest, "invalid_id"},
		{"someone else's order", "/orders/42/cancel", true, fail(ErrNotFound), http.StatusNotFound, "not_found"},
		{"already paid", "/orders/42/cancel", true, fail(ErrConflict), http.StatusConflict, "conflict"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodPost, tt.path, nil)
			if tt.login {
				req = req.WithContext(WithUserID(req.Context(), 7))
			}
			rec := httptest.NewRecorder()
			newTestMux(fakeService{cancel: tt.svc}).ServeHTTP(rec, req)

			if rec.Code != tt.wantCode {
				t.Fatalf("status = %d, want %d", rec.Code, tt.wantCode)
			}
			if tt.wantErr == "" {
				return
			}
			var body errorBody
			if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
				t.Fatalf("decode error body: %v", err)
			}
			if body.Error.Code != tt.wantErr {
				t.Errorf("error.code = %q, want %q", body.Error.Code, tt.wantErr)
			}
		})
	}
}

The API docs have one section per endpoint:

# order API

## POST /orders/{id}/cancel

Cancels an unpaid order. Only the owner may cancel it.

| Status | error.code      | When                               |
| ------ | --------------- | ---------------------------------- |
| 200    |                 | Success; returns the order         |
| 400    | invalid_id      | id is not a positive integer       |
| 401    | unauthenticated | Not logged in                      |
| 404    | not_found       | Missing, or not the caller's order |
| 409    | conflict        | Already paid or cancelled          |

The conventions now have a precise basis. Every rule written into the skill from here on must point back to a line above.

Step 5: ① Create the folder, ② write the description, ③ write the steps and done criteria

① Create the folder

Illustration ① Create the folder Terminal: repo root $ mkdir -p .claude/skills/shop-add-endpoint/{references,templates,scripts} A $ touch .claude/skills/shop-add-endpoint/SKILL.md $ find .claude/skills -maxdepth 2 | sort .claude/skills .claude/skills/shop-add-endpoint .claude/skills/shop-add-endpoint/SKILL.md B .claude/skills/shop-add-endpoint/references .claude/skills/shop-add-endpoint/scripts .claude/skills/shop-add-endpoint/templates A Create a folder under the repo’s .claude/skills/; its name is the skill’s name B Only SKILL.md is required; the other three folders are conventions C Use lowercase letters, digits and hyphens, with a project prefix

Figure: Illustration. Create .claude/skills/shop-add-endpoint/ with three subfolders from the repo root, then an empty SKILL.md.

mkdir -p .claude/skills/shop-add-endpoint/{references,templates,scripts}
touch .claude/skills/shop-add-endpoint/SKILL.md

The folder’s name is the skill’s name. The Agent Skills spec requires names to use only lowercase letters, digits and hyphens, up to 64 characters, not starting or ending with a hyphen, and matching the folder; Claude Code also falls back to the folder name when name is omitted. references/ and scripts/ are the spec’s suggested names (the spec puts static resources such as templates in assets/; this article uses the plainer templates/, and the spec allows any other folder). Don’t create folders you won’t use.

② Write the description

Illustration ② Write the description SKILL.md --- name: shop-add-endpoint A description: Add or change an HTTP API endpoint in a shop Go service, B following project conventions for handler, test, route and docs. Use when asked to "add an API", "new endpoint", "add an endpoint". C Not for deploys, database migrations or api-gateway routing. D argument-hint: '<service> "<METHOD> <path>" <...>' --- A name matches the folder; it is also the slash command /shop-add-endpoint B What: one sentence on the result, with the main use first C When: the words people actually say, in every language the team uses D Not: draw the boundary so it doesn’t steal another skill’s work

Figure: Illustration. The description is split into what it does, when to use it and what it does not do; name matches the folder and is also the slash command.

A good description answers three questions:

  1. What it does: one sentence on the result, placed first. The official documentation says each skill’s description in the skill listing (plus the optional when_to_use) is truncated beyond 1,536 characters, and with many skills, the descriptions of the least-used ones may be dropped entirely. Putting the keywords first is safest.
  2. When to use it: the words people actually say. The team mixes Chinese and English, so the trigger phrases cover both.
  3. What it does not do: “not for debugging, deploys, database migrations or api-gateway routing”. This keeps Claude from picking the skill for “look into this 500”, and keeps the boundary with other skills clear.

③ Write the steps and done criteria

Illustration ③ Write the steps and done criteria SKILL.md (body) # Add an API endpoint Target: $ARGUMENTS. Ask if the service or route is unclear. Only edit internal/<service>/ and docs/api/<service>.md. A ## Steps 1. Read references/conventions.md and one existing endpoint 2. Write TestHandler_<method> first; see it fail 3. Write the handler; codes in references/error-codes.md B 4. Register route 5. Write docs/api 6. Run check-endpoint ## Done when - check-endpoint all OK, go vet and go test -race pass C - Paste the real output of all three; list what is untested A Boundaries first: what may be edited, what must not be done B One action per step, saying which file to read and when C Done criteria must be checkable: commands and output, not “do it well”

Figure: Illustration. Boundaries first, then the steps, then checkable done criteria; each step says which file to read and when.

The complete SKILL.md:

---
name: shop-add-endpoint
description: Add or change an HTTP API endpoint in a shop Go service (order, payment, inventory), following project conventions for the handler, table-driven tests, route registration and docs/api, then verify with check-endpoint. Use when asked to "add an API", "add an endpoint", "open a POST /orders/...", or "change an endpoint's response". Not for debugging, deploys, database migrations or api-gateway routing.
argument-hint: '<service> "<METHOD> <path>" <description>'
allowed-tools: Bash(go run ${CLAUDE_SKILL_DIR}/scripts/check-endpoint/main.go *) Bash(go vet *) Bash(go test *) Bash(gofmt -l *)
---

# Add an API endpoint

Target: $ARGUMENTS (for example `order "POST /orders/{id}/refunds" partial refund`). If the service, method or path is unclear, ask; do not guess.

Only edit `internal/<service>/` and `docs/api/<service>.md`. If the database schema, api-gateway or dependencies need to change, stop and explain what is needed; do not do it yourself. These rules apply for the whole task.

## Steps

1. Read references/conventions.md, then `internal/<service>/routes.go` and one existing endpoint (for order, cancel.go and cancel_test.go), and confirm the conventions match the reference file; if they differ, follow the code and say so in your report.
2. Write the test first: following templates/handler_test.go, add `TestHandler_<method>` in `internal/<service>/<action>_test.go`, covering at least success, not logged in, invalid input and someone else's resource (404). Run `go test ./internal/<service>/...` and confirm the new test fails.
3. Write the handler: following templates/handler.go, one endpoint per file, `<action>.go`. Before returning an error, read references/error-codes.md to pick the code; if none fits, report it and propose a new code instead of inventing one.
4. Register the route in `Routes` in `routes.go`.
5. Add a `## <METHOD> <path>` section to `docs/api/<service>.md`, with a status table in the existing format.
6. Run the checker and fix every FAIL until all are OK:

   ```sh
   go run ${CLAUDE_SKILL_DIR}/scripts/check-endpoint/main.go -service <service> -route "<METHOD> <path>"
   ```

7. Run `gofmt -l internal/`, `go vet ./...` and `go test -race ./internal/<service>/...`.

## Done when

- check-endpoint is all OK, `gofmt -l` prints nothing, and `go vet` and `go test -race` pass.
- Your report pastes the real output of these commands and lists the files changed and the cases left untested.

The reasoning, point by point:

  • Boundaries first. “Only edit internal/<service>/ and docs/api/<service>.md”, “stop if the schema must change” — adding an endpoint easily turns into doing one more thing “while I’m here”, and drawing the line up front works better than reminding afterwards.
  • “These rules apply for the whole task.” SKILL.md stays in the conversation once loaded, but Claude Code doesn’t re-read the file; standing rules are more reliable than one-off reminders.
  • Step 1 compares with the code first. However careful, a reference file goes stale; having Claude read a real endpoint first, follow the code when they differ and report it, surfaces a stale skill instead of quietly repeating the old style.
  • Write the test first and watch it fail. A test you have never seen fail doesn’t prove it tests the new code.
  • No invented error codes. Error codes are for the front end and other services to act on, and a new one needs discussion; if none fits, report it rather than making up a name.
  • $ARGUMENTS. The arguments given on invocation replace this placeholder, for example /shop-add-endpoint order "POST /orders/{id}/refunds" partial refund. Without arguments, the skill asks.
  • ${CLAUDE_SKILL_DIR}. The official documentation describes this variable as the folder containing SKILL.md, regardless of the current working directory. Pointing to the checker through it means nothing changes when the skill later moves into a plugin (with a different path).
  • allowed-tools lists only specific commands. Tools listed here run without asking during the turn that invokes the skill, and the grant clears when you send your next message; it doesn’t restrict other tools. Here it lists only the checker itself, go vet, go test and gofmt -l (which lists, never edits); writing files still follows your usual permission settings. The official documentation’s example also allows a bundled script by writing its full path with ${CLAUDE_SKILL_DIR}.
  • No disable-model-invocation. The skill creates files, but someone saying “add an API” wants files changed anyway; the skill only makes the changes consistent, and everything is in git and reversible. Skills that touch external systems (deploying, pushing, writing to a production database) are the ones to restrict to manual invocation.

Step 6: ④ Add conventions and templates

Illustration ④ Add conventions and templates references/conventions.md # Endpoint conventions for the order service Source: internal/order/ (main, commit 3f9c2e1) A - One file per endpoint: <action>.go + <action>_test.go (source: cancel.go, cancel_test.go) B - Errors only via writeError; never http.Error (source: writeError in httpjson.go) - Another user’s order returns 404 not_found, not 403 (source: comment in cancel.go) A Record which commit it was taken from, so you know when to refresh it B Cite a source file for each rule, so Claude and reviewers can verify C Templates are copies of real files: templates/handler.go is cancel.go D One level only: SKILL.md points to references; they point nowhere else

Figure: Illustration. Every convention cites its source file, and the header records the commit it was taken from; templates are copies of real files; references are one level deep.

references/conventions.md lists the conventions found in Step 4, each with its source:

# Endpoint conventions for the order service

Source: `internal/order/` (main, commit 3f9c2e1). Where the code and this file disagree, follow the code and update this file.

## Files and routes

- One file per endpoint: `<action>.go` + `<action>_test.go`. (source: cancel.go, cancel_test.go)
- Routes are registered only in `(*Handler).Routes` in `routes.go`: `mux.HandleFunc("<METHOD> <path>", h.<method>)`, with a lowercase method name. (source: routes.go)
- Handlers depend only on the `orderService` interface in `routes.go`; add any service method a new endpoint needs to that interface. (source: routes.go)

## Requests

- Identity: `UserIDFrom(r.Context())`; 401 if absent. (source: cancel.go)
- Path parameters: `r.PathValue` plus `strconv.ParseInt`; 400 unless a positive integer. (source: cancel.go)
- Requests with a body: limit to 1 MiB with `http.MaxBytesReader` and turn on `DisallowUnknownFields` on the `json.Decoder`. (source: security rules in CLAUDE.md)

## Responses

- Success: `writeJSON(w, status, v)`. (source: httpjson.go)
- Errors: only `writeError(w, status, code, msg)`; the body is `{"error":{"code":"...","message":"..."}}`; never `http.Error`. (source: httpjson.go)
- Someone else's resource returns 404, not 403, so its existence is not revealed. (source: comment in cancel.go)
- 500: log with `h.logger.ErrorContext`, return `internal`, and never send the err text to the client. (source: cancel.go)
- Amount fields are always int64 minor units.

## Tests

- Name `TestHandler_<method>`, table-driven, going through the real routes via `newTestMux`. (source: cancel_test.go)
- The fake service uses function fields so each case decides what it returns. (source: fakeService in cancel_test.go)

## Docs

- One section per endpoint in `docs/api/<service>.md`, headed `## <METHOD> <path>`, followed by a status table. (source: docs/api/order.md)

references/error-codes.md is the error-code table, read only “before returning an error”:

# Error codes

Source: `grep -rn 'writeError(' internal/` (main, commit 3f9c2e1). Explain any new code in the PR and update this table.

| Status | code            | When                                         |
| ------ | --------------- | -------------------------------------------- |
| 400    | invalid_id      | The ID in the path is not a positive integer |
| 400    | invalid_body    | Malformed JSON, unknown fields, too large    |
| 401    | unauthenticated | Not logged in                                |
| 404    | not_found       | Missing, or not the caller's resource        |
| 409    | conflict        | State forbids it (for example, already paid) |
| 500    | internal        | Anything else; details go to the log only    |

(The table reflects a search across all of internal/, so it includes codes such as invalid_body used by endpoints other than the cancel.go excerpted above.)

The templates are straight copies of real files:

cp internal/order/cancel.go      .claude/skills/shop-add-endpoint/templates/handler.go
cp internal/order/cancel_test.go .claude/skills/shop-add-endpoint/templates/handler_test.go

Why copy, rather than write a template with {{.Name}} placeholders? Because the real file compiles, is tested and was reviewed, so Claude only has to rename things; a hand-written template has never been compiled, and its mistakes get faithfully copied into every new endpoint. The templates sit under .claude/, and Go tools skip directories starting with . when matching ./..., so they are never compiled as project code.

Templates and their sources drift apart over time, so decide which is the original. There are two approaches:

ApproachFitsCost
Don’t copy; point SKILL.md straight at cancel.goThe skill is used only in this repoWhen it moves into a plugin, other repos don’t have that file
Copy into templates/ and check with diff in CIThe skill may leave the repo, or the template should stay at a reviewed versionChanging cancel.go means updating the template too (CI will remind you)

This article takes the second, because Step 10 turns it into a plugin. Step 9 adds the diff to CI.

Step 7: ⑤ Add a checker

“Is there a test?”, “is the route registered?”, “is http.Error used?”, “do the docs have the section?” — all four have definite answers, so they go to code. Claude runs it when finished and fixes whatever FAILs; CI can run the same tool.

Illustration ⑤ Add a checker Terminal: checking a half-done endpoint $ go -C .claude/skills/shop-add-endpoint/scripts/check-endpoint run . \ -root "$PWD" -service order -route "POST /orders/{id}/refunds" OK route POST /orders/{id}/refunds → h.refund OK handler internal/order/refund.go:7 FAIL errors internal/order/refund.go:9 uses http.Error; use writeError A FAIL test TestHandler_refund not found FAIL docs docs/api/order.md has no "## POST /orders/{id}/refunds" exit status 1 B A Every FAIL has a location and a fix, so Claude doesn’t have to guess B Exit code 1 on any FAIL: the skill uses it to decide done; CI can too C “Is there a test?” and “is the route registered?” are answered by code

Figure: Illustration. The route and handler pass; the error format, test and docs fail, each with a location and a fix; any FAIL sets exit code 1.

The checker lives in scripts/check-endpoint/ and uses only the standard library. It reads the source with go/parser rather than matching text with regular expressions, so http.Error in a comment is not a false alarm, and different line breaks or spacing are not missed:

// .claude/skills/shop-add-endpoint/scripts/check-endpoint/main.go
// check-endpoint checks that a new endpoint follows the shop conventions:
// the route is registered, the handler exists, it has a test, it avoids http.Error, and the API docs have a section.
package main

import (
	"bufio"
	"flag"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type result struct {
	ok    bool
	item  string
	about string
}

func main() {
	root := flag.String("root", ".", "repo root")
	service := flag.String("service", "", "service name, e.g. order")
	route := flag.String("route", "", `route pattern, e.g. "POST /orders/{id}/refunds"`)
	flag.Parse()
	if *service == "" || *route == "" {
		fmt.Fprintln(os.Stderr, "usage: check-endpoint -root <repo> -service <name> -route \"<METHOD> <path>\"")
		os.Exit(2)
	}
	results, err := check(*root, *service, *route)
	if err != nil {
		fmt.Fprintln(os.Stderr, "check-endpoint:", err)
		os.Exit(2)
	}
	if report(os.Stdout, results) {
		os.Exit(1)
	}
}

// report prints every result and returns true if anything failed.
func report(w io.Writer, results []result) bool {
	failed := false
	for _, r := range results {
		status := "OK  "
		if !r.ok {
			status, failed = "FAIL", true
		}
		fmt.Fprintf(w, "%s %-8s %s\n", status, r.item, r.about)
	}
	return failed
}

func check(root, service, route string) ([]result, error) {
	pkgDir := filepath.Join(root, "internal", service)
	fset := token.NewFileSet()
	entries, err := os.ReadDir(pkgDir)
	if err != nil {
		return nil, err
	}
	var files, tests []*ast.File
	for _, e := range entries {
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") {
			continue
		}
		f, err := parser.ParseFile(fset, filepath.Join(pkgDir, e.Name()), nil, 0)
		if err != nil {
			return nil, err
		}
		if strings.HasSuffix(e.Name(), "_test.go") {
			tests = append(tests, f)
		} else {
			files = append(files, f)
		}
	}

	at := func(pos token.Pos) string {
		p := fset.Position(pos)
		return fmt.Sprintf("%s:%d", relTo(root, p.Filename), p.Line)
	}

	var out []result
	name := findRoute(files, route)
	if name == "" {
		out = append(out, result{false, "route", fmt.Sprintf("no mux.HandleFunc(%q, h.<method>) in Routes", route)})
		// Without a route there is no handler name, so skip the remaining checks.
		return append(out, checkDocs(root, service, route)), nil
	}
	out = append(out, result{true, "route", fmt.Sprintf("%s → h.%s", route, name)})

	fn := findMethod(files, name)
	if fn == nil {
		out = append(out, result{false, "handler", "func (h *Handler) " + name + " not found"})
	} else {
		out = append(out, result{true, "handler", at(fn.Pos())})
		if pos, found := findHTTPError(fn); found {
			out = append(out, result{false, "errors", at(pos) + " uses http.Error; use writeError"})
		} else {
			out = append(out, result{true, "errors", "writeError only"})
		}
	}

	testName := "TestHandler_" + name
	if hasFunc(tests, testName) {
		out = append(out, result{true, "test", testName})
	} else {
		out = append(out, result{false, "test", testName + " not found"})
	}
	return append(out, checkDocs(root, service, route)), nil
}

// findRoute returns <name> from mux.HandleFunc("<route>", h.<name>).
func findRoute(files []*ast.File, route string) string {
	var name string
	for _, f := range files {
		ast.Inspect(f, func(n ast.Node) bool {
			call, ok := n.(*ast.CallExpr)
			if !ok || len(call.Args) != 2 {
				return true
			}
			sel, ok := call.Fun.(*ast.SelectorExpr)
			if !ok || sel.Sel.Name != "HandleFunc" {
				return true
			}
			lit, ok := call.Args[0].(*ast.BasicLit)
			if !ok || lit.Kind != token.STRING {
				return true
			}
			if s, err := strconv.Unquote(lit.Value); err != nil || s != route {
				return true
			}
			if h, ok := call.Args[1].(*ast.SelectorExpr); ok {
				name = h.Sel.Name
			}
			return false
		})
	}
	return name
}

func findMethod(files []*ast.File, name string) *ast.FuncDecl {
	for _, f := range files {
		for _, d := range f.Decls {
			fn, ok := d.(*ast.FuncDecl)
			if !ok || fn.Recv == nil || fn.Name.Name != name || len(fn.Recv.List) != 1 {
				continue
			}
			if star, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok {
				if id, ok := star.X.(*ast.Ident); ok && id.Name == "Handler" {
					return fn
				}
			}
		}
	}
	return nil
}

func findHTTPError(fn *ast.FuncDecl) (token.Pos, bool) {
	var pos token.Pos
	ast.Inspect(fn, func(n ast.Node) bool {
		sel, ok := n.(*ast.SelectorExpr)
		if ok && sel.Sel.Name == "Error" {
			if id, ok := sel.X.(*ast.Ident); ok && id.Name == "http" {
				pos = sel.Pos()
				return false
			}
		}
		return pos == token.NoPos
	})
	return pos, pos != token.NoPos
}

func hasFunc(files []*ast.File, name string) bool {
	for _, f := range files {
		for _, d := range f.Decls {
			if fn, ok := d.(*ast.FuncDecl); ok && fn.Recv == nil && fn.Name.Name == name {
				return true
			}
		}
	}
	return false
}

// checkDocs confirms docs/api/<service>.md has a "## <route>" section.
func checkDocs(root, service, route string) result {
	path := filepath.Join(root, "docs", "api", service+".md")
	name := relTo(root, path)
	f, err := os.Open(path)
	if err != nil {
		return result{false, "docs", name + " not found"}
	}
	defer f.Close()
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		if strings.TrimSpace(sc.Text()) == "## "+route {
			return result{true, "docs", name}
		}
	}
	return result{false, "docs", name + " has no \"## " + route + "\" section"}
}

// relTo makes paths relative to the repo root, ready to paste into a report.
func relTo(root, path string) string {
	if r, err := filepath.Rel(root, path); err == nil {
		return r
	}
	return path
}

It has its own go.mod (module shop-add-endpoint/check-endpoint), so this folder still builds and tests on its own after leaving the shop’s repo (for example, moving into a plugin repo). Run as a single file with go run from the repo root, the default -root of . is the repo root.

The test builds a minimal repo in a temporary directory, and each case removes or breaks exactly one thing and checks that only that item fails:

// .claude/skills/shop-add-endpoint/scripts/check-endpoint/main_test.go
package main

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

const routes = `package order

import "net/http"

type Handler struct{}

func (h *Handler) Routes(mux *http.ServeMux) {
	mux.HandleFunc("POST /orders/{id}/refunds", h.refund)
}
`

const goodHandler = `package order

import "net/http"

func (h *Handler) refund(w http.ResponseWriter, r *http.Request) {
	writeError(w, http.StatusBadRequest, "invalid_amount", "amount must be positive")
}
`

const badHandler = `package order

import "net/http"

func (h *Handler) refund(w http.ResponseWriter, r *http.Request) {
	http.Error(w, "bad amount", http.StatusBadRequest)
}
`

const goodTest = `package order

import "testing"

func TestHandler_refund(t *testing.T) {}
`

const docs = "# order API\n\n## POST /orders/{id}/refunds\n"

// writeRepo builds a minimal repo in a temp dir; files with empty content are skipped.
func writeRepo(t *testing.T, files map[string]string) string {
	t.Helper()
	root := t.TempDir()
	for name, body := range files {
		if body == "" {
			continue
		}
		p := filepath.Join(root, name)
		if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
			t.Fatal(err)
		}
	}
	return root
}

func TestCheck(t *testing.T) {
	const route = "POST /orders/{id}/refunds"
	tests := []struct {
		name     string
		routes   string
		handler  string
		test     string
		docs     string
		wantFail []string // items expected to FAIL
	}{
		{"all good", routes, goodHandler, goodTest, docs, nil},
		{"route not registered", strings.Replace(routes, "refunds", "refund", 1), goodHandler, goodTest, docs, []string{"route"}},
		{"uses http.Error", routes, badHandler, goodTest, docs, []string{"errors"}},
		{"no test", routes, goodHandler, "", docs, []string{"test"}},
		{"no docs section", routes, goodHandler, goodTest, "# order API\n", []string{"docs"}},
		{"handler missing", routes, "", goodTest, docs, []string{"handler"}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			root := writeRepo(t, map[string]string{
				"internal/order/routes.go":      tt.routes,
				"internal/order/refund.go":      tt.handler,
				"internal/order/refund_test.go": tt.test,
				"docs/api/order.md":             tt.docs,
			})
			results, err := check(root, "order", route)
			if err != nil {
				t.Fatal(err)
			}
			var got []string
			for _, r := range results {
				if !r.ok {
					got = append(got, r.item)
				}
			}
			if strings.Join(got, ",") != strings.Join(tt.wantFail, ",") {
				t.Errorf("FAIL items = %v, want %v\n%v", got, tt.wantFail, results)
			}
		})
	}
}

Here is what running it looks like. On the existing cancel endpoint:

$ go run ./.claude/skills/shop-add-endpoint/scripts/check-endpoint/main.go -service order -route "POST /orders/{id}/cancel"
OK   route    POST /orders/{id}/cancel → h.cancel
OK   handler  internal/order/cancel.go:10
OK   errors   writeError only
OK   test     TestHandler_cancel
OK   docs     docs/api/order.md

On a half-done refund endpoint (using http.Error, no test, no docs):

$ go run ./.claude/skills/shop-add-endpoint/scripts/check-endpoint/main.go -service order -route "POST /orders/{id}/refunds"
OK   route    POST /orders/{id}/refunds → h.refund
OK   handler  internal/order/refund.go:7
FAIL errors   internal/order/refund.go:9 uses http.Error; use writeError
FAIL test     TestHandler_refund not found
FAIL docs     docs/api/order.md has no "## POST /orders/{id}/refunds" section
exit status 1

What belongs in code and what stays with the model? The test is whether there is a definite answer. Whether the route is registered or the test function exists: yes. “Should this error be 404 or 409?”, “are there enough test cases?”: those need an understanding of the requirement, so they stay with the model, which must give its reasons in the report. The other test is whether the check is useful outside the skill: check-endpoint is useful in CI too, so it needs tests and must be stable; a small script that exists only for the skill can be simpler.

Step 8: ⑥ Try it locally and ⑦ test triggering

⑥ Try it locally

Illustration ⑥ Try it locally Claude Code session > Add a partial-refund API to order: POST /orders/{id}/refunds A (skill loaded: shop-add-endpoint) Reading references/conventions.md and cancel.go… > /shop-add-endpoint payment "POST /payments/{id}/capture" capture B > What skills are available? C shop-add-endpoint: Add or change an HTTP API endpoint… A Automatic: state the need in plain words and see whether it loads B Slash command: invoke it directly with arguments; the most reliable C Missing? Ask which skills exist, run /reload-skills, check the frontmatter

Figure: Illustration. State the need in plain words and see whether it loads by itself; invoke it directly with the slash command; if the skill is missing, first ask which skills are available.

Try both ways of invoking it:

  1. Automatic triggering. Open Claude Code in the repo and say it plainly: “Add a partial-refund API to order: POST /orders/{id}/refunds”. Watch whether it loads shop-add-endpoint, reads the reference file first and writes the test first, as the steps say.
  2. Slash command. /shop-add-endpoint payment "POST /payments/{id}/capture" capture. This path skips description matching and confirms the content itself works.

If the skill doesn’t show up, follow the official troubleshooting order:

  • Ask Claude “What skills are available?” and confirm it is listed. If a new skill hasn’t appeared, run /reload-skills.
  • A frontmatter parse failure is the most common cause. The official documentation says that when the YAML is malformed, the skill still loads but with empty metadata — /name still works, but Claude can’t match against the description, so it never triggers automatically. Colons and quotes in the description are the usual culprits. Starting with claude --debug shows the parse error; recent versions of Claude Code can also run claude plugin validate .claude/skills to check the frontmatter of every SKILL.md in the project.
  • If the slash command works but automatic triggering doesn’t: go back to ② and add the words people actually use.

⑦ Test triggering

Seeing it used once is not enough. Keep a small set of test prompts in the skill folder, reviewed along with the skill:

# shop-add-endpoint trigger tests

## Should trigger

- Add a partial-refund API to order: POST /orders/{id}/refunds
- inventory needs an endpoint to look up stock
- add a GET /payments/{id} endpoint
- make the cancel handler also return cancelled_at

## Should not trigger

- payment's webhook returns 500; look into it
- write the SQL for migration 0007
- add a forwarding rule to api-gateway

## Expected result (first should-trigger prompt)

- Writes TestHandler_refund first and pastes the failing output
- check-endpoint is all OK, with the output pasted
- No files changed outside internal/order and docs/api

Ask each one in a new session, two or three times each (the model doesn’t decide the same way every time), and record whether the skill loaded:

Illustration ⑦ Trigger tests Prompt Expect 3 runs Add a partial-refund API to order load 3/3 inventory needs a stock lookup endpoint load 3/3 add a GET /payments/{id} endpoint load 3/3 Return one more field from cancel load 2/3 payment’s webhook returns 500; debug it none wrong 1/3 Write the SQL for migration 0007 none 0/3 Add a forwarding rule to api-gateway none 0/3 A Wrong trigger: add “not for debugging” to the description, then rerun all B Missed 2/3: add phrasings like “change an existing endpoint’s response”

Figure: Illustration. Seven prompts, three runs each; “payment’s webhook returns 500” triggered wrongly once, and a request to change an existing endpoint was missed once; both send you back to ② to fix the description, then rerun everything.

The most useful half of the table is should not trigger. A wrong trigger costs more than a miss: when it misses, you can still type /shop-add-endpoint; when it triggers wrongly, a debugging conversation gets the whole “add an endpoint” procedure, and the agent may start creating files. Rerun the whole set every time you change the description.

To automate this, the skill-creator plugin mentioned in the official documentation can generate should-trigger and should-not-trigger prompts, measure the hit rate and suggest description edits; fuller measurement (with and without the skill, team-level indicators) is in “Getting More from AI Agent Skills: Choosing, Writing and Chaining Them into a Workflow”. At the beginner stage, a hand-written list rerun after every description change catches most problems.

Iterate from real failures. While trying it, note every time the agent gets something wrong: skipped the docs, invented an error code, wrote SQL in the handler. Each mistake has only three fixes: add a rule (to SKILL.md or a reference file), add a check (to check-endpoint), or fix the description. Prefer a check wherever one can catch it.

Step 9: ⑧ Commit to git so the team gets it on clone

Illustration ⑧ Commit to git, or package a plugin Terminal $ git switch -c skill/shop-add-endpoint $ git add .claude/skills/shop-add-endpoint $ git commit -m "skill: add shop-add-endpoint (conventions from internal/order)" A $ git push -u origin skill/shop-add-endpoint # Open a PR: .claude/ is reviewed by its CODEOWNERS B A The skill lives in the same repo and goes through the same review B Review whether the description widened, tools grew, or scripts appeared Only this repo .claude/skills/ Several repos plugin + marketplace Only you ~/.claude/skills/

Figure: Illustration. The skill lives in the same repo as the code and goes through the same branch, PR and review process; below are the three ways to share it, and this step takes the first.

A project skill is just ordinary files in the repo, and git is how it is shared:

git switch -c skill/shop-add-endpoint
git add .claude/skills/shop-add-endpoint
git commit -m "skill: add shop-add-endpoint (conventions from internal/order)"
git push -u origin skill/shop-add-endpoint

Once merged, anyone who clones or pulls the repo and opens Claude Code in it has the skill, with nothing to install. This is the great strength of a project skill: it is always at the same version as the code it describes. Check out a branch from three months ago and the skill is as it was three months ago, consistent with the code of that time.

What to look for when reviewing a skill PR. A skill changes how everyone’s agent works, so review it like code. “Bringing AI Workflows into the Team Process: PR Review, CI and Human Gates” already put .claude/ in CODEOWNERS. Look especially at three things: whether the description has widened (and will start taking other work), whether allowed-tools allows more, and whether new scripts that run have been added.

Keep the skill in sync with the code. The most common way a skill dies is going stale: the code changes a convention and the skill still teaches the old one. Hand the syncing to CI:

# The skill's checker must pass its own tests
go -C .claude/skills/shop-add-endpoint/scripts/check-endpoint test ./...

# Templates must match their sources exactly; change cancel.go without the template and this fails
diff -u internal/order/cancel.go      .claude/skills/shop-add-endpoint/templates/handler.go
diff -u internal/order/cancel_test.go .claude/skills/shop-add-endpoint/templates/handler_test.go

# An existing endpoint known to be correct must pass; if not, the checker and the conventions have drifted
go run ./.claude/skills/shop-add-endpoint/scripts/check-endpoint/main.go -service order -route "POST /orders/{id}/cancel"

The last line matters: it confirms the checker itself hasn’t gone stale. If someone moves the error format to a new helper without updating check-endpoint, this line breaks first, rather than some new endpoint inexplicably failing six months later.

Also record in the header of references/conventions.md which commit it was taken from (3f9c2e1). To check whether the reference file is out of date, git log 3f9c2e1..HEAD -- internal/order/ lists the changes since, and you can see whether any affects the conventions.

Step 10: Package a plugin and marketplace for other repos

A few months later, two other Go services in the company (each its own repo: warehouse and billing) need to add endpoints following the same platform conventions. Copying .claude/skills/shop-add-endpoint into each repo soon gives you three versions. Claude Code’s answer is the plugin: a packaged folder that can carry skills, subagents, hooks and MCP servers; and a marketplace that lists which plugins exist and where to fetch them. The marketplace itself is a git repo.

shop-ai-skills (git repo = marketplace) .claude-plugin/ marketplace.json plugins/shop-go/ .claude-plugin/plugin.json skills/add-endpoint/ SKILL.md references/ templates/ scripts/ PR review description, tools, scripts Merge + version 1.2.0 → 1.3.0 shop repo /shop-go:add-endpoint warehouse repo /shop-go:add-endpoint billing repo /shop-go:add-endpoint Setting up another repo /plugin marketplace add https://git.example.com/platform/shop-ai-skills.git /plugin install shop-go@shop-ai-skills Team: extraKnownMarketplaces + enabledPlugins in .claude/settings.json; each still installs

Figure: One git repo is the marketplace, holding marketplace.json and the shop-go plugin; changes go through PR review and a version bump before release; other repos add the marketplace, install the plugin and invoke /shop-go:add-endpoint.

Split first: what belongs in the plugin. Not all of the skill can move. cancel.go is a file in the shop’s repo that warehouse doesn’t have; what belongs in the plugin is the part every repo shares: the error format, how routes are registered, the test structure and the checker. Each repo’s own part (which endpoint is the template, which services exist) stays in that repo’s project skill or its CLAUDE.md.

The marketplace repo’s layout:

shop-ai-skills/
├── .claude-plugin/
│   └── marketplace.json
└── plugins/
    └── shop-go/
        ├── .claude-plugin/
        │   └── plugin.json
        └── skills/
            └── add-endpoint/
                ├── SKILL.md          # name: add-endpoint
                ├── references/
                ├── templates/
                └── scripts/check-endpoint/

Only plugin.json goes inside .claude-plugin/; skills/ must sit at the plugin root, and a skills/ inside .claude-plugin/ doesn’t load. The skill’s folder is renamed add-endpoint, and name with it — invocation adds the plugin name in front, giving /shop-go:add-endpoint, so no prefix of your own is needed.

The plugin manifest, plugins/shop-go/.claude-plugin/plugin.json (only name is required; it is also the skills’ prefix):

{
	"name": "shop-go",
	"description": "Add HTTP endpoints to Go services following the platform conventions",
	"version": "1.3.0",
	"author": {
		"name": "Shop Platform Team"
	}
}

The marketplace catalogue, .claude-plugin/marketplace.json (name, owner and plugins are required; each plugin needs a name and a source, and a relative path is counted from the marketplace root and may not use ..):

{
	"name": "shop-ai-skills",
	"description": "Skills shared by the shop's Go services",
	"owner": {
		"name": "Shop Platform Team"
	},
	"plugins": [
		{
			"name": "shop-go",
			"source": "./plugins/shop-go",
			"description": "Add HTTP endpoints to Go services following the platform conventions"
		}
	]
}

Keep the two names the same: when the entry name in the marketplace (what you type to install, shop-go@shop-ai-skills) differs from the name in plugin.json (the skills’ prefix), installation can’t find the plugin.

Try it locally before publishing. A plugin loads without any marketplace:

claude plugin validate ./plugins/shop-go   # checks plugin.json and every SKILL.md's frontmatter
claude plugin validate .                   # checks marketplace.json
claude --plugin-dir ./plugins/shop-go      # loads it for this session only; then type /shop-go:add-endpoint

After editing files, run /reload-plugins in the session to reload.

Installing it in another repo. Once the marketplace is pushed to the company’s git host, in a Claude Code session in warehouse:

/plugin marketplace add https://git.example.com/platform/shop-ai-skills.git
/plugin install shop-go@shop-ai-skills

/plugin marketplace add accepts GitHub owner/repo shorthand, a full git URL, a local path, or the URL of a marketplace.json; anything not on GitHub needs the full URL, because owner/repo always means github.com. Private repos use the git credentials already on each person’s machine (an SSH key or a credential helper); marketplace.json has no field for a token, and shouldn’t.

Getting everyone in a repo onto the same setup. Leaving each person to add the marketplace means someone will miss it. Run claude plugin marketplace add https://git.example.com/platform/shop-ai-skills.git --scope project once in the warehouse repo and it writes .claude/settings.json; or write it yourself and commit it:

{
	"extraKnownMarketplaces": {
		"shop-ai-skills": {
			"source": {
				"source": "git",
				"url": "https://git.example.com/platform/shop-ai-skills.git"
			}
		}
	},
	"enabledPlugins": {
		"shop-go@shop-ai-skills": true
	}
}

extraKnownMarketplaces registers the marketplace (keyed by the name in marketplace.json), and enabledPlugins enables the plugin (plugin@marketplace). The official documentation notes two details: the marketplace is registered only after a contributor accepts the workspace trust dialog for that folder; and enabledPlugins doesn’t install anything, so each person still runs claude plugin install shop-go@shop-ai-skills --scope project once.

Versions and updates. This is the biggest difference from a project skill: a project skill follows git pull, whereas an installed plugin keeps a cached copy that updates only when its version changes.

  • If plugin.json sets version, raise it on every release; forget, and users stay on the old cached copy. Leave version out and users track commits instead, with every push counting as a new version. Don’t set the version in both plugin.json and marketplace.json: if they differ, plugin.json wins, and claude plugin validate reports the mismatch.
  • Third-party marketplaces don’t auto-update in the background by default. Users turn on auto-update on the marketplace’s page in /plugin, or run /plugin marketplace update shop-ai-skills themselves. For a team this is a good thing: an upgrade is a visible decision.
  • To keep some repos on a stable release, append #<branch or tag> to the URL when adding the marketplace (for example …/shop-ai-skills.git#stable), or pin the marketplace entry with ref or sha.
  • Tag releases in git so you can look back. The official documentation resolves plugin dependency version ranges against tags of the form <plugin>--v<version>, so a tag such as shop-go--v1.3.0 works well.

Changes still go through PRs: edits to the description, allowed-tools and scripts are all reviewed, and the version is raised after merging. A plugin’s reach is wider than a project skill’s — one merge affects every repo that installs it — so review it more strictly.

Choosing between the three:

SituationChoiceReason
You’re trying out a new skillPersonal ~/.claude/skills/Changes take effect at once and affect nobody else; move it into the repo once stable
The conventions belong to this repo onlyProject .claude/skills/, committed to gitSame version and review as the code, there on clone, no install or versioning
Several repos share the same practicePlugin + marketplaceOne original, one version, pinnable and upgradable step by step
You just want one or two colleagues to try a pluginGive them the folder or a zip, loaded with --plugin-dirMentioned in the official documentation; no marketplace needed first

When not to make a plugin: only one repo uses it (an extra layer of versioning for no benefit); the content is tightly bound to one repo’s files (move it out and it loses its basis); it is still changing often (every change needs a release, and users need to update). Also note that an enabled plugin brings the descriptions of all its automatically invocable skills into every session, even ones where nothing from it is used; the more you install, the more context it takes.

After moving the skill into a plugin, delete the original .claude/skills/shop-add-endpoint. The official documentation warns that while the original remains, both load (/shop-add-endpoint and /shop-go:add-endpoint side by side), and the two descriptions compete for the same requests.

Common pitfalls

The description is just a noun. “Endpoint tool” — no trigger words and no boundary, so it either never triggers or triggers on everything. Say what it does, the words people will use, and what it doesn’t do.

Broken frontmatter goes unnoticed. When the YAML fails to parse, the skill still loads and the slash command still works, but the description is empty, so it never triggers automatically. If the description contains colons or quotes, parse it once with a YAML tool, or look at the error with claude --debug.

Conventions written from memory. What you get is how it ought to be, not how it is, contradicting the code in the repo. Every rule must point back to a file.

Hand-written templates. In a template nobody has compiled, the mistakes are copied into every new endpoint. Copy a real, reviewed file from the repo, and have CI check it still matches its source.

Asking the prompt to “remember to write a test”. The model may report “test added” when it wasn’t. Questions that code can answer go to the checker and its exit code.

Stuffing the whole handbook into SKILL.md. Every line stays in the conversation once loaded, and the longer it is, the more gets ignored. SKILL.md holds only the procedure and which file to read when; details go in reference files, which shouldn’t point onward to yet more files.

allowed-tools too broad. Bash(*) means nothing in that turn asks first. List only specific read-only or locally reversible commands.

Testing only with the slash command. The slash command skips description matching, so it can’t tell you whether automatic triggering works. Run several should-trigger and should-not-trigger prompts.

A personal skill overriding the project skill. Personal wins on a name clash. Give team skills a prefixed name, and when someone says “it behaves differently for me”, check ~/.claude/skills/ first.

Changing a plugin without raising its version. For a plugin that sets version, users get new content only when the version changes.

Keeping the original after moving to a plugin. The old project skill and the new plugin skill both load, and their descriptions compete for the same requests.

Key takeaways

  • A skill is a folder whose only required file is SKILL.md: name and description in the frontmatter, plus steps and done criteria; it can carry references/, templates/ and scripts/.
  • Layered loading: descriptions are always present, SKILL.md loads on a matching request or slash command and stays, and reference files and scripts are read or run only when a step needs them.
  • The description says what it does, when to use it (in the words people use) and what it doesn’t do, with the main use first; before loading, it is all Claude can see.
  • Location decides who gets it: personal ~/.claude/skills/, project .claude/skills/ (travels with git), or a plugin (across repos, namespaced). Polish it in one repo, then spread it.
  • Doing it right: one job per skill, a short SKILL.md, details in one-level-deep reference files with “when to read” spelled out, content from real code, deterministic checks in code, checkable done criteria, least permission, no secrets, should and should-not trigger tests, and iteration from real failures.
  • “Turning the project’s git into a skill”: use git log and grep to find a representative endpoint and the conventions, cite a source and commit for each rule, copy real files as templates, and turn the conventions with definite answers into a checker.
  • Keep it in sync with CI: the checker’s own tests, a diff between templates and sources, and an existing endpoint that must pass the checker.
  • Commit project skills to the repo: there on clone, same version and same review as the code.
  • Across repos, package a plugin: .claude-plugin/plugin.json + skills/, with a marketplace in .claude-plugin/marketplace.json; /plugin marketplace add, /plugin install plugin@marketplace; teams register and enable with extraKnownMarketplaces and enabledPlugins; raise version to release, and pin with #ref.
  • Claude Code skills follow the Agent Skills open standard; for use in other tools, keep the frontmatter to the standard’s fields.

References

  • Extend Claude with skills (official Claude Code documentation): skill locations, frontmatter fields, the 1,536-character description cap and disable-model-invocation, used in steps 1, 2 and 5.
  • Specification (Agent Skills): naming rules, the standard fields and the scripts/, references/, assets/ conventions in steps 1 and 5.
  • Skill authoring best practices (official Claude Platform documentation): writing descriptions, progressive disclosure and testing a skill with evaluations, used in steps 5 to 8.
  • Equipping agents with Agent Skills (Anthropic): why skills load their contents only when needed, the idea behind step 1.
  • Plugins overview (official Claude Code documentation): plugin structure and .claude-plugin/plugin.json, used in step 10.
  • Create a marketplace (official Claude Code documentation): the required marketplace.json fields and relative plugin sources in step 10.

Next

With a first skill in hand, the questions become: should you install the many ready-made skills out there; what belongs in CLAUDE.md, skills, hooks, subagents and MCP; how do you chain several skills into a flow from requirements to verification; and how do you know they actually help? The next article, “Getting More from AI Agent Skills: Choosing, Writing and Chaining Them into a Workflow”, takes on these advanced topics and writes a pre-release check skill for the shop.