☕️ Java à l'ère de l'IA 🤖 - partie 6 : MCP

🏴󠁧󠁢󠁥󠁮󠁧󠁿 You can find the English version of this article here 🏴󠁧󠁢󠁥󠁮󠁧󠁿.

TL;DR

🔌 Sixième article de la série sur l'IA dans vos applications Java ☕️, cette fois consacré à MCP (Model Context Protocol).
🤷 Avec le function calling, chaque application code ses propres outils. MCP permet de les récupérer, au moment de l'exécution, auprès d'un serveur qui les expose.
🧠 Le principe : le client MCP demande au serveur la liste de ses outils, les décrit au modèle comme de simples fonctions, puis fait exécuter par le serveur l'appel que le modèle demande.
⚠️ Le serveur MCP d'OVHcloud expose 471 outils, dont certains suppriment des choses : choisir ce que le modèle a le droit de voir est la responsabilité du client.
☕️ Le même use case est implémenté du plus bas niveau au plus haut : Bash, Java pur, les SDK OpenAI et MCP, LangChain4j, Quarkus et Spring AI.
🐙 Tous les exemples utilisent AI Endpoints et le serveur MCP d'OVHcloud, et sont disponibles ici.


📜 Introduction

Petit rappel des épisodes précédents : cet article fait partie d'une série d'articles visant à expliquer comment intégrer de l'IA dans les applications que nous développons en Java ☕️. Après les bases (partie 1), la mémoire (partie 2 et partie 3), le RAG (partie 4) et le function calling (partie 5), on continue avec ce qui avait été annoncé à la fin de l'article précédent : MCP.

🤷 Mais pourquoi MCP ?

Dans la partie 5, on a donné au modèle la possibilité de demander l'exécution d'une fonction get_room_capacity. Ça fonctionne très bien, mais la fonction, sa description et son exécution sont codées dans notre application.

Imaginons maintenant que l'on veuille donner à notre chatbot accès à l'API d'OVHcloud : lister ses serveurs, ses domaines, ses bases de données, ... Il faudrait écrire et décrire une fonction par appel d'API, puis recommencer dans la prochaine application, puis dans celle d'après 😩. Et chaque fournisseur de services ferait de même dans son coin, avec son propre format.

C'est le problème que résout le Model Context Protocol (MCP) : un protocole standard pour qu'un serveur expose des outils, et qu'une application quelconque, le client, puisse les découvrir et les utiliser. Les outils sont écrits une fois, par ceux qui connaissent le service, et n'importe quelle application compatible MCP peut s'en servir.

ℹ️ MCP ne se limite pas aux outils : un serveur peut aussi exposer des ressources (des données à lire) et des prompts. Dans cet article, on ne s'intéresse qu'aux outils, c'est de loin l'usage le plus courant.

Pour cet article, on va utiliser le serveur MCP d'OVHcloud, qui expose l'API d'OVHcloud sous forme d'outils, et lui poser une question simple : dans quelles localisations puis-je déployer un Hosted Private Cloud ?

🔑 Pour lancer les exemples, il vous faudra en plus du token AI Endpoints un token d'accès au serveur MCP.

🔎 Comment fonctionne MCP ?

Première chose importante à comprendre : le modèle ne sait pas ce qu'est MCP ⚠️. Il ne parle jamais au serveur MCP, et rien dans la requête qu'il reçoit ne dit qu'un outil vient d'un serveur MCP. Pour lui, c'est du function calling, exactement comme dans la partie 5.

Tout le travail est fait par notre application, le client MCP :

  1. elle ouvre une session avec le serveur MCP
  2. elle lui demande la liste de ses outils (tools/list)
  3. elle choisit ceux qu'elle veut proposer au modèle et les lui décrit, comme des fonctions
  4. quand le modèle demande un appel, elle le transmet au serveur MCP (tools/call)
  5. elle renvoie le résultat au modèle, qui rédige sa réponse

Les étapes 3 à 5 sont celles de la partie 5, seule l'exécution de l'outil change de place : elle se fait sur le serveur MCP, et plus dans notre code.

📡 Le protocole

MCP s'appuie sur JSON-RPC 2.0 : chaque message est un document JSON avec une méthode (method), des paramètres (params) et un identifiant (id) qui permet de relier la réponse à la requête. Pour un serveur distant comme celui d'OVHcloud, ces messages transitent en HTTP, avec le transport Streamable HTTP : un simple POST par message.

Tout commence par un handshake, décrit dans la spécification :

  • le client envoie une requête initialize, avec la version du protocole qu'il parle et ses capacités
  • le serveur répond, et lui attribue un identifiant de session dans l'en-tête HTTP Mcp-Session-Id, que le client doit ensuite répéter sur toutes ses requêtes
  • le client confirme avec une notification notifications/initialized (une notification n'a pas d'id : pas de réponse attendue)
// ➡️ 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: <identifiant de session>

// ➡️ POST https://mcp.eu.ovhcloud.com/mcp (avec l'en-tête Mcp-Session-Id)
{ "jsonrpc": "2.0", "method": "notifications/initialized" }

Ensuite, on peut demander la liste des outils avec tools/list. Chaque outil est décrit par un nom, une description et un JSON Schema de ses paramètres (inputSchema).

{
  "name": "list-dedicatedcloud-locations",
  "description": "List hosting locations",
  "inputSchema": {
    "properties": {},
    "type": "object"
  }
}

Pas de paramètre, une description minimaliste : on verra que le modèle s'en contente très bien.

Enfin, pour exécuter un outil, on utilise tools/call avec son nom et ses arguments :

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": { "name": "list-dedicatedcloud-locations", "arguments": {} }
}

Le serveur répond avec une liste de blocs de contenu (content), ici un seul bloc de texte contenant le résultat de l'appel à l'API d'OVHcloud.

🧰 471 outils 😱

En faisant notre tools/list, petite surprise : le serveur MCP d'OVHcloud expose 471 outils, soit environ 350 Ko de JSON Schema. Et tous ne se contentent pas de lire : un peu moins de 200 modifient quelque chose, dont 54 commencent par delete- 💥.

Donner tous ces outils au modèle serait une très mauvaise idée :

  • le coût 💸 : comme vu dans la partie 5, la description de chaque outil est envoyée à chaque appel au modèle, 350 Ko de description à chaque question, la facture et la fenêtre de contexte n'apprécieraient pas
  • la qualité 🎯 : plus il y a d'outils, plus le modèle a de chances de se tromper d'outil
  • la sécurité ⚠️ : le modèle pourrait décider, tout seul, d'appeler un outil qui supprime une ressource de votre compte

⚠️ Le serveur expose ce qu'il sait faire, c'est au client de choisir ce que le modèle a le droit de voir et d'appeler. Dans tous les exemples, on ne garde qu'un seul outil : list-dedicatedcloud-locations, qui ne fait que lire.

🖥️ La base : Bash

Comme pour les articles précédents, on commence avec curl et jq, pour bien voir ce qui transite, ici entre trois acteurs : notre script, le serveur MCP et le modèle.

#!/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'
  • ligne 25 : le seul outil que l'on va proposer au modèle
  • lignes 29 à 43 : le handshake, la requête initialize. On ne garde de la réponse que l'en-tête Mcp-Session-Id
  • lignes 51 à 58 : l'envoi d'un message au serveur MCP, avec le token et l'identifiant de session
  • ligne 61 : la notification qui termine le handshake
  • ligne 70 : la demande de la liste des outils
  • lignes 72 à 79 : on ne garde que notre outil, et on l'emballe dans le format attendu par l'API de chat : l'inputSchema de MCP devient directement les parameters de la fonction
  • ligne 110 : le premier appel au modèle, comme dans la partie 5
  • lignes 129 à 131 : un outil sans paramètre peut revenir avec des arguments vides, on les remplace par un objet vide
  • lignes 139 à 142 : on vérifie que le modèle demande bien l'outil qu'on lui a proposé
  • lignes 144 à 151 : l'appel de l'outil, cette fois sur le serveur MCP avec tools/call, dont on extrait le texte du résultat
  • lignes 159 à 163 : l'ajout de la demande d'appel et du résultat dans la conversation
  • ligne 169 : le deuxième appel au modèle

Et voici le résultat :

===== 🔌 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!

On retrouve bien nos 471 outils, dont un seul est passé au modèle. Le modèle demande l'appel de list-dedicatedcloud-locations avec des arguments vides, le serveur MCP appelle l'API d'OVHcloud (GET /v1/dedicatedCloud/location) et le modèle rédige sa réponse à partir de la liste des codes de localisation 🎉.

⚠️ Comme dans la partie 5, le script ne traite que la première demande d'appel, et ne boucle pas si le modèle en demande d'autres.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

☕️ Java

✍️ Pure Java

Passons à la version Java sans librairie, avec le HttpClient du JDK et 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());
}
  • ligne 30 : le seul outil que l'on va proposer au modèle
  • lignes 47 à 57 : le handshake, la requête initialize
  • lignes 59 à 63 : la récupération de l'identifiant de session dans l'en-tête de la réponse, d'où le besoin de garder la réponse HTTP brute
  • lignes 66 et 67 : la notification qui termine le handshake
  • lignes 76 et 77 : la demande de la liste des outils
  • lignes 79 à 92 : le filtre sur notre outil, et sa conversion au format de l'API de chat
  • ligne 109 : les outils sont ajoutés au corps de la requête
  • ligne 117 : le premier appel au modèle
  • lignes 135 à 139 : les arguments vides remplacés par un objet vide
  • lignes 147 à 150 : la vérification du nom de l'outil demandé
  • lignes 152 à 160 : l'appel de l'outil sur le serveur MCP avec tools/call
  • lignes 168 à 172 : l'ajout de la demande d'appel et du résultat dans la conversation
  • ligne 178 : le deuxième appel au modèle
  • lignes 186 à 196 : l'envoi d'un message au serveur MCP, avec l'identifiant de session dès qu'on en a un

Toujours aussi verbeux, mais tout est là : un client MCP, ce n'est finalement que quelques requêtes JSON-RPC 🤓.

===== 🔌 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.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

🛠️ Avec les SDK OpenAI et MCP

Le SDK OpenAI ne sait rien de MCP, on lui adjoint donc le SDK Java officiel de MCP, qui va gérer pour nous la session et les messages JSON-RPC.

///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);
}
  • lignes 4 à 7 : le SDK MCP, avec son support de Jackson 2 pour ne pas avoir deux versions de Jackson dans le classpath (le SDK OpenAI est en Jackson 2, le SDK MCP en Jackson 3 par défaut)
  • lignes 40 à 51 : la conversion d'un outil MCP en outil OpenAI. Contrairement à la partie 5, impossible de générer la description à partir d'une classe Java : le schéma n'est connu qu'à l'exécution, on le recopie donc clé par clé
  • lignes 80 à 87 : le transport Streamable HTTP, avec un customizer qui ajoute le token à chaque requête
  • lignes 89 et 90 : la création du client MCP, et le handshake avec initialize(). L'identifiant de session est ensuite géré par le transport
  • lignes 94 et 95 : la réponse du handshake nous donne le nom du serveur et la version du protocole négociée
  • lignes 99 à 103 : la liste des outils, filtrée et convertie
  • ligne 115 : l'ajout des outils dans la requête
  • ligne 125 : le premier appel au modèle
  • lignes 154 à 158 : la vérification du nom de l'outil demandé
  • lignes 160 à 163 : l'appel de l'outil sur le serveur MCP avec callTool, puis la fermeture de la session
  • ligne 166 : le résultat MCP est une liste de blocs de contenu, ici un bloc de texte
  • lignes 179 à 181 : l'ajout de la demande d'appel et du résultat dans la conversation
  • ligne 188 : le deuxième appel au modèle

Le SDK MCP nous débarrasse de la plomberie du protocole, mais l'orchestration reste à notre charge, comme dans la partie 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.

On voit au passage que le serveur s'appelle unified, en version 1.0.0, et qu'il parle la version 2025-03-26 du protocole.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

🦜 Avec LangChain4j

Avec LangChain4j et son module langchain4j-mcp, on retrouve la simplicité de la partie 5 : le framework prend tout en charge.

///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);
}
  • ligne 5 : le module MCP de LangChain4j
  • ligne 9 : Jackson modifie par réflexion des champs final des classes du protocole, ce que Java 26 signale par un avertissement, sauf si on l'autorise explicitement
  • ligne 48 : la liste des outils que l'on va proposer au modèle
  • ligne 58 : la réponse du modèle à partir du résultat de l'outil est longue à générer, le délai par défaut d'une minute ne suffit pas
  • lignes 65 à 70 : le transport Streamable HTTP, avec le token dans un en-tête
  • lignes 72 à 74 : le client MCP, qui se charge du handshake et de la session
  • lignes 83 à 86 : le McpToolProvider, qui liste les outils du serveur, ne garde que ceux dont le nom est dans notre liste, et les exécute quand le modèle le demande
  • ligne 101 : le tool provider est branché sur l'AI Service, à la place des .tools(...) de la partie 5
  • lignes 102 à 111 : les deux callbacks d'affichage, les mêmes que dans la partie 5
  • ligne 119 : l'appel à l'assistant

Il n'y a plus une seule ligne de code d'outil dans le fichier : l'outil vient du serveur, et LangChain4j fait le reste 🤯.

===== 🔌 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.

ℹ️ Pour voir les échanges JSON-RPC avec le serveur MCP, il suffit de décommenter les .logRequests(true) et .logResponses(true) du transport (lignes 68 et 69), en remplaçant slf4j-nop par slf4j-simple.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

⚡️ Avec Quarkus

Avec Quarkus, le serveur MCP se déclare dans la 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
  • ligne 11 : comme avec LangChain4j, on augmente le délai d'attente du modèle
  • lignes 15 à 17 : le serveur MCP, nommé ovhcloud : son transport, son URL et l'en-tête portant le token. Aucune ligne de Java n'ouvre la session

Côté code :

///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();
    }
}
  • ligne 10 : l'extension MCP de Quarkus LangChain4j
  • ligne 24 : le fichier mcp.properties est monté comme application.properties
  • lignes 48 à 64 : le filtre des outils. L'extension propose @McpToolBox pour donner les outils d'un serveur à un AI Service, mais elle les donne tous, sans filtre possible par configuration. On passe donc par un bean qui fournit un McpToolProvider filtré, comme avec LangChain4j
  • ligne 68 : ce fournisseur d'outils est branché sur l'AI Service
  • lignes 80 à 83 : le client MCP déclaré dans la configuration est un bean, que l'on peut injecter
  • ligne 98 : on s'en sert ici uniquement pour afficher la liste des outils
  • ligne 113 : l'appel, avec uniquement la question
  • lignes 121 à 129 : l'observer de ToolExecutedEvent de la partie 5, pour l'affichage

⚠️ Le bean qui fournit les outils doit être @ApplicationScoped, sinon Quarkus ne le trouve pas et le build échoue avec une UnsatisfiedResolutionException.

===== 🔌 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.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

☘️ Avec Spring AI

Pour finir, Spring AI, où le serveur MCP se déclare lui aussi dans la 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
  • lignes 8 à 12 : le serveur MCP d'OVHcloud nomme ses outils d'après les routes HTTP de l'API, avec des / et des {}, ce que la spécification MCP n'autorise pas. Spring AI affiche un avertissement pour chacun des 53 noms concernés, on fait donc taire le validateur
  • lignes 20 et 21 : la connexion au serveur MCP, nommée ovhcloud, avec son URL et son chemin
///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);
        };
    }
}
  • ligne 9 : le starter MCP client de Spring AI
  • lignes 47 à 66 : le ToolCallback qui affiche l'appel et le résultat, comme dans la partie 5
  • lignes 83 à 91 : la configuration de Spring AI ne permet pas d'ajouter un en-tête, le token passe donc par un customizer de requête, avec la même astuce de Content-Type qu'avec le SDK MCP (Spring AI s'appuie dessus)
  • lignes 95 à 98 : le filtre des outils. Spring AI détecte tout seul un bean McpToolFilter : les outils refusés ne sont jamais transformés en callbacks, et le modèle n'en entend jamais parler
  • lignes 101 à 104 : par défaut, Spring AI préfixe le nom des outils par le nom de la connexion, on le désactive pour garder le nom d'origine
  • lignes 107 à 110 : Spring AI fournit les outils MCP (SyncMcpToolCallbackProvider) et les clients MCP déjà initialisés
  • lignes 122 à 125 : les outils filtrés, enveloppés pour l'affichage
  • ligne 137 : les outils sont branchés sur le ChatClient. Le cast est nécessaire car les autres variantes de la méthode sont dépréciées
  • lignes 147 à 150 : l'appel, avec uniquement la 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.

Petite différence : Spring AI renvoie au modèle le résultat MCP tel quel, sous forme de liste de blocs de contenu, là où les autres n'en gardent que le texte. Le modèle, lui, s'en accommode très bien 😉.

Pour voir le source complet de cet exemple, c'est ici 📜.

📽️ Voyons ça en action !

🤥 Le modèle n'a pas (encore) tout compris

Si vous avez lu les réponses attentivement, vous avez peut-être tiqué. L'outil ne renvoie que des codes de localisation (rbx2a, lim1c, eri1c, ...), et c'est le modèle qui les traduit en villes. Pour rbx (Roubaix) ou sbg (Strasbourg), pas de souci, mais pour les autres, voici ce qu'il a répondu d'une exécution à l'autre :

Code Bash Java pur LangChain4j Quarkus Spring AI
lim1c Limoges Limerick Lima Limoges Limerick
hdf1a Haute‑Fôret Hannover « un site plus récent, en France » Hauts‑de‑France (Lille) Helsinki
pop1a Papeete Pop!_OS (Amsterdam) 🤣 « un POP Europe/Asie‑Pacifique » Vancouver Paris‑Orly

Le function calling, qu'il passe par MCP ou non, garantit que les données viennent bien de l'outil, pas que le modèle les interprète correctement. Il n'a pas la correspondance entre ces codes et les villes, alors il devine, avec beaucoup d'aplomb 😅.

Pour corriger ça, il faudrait lui donner l'information : un outil de plus qui détaille une localisation, ou une description d'outil plus précise. C'est tout l'enjeu de la sélection des outils : ni trop, ni trop peu.

🔭 Et après ?

Notre exemple est volontairement minimaliste : un serveur, un outil, un appel, en lecture seule. Dans une vraie application, quelques points méritent votre attention :

  • le choix des outils : c'est la responsabilité du client, et le filtre par nom n'est qu'un début. On peut aussi demander une confirmation à l'utilisateur avant tout outil qui modifie quelque chose
  • l'authentification 🔑 : nos exemples utilisent un token dans un en-tête. MCP prévoit aussi OAuth 2, que les clients comme les assistants de code savent utiliser pour vous connecter avec votre compte
  • la confiance ⚠️ : un serveur MCP est du code tiers, qui décrit lui-même ses outils au modèle. Les descriptions et les résultats d'un serveur malveillant peuvent contenir des instructions destinées au modèle (prompt injection), il faut donc choisir ses serveurs avec soin
  • les transports : on a utilisé Streamable HTTP pour un serveur distant, mais beaucoup de serveurs MCP tournent en local, lancés par le client et pilotés par leur entrée et sortie standard (stdio)

Vous retrouverez les détails sur MCP ici :

🏁 Conclusion

Voilà pour cette introduction à MCP côté client. Derrière l'acronyme, on retrouve le function calling de la partie 5, avec un protocole standard pour découvrir les outils et les faire exécuter ailleurs que dans notre application. Le modèle ne voit toujours que des fonctions, c'est notre application qui fait le lien avec le serveur MCP... et qui décide de ce que le modèle a le droit de faire.

L'ensemble du code source est disponible dans le dépôt GitHub java-ai-area-blog.

Si vous êtes arrivés jusque-là, merci de m'avoir lu et s'il y a des coquilles n'hésitez pas à me faire une issue ou PR 😊.