Building Gemini tool calling with @Tool in Spring AI 2.0.1
Expose Spring beans as Gemini tools using @Tool in Spring AI 2.0.1, cap tool loops, and fix Failed to parse JSON errors with a custom exception processor.
LLMs can’t read your live database or query internal APIs on their own. Spring AI 2.0.1 bridges that gap by turning
@Tool-annotated Spring bean methods into JSON Schema definitions that Gemini invokes during a chat turn. In this post, I’ll wire up order lookup tools with call limits and fix a Spring AI 2.0.1 bug where tool exceptions crashGoogleGenAiChatModelwithFailed to parse JSON.
Tested with Spring Boot 4.1.1, Kotlin 2.3.21, Spring AI 2.0.1, and
gemini-3.5-flash-lite.
How the tool calling loop works
When you pass a @Tool bean to ChatClient, Spring AI’s ToolCallingAdvisor runs a multi-turn loop between Gemini and your Spring application without exposing those intermediate steps to the HTTP caller (for a deeper look at the underlying protocol, see LLM tool use and function calling mechanisms).
sequenceDiagram
autonumber
actor User as Client
participant API as ToolCallingController
participant Advisor as ToolCallingAdvisor
participant Gemini as Google Gemini API
participant Tools as "@Tool OrderTools Bean"
User->>API: POST /api/tools/chat ("Check status for ORD-1002")
API->>Advisor: chatClient.prompt().tools(orderTools).call()
Advisor->>Gemini: Turn 1 (prompt + getOrderStatus JSON Schema)
Note over Gemini: Decides live lookup is required
Gemini-->>Advisor: FunctionCall (name="getOrderStatus", args={orderId="ORD-1002"})
Advisor->>Tools: Reflectively invoke getOrderStatus("ORD-1002")
Tools-->>Advisor: OrderStatus(status=SHIPPED, carrier="FedEx", ...)
Advisor->>Gemini: Turn 2 (FunctionResponse JSON payload)
Note over Gemini: Synthesizes final user-facing answer
Gemini-->>Advisor: AssistantMessage ("Your 27-inch monitor is shipped via FedEx...")
Advisor-->>API: Final response text
API-->>User: 200 OK
From the client’s perspective, this is a single HTTP POST. Under the hood, Spring AI makes two LLM round trips: one to receive the structured FunctionCall, and a second to feed back the serialized FunctionResponse so Gemini can write the final answer.
Choosing @Tool vs. alternatives
| Approach | Best fit | Latency / overhead | When to avoid |
|---|---|---|---|
Spring AI @Tool bean | In-process DB lookups, internal service calls in the same JVM | Low (local reflection) | Tools shared across multiple services or languages |
| MCP server | Cross-team or multi-agent tool catalogs over stdio/HTTP | Medium (extra process or network hop) | Single-service prototypes with 2–3 local methods |
| Prompt-stuffed context | Static reference data that fits in one prompt | Lowest (1 LLM call) | Live transactional data (orders, inventory, prices) |
When not to use @Tool directly: Don’t expose destructive write operations (refunds, account deletion, bulk updates) to an unguarded tool loop without a human approval step or strict authorization checks. Also skip tool calling for deterministic workflows where a regular REST endpoint or service pipeline already knows which database query to run—paying for two LLM round trips just to route a fixed query adds latency and cost for zero benefit.
Project setup and loop guardrails
The complete working module is available in spring-ai-examples (tool-calling).
build.gradle.kts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
implementation("tools.jackson.module:jackson-module-kotlin")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
application.yaml
Always cap tool invocations per request. A confused model retrying a failing lookup in a tight loop can burn through your token quota and hold HTTP threads open:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
server:
port: 8088
spring:
application:
name: tool-calling
ai:
google:
genai:
api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
chat:
model: gemini-3.5-flash-lite
tools:
# Return tool errors to the model instead of aborting the whole request
throw-exception-on-error: false
limits:
# Cap at 5 calls per tool and 10 total calls in a single request
max-calls-per-tool-default: 5
max-total-tool-calls: 10
on-limit-exceeded: return-error-response
logging:
level:
# Log tool arguments and serialized responses during local debugging
org.springframework.ai.model.tool: DEBUG
Writing business tools with @Tool and @ToolParam
The description strings on @Tool and @ToolParam aren’t documentation comments—they are the prompt instructions Gemini uses to decide when to call a method and how to format its arguments. Vague descriptions lead to malformed inputs or skipped tool calls.
tools/OrderTools.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package io.github.cmsong111.tool_calling.tools
import io.github.cmsong111.tool_calling.dto.DeliveryStatus
import io.github.cmsong111.tool_calling.dto.OrderStatus
import org.slf4j.LoggerFactory
import org.springframework.ai.tool.annotation.Tool
import org.springframework.ai.tool.annotation.ToolParam
import org.springframework.stereotype.Component
import java.time.LocalDate
@Component
class OrderTools {
private val log = LoggerFactory.getLogger(javaClass)
private val orders: Map<String, OrderStatus> = listOf(
OrderStatus("ORD-1001", "Namju Kim", "Mechanical Keyboard", DeliveryStatus.DELIVERED, "UPS", "6894-1234-0001", LocalDate.of(2026, 10, 8)),
OrderStatus("ORD-1002", "Namju Kim", "27-inch Monitor", DeliveryStatus.SHIPPED, "FedEx", "4021-5678-0002", LocalDate.of(2026, 10, 13)),
OrderStatus("ORD-1003", "Younghee Lee", "Wireless Mouse", DeliveryStatus.PREPARING, null, null, LocalDate.of(2026, 10, 15)),
OrderStatus("ORD-1004", "Chulsoo Park", "USB-C Hub", DeliveryStatus.CANCELLED, null, null, null),
).associateBy { it.orderId }
@Tool(description = "Look up an order's item name, delivery status, carrier, tracking number, and estimated delivery date by order ID. Order IDs use the format 'ORD-' followed by 4 digits.")
fun getOrderStatus(
@ToolParam(description = "Order ID to look up (example: ORD-1002)") orderId: String
): OrderStatus {
log.info("[Tool] getOrderStatus(orderId={})", orderId)
val normalized = orderId.trim().uppercase()
require(ORDER_ID_PATTERN.matches(normalized)) {
"Invalid order ID format: '$orderId'. Expected 'ORD-' followed by 4 digits (example: ORD-1002)."
}
return orders[normalized] ?: throw OrderNotFoundException(normalized)
}
@Tool(description = "List all orders placed by a customer using their full name.")
fun findOrdersByCustomer(
@ToolParam(description = "Customer full name (example: Namju Kim)") customerName: String
): List<OrderStatus> {
log.info("[Tool] findOrdersByCustomer(customerName={})", customerName)
require(customerName.isNotBlank()) { "Customer name must not be blank." }
return orders.values.filter { it.customerName == customerName.trim() }
}
companion object {
private val ORDER_ID_PATTERN = Regex("^ORD-\\d{4}$")
}
}
Notice the input validation inside getOrderStatus. Never trust model-supplied arguments blindly: trim whitespace, normalize case, and validate against a strict regex before touching any repository.
Fixing the Spring AI 2.0.1 JSON parsing bug on tool exceptions
During integration testing, I asked the chatbot about a nonexistent order (ORD-9999). Even with throw-exception-on-error: false, the entire request failed with an unhandled 500 error.
Spring AI 2.0.1
GoogleGenAiChatModeltool exception bug: WhenOrderToolsthrowsOrderNotFoundException, Spring AI’s defaultDefaultToolExecutionExceptionProcessorreturns the raw exception message as a plain string ("Order ORD-9999 not found"). However, the Google GenAI SDK requires everyFunctionResponsepayload to be a JSON object (Map).GoogleGenAiChatModelrunsJsonParser.fromJsonunconditionally on the tool result string, throwingorg.springframework.ai.retry.NonTransientAiException: Failed to parse JSONwhenever a plain string comes back.
The fix is a one-line custom ToolExecutionExceptionProcessor bean that wraps every tool exception message in a valid JSON object ({"error": "..."}).
ToolCallingApplication.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@SpringBootApplication
class ToolCallingApplication {
@Bean
fun chatClient(builder: ChatClient.Builder): ChatClient {
return builder
.defaultSystem(
"""
You are a customer support assistant for an online store.
For any question requiring live data such as orders, shipping, or weather, always call the provided tools before answering.
If a tool returns an error, explain it politely to the customer and never guess or fabricate details.
""".trimIndent()
)
.build()
}
/**
* Wrap tool exception messages as a JSON object to prevent
* GoogleGenAiChatModel from throwing Failed to parse JSON.
*/
@Bean
fun toolExecutionExceptionProcessor(): ToolExecutionExceptionProcessor {
return ToolExecutionExceptionProcessor { exception ->
JsonParser.toJson(mapOf("error" to exception.message))
}
}
}
Figure 1. DefaultToolExecutionExceptionProcessor triggering Failed to parse JSON versus graceful recovery after wrapping errors as JSON.
With that bean registered, Gemini receives {"error": "Order ORD-9999 not found"} cleanly and responds to the user with a polite message asking them to double-check the order number.
Binding tools in ChatClient and verifying locally
In the service layer, attach your tool beans per request using .tools(...). Keeping a separate chatWithoutTools method also makes it easy to compare grounded tool responses against baseline model behavior.
service/ToolCallingService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Service
class ToolCallingService(
private val chatClient: ChatClient,
private val orderTools: OrderTools,
private val weatherTools: WeatherTools
) {
fun chat(message: String): String {
return chatClient.prompt()
.user(message)
.tools(orderTools, weatherTools)
.call()
.content() ?: ""
}
fun chatWithoutTools(message: String): String {
return chatClient.prompt()
.user(message)
.call()
.content() ?: ""
}
}
Run the unit and integration suite to verify JSON Schema generation, the custom exception processor, and multi-tool orchestration:
1
./gradlew :tool-calling:test
Figure 2. Unit and integration test suite covering schema generation, JSON error wrapping, and live Gemini tool calls.
Now test the live endpoint with curl:
1
2
3
curl -s -X POST http://localhost:8088/api/tools/chat \
-H "Content-Type: application/json" \
-d '{"message": "Check the delivery status for order ORD-1002"}' | jq .
Figure 3. Gemini invoking OrderTools with ORD-1002 and returning a live shipping summary.
1
2
3
{
"answer": "Your 27-inch Monitor (ORD-1002) is currently shipped via FedEx with tracking number 4021-5678-0002. The estimated delivery date is October 13, 2026."
}
Production caveats and checklist
- Always wrap tool exceptions in JSON for Gemini: Register a custom
ToolExecutionExceptionProcessorreturning{"error": "..."}when running Spring AI 2.0.1 withspring-ai-starter-model-google-genai. - Enforce per-tool and total call limits: Configure
max-calls-per-tool-defaultandmax-total-tool-callsso retry loops can’t exhaust quotas or block servlet threads. - Keep tool schemas tight: Every
@Toolbean you attach is serialized into the prompt on every turn. Only pass the tools relevant to that endpoint instead of registering every bean globally. - Validate all tool inputs server-side: Treat LLM arguments like untrusted user input—enforce format regexes, authorization scopes, and read-only boundaries inside the tool method itself.
- Need live web results instead of internal DB lookups? For open-ended external facts, pair Gemini with built-in web search—see Google Search Grounding with Spring AI and Gemini.