What this article covers#
How the agent concepts from Module 3 map to Spring AI 2.0 code:
| Concept | Spring AI |
|---|---|
| Tool | @Tool method, ToolCallback |
| Identity passed to tools | ToolContext |
| Agent loop | Built-in tool execution in ChatClient, or ToolCallingAdvisor |
| MCP client | spring-ai-starter-mcp-client → tools as ToolCallbackProvider |
| MCP server | spring-ai-starter-mcp-server-webmvc + @McpTool |
| Short-term memory | ChatMemory + MessageChatMemoryAdvisor |
| Persistent memory | JdbcChatMemoryRepository (and Redis, Cassandra, Mongo, Neo4j) |
Tools with @Tool#
@Component
class OrderTools {
private final OrderService orders;
OrderTools(OrderService orders) { this.orders = orders; }
@Tool(description = """
Get status, items and delivery estimate of one of the current customer's orders.
Use when the customer asks where an order is. Order numbers look like A-12345.""")
OrderView getOrder(@ToolParam(description = "Order number, e.g. A-12345") String orderId,
ToolContext ctx) {
String customerId = (String) ctx.getContext().get("customerId"); // from session, not the model
return orders.findForCustomer(orderId, customerId)
.orElseThrow(() -> new ToolException("Order not found for this customer"));
}
@Tool(description = "Refund an order of the current customer. Amount in EUR.")
RefundResult refund(String orderId, BigDecimal amount, String reason, ToolContext ctx) {
String customerId = (String) ctx.getContext().get("customerId");
return orders.requestRefund(orderId, customerId, amount, reason); // limits enforced here
}
}
String reply = chatClient.prompt()
.user(customerMessage)
.tools(orderTools)
.toolContext(Map.of("customerId", authenticatedCustomerId))
.call()
.content();
- Spring AI generates JSON Schemas from method signatures;
@ToolParamadds descriptions and required flags. ToolContextpasses data to the tool without sending it to the model — use it for identity, tenant and correlation IDs.returnDirect = trueon@Toolreturns the result to the caller without another model round trip.- Exceptions can be converted into messages for the model so it can recover; keep them short and helpful. (
ToolExceptionabove stands for your own exception type.) - Enforce business limits in
OrderService, not in the prompt.
The tool-calling loop#
sequenceDiagram
participant App as Your code
participant CC as ChatClient
participant LLM as ChatModel
participant T as OrderTools
App->>CC: prompt + tools + toolContext
CC->>LLM: messages + tool definitions
LLM-->>CC: tool call getOrder(A-10293)
CC->>T: getOrder("A-10293", ctx)
T-->>CC: OrderView
CC->>LLM: messages + tool result
LLM-->>CC: final text
CC-->>App: content
By default the tool loop runs inside the model call. In Spring AI 2.0 you can instead add ToolCallingAdvisor, which runs the loop inside the advisor chain, so other advisors (logging, memory, guardrails, auditing) see every iteration — useful for agent observability and per-step policy checks.
Consuming MCP servers (MCP client)#
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
spring.ai.mcp.client.streamable-http.connections.tickets.url=https://mcp-gateway.internal/tickets
spring.ai.mcp.client.streamable-http.connections.crm.url=https://mcp-gateway.internal/crm
The auto-configuration connects to each server, lists its tools and exposes them as a ToolCallbackProvider:
@Bean
ChatClient supportAgent(ChatClient.Builder builder, ToolCallbackProvider mcpTools) {
return builder
.defaultSystem("You are ACME's support agent. Use tools to look up facts; never guess.")
.defaultToolCallbacks(mcpTools)
.build();
}
Local stdio servers are configured under spring.ai.mcp.client.stdio. Authentication to remote servers is configured on the HTTP transport (for example OAuth2 client credentials or token exchange through Spring Security).
Exposing an MCP server#
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
spring.ai.mcp.server.name=orders-mcp
spring.ai.mcp.server.version=1.0.0
spring.ai.mcp.server.protocol=STREAMABLE
@Component
class OrderMcpTools {
private final OrderService orders;
OrderMcpTools(OrderService orders) { this.orders = orders; }
@McpTool(name = "get_order_status",
description = "Status and delivery estimate of an order. Order numbers look like A-12345.",
annotations = @McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false))
OrderView getOrderStatus(
@McpToolParam(description = "Order number", required = true) String orderId) {
return orders.findForCurrentUser(orderId); // user from the validated OAuth token
}
}
flowchart LR
H["MCP hosts<br/>copilot, IDE, agents"] -->|"Streamable HTTP + OAuth"| GW["MCP gateway"]
GW --> S["orders-mcp<br/>Spring Boot + spring-ai-starter-mcp-server-webmvc<br/>Spring Security resource server"]
S --> SVC["OrderService<br/>business rules, limits"]
SVC --> DB[("Orders DB")]
protocol=STREAMABLEgives the Streamable HTTP transport;STATELESSsuits horizontally scaled servers without session state; the older SSE transport is deprecated in 2.0.- Secure it as an OAuth2 resource server with Spring Security; validate audience and scopes; derive the user from the token.
- Annotations also exist for resources (
@McpResource), prompts (@McpPrompt) and completions.
Chat memory#
@Bean
ChatMemory chatMemory(JdbcChatMemoryRepository repository) {
return MessageWindowChatMemory.builder()
.chatMemoryRepository(repository) // persisted in PostgreSQL
.maxMessages(20)
.build();
}
@Bean
ChatClient assistant(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
String reply = assistant.prompt()
.user(message)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId)) // required
.call()
.content();
MessageWindowChatMemorykeeps the last N messages (a sliding window).- Repositories: in-memory (default), JDBC (
spring-ai-starter-model-chat-memory-repository-jdbc), Redis, Cassandra, MongoDB, Neo4j. ChatMemory.CONVERSATION_IDis required on every call; derive it from your session and validate the user owns it.- For long conversations add summarisation (a custom advisor) — see memory strategies.
VectorStoreChatMemoryAdvisorretrieves relevant past messages semantically instead of the last N.
Human approval for risky tools#
Spring AI executes tools you register, so put approval in the tool or service:
flowchart LR
T["@Tool refund()"] --> S{"amount ≤ €100?"}
S -->|"yes"| P["Execute refund<br/>idempotency key"]
S -->|"no"| A["Create approval task<br/>status PENDING_APPROVAL"]
A --> R["Return 'pending approval'<br/>to the model"]
H["Supervisor approves<br/>in back-office UI"] --> P
For long waits, persist state (conversation + pending action) and resume when the approval event arrives, rather than holding the HTTP request.
Putting it together: a small support agent#
@Service
class SupportAgent {
private final ChatClient chatClient;
SupportAgent(ChatClient.Builder builder, ChatMemory memory, OrderTools orderTools,
ToolCallbackProvider mcpTools, Advisor ragAdvisor) {
this.chatClient = builder
.defaultSystem("""
You are ACME's customer-support agent.
- Use tools for facts about orders; never invent order data.
- Follow the returns policy in the retrieved context.
- Refunds above 100 EUR need approval; tell the customer it is pending.
- If the customer is upset or mentions legal action, call escalate_to_human.
""")
.defaultTools(orderTools)
.defaultToolCallbacks(mcpTools)
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(memory).build(),
ragAdvisor, // policy RAG
new SimpleLoggerAdvisor())
.build();
}
String handle(String conversationId, String customerId, String message) {
return chatClient.prompt()
.user(message)
.toolContext(Map.of("customerId", customerId))
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();
}
}
Add: timeouts and retries on the model client, a step limit, observability (next article), and evaluation tests.
Common mistakes#
Review questions#
How do you define tools in Spring AI?
Annotate methods with @Tool (and parameters with @ToolParam), then pass the object with .tools(...) or defaultTools(...). Spring AI generates schemas, executes calls the model requests and feeds results back. ToolContext passes non-model data such as user identity.
How does a Spring AI application use MCP servers?
Add the MCP client starter and configure connections (stdio or Streamable HTTP). The auto-configuration exposes all server tools as a ToolCallbackProvider, which you register on a ChatClient with defaultToolCallbacks.
How do you build an MCP server with Spring Boot?
Add the MCP server WebMVC or WebFlux starter, set name, version and protocol=STREAMABLE, and annotate methods with @McpTool / @McpToolParam (plus @McpResource, @McpPrompt). Secure it as an OAuth2 resource server.
How does Spring AI handle conversation memory?
ChatMemory (for example MessageWindowChatMemory) backed by a ChatMemoryRepository such as JDBC, used via MessageChatMemoryAdvisor; every call passes ChatMemory.CONVERSATION_ID.
Summary#
@Tool+ToolContextfor safe in-process tools; enforce limits in services.- MCP client starter turns remote MCP servers into tool callbacks; MCP server starter +
@McpToolexposes your services. ChatMemory+ repositories +MessageChatMemoryAdvisorfor conversation state.- Approval and long waits belong in services with persisted state.
References#
- Spring AI, Tool Calling.
- Spring AI, MCP Client Boot Starter and MCP Server Boot Starter.
- Spring AI, Chat Memory.