Skip to main content

Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ

Set up Claude Code on a Spring Boot 4.2 project: a short CLAUDE.md, permission rules, hooks that block dangerous commands and run the matching test after every edit, a Stop gate, skills, project-scoped MCP servers and the IntelliJ plugin. The hook scripts and the claude mcp CLI were actually run; what Claude Code does with them is marked as documentation.

Claude Code is an AI coding assistant that runs in your terminal or IDE, reads your project, edits files and runs commands such as mvn test. Out of the box it knows Java and Spring well, but it does not know your project: which Maven command you use, that your team banned field injection, that an applied Flyway migration must never be edited. Left alone, it can also fall back on Spring Boot 3 habits, such as old import packages, because Boot 4 is recent. This post sets Claude Code up on a small Spring Boot 4.2 orders service, one feature at a time: a CLAUDE.md file for instructions, permissions for what it may run, hooks (scripts Claude Code runs for you at fixed moments) that block dangerous commands and run the right test after every edit, skills for repeatable tasks, MCP servers for tools such as Gitea and a database, and the IntelliJ plugin. Everything is committed in one companion module you can open and run.
What was run, and what was not. The hook scripts were executed here with the exact JSON that Claude Code documents for each event, the test suite and the configuration lint ran on JDK 25, and the claude mcp commands were run with the real Claude Code 2.1.330 CLI in a throwaway directory. What was not run: a live Claude Code session (the sandbox had no signed-in account, so a headless run failed with an authentication error), the JetBrains plugin (no IDE), and the MCP servers themselves (one package was blocked from executing, the other needs a Gitea token). Anything below about what Claude Code does with a hook’s exit code, or how the IDE behaves, comes from the Claude Code documentation and is marked as documentation, not as an observation.

Versions. Spring Boot 4.2.0 (GA 19 November 2026, verified on Maven Central), Claude Code CLI 2.1.330, JDK 25 (Temurin 25.0.5.1), JUnit 6.1.3, jq 1.7. Companion code: asmhatre/java-ai-agents, module claude-code-spring.

Claude Code only knows what you put in front of it, and some of that is advice while some is enforced

Start with one distinction, because the rest of the post hangs on it. Some of Claude Code’s configuration is text the model reads: your CLAUDE.md, rules, skills. The model usually follows it, but it is context, not a lock. The documentation says so directly: CLAUDE.md is loaded as context, not enforced configuration, and for guaranteed behaviour it points you at a hook. Other configuration is code that Claude Code itself runs: permission rules and hooks. Those do not depend on the model remembering anything.
What Claude Code reads versus what Claude Code runs Context the model reads (advice) CLAUDE.mdevery session, in full .claude/rules/*.mdall, or only for matching paths SKILL.mdbody loads only when the skill is used MCP tool listtools the model may choose to call The model can read all of this and still get it wrong. Nothing checks. Code Claude Code executes (enforcement) permissions.denyrefuses a matching call PreToolUse hookcan deny before the tool runs PostToolUse hookruns after, feeds results back Stop hookcan refuse to let Claude finish A script decides, not the model. It behaves the same on every run. A rule you cannot afford to have ignored belongs on the right. A convention you want followed most of the time belongs on the left.
The picture is the whole strategy. Put conventions on the left, where a mistake costs you a review comment. Put anything that must never happen, such as a force-push or an edit to an applied database migration, on the right. Later sections show one of each side by side so you can see the difference in a real run.
Going deeper: what loads when, and where each file lives
  • CLAUDE.md locations, broadest to most specific: a managed policy file for organisations, ~/.claude/CLAUDE.md for you in every project, ./CLAUDE.md or ./.claude/CLAUDE.md for the project (commit it), and ./CLAUDE.local.md for personal notes (git-ignore it). Files are concatenated, not overridden, and Claude Code walks up from the directory you started in.
  • Settings files: ~/.claude/settings.json (you, every project), .claude/settings.json (the team, commit it), .claude/settings.local.json (you, this project). Managed settings override everything; the command line (--settings) comes next, then local, project and user. Lists such as permissions.allow are merged across files instead of replaced.
  • Start Claude Code in the folder that holds .claude/. It reads the shared settings file from the session’s working directory, so in a multi-module repository such as the companion one, run claude inside claude-code-spring/.
  • Auto memory is a separate feature: notes Claude writes for itself, stored under ~/.claude/projects/ on your machine. It is not shared with your team. CLAUDE.md is the one you write and commit.
  • Run /status inside Claude Code to see which settings files were loaded, and /hooks for a read-only list of configured hooks. (Documentation.)

Going deeper

A good CLAUDE.md lists the things the model gets wrong about your stack, not a tour of your code

CLAUDE.md is a Markdown file at the root of your project. Claude Code loads it at the start of every session, so it works like a briefing a new teammate reads on day one. The documentation recommends keeping each file under 200 lines because longer files reduce how well it is followed. The companion project’s file is 33 lines, and the part that earns its place is the Spring Boot 4 section, because Boot 4 renamed packages that older habits still point at.

The section below is from CLAUDE.md:

## Spring Boot 4 rules (older habits and examples still use the Boot 3 names, so these matter)
- Jackson 3: import `tools.jackson.databind.*`. Do not import `com.fasterxml.jackson.databind.*`.
- MockMvc tests: `@AutoConfigureMockMvc` lives in `org.springframework.boot.webmvc.test.autoconfigure`.
  The old `org.springframework.boot.test.autoconfigure.web.servlet` package does not exist in Boot 4.
- Web starter is `spring-boot-starter-webmvc`, test starter is `spring-boot-starter-webmvc-test`.
- Constructor injection only. No field `@Autowired` in `src/main`.
Notice what is not in the file: a description of the packages, or what a REST controller is. The model can read the code for that. The file holds commands, rules that contradict its habits, and a definition of done. Advice is not enforcement, so test it. The Jackson 3 and MockMvc rules are cheap to turn into a test. ConventionsTest scans every Java file for the Boot 3 imports and for field injection, and fails the build if it finds one, whether a person or a model wrote it. This is the left column of the diagram moving to the right column.

The test writes its result to output/02-conventions.txt:

java files scanned: 9
violations: 0
The same idea works for the configuration itself. A broken settings file or a hook path that points nowhere is normally discovered when a session starts. ClaudeConfigTest lints it in CI instead: line count of CLAUDE.md, that every @import exists, that every hook script exists and is executable, that every skill has a matching name, and that no literal secret sits in .mcp.json.

Its output is output/01-config-lint.txt:

CLAUDE.md lines: 33 (guidance: under 200)
CLAUDE.md import @README.md exists: true
settings.json hook events: [PreToolUse, PostToolUse, Stop]
  PreToolUse  matcher=Bash                   ./.claude/hooks/guard-bash.sh executable=true timeout=10
  PreToolUse  matcher=Edit|Write|MultiEdit   ./.claude/hooks/protect-files.sh executable=true timeout=10
  PostToolUse matcher=Edit|Write|MultiEdit   ./.claude/hooks/test-after-edit.sh executable=true timeout=180
  Stop        matcher=(none, matches everything) ./.claude/hooks/stop-gate.sh executable=true timeout=300
permissions.deny: [Read(./.env), Read(./.env.*), Read(./src/main/resources/application-prod.properties)]
skill new-endpoint: keys=[name, description, argument-hint, allowed-tools]
skill review-diff: keys=[name, description, disable-model-invocation, allowed-tools]
mcp server gitea: type=stdio command=gitea-mcp
mcp server db: type=stdio command=npx
secrets in .mcp.json: false
The lint caught its author twice. My first version of the @import check treated @Autowired inside backticks as an import, so I stripped code spans before matching. That is this lint’s own rule; I did not verify how Claude Code treats an @ inside a code span, so check the memory docs if you depend on it. The second failure was real: CLAUDE.md imported @README.md and I had not written the README yet. The test failed, which is exactly its job.
Going deeper: @imports, path-scoped rules, /init and AGENTS.md

Imports. Writing @README.md in CLAUDE.md pulls that file in at launch. Relative paths resolve from the importing file, imports can nest up to four levels, and imported files still cost context. The first external import in a project triggers an approval dialog. (Documentation.)

Rules. Every .md file under .claude/rules/ is discovered. A rule with no paths: frontmatter loads at launch like CLAUDE.md; a rule with paths: loads only when Claude reads a matching file. The companion project has one, for tests:

.claude/rules/testing.md
---
paths:
  - "src/test/**/*.java"
---

# Test rules
- JUnit 6 and AssertJ. Static-import `assertThat`.
- Name tests as sentences: `tenUnitsGetTenPercentOff`, not `testDiscount`.
- Unit-test services without Spring. Use `@SpringBootTest` only for controller wiring.
- One behaviour per test. No logic (loops, ifs) inside a test.

This keeps test conventions out of the context until Claude is actually working in src/test.

/init. The /init command analyses the codebase and drafts a starting CLAUDE.md; if one exists it suggests improvements instead of overwriting. Treat the draft as a first pass and cut it down.

AGENTS.md. Claude Code reads CLAUDE.md, not AGENTS.md. If your team already has an AGENTS.md, put @AGENTS.md at the top of CLAUDE.md.

Comments are free. Block-level HTML comments in CLAUDE.md are stripped before the file is injected, so you can leave maintainer notes without spending tokens. (All of this paragraph: documentation.)

Going deeper

Let it run your tests without asking, and keep secrets out of reach with deny rules

By default Claude Code asks before it runs a shell command or edits a file. That is safe and slow: a session that asks permission for every mvn test trains you to click Yes without reading. Permission rules let you say, once and for the whole team, which commands are fine and which files are off limits. They live in .claude/settings.json.

The permissions part of .claude/settings.json:

  "permissions": {
    "allow": [
      "Bash(mvn -B -q test *)",
      "Bash(mvn -B -q test)",
      "Bash(mvn -B verify)",
      "Bash(git status)",
      "Bash(git diff *)"
    ],
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./src/main/resources/application-prod.properties)"
    ]
  },
Three things to know before you rely on this. Order: rules are checked deny first, then ask, then allow, and the first match wins, so a deny in any settings file beats an allow in another. Wildcards: Bash(mvn -B -q test *) with a space before the * also matches the bare command; the space matters, because Bash(ls*) would match lsof too. Compound commands: Claude Code understands &&, ||, ; and pipes, so allowing mvn test does not allow mvn test && curl evil, because each part must match on its own. (All from the permissions documentation.)
A deny rule is not a sandbox. Read(./.env) stops Claude’s own file tools and the file commands Claude Code recognises, such as cat and sed. It does not stop a program that opens the file itself. A Maven build, a Spring Boot app or a Python script that reads application-prod.properties is outside what the rule can see, and so is grep -r run from inside the folder. If a file must be unreachable, the documentation’s answer is the OS-level sandbox, not a deny rule. And keep real production credentials out of the working tree regardless.
Going deeper: allow rules, workspace trust and the IDE
  • Allow rules wait for trust. In a committed .claude/settings.json, permissions.allow rules apply only after each teammate trusts the folder; deny and ask rules apply immediately. A teammate who has not trusted the folder still gets prompts.
  • Personal overrides go in .claude/settings.local.json. “Yes, and don’t ask again” on a prompt writes an allow rule there. Add it to .gitignore if you create it by hand; the companion project’s .gitignore already does.
  • Permission modes. acceptEdits and auto mode approve edits inside the working directory without asking. The JetBrains documentation warns that in acceptEdits Claude may be able to modify IDE configuration files that the IDE can run automatically, so prefer manual edit approval inside an IDE.
  • Read deny rules also stop the IDE from sharing a selected file with Claude, which matters when you have a .env open in a tab.
  • All of the above are from the Claude Code documentation; none was exercised in a live session.

Going deeper

A hook is a script Claude Code runs for you, so it can say no even when the model would not

A hook is a command you register for a moment in Claude Code’s life: before a tool runs, after it runs, when Claude wants to stop. Claude Code starts your script, writes a JSON description of what is happening to its standard input, and reads the result from the exit code and what the script prints. Your script is ordinary code, so its decision is the same on every run. That is the difference from CLAUDE.md.
One tool call, and where each hook can step in Claude asksedit, run, read PreToolUse hookcan say no Permission rulesdeny, ask, allow Tool runsfile changes PostToolUsereports back exit 2 or a deny decision:the call never happens by now the file is already changed:exit 2 only sends stderr to Claude Stop hook, when Claude thinks it is finishedexit 2 or decision block: Claude must keep working Only the first hook prevents anything. The last one is how you keep Claude from declaring victory early.
Read the diagram left to right. The first hook, PreToolUse, runs before anything has happened, so it is the only one that can prevent something. PostToolUse runs after the tool, when the file has already changed, so all it can do is tell Claude what it found. Stop runs when Claude believes it is done and is how you keep it from finishing early. The next three sections build one hook for each. The exit code is the contract. Exit 0 means success and any JSON on stdout is read. Exit 2 is a blocking error: on events that can block, the action stops and your stderr is handed to Claude as the reason. Any other exit code, including 1, is a non-blocking error: the action goes ahead. A script that fails with exit 1 therefore guards nothing, which is the most common hook mistake. (Documentation.)

The first hook watches shell commands. .claude/hooks/guard-bash.sh denies a few commands by printing a decision as JSON:

#!/bin/bash
# PreToolUse hook for the Bash tool. Reads the hook JSON on stdin (needs jq).
# Denies a few commands by returning a permissionDecision, which Claude sees as the reason.
COMMAND=$(jq -r '.tool_input.command // empty')

deny() {
  jq -n --arg reason "$1" '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: $reason
    }
  }'
  exit 0
}

case "$COMMAND" in
  *"mvn deploy"*|*"mvn release:"*)   deny "Publishing artifacts is a human decision. Run mvn verify instead." ;;
  *"git push --force"*|*"git push -f"*) deny "Force-pushing is blocked in this project." ;;
  *"rm -rf"*)                         deny "rm -rf is blocked. Delete specific files instead." ;;
  *"| sh"*|*"| bash"*)                deny "Piping downloaded text into a shell is blocked." ;;
esac
exit 0

It is registered for the Bash tool in settings.json. Fed a real PreToolUse payload for mvn deploy, it answers as below (from output/03-guard-bash.txt). An ordinary mvn -B -q test in the same file produces empty output and exit 0, meaning no objection.

## mvn deploy -DskipTests
input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"mvn deploy -DskipTests"}}
stdout: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Publishing artifacts is a human decision. Run mvn verify instead."}}
stderr: (empty)
exit  : 0
Claude receives the reason text, so a good reason doubles as an instruction: “Run mvn verify instead” tells it what to do next.
A hook cannot loosen a deny rule. The documentation is explicit that a PreToolUse hook’s decision does not bypass permission rules: a matching deny rule still blocks the call even if the hook says allow. In the other direction, a hook that blocks with exit 2 stops the call before allow rules are even considered. So the two layers add up: static patterns go in permissions.deny, and anything that needs logic goes in a hook.
Going deeper: protecting files, and the exact JSON each side sends

A second PreToolUse hook, registered for Edit|Write|MultiEdit, protects files instead of commands. It uses the other way to block, exit code 2 with the reason on stderr, and it encodes a Flyway rule that is easy to state and easy for a model to break: an applied migration is immutable. The hook allows creating a new V2__*.sql but refuses to change one that exists.

.claude/hooks/protect-files.sh
#!/bin/bash
# PreToolUse hook for Edit|Write|MultiEdit. Exit code 2 blocks the call and sends stderr to Claude.
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name // empty')
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Production config is never edited by the agent.
case "$FILE" in
  *application-prod.*|*/.env|*/.env.*)
    echo "Blocked: $FILE is production configuration. Ask the user to change it." >&2
    exit 2 ;;
esac

# An applied Flyway migration is immutable. Creating a new V<n> file is fine, changing an existing one is not.
case "$FILE" in
  */db/migration/V*.sql)
    if [ "$TOOL" != "Write" ] || [ -e "$FILE" ]; then
      echo "Blocked: $FILE is an existing Flyway migration. Add a new V<next>__*.sql file instead." >&2
      exit 2
    fi ;;
esac
exit 0

Real output for an edit to the existing migration, from output/04-protect-files.txt:

## Edit an existing migration
input : {"hook_event_name":"PreToolUse","tool_name":"Edit","tool_input":{"file_path":"<project>/src/main/resources/db/migration/V1__create_orders.sql"}}
stdout: (empty)
stderr: Blocked: <project>/src/main/resources/db/migration/V1__create_orders.sql is an existing Flyway migration. Add a new V<next>__*.sql file instead.
exit  : 2

Matchers. The matcher field filters by tool name. Letters, digits, _, -, spaces, commas and | form an exact list (so Edit|Write|MultiEdit is three tools); anything else is treated as a regular expression. MCP tools are named mcp__<server>__<tool>. (Documentation.)

Paths. ${CLAUDE_PROJECT_DIR} expands to the project root where the session started, which is why every command in the companion settings.json starts with it: the hook works no matter what directory Claude has cd-ed into.

Valid JSON only. If a hook prints JSON, nothing else may precede it on stdout. A shell profile that echoes a banner, for instance through BASH_ENV, makes the output stop starting with { and Claude Code then reads it as plain text, with no error. claude --debug logs “Hook output does not start with {” when this happens. (Documentation.)

Needs jq. Both scripts parse the input with jq. If your CI image or a teammate’s machine lacks it, the hooks fail with a non-blocking error and guard nothing.

Going deeper

The most useful hook for a Java project runs the matching test after every edit

Java has a long feedback loop compared with scripting languages, and a model that edits five files before running anything can bury the one that broke. A PostToolUse hook fixes that: after every edit to a Java file, find the test class with the matching name, run just that class, and if it fails, hand the failure text back to Claude immediately.

.claude/hooks/test-after-edit.sh:

#!/bin/bash
# PostToolUse hook for Edit|Write|MultiEdit. Runs the test class that matches the edited Java file.
# Green: silent, exit 0. Red: failure lines on stderr and exit 2, which Claude Code shows to Claude.
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
case "$FILE" in *.java) ;; *) exit 0 ;; esac

BASE=$(basename "$FILE" .java)
case "$BASE" in
  *Test) TESTCLASS="$BASE" ;;
  *)     TESTCLASS="${BASE}Test" ;;
esac

ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}"
cd "$ROOT" || exit 0
if ! find src/test -name "${TESTCLASS}.java" | grep -q .; then
  exit 0   # no matching test class: nothing to run
fi

OUT=$(mvn -B -q test -Dtest="$TESTCLASS" -Dsurefire.failIfNoSpecifiedTests=false 2>&1)
STATUS=$?
if [ $STATUS -ne 0 ]; then
  echo "Tests failed after editing $(basename "$FILE") ($TESTCLASS):" >&2
  # Surefire's "Failures:" block carries the assertion messages (expected/actual); prefer it.
  FOUND=$(echo "$OUT" | awk '/^\[ERROR\] (Failures|Errors):/{p=1} p{print} p&&/^\[ERROR\] Tests run:/{exit}' | head -20)
  [ -z "$FOUND" ] && FOUND=$(echo "$OUT" | grep -E '^\[ERROR\]' | grep -v -E 'Help 1|re-run Maven|For more information|full stack trace|See .*surefire|MojoFailure|^\[ERROR\] *$' | head -15)
  if [ -n "$FOUND" ]; then echo "$FOUND" >&2; else echo "$OUT" | tail -15 >&2; fi
  exit 2
fi
exit 0
The script maps OrderService.java to OrderServiceTest, skips quietly if no such class exists, and runs only that class so the hook costs seconds, not a full build. Here it is against a throwaway copy of the project where I changed >= to > in the discount rule. The transcript is output/05-test-after-edit.txt:
changed: 40:        if (order.quantity() > BULK_THRESHOLD) {
input : {"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"<project>/src/main/java/com/ankurm/claudecode/orders/OrderService.java"},"tool_response":{"success":true}}
stdout: (empty)
stderr: Tests failed after editing OrderService.java (OrderServiceTest):
stderr: [ERROR] Failures: 
stderr: [ERROR]   OrderServiceTest.tenUnitsGetTenPercentOff:23 
stderr: expected: 90.00
stderr:  but was: 100.00
stderr: [ERROR] Tests run: 4, Failures: 1, Errors: 0, Skipped: 0
exit  : 2
Claude would see the failing test name, the expected value and the actual value, which is enough to fix the bug without being asked. A compile error takes the same path and gets the compiler’s own message back.
My first version printed the headline and nothing else. The first run of the tour reported “Tests failed after editing OrderService.java” with no detail, even for correct code. The cause was in my harness, not the hook: the throwaway copy of the module had no parent POM beside it, so Maven could not build at all. But it showed that a hook which cannot find its failure lines is worse than useless, because Claude gets a red flag and nothing to act on. The script now prefers Surefire’s own Failures: block, falls back to any [ERROR] lines, and finally to the last 15 lines of output.
One behaviour to keep in mind: because the tool has already run by the time a PostToolUse hook fires, exit 2 here does not undo the edit. According to the documentation, Claude sees the stderr, but nothing is blocked. That is the right design for this hook, since you want the edit kept and fixed, not rolled back.
Going deeper: speed, scope and the if filter
  • Cost. The tour ran five Maven builds (three of this hook, two of the Stop gate below) in about 26 seconds on a two-vCPU sandbox, so roughly five seconds each on a tiny project. In a large multi-module build, add -pl and -am to the Maven command, or point the hook at a faster runner. The hook has a 180 second timeout in settings.json; the documented default for command hooks is 600 seconds.
  • Name matching is a convention. Foo maps to FooTest. If your project uses FooTests or FooIT, change the two lines that build TESTCLASS. A file with no matching test runs nothing and passes silently, which can look like safety. Pair this hook with the Stop hook below.
  • Filtering inside the script (*.java only) is what the companion code does. The documentation also describes an if field on a hook that takes permission-rule syntax such as Edit(*.java); I did not test it, so I kept the filter in the script where it is visible and runnable.
  • Formatters. The same event is where teams run a formatter such as Spotless after each edit. Keep that hook non-blocking, since a formatting failure should not stop work.

Going deeper

A Stop hook stops Claude from saying “done” while the build is red

Models sometimes finish a turn with a confident summary and a failing test. A Stop hook runs at that moment. If it blocks, Claude does not finish; it receives your message and keeps working. The companion hook runs the full suite and blocks only if it is red.

.claude/hooks/stop-gate.sh:

#!/bin/bash
# Stop hook. Refuses to let Claude finish while the full suite is red.
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
  exit 0   # we already pushed Claude back once this turn; let it stop and report
fi

ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}"
cd "$ROOT" || exit 0
OUT=$(mvn -B -q test 2>&1)
if [ $? -ne 0 ]; then
  SUMMARY=$(echo "$OUT" | awk '/^\[ERROR\] (Failures|Errors):/{p=1} p{print} p&&/^\[ERROR\] Tests run:/{exit}' | head -20)
  [ -z "$SUMMARY" ] && SUMMARY=$(echo "$OUT" | grep -E '^\[ERROR\]' | grep -v -E 'Help 1|re-run Maven|For more information|full stack trace|See .*surefire|MojoFailure|^\[ERROR\] *$' | head -8)
  [ -z "$SUMMARY" ] && SUMMARY=$(echo "$OUT" | tail -8)
  jq -n --arg r "The test suite is red. Fix it before finishing:
$SUMMARY" '{decision: "block", reason: $r}'
fi
exit 0

The first lines matter most. A Stop hook that blocks makes Claude work again, which ends in another Stop event, which runs the hook again. stop_hook_active is true when Claude is already continuing because of a Stop hook, so the script lets it stop. Claude Code also overrides a Stop hook that has blocked eight times in a row with no tool call between them; the documentation names CLAUDE_CODE_STOP_HOOK_BLOCK_CAP for raising that limit. From output/06-stop-gate.txt, with the discount bug reintroduced:

## Suite red (>= changed to >), stop_hook_active=false
input : {"hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"Done."}
stdout: {"decision":"block","reason":"The test suite is red. Fix it before finishing:\n[ERROR] Failures: \n[ERROR]   OrderControllerTest.createThenFetch:27 JSON path \"$.total\" expected:<90.0> but was:<100.0>\n[ERROR]   OrderServiceTest.tenUnitsGetTenPercentOff:23 \nexpected: 90.00\n but was: 100.00\n[ERROR] Tests run: 9, Failures: 2, Errors: 0, Skipped: 0"}
stderr: (empty)
exit  : 0
The same hook with stop_hook_active set to true exits 0 with no output in the next block of that file, so the loop cannot run forever even if Claude cannot fix the failure.
Going deeper: Stop versus a CI gate, and what I could not confirm
  • A Stop hook is not CI. It runs only inside a session on one machine. It stops a model finishing early; it does not stop a person pushing red code. Keep the same mvn test in your pipeline.
  • Cost. The full suite runs at the end of every turn, including turns that only answered a question. If that hurts, run the gate only when files changed, for example by checking git status --porcelain at the top of the script.
  • Exit 2 or JSON? The script uses the JSON form (decision: block with a reason), which the documentation lists for Stop. Exit code 2 with the reason on stderr is the other documented way and also keeps Claude working.
  • Not confirmed here: I found the stop_hook_active guidance and the eight-block cap in the hooks guide, but could not retrieve the reference page’s own Stop section in full, so the field list for Stop input comes from the guide and from the sibling SubagentStop section.

Going deeper

Pick bash and jq for hooks that run on every command, and keep JVM hooks for rare ones

Java developers will reach for Java, and JDK 25 makes it pleasant: a single .java file runs directly with java GuardBash.java, with an unnamed class and an instance main. The companion repository has GuardBash.java, the same deny rules as the shell version. The catch is start-up cost, and a PreToolUse hook runs before every matching command. Measured by scripts/hook-latency.sh:
java: openjdk version "25.0.5.1" 2026-11-17 LTS
jq  : jq-1.7
guard-bash.sh (bash + jq)               7 ms per call (average of 20)
java GuardBash.java (source launcher)    608 ms per call (average of 20)

both produce the same decision:
deny
deny
Both give the same decision. On this sandbox the shell hook takes about 7 ms and the source launcher about 600 ms, because each call compiles the file and starts a JVM. These figures change with every machine; treat them as the order of magnitude, roughly a hundred times. For a hook on every Bash call that adds up. A Java hook is a fine choice for a rare event, or when you need a real JSON parser and a compiled jar; note that the companion GuardBash.java extracts the command with a regular expression and is only good enough to measure.

Going deeper

Skills are checklists Claude loads only when the task calls for them

CLAUDE.md is always in context, so every line costs attention on every task. A skill is the opposite: a folder with a SKILL.md file whose body is loaded only when it is used, either because you type its name as a slash command or because Claude decides the request matches the skill’s description. Multi-step procedures belong here, not in CLAUDE.md. Project skills live in .claude/skills/<name>/SKILL.md; commit them and the team shares them.

The companion project has two. .claude/skills/review-diff/SKILL.md is a review you run before committing:

---
name: review-diff
description: Reviews the uncommitted changes for bugs, missing tests and Spring Boot 4 import mistakes. Use before committing.
disable-model-invocation: true
allowed-tools: Bash(git diff *) Bash(git status *)
---

## Changes under review

!`git diff HEAD`

## What to check
1. Behaviour changes without a matching test.
2. Boot 3 imports that no longer exist in Boot 4 (see CLAUDE.md).
3. `double` used for money, field injection, entities returned from controllers.
4. Edits to files under `db/migration` that already exist.

Report findings as a list: file, line, problem, suggested fix. If there are none, say so in one line.
Two frontmatter fields do the work. disable-model-invocation: true means only you can start it, by typing /review-diff; Claude will not decide to run it by itself, which suits anything with side effects or cost. And the line starting with an exclamation mark and backticks runs git diff HEAD before the skill reaches Claude and puts the output in its place, so the review sees the real diff without Claude spending a turn fetching it. allowed-tools pre-approves those git commands for the turn.
These two skills were validated for structure, not run. The lint test checks that the frontmatter parses and that each name matches its folder. Whether Claude follows the steps, or reviews well, needs a live session, and I had none. Treat the skill text as a starting point and watch the first few runs.
Going deeper: the other skill, frontmatter fields and where skills live

The second skill is user-invocable and model-invocable. /new-endpoint add a cancel route substitutes everything after the name into $ARGUMENTS:

.claude/skills/new-endpoint/SKILL.md
---
name: new-endpoint
description: Adds a REST endpoint to the orders service the way this project does it (controller, service, tests). Use when asked to add or extend an endpoint.
argument-hint: "[what the endpoint should do]"
allowed-tools: Bash(mvn *)
---

Add an endpoint for: $ARGUMENTS

Follow these steps in order.

1. Read `OrderController` and `OrderService` first and copy their style.
2. Put business logic in `OrderService`, a unit test in `OrderServiceTest` first (red), then the code (green).
3. Add the controller method and a MockMvc case in `OrderControllerTest`.
4. Run `mvn -B -q test`. Do not report done until it is green.
5. Reply with the new route, the status codes it returns, and the test names you added.
  • Fields I did not use but you may want: user-invocable: false (hide it from the menu, Claude only), context: fork with agent (run in a subagent so a long review does not fill your main context), paths (limit automatic activation to matching files), model and effort overrides, and hooks scoped to the skill’s lifetime.
  • Scopes. Personal skills in ~/.claude/skills/ apply to every project, and when names collide enterprise beats personal beats project.
  • Old custom commands. A file at .claude/commands/deploy.md and a skill at .claude/skills/deploy/SKILL.md both create /deploy; if both exist the skill wins.
  • Keep SKILL.md under 500 lines and move long reference material into files it links to. (All of this: documentation.)

Going deeper

MCP servers give Claude your other tools, and a committed .mcp.json does not start until you approve it

MCP, the Model Context Protocol, is a standard way to plug tools into an AI assistant. An MCP server might expose your Gitea repositories or let Claude run read-only SQL; Claude Code connects to it and the model can then call those tools. For a team, the useful part is that servers can be defined in a file you commit, .mcp.json, so everyone gets the same set.
A committed server does not start until you approve it .mcp.jsonin git Pending approvalnothing is spawned You approvein claude Serverstarts Same server name in two scopes: the closer scope wins local (private to you) project (.mcp.json) user (all your projects) >> A pull request that adds a server to .mcp.json cannot start it on a teammate’s machine by itself.
The top row is the safety property worth knowing. A server defined in a committed file is pending until the person at the keyboard approves it, so a pull request that adds a server cannot silently start a process on your laptop. The bottom row is precedence: if the same name is defined in more than one scope, the closest one wins. You do not have to write the JSON by hand, and you should not guess its shape. claude mcp add --scope project writes it. The companion .mcp.json was generated this way, and the tour script checks that the committed file is byte-for-byte what the CLI produces. Real output from Claude Code 2.1.330, from output/08-mcp-cli.txt:
$ claude mcp add --scope project --transport stdio gitea --env GITEA_HOST=https://ankurm.com/git.app --env GITEA_ACCESS_TOKEN=${GITEA_TOKEN} -- gitea-mcp -t stdio
Added stdio MCP server gitea with command: gitea-mcp -t stdio to project config
File modified: <tmp>/project/.mcp.json
Notice ${GITEA_TOKEN} in the stored file. The token is an environment variable that Claude Code expands when it starts the server, so the secret stays out of git. If the variable is unset the CLI warns you instead of failing, and the lint test asserts the file contains no literal secret. Here is the listing before approval:
$ claude mcp list     (GITEA_TOKEN and DB_URL unset)
Checking MCP server health…
gitea: gitea-mcp -t stdio - ⏸ Pending approval (run `claude` to approve)
db: npx -y @bytebase/[email protected] --transport stdio --dsn ${DB_URL} - ⏸ Pending approval (run `claude` to approve)
MCP config diagnostics ‼
For help configuring MCP servers, see: https://code.claude.com/docs/en/mcp
[Has warnings] Project config (shared via .mcp.json)
Location: <tmp>/project/.mcp.json
 ├ [Warning] [gitea] mcpServers.gitea: Missing environment variables: GITEA_TOKEN
 └ [Warning] [db] mcpServers.db: Missing environment variables: DB_URL
A “url” without a “type” is skipped, with a warning you can miss. A hand-written remote entry that has only a url is not loaded. In the run, claude mcp list printed “No MCP servers configured” and, underneath, a warning that the entry was skipped and needs "type": "http". If a server you committed never shows up, read the warnings under the list, not just the list.
Going deeper: the two servers, scopes, and what I did not run

Gitea. The gitea-mcp server is run as gitea-mcp -t stdio with GITEA_HOST and GITEA_ACCESS_TOKEN in its environment, according to its README. It also has a read-only mode (GITEA_READONLY or the -r flag) that hides write tools. I did not start it: it needs a token and the binary on PATH. Use a token with the fewest scopes that work.

Database. The db entry uses @bytebase/[email protected], which exists on npm. My attempt to execute it to read its --help was blocked by the sandbox’s safety classifier, so the flags in the file come from its README (--transport stdio and --dsn), not from a run. The README did not name a read-only flag. Whatever the server offers, give it a database role that can only SELECT; that is the control that holds. Also note that the older @modelcontextprotocol/server-postgres package is marked deprecated on npm as archived and unmaintained, so avoid it.

Scopes. --scope local (the default) is private to you in this project and lives in ~/.claude.json; --scope project writes .mcp.json; --scope user applies to all your projects. The tour defined the same name in user and local scope and claude mcp get reported the local one, matching the documented order of local, then project, then user.

Variable expansion. ${VAR} and ${VAR:-default} work in command, args, env, url and headers. In a remote server’s url and headers, a few well-known credential variables such as ANTHROPIC_API_KEY and NPM_TOKEN expand to empty on purpose, so a project file cannot leak them. (Documentation.)

Headless runs. In claude -p and Agent SDK sessions there is nobody to approve, so project servers load without asking. Block them with disabledMcpjsonServers if you run Claude Code in CI. (Documentation.)

Your own server. Writing an MCP server in plain Java is covered in Write an MCP Server with the Plain MCP Java SDK, and the client side in Spring AI MCP Client.

Going deeper

In IntelliJ, Claude Code is the same CLI with the editor wired to it

The JetBrains plugin does not contain a separate assistant. It runs the claude command in the IDE’s terminal and connects to it, so everything above, including CLAUDE.md, hooks and MCP servers, behaves exactly as in a plain terminal. What the plugin adds is editor integration. This whole section is from the JetBrains documentation. I had no IDE in the sandbox, so none of it was run.
  • Install both pieces. Install the Claude Code CLI first, then the plugin from the JetBrains Marketplace and restart the IDE. If the plugin cannot find claude it shows a “Cannot launch Claude Code” notification; set the full path under Settings, Tools, Claude Code.
  • Quick launch with Ctrl+Esc (Cmd+Esc on Mac).
  • Diffs open in the IDE’s own diff viewer instead of the terminal; the Diff tool setting in /config switches between that and the terminal.
  • Selection context. The current selection and active file are shared with Claude automatically, and you can insert references like @src/auth.ts#L1-99 with Alt+Ctrl+K (Cmd+Option+K on Mac).
  • Diagnostics. Claude can read the IDE’s inspection errors through a single tool, getDiagnostics. Claude Code does not request diagnostics from the plugin on its own after edits.
  • From a separate terminal, run /ide inside Claude Code to connect to a running JetBrains IDE; start it from the project root so both see the same files.
Two cautions the docs raise. First, the plugin runs a small local server so the CLI can talk to the IDE, on an ephemeral port with a token in a lock file under ~/.claude/ide/. By default it listens only on 127.0.0.1; the setting that opens it to your network sends the token over unencrypted ws://, so leave it off unless WSL2 networking forces it. Second, in acceptEdits mode Claude may be able to change IDE configuration files that the IDE executes, which can sidestep Bash permission prompts. Use manual edit approval in an IDE.
Going deeper: Remote Development, WSL and troubleshooting
  • Remote Development. Install the plugin on the remote host, not on your local client.
  • WSL2. “No available IDEs detected” is usually NAT networking or the Windows firewall. The documented fixes are a firewall rule for the WSL2 subnet or mirrored networking in .wslconfig (Windows 11 22H2 or later). Set the plugin’s Claude command to wsl -d <distro> -- bash -lic "claude".
  • Esc does not interrupt Claude. In Settings, Tools, Terminal, turn off “Move focus to the editor with Escape”.
  • Plugin not connecting. Start claude from the project root, make sure the plugin is enabled, restart the IDE fully (the docs say you may need to do it more than once).

Going deeper

A review workflow that fits a Java team: small prompts, hooks as guardrails, one human read

Put the pieces together as a loop you can describe in a sentence. Ask for one small change. Let the hooks run: the guard blocks dangerous commands, the matching test goes red or green after each edit, and the Stop gate refuses a red finish. Then run /review-diff for a second look at the diff, read the diff yourself, and let CI run the full pipeline. The hooks are the cheap, deterministic layer; your own read of the diff is the expensive one that cannot be delegated.
Going deeper: starting a new project with this setup
  1. Copy .claude/, CLAUDE.md and .mcp.json into your repository and edit CLAUDE.md to your real commands and rules.
  2. Run the companion’s lint idea in CI so a broken hook path fails a pull request, not a teammate’s session.
  3. Start claude in the repository root, run /status to confirm which settings loaded and /hooks to see the registered hooks, then approve the project’s MCP servers when asked.
  4. Watch the first sessions. If Claude ignores a CLAUDE.md rule, decide whether it belongs in a test or a hook.

Going deeper

Should you do all of this?

Start with CLAUDE.md and one hook, not all of it. A short CLAUDE.md with your build commands and your two or three “the model always gets this wrong” rules gives most of the benefit for ten minutes of work. Add the test-after-edit hook if your suite is fast enough that running one class does not slow every edit; if it takes a minute, it will make sessions miserable and people will switch it off. Add the Stop gate only if you trust your tests. A green gate on a weak suite is false comfort. Skills and MCP servers are worth it when you notice yourself pasting the same instructions or the same data repeatedly, not before.

And remember what this post could not show: the hook scripts were exercised, but Claude Code’s behaviour with them, the skills’ quality and the IDE plugin were not. Run the setup in a real session on a branch, with /hooks and claude --debug open, before you trust it on a team.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.