Tool Calling in Spring AI – Connecting LLMs with Java Methods and REST APIs

In Spring AI, Tool Calling (also referred to as Function Calling) enables Large Language Models (LLMs) to interact with live enterprise systems, query databases, invoke external REST APIs, and trigger real-world business actions. Because LLMs are trained on static historical data and cannot directly execute code or access private systems on their own, Spring AI acts as the secure execution bridge between the model’s reasoning and your Java application.

1. How the Tool Calling Execution Lifecycle Works

Crucially, the LLM never executes your Java methods or REST APIs directly. Instead, Spring AI orchestrates a multi-step handshake:
  1. Tool Definition & Schema Registration: When ChatClient sends a prompt to the LLM, Spring AI attaches metadata describing every available tool—its name, description, and an automatically generated JSON Schema detailing its input parameters.

  2. Model Decision & Argument Generation: The LLM analyzes the user’s prompt. If external data or an action is required, the model pauses text generation and returns a structured tool-call request specifying the target tool name and JSON arguments matching the schema.

  3. Advisor-Driven Execution Loop (Spring AI 2.0+): Spring AI intercepts the tool-call request—handled as a first-class, composable loop inside ChatClient’s advisor chain (ToolCallAdvisor)—resolves the matching Java tool, validates the arguments, and executes the method locally.

  4. Result Serialization & Return: Spring AI serializes the Java return value (or exception message) into JSON and sends it back to the LLM as a ToolResponseMessage alongside the conversation history.

  5. Final Synthesis (or Chained Calls): The LLM incorporates the live tool output to generate a grounded final answer—or requests additional sequential/parallel tool calls until the user’s goal is satisfied.

2. Ways to Define Tools in Spring AI

Spring AI provides flexible mechanisms for exposing both local Java logic and remote REST APIs as model-callable tools:

Approach Mechanism & Annotations Best-Fit Use Case
Declarative Java Methods (@Tool) Annotate standard methods inside Spring @Component or @Service beans with @Tool and parameter descriptions with @ToolParam. Spring AI automatically derives the JSON Schema from Java types and parameter names. Exposing existing Spring business services, JPA/JDBC repositories, or internal domain operations.
Programmatic Tool Callbacks (MethodToolCallback / FunctionToolCallback) Register Java java.util.function.Function, Supplier, Consumer, or BiFunction beans—or build ToolCallback instances dynamically at runtime with custom ToolDefinition schemas. Dynamically generated tools, multi-tenant plugin architectures, or wrapping third-party libraries without modifying source code.
REST API Client Wrappers Inside a @Tool method or Function bean, use Spring’s RestClient, WebClient, or @HttpExchange declarative HTTP interfaces to call external microservices, payment gateways, weather APIs, or CRM endpoints, returning mapped DTOs back to the LLM. Connecting LLMs to external SaaS APIs, internal REST microservices, or legacy HTTP backends.
Model Context Protocol (MCP) Tools Connect via Spring AI’s MCP Client starters to automatically discover and invoke tools exposed by remote MCP servers over stdio or SSE/HTTP. Sharing reusable tool ecosystems across multiple AI applications and organizational teams.

3. Key Annotations & Configuration Controls

  • @Tool Attributes:

    • name: Unique identifier sent to the LLM (defaults to the Java method name).

    • description: Clear natural-language explanation telling the LLM what the tool does and when to invoke it—the single biggest factor in accurate tool selection.

    • returnDirect: When set to true, bypasses sending the tool’s output back to the LLM and returns the tool result directly to the caller (ideal for deterministic lookups or binary downloads).

    • resultConverter: Customizes how complex Java objects are converted into strings/JSON for the model.

  • @ToolParam Attributes:

    • description: Explains expected parameter formats, units, or example values (e.g., "Order ID formatted as ORD-1042") to prevent malformed arguments.

    • required: Marks parameters as mandatory or optional inside the generated JSON Schema (all parameters default to required unless specified otherwise).

  • Registration Scope (defaultTools vs. .tools()): Tools can be registered globally on ChatClient.Builder (defaultTools(...)) for every request or attached dynamically per request (.tools(...)) based on user roles or feature flags.

4. Security, Context Injection & Loop Governance

Exposing live Java methods and REST APIs to probabilistic AI models introduces operational and security risks that Spring AI addresses natively:
  • Out-of-Band Context Injection (ToolContext): Sensitive data—such as authenticated userId, tenantId, JWT tokens, or session IDs—should never be passed as LLM-generated tool parameters (which could be spoofed via prompt injection). Instead, adding a ToolContext parameter to a @Tool method allows Spring AI to inject trusted server-side context automatically while hiding that parameter from the LLM’s JSON Schema.

  • Loop & Recursion Guardrails (Spring AI 2.0+): To prevent runaway token spend or infinite tool loops, Spring AI provides built-in properties to cap total tool invocations per request (spring.ai.tools.limits.max-total-tool-calls) and per-tool invocation limits (max-calls-per-tool).

  • Graceful Exception Handling (ToolExecutionExceptionProcessor): When a REST API times out or a database lookup throws an exception, Spring AI catches the error and feeds a controlled error message back to the LLM so the model can recover, retry with corrected arguments, or explain the issue politely rather than crashing the HTTP request.

  • Observability & Live Streaming Events: Because tool execution lives inside the advisor chain in Spring AI 2.0+, applications can observe ToolCallEvent phases (STARTED / COMPLETED) in real time—enabling live UI indicators (such as “Checking order status…”) during streaming responses.

5. Production Best Practices

  • Write Precision Descriptions: Treat @Tool and @ToolParam descriptions like API documentation written for a junior developer—explicitly state preconditions, expected formats, and when not to call a tool.

  • Keep Tool Interfaces Focused & Atomic: Design small, single-purpose tools (e.g., getOrderStatus and listCustomerOrders separately) rather than monolithic Swiss-army-knife methods with dozens of optional parameters.

  • Require Confirmation for Mutating Actions: Read-only queries (fetching stock prices or order status) can run automatically, whereas state-changing REST calls (canceling orders, issuing refunds, sending emails) should either enforce Spring Security authorization checks or require explicit human-in-the-loop confirmation.

  • Filter Large REST Payloads Before Returning: External REST APIs often return massive JSON payloads full of irrelevant metadata; map API responses into lean Java records containing only the fields the LLM actually needs to conserve context tokens and improve reasoning accuracy.

Hands-on Experiment: AI-Powered Banking and Transaction Assistant using Spring AI Tool Calling

Aim: To build a Spring Boot application that uses Spring AI tool calling so an LLM can check balances, list transactions, transfer money and convert currency through Java methods and a REST API.

Description: The application has two parts. The first is a normal banking REST API for accounts, transactions and transfers, stored in MySQL. The second is an AI assistant endpoint where the user writes in plain English. The model reads the tool descriptions and chooses the right Java method, such as the balance lookup or the currency conversion that calls an external REST API. For transfers the model must first ask for confirmation, and money moves only when the user clearly confirms. Demo accounts are created automatically at first start.

Software / Tools Required

  • JDK 17
  • Spring Boot 3.x
  • Maven
  • MySQL 8.x
  • IDE (IntelliJ IDEA / Eclipse / VS Code)
  • Postman
  • An OpenAI API key (environment variable OPENAI_API_KEY)
  • Internet access (for the exchange rate API)

Steps

  1. Generate the project using Spring Initializr
  2. Add the Spring AI BOM and dependencies in pom.xml
  3. Configure MySQL, OpenAI and the exchange API URL in application.properties
  4. Create the entities Account and BankTransaction
  5. Create the repositories
  6. Create the business services AccountService and ExchangeRateService
  7. Create BankingTools with the @Tool methods
  8. Create AssistantService and register the tools on the ChatClient
  9. Create the REST controller
  10. Run the application and test with Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

Field Value
Project Maven
Language Java
Spring Boot 3.4.x (Spring AI 1.0 needs 3.4.x)
Group com.example
Artifact banking-tool-assistant
Packaging Jar
Java 17
Dependencies Spring Web, Spring Data JPA, MySQL Driver, OpenAI (Spring AI)

Step 2: Project Structure

banking-tool-assistant
├── pom.xml
├── README.md
└── src/main
    ├── java/com/example/bankingassistant
    │   ├── BankingAssistantApplication.java
    │   ├── entity
    │   │   ├── Account.java
    │   │   └── BankTransaction.java
    │   ├── repository
    │   │   ├── AccountRepository.java
    │   │   └── BankTransactionRepository.java
    │   ├── service
    │   │   ├── AccountService.java
    │   │   ├── ExchangeRateService.java
    │   │   ├── BankingTools.java
    │   │   └── AssistantService.java
    │   └── controller
    │       └── BankingController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

Running the Application

  1. Start MySQL. The database banking_assistant_db is created automatically.
  2. Set the key: export OPENAI_API_KEY=sk-... (Windows: setx OPENAI_API_KEY "sk-...", then reopen the terminal).
  3. Run mvn spring-boot:run, or run BankingAssistantApplication from your IDE.
  4. The app starts at http://localhost:8080. Watch the console: each tool call prints a line starting with TOOL CALLED:.

URLs and Request Payloads

Normal REST APIs (same service methods the tools use)

# Method URL Payload
1 POST /api/accounts { "holderName": "Kiran", "openingBalance": 10000 }
2 GET /api/accounts/ACC1001 none
3 GET /api/accounts/ACC1001/transactions?count=3 none
4 POST /api/transfers { "fromAccount": "ACC1001", "toAccount": "ACC1002", "amount": 500 }
5 GET /api/exchange?amount=100&from=USD&to=INR none

AI assistant, all sent to POST /api/assistant/chat

# Payload Tool the model should call
6 { "message": "What is the balance of ACC1001?" } getBalance
7 { "message": "Show the last 3 transactions of ACC1001" } getRecentTransactions
8 { "message": "Convert 250 USD to INR" } convertCurrency (external REST API)
9 { "message": "Transfer 500 from ACC1001 to ACC1002" } transferMoney with confirmed=false, so it asks you to confirm and nothing moves
10 { "message": "Yes, I confirm: transfer 500 from ACC1001 to ACC1002" } transferMoney with confirmed=true, so the transfer executes
11 { "message": "Transfer 900000 from ACC1002 to ACC1001, I confirm" } transferMoney, which fails with an insufficient balance message
12 { "message": "Convert the balance of ACC1003 to USD" } getBalance, then convertCurrency in one answer
Scroll to Top