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 theclaude mcpcommands 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: yourCLAUDE.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.
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.mdfor you in every project,./CLAUDE.mdor./.claude/CLAUDE.mdfor the project (commit it), and./CLAUDE.local.mdfor 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 aspermissions.alloware 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, runclaudeinsideclaude-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.mdis the one you write and commit. - Run
/statusinside Claude Code to see which settings files were loaded, and/hooksfor 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@importcheck treated@Autowiredinside 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.mdimported@README.mdand 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:
---
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 everymvn 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 ascatandsed. It does not stop a program that opens the file itself. A Maven build, a Spring Boot app or a Python script that readsapplication-prod.propertiesis outside what the rule can see, and so isgrep -rrun 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.allowrules apply only after each teammate trusts the folder;denyandaskrules 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.gitignoreif you create it by hand; the companion project’s.gitignorealready does. - Permission modes.
acceptEditsand auto mode approve edits inside the working directory without asking. The JetBrains documentation warns that inacceptEditsClaude 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
.envopen 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 fromCLAUDE.md.
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.
#!/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
- Claude Code docs: hooks reference
- Claude Code docs: hooks guide
- scripts/hook-tour.sh (how the transcripts were produced)
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 ownOne 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.Failures:block, falls back to any[ERROR]lines, and finally to the last 15 lines of output.
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
-pland-amto the Maven command, or point the hook at a faster runner. The hook has a 180 secondtimeoutinsettings.json; the documented default for command hooks is 600 seconds. - Name matching is a convention.
Foomaps toFooTest. If your project usesFooTestsorFooIT, change the two lines that buildTESTCLASS. 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 (
*.javaonly) is what the companion code does. The documentation also describes aniffield on a hook that takes permission-rule syntax such asEdit(*.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.#!/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 testin 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 --porcelainat the top of the script. - Exit 2 or JSON? The script uses the JSON form (
decision: blockwith areason), 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_activeguidance 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:
---
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: forkwithagent(run in a subagent so a long review does not fill your main context),paths(limit automatic activation to matching files),modelandeffortoverrides, andhooksscoped 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.mdand a skill at.claude/skills/deploy/SKILL.mdboth create/deploy; if both exist the skill wins. - Keep
SKILL.mdunder 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.
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 aurlis not loaded. In the run,claude mcp listprinted “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 theclaude 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
claudeit 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
/configswitches 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-99with 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
/ideinside 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 unencryptedws://, so leave it off unless WSL2 networking forces it. Second, inacceptEditsmode 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 towsl -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
claudefrom 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
- Copy
.claude/,CLAUDE.mdand.mcp.jsoninto your repository and editCLAUDE.mdto your real commands and rules. - Run the companion’s lint idea in CI so a broken hook path fails a pull request, not a teammate’s session.
- Start
claudein the repository root, run/statusto confirm which settings loaded and/hooksto see the registered hooks, then approve the project’s MCP servers when asked. - Watch the first sessions. If Claude ignores a
CLAUDE.mdrule, decide whether it belongs in a test or a hook.
Going deeper
- README.md
- scripts/run-all.sh (regenerates every transcript)
Should you do all of this?
Start with CLAUDE.md and one hook, not all of it. A shortCLAUDE.mdwith 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/hooksandclaude --debugopen, before you trust it on a team.
Further reading
- Companion repository: java-ai-agents, module claude-code-spring
- Spring Boot 4.2 GA: What’s New, What’s Deprecated and the 4.1 to 4.2 Upgrade Checklist
- Write an MCP Server with the Plain MCP Java SDK (No Spring)
- Spring AI MCP Client: Calling External MCP Servers from ChatClient
- Tool Calling in Spring AI 2.0
- Claude Code: hooks reference
- Claude Code: CLAUDE.md, rules and auto memory
- Claude Code: skills
- Claude Code: MCP
- Claude Code: permissions
- Claude Code: JetBrains IDEs
No Comments yet!