☕️ Java in the AI Era 🤖 - part 6: MCP
More human than human is our motto. ©Eldon Tyrell
🇫🇷 Vous trouverez la version française de cet article ici 🇫🇷.
TL;DR
🔌 Sixth article of the series about AI in your Java applications ☕️, this time dedicated to MCP (Model Context Protocol).
🤷 With function calling, each application codes its own tools. MCP lets it fetch them, at runtime, from a server that exposes them.
🧠 The principle: the MCP client asks the server for its list of tools, describes them to the model as plain functions, then has the server run the call the model asks for.
⚠️ OVHcloud's MCP server exposes 471 tools, some of which delete things: choosing what the model is allowed to see is the client's responsibility.
☕️ The same use case is implemented from the lowest level to the highest: Bash, plain Java, the OpenAI and MCP SDKs, LangChain4j, Quarkus and Spring AI.
🐙 All the examples use OVHcloud's AI Endpoints and MCP server, and are available here.
📜 Introduction
A quick recap of the previous episodes: this article is part of a series meant to explain how to integrate AI into the applications we develop in Java ☕️. After the basics (part 1), memory (part 2 and part 3), RAG (part 4) and function calling (part 5), let's continue with what was announced at the end of the previous article: MCP.
🤷 But why MCP?
In part 5, we gave the model the ability to ask for the execution of a get_room_capacity function.
It works very well, but the function, its description and its execution are coded inside our application.
Now let's imagine we want to give our chatbot access to the OVHcloud API: listing your servers, your domains, your databases, ... We would have to write and describe one function per API call, then do it all again in the next application, and in the one after that 😩. And every service provider would do the same on their own, with their own format.
That's the problem the Model Context Protocol (MCP) solves: a standard protocol for a server to expose tools, and for any application, the client, to discover and use them. The tools are written once, by the people who know the service, and any MCP-compatible application can use them.
ℹ️ MCP isn't limited to tools: a server can also expose resources (data to read) and prompts. In this article, we only look at tools, which is by far the most common use.
For this article, we're going to use OVHcloud's MCP server, which exposes the OVHcloud API as tools, and ask it a simple question: in which locations can I deploy a Hosted Private Cloud?
🔑 To run the examples, on top of the AI Endpoints token, you'll need an access token for the MCP server.
🔎 How does MCP work?
First important thing to understand: the model doesn't know what MCP is ⚠️. It never talks to the MCP server, and nothing in the request it receives says that a tool comes from an MCP server. For the model, it's function calling, exactly as in part 5.
All the work is done by our application, the MCP client:
- it opens a session with the MCP server
- it asks for the list of its tools (
tools/list) - it picks the ones it wants to offer the model and describes them to it, as functions
- when the model asks for a call, it forwards it to the MCP server (
tools/call) - it sends the result back to the model, which writes its answer
Steps 3 to 5 are the ones from part 5, only the execution of the tool moves: it happens on the MCP server, no longer in our code.
📡 The protocol
MCP is built on JSON-RPC 2.0: each message is a JSON document with a method (method), parameters (params) and an identifier (id) used to match the response with the request.
For a remote server like OVHcloud's, these messages travel over HTTP, with the Streamable HTTP transport: a simple POST per message.
It all starts with a handshake, described in the specification:
- the client sends an
initializerequest, with the protocol version it speaks and its capabilities - the server answers, and gives it a session identifier in the
Mcp-Session-IdHTTP header, which the client then has to repeat on all its requests - the client confirms with a
notifications/initializednotification (a notification has noid: no answer expected)
// ➡️ POST https://mcp.eu.ovhcloud.com/mcp
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": { "name": "bash-mcp-client", "version": "1.0.0" }
}
}
// ⬅️ Mcp-Session-Id: <session id>
// ➡️ POST https://mcp.eu.ovhcloud.com/mcp (avec l'en-tête Mcp-Session-Id)
{ "jsonrpc": "2.0", "method": "notifications/initialized" }
Next, we can ask for the list of tools with tools/list.
Each tool is described by a name, a description and a JSON Schema of its parameters (inputSchema).
{
"name": "list-dedicatedcloud-locations",
"description": "List hosting locations",
"inputSchema": {
"properties": {},
"type": "object"
}
}
No parameter, a minimalist description: we'll see that the model is perfectly happy with it.
Finally, to run a tool, we use tools/call with its name and its arguments:
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": { "name": "list-dedicatedcloud-locations", "arguments": {} }
}
The server answers with a list of content blocks (content), here a single text block containing the result of the call to the OVHcloud API.
🧰 471 tools 😱
When running our tools/list, a little surprise: OVHcloud's MCP server exposes 471 tools, roughly 350 KB of JSON Schema.
And not all of them just read: a bit fewer than 200 modify something, 54 of which start with delete- 💥.
Giving all these tools to the model would be a very bad idea:
- the cost 💸: as seen in part 5, the description of each tool is sent with every call to the model, 350 KB of description for every question, neither the bill nor the context window would like it
- the quality 🎯: the more tools there are, the more likely the model is to pick the wrong one
- the security ⚠️: the model could decide, on its own, to call a tool that deletes a resource from your account
⚠️ The server exposes what it can do, it's up to the client to choose what the model is allowed to see and call. In all the examples, we keep only one tool:
list-dedicatedcloud-locations, which only reads.
🖥️ The basics: Bash
As in the previous articles, we start with curl and jq, to clearly see what goes through, here between three actors: our script, the MCP server and the model.
#!/usr/bin/env bash
#
# MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b).
#
# The tool offered to the model is not written here: it is discovered at runtime
# on the OVHcloud MCP server, over JSON-RPC. The script hands its schema to the
# model as an ordinary function, then runs the call the model asks for by sending
# it back to the MCP server. Needs curl and jq.
#
# Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
# Docs: https://labs.ovhcloud.com/en/mcp-server/
# Docs: https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle
set -a
source "$(dirname "$0")/../.env"
set +a
MCP_SERVER="https://mcp.eu.ovhcloud.com/mcp"
ENDPOINT="https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/chat/completions"
MODEL="gpt-oss-120b"
QUESTION="In which locations can I deploy a Hosted Private Cloud?"
# The server advertises hundreds of tools, many of them destructive. Choosing the
# ones the model gets to see is the job of the client, not of the server.
TOOL="list-dedicatedcloud-locations"
# 1) Handshake. The session id comes back in a response header, and has to be
# repeated on every request made afterwards.
SESSION_ID=$(curl -s -D - -o /dev/null -X POST "$MCP_SERVER" \
-H "Authorization: Bearer ${OVH_MCP_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": { "name": "bash-mcp-client", "version": "1.0.0" }
}
}' \
| grep -i '^mcp-session-id:' | tr -d '\r' | cut -d' ' -f2)
if [ -z "$SESSION_ID" ]; then
echo "No session id returned by the MCP server: check OVH_MCP_ACCESS_TOKEN." >&2
exit 1
fi
# Every JSON-RPC message sent after the handshake goes through here.
mcp() {
curl -s -X POST "$MCP_SERVER" \
-H "Authorization: Bearer ${OVH_MCP_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: ${SESSION_ID}" \
-d "$1"
}
# The notification closing the handshake. It carries no id, so there is no answer.
mcp '{ "jsonrpc": "2.0", "method": "notifications/initialized" }' > /dev/null
echo "===== 🔌 MCP SESSION 🔌 ====="
echo "$MCP_SERVER"
echo
# 2) Ask the server what it can do, and keep one tool out of the lot. An MCP tool
# already describes its parameters as a JSON schema, so the description only
# has to be wrapped in the envelope the chat API expects.
TOOLS_LIST=$(mcp '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }')
TOOLS=$(echo "$TOOLS_LIST" | jq --arg name "$TOOL" '[
.result.tools[]
| select(.name == $name)
| {
type: "function",
function: { name: .name, description: .description, parameters: .inputSchema }
}
]')
echo "===== 🧰 MCP TOOLS 🧰 ====="
echo "$(echo "$TOOLS_LIST" | jq '.result.tools | length') tools advertised by the server," \
"$(echo "$TOOLS" | jq 'length') passed to the model"
echo "$TOOLS" | jq .
echo
MESSAGES=$(jq -n --arg content "$QUESTION" '[
{ role: "system", content: "provide a concise answer" },
{ role: "user", content: $content }
]')
# Sends the conversation, along with the tools available, and prints the response.
chat() {
jq -n --arg model "$MODEL" --argjson messages "$MESSAGES" --argjson tools "$TOOLS" '{
model: $model,
messages: $messages,
tools: $tools
}' | curl -s "$ENDPOINT" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OVH_AI_ENDPOINTS_ACCESS_TOKEN}" \
-d @-
}
# 3) First call: the question, and the tool as the model sees it. Nothing in the
# request says that it comes from an MCP server.
echo "===== ⬆️ JSON REQUEST (question + tools sent to the model) ⬆️ ====="
echo "$MESSAGES" | jq --argjson tools "$TOOLS" '{ messages: ., tools: $tools }'
echo
RESPONSE=$(chat)
echo "===== ⬇️ JSON RESPONSE ⬇️ ====="
echo "$RESPONSE" | jq .
echo
ASSISTANT_MESSAGE=$(echo "$RESPONSE" | jq '.choices[0].message')
TOOL_CALL=$(echo "$ASSISTANT_MESSAGE" | jq -c '.tool_calls[0] // empty')
# Asking for a tool is a choice of the model, not an obligation: without a tool
# call its message already holds the answer and there is nothing to run.
if [ -z "$TOOL_CALL" ]; then
echo "===== 🤖 ANSWER 🤖 ====="
echo "$ASSISTANT_MESSAGE" | jq -r '.content'
exit 0
fi
TOOL_CALL_ID=$(echo "$TOOL_CALL" | jq -r '.id')
FUNCTION_NAME=$(echo "$TOOL_CALL" | jq -r '.function.name')
# A tool without parameters can come back with empty arguments.
ARGUMENTS=$(echo "$TOOL_CALL" | jq -r '.function.arguments // "{}"')
ARGUMENTS=${ARGUMENTS:-"{}"}
echo "===== 🛠️ TOOL CALL (requested by the model) 🛠️ ====="
echo "$FUNCTION_NAME $ARGUMENTS"
echo
# 4) Run the tool, this time on the MCP server. The name is checked first: only
# the tool handed to the model is allowed to be called.
if [ "$FUNCTION_NAME" != "$TOOL" ]; then
echo "Unexpected tool requested by the model: $FUNCTION_NAME" >&2
exit 1
fi
CALL=$(jq -nc --arg name "$FUNCTION_NAME" --argjson arguments "$ARGUMENTS" '{
jsonrpc: "2.0",
id: 3,
method: "tools/call",
params: { name: $name, arguments: $arguments }
}')
RESULT=$(mcp "$CALL" | jq -r '.result.content[0].text')
echo "===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ ====="
echo "$RESULT"
echo
# 5) Second call: the conversation so far, plus the tool call of the model and
# its result, tied together by the tool call id.
MESSAGES=$(echo "$MESSAGES" | jq \
--argjson assistant "$ASSISTANT_MESSAGE" \
--arg id "$TOOL_CALL_ID" \
--arg result "$RESULT" \
'. + [ $assistant, { role: "tool", tool_call_id: $id, content: $result } ]')
echo "===== ⬆️ JSON REQUEST (tool call + tool result sent to the model) ⬆️ ====="
echo "$MESSAGES" | jq '{ messages: . }'
echo
RESPONSE=$(chat)
echo "===== 🤖 ANSWER 🤖 ====="
echo "$RESPONSE" | jq -r '.choices[0].message.content'
- line 25: the only tool we're going to offer the model
- lines 29 to 43: the handshake, the
initializerequest. From the response, we only keep theMcp-Session-Idheader - lines 51 to 58: sending a message to the MCP server, with the token and the session identifier
- line 61: the notification that ends the handshake
- line 70: the request for the list of tools
- lines 72 to 79: we keep only our tool, and wrap it in the format expected by the chat API: the MCP
inputSchemadirectly becomes theparametersof the function - line 110: the first call to the model, as in part 5
- lines 129 to 131: a tool without parameters can come back with empty arguments, we replace them with an empty object
- lines 139 to 142: we check that the model asks for the tool we offered it
- lines 144 to 151: the tool call, this time on the MCP server with
tools/call, from which we extract the text of the result - lines 159 to 163: adding the call request and the result to the conversation
- line 169: the second call to the model
And here is the result:
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com/mcp
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
[
{
"type": "function",
"function": {
"name": "list-dedicatedcloud-locations",
"description": "List hosting locations",
"parameters": {
"properties": {},
"type": "object"
}
}
}
]
===== ⬆️ JSON REQUEST (question + tools sent to the model) ⬆️ =====
{
"messages": [
{
"role": "system",
"content": "provide a concise answer"
},
{
"role": "user",
"content": "In which locations can I deploy a Hosted Private Cloud?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "list-dedicatedcloud-locations",
"description": "List hosting locations",
"parameters": {
"properties": {},
"type": "object"
}
}
}
]
}
===== ⬇️ JSON RESPONSE ⬇️ =====
{
"id": "chatcmpl-b89ea51054551414",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"reasoning": "The user asks: \"In which locations can I deploy a Hosted Private Cloud?\" This refers likely to the provider's dedicated cloud offering. The tool list-dedicatedcloud-locations can give that info. So we need to call it.",
"tool_calls": [
{
"id": "chatcmpl-tool-9bc1f854691ce351",
"type": "function",
"function": {
"name": "list-dedicatedcloud-locations",
"arguments": "{}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"created": 1796194489,
"model": "gpt-oss-120b",
"object": "chat.completion",
"usage": {
"prompt_tokens": 134,
"completion_tokens": 73,
"total_tokens": 207,
"completion_tokens_details": {
"reasoning_tokens": 49
}
}
}
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location
Status: 200
Response:
["rbx2a","sbg1a","rbx2b","rbx2c","pop1a","lim1c","waw1c","sbg1c","eri1c","par1c","sbg1d","rbx2d","hdf1a","rbx3a"]
===== ⬆️ JSON REQUEST (tool call + tool result sent to the model) ⬆️ =====
{
"messages": [
{
"role": "system",
"content": "provide a concise answer"
},
{
"role": "user",
"content": "In which locations can I deploy a Hosted Private Cloud?"
},
{
"role": "assistant",
"reasoning": "The user asks: \"In which locations can I deploy a Hosted Private Cloud?\" This refers likely to the provider's dedicated cloud offering. The tool list-dedicatedcloud-locations can give that info. So we need to call it.",
"tool_calls": [
{
"id": "chatcmpl-tool-9bc1f854691ce351",
"type": "function",
"function": {
"name": "list-dedicatedcloud-locations",
"arguments": "{}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "chatcmpl-tool-9bc1f854691ce351",
"content": "HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location\nStatus: 200\nResponse:\n[\"rbx2a\",\"sbg1a\",\"rbx2b\",\"rbx2c\",\"pop1a\",\"lim1c\",\"waw1c\",\"sbg1c\",\"eri1c\",\"par1c\",\"sbg1d\",\"rbx2d\",\"hdf1a\",\"rbx3a\"]"
}
]
}
===== 🤖 ANSWER 🤖 =====
You can deploy a Hosted Private Cloud in the following OVHcloud locations:
- **rbx2a** – Roubaix (France)
- **sbg1a** – Strasbourg (France)
- **rbx2b** – Roubaix (France)
- **rbx2c** – Roubaix (France)
- **pop1a** – Papeete (French Polynesia)
- **lim1c** – Limoges (France)
- **waw1c** – Warsaw (Poland)
- **sbg1c** – Strasbourg (France)
- **eri1c** – Erfurt (Germany)
- **par1c** – Paris (France)
- **sbg1d** – Strasbourg (France)
- **rbx2d** – Roubaix (France)
- **hdf1a** – Haute‑Fôret (France)
- **rbx3a** – Roubaix (France)
These are the current data‑center locations where you can provision a Hosted Private Cloud. If you need more details about each location (e.g., specific services or compliance), just let me know!
We do find our 471 tools, only one of which is passed to the model.
The model asks for a call to list-dedicatedcloud-locations with empty arguments, the MCP server calls the OVHcloud API (GET /v1/dedicatedCloud/location) and the model writes its answer from the list of location codes 🎉.
⚠️ As in part 5, the script only handles the first call request, and doesn't loop if the model asks for more.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
☕️ Java
✍️ Pure Java
Let's move on to the Java version without any library, with the JDK HttpClient and Jackson.
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 26+
//DEPS com.fasterxml.jackson.core:jackson-databind:2.22.4
//
// MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b),
// with the JDK HttpClient and Jackson.
//
// The tool offered to the model is not written here: it is discovered at runtime
// on the OVHcloud MCP server, over JSON-RPC. The program hands its schema to the
// model as an ordinary function, then runs the call the model asks for by sending
// it back to the MCP server.
//
// Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
// Docs: https://labs.ovhcloud.com/en/mcp-server/
// Docs: https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
final String MCP_SERVER = "https://mcp.eu.ovhcloud.com/mcp";
final String ENDPOINT = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/chat/completions";
final String MODEL = "gpt-oss-120b";
// The server advertises hundreds of tools, many of them destructive. Choosing the
// ones the model gets to see is the job of the client, not of the server.
final String TOOL = "list-dedicatedcloud-locations";
// Both tokens are read from the environment, exported by run.sh from .env.
final String TOKEN = System.getenv("OVH_AI_ENDPOINTS_ACCESS_TOKEN");
final String MCP_TOKEN = System.getenv("OVH_MCP_ACCESS_TOKEN");
final ObjectMapper MAPPER = new ObjectMapper();
final HttpClient CLIENT = HttpClient.newHttpClient();
// Handed out by the server during the handshake, then repeated on every request.
String sessionId;
void main() throws Exception {
var question = "In which locations can I deploy a Hosted Private Cloud?";
// 1) Handshake. The session id comes back in a response header, not in the
// JSON-RPC result, which is why the raw response is needed here.
var handshake = sendToMcp("""
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": { "name": "pure-java-mcp-client", "version": "1.0.0" }
}
}""");
sessionId = handshake.headers().firstValue("mcp-session-id").orElse(null);
if (sessionId == null) {
IO.println("No session id returned by the MCP server: check OVH_MCP_ACCESS_TOKEN.");
return;
}
// The notification closing the handshake. It carries no id, so there is no answer.
sendToMcp("""
{ "jsonrpc": "2.0", "method": "notifications/initialized" }""");
IO.println("===== 🔌 MCP SESSION 🔌 =====");
IO.println(MCP_SERVER);
IO.println();
// 2) Ask the server what it can do, and keep one tool out of the lot. An MCP
// tool already describes its parameters as a JSON schema, so the description
// only has to be wrapped in the envelope the chat API expects.
var advertised = mcp("""
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }""").at("/result/tools");
var tools = MAPPER.createArrayNode();
for (JsonNode advertisedTool : advertised) {
if (!TOOL.equals(advertisedTool.get("name").asText())) {
continue;
}
var function = MAPPER.createObjectNode()
.put("name", advertisedTool.get("name").asText())
.put("description", advertisedTool.get("description").asText());
function.set("parameters", advertisedTool.get("inputSchema"));
var entry = tools.addObject();
entry.put("type", "function");
entry.set("function", function);
}
IO.println("===== 🧰 MCP TOOLS 🧰 =====");
IO.println(advertised.size() + " tools advertised by the server, " + tools.size() + " passed to the model");
IO.println(tools.toPrettyString());
IO.println();
// The same body is sent twice: only its messages array grows in between.
var body = MAPPER.createObjectNode();
body.put("model", MODEL);
var messages = body.putArray("messages");
messages.addObject()
.put("role", "system")
.put("content", "provide a concise answer");
messages.addObject()
.put("role", "user")
.put("content", question);
body.set("tools", tools);
// 3) First call: the question, and the tool as the model sees it. Nothing in
// the request says that it comes from an MCP server.
IO.println("===== ⬆️ JSON REQUEST (question + tools sent to the model) ⬆️ =====");
IO.println(body.toPrettyString());
IO.println();
JsonNode response = post(body.toString());
IO.println("===== ⬇️ JSON RESPONSE ⬇️ =====");
IO.println(response.toPrettyString());
IO.println();
JsonNode assistantMessage = response.at("/choices/0/message");
JsonNode toolCall = assistantMessage.at("/tool_calls/0");
// Asking for a tool is a choice of the model, not an obligation: without a tool
// call its message already holds the answer and there is nothing to run.
if (toolCall.isMissingNode()) {
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(assistantMessage.at("/content").asText());
return;
}
var functionName = toolCall.at("/function/name").asText();
// A tool without parameters can come back with empty arguments.
var arguments = toolCall.at("/function/arguments").asText();
if (arguments.isBlank()) {
arguments = "{}";
}
IO.println("===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====");
IO.println(functionName + " " + arguments);
IO.println();
// 4) Run the tool, this time on the MCP server. The name is checked first: only
// the tool handed to the model is allowed to be called.
if (!TOOL.equals(functionName)) {
IO.println("Unexpected tool requested by the model: " + functionName);
return;
}
var call = MAPPER.createObjectNode();
call.put("jsonrpc", "2.0");
call.put("id", 3);
call.put("method", "tools/call");
var params = call.putObject("params");
params.put("name", functionName);
params.set("arguments", MAPPER.readTree(arguments));
var result = mcp(call.toString()).at("/result/content/0/text").asText();
IO.println("===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====");
IO.println(result);
IO.println();
// 5) Second call: the conversation so far, plus the tool call of the model and
// its result, tied together by the tool call id.
messages.add(assistantMessage);
messages.addObject()
.put("role", "tool")
.put("tool_call_id", toolCall.get("id").asText())
.put("content", result);
IO.println("===== ⬆️ JSON REQUEST (tool call + tool result sent to the model) ⬆️ =====");
IO.println(body.toPrettyString());
IO.println();
response = post(body.toString());
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(response.at("/choices/0/message/content").asText());
}
// Every JSON-RPC message goes through here. The session header is only there once
// the handshake has handed one out.
HttpResponse<String> sendToMcp(String body) throws Exception {
var request = HttpRequest.newBuilder(URI.create(MCP_SERVER))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("Authorization", "Bearer " + MCP_TOKEN)
.POST(HttpRequest.BodyPublishers.ofString(body));
if (sessionId != null) {
request.header("Mcp-Session-Id", sessionId);
}
return CLIENT.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
JsonNode mcp(String body) throws Exception {
return MAPPER.readTree(sendToMcp(body).body());
}
JsonNode post(String body) throws Exception {
var request = HttpRequest.newBuilder(URI.create(ENDPOINT))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + TOKEN)
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
return MAPPER.readTree(CLIENT.send(request, HttpResponse.BodyHandlers.ofString()).body());
}
- line 30: the only tool we're going to offer the model
- lines 47 to 57: the handshake, the
initializerequest - lines 59 to 63: getting the session identifier from the response header, hence the need to keep the raw HTTP response
- lines 66 and 67: the notification that ends the handshake
- lines 76 and 77: the request for the list of tools
- lines 79 to 92: the filter on our tool, and its conversion to the chat API format
- line 109: the tools are added to the request body
- line 117: the first call to the model
- lines 135 to 139: empty arguments replaced with an empty object
- lines 147 to 150: checking the name of the requested tool
- lines 152 to 160: the tool call on the MCP server with
tools/call - lines 168 to 172: adding the call request and the result to the conversation
- line 178: the second call to the model
- lines 186 to 196: sending a message to the MCP server, with the session identifier as soon as we have one
Still as verbose, but everything is there: in the end, an MCP client is just a few JSON-RPC requests 🤓.
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com/mcp
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
[ {
"type" : "function",
"function" : {
"name" : "list-dedicatedcloud-locations",
"description" : "List hosting locations",
"parameters" : {
"properties" : { },
"type" : "object"
}
}
} ]
...
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location
Status: 200
Response:
["rbx2a","sbg1a","rbx2b","rbx2c","pop1a","lim1c","waw1c","sbg1c","eri1c","par1c","sbg1d","rbx2d","hdf1a","rbx3a"]
...
===== 🤖 ANSWER 🤖 =====
You can deploy a **Hosted Private Cloud** (Dedicated Cloud) in any of the following OVHcloud locations:
| Region | Data‑center code |
|--------|------------------|
| **Paris** – France | `par1c` |
| **Roubaix** – France | `rbx2a`, `rbx2b`, `rbx2c`, `rbx2d`, `rbx3a` |
| **Strasbourg** – France | `sbg1a`, `sbg1c`, `sbg1d` |
| **Limerick** – Ireland | `lim1c` |
| **Warsaw** – Poland | `waw1c` |
| **Erfurt** – Germany | `eri1c` |
| **Hannover** – Germany | `hdf1a` |
| **Pop!_OS** (Amsterdam) – Netherlands | `pop1a` |
These locations cover most major EU regions where OVHcloud offers Hosted Private Cloud services. Choose the data‑center that best matches your latency, compliance, and redundancy requirements.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
🛠️ With the OpenAI and MCP SDKs
The OpenAI SDK knows nothing about MCP, so we pair it with the official MCP Java SDK, which handles the session and the JSON-RPC messages for us.
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 26+
//DEPS com.openai:openai-java:4.94.0
//DEPS io.modelcontextprotocol.sdk:mcp-core:2.2.0
// mcp-json-jackson2 keeps a single Jackson on the classpath: the OpenAI SDK is
// on Jackson 2, while the default JSON binding of the MCP SDK is on Jackson 3.
//DEPS io.modelcontextprotocol.sdk:mcp-json-jackson2:2.2.0
//DEPS org.slf4j:slf4j-nop:2.0.20
//
// MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b) through the
// official OpenAI Java SDK (https://github.com/openai/openai-java) and the
// official MCP Java SDK (https://github.com/modelcontextprotocol/java-sdk).
//
// The tool offered to the model is not written here: it is discovered at runtime
// on the OVHcloud MCP server, and its JSON schema is turned into a tool definition
// on the fly. The call the model asks for is then routed back to the MCP server.
//
// Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
// Docs: https://labs.ovhcloud.com/en/mcp-server/
// Docs: https://java.sdk.modelcontextprotocol.io/latest/client/
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.FunctionDefinition;
import com.openai.models.FunctionParameters;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.chat.completions.ChatCompletionFunctionTool;
import com.openai.models.chat.completions.ChatCompletionMessage;
import com.openai.models.chat.completions.ChatCompletionToolMessageParam;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.spec.McpSchema;
// A tool advertised by the MCP server, described as the chat API expects it. The
// schema is only known at runtime, so the tool is built key by key instead of
// being derived from a Java class.
ChatCompletionFunctionTool asChatTool(McpSchema.Tool tool) {
var parameters = FunctionParameters.builder();
tool.inputSchema().forEach((key, value) -> parameters.putAdditionalProperty(key, JsonValue.from(value)));
return ChatCompletionFunctionTool.builder()
.function(FunctionDefinition.builder()
.name(tool.name())
.description(tool.description())
.parameters(parameters.build())
.build())
.build();
}
void main() {
// baseUrl must include the /v1 suffix. Both tokens are read from the
// environment, exported by run.sh from .env.
final String baseUrl = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1";
final String model = "gpt-oss-120b";
final String token = System.getenv("OVH_AI_ENDPOINTS_ACCESS_TOKEN");
// The transport takes the host and the path separately.
final String mcpServer = "https://mcp.eu.ovhcloud.com";
final String mcpEndpoint = "/mcp";
final String mcpToken = System.getenv("OVH_MCP_ACCESS_TOKEN");
// The server advertises hundreds of tools, many of them destructive. Choosing
// the ones the model gets to see is the job of the client, not of the server.
final String toolName = "list-dedicatedcloud-locations";
var question = "In which locations can I deploy a Hosted Private Cloud?";
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(baseUrl)
.apiKey(token)
//.logLevel(LogLevel.DEBUG)
.build();
// 1) The MCP session. initialize() runs the handshake; the session id it hands
// out is then carried by the transport on its own. Signing the requests is
// the only thing left to do, through a customizer.
var transport = HttpClientStreamableHttpTransport.builder(mcpServer)
.endpoint(mcpEndpoint)
// The server rejects the charset the JDK HttpClient appends to the
// content type, so the header is set again rather than added to.
.addHttpRequestCustomizer((request, method, uri, body, context) ->
request.header("Authorization", "Bearer " + mcpToken)
.setHeader("Content-Type", "application/json"))
.build();
var mcp = McpClient.sync(transport).build();
var session = mcp.initialize();
IO.println("===== 🔌 MCP SESSION 🔌 =====");
IO.println(mcpServer + mcpEndpoint);
IO.println(session.serverInfo().name() + " " + session.serverInfo().version()
+ ", protocol " + session.protocolVersion());
IO.println();
// 2) Ask the server what it can do, and keep one tool out of the lot.
var advertised = mcp.listTools().tools();
var tools = advertised.stream()
.filter(tool -> toolName.equals(tool.name()))
.map(tool -> asChatTool(tool))
.toList();
IO.println("===== 🧰 MCP TOOLS 🧰 =====");
IO.println(advertised.size() + " tools advertised by the server, " + tools.size() + " passed to the model");
tools.forEach(IO::println);
IO.println();
// The same builder serves both calls: only its messages grow in between.
var paramsBuilder = ChatCompletionCreateParams.builder()
.model(model)
.addSystemMessage("provide a concise answer")
.addUserMessage(question);
tools.forEach(paramsBuilder::addTool);
// 3) First call: the question, and the tool as the model sees it. Nothing in
// the request says that it comes from an MCP server.
var params = paramsBuilder.build();
IO.println("===== ⬆️ REQUEST (question + tools sent to the model) ⬆️ =====");
params.messages().forEach(IO::println);
params.tools().orElseThrow().forEach(IO::println);
IO.println();
ChatCompletion response = client.chat().completions().create(params);
IO.println("===== ⬇️ RESPONSE (SDK object) ⬇️ =====");
IO.println(response.toString());
IO.println();
ChatCompletionMessage assistantMessage = response.choices().getFirst().message();
var toolCalls = assistantMessage.toolCalls().orElse(List.of());
// Asking for a tool is a choice of the model, not an obligation: without a tool
// call its message already holds the answer and there is nothing to run.
if (toolCalls.isEmpty()) {
mcp.close();
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(assistantMessage.content().orElse(""));
return;
}
var toolCall = toolCalls.getFirst().asFunction();
// A tool without parameters can come back with empty arguments.
var arguments = toolCall.function().arguments().isBlank() ? "{}" : toolCall.function().arguments();
IO.println("===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====");
IO.println(toolCall.function().name() + " " + arguments);
IO.println();
// 4) Run the tool, this time on the MCP server. The name is checked first: only
// the tool handed to the model is allowed to be called. The arguments stay
// the JSON text written by the model, which the request parses itself.
if (!toolName.equals(toolCall.function().name())) {
mcp.close();
IO.println("Unexpected tool requested by the model: " + toolCall.function().name());
return;
}
var callResult = mcp.callTool(McpSchema.CallToolRequest.builder(toolCall.function().name())
.arguments(McpJsonDefaults.getMapper(), arguments)
.build());
mcp.close();
// An MCP result is a list of content blocks: this tool answers with text.
var result = ((McpSchema.TextContent) callResult.content().getFirst()).text();
var toolMessage = ChatCompletionToolMessageParam.builder()
.toolCallId(toolCall.id())
.content(result)
.build();
IO.println("===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====");
IO.println(toolMessage.content().asText());
IO.println();
// 5) Second call: the conversation so far, plus the tool call of the model and
// its result, tied together by the tool call id.
paramsBuilder
.addMessage(assistantMessage)
.addMessage(toolMessage);
params = paramsBuilder.build();
IO.println("===== ⬆️ REQUEST (tool call + tool result sent to the model) ⬆️ =====");
params.messages().forEach(IO::println);
IO.println();
response = client.chat().completions().create(params);
IO.println("===== 🤖 ANSWER 🤖 =====");
response.choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(IO::println);
}
- lines 4 to 7: the MCP SDK, with its Jackson 2 support so as not to have two versions of Jackson on the classpath (the OpenAI SDK is on Jackson 2, the MCP SDK on Jackson 3 by default)
- lines 40 to 51: converting an MCP tool into an OpenAI tool. Unlike part 5, the description can't be generated from a Java class: the schema is only known at runtime, so we copy it key by key
- lines 80 to 87: the Streamable HTTP transport, with a customizer that adds the token to each request
- lines 89 and 90: creating the MCP client, and the handshake with
initialize(). The session identifier is then handled by the transport - lines 94 and 95: the handshake response gives us the name of the server and the negotiated protocol version
- lines 99 to 103: the list of tools, filtered and converted
- line 115: adding the tools to the request
- line 125: the first call to the model
- lines 154 to 158: checking the name of the requested tool
- lines 160 to 163: the tool call on the MCP server with
callTool, then closing the session - line 166: the MCP result is a list of content blocks, here a text block
- lines 179 to 181: adding the call request and the result to the conversation
- line 188: the second call to the model
The MCP SDK takes the protocol plumbing off our hands, but the orchestration is still up to us, as in part 5.
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com/mcp
unified 1.0.0, protocol 2025-03-26
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
ChatCompletionFunctionTool{function=FunctionDefinition{name=list-dedicatedcloud-locations, description=List hosting locations, parameters=FunctionParameters{additionalProperties={properties={}, type=object}}, strict=, additionalProperties={}}, type=function, additionalProperties={}}
...
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location
Status: 200
Response:
["rbx2a","sbg1a","rbx2b","rbx2c","pop1a","lim1c","waw1c","sbg1c","eri1c","par1c","sbg1d","rbx2d","hdf1a","rbx3a"]
...
===== 🤖 ANSWER 🤖 =====
You can launch a **Hosted Private Cloud** in any of the following OVH data‑center locations:
- **rbx2a** – Roubaix (France)
- **sbg1a** – Strasbourg (France)
- **rbx2b** – Roubaix (France)
- **rbx2c** – Roubaix (France)
- **pop1a** – (Canada)
- **lim1c** – Limoges (France)
- **waw1c** – Warsaw (Poland)
- **sbg1c** – Strasbourg (France)
- **eri1c** – (Germany)
- **par1c** – Paris (France)
- **sbg1d** – Strasbourg (France)
- **rbx2d** – Roubaix (France)
- **hdf1a** – Hauts‑de‑France (France)
- **rbx3a** – Roubaix (France)
These location codes correspond to OVH’s data‑center sites across Europe (and one in Canada). When ordering a Hosted Private Cloud you can select any of the above locations to suit your latency, compliance, or redundancy requirements.
By the way, we can see that the server is called unified, in version 1.0.0, and that it speaks version 2025-03-26 of the protocol.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
🦜 With LangChain4j
With LangChain4j and its langchain4j-mcp module, we get back the simplicity of part 5: the framework handles everything.
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 26+
//DEPS dev.langchain4j:langchain4j:1.22.0
//DEPS dev.langchain4j:langchain4j-open-ai:1.22.0
//DEPS dev.langchain4j:langchain4j-mcp:1.22.0-beta32
//DEPS org.slf4j:slf4j-nop:2.0.20
// Jackson writes the final fields of the MCP protocol records by reflection,
// which Java 26 warns about unless it is allowed explicitly.
//JAVA_OPTIONS --enable-final-field-mutation=ALL-UNNAMED
//
// MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b)
// through LangChain4j AI Services (https://github.com/langchain4j/langchain4j).
//
// The tools offered to the model are not written here: a tool provider discovers
// them at runtime on the OVHcloud MCP server, keeps the ones it is told to keep,
// and runs the call the model asks for.
//
// Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
// Docs: https://labs.ovhcloud.com/en/mcp-server/
// Docs: https://docs.langchain4j.dev/tutorials/mcp
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.http.StreamableHttpMcpTransport;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.SystemMessage;
interface Assistant {
@SystemMessage("provide a concise answer")
String chat(String userMessage);
}
void main() throws Exception {
// baseUrl must include the /v1 suffix. Both tokens are read from the
// environment, exported by run.sh from .env.
final String baseUrl = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1";
final String model = "gpt-oss-120b";
final String token = System.getenv("OVH_AI_ENDPOINTS_ACCESS_TOKEN");
final String mcpServer = "https://mcp.eu.ovhcloud.com/mcp";
final String mcpToken = System.getenv("OVH_MCP_ACCESS_TOKEN");
// The server advertises hundreds of tools, many of them destructive. Choosing
// the ones the model gets to see is the job of the client, not of the server.
final List<String> toolNames = List.of("list-dedicatedcloud-locations");
var question = "In which locations can I deploy a Hosted Private Cloud?";
ChatModel chatModel = OpenAiChatModel.builder()
.baseUrl(baseUrl)
.apiKey(token)
.modelName(model)
// Listing what the tool returned takes the model well over the
// default one minute.
.timeout(Duration.ofMinutes(3))
// .logRequests(true)
// .logResponses(true)
.build();
// 1) The MCP session. The handshake and the session id are handled by the
// client: the token is the only thing to pass, as a header.
var transport = new StreamableHttpMcpTransport.Builder()
.url(mcpServer)
.customHeaders(Map.of("Authorization", "Bearer " + mcpToken))
// .logRequests(true)
// .logResponses(true)
.build();
McpClient mcpClient = new DefaultMcpClient.Builder()
.transport(transport)
.build();
IO.println("===== 🔌 MCP SESSION 🔌 =====");
IO.println(mcpServer);
IO.println();
// 2) The tool provider lists the tools of the server and keeps the ones named
// here. It also turns them into something the model understands, and runs
// them when the model asks: there is no tool code in this file.
var toolProvider = McpToolProvider.builder()
.mcpClients(mcpClient)
.filterToolNames(toolNames)
.build();
var advertised = mcpClient.listTools();
IO.println("===== 🧰 MCP TOOLS 🧰 =====");
IO.println(advertised.size() + " tools advertised by the server, " + toolNames.size() + " passed to the model");
advertised.stream()
.filter(tool -> toolNames.contains(tool.name()))
.forEach(IO::println);
IO.println();
// The AI Service calls the model, runs the tool the model asks for and calls
// the model again with the result. The two callbacks only show it happening.
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.toolProvider(toolProvider)
.beforeToolExecution(before -> {
IO.println("===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====");
IO.println(before.request().name() + " " + before.request().arguments());
IO.println();
})
.afterToolExecution(after -> {
IO.println("===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====");
IO.println(after.result());
IO.println();
})
.build();
IO.println("===== ❓ QUESTION ❓ =====");
IO.println(question);
IO.println();
// The tool banners are printed during this call, hence the answer kept aside.
var answer = assistant.chat(question);
mcpClient.close();
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(answer);
}
- line 5: the LangChain4j MCP module
- line 9: Jackson modifies
finalfields of the protocol classes by reflection, which Java 26 reports with a warning, unless it's explicitly allowed - line 48: the list of tools we're going to offer the model
- line 58: the model's answer based on the tool result takes a long time to generate, the default one-minute timeout isn't enough
- lines 65 to 70: the Streamable HTTP transport, with the token in a header
- lines 72 to 74: the MCP client, which takes care of the handshake and the session
- lines 83 to 86: the
McpToolProvider, which lists the tools of the server, keeps only those whose name is in our list, and runs them when the model asks - line 101: the tool provider is plugged into the AI Service, instead of the
.tools(...)of part 5 - lines 102 to 111: the two display callbacks, the same as in part 5
- line 119: the call to the assistant
There isn't a single line of tool code left in the file: the tool comes from the server, and LangChain4j does the rest 🤯.
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com/mcp
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
ToolSpecification { name = "list-dedicatedcloud-locations", description = "List hosting locations", parameters = JsonObjectSchema {description = null, properties = {}, required = [], additionalProperties = null, definitions = {} }, metadata = {}, strict = null }
===== ❓ QUESTION ❓ =====
In which locations can I deploy a Hosted Private Cloud?
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location
Status: 200
Response:
["rbx2a","sbg1a","rbx2b","rbx2c","pop1a","lim1c","waw1c","sbg1c","eri1c","par1c","sbg1d","rbx2d","hdf1a","rbx3a"]
===== 🤖 ANSWER 🤖 =====
You can launch a **Hosted Private Cloud** in any of the OVH data‑center locations that the API reports as available for Dedicated Cloud services. As of the latest query, the supported locations are:
| Location code | Physical site (city/region) |
|---------------|-----------------------------|
| **rbx2a** | Roubaix (France) |
| **rbx2b** | Roubaix (France) |
| **rbx2c** | Roubaix (France) |
| **rbx2d** | Roubaix (France) |
| **rbx3a** | Roubaix (France) |
| **sbg1a** | Strasbourg (France) |
| **sbg1c** | Strasbourg (France) |
| **sbg1d** | Strasbourg (France) |
| **pop1a** | (POP – Europe/Asia‑Pacific region, often used for traffic‑exchange nodes) |
| **lim1c** | Lima (Peru) |
| **waw1c** | Warsaw (Poland) |
| **eri1c** | Erfurt (Germany) |
| **par1c** | Paris (France) |
| **hdf1a** | (HDF – likely a newer or specialized site, currently in France) |
These are the current locations where you can provision a Hosted Private Cloud. Availability can evolve, so it’s always a good idea to check the OVH API or the OVH Control Panel for the most up‑to‑date list before planning a deployment.
ℹ️ To see the
JSON-RPCexchanges with the MCP server, just uncomment the transport's.logRequests(true)and.logResponses(true)(lines 68 and 69), and replaceslf4j-nopwithslf4j-simple.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
⚡️ With Quarkus
With Quarkus, the MCP server is declared in the configuration.
# Used by the MCP example only, mounted as application.properties by its //FILES
# directive. The other examples of this directory keep application.properties.
quarkus.banner.enabled=false
quarkus.log.level=WARN
quarkus.langchain4j.openai.base-url=https://oai.endpoints.kepler.ai.cloud.ovh.net/v1
quarkus.langchain4j.openai.api-key=${OVH_AI_ENDPOINTS_ACCESS_TOKEN}
quarkus.langchain4j.openai.chat-model.model-name=gpt-oss-120b
# Listing what the tool returned takes the model well over the default minute.
quarkus.langchain4j.openai.timeout=3m
# The MCP server, declared as configuration: a transport, a URL and the header
# carrying the token. No Java code opens the session or runs the handshake.
quarkus.langchain4j.mcp.ovhcloud.transport-type=streamable-http
quarkus.langchain4j.mcp.ovhcloud.url=https://mcp.eu.ovhcloud.com/mcp
quarkus.langchain4j.mcp.ovhcloud.header."Authorization"=Bearer ${OVH_MCP_ACCESS_TOKEN}
# Uncomment to log the raw JSON-RPC traffic with the MCP server:
#quarkus.langchain4j.mcp.ovhcloud.log-requests=true
#quarkus.langchain4j.mcp.ovhcloud.log-responses=true
- line 11: as with LangChain4j, we increase the model timeout
- lines 15 to 17: the MCP server, named
ovhcloud: its transport, its URL and the header carrying the token. Not a single line of Java opens the session
On the code side:
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 26+
// jboss-threads needs java.lang opened on Java 24+ (thread-local reset capability).
//JAVA_OPTIONS --add-opens=java.base/java.lang=ALL-UNNAMED
// Jackson writes the final fields of the MCP protocol records by reflection,
// which Java 26 warns about unless it is allowed explicitly.
//JAVA_OPTIONS --enable-final-field-mutation=ALL-UNNAMED
//DEPS io.quarkus.platform:quarkus-bom:3.33.4.1@pom
//DEPS io.quarkiverse.langchain4j:quarkus-langchain4j-openai:1.14.2
//DEPS io.quarkiverse.langchain4j:quarkus-langchain4j-mcp:1.14.2
//
// MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b)
// through Quarkus + quarkus-langchain4j
// (https://github.com/quarkiverse/quarkus-langchain4j).
//
// Single-file Quarkus application run by JBang. The MCP server is declared in the
// configuration, which makes its client a bean. The tools it advertises are
// discovered at runtime, filtered down to one, and run by the extension.
//
// Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
// Docs: https://labs.ovhcloud.com/en/mcp-server/
// Docs: https://docs.quarkiverse.io/quarkus-langchain4j/dev/mcp.html
//FILES application.properties=mcp.properties
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.observability.api.event.ToolExecutedEvent;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.tool.ToolProvider;
import io.quarkiverse.langchain4j.RegisterAiService;
import io.quarkiverse.langchain4j.mcp.runtime.McpClientName;
import io.quarkus.runtime.QuarkusApplication;
import io.quarkus.runtime.annotations.QuarkusMain;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.control.ActivateRequestContext;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import java.util.List;
import java.util.function.Supplier;
// The server advertises hundreds of tools, many of them destructive. Choosing the
// ones the model gets to see is the job of the client, not of the server, and the
// extension has no configuration property for it: hence this bean, which filters
// the tools of the injected client.
@ApplicationScoped
class OvhcloudTools implements Supplier<ToolProvider> {
static final List<String> TOOL_NAMES = List.of("list-dedicatedcloud-locations");
@Inject
@McpClientName("ovhcloud")
McpClient mcpClient;
@Override
public ToolProvider get() {
return McpToolProvider.builder()
.mcpClients(mcpClient)
.filterToolNames(TOOL_NAMES)
.build();
}
}
// The AI service calls the model, runs the tool the model asks for and calls the
// model again with the result.
@RegisterAiService(toolProviderSupplier = OvhcloudTools.class)
interface Assistant {
@SystemMessage("provide a concise answer")
String chat(String userMessage);
}
@QuarkusMain
public class _04_07_McpClient implements QuarkusApplication {
@Inject
Assistant assistant;
// The client of the server declared under quarkus.langchain4j.mcp.ovhcloud.
@Inject
@McpClientName("ovhcloud")
McpClient mcpClient;
@ConfigProperty(name = "quarkus.langchain4j.mcp.ovhcloud.url")
String mcpServer;
// @ActivateRequestContext makes the CDI request scope available for the call.
@Override
@ActivateRequestContext
public int run(String... args) {
var question = "In which locations can I deploy a Hosted Private Cloud?";
IO.println("===== 🔌 MCP SESSION 🔌 =====");
IO.println(mcpServer);
IO.println();
var advertised = mcpClient.listTools();
IO.println("===== 🧰 MCP TOOLS 🧰 =====");
IO.println(advertised.size() + " tools advertised by the server, "
+ OvhcloudTools.TOOL_NAMES.size() + " passed to the model");
advertised.stream()
.filter(tool -> OvhcloudTools.TOOL_NAMES.contains(tool.name()))
.forEach(IO::println);
IO.println();
IO.println("===== ❓ QUESTION ❓ =====");
IO.println(question);
IO.println();
// The tool banners are printed during this call, hence the answer kept aside.
var answer = assistant.chat(question);
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(answer);
return 0;
}
// Fired by the extension once a tool has run: it only shows what happened.
void onToolExecuted(@Observes ToolExecutedEvent event) {
IO.println("===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====");
IO.println(event.request().name() + " " + event.request().arguments());
IO.println();
IO.println("===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====");
IO.println(event.resultText());
IO.println();
}
}
- line 10: the MCP extension of Quarkus LangChain4j
- line 24: the
mcp.propertiesfile is mounted asapplication.properties - lines 48 to 64: the tool filter. The extension offers
@McpToolBoxto give the tools of a server to an AI Service, but it gives all of them, with no way to filter them through configuration. So we go through a bean that provides a filteredMcpToolProvider, as with LangChain4j - line 68: this tool provider is plugged into the AI Service
- lines 80 to 83: the MCP client declared in the configuration is a bean, which can be injected
- line 98: here we only use it to display the list of tools
- line 113: the call, with only the question
- lines 121 to 129: the
ToolExecutedEventobserver from part 5, for display
⚠️ The bean providing the tools must be
@ApplicationScoped, otherwise Quarkus doesn't find it and the build fails with anUnsatisfiedResolutionException.
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com/mcp
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
ToolSpecification { name = "list-dedicatedcloud-locations", description = "List hosting locations", parameters = JsonObjectSchema {description = null, properties = {}, required = [], additionalProperties = null, definitions = {} }, metadata = {}, strict = null }
===== ❓ QUESTION ❓ =====
In which locations can I deploy a Hosted Private Cloud?
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location
Status: 200
Response:
["rbx2a","sbg1a","rbx2b","rbx2c","pop1a","lim1c","waw1c","sbg1c","eri1c","par1c","sbg1d","rbx2d","hdf1a","rbx3a"]
===== 🤖 ANSWER 🤖 =====
You can launch a **Hosted Private Cloud** in any of OVHcloud’s dedicated‑cloud data‑center locations. As of the latest catalogue, the supported locations are:
| Location code | Data‑center (city, country) |
|---------------|-----------------------------|
| **rbx2a** | Roubaix, France |
| **rbx2b** | Roubaix, France |
| **rbx2c** | Roubaix, France |
| **rbx2d** | Roubaix, France |
| **rbx3a** | Roubaix, France |
| **sbg1a** | Strasbourg, France |
| **sbg1c** | Strasbourg, France |
| **sbg1d** | Strasbourg, France |
| **par1c** | Paris, France |
| **hdf1a** | Hauts‑de‑France (Lille), France |
| **lim1c** | Limoges, France |
| **waw1c** | Warsaw, Poland |
| **eri1c** | Erfurt, Germany |
| **pop1a** | PoP (Vancouver), Canada |
These are the geographic points where OVHcloud currently offers Hosted Private Cloud (formerly “Dedicated Cloud”) resources. Availability of specific flavors or services can vary by site, so it’s always a good idea to check the latest OVHcloud catalogue or contact support for any location‑specific constraints.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
☘️ With Spring AI
To finish, Spring AI, where the MCP server is also declared in the configuration.
# Used by the MCP example only, mounted as application.properties by its //FILES
# directive. The other examples of this directory keep application.properties.
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=WARN
logging.level.org.springframework.boot.autoconfigure.AutoConfigurationPackages=ERROR
# The server names its tools after HTTP routes, which the MCP spec does not allow:
# one warning for each of the 53 it gets wrong. Silence the validator and the two providers
# complaining that this client declares no sampling and no elicitation handler.
logging.level.io.modelcontextprotocol.util.ToolNameValidator=ERROR
logging.level.org.springframework.ai.mcp.annotation=ERROR
spring.ai.openai.base-url=https://oai.endpoints.kepler.ai.cloud.ovh.net/v1
spring.ai.openai.chat.options.model=gpt-oss-120b
spring.ai.openai.api-key=${OVH_AI_ENDPOINTS_ACCESS_TOKEN}
# The MCP server, declared as configuration: a connection name, a host and a path.
# No Java code opens the session or runs the handshake.
spring.ai.mcp.client.streamable-http.connections.ovhcloud.url=https://mcp.eu.ovhcloud.com
spring.ai.mcp.client.streamable-http.connections.ovhcloud.endpoint=/mcp
- lines 8 to 12: OVHcloud's MCP server names its tools after the HTTP routes of the API, with
/and{}, which the MCP specification doesn't allow. Spring AI displays a warning for each of the 53 names concerned, so we silence the validator - lines 20 and 21: the connection to the MCP server, named
ovhcloud, with its URL and its path
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 26+
//DEPS org.springframework.boot:spring-boot-dependencies:4.1.2@pom
//DEPS org.springframework.ai:spring-ai-bom:2.0.2@pom
//DEPS org.springframework.boot:spring-boot-starter:4.1.2
// AspectJ weaver, required by Spring AI's ChatClient advisors (AOP).
//DEPS org.aspectj:aspectjweaver:1.9.26
//DEPS org.springframework.ai:spring-ai-starter-model-openai:2.0.2
//DEPS org.springframework.ai:spring-ai-starter-mcp-client:2.0.2
// Servlet API present only so Boot's web-servlet config classes resolve during
// bean introspection; the app stays non-web (spring.main.web-application-type=none).
//DEPS jakarta.servlet:jakarta.servlet-api:6.1.0
//
// MCP client example calling OVHcloud AI Endpoints (gpt-oss-120b)
// through Spring AI (https://docs.spring.io/spring-ai/reference/).
//
// Single-file Spring Boot application run by JBang. The MCP server is declared in
// the configuration, which makes its client a bean. The tools it advertises are
// discovered at runtime, filtered down to one, and run by Spring AI.
//
// Docs: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/gpt-oss-120b/
// Docs: https://labs.ovhcloud.com/en/mcp-server/
// Docs: https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html
//FILES application.properties=mcp.properties
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.customizer.McpSyncHttpClientRequestCustomizer;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.McpToolFilter;
import org.springframework.ai.mcp.McpToolNamePrefixGenerator;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
import java.util.List;
// Wraps a tool to print what goes in and what comes out. Not needed for the tool
// to work: it only shows the call happening.
record LoggedTool(ToolCallback tool) implements ToolCallback {
@Override
public ToolDefinition getToolDefinition() {
return tool.getToolDefinition();
}
@Override
public String call(String arguments) {
IO.println("===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====");
IO.println(getToolDefinition().name() + " " + arguments);
IO.println();
var result = tool.call(arguments);
IO.println("===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====");
IO.println(result);
IO.println();
return result;
}
}
// NOT @SpringBootApplication: this file lives in the default package, so its
// @ComponentScan would scan the whole classpath and break Spring's own config.
@SpringBootConfiguration
@EnableAutoConfiguration
public class _05_07_McpClient {
// The server advertises hundreds of tools, many of them destructive. Choosing
// the ones the model gets to see is the job of the client, not of the server.
static final String TOOL_NAME = "list-dedicatedcloud-locations";
public static void main(String[] args) {
SpringApplication.run(_05_07_McpClient.class, args);
}
// The transport builds its own requests, so the token is added to them here.
@Bean
McpSyncHttpClientRequestCustomizer mcpAuthorization(
@Value("${OVH_MCP_ACCESS_TOKEN}") String mcpToken) {
return (request, method, uri, body, context) -> request
.header("Authorization", "Bearer " + mcpToken)
// The server rejects the charset the JDK HttpClient appends to the
// content type, so the header is set again rather than added to.
.setHeader("Content-Type", "application/json");
}
// Picked up by the auto-configuration: the tools it returns false for are never
// turned into callbacks, and the model never hears about them.
@Bean
McpToolFilter mcpToolFilter() {
return (connection, tool) -> TOOL_NAME.equals(tool.name());
}
// Tool names are prefixed with the connection name by default.
@Bean
McpToolNamePrefixGenerator mcpToolNames() {
return McpToolNamePrefixGenerator.noPrefix();
}
@Bean
CommandLineRunner run(ChatClient.Builder builder,
SyncMcpToolCallbackProvider toolCallbacks,
List<McpSyncClient> mcpClients,
@Value("${spring.ai.mcp.client.streamable-http.connections.ovhcloud.url}") String mcpServer) {
return args -> {
var question = "In which locations can I deploy a Hosted Private Cloud?";
var mcpClient = mcpClients.getFirst();
IO.println("===== 🔌 MCP SESSION 🔌 =====");
IO.println(mcpServer);
IO.println(mcpClient.getServerInfo().name() + " " + mcpClient.getServerInfo().version()
+ ", protocol " + mcpClient.getCurrentInitializationResult().protocolVersion());
IO.println();
var advertised = mcpClient.listTools().tools();
var tools = Arrays.stream(toolCallbacks.getToolCallbacks())
.map(LoggedTool::new)
.toArray(ToolCallback[]::new);
IO.println("===== 🧰 MCP TOOLS 🧰 =====");
IO.println(advertised.size() + " tools advertised by the server, "
+ tools.length + " passed to the model");
Arrays.stream(tools).forEach(tool -> IO.println(tool.getToolDefinition()));
IO.println();
var chatClient = builder
.defaultSystem("provide a concise answer")
// Cast because defaultTools takes Object..., and every other
// overload taking callbacks is deprecated for removal.
.defaultTools((Object[]) tools)
.build();
IO.println("===== ❓ QUESTION ❓ =====");
IO.println(question);
IO.println();
// The ChatClient calls the model, runs the tool the model asks for and
// calls the model again with the result. The tool banners are printed
// during this call, hence the answer kept aside.
var answer = chatClient.prompt()
.user(question)
.call()
.content();
IO.println("===== 🤖 ANSWER 🤖 =====");
IO.println(answer);
};
}
}
- line 9: the Spring AI MCP client starter
- lines 47 to 66: the
ToolCallbackthat displays the call and the result, as in part 5 - lines 83 to 91: Spring AI's configuration doesn't allow adding a header, so the token goes through a request customizer, with the same
Content-Typetrick as with the MCP SDK (Spring AI is built on it) - lines 95 to 98: the tool filter. Spring AI detects a
McpToolFilterbean on its own: the rejected tools are never turned into callbacks, and the model never hears about them - lines 101 to 104: by default, Spring AI prefixes tool names with the connection name, we disable it to keep the original name
- lines 107 to 110: Spring AI provides the MCP tools (
SyncMcpToolCallbackProvider) and the already initialized MCP clients - lines 122 to 125: the filtered tools, wrapped for display
- line 137: the tools are plugged into the
ChatClient. The cast is needed because the other variants of the method are deprecated - lines 147 to 150: the call, with only the question
===== 🔌 MCP SESSION 🔌 =====
https://mcp.eu.ovhcloud.com
unified 1.0.0, protocol 2025-03-26
===== 🧰 MCP TOOLS 🧰 =====
471 tools advertised by the server, 1 passed to the model
DefaultToolDefinition[name=list-dedicatedcloud-locations, description=List hosting locations, inputSchema={"properties":{},"type":"object"}]
===== ❓ QUESTION ❓ =====
In which locations can I deploy a Hosted Private Cloud?
===== 🛠️ TOOL CALL (requested by the model) 🛠️ =====
list-dedicatedcloud-locations {}
===== 🛠️ TOOL RESULT (sent back to the model) 🛠️ =====
[{"text":"HTTP GET https://eu.api.ovh.com/v1/dedicatedCloud/location\nStatus: 200\nResponse:\n[\"rbx2a\",\"sbg1a\",\"rbx2b\",\"rbx2c\",\"pop1a\",\"lim1c\",\"waw1c\",\"sbg1c\",\"eri1c\",\"par1c\",\"sbg1d\",\"rbx2d\",\"hdf1a\",\"rbx3a\"]"}]
===== 🤖 ANSWER 🤖 =====
Here are the data‑center locations where you can launch a **Hosted Private Cloud (Dedicated Cloud)** on OVHcloud:
| Location code | City / Region | Country |
|---------------|---------------|---------|
| **rbx2a** | Roubaix 2 A | France |
| **rbx2b** | Roubaix 2 B | France |
| **rbx2c** | Roubaix 2 C | France |
| **rbx2d** | Roubaix 2 D | France |
| **rbx3a** | Roubaix 3 A | France |
| **sbg1a** | Strasbourg 1 A | France |
| **sbg1c** | Strasbourg 1 C | France |
| **sbg1d** | Strasbourg 1 D | France |
| **pop1a** | Paris 1 A *(POP = “Paris‑Orly”)* | France |
| **par1c** | Paris 1 C | France |
| **hdf1a** | Helsinki 1 A | Finland |
| **eri1c** | Erfurt 1 C | Germany |
| **waw1c** | Warsaw 1 C | Poland |
| **lim1c** | Limerick 1 C | Ireland |
These locations span several European regions (France, Finland, Germany, Poland, and Ireland) and represent the specific data‑center clusters available for provisioning a Hosted Private Cloud. Choose the location that best matches your latency, compliance, and geographic requirements.
A small difference: Spring AI sends the MCP result back to the model as is, as a list of content blocks, whereas the others only keep its text. The model copes with it very well 😉.
To see the full source code of this example, it's here 📜.
📽️ Let's see it in action!
🤥 The model hasn't (yet) understood everything
If you read the answers carefully, you may have raised an eyebrow.
The tool only returns location codes (rbx2a, lim1c, eri1c, ...), and it's the model that translates them into cities.
For rbx (Roubaix) or sbg (Strasbourg), no problem, but for the others, here is what it answered from one run to the next:
| Code | Bash | Plain Java | LangChain4j | Quarkus | Spring AI |
|---|---|---|---|---|---|
lim1c |
Limoges | Limerick | Lima | Limoges | Limerick |
hdf1a |
Haute‑Fôret | Hannover | “a newer site, in France” | Hauts‑de‑France (Lille) | Helsinki |
pop1a |
Papeete | Pop!_OS (Amsterdam) 🤣 | “a Europe/Asia‑Pacific POP” | Vancouver | Paris‑Orly |
Function calling, through MCP or not, guarantees that the data really comes from the tool, not that the model interprets it correctly. It doesn't have the mapping between these codes and the cities, so it guesses, with a lot of aplomb 😅.
To fix that, we would have to give it the information: one more tool that details a location, or a more precise tool description. That's the whole challenge of selecting tools: neither too many, nor too few.
🔭 What's next?
Our example is deliberately minimalist: one server, one tool, one call, read-only. In a real application, a few points deserve your attention:
- the choice of tools: it's the client's responsibility, and filtering by name is just a start. You can also ask the user for confirmation before any tool that modifies something
- authentication 🔑: our examples use a token in a header. MCP also provides OAuth 2, which clients such as coding assistants can use to log you in with your account
- trust ⚠️: an MCP server is third-party code, which describes its own tools to the model. The descriptions and results of a malicious server can contain instructions aimed at the model (prompt injection), so choose your servers carefully
- transports: we used Streamable HTTP for a remote server, but many MCP servers run locally, launched by the client and driven through their standard input and output (
stdio)
You'll find more details about MCP here:
🏁 Conclusion
That's it for this introduction to MCP on the client side. Behind the acronym, we find the function calling of part 5, with a standard protocol to discover tools and have them run somewhere other than in our application. The model still only sees functions, it's our application that makes the link with the MCP server... and that decides what the model is allowed to do.
All the source code is available in the GitHub repository java-ai-area-blog.
If you made it this far, thanks for reading! If you spot any typos, feel free to open an issue or PR 😊.