- Ressources
- Cookbooks
Move a Spring AI agent to Mistral Studio
Move a Spring AI agent to Mistral Studio
Move a Spring AI agent to Mistral Studio
Build a conversational agent with Spring AI's ChatClient, publish its tools with an MCP server, then run the same agent in Mistral Studio.
Guillaume Desforges, @GuillaumeDesforges, Mistral
Managed agents and the Mistral Agents SDK (mistralai-agents) are in public preview. Their API and behavior can change during the preview.
You start with an agent inside a Spring Boot backend, then move it to Mistral Studio while keeping its tools.
You write the tools once. What changes from one step to the next is where the agent loop runs: first inside the backend's HTTP request, then in a session that Mistral Studio stores and traces. A configuration property switches between the two, so you can roll back at any time.
The example application
The example application holds a small catalogue of documents, and the agent has two tools: search documents by keyword, and read a document. In your own application, the tools call your business services. The agent answers questions such as "Which documents are about the network?", then "Which one is the latest?", because it remembers the previous question.
The backend exposes the agent through a single route, POST /api/chat. Its contract stays the same in all three steps, so the client that calls it doesn't change:
POST /api/chat
Content-Type: application/json
{"conversationId": null, "message": "Which documents are about the network?"}
200 OK
{"conversationId": "8aef69f6-…", "answer": "Two documents are about the network: …"}
The backend assigns a conversationId to the first message. The client sends it back with the next messages, and the backend uses it to find the conversation's history.
The code has three Maven projects, one per step, in this folder. Each one runs on its own and builds on the previous one:
- step-1-chatclient/: the agent runs in the backend with the ChatClient
- step-2-mcp-server/: the same backend also publishes its tools on an MCP server at /mcp
- step-3-ai-studio/: the agent definition (agent/) and the backend that calls it in Studio (backend/)
You don't type any code. Each step folder is a complete project, ready to run. The snippets in this cookbook show the key parts of these projects, and link to the full files.
Prerequisites
To complete this cookbook, you will need:
- Java 21 and Maven 3.9
- Python 3.12 to 3.14 and uv, for step 3 only
- A Mistral account to create an API key, in a workspace with access to Studio agents for step 3
- Git, curl, and openssl, to get the code, call the backend, and create a token
Environment setup
Set up the code and the environment variables once. Every step reuses them.
Install
Clone the cookbook repository and go to this cookbook's folder, spring_ai_studio_agent. Open every terminal you use in this cookbook in this folder. Each later cd moves from where that terminal is:
git clone https://github.com/mistralai/cookbook.git
cd cookbook/mistral/agents/spring_ai_studio_agent
Maven downloads the Java dependencies on the first build, and uv installs the Mistral Agents SDK in step 3. Check that the tests pass. They need neither an API key nor network access to Mistral:
(cd step-1-chatclient && mvn test)
(cd step-2-mcp-server && mvn test)
(cd step-3-ai-studio/backend && mvn test)
Each project ends with Tests run: …, Failures: 0, Errors: 0 and BUILD SUCCESS.
Required environment variables
To complete this cookbook, you'll need a Mistral API key. In Studio, navigate to the API keys section and create a new API key.
Create a .env at the root of your project, the spring_ai_studio_agent folder, and add your Mistral API key. Steps 2 and 3 also need a token that protects the MCP server, and the header that the agent sends with it:
MISTRAL_API_KEY=your-mistral-api-key
ASSISTANT_MCP_TOKEN=your-mcp-token
DOCUMENTS_MCP_AUTH="Bearer ${ASSISTANT_MCP_TOKEN}"
Replace your-mcp-token with a random value, such as the output of openssl rand -hex 32. Keep the quotes on the last line, because its value contains a space. The cookbook's .gitignore keeps .env out of Git.
Each step loads this file itself, so you don't export anything:
- The Spring Boot projects import it in their application.yml, with spring.config.import.
- check-mcp.sh, in step 2, reads it before it calls the MCP server.
- The agent, in step 3, gets it from uv run --env-file.
A variable set in your shell takes precedence over the file.
Step 1: Create the agent with the ChatClient
In this step, the agent runs inside the Spring backend, during the user's request:
flowchart LR
client[Client] -- "HTTP /api/chat" --> backend
subgraph backend[Spring backend]
api["/api/chat"] --> chatclient["ChatClient: agent loop, history"]
chatclient --> tools["@Tool methods → services"]
end
chatclient -- HTTP --> mistral["Mistral API<br/>Mistral Large 4"]
Spring AI's ChatClient sends the message to the model, with the description of the tools. When the model asks for a tool, the ChatClient runs it and sends the result back. It repeats until the model gives its final answer.
Add the dependencies
The project uses Spring Boot 4.2 and Spring AI 2.1, and the Spring AI BOM sets the versions. It needs three dependencies: the Mistral model and the two session memory modules. See step-1-chatclient/pom.xml for the full file:
<!-- The Mistral chat model behind the ChatClient -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-mistral-ai</artifactId>
</dependency>
<!-- Session memory: the conversation history, keyed by conversation ID -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-session</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-session-advisor</artifactId>
</dependency>
Define the tools
The tools are methods of an ordinary Spring service. The @Tool and @ToolParam annotations describe each method and each parameter to the model. This excerpt leaves out the catalogue's data; see DocumentService.java for the full class:
@Service
public class DocumentService {
public record Document(String id, String title, LocalDate date, List<String> tags, String text) {}
public record DocumentSummary(String id, String title, LocalDate date, List<String> tags) {}
@Tool(name = "search_documents",
description = "Search the documents whose title, text or tags contain a word; returns their IDs, titles, dates and tags")
public List<DocumentSummary> search(@ToolParam(description = "One English word to look for, such as 'network'; the documents are in English") String query) {
String word = query.toLowerCase(Locale.ROOT);
return documents.values().stream()
.filter(d -> (d.title() + " " + d.text() + " " + d.tags()).toLowerCase(Locale.ROOT).contains(word))
.sorted((a, b) -> a.id().compareTo(b.id()))
.map(d -> new DocumentSummary(d.id(), d.title(), d.date(), d.tags()))
.toList();
}
@Tool(name = "get_document", description = "Return a document's full text from its ID, such as DOC-1")
public Document get(@ToolParam(description = "The document's ID") String id) {
Document document = documents.get(id);
if (document == null) {
throw new IllegalArgumentException("No document " + id);
}
return document;
}
}
Keep these points in mind when you write tools:
- The model picks a tool from its name and description. Say when to use it and what it returns.
- Spring AI derives the JSON schema of the parameters from the method's signature. It serializes return values to JSON, records included.
- When a tool throws an exception, the model receives the error message and decides what to do next.
- Expose a few chosen tools rather than whole services. Each tool is an action the model can take on its own.
Create the agent
The rest of the backend sees the agent only through a one-method interface. In step 3, you change its implementation without touching the API:
/** The conversational agent, as the rest of the backend sees it: one answer per user message. */
public interface Assistant {
String reply(String conversationId, String message);
}
The implementation builds the ChatClient once, with the instructions, the tools, and the session memory:
@Component
public class ChatClientAssistant implements Assistant {
static final String INSTRUCTIONS = """
You help users find information in the application's documents.
Search with one or two English keywords, read only the documents you need, then answer.
Never invent a document or its content. Cite the document IDs you used.
Answer in the user's language.""";
private final ChatClient chatClient;
public ChatClientAssistant(ChatClient.Builder builder, DocumentService documents) {
// Demo store: in memory, lost on restart. Use spring-ai-starter-model-session-jdbc in production.
SessionService sessions = DefaultSessionService.builder()
.sessionRepository(InMemorySessionRepository.builder().build())
.build();
this.chatClient = builder
.defaultSystem(INSTRUCTIONS)
.defaultTools(documents) // the @Tool methods
.defaultAdvisors(SessionAdvisors.builder(sessions).build()) // the conversation's history
.build();
}
@Override
public String reply(String conversationId, String message) {
return chatClient.prompt()
.user(message)
.advisors(SessionAdvisors.session(conversationId))
.call()
.content();
}
}
Here's what each part does:
- defaultTools(documents) gives the model every @Tool method of the service. The ChatClient adds the ToolCallingAdvisor itself, which runs the agent loop.
- SessionAdvisors records each exchange in the conversationId session, and sends the history to the model with each message. The session starts with the first message.
- The sessions stay in memory here. They're lost on restart, and each instance has its own. In production, the spring-ai-starter-model-session-jdbc starter stores them in the application's database.
Expose the chat API
The controller only knows the Assistant interface. It creates a conversationId for the first message:
@RestController
@RequestMapping("/api")
public class ChatController {
public record ChatRequest(String conversationId, String message) {}
public record ChatResponse(String conversationId, String answer) {}
private final Assistant assistant;
public ChatController(Assistant assistant) {
this.assistant = assistant;
}
@PostMapping("/chat")
public ChatResponse chat(@RequestBody ChatRequest request) {
String conversationId = request.conversationId() != null
? request.conversationId()
: UUID.randomUUID().toString();
return new ChatResponse(conversationId, assistant.reply(conversationId, request.message()));
}
}
AssistantApplication is a standard @SpringBootApplication class. The configuration imports the .env file, sets the model, and reads the API key:
spring:
application:
name: assistant
config:
# The cookbook's .env file, read as properties; variables set in the shell take precedence.
import: optional:file:../.env[.properties]
ai:
model:
# Only the chat model is used.
embedding: none
moderation: none
ocr: none
mistralai:
api-key: ${MISTRAL_API_KEY}
chat:
options:
model: mistral-large-4
temperature: 0.2
Run the application
In a first terminal, in the spring_ai_studio_agent folder, start the backend. It listens on http://localhost:8080:
cd step-1-chatclient
mvn spring-boot:run
Open a second terminal in the spring_ai_studio_agent folder. Send a first message without a conversationId. Then ask a follow-up question in the same conversation, with the conversationId of the first answer:
curl -s localhost:8080/api/chat -H 'Content-Type: application/json' \
-d '{"message": "Which documents are about the network?"}'
curl -s localhost:8080/api/chat -H 'Content-Type: application/json' \
-d '{"conversationId": "8aef69f6-2520-48e4-a355-41017200d0f1", "message": "Which one is the latest?"}'
Each answer arrives within a few seconds. The model's wording varies from one run to the next:
{
"conversationId": "8aef69f6-2520-48e4-a355-41017200d0f1",
"answer": "Two documents are about the network:\n\n1. **DOC-1 – \"Network maintenance window\"** (2026-11-02, tags: operations, network): the core network is down for maintenance on Saturday from 22:00 to 02:00.\n\n2. **DOC-3 – \"Quarterly network capacity report\"** (2026-11-16, tags: operations, network, report): peak traffic grew by a third over the quarter; two links reach 80% at peak."
}
{
"conversationId": "8aef69f6-2520-48e4-a355-41017200d0f1",
"answer": "**DOC-3** (\"Quarterly network capacity report\"), dated **November 16, 2026**, is the latest, against November 2, 2026 for DOC-1."
}
The second answer builds on the first, because the model received the conversation's history.
Test without a key or network
In ChatClientAssistantTest.java, a scripted model replaces the Mistral API. It first asks for a search_documents call, then answers. The test checks that the tool runs in the process, and that the follow-up question sends the history. Run it from the second terminal:
(cd step-1-chatclient && mvn test)
Step 2: Publish the tools over MCP
In this step, the backend keeps its ChatClient and also publishes its tools on an MCP server:
flowchart LR
client["Client (unchanged)"] -- "HTTP /api/chat" --> backend
subgraph backend[Spring backend]
api["/api/chat"] --> chatclient[ChatClient]
chatclient --> tools["@Tool methods → services"]
mcp["New: MCP server /mcp"] --> tools
end
chatclient -- HTTP --> mistral["Mistral API<br/>Mistral Large 4"]
An agent that runs in Studio can't call the backend's Java methods. It needs an MCP server. The Model Context Protocol (MCP) is the standard protocol an agent uses to discover and call a server's tools. In this step, you add this server to the backend from step 1, on the /mcp route. It uses Streamable HTTP, the current remote transport of MCP.
This step adds one dependency, one configuration class, an authentication filter, and a few lines of YAML. The service and its annotations, the ChatClient agent, and the /api/chat route don't change.
Add the MCP starter
The step 2 pom.xml adds this starter to the one from step 1. For a reactive application, use spring-ai-starter-mcp-server-webflux instead:
<!-- Step 2: the MCP server, on Spring MVC, which publishes the same tools over HTTP -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
Publish the tools
The starter publishes the tools of every ToolCallbackProvider bean over MCP. One bean is enough to publish the service's @Tool methods. MCP clients see the same names, descriptions, and schemas as the ChatClient. The same class protects /mcp with a token, without touching the /api routes:
@Configuration
public class McpToolsConfig {
/** The MCP server starter publishes every ToolCallbackProvider bean as MCP tools. */
@Bean
ToolCallbackProvider documentTools(DocumentService documents) {
return MethodToolCallbackProvider.builder().toolObjects(documents).build();
}
/** Requires the bearer token on /mcp only; the /api routes keep the application's own security. */
@Bean
FilterRegistrationBean<BearerTokenFilter> mcpTokenFilter(@Value("${assistant.mcp.token}") String token) {
var registration = new FilterRegistrationBean<>(new BearerTokenFilter(token));
registration.addUrlPatterns("/mcp", "/mcp/*");
return registration;
}
}
BearerTokenFilter.java rejects any request to /mcp without the expected Authorization: Bearer <token> header.
In production, replace this filter with the application's security, such as Spring Security's OAuth2 resource server, with one client per agent. Each tool call arrives as an ordinary HTTP request. Access controls and @Transactional apply to it as they do to a controller.
Configure the server
The step 2 application.yml adds the spring.ai.mcp.server block, and the token expected on /mcp, read from ASSISTANT_MCP_TOKEN:
spring:
ai:
mcp:
server:
name: documents
version: 0.1.0
type: SYNC
protocol: STREAMABLE # Streamable HTTP, served at /mcp
assistant:
mcp:
token: ${ASSISTANT_MCP_TOKEN}
Check the server
In the first terminal, stop the step 1 backend with Ctrl+C, then start the step 2 backend:
cd ../step-2-mcp-server
mvn spring-boot:run
In the second terminal, still in the spring_ai_studio_agent folder, run check-mcp.sh. The script reads ASSISTANT_MCP_TOKEN from .env and acts as an MCP client: it opens a session, lists the tools, and calls one. It then checks that the server refuses a request without the token:
./step-2-mcp-server/check-mcp.sh
The server returns the two tools, with the descriptions and schemas derived from the annotations, then the search result. This output is abridged:
event:message
data: {"jsonrpc":"2.0","id":2,"result":{"tools":[
{"name":"search_documents","description":"Search the documents whose title, text or tags contain a word; returns their IDs, titles, dates and tags",
"inputSchema":{"type":"object","properties":{"query":{"type":"string","description":"One English word to look for, such as 'network'; the documents are in English"}},"required":["query"], …}},
{"name":"get_document","description":"Return a document's full text from its ID, such as DOC-1", …}]}}
event:message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"[{\"id\":\"DOC-1\",\"title\":\"Network maintenance window\", …},{\"id\":\"DOC-3\",\"title\":\"Quarterly network capacity report\", …}]"}],"isError":false}}
without the token: HTTP 401
Nothing changes on /api/chat. The ChatClient still calls the methods directly, without going through MCP.
Test the MCP server
McpServerTest.java starts the application, then calls the tools with the MCP Java client, with and without the right token. Run it from the second terminal:
(cd step-2-mcp-server && mvn test)
Follow good practices for MCP tools
Keep these rules in mind when you publish tools for remote agents:
- One tool per atomic operation. Each tool call has its own request and its own transaction. An operation that must be atomic must fit in a single tool.
- Idempotent tools. Studio doesn't replay a tool call that a failure interrupted. A tool with side effects can still run twice. Write it so that a second run has no effect.
- @Tool rather than @McpTool. @Tool serves both the ChatClient and the MCP server, and the service doesn't depend on MCP. Keep @McpTool for tools that need MCP-specific features, such as the request context.
Step 3: Run the agent in Studio
In this step, the backend calls the agent in Studio, and the agent calls back the backend's tools over MCP:
flowchart LR
client["Client (unchanged)"] -- "HTTP /api/chat" --> backend
subgraph backend[Spring backend]
api["/api/chat"] --> studioclient["New: agent client"]
mcp["MCP server /mcp"] --> tools["@Tool methods → services"]
end
subgraph studio[Mistral Studio]
agent["Agent documents-assistant<br/>durable sessions, traces<br/>Mistral Large 4"]
end
studioclient -- "sessions API" --> agent
agent -- MCP --> mcp
An HTTP request is a poor fit for long tasks, for tasks that chain many tool calls, and for tasks that must survive a restart. In Studio, you define the agent once: its model, its instructions, and its tools. Each conversation becomes a session that Mistral stores, and each call to the model or to a tool is traced in it. A turn that a failure interrupts usually resumes from its last completed step.
You define the agent in Python with the Mistral Agents SDK. It runs in a worker, either on your machines with agents serve, or on Mistral's infrastructure with agents deploy. The agent calls the tools through the MCP server from step 2. The Java backend calls the agent as a service: it opens a session, sends the message, and reads the answer.
This step adds a small Python project that defines the agent, a Java class that calls it, and a property that picks between the ChatClient and the Studio agent. The service and its tools, the MCP server, and the /api/chat route don't change.
Define the agent
The agent's project has two files, in an agent/ folder next to the backend. pyproject.toml pins the SDK and names the entry point:
[project]
name = "documents-assistant"
version = "0.1.0"
requires-python = ">=3.12,<3.15"
dependencies = ["mistralai-agents==1.1.3"]
[tool.uv]
package = false
[tool.mistralai.agents]
entrypoint = "main:agent"
main.py defines the agent:
import os
from mistralai import agents
agent = agents.Agent(
name="documents-assistant",
model="mistral-large-4",
instructions=(
"You help users find information in the application's documents. "
"Search with one or two English keywords, read only the documents you need, then answer. "
"Never invent a document or its content. Cite the document IDs you used. "
"Answer in the user's language."
),
mcps={
"documents": agents.RemoteMCP(
# The backend's MCP server, as the worker that runs the agent reaches it.
url=os.environ.get("DOCUMENTS_MCP_URL", "http://localhost:8080/mcp"),
namespace="documents",
# The NAME of the environment variable that holds "Bearer <token>", never the token itself.
auth_header_env_vars={"Authorization": "DOCUMENTS_MCP_AUTH"},
)
},
)
Here's what each part does:
- The instructions are the same as the ChatClient's, so that the agent behaves the same way.
- RemoteMCP declares the backend's MCP server. The worker connects to it, so the worker must be able to reach this address.
- auth_header_env_vars gives the name of the environment variable that holds the Authorization header. The token never appears in the code.
Try the agent locally
Keep the step 2 backend running in the first terminal. In the second terminal, go to the agent's folder. --env-file ../../.env passes the .env file to the agent, including MISTRAL_API_KEY and DOCUMENTS_MCP_AUTH. agents info checks the agent's definition and reports missing variables. agents chat then runs the agent locally, and the agent reaches the MCP server on localhost:
cd step-3-ai-studio/agent
uv run --env-file ../../.env agents info
uv run --env-file ../../.env agents chat -m "Which documents are about the network?"
The output shows the tool calls, then the answer:
→ documents.search_documents {"query": "network"}
← documents.search_documents done
→ documents.get_document {"id": "DOC-1"}
→ documents.get_document {"id": "DOC-3"}
← documents.get_document done
← documents.get_document done
Two documents are about the network:
1. **DOC-1 — "Network maintenance window"** (November 2, 2026, tags: operations, network)
- The core network is down for maintenance on Saturday from 22:00 to 02:00.
2. **DOC-3 — "Quarterly network capacity report"** (November 16, 2026, tags: operations, network, report)
- Peak traffic grew by a third over the quarter; two links reach 80% at peak.
**Documents cited: DOC-1, DOC-3**
Serve the agent with agents serve
agents serve starts a worker on your machine and registers the agent in your Studio workspace. Mistral stores the sessions, serves the model, and traces each turn. The worker runs the agent loop and the MCP calls from your network, so the MCP server can stay internal. Start it in the second terminal, still in step-3-ai-studio/agent:
uv run --env-file ../../.env agents serve
# ✓ Agent documents-assistant is serving on agents-sdk-documents-assistant
# Debug: https://console.mistral.ai/managed-agents/<agent id>/sessions
In the Studio console, you see the agent, its sessions, and the details of each turn's calls.
Call the agent from the backend
On the Java side, a new implementation of Assistant replaces the ChatClient. It opens a Studio session per conversation, and starts a turn per message. This excerpt shows how it starts a turn; see StudioAssistant.java for the full class, including how it reads the answer:
@Component
@ConditionalOnProperty(name = "assistant.mode", havingValue = "studio")
public class StudioAssistant implements Assistant {
/** Where a conversation stands in Studio: its session, and how far its events were read. */
private record Conversation(String sessionId, String cursor) {}
// ...
@Override
public String reply(String conversationId, String message) {
List<Map<String, String>> content = List.of(Map.of("type", "text", "text", message));
Conversation conversation = conversations.get(conversationId);
String turnId;
if (conversation == null) {
// First message: open a session on the agent, with this message as its first turn.
JsonNode started = http.post().uri("/sessions")
.body(Map.of(
"idempotency_key", UUID.randomUUID().toString(),
"agent_name", agentName,
"session_protocol", "session_v1",
"initial_turn", Map.of("message", content)))
.retrieve().body(JsonNode.class);
conversation = new Conversation(started.at("/agent_session/agent_session_id").asString(), null);
turnId = started.at("/initial_turn/id").asString();
} else {
// Next messages: a new turn in the same session; Studio keeps the history.
JsonNode turn = http.post().uri("/sessions/{id}/turn/start", conversation.sessionId())
.body(Map.of(
"idempotency_key", UUID.randomUUID().toString(),
"source", "agents_sdk",
"message", content))
.retrieve().body(JsonNode.class);
turnId = turn.at("/turn/id").asString();
}
return awaitAnswer(conversationId, conversation, turnId);
}
}
The class calls three routes of the Mistral API, under https://api.mistral.ai/v2/agents:
Route | Purpose |
|---|---|
| POST /sessions | Opens a session with the named agent, and starts its first turn with the user's message. Returns the session ID and the turn ID. |
| POST /sessions/{id}/turn/start | Starts a new turn in an existing session: the follow-up question. Studio gives the history to the model itself. |
| GET /sessions/{id}/events/history | Reads the session's events from a cursor. The turn's turn_terminated event holds the final answer in termination.output. |
These are the routes that the Mistral Agents SDK for Python 1.1.3 calls. If they change, only this class needs updating.
Keep the ChatClient implementation during the transition. An annotation makes each implementation conditional, and the assistant.mode property picks which one to load:
/** The agent runs inside the backend: Spring AI's ChatClient calls the model and the tools within the request. */
@Component
@ConditionalOnProperty(name = "assistant.mode", havingValue = "chat-client", matchIfMissing = true)
public class ChatClientAssistant implements Assistant {
The configuration adds assistant.mode, read from ASSISTANT_MODE, and the agent's name:
assistant:
mcp:
token: ${ASSISTANT_MCP_TOKEN}
# Step 3: chat-client runs the agent in this backend; studio calls the agent in Mistral Studio.
mode: ${ASSISTANT_MODE:chat-client}
studio:
agent-name: documents-assistant
The pom.xml adds Spring's HTTP client:
<!-- Step 3: the HTTP client that calls the agent in Mistral Studio -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
Run the backend and the agent
Keep the worker running in the second terminal. In the first terminal, stop the step 2 backend with Ctrl+C, then start the step 3 backend in studio mode. It serves the same MCP server on the same port, so the worker reaches the tools again:
cd ../step-3-ai-studio/backend
ASSISTANT_MODE=studio mvn spring-boot:run
Open a third terminal in the spring_ai_studio_agent folder, and send the same requests as in step 1:
curl -s localhost:8080/api/chat -H 'Content-Type: application/json' \
-d '{"message": "Which documents are about the network?"}'
curl -s localhost:8080/api/chat -H 'Content-Type: application/json' \
-d '{"conversationId": "2864b6a7-312d-4295-8b8d-3a88d69b4f5f", "message": "Which one is the latest?"}'
The answers have the same shape as in step 1, and the model's wording varies from one run to the next:
{
"conversationId": "2864b6a7-312d-4295-8b8d-3a88d69b4f5f",
"answer": "Two documents are about the network:\n\n**1. DOC-1 — \"Network maintenance window\"** (November 2, 2026)\n- Tags: `operations`, `network`\n- Content: \"The core network is down for maintenance on Saturday from 22:00 to 02:00.\"\n\n**2. DOC-3 — \"Quarterly network capacity report\"** (November 16, 2026)\n- Tags: `operations`, `network`, `report`\n- Content: \"Peak traffic grew by a third over the quarter; two links reach 80% at peak.\""
}
{
"conversationId": "2864b6a7-312d-4295-8b8d-3a88d69b4f5f",
"answer": "**DOC-3 \"Quarterly network capacity report\"**, dated **November 16, 2026**, is the latest, against November 2, 2026 for DOC-1 (\"Network maintenance window\")."
}
The first answer took about a minute, including the session's creation, the discovery of the MCP tools, and the tool calls. The follow-up question took about ten seconds. To go back to the behavior of step 1, restart the backend with ASSISTANT_MODE=chat-client.
Test without network
In StudioAssistantTest.java, a mock server replays Studio's responses. It opens a session with a first turn, then serves a second turn in the same session. The test reads the second turn from the first one's cursor. Run it from the third terminal:
(cd step-3-ai-studio/backend && mvn test)
Deploy the agent with agents deploy
With agents deploy, Mistral builds an image of the agent's project and runs it on its infrastructure. The worker then runs on Mistral's side, and must reach the MCP server from the internet, over HTTPS. To set this up:
1.
Publish /mcp at a public HTTPS address, behind the application's gateway or reverse proxy. Protect it with a token or OAuth2, and open only this route.2.
Pass this address to RemoteMCP through the DOCUMENTS_MCP_URL variable, in place of the default http://localhost:8080/mcp.3.
In Studio, store Bearer <token> as a workspace secret named documents-mcp-auth, and bind it to the variable that RemoteMCP reads.
agents deploy builds the version pushed to the Git repository, not your local files. Work from a repository you can push to, such as your fork of this one. In the second terminal, stop the worker with Ctrl+C. Still in step-3-ai-studio/agent, commit and push the agent's project, then deploy it:
git add pyproject.toml uv.lock main.py
git commit -m "Deploy the documents assistant"
git push
uv run --env-file ../../.env agents deploy --secret-binding DOCUMENTS_MCP_AUTH=secret:workspace:documents-mcp-auth
uv run --env-file ../../.env agents logs documents-assistant --follow
The backend doesn't change, because it calls the agent by name.
To try it from your machine, a temporary tunnel such as cloudflared tunnel --url http://localhost:8080 can serve as the public address. Close it right after. If the MCP server must not be exposed, run agents serve on a server inside the application's network instead. The MCP calls then stay in that network.
Clean up
Stop the backend and the worker with Ctrl+C, and close the tunnel if you opened one. agents shutdown doesn't stop a local worker, so stop it first.
Then delete the agent from Studio. In the second terminal, still in step-3-ai-studio/agent, run agents shutdown. It asks for confirmation, shuts the agent down permanently in your workspace, and deletes the deployment that agents deploy created:
uv run --env-file ../../.env agents shutdown documents-assistant
If you created the documents-mcp-auth workspace secret, delete it in Studio too.
Next steps
These changes take the example further toward production:
- Long tasks. The session goes on in Studio even when the backend stops waiting. For a long task, return the turn ID right away, and let the client ask for the answer later, from any backend instance.
- Mapping conversations to sessions. The example keeps this mapping in memory. In production, store it in the application's database, with the read cursor.
- Identity. Here, the MCP server recognizes the agent by its token, and the agent acts with a service identity. For the agent to act on the user's behalf, pass the user's identity through to the tool call.
- Approvals. A Mistral Agents SDK permission policy can require an approval before some tool calls. The turn then waits for the decision, even when the application is closed.
- Removing the ChatClient. Once every use case runs in Studio, delete ChatClientAssistant, the session memory, and the assistant.mode property. The backend keeps the MCP server and the agent client.
Sources
This cookbook relies on the following documentation.
Spring AI 2.1:
Mistral:
- Agents overview
- Connectors and MCP
- Sessions
- Session and Turn reference
- Where agents run
- agents serve
- agents deploy
- Mistral Large 4
- mistralai-agents on PyPI
MCP:
Summary
This cookbook moved a conversational agent from Spring AI's ChatClient, inside a Spring Boot backend, to an agent that runs in Mistral Studio, without rewriting its tools or changing the backend's chat API.
What you built:
- A Spring Boot backend with an agent built on the ChatClient, @Tool methods, and session memory, behind POST /api/chat
- An MCP server in the same backend that publishes the same tools over Streamable HTTP, behind a bearer token
- An agent defined with the Mistral Agents SDK, served with agents serve, that calls the tools over MCP
- A backend client that opens a Studio session per conversation, selected by the assistant.mode property
Mistral features used:
- Mistral Large 4, through the chat completions API in Spring AI
- Studio agents and sessions
- Mistral Agents SDK (mistralai-agents), with RemoteMCP, agents chat, agents serve, and agents deploy
Other services:
- Spring AI and its MCP server starter
- The MCP Java SDK
Read more about agents in the Mistral documentation.