What was run, and what was not. Every test drives the real Spring AI pause and resume code with a hand-writtenScriptedChatModelthat returns the tool calls I queue, so no language model is involved: this shows what Spring AI does when a model asks for a gated tool, not how often a real model does. The approver page was tested on its server side only (events, HTML fragments, escaping); I did not open it in a browser. Streaming, session memory and the abandoned-pause cases are described from the reference documentation and marked as such.
Versions. Spring AI 2.1.0 (Maven Central lists the GA under 19 November 2026; the RC1 that introduced this feature is listed under 22 October), Spring Boot 4.1.3 (4.2.0 is out and was not tried), JDK 25 (Temurin 25.0.5.1), htmx 2.0.11. Companion code: asmhatre/spring-ai, module tool-confirmation. Every code block below names the file it came from, and every console block is copied from a file underoutput/.
The model asks, your code decides: a tool call is a request, not yet an action
When you give a model a tool, the model never runs it. It replies with a request — “callbookFlight with VX205” — and Spring AI’s tool-calling loop runs the matching Java method, sends the result back to the model, and repeats until the model answers in plain text. The loop is where a person can step in, because there is a moment between “the model asked” and “the method ran”.
Going deeper: how this fits the rest of the tool-calling stack
- The check lives in
ToolCallingManager, not in the advisor, so it applies to theToolCallingAdvisorloop and to loops you write yourself (docs-sourced). The advisor catches aToolCallConfirmationRequiredExceptionand returns the reply; you can see that exception’s shape in output/15-api-surface.txt. - For how the loop,
@ToolandToolContextwork before confirmation enters the picture, read Tool Calling in Spring AI 2.0. - For the opposite concern — a tool call you did not want, caused by hostile text — see Prompt Injection Defense in Spring AI. Confirmation is a human check on one call; an allow-list stops calls from being possible at all. They are complements.
Mark the tool, and the loop stops before anything runs
Start with one harmless tool and two that change the world. The opt-in is one attribute on the annotation you already use.searchFlights is left alone; bookFlight and cancelBooking say requiresConfirmation = true. The tools are in FlightTools.java, and each writes a line to a small BookingLedger when it really runs, so tests can tell “paused” from “ran”:
@Tool(description = "Search flights between two cities. Read-only.")
public String searchFlights(String from, String to) {
this.ledger.record("searchFlights " + from + "->" + to);
return "VX205 07:10 USD 240; VX311 18:40 USD 198";
}
@Tool(description = "Book a flight by flight number. Charges the customer.", requiresConfirmation = true)
public String bookFlight(String flightNumber) {
this.ledger.record("bookFlight " + flightNumber);
return "Booked " + flightNumber + ", reference BK-" + Math.abs(flightNumber.hashCode() % 1000);
}
The flag does not live on the method. Spring AI reads the annotation into a ToolMetadata object, and that is what the confirmation policy looks at. That matters for tools that are not annotated methods. DeleteFileTool.java builds one as a FunctionToolCallback and sets the same flag through the metadata builder:
public static ToolCallback create(BookingLedger ledger) {
return FunctionToolCallback.builder("deleteFile", (DeleteRequest request) -> {
ledger.record("deleteFile " + request.path());
return "Deleted " + request.path();
})
.description("Delete a file by path. Irreversible.")
.inputType(DeleteRequest.class)
.toolMetadata(ToolMetadata.builder().requiresConfirmation(true).build())
.build();
}
Going deeper: the exact API surface in the 2.1.0 jars
Before writing any of this I disassembled the 2.1.0 jars rather than trust the docs’ prose, and the result is committed as output/15-api-surface.txt (regenerated by scripts/api-surface.sh). The parts that matter:
public interface org.springframework.ai.tool.metadata.ToolMetadata {
public default boolean returnDirect();
public default boolean requiresConfirmation();
public static org.springframework.ai.tool.metadata.DefaultToolMetadata$Builder builder();
public static org.springframework.ai.tool.metadata.ToolMetadata from(java.lang.reflect.Method);The two configuration properties and their defaults, from the same file:
# Configuration properties, from spring-ai-autoconfigure-model-tool-2.1.0.jar
spring.ai.tools.confirmation.enabled | default: True
spring.ai.tools.confirmation.tools | default: NonerequiresConfirmation() is a default method on the interface, so any ToolMetadata you wrote before 2.1 compiles unchanged and answers “no”.
A paused reply looks like an empty answer, so check for the pause explicitly
Here is the trap that makes the next code necessary. When the loop pauses, the call to the model has succeeded: you get a normalChatResponse whose text is empty and which has a tool call in it. If your code only reads .content(), the user sees a blank answer and nothing in the logs. You have to ask the response whether it is a pause, with ToolCallDecisions.awaitingDecision(reply) (the list of call keys waiting) or isAwaitingDecision(reply).
The first half of PauseAndResumeTest.java does this with the scripted model asking for bookFlight:
List<Message> conversation = List.of(new UserMessage("Book flight VX205 for tomorrow"));
ChatResponse reply = client.prompt().messages(conversation).call().chatResponse();
List<String> awaiting = ToolCallDecisions.awaitingDecision(reply);
What it printed (output/01-pause-and-resume.txt):
-- first request ----------------------------------------------
model calls so far: 1
reply text (content()): ''
reply has tool calls: true
awaitingDecision(reply): [call_1]
isAwaitingDecision(reply): true
tool call shown to the person: bookFlight {"flightNumber":"VX205"}
ledger (real side effects): []
metadata key holding the keys: spring.ai.tool-calls-awaiting-decision
Read the numbers. One model call was made, the reply text is the empty string, the call is still there for you to show, and the ledger is empty: the booking did not happen. The key call_1 is the call’s own id from the model. The last line is the name of the response-metadata entry where Spring AI stores the waiting keys, in case you ever need to read it raw.
The fingerprint of a missed pause. A chat endpoint that returns an empty string, with no exception and no log line, right after the model “decided” to use a tool. If a gated tool is involved, the reply is paused, not broken: readchatResponse()and checkawaitingDecisionbefore you read the text.
Going deeper: keys, and what happens without call ids
The key of a call is its id. Some providers omit ids, and a model can repeat one, so Spring AI falls back to the call’s position and gives it a key starting with #. This test sends two calls that share the id dup and one call with an empty id (PositionKeysTest.java):
POSITION_KEY_PREFIX: #
two calls that both have id 'dup' -> keys: [#0, #1]
awaitingDecision for that reply: [#0, #1]
one call with an empty id -> keys: [#0]
allow('#0') + deny('#1') -> ledger: [bookFlight VX205]The keys are returned in the order of the message’s tool calls, and a position key only makes sense against the reply it was made from, so store the reply exactly as it came back and resume with that same object (docs-sourced; the test above shows the keys themselves). Streaming works differently: text streams as usual and the last chunk carries the awaiting keys, and an aggregated response does not (docs-sourced, not run here; the scripted model does not stream).
Resume by answering every call, then sending the results back to the model
A person looks at the call and says yes or no. In code that is oneToolCallDecision per tool call: allow(key) or deny(key). You collect them into ToolCallDecisions and hand them, with the reply that paused, to the same ToolCallingManager. It runs the allowed calls and returns the conversation so far with the tool results appended. Then you send that to the model as the next request.
ToolCallDecisions decisions = ToolCallDecisions.of(ToolCallDecision.allow("call_1"));
Prompt prompt = new Prompt(conversation,
ToolCallingChatOptions.builder().toolCallbacks(tools.callbacks()).build());
ToolExecutionResult result = manager.executeToolCalls(prompt, reply, decisions);
String answer = client.prompt().messages(result.conversationHistory()).call().content();
The rest of output/01-pause-and-resume.txt:
-- after allow(call_1) + executeToolCalls ---------------------
ledger (real side effects): [bookFlight VX205]
conversationHistory():
UserMessage[Book flight VX205 for tomorrow]
AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}]
ToolResponseMessage[call_1:bookFlight -> "Booked VX205, reference BK-5"]
returnDirect(): false
-- resumed request --------------------------------------------
model calls so far: 2
final answer: Done. VX205 is booked.
Three things to take from the output. The ledger now has the booking, so the tool ran only after the decision. The history ends with the assistant’s tool call followed by a ToolResponseMessage holding the real result. And the second model call used exactly that history, which is how the model learns the booking succeeded and can answer in plain text.
The Prompt built in that block carries the tool callbacks again. Resume does not look tools up by name on its own, so the same list is registered twice, in ToolRegistry.java (once on the client, once on the Prompt), and ChatClientFactory.java passes the same manager to the advisor and to the resume:
public static ChatClient create(ChatModel chatModel, ToolCallingManager manager, List<ToolCallback> tools) {
ToolCallingAdvisor advisor = ToolCallingAdvisor.builder().toolCallingManager(manager).build();
return ChatClient.builder(chatModel)
.defaultOptions(baseOptions(chatModel))
.defaultToolCallbacks(tools)
.defaultAdvisors(advisor)
.build();
}
Going deeper: chat memory instead of keeping the conversation yourself (docs-sourced, not run)
This module keeps the conversation itself and resumes with the full history, which is what the documentation calls the “application keeps the conversation” path. With chat memory, the documentation says to send only the tool results (the last message of the history) and let the memory advisor supply the rest. It also notes that MessageChatMemoryAdvisor and the ChatMemory API are deprecated since 2.1.0, with removal planned for 3.0.0, and points to session memory. I did not run a memory-backed resume; for the session API itself see Chat Memory to Session Memory in Spring AI 2.1.
If every call was allowed and every tool has returnDirect = true, result.returnDirect() is true and you return the results without another model call; a denied call always goes back to the model (docs-sourced; the returnDirect() value for a denial is in output/03-deny-messages.txt).
One gated call pauses the whole reply, and every call in it needs a decision
Models often ask for several tools at once. The rule is blunt: if any call in a reply needs confirmation, the whole reply pauses and none of its calls run. So a harmless search that happens to share a reply with a booking waits too. WholeReplyPausesTest.java scripts exactly that reply:calls in the reply: [call_1=searchFlights, call_2=bookFlight]
awaitingDecision(reply): [call_2]
ledger after the pause: []
decision for call_2 only -> IllegalArgumentException:
Every tool call of the reply needs a decision; missing: [call_1]
ledger after the refused resume: []
decisions for both -> ledger: [searchFlights BOS->SFO, bookFlight VX205]
tool results, in the model's order:
ToolResponseMessage[call_1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"][call_2:bookFlight -> "Booked VX205, reference BK-5"]
Look closely at the second line, because it is the trap in this feature. awaitingDecision returns only [call_2] — the call the policy flagged — yet the resume refuses a decision list that leaves out call_1, the harmless search. The error says every tool call of the reply needs a decision, and the ledger stays empty, so nothing ran. An approval screen built from awaitingDecision alone shows the person one call, collects one decision, and fails on submit.
Build the screen from all the calls, not from the awaiting keys. UseToolCallDecisions.toolCallKeys(message)with the message’sgetToolCalls()to list every call, and let the person allow or deny each. PendingApproval.calls() does this, so the approver sees the harmless search next to the booking.
Going deeper: the three ways a resume is refused
A resume is validated as a whole before any tool runs, so a bad decision list never leaves a half-finished booking. ResumeErrorsTest.java triggers all three:
1. no decision for call_1:
IllegalArgumentException: Every tool call of the reply needs a decision; missing: [call_1]
2. a decision for a key that is not in the reply (call_99):
IllegalArgumentException: No tool call has the key 'call_99'; the reply's tool call keys: [call_1]
3. allowed call, but its tool is not on the Prompt:
IllegalArgumentException: The prompt does not carry the tool 'bookFlight' of the allowed call 'call_1'; an allowed call runs only with a tool of the prompt
ledger after all three: []The third one is the easiest to hit in your own code: the Prompt you pass to executeToolCalls must carry the tool callbacks, or an allowed call has nothing to run. The policy is also not re-evaluated on resume (docs-sourced), which is why a decision is required for calls it never flagged.
Denying is a message to the model, not an error
A “no” does not throw anything. It becomes the result of the tool call, as text the model reads, and the model then answers the user. There are two forms.deny(key) sends a built-in sentence. deny(key, message) sends yours, which is how you tell the model what to do next. DenyTest.java denies one booking each way:
DEFAULT_DENY_MESSAGE: The user did not allow this tool call.
history the model is sent next:
UserMessage[Rebook me on VX205]
AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}, call_2:cancelBooking{"reference":"BK-9"}]
ToolResponseMessage[call_1:bookFlight -> The user did not allow this tool call.][call_2:cancelBooking -> The user wants an aisle seat, ask again.]
ledger (nothing ran): []
returnDirect(): false
model's next answer: Understood, I will ask which seat you prefer.
Read the history the model gets next. The first denial arrives as the default sentence and the second as the message written for it, both in the slot where a successful result would have been. The ledger is empty, so neither tool ran, and the scripted model’s next answer shows it can react to the message by asking a follow-up. Writing the message as an instruction (“ask which seat they want”) is the useful form, because the model reads it as a tool result.
Going deeper: the deny API as the jar declares it
From output/15-api-surface.txt (javap -public on the 2.1.0 jar): a decision is a record with the call key, an allowed flag and a message, and the two deny factories differ only in whether they carry your message.
public final class org.springframework.ai.model.tool.ToolCallDecision extends java.lang.Record {
public static final java.lang.String DEFAULT_DENY_MESSAGE;
public org.springframework.ai.model.tool.ToolCallDecision(java.lang.String, boolean, java.lang.String);
public static org.springframework.ai.model.tool.ToolCallDecision allow(java.lang.String);
public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String);
public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String, java.lang.String);
public java.lang.String denyMessage();
public final java.lang.String toString();
public final int hashCode();
public final boolean equals(java.lang.Object);
public java.lang.String toolCallId();
public boolean allowed();
public java.lang.String message();
A deny message is untrusted text. It goes into the conversation as a tool result and is not sanitised (docs-sourced). If a person types it, treat it like any user input; if your own code builds it from a user’s words, do not let it contain instructions you would not give the model yourself.
Choose what needs a person: by flag, by name, or by looking at the arguments
The annotation covers tools you own. Real systems also have tools you cannot edit (an MCP server’s tools) and tools that are harmless most of the time and dangerous with certain arguments (a transfer of five dollars versus five thousand). That is what aToolCallConfirmationPolicy is for: a function that receives the tool call (name and JSON arguments) and the tool’s metadata and answers yes or no. Four are built in — fromToolMetadata() (the default), forTools(names...), none() and a.or(b) — and you can write your own. ConfirmationPolicies.java pauses transfers over a thousand dollars:
@Bean
ToolCallConfirmationPolicy largeTransfers() {
return (toolCall, toolMetadata) -> toolCall.name().equals("transferMoney")
&& amountOf(toolCall.arguments()) > TRANSFER_LIMIT;
}
/** Model-supplied JSON is untrusted: an unreadable amount is treated as "needs a person". */
static int amountOf(String argumentsJson) {
try {
JsonNode amount = JSON.readTree(argumentsJson).path("amount");
return amount.isNumber() ? amount.asInt() : Integer.MAX_VALUE;
}
catch (RuntimeException e) {
return Integer.MAX_VALUE;
}
}
A thing to notice in amountOf: the arguments are JSON the model wrote, so the policy must expect garbage. Anything unreadable counts as “needs a person”, so a malformed call fails safe. Now ten combinations, each answered by running the same scripted question (PolicyTest.java):
policy | call result
default (fromToolMetadata) | bookFlight PAUSES [c1]
default (fromToolMetadata) | transferMoney 500 runs (ledger [transferMoney ACME 500])
none() | bookFlight runs (ledger [bookFlight VX205])
forTools("transferMoney") | transferMoney 500 PAUSES [c2]
forTools("transferMoney") | bookFlight runs (ledger [bookFlight VX205])
over-1000 argument policy | transferMoney 500 runs (ledger [transferMoney ACME 500])
over-1000 argument policy | transferMoney 5000 PAUSES [c3]
over-1000 argument policy | bookFlight runs (ledger [bookFlight VX205])
fromToolMetadata().or(over-1000)| bookFlight PAUSES [c1]
fromToolMetadata().or(over-1000)| transferMoney 5000 PAUSES [c3]
Read it row by row. The default policy pauses bookFlight because of its flag and lets a 500-dollar transfer run. none() switches everything off. forTools("transferMoney") pauses transfers by name and says nothing about bookFlight, which therefore runs. The argument policy pauses only the 5000 transfer. And fromToolMetadata().or(...) is the combination you usually want: the flag and the argument rule.
The eighth row is the second trap: a policy that names only transfers leaves bookFlight running. When you build a ToolCallingManager yourself and pass a policy, that policy replaces the default instead of adding to it, so the over-1000 policy on its own leaves your annotated tools unprotected. With Spring Boot you avoid this: the auto-configuration ORs the flag, the property and every policy bean together, so a bean can only add calls that need a person, never remove one (docs-sourced; the last line of the output further down shows a bean still applying when the flag is off).
The property form pauses a tool you cannot annotate. The test sets it like this (ToolsPropertyTest.java), with a USD 5 transfer, far under the 1000 bean:
@SpringBootTest(properties = { "spring.ai.model.chat=none", "spring.ai.tools.confirmation.tools=transferMoney" })
status: AWAITING_APPROVAL
calls: [CallView[key=t1, name=transferMoney, arguments={"payee":"ACME","amount":5}]]
ledger: []
The name is the one the model sees, including any prefix an MCP client adds (docs-sourced). Finally, the one switch that turns the flag off. It exists for tests and batch jobs where nobody can answer, it logs a warning at startup, and it does not touch the property or the beans (ConfirmationDisabledTest.java):
startup warning: WARN ToolCallingAutoConfiguration: Tool call confirmation is disabled (spring.ai.tools.confirmation.enabled=false): tools marked requiresConfirmation run as soon as the model calls them, without a person's confirmation.
bookFlight (requiresConfirmation = true): status=DONE ledger=[bookFlight VX205]
transferMoney 5000 (policy bean): status=AWAITING_APPROVAL ledger=[bookFlight VX205]
Turning the flag off is silent for users and loud only in the log. The first booking above ran with no pause, becauseenabled=falsemakes the flag stop counting, while the 5000 transfer still paused because a policy bean is not governed by that switch. If you putenabled=falsein a shared test profile, check that it cannot reach production.
Going deeper: a custom manager must forward the decision overload
If you wrap DefaultToolCallingManager for logging or metrics, the interface has three methods, and the one resumption uses, executeToolCalls(Prompt, ChatResponse, ToolCallDecisions), is a default method that throws (see output/15-api-surface.txt). The pause still works through a wrapper that forgets it, which makes the omission easy to ship. This test builds exactly that wrapper:
static final class ForgetfulManager implements ToolCallingManager {
private final ToolCallingManager delegate = ToolCallingManager.builder().build();
@Override
public List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions options) {
return delegate.resolveToolDefinitions(options);
}
@Override
public ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse chatResponse) {
return delegate.executeToolCalls(prompt, chatResponse);
}
}pause through the wrapping manager: awaitingDecision = [call_1]
resume through the wrapping manager: UnsupportedOperationException: com.ankurm.toolconfirmation.CustomManagerTest$ForgetfulManager does not support tool call decisions
ledger: []The reference page says a wrapper must delegate this method too. Declaring your own ToolCallingManager bean replaces the auto-configured one and with it the policy built from the flag, the property and your beans, so wire the policy into your own manager if you do (docs-sourced).
What the framework does not do: hold the pause, check the approver, answer it once, keep a record
Everything so far is Spring AI. What follows is the application that makes it safe to put in front of people, and the reference page says plainly that it is yours: the framework does not authenticate the approver, does not prevent a replay, and keeps no state while paused.private ChatResult handle(String conversationId, String user, List<Message> conversation, ChatResponse reply) {
List<String> awaiting = ToolCallDecisions.awaitingDecision(reply);
if (!awaiting.isEmpty()) {
PendingApproval pending = new PendingApproval(UUID.randomUUID().toString().substring(0, 8),
conversationId, user, Instant.now(), List.copyOf(conversation), reply, awaiting);
this.store.add(pending);
this.conversations.save(conversationId, conversation);
for (CallView call : pending.calls()) {
this.audit.record("PAUSED", pending.id(), user, call.name(), call.arguments());
}
this.events.publish("approval-requested", pending.id());
return ChatResult.awaiting(pending);
}
AssistantMessage output = reply.getResult().getOutput();
conversation.add(output);
this.conversations.save(conversationId, conversation);
return ChatResult.done(output.getText());
}
The paused reply is kept in PendingApproval.java and the approver only ever sends keys and verdicts. That is deliberate: a client that could supply the reply could run any tool with any arguments and approve it itself (docs-sourced; it is the first item in the page’s security list). Now the resume, with the two guards that come before any tool runs:
PendingApproval pending = this.store.find(approvalId).orElse(null);
if (pending == null) {
if (this.store.wasResolved(approvalId)) {
this.audit.record("REPLAY_REFUSED", approvalId, approver, "-", "pause already resolved");
throw new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved");
}
throw new ApprovalException(HttpStatus.NOT_FOUND, "no such approval " + approvalId);
}
if (!this.properties.mayApprove(approver)) {
this.audit.record("APPROVER_REFUSED", approvalId, String.valueOf(approver), "-", "not in the approver list");
throw new ApprovalException(HttpStatus.FORBIDDEN, "'" + approver + "' may not approve");
}
pending = this.store.take(approvalId).orElseThrow(
() -> new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved"));
Then the API, over HTTP, as one story. A requester asks to book; the pause comes back with an id; a stranger is refused; an approver sends an empty decision list and is refused with the pause kept; the real approval books the flight; and the same pause is refused a second time (ApprovalApiTest.java, output output/10-http-flow.txt):
POST /api/chat (carol: Book VX205)
-> 200 {"status":"AWAITING_APPROVAL","answer":null,"approvalId":"4dbe1483","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]}
ledger: []
GET /api/approvals
-> 200 [{"id":"4dbe1483","conversationId":"c1","requestedBy":"carol","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]}]
POST /api/approvals/4dbe1483/decisions X-Approver: mallory (allow call_1)
-> 403 {"error":"'mallory' may not approve"}
ledger: []
POST /api/approvals/4dbe1483/decisions X-Approver: alice (no decisions)
-> 400 {"error":"Every tool call of the reply needs a decision; missing: [call_1]"}
still pending: true
POST /api/approvals/4dbe1483/decisions X-Approver: alice (allow call_1)
-> 200 {"status":"DONE","answer":"Booked VX205. Reference BK-5.","approvalId":null,"calls":[]}
ledger: [bookFlight VX205]
POST /api/approvals/4dbe1483/decisions X-Approver: bob (the same pause again)
-> 409 {"error":"approval 4dbe1483 was already resolved"}
ledger: [bookFlight VX205]
POST /api/approvals/nope0000/decisions X-Approver: alice
-> 404 {"error":"no such approval nope0000"}
Each response is a status the caller can act on: 403 for someone not on the list, 400 for a bad decision list (and the pause survives, so the approver can fix it), 409 for a pause that was already answered, 404 for an id that never existed. The ledger confirms that the booking happened once, after the one valid approval. The audit log kept the whole exchange (AuditLog.java, output/11-audit-log.txt):
PAUSED approval=4dbe1483 actor=carol tool=bookFlight {"flightNumber":"VX205"}
APPROVER_REFUSED approval=4dbe1483 actor=mallory tool=- not in the approver list
DECISION_REJECTED approval=4dbe1483 actor=alice tool=- Every tool call of the reply needs a decision; missing: [call_1]
APPROVED approval=4dbe1483 actor=alice tool=bookFlight {"flightNumber":"VX205"}
REPLAY_REFUSED approval=4dbe1483 actor=bob tool=- pause already resolved
The framework logs none of this, because it does not know who anyone is. These lines say who paused, who was refused, who allowed what with which arguments, and who tried to replay. The refusal lines are as important as the approvals: they are what you read after an incident.
Replays deserve their own proof. Run executeToolCalls twice with the same decisions on the same reply and the tool runs twice (ReplayTest.java):
calls to executeToolCalls: 2
ledger: [bookFlight VX205, bookFlight VX205]
A customer is booked, and charged, twice.
That is why the store answers a pause once. ApprovalStore.java removes and returns in one atomic step, so two approvers clicking at the same moment cannot both get it:
/** Atomic: the first caller gets the pause, every later caller gets empty. */
public Optional<PendingApproval> take(String id) {
return Optional.ofNullable(this.pending.remove(id));
}
Sixteen threads approving the same pause at once (ConcurrentApprovalTest.java):
1 x 200 DONE
15 x 409 approval <id> was already resolved
ledger: [bookFlight VX205]
One wins, fifteen get a 409, and there is one booking. A check-then-act version (look the pause up, then remove it) would let several of those threads through, because the tool runs between the two steps.
The approver check here is a stand-in.ApprovalPropertiescompares a name from theX-Approverheader to a list so the check is visible in the tests. A request header proves nothing. In a real service read the authenticated principal and its authorities (Spring Security), and consider refusing the requester approving their own request, which this module does not do.
Going deeper: what to persist if a pause must survive a restart (design note, not run)
The store here is a ConcurrentHashMap, so a restart loses every pause. The documentation says a paused response is ordinary data and that approval flows can survive restarts if you keep the conversation state; I did not build that. What you would need to persist, reasoned from the code above: the conversation messages that preceded the reply, the reply itself (its tool calls and ids, exactly as the model sent them, because position keys depend on order), the requester, and a status that moves from pending to resolved with a compare-and-set so the one-winner rule survives across servers. Do not recreate the reply from what you showed the approver.
Abandoned pauses need a policy too. If nobody answers and the user sends a new message, the history now holds tool calls with no results, and most providers reject that (docs-sourced). Resolve the pause first, for example by denying every call with a message such as “The user moved on”, before accepting new input; do not resume a pause after new input was accepted.
An approver page where an open stream says “something changed” and HTML fragments carry the data
An approver needs a screen that shows new pauses as they happen. The smallest honest version uses two ideas. Server-Sent Events (SSE) is a response that never ends: the server writes a line whenever it has news and the browser reads it. htmx lets an HTML attribute say “when this happens, fetch that URL and swap the result in”. Put them together and the page needs no JavaScript of our own.approval-requested by fetching the list again as ready-made HTML. That keeps the logic on the server and makes the stream trivially small. The page is approver.html and this is all of it that matters:
<body hx-ext="sse" sse-connect="/approvals/stream">
<h1>Pending tool approvals</h1>
<div id="pending" hx-get="/ui/approvals" hx-trigger="load, sse:approval-requested, sse:approval-resolved"></div>
</body>
The server side is ApproverUiController.java. Every string that came from the model — the tool name and especially its arguments — is HTML-escaped, because the model chose those strings and a prompt-injected model can choose markup. The form also defaults to Deny, so a submit with nothing selected refuses rather than allows:
for (CallView call : p.calls()) {
String key = HtmlUtils.htmlEscape(call.key());
html.append("<div class=\"call\"><code>").append(HtmlUtils.htmlEscape(call.name())).append("</code> ")
.append("<pre>").append(HtmlUtils.htmlEscape(call.arguments())).append("</pre>")
.append("<label><input type=\"radio\" name=\"decision-").append(key)
.append("\" value=\"allow\"> Allow</label> ")
.append("<label><input type=\"radio\" name=\"decision-").append(key)
.append("\" value=\"deny\" checked> Deny</label> ")
.append("<input type=\"text\" name=\"message-").append(key)
.append("\" placeholder=\"Message to the model if denied\"></div>");
}
The test hands the model a hostile argument — an <img onerror> tag as the flight number — and reads back what a real embedded server sends (ApproverUiTest.java):
tool argument chosen by the model: <img src=x onerror=alert(1)>
SSE lines the approver page received:
event:hello
data:connected
event:approval-requested
data:69b1d486
event:approval-resolved
data:69b1d486
GET /ui/approvals (the <pre> element):
<pre>{"flightNumber":"<img src=x onerror=alert(1)>"}</pre>
POST /ui/approvals/69b1d486 (approver=alice, deny) ->
<p class="ok">Decision recorded.</p>
ledger: []
approver.html wiring:
<!-- The page opens ONE SSE connection. Each event re-runs the hx-get below; the browser never polls. -->
<body hx-ext="sse" sse-connect="/approvals/stream">
<div id="pending" hx-get="/ui/approvals" hx-trigger="load, sse:approval-requested, sse:approval-resolved"></div>
Three things are visible. The stream delivered hello, then approval-requested and approval-resolved with the approval id. The fragment shows the tag as inert text, with < where the angle bracket was. And the denial through the form left the ledger empty. What this does not show is a browser: I did not open the page, so htmx’s handling of the events is exactly as documented, not observed.
An open stream delays a graceful shutdown. Spring Boot stops its web server gracefully by default, waiting for requests in flight, and an SSE stream never finishes. During this module’s tests one approver page held the test JVM for 30 seconds until Surefire killed it. A thread dump showedThe measurement, from ShutdownTest.java with the grace period shortened to 5 seconds so the test is quick (output/14-sse-and-graceful-shutdown.txt):tomcat-shutdownwaiting, and@PreDestroywas too late because it runs after that wait. The fix is aSmartLifecyclewith the highest phase, which stops before the web server and completes every stream.
streams left open: over 4000 ms
streams completed by the lifecycle: under 2000 ms
(the exact figures vary per run; the 5 s wall is the configured grace period)
With streams left open, closing the context took more than four seconds, effectively the whole grace period; with them completed first, under two. The test asserts those two bounds rather than exact times, which vary per run. The fix is in ApprovalEvents.java:
public void stop() {
if (this.closeStreamsOnStop) {
this.emitters.forEach(SseEmitter::complete);
this.emitters.clear();
}
this.running = false;
}
Going deeper: the approver page, line by line (and what I did not verify)
- Vendored scripts. htmx 2.0.11 and its SSE extension are copied under
src/main/resources/static/vendor/(with a checksum file) so the page makes no CDN request. Reused from the earlier streaming chat UI module, where the same files were checked in a headless browser; this page itself was not. - Not verified here: how htmx swaps the fragment into the
#pendingelement, the radio buttons’ behaviour in a real browser, and reconnection after the stream drops. These come from the htmx documentation, not from a run. - Not covered: authentication of the page, CSRF protection for the form post, and showing the approver who is asking beyond the requester name. All three belong in a real deployment.
Two quieter problems: the earlier rounds of a turn, and the pause you never resume
A single user turn can involve several rounds of tool calls. Suppose the model first runs the harmless search, then asks for the booking. The paused response contains only the last reply, so your stored conversation does not know the search happened. MultiRoundTest.java scripts that turn and prints what the model was sent each time:ledger at the pause: [searchFlights BOS->SFO]
model calls: 3
prompt 1 sent to the model:
UserMessage[Find a flight BOS to SFO and book the first one]
prompt 2 sent to the model:
UserMessage[Find a flight BOS to SFO and book the first one]
AssistantMessage[toolCalls=s1:searchFlights{"from":"BOS","to":"SFO"}]
ToolResponseMessage[s1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"]
prompt 3 sent to the model:
UserMessage[Find a flight BOS to SFO and book the first one]
AssistantMessage[toolCalls=b1:bookFlight{"flightNumber":"VX205"}]
ToolResponseMessage[b1:bookFlight -> "Booked VX205, reference BK-5"]
Prompt 2 had the search round; prompt 3 (the resume) does not.
Prompt 2 contains the search call and its result. Prompt 3, the resume after approval, does not: the model is asked to continue a booking without the flight list it chose from. I did not try a real model, so what it would do without that context is open. The reference page says the same in its own terms: with memory outside the loop earlier rounds are lost, and with memory inside the loop every round is stored (docs-sourced; I did not run the memory-inside variant). Two remedies I did not test: keep read-only lookups out of the same turn as the gated action, or store the full turn yourself instead of only the user message.
Going deeper: other documented behaviour I did not run
- Tool Search. Tools disclosed by the Tool Search Tool keep their metadata, so a disclosed gated tool pauses the loop; resume with the full tool set configured on the client (see the tool-calling post for the advisor).
- Call limits. Limits apply to allowed calls, and on resume the manager counts only the calls it finds in the prompt; exceeding one throws
ToolCallLimitExceededExceptionto your application, since there is no loop to turn it into a reply. - Replays and approvers. The page’s own security list: read the paused reply from storage the end user cannot modify, authenticate the approver yourself, make resumption idempotent, and treat deny messages as untrusted. The first, third and fourth are demonstrated above; the second is the stand-in noted earlier.
- Observability. A pause is an ordinary response, so your existing metrics see a successful model call. If you want a gauge of pending approvals,
ApprovalStore.pending()is the place to read it. See custom advisors for hooking the chain.
Should you build this? Only for actions that are costly to undo
Gate the few calls that matter, and still authorise inside the tool. Confirmation is a human check on the model’s request, not an authorisation system. A person approving 40 calls an hour approves the 41st without reading it, so gate only what is costly or irreversible (money, deletion, outbound messages) and leave reads alone. Inside the tool, still check that the user may do the thing, because the approver is not the caller and the arguments came from a model. Make the tool idempotent too: a replayed approval, or a retry after a timeout, should not charge twice. And if there is no person to ask — a batch job, an overnight agent — this feature is the wrong tool; use an allow-list and limits instead (see Prompt Injection Defense in Spring AI).
Further reading
- Companion repository: asmhatre/spring-ai, module tool-confirmation — the code and the 17 transcripts quoted above, regenerated by
./scripts/run-all.sh. - Tool Call Confirmation, Spring AI 2.1 reference — the pause and resume flow, policies, properties and security notes.
- Tool Calling, Spring AI 2.1 reference — user-controlled tool execution and the loop.
- Tool Calling in Spring AI 2.0: @Tool, ToolCallingAdvisor and the Tool Search Advisor
- Spring AI MCP Client: Calling External MCP Servers from ChatClient — gate tools you do not own with
forTools. - Securing an MCP Server with Spring Security 7 — per-tool scopes, the server-side counterpart.
- Streaming AI Chat UI with Spring AI, SSE and htmx
No Comments yet!