This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 5b6d67794f09 CAMEL-27125: re-resolve OAuth token on every request
instead of once at startup (#30707)
5b6d67794f09 is described below
commit 5b6d67794f098c033a589c7838aaf1dc8ebec604
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 30 11:51:30 2026 +0100
CAMEL-27125: re-resolve OAuth token on every request instead of once at
startup (#30707)
The OAuth token of oauthProfile is now resolved for every request instead
of once at startup, so a short-lived
token is refreshed after it expires: camel-openai (OpenAI client and MCP
transports), camel-langchain4j-agent
(MCP transports) and camel-spring-ai-chat. In camel-openai, oauthProfile
now takes precedence over apiKey
(upgrade guide 4.25). Tests cover a token that rotates within one MCP
session.
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
---
.../catalog/docs/langchain4j-agent-component.adoc | 12 +-
.../camel/catalog/docs/openai-component.adoc | 4 +-
.../src/main/docs/langchain4j-agent-component.adoc | 12 +-
.../agent/LangChain4jMcpServerDefinition.java | 31 +-
.../agent/LangChain4jMcpOAuthTokenRefreshTest.java | 244 +++++++++++++
.../StubOAuthClientAuthenticationFactory.java | 40 ++-
.../camel/oauth-client-authentication-factory | 17 +
.../src/main/docs/openai-component.adoc | 4 +-
.../camel/component/openai/OpenAIEndpoint.java | 70 ++--
.../openai/OpenAIClientConfigurationTest.java | 25 ++
.../openai/OpenAIClientOAuthTokenRefreshTest.java | 123 +++++++
.../openai/OpenAIMcpOAuthTokenRefreshTest.java | 274 ++++++++++++++
.../StubOAuthClientAuthenticationFactory.java | 40 ++-
.../camel/oauth-client-authentication-factory | 17 +
.../springai/chat/mcp/SpringAiChatMcpManager.java | 43 ++-
.../chat/SpringAiChatMcpOAuthTokenRefreshTest.java | 394 +++++++++++++++++++++
.../chat/StubOAuthClientAuthenticationFactory.java | 38 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc | 12 +
18 files changed, 1339 insertions(+), 61 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-agent-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-agent-component.adoc
index 50deed443600..f617a4d8d908 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-agent-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/langchain4j-agent-component.adoc
@@ -125,10 +125,18 @@ The langchain4j-agent component accepts a pre-built
`Agent` or `ChatModel` bean
._Java-only: programmatic `ChatModel` bean registration with `OAuthHelper`_
[source,java]
----
-String token = OAuthHelper.resolveOAuthToken(getContext(), "azure");
+CamelContext context = getContext();
+String profile = "azure";
ChatModel chatModel = OpenAiChatModel.builder()
- .apiKey(token)
+ .customHeaders(() -> {
+ try {
+ String token = OAuthHelper.resolveOAuthToken(context, profile);
+ return Map.of("Authorization", "Bearer " + token);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to resolve OAuth token for
profile: " + profile, e);
+ }
+ })
.modelName("gpt-4")
.build();
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openai-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openai-component.adoc
index 9127ac23573e..035a2ca604c1 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openai-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openai-component.adoc
@@ -123,13 +123,15 @@ include::partial$component-endpoint-headers.adoc[]
Set `baseUrl` to your providers endpoint (default:
`https://api.openai.com/v1`).
-API key resolution order:
+API key resolution order (when no `oauthProfile` is set):
- Endpoint `apiKey`
- Component `apiKey`
- Environment variable `OPENAI_API_KEY`
- System property `openai.api.key`
+When `oauthProfile` is set, it takes precedence over all of the above and the
API key is not used.
+
[NOTE]
====
The API key can be omitted for an OpenAI-compatible server that checks no key,
such as a local Ollama, vLLM or LM
diff --git
a/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc
b/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc
index 50deed443600..f617a4d8d908 100644
---
a/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc
+++
b/components/camel-ai/camel-langchain4j-agent/src/main/docs/langchain4j-agent-component.adoc
@@ -125,10 +125,18 @@ The langchain4j-agent component accepts a pre-built
`Agent` or `ChatModel` bean
._Java-only: programmatic `ChatModel` bean registration with `OAuthHelper`_
[source,java]
----
-String token = OAuthHelper.resolveOAuthToken(getContext(), "azure");
+CamelContext context = getContext();
+String profile = "azure";
ChatModel chatModel = OpenAiChatModel.builder()
- .apiKey(token)
+ .customHeaders(() -> {
+ try {
+ String token = OAuthHelper.resolveOAuthToken(context, profile);
+ return Map.of("Authorization", "Bearer " + token);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to resolve OAuth token for
profile: " + profile, e);
+ }
+ })
.modelName("gpt-4")
.build();
diff --git
a/components/camel-ai/camel-langchain4j-agent/src/main/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpServerDefinition.java
b/components/camel-ai/camel-langchain4j-agent/src/main/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpServerDefinition.java
index 1b61474006fd..ab4fe5cfe142 100644
---
a/components/camel-ai/camel-langchain4j-agent/src/main/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpServerDefinition.java
+++
b/components/camel-ai/camel-langchain4j-agent/src/main/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpServerDefinition.java
@@ -217,15 +217,17 @@ public class LangChain4jMcpServerDefinition {
return clientBuilder.build();
}
+ /**
+ * Builds the MCP transport for this server definition.
+ *
+ * <p>
+ * When an {@code oauthProfile} is configured, the OAuth token is resolved
lazily via a {@code Supplier} on every
+ * outgoing request rather than eagerly at startup. This enables
short-lived tokens to be refreshed when they
+ * expire, at the cost of deferring misconfiguration errors (wrong profile
name, unreachable OIDC server) to the
+ * first request rather than surfacing them at endpoint start.
+ */
@SuppressWarnings("deprecation")
private McpTransport buildTransport(CamelContext camelContext) throws
Exception {
- // Resolve OAuth token for HTTP-based transports
- Map<String, String> authHeaders = null;
- if (oauthProfile != null && !oauthProfile.isBlank() && camelContext !=
null) {
- String token = OAuthHelper.resolveOAuthToken(camelContext,
oauthProfile);
- authHeaders = Map.of("Authorization", "Bearer " + token);
- }
-
if ("http".equalsIgnoreCase(transportType) ||
"streamableHttp".equalsIgnoreCase(transportType)) {
if (url == null || url.trim().isEmpty()) {
throw new IllegalArgumentException("URL is required for HTTP
MCP transport");
@@ -235,8 +237,19 @@ public class LangChain4jMcpServerDefinition {
.logRequests(logRequests)
.logResponses(logResponses)
.timeout(timeout);
- if (authHeaders != null) {
- builder.customHeaders(authHeaders);
+ if (oauthProfile != null && !oauthProfile.isBlank() &&
camelContext != null) {
+ // Use a Supplier so the token is re-resolved on every request,
+ // allowing short-lived OAuth tokens to be refreshed when they
expire.
+ final String profile = oauthProfile;
+ final CamelContext ctx = camelContext;
+ builder.customHeaders(() -> {
+ try {
+ String token = OAuthHelper.resolveOAuthToken(ctx,
profile);
+ return Map.of("Authorization", "Bearer " + token);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to resolve OAuth
token for profile: " + profile, e);
+ }
+ });
}
return builder.build();
} else if ("stdio".equalsIgnoreCase(transportType)) {
diff --git
a/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpOAuthTokenRefreshTest.java
b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpOAuthTokenRefreshTest.java
new file mode 100644
index 000000000000..23eb5bcf259b
--- /dev/null
+++
b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/LangChain4jMcpOAuthTokenRefreshTest.java
@@ -0,0 +1,244 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.langchain4j.agent;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import dev.langchain4j.mcp.client.McpClient;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Verifies that a changed OAuth token is picked up on the next MCP request,
proving that the {@code customHeaders}
+ * supplier is called per-request rather than once at startup.
+ */
+class LangChain4jMcpOAuthTokenRefreshTest {
+
+ private static final String PROFILE = "refresh-test";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final List<String> RECORDED_AUTHORIZATIONS = new
CopyOnWriteArrayList<>();
+
+ private static ExecutorService executor;
+ private static HttpServer httpServer;
+ private static String serverUrl;
+
+ @BeforeAll
+ static void startMcpServer() throws Exception {
+ InetAddress loopback = InetAddress.getLoopbackAddress();
+ executor = Executors.newCachedThreadPool();
+ httpServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
+ httpServer.createContext("/mcp",
LangChain4jMcpOAuthTokenRefreshTest::handleMcpRequest);
+ httpServer.setExecutor(executor);
+ httpServer.start();
+ serverUrl = new URI("http", null, loopback.getHostAddress(),
httpServer.getAddress().getPort(), "/mcp", null, null)
+ .toString();
+ }
+
+ @AfterAll
+ static void stopMcpServer() {
+ if (httpServer != null) {
+ httpServer.stop(0);
+ }
+ if (executor != null) {
+ executor.shutdownNow();
+ }
+ }
+
+ @AfterEach
+ void resetStub() {
+ StubOAuthClientAuthenticationFactory.reset(PROFILE);
+ RECORDED_AUTHORIZATIONS.clear();
+ }
+
+ /**
+ * The supplier returns token-1 for the first request (initialize) and
token-2 for the second request (tools/list),
+ * both within the same MCP session. This proves that the {@code
customHeaders} supplier is called on every HTTP
+ * request rather than once at client creation: the per-request supplier
causes each POST to re-invoke it, so a
+ * rotated token appears immediately on the very next request on the same
open connection.
+ */
+ @Test
+ void tokenSupplierIsCalledPerRequestWithinSameSession() throws Exception {
+ // Rotating supplier: first call → token-1 (initialize), second call →
token-2 (tools/list)
+ StubOAuthClientAuthenticationFactory.registerRotating(PROFILE,
"token-1", "token-2");
+
+ try (DefaultCamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.start();
+
+ LangChain4jMcpServerDefinition def = createDefinition();
+ McpClient client = def.buildClient(camelContext);
+ try {
+ assertThat(client.listTools()).isNotNull();
+ } finally {
+ client.close();
+ }
+ // The session sends at least two POSTs (initialize + tools/list).
With per-request resolution the tokens
+ // rotate across requests; without it every request would carry
the same value baked at client creation.
+ assertThat(RECORDED_AUTHORIZATIONS).hasSizeGreaterThanOrEqualTo(2);
+ assertThat(RECORDED_AUTHORIZATIONS.get(0)).isEqualTo("Bearer
token-1");
+ assertThat(RECORDED_AUTHORIZATIONS.get(1)).isEqualTo("Bearer
token-2");
+ }
+ }
+
+ /**
+ * The stub returns token-1 for the first session and then token-2 for the
second session. All requests in the first
+ * MCP session carry token-1; all requests in the second session carry
token-2, proving per-request resolution.
+ */
+ @Test
+ void tokenChangeBetweenSessionsIsPickedUp() throws Exception {
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE, "token-1");
+
+ try (DefaultCamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.start();
+
+ // First session: initializes and lists tools — all requests carry
token-1
+ LangChain4jMcpServerDefinition def1 = createDefinition();
+ McpClient client1 = def1.buildClient(camelContext);
+ try {
+ assertThat(client1.listTools()).isNotNull();
+ } finally {
+ client1.close();
+ }
+ List<String> firstSessionAuths =
List.copyOf(RECORDED_AUTHORIZATIONS);
+ assertThat(firstSessionAuths).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-1"));
+
+ RECORDED_AUTHORIZATIONS.clear();
+
+ // Switch the token the stub returns
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE,
"token-2");
+
+ // Second session: the stub now returns token-2
+ LangChain4jMcpServerDefinition def2 = createDefinition();
+ McpClient client2 = def2.buildClient(camelContext);
+ try {
+ assertThat(client2.listTools()).isNotNull();
+ } finally {
+ client2.close();
+ }
+ assertThat(RECORDED_AUTHORIZATIONS).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-2"));
+ }
+ }
+
+ private LangChain4jMcpServerDefinition createDefinition() {
+ LangChain4jMcpServerDefinition def = new
LangChain4jMcpServerDefinition();
+ def.setServerName("token-refresh-test");
+ def.setTransportType("http");
+ def.setUrl(serverUrl);
+ def.setOauthProfile(PROFILE);
+ return def;
+ }
+
+ /**
+ * A minimal MCP Streamable HTTP handler that records the Authorization
header and responds to initialize and
+ * tools/list JSON-RPC requests.
+ */
+ private static void handleMcpRequest(HttpExchange exchange) throws
IOException {
+ try {
+ String httpMethod = exchange.getRequestMethod();
+ String authorization =
exchange.getRequestHeaders().getFirst("Authorization");
+ if (authorization != null && "POST".equals(httpMethod)) {
+ RECORDED_AUTHORIZATIONS.add(authorization);
+ }
+
+ if (!"POST".equals(httpMethod)) {
+ exchange.sendResponseHeaders(405, -1);
+ return;
+ }
+
+ String body = new String(exchange.getRequestBody().readAllBytes(),
StandardCharsets.UTF_8);
+ JsonNode message = MAPPER.readTree(body);
+ String method = message.path("method").asText("");
+ Object id = message.has("id") ? message.get("id") : null;
+
+ if (id == null) {
+ // notification
+ exchange.sendResponseHeaders(202, -1);
+ return;
+ }
+
+ ObjectNode response = MAPPER.createObjectNode();
+ response.put("jsonrpc", "2.0");
+ response.set("id", message.get("id"));
+
+ switch (method) {
+ case "initialize" -> {
+ ObjectNode result = MAPPER.createObjectNode();
+ result.put("protocolVersion", "2024-11-05");
+ ObjectNode capabilities = MAPPER.createObjectNode();
+ ObjectNode tools = MAPPER.createObjectNode();
+ tools.put("listChanged", false);
+ capabilities.set("tools", tools);
+ result.set("capabilities", capabilities);
+ ObjectNode serverInfo = MAPPER.createObjectNode();
+ serverInfo.put("name", "token-refresh-test-server");
+ serverInfo.put("version", "1.0.0");
+ result.set("serverInfo", serverInfo);
+ response.set("result", result);
+ }
+ case "tools/list" -> {
+ ObjectNode result = MAPPER.createObjectNode();
+ ArrayNode toolsArray = MAPPER.createArrayNode();
+ ObjectNode echoTool = MAPPER.createObjectNode();
+ echoTool.put("name", "echo");
+ echoTool.put("description", "Echoes the message");
+ ObjectNode inputSchema = MAPPER.createObjectNode();
+ inputSchema.put("type", "object");
+ echoTool.set("inputSchema", inputSchema);
+ toolsArray.add(echoTool);
+ result.set("tools", toolsArray);
+ response.set("result", result);
+ }
+ default -> {
+ ObjectNode error = MAPPER.createObjectNode();
+ error.put("code", -32601);
+ error.put("message", "Method not found: " + method);
+ response.set("error", error);
+ }
+ }
+
+ byte[] json = MAPPER.writeValueAsBytes(response);
+ exchange.getResponseHeaders().set("Content-Type",
"application/json");
+ exchange.sendResponseHeaders(200, json.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(json);
+ }
+ } finally {
+ exchange.close();
+ }
+ }
+}
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/StubOAuthClientAuthenticationFactory.java
similarity index 52%
copy from
components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
copy to
components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/StubOAuthClientAuthenticationFactory.java
index cd9b0247358e..c5186e03cef3 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
+++
b/components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/StubOAuthClientAuthenticationFactory.java
@@ -14,7 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.component.springai.chat;
+package org.apache.camel.component.langchain4j.agent;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.OAuthClientAuthenticationFactory;
@@ -23,9 +28,39 @@ import org.apache.camel.spi.OAuthClientConfig;
/**
* Stands in for camel-oauth in tests: returns a fixed token per profile,
without calling a token endpoint. Registered
* in {@code
META-INF/services/org/apache/camel/oauth-client-authentication-factory}.
+ *
+ * <p>
+ * Tests that need rotating tokens can call {@link #registerRotating(String,
String...)} before the test and
+ * {@link #reset(String)} after.
*/
public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenticationFactory {
+ private static final Map<String, Supplier<String>> TOKEN_SUPPLIERS = new
ConcurrentHashMap<>();
+
+ /**
+ * Registers a rotating token sequence for the given profile. Successive
calls to
+ * {@link #resolveToken(CamelContext, String)} return the tokens in order;
the last token is repeated.
+ */
+ static void registerRotating(String profileName, String... tokens) {
+ AtomicInteger idx = new AtomicInteger(0);
+ TOKEN_SUPPLIERS.put(profileName, () ->
tokens[Math.min(idx.getAndIncrement(), tokens.length - 1)]);
+ }
+
+ /**
+ * Registers a fixed token that can be changed later with another call.
Use this when the exact number of requests
+ * per session is unknown and each session must carry a specific token.
+ */
+ static void registerFixed(String profileName, String token) {
+ TOKEN_SUPPLIERS.put(profileName, () -> token);
+ }
+
+ /**
+ * Removes any rotating token supplier for the given profile, reverting to
the default fixed-token behavior.
+ */
+ static void reset(String profileName) {
+ TOKEN_SUPPLIERS.remove(profileName);
+ }
+
static String tokenFor(String profileName) {
return "token-for-" + profileName;
}
@@ -37,7 +72,8 @@ public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenti
@Override
public String resolveToken(CamelContext context, String profileName) {
- return tokenFor(profileName);
+ Supplier<String> supplier = TOKEN_SUPPLIERS.get(profileName);
+ return supplier != null ? supplier.get() : tokenFor(profileName);
}
@Override
diff --git
a/components/camel-ai/camel-langchain4j-agent/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
b/components/camel-ai/camel-langchain4j-agent/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
new file mode 100644
index 000000000000..18f11ac13477
--- /dev/null
+++
b/components/camel-ai/camel-langchain4j-agent/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+class=org.apache.camel.component.langchain4j.agent.StubOAuthClientAuthenticationFactory
diff --git
a/components/camel-ai/camel-openai/src/main/docs/openai-component.adoc
b/components/camel-ai/camel-openai/src/main/docs/openai-component.adoc
index 9127ac23573e..035a2ca604c1 100644
--- a/components/camel-ai/camel-openai/src/main/docs/openai-component.adoc
+++ b/components/camel-ai/camel-openai/src/main/docs/openai-component.adoc
@@ -123,13 +123,15 @@ include::partial$component-endpoint-headers.adoc[]
Set `baseUrl` to your providers endpoint (default:
`https://api.openai.com/v1`).
-API key resolution order:
+API key resolution order (when no `oauthProfile` is set):
- Endpoint `apiKey`
- Component `apiKey`
- Environment variable `OPENAI_API_KEY`
- System property `openai.api.key`
+When `oauthProfile` is set, it takes precedence over all of the above and the
API key is not used.
+
[NOTE]
====
The API key can be omitted for an OpenAI-compatible server that checks no key,
such as a local Ollama, vLLM or LM
diff --git
a/components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIEndpoint.java
b/components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIEndpoint.java
index 2f5155c9cc23..33d24dde0640 100644
---
a/components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIEndpoint.java
+++
b/components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIEndpoint.java
@@ -19,7 +19,6 @@ package org.apache.camel.component.openai;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URISyntaxException;
-import java.net.http.HttpRequest;
import java.security.KeyStore;
import java.time.Duration;
import java.util.ArrayList;
@@ -44,6 +43,7 @@ import javax.net.ssl.X509TrustManager;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.Timeout;
+import com.openai.credential.BearerTokenCredential;
import com.openai.models.chat.completions.ChatCompletionFunctionTool;
import com.openai.models.decisions.Decision;
import com.openai.models.decisions.DecisionCreateParams;
@@ -53,6 +53,7 @@ import
io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
+import
io.modelcontextprotocol.client.transport.customizer.McpSyncHttpClientRequestCustomizer;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.spec.McpClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
@@ -520,13 +521,20 @@ public class OpenAIEndpoint extends DefaultEndpoint {
private McpClientTransport createMcpTransport(String serverName, String
transportType, Map<String, String> props)
throws Exception {
- // Resolve per-server OAuth token if configured
+ // Build a per-request customizer so the OAuth token is re-resolved on
every request,
+ // allowing short-lived tokens to be refreshed when they expire.
String mcpOauthProfile = props.get("oauthProfile");
- HttpRequest.Builder authRequestBuilder = null;
+ McpSyncHttpClientRequestCustomizer oauthCustomizer = null;
if (ObjectHelper.isNotEmpty(mcpOauthProfile)) {
- String token = OAuthHelper.resolveOAuthToken(getCamelContext(),
mcpOauthProfile);
- authRequestBuilder = HttpRequest.newBuilder()
- .header("Authorization", "Bearer " + token);
+ oauthCustomizer = (requestBuilder, method, uri, body, context) -> {
+ try {
+ String token =
OAuthHelper.resolveOAuthToken(getCamelContext(), mcpOauthProfile);
+ requestBuilder.header("Authorization", "Bearer " + token);
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "Failed to resolve OAuth token for MCP server '" +
serverName + "': " + e.getMessage(), e);
+ }
+ };
}
return switch (transportType) {
@@ -550,8 +558,8 @@ public class OpenAIEndpoint extends DefaultEndpoint {
McpServerUrl serverUrl = splitMcpServerUrl(serverName, url,
DEFAULT_SSE_ENDPOINT);
HttpClientSseClientTransport.Builder sseBuilder =
HttpClientSseClientTransport.builder(serverUrl.baseUri())
.sseEndpoint(serverUrl.endpoint());
- if (authRequestBuilder != null) {
- sseBuilder.requestBuilder(authRequestBuilder);
+ if (oauthCustomizer != null) {
+ sseBuilder.addHttpRequestCustomizer(oauthCustomizer);
}
yield sseBuilder.build();
}
@@ -569,8 +577,8 @@ public class OpenAIEndpoint extends DefaultEndpoint {
if (protocolVersions != null) {
transportBuilder.supportedProtocolVersions(protocolVersions);
}
- if (authRequestBuilder != null) {
- transportBuilder.requestBuilder(authRequestBuilder);
+ if (oauthCustomizer != null) {
+ transportBuilder.addHttpRequestCustomizer(oauthCustomizer);
}
yield transportBuilder.build();
}
@@ -937,17 +945,30 @@ public class OpenAIEndpoint extends DefaultEndpoint {
private static final String NO_API_KEY = "camel-openai-no-api-key";
protected OpenAIClient createClient() throws Exception {
- String apiKey = resolveApiKey();
-
OpenAIOkHttpClient.Builder builder = OpenAIOkHttpClient.builder();
- if (ObjectHelper.isNotEmpty(apiKey)) {
- builder.apiKey(apiKey);
+ if (ObjectHelper.isNotEmpty(configuration.getOauthProfile())) {
+ // Use a Supplier-based credential so the token is re-resolved on
every request,
+ // allowing short-lived OAuth tokens to be refreshed when they
expire.
+ String profile = configuration.getOauthProfile();
+ builder.credential(BearerTokenCredential.create(
+ () -> {
+ try {
+ return
OAuthHelper.resolveOAuthToken(getCamelContext(), profile);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to resolve
OAuth token for profile: " + profile, e);
+ }
+ }));
} else {
- // no key, such as for a local server (Ollama, vLLM, LM Studio):
the SDK needs a credential, so a placeholder
- // is given, and its Authorization header is removed, so the
requests are sent without one
- builder.apiKey(NO_API_KEY);
- builder.removeHeaders("Authorization");
+ String apiKey = resolveApiKey();
+ if (ObjectHelper.isNotEmpty(apiKey)) {
+ builder.apiKey(apiKey);
+ } else {
+ // no key, such as for a local server (Ollama, vLLM, LM
Studio): the SDK needs a credential, so a
+ // placeholder is given, and its Authorization header is
removed, so the requests are sent without one
+ builder.apiKey(NO_API_KEY);
+ builder.removeHeaders("Authorization");
+ }
}
builder.baseUrl(ObjectHelper.notNullOrEmpty(configuration.getBaseUrl(),
"baseUrl"));
@@ -1098,16 +1119,13 @@ public class OpenAIEndpoint extends DefaultEndpoint {
}
protected String resolveApiKey() throws Exception {
- // Priority: URI parameter > OAuth profile > environment variable >
system property
+ // Priority: configuration property (apiKey) > environment variable >
system property
+ // OAuth profile is handled separately in createClient() via
BearerTokenCredential.create(Supplier)
+ // so that tokens are re-resolved on every request rather than once at
startup.
if (ObjectHelper.isNotEmpty(configuration.getApiKey())) {
return configuration.getApiKey();
}
- // Try OAuth profile if configured
- if (ObjectHelper.isNotEmpty(configuration.getOauthProfile())) {
- return resolveOAuthToken();
- }
-
String envApiKey = System.getenv("OPENAI_API_KEY");
if (ObjectHelper.isNotEmpty(envApiKey)) {
return envApiKey;
@@ -1116,10 +1134,6 @@ public class OpenAIEndpoint extends DefaultEndpoint {
return System.getProperty("openai.api.key");
}
- private String resolveOAuthToken() throws Exception {
- return OAuthHelper.resolveOAuthToken(getCamelContext(),
configuration.getOauthProfile());
- }
-
public OpenAIOperations getOperation() {
return operation;
}
diff --git
a/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientConfigurationTest.java
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientConfigurationTest.java
index afe36b6ef9a7..82f9b6cfc0ab 100644
---
a/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientConfigurationTest.java
+++
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientConfigurationTest.java
@@ -24,6 +24,7 @@ import java.util.Map;
import com.openai.client.OpenAIClient;
import com.openai.core.ClientOptions;
import com.openai.core.Timeout;
+import com.openai.credential.BearerTokenCredential;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
@@ -34,6 +35,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import tools.jackson.databind.ObjectMapper;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -271,6 +273,29 @@ class OpenAIClientConfigurationTest extends
CamelTestSupport {
};
}
+ /**
+ * When both {@code oauthProfile} and {@code apiKey} are configured,
{@code oauthProfile} takes precedence. The
+ * resulting client must use a {@link BearerTokenCredential} (OAuth), not
an API-key credential.
+ */
+ @Test
+ void oauthProfileTakesPrecedenceOverApiKey() throws Exception {
+ OpenAIEndpoint endpoint = (OpenAIEndpoint) context()
+
.getEndpoint("openai:chat-completion?apiKey=explicit-key&oauthProfile=prec-test");
+
+ OpenAIClient client = endpoint.createClient();
+ try {
+ ClientOptions options = clientOptions(client);
+ assertThat(options.credential())
+ .as("oauthProfile must win over an explicit apiKey")
+ .isInstanceOf(BearerTokenCredential.class);
+ assertThat(((BearerTokenCredential) options.credential()).token())
+ .as("oauthProfile must win over an explicit apiKey")
+
.isEqualTo(StubOAuthClientAuthenticationFactory.tokenFor("prec-test"));
+ } finally {
+ client.close();
+ }
+ }
+
private OpenAIEndpoint createEndpoint() throws Exception {
OpenAIEndpoint endpoint = (OpenAIEndpoint)
context().getEndpoint("openai:chat-completion?apiKey=dummy");
endpoint.getConfiguration().setAdditionalHeader(null);
diff --git
a/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientOAuthTokenRefreshTest.java
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientOAuthTokenRefreshTest.java
new file mode 100644
index 000000000000..0448f2049f5c
--- /dev/null
+++
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIClientOAuthTokenRefreshTest.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.openai;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Verifies that the OpenAI direct client (chat-completion, decisions)
re-resolves the OAuth token on every request
+ * rather than baking it in at client-creation time. The test registers a
{@link StubOAuthClientAuthenticationFactory}
+ * via the service-loader mechanism and swaps the token between two requests
to prove per-request resolution.
+ */
+class OpenAIClientOAuthTokenRefreshTest extends CamelTestSupport {
+
+ private static final String PROFILE = "client-refresh-test";
+
+ private static final String COMPLETION = """
+
{"id":"chatcmpl-1","object":"chat.completion","created":0,"model":"stub",
+
"choices":[{"index":0,"message":{"role":"assistant","content":"ok"},
+ "finish_reason":"stop"}]}
+ """;
+
+ private static HttpServer server;
+ private static final List<String> recordedAuthorizations = new
CopyOnWriteArrayList<>();
+
+ @BeforeAll
+ static void startServer() throws IOException {
+ server = HttpServer.create(new
InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ server.createContext("/v1/chat/completions",
OpenAIClientOAuthTokenRefreshTest::reply);
+ server.start();
+ }
+
+ @AfterAll
+ static void stopServer() {
+ if (server != null) {
+ server.stop(0);
+ }
+ }
+
+ @AfterEach
+ void resetStub() {
+ StubOAuthClientAuthenticationFactory.reset(PROFILE);
+ recordedAuthorizations.clear();
+ }
+
+ private static void reply(HttpExchange exchange) throws IOException {
+ String authorization =
exchange.getRequestHeaders().getFirst("Authorization");
+ recordedAuthorizations.add(authorization != null ? authorization : "");
+ byte[] body = COMPLETION.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.sendResponseHeaders(200, body.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(body);
+ }
+ exchange.close();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ String baseUrl = "http://localhost:" + server.getAddress().getPort() +
"/v1";
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:oauth")
+ .to("openai:chat-completion?model=stub&oauthProfile="
+ PROFILE + "&baseUrl=" + baseUrl);
+ }
+ };
+ }
+
+ /**
+ * The stub returns token-1 for the first request and then token-2 for the
second. The OpenAI client must re-resolve
+ * the credential on every request so that an expired token is not reused.
+ */
+ @Test
+ void tokenChangeBetweenRequestsIsPickedUp() {
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE, "token-1");
+
+ template.requestBody("direct:oauth", "Hello", String.class);
+
+ assertThat(recordedAuthorizations).as("first request")
+ .containsExactly("Bearer token-1");
+
+ recordedAuthorizations.clear();
+
+ // Rotate the token — the credential supplier must be called again on
the next request
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE, "token-2");
+
+ template.requestBody("direct:oauth", "Hello again", String.class);
+
+ assertThat(recordedAuthorizations).as("second request after token
rotation")
+ .containsExactly("Bearer token-2");
+ }
+}
diff --git
a/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIMcpOAuthTokenRefreshTest.java
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIMcpOAuthTokenRefreshTest.java
new file mode 100644
index 000000000000..b3407e981335
--- /dev/null
+++
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/OpenAIMcpOAuthTokenRefreshTest.java
@@ -0,0 +1,274 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.openai;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import io.modelcontextprotocol.client.McpSyncClient;
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.json.McpJsonDefaults;
+import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.server.McpServer;
+import io.modelcontextprotocol.server.McpStatelessServerFeatures;
+import io.modelcontextprotocol.server.McpStatelessServerHandler;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
+import io.modelcontextprotocol.spec.McpSchema;
+import io.modelcontextprotocol.spec.McpStatelessServerTransport;
+import io.modelcontextprotocol.spec.ProtocolVersions;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Verifies that a changed OAuth token is picked up on the next MCP request,
proving that the token supplier is called
+ * per-request rather than once at startup.
+ */
+class OpenAIMcpOAuthTokenRefreshTest {
+
+ private static final String PROFILE = "refresh-test";
+ private static final Set<String> SERVED_PATHS = Set.of("/mcp");
+ private static final List<String> RECORDED_AUTHORIZATIONS = new
CopyOnWriteArrayList<>();
+
+ private static ExecutorService executor;
+ private static HttpServer httpServer;
+ private static McpStatelessSyncServer mcpServer;
+ private static String serverUrl;
+
+ @BeforeAll
+ static void startMcpServer() throws Exception {
+ McpJsonMapper jsonMapper = McpJsonDefaults.getMapper();
+ RecordingTransport transport = new RecordingTransport(jsonMapper);
+
+ McpSchema.Tool echo = McpSchema.Tool.builder("echo",
+ Map.of("type", "object",
+ "properties", Map.of("message", Map.of("type",
"string")),
+ "required", List.of("message")))
+ .description("Echoes the message")
+ .build();
+ mcpServer = McpServer.sync(transport)
+ .serverInfo("token-refresh-test-server", "1.0.0")
+
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
+
.tools(McpStatelessServerFeatures.SyncToolSpecification.builder()
+ .tool(echo)
+ .callHandler((context, request) ->
McpSchema.CallToolResult.builder(List.of(
+ McpSchema.TextContent.builder("echo: " +
request.arguments().get("message")).build()))
+ .build())
+ .build())
+ .build();
+
+ InetAddress loopback = InetAddress.getLoopbackAddress();
+ executor = Executors.newCachedThreadPool();
+ httpServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
+ httpServer.createContext("/", transport);
+ httpServer.setExecutor(executor);
+ httpServer.start();
+ serverUrl = new URI("http", null, loopback.getHostAddress(),
httpServer.getAddress().getPort(), null, null, null)
+ .toString();
+ }
+
+ @AfterAll
+ static void stopMcpServer() {
+ if (httpServer != null) {
+ httpServer.stop(0);
+ }
+ if (executor != null) {
+ executor.shutdownNow();
+ }
+ if (mcpServer != null) {
+ mcpServer.close();
+ }
+ }
+
+ @AfterEach
+ void resetStub() {
+ StubOAuthClientAuthenticationFactory.reset(PROFILE);
+ RECORDED_AUTHORIZATIONS.clear();
+ }
+
+ /**
+ * The supplier returns token-1 for the first request (initialize) and
token-2 for the second request (tools/list),
+ * both within the same MCP session. This proves that the OAuth token
supplier is called on every HTTP request
+ * rather than once at client creation: the per-request customizer causes
each POST to re-invoke the supplier, so a
+ * rotated token appears immediately on the very next request on the same
open connection.
+ */
+ @Test
+ void tokenSupplierIsCalledPerRequestWithinSameSession() throws Exception {
+ // Rotating supplier: first call → token-1 (initialize), second call →
token-2 (tools/list)
+ StubOAuthClientAuthenticationFactory.registerRotating(PROFILE,
"token-1", "token-2");
+
+ DefaultCamelContext camelContext = new DefaultCamelContext();
+ camelContext.start();
+ try {
+ OpenAIComponent component = new OpenAIComponent();
+ component.setCamelContext(camelContext);
+ OpenAIConfiguration configuration = new OpenAIConfiguration();
+ configuration.setMcpTimeout(10);
+ OpenAIEndpoint endpoint = new
OpenAIEndpoint("openai:chat-completion", component, configuration);
+ endpoint.setCamelContext(camelContext);
+
+ McpSyncClient client = endpoint.createMcpClient("local",
+ Map.of("transportType", "streamableHttp", "url", serverUrl
+ "/mcp", "oauthProfile", PROFILE));
+ try {
+
assertThat(client.listTools().tools()).extracting(McpSchema.Tool::name).containsExactly("echo");
+ } finally {
+ client.closeGracefully();
+ }
+ // The session sends at least two POSTs (initialize + tools/list).
With per-request resolution the tokens
+ // rotate across requests; without it every request would carry
the same value baked at client creation.
+ assertThat(RECORDED_AUTHORIZATIONS).hasSizeGreaterThanOrEqualTo(2);
+ assertThat(RECORDED_AUTHORIZATIONS.get(0)).isEqualTo("Bearer
token-1");
+ assertThat(RECORDED_AUTHORIZATIONS.get(1)).isEqualTo("Bearer
token-2");
+ } finally {
+ camelContext.stop();
+ }
+ }
+
+ /**
+ * The stub returns token-1 for the first session and then token-2 for the
second session. All requests in the first
+ * MCP session carry token-1; all requests in the second session carry
token-2, proving per-request resolution.
+ */
+ @Test
+ void tokenChangeBetweenSessionsIsPickedUp() throws Exception {
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE, "token-1");
+
+ DefaultCamelContext camelContext = new DefaultCamelContext();
+ camelContext.start();
+ try {
+ OpenAIComponent component = new OpenAIComponent();
+ component.setCamelContext(camelContext);
+ OpenAIConfiguration configuration = new OpenAIConfiguration();
+ configuration.setMcpTimeout(10);
+ OpenAIEndpoint endpoint = new
OpenAIEndpoint("openai:chat-completion", component, configuration);
+ endpoint.setCamelContext(camelContext);
+
+ // First session: initializes and lists tools — all requests carry
token-1
+ McpSyncClient client1 = endpoint.createMcpClient("local",
+ Map.of("transportType", "streamableHttp", "url", serverUrl
+ "/mcp", "oauthProfile", PROFILE));
+ try {
+
assertThat(client1.listTools().tools()).extracting(McpSchema.Tool::name).containsExactly("echo");
+ } finally {
+ client1.closeGracefully();
+ }
+ List<String> firstSessionAuths =
List.copyOf(RECORDED_AUTHORIZATIONS);
+ assertThat(firstSessionAuths).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-1"));
+
+ RECORDED_AUTHORIZATIONS.clear();
+
+ // Switch the token the stub returns
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE,
"token-2");
+
+ // Second session: the stub now returns token-2
+ McpSyncClient client2 = endpoint.createMcpClient("local",
+ Map.of("transportType", "streamableHttp", "url", serverUrl
+ "/mcp", "oauthProfile", PROFILE));
+ try {
+
assertThat(client2.listTools().tools()).extracting(McpSchema.Tool::name).containsExactly("echo");
+ } finally {
+ client2.closeGracefully();
+ }
+ assertThat(RECORDED_AUTHORIZATIONS).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-2"));
+ } finally {
+ camelContext.stop();
+ }
+ }
+
+ /**
+ * A minimal Streamable HTTP handler that records the Authorization header
of every POST request.
+ */
+ private static final class RecordingTransport implements
McpStatelessServerTransport, HttpHandler {
+
+ private final McpJsonMapper jsonMapper;
+ private volatile McpStatelessServerHandler mcpHandler;
+
+ RecordingTransport(McpJsonMapper jsonMapper) {
+ this.jsonMapper = jsonMapper;
+ }
+
+ @Override
+ public void setMcpHandler(McpStatelessServerHandler mcpHandler) {
+ this.mcpHandler = mcpHandler;
+ }
+
+ @Override
+ public Mono<Void> closeGracefully() {
+ return Mono.empty();
+ }
+
+ @Override
+ public List<String> protocolVersions() {
+ return List.of(ProtocolVersions.MCP_2024_11_05,
ProtocolVersions.MCP_2025_03_26,
+ ProtocolVersions.MCP_2025_06_18,
ProtocolVersions.MCP_2025_11_25);
+ }
+
+ @Override
+ public void handle(HttpExchange exchange) throws IOException {
+ try {
+ String httpMethod = exchange.getRequestMethod();
+ String path = exchange.getRequestURI().getPath();
+ String authorization =
exchange.getRequestHeaders().getFirst("Authorization");
+ if (authorization != null && "POST".equals(httpMethod)) {
+ RECORDED_AUTHORIZATIONS.add(authorization);
+ }
+
+ if (!SERVED_PATHS.contains(path) ||
!"POST".equals(httpMethod)) {
+ exchange.sendResponseHeaders(SERVED_PATHS.contains(path) ?
405 : 404, -1);
+ return;
+ }
+
+ String body = new
String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ McpSchema.JSONRPCMessage message =
McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
+ if (message instanceof McpSchema.JSONRPCRequest request) {
+ McpSchema.JSONRPCResponse response
+ =
mcpHandler.handleRequest(McpTransportContext.EMPTY, request).block();
+ byte[] json =
jsonMapper.writeValueAsString(response).getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type",
"application/json");
+ exchange.sendResponseHeaders(200, json.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(json);
+ }
+ } else if (message instanceof McpSchema.JSONRPCNotification
notification) {
+ mcpHandler.handleNotification(McpTransportContext.EMPTY,
notification).block();
+ exchange.sendResponseHeaders(202, -1);
+ } else {
+ exchange.sendResponseHeaders(400, -1);
+ }
+ } finally {
+ exchange.close();
+ }
+ }
+ }
+}
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/StubOAuthClientAuthenticationFactory.java
similarity index 52%
copy from
components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
copy to
components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/StubOAuthClientAuthenticationFactory.java
index cd9b0247358e..53fe7da74796 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
+++
b/components/camel-ai/camel-openai/src/test/java/org/apache/camel/component/openai/StubOAuthClientAuthenticationFactory.java
@@ -14,7 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.component.springai.chat;
+package org.apache.camel.component.openai;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.OAuthClientAuthenticationFactory;
@@ -23,9 +28,39 @@ import org.apache.camel.spi.OAuthClientConfig;
/**
* Stands in for camel-oauth in tests: returns a fixed token per profile,
without calling a token endpoint. Registered
* in {@code
META-INF/services/org/apache/camel/oauth-client-authentication-factory}.
+ *
+ * <p>
+ * Tests that need rotating tokens can call {@link #registerRotating(String,
String...)} before the test and
+ * {@link #reset(String)} after.
*/
public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenticationFactory {
+ private static final Map<String, Supplier<String>> TOKEN_SUPPLIERS = new
ConcurrentHashMap<>();
+
+ /**
+ * Registers a rotating token sequence for the given profile. Successive
calls to
+ * {@link #resolveToken(CamelContext, String)} return the tokens in order;
the last token is repeated.
+ */
+ static void registerRotating(String profileName, String... tokens) {
+ AtomicInteger idx = new AtomicInteger(0);
+ TOKEN_SUPPLIERS.put(profileName, () ->
tokens[Math.min(idx.getAndIncrement(), tokens.length - 1)]);
+ }
+
+ /**
+ * Registers a fixed token that can be changed later with another call.
Use this when the exact number of requests
+ * per session is unknown and each session must carry a specific token.
+ */
+ static void registerFixed(String profileName, String token) {
+ TOKEN_SUPPLIERS.put(profileName, () -> token);
+ }
+
+ /**
+ * Removes any rotating token supplier for the given profile, reverting to
the default fixed-token behavior.
+ */
+ static void reset(String profileName) {
+ TOKEN_SUPPLIERS.remove(profileName);
+ }
+
static String tokenFor(String profileName) {
return "token-for-" + profileName;
}
@@ -37,7 +72,8 @@ public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenti
@Override
public String resolveToken(CamelContext context, String profileName) {
- return tokenFor(profileName);
+ Supplier<String> supplier = TOKEN_SUPPLIERS.get(profileName);
+ return supplier != null ? supplier.get() : tokenFor(profileName);
}
@Override
diff --git
a/components/camel-ai/camel-openai/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
b/components/camel-ai/camel-openai/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
new file mode 100644
index 000000000000..d349f9087a76
--- /dev/null
+++
b/components/camel-ai/camel-openai/src/test/resources/META-INF/services/org/apache/camel/oauth-client-authentication-factory
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+class=org.apache.camel.component.openai.StubOAuthClientAuthenticationFactory
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/mcp/SpringAiChatMcpManager.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/mcp/SpringAiChatMcpManager.java
index 71ff383e226c..70c703b619c9 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/mcp/SpringAiChatMcpManager.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/main/java/org/apache/camel/component/springai/chat/mcp/SpringAiChatMcpManager.java
@@ -18,7 +18,6 @@ package org.apache.camel.component.springai.chat.mcp;
import java.net.URI;
import java.net.URISyntaxException;
-import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
@@ -31,6 +30,7 @@ import
io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
+import
io.modelcontextprotocol.client.transport.customizer.McpSyncHttpClientRequestCustomizer;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.spec.McpClientTransport;
import org.apache.camel.CamelContext;
@@ -151,18 +151,35 @@ public class SpringAiChatMcpManager {
LOG.debug("All MCP clients closed");
}
+ /**
+ * Creates the MCP transport for the given server configuration.
+ *
+ * <p>
+ * When an {@code oauthProfile} is configured, the OAuth token is resolved
lazily via a per-request customizer
+ * rather than eagerly at startup. This enables short-lived tokens to be
refreshed when they expire, at the cost of
+ * deferring misconfiguration errors (wrong profile name, unreachable OIDC
server) to the first request rather than
+ * surfacing them at endpoint start.
+ */
private McpClientTransport createTransport(
String serverName, String transportType, Map<String, String>
props, CamelContext camelContext)
throws Exception {
- // Resolve per-server OAuth token if configured
+ // Build a per-request customizer so the OAuth token is re-resolved on
every request,
+ // allowing short-lived tokens to be refreshed when they expire.
String oauthProfile = props.get("oauthProfile");
- HttpRequest.Builder authRequestBuilder = null;
+ McpSyncHttpClientRequestCustomizer oauthCustomizer = null;
if (ObjectHelper.isNotEmpty(oauthProfile)) {
- String token = OAuthHelper.resolveOAuthToken(camelContext,
oauthProfile);
- authRequestBuilder = HttpRequest.newBuilder()
- .header("Authorization", "Bearer " + token);
- LOG.debug("OAuth token resolved for MCP server '{}' using profile
'{}'", serverName, oauthProfile);
+ final String profile = oauthProfile;
+ oauthCustomizer = (requestBuilder, method, uri, body, context) -> {
+ try {
+ String token = OAuthHelper.resolveOAuthToken(camelContext,
profile);
+ requestBuilder.header("Authorization", "Bearer " + token);
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "Failed to resolve OAuth token for MCP server '" +
serverName + "': " + e.getMessage(), e);
+ }
+ };
+ LOG.debug("OAuth customizer registered for MCP server '{}' using
profile '{}'", serverName, profile);
}
return switch (transportType) {
@@ -184,7 +201,7 @@ public class SpringAiChatMcpManager {
throw new IllegalArgumentException(
"mcpServer." + serverName + ".url is required for
streamableHttp transport");
}
- yield createStreamableHttpTransport(serverName, url,
authRequestBuilder);
+ yield createStreamableHttpTransport(serverName, url,
oauthCustomizer);
}
case "sse" -> {
String url = props.get("url");
@@ -197,8 +214,8 @@ public class SpringAiChatMcpManager {
McpServerUrl serverUrl = splitUrl(serverName, url,
DEFAULT_SSE_ENDPOINT);
HttpClientSseClientTransport.Builder sseBuilder =
HttpClientSseClientTransport.builder(serverUrl.baseUri())
.sseEndpoint(serverUrl.endpoint());
- if (authRequestBuilder != null) {
- sseBuilder.requestBuilder(authRequestBuilder);
+ if (oauthCustomizer != null) {
+ sseBuilder.addHttpRequestCustomizer(oauthCustomizer);
}
yield sseBuilder.build();
}
@@ -212,13 +229,13 @@ public class SpringAiChatMcpManager {
* Creates the Streamable HTTP transport for the MCP endpoint at the given
URL.
*/
private static McpClientTransport createStreamableHttpTransport(
- String serverName, String url, HttpRequest.Builder
authRequestBuilder) {
+ String serverName, String url, McpSyncHttpClientRequestCustomizer
oauthCustomizer) {
McpServerUrl serverUrl = splitUrl(serverName, url,
DEFAULT_STREAMABLE_HTTP_ENDPOINT);
HttpClientStreamableHttpTransport.Builder builder
=
HttpClientStreamableHttpTransport.builder(serverUrl.baseUri())
.endpoint(serverUrl.endpoint());
- if (authRequestBuilder != null) {
- builder.requestBuilder(authRequestBuilder);
+ if (oauthCustomizer != null) {
+ builder.addHttpRequestCustomizer(oauthCustomizer);
}
return builder.build();
}
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatMcpOAuthTokenRefreshTest.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatMcpOAuthTokenRefreshTest.java
new file mode 100644
index 000000000000..834d1652a8ab
--- /dev/null
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/SpringAiChatMcpOAuthTokenRefreshTest.java
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.springai.chat;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.json.McpJsonDefaults;
+import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.server.McpServer;
+import io.modelcontextprotocol.server.McpStatelessServerFeatures;
+import io.modelcontextprotocol.server.McpStatelessServerHandler;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
+import io.modelcontextprotocol.spec.McpSchema;
+import io.modelcontextprotocol.spec.McpStatelessServerTransport;
+import io.modelcontextprotocol.spec.ProtocolVersions;
+import org.apache.camel.component.springai.chat.mcp.SpringAiChatMcpManager;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Verifies that a changed OAuth token is picked up on the next MCP request,
proving that the token supplier is called
+ * per-request rather than once at startup.
+ * <p>
+ * Tests cover both the {@code streamableHttp} transport (POST-based) and the
{@code sse} transport (GET SSE stream +
+ * POST message endpoint) to prove that {@code addHttpRequestCustomizer} is
wired correctly on both
+ * {@link
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport.Builder}
and
+ * {@link
io.modelcontextprotocol.client.transport.HttpClientSseClientTransport.Builder}.
+ */
+class SpringAiChatMcpOAuthTokenRefreshTest {
+
+ private static final String PROFILE = "refresh-test";
+ private static final Set<String> STREAMABLE_PATHS = Set.of("/mcp");
+ private static final Set<String> SSE_PATHS = Set.of("/sse");
+ private static final List<String> RECORDED_AUTHORIZATIONS = new
CopyOnWriteArrayList<>();
+
+ private static ExecutorService executor;
+ private static HttpServer httpServer;
+ private static McpStatelessSyncServer mcpServer;
+ private static DualTransport transport;
+ private static String serverUrl;
+
+ @BeforeAll
+ static void startMcpServer() throws Exception {
+ McpJsonMapper jsonMapper = McpJsonDefaults.getMapper();
+ transport = new DualTransport(jsonMapper);
+
+ McpSchema.Tool echo = McpSchema.Tool.builder("echo",
+ Map.of("type", "object",
+ "properties", Map.of("message", Map.of("type",
"string")),
+ "required", List.of("message")))
+ .description("Echoes the message")
+ .build();
+ mcpServer = McpServer.sync(transport)
+ .serverInfo("token-refresh-test-server", "1.0.0")
+
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
+
.tools(McpStatelessServerFeatures.SyncToolSpecification.builder()
+ .tool(echo)
+ .callHandler((context, request) ->
McpSchema.CallToolResult.builder(List.of(
+ McpSchema.TextContent.builder("echo: " +
request.arguments().get("message")).build()))
+ .build())
+ .build())
+ .build();
+
+ InetAddress loopback = InetAddress.getLoopbackAddress();
+ // SSE streams hold a thread until they are closed — pool must be
unbounded
+ executor = Executors.newCachedThreadPool();
+ httpServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
+ httpServer.createContext("/", transport);
+ httpServer.setExecutor(executor);
+ httpServer.start();
+ serverUrl = new URI("http", null, loopback.getHostAddress(),
httpServer.getAddress().getPort(), null, null, null)
+ .toString();
+ }
+
+ @AfterAll
+ static void stopMcpServer() {
+ if (httpServer != null) {
+ httpServer.stop(0);
+ }
+ if (executor != null) {
+ executor.shutdownNow();
+ }
+ if (mcpServer != null) {
+ mcpServer.close();
+ }
+ }
+
+ @AfterEach
+ void resetStub() {
+ StubOAuthClientAuthenticationFactory.reset(PROFILE);
+ RECORDED_AUTHORIZATIONS.clear();
+ transport.endSseStreams();
+ }
+
+ /**
+ * The supplier returns token-1 for the first request (initialize) and
token-2 for the second request (tools/list),
+ * both within the same MCP session. This proves that the token supplier
is called on every HTTP request rather than
+ * once at client creation: the per-request customizer causes each POST to
re-invoke the supplier, so a rotated
+ * token appears immediately on the very next request on the same open
connection.
+ */
+ @Test
+ void tokenSupplierIsCalledPerRequestWithinSameSession() throws Exception {
+ // Rotating supplier: first call → token-1 (initialize), second call →
token-2 (tools/list)
+ StubOAuthClientAuthenticationFactory.registerRotating(PROFILE,
"token-1", "token-2");
+
+ try (DefaultCamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.start();
+
+ SpringAiChatMcpManager manager = new SpringAiChatMcpManager();
+ try {
+ manager.initialize(
+ Map.<String, Object> of(
+ "local.transportType", "streamableHttp",
+ "local.url", serverUrl + "/mcp",
+ "local.oauthProfile", PROFILE),
+ 10, camelContext);
+ assertThat(manager.getToolCallbackProvider()).isNotNull();
+ } finally {
+ manager.close();
+ }
+ // The session sends at least two POSTs (initialize + tools/list).
With per-request resolution the tokens
+ // rotate across requests; without it every request would carry
the same value baked at client creation.
+ assertThat(RECORDED_AUTHORIZATIONS).hasSizeGreaterThanOrEqualTo(2);
+ assertThat(RECORDED_AUTHORIZATIONS.get(0)).isEqualTo("Bearer
token-1");
+ assertThat(RECORDED_AUTHORIZATIONS.get(1)).isEqualTo("Bearer
token-2");
+ }
+ }
+
+ /**
+ * The stub returns token-1 for the first session and then token-2 for the
second session. All requests in the first
+ * MCP session carry token-1; all requests in the second session carry
token-2, proving per-request resolution via
+ * the {@code streamableHttp} transport.
+ */
+ @Test
+ void tokenChangeBetweenSessionsIsPickedUp() throws Exception {
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE, "token-1");
+
+ try (DefaultCamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.start();
+
+ // First session: initializes and lists tools — all requests carry
token-1
+ SpringAiChatMcpManager manager1 = new SpringAiChatMcpManager();
+ try {
+ manager1.initialize(
+ Map.<String, Object> of(
+ "local.transportType", "streamableHttp",
+ "local.url", serverUrl + "/mcp",
+ "local.oauthProfile", PROFILE),
+ 10, camelContext);
+ assertThat(manager1.getToolCallbackProvider()).isNotNull();
+ } finally {
+ manager1.close();
+ }
+ List<String> firstSessionAuths =
List.copyOf(RECORDED_AUTHORIZATIONS);
+ assertThat(firstSessionAuths).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-1"));
+
+ RECORDED_AUTHORIZATIONS.clear();
+
+ // Switch the token the stub returns
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE,
"token-2");
+
+ // Second session: the stub now returns token-2
+ SpringAiChatMcpManager manager2 = new SpringAiChatMcpManager();
+ try {
+ manager2.initialize(
+ Map.<String, Object> of(
+ "local.transportType", "streamableHttp",
+ "local.url", serverUrl + "/mcp",
+ "local.oauthProfile", PROFILE),
+ 10, camelContext);
+ assertThat(manager2.getToolCallbackProvider()).isNotNull();
+ } finally {
+ manager2.close();
+ }
+ assertThat(RECORDED_AUTHORIZATIONS).isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-2"));
+ }
+ }
+
+ /**
+ * Same as {@link #tokenChangeBetweenSessionsIsPickedUp()} but over the
{@code sse} transport — exercising the
+ * {@link
io.modelcontextprotocol.client.transport.HttpClientSseClientTransport.Builder#addHttpRequestCustomizer}
+ * overload rather than the streamableHttp builder, confirming both
builders accept the same customizer API.
+ */
+ @Test
+ void sseTransportSendsTokenOnEveryRequest() throws Exception {
+ StubOAuthClientAuthenticationFactory.registerFixed(PROFILE,
"token-sse");
+
+ try (DefaultCamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.start();
+
+ SpringAiChatMcpManager manager = new SpringAiChatMcpManager();
+ try {
+ manager.initialize(
+ Map.<String, Object> of(
+ "local.transportType", "sse",
+ "local.url", serverUrl,
+ "local.oauthProfile", PROFILE),
+ 10, camelContext);
+ assertThat(manager.getToolCallbackProvider()).isNotNull();
+ } finally {
+ manager.close();
+ }
+ assertThat(RECORDED_AUTHORIZATIONS).as("SSE transport requests
must carry the Authorization header")
+ .isNotEmpty()
+ .allSatisfy(auth -> assertThat(auth).isEqualTo("Bearer
token-sse"));
+ }
+ }
+
+ /**
+ * Serves the stateless MCP server over both Streamable HTTP and HTTP+SSE,
recording every Authorization header it
+ * sees. The SSE case implements the legacy HTTP+SSE transport protocol: a
GET to {@code /sse} opens the SSE event
+ * stream whose first event names the message endpoint ({@code /message});
subsequent POSTs to that endpoint carry
+ * JSON-RPC messages and responses are returned on the SSE stream.
+ */
+ private static final class DualTransport implements
McpStatelessServerTransport, HttpHandler {
+
+ private static final String END_OF_STREAM = "";
+
+ private final McpJsonMapper jsonMapper;
+ private final Map<String, SseSession> sseSessions = new
ConcurrentHashMap<>();
+ private volatile McpStatelessServerHandler mcpHandler;
+
+ private record SseSession(BlockingQueue<String> events) {
+ }
+
+ DualTransport(McpJsonMapper jsonMapper) {
+ this.jsonMapper = jsonMapper;
+ }
+
+ @Override
+ public void setMcpHandler(McpStatelessServerHandler mcpHandler) {
+ this.mcpHandler = mcpHandler;
+ }
+
+ @Override
+ public Mono<Void> closeGracefully() {
+ return Mono.empty();
+ }
+
+ @Override
+ public List<String> protocolVersions() {
+ return List.of(ProtocolVersions.MCP_2024_11_05,
ProtocolVersions.MCP_2025_03_26,
+ ProtocolVersions.MCP_2025_06_18,
ProtocolVersions.MCP_2025_11_25);
+ }
+
+ void endSseStreams() {
+ sseSessions.values().forEach(session ->
session.events().add(END_OF_STREAM));
+ }
+
+ @Override
+ public void handle(HttpExchange exchange) throws IOException {
+ try {
+ String httpMethod = exchange.getRequestMethod();
+ String path = exchange.getRequestURI().getPath();
+ String query = exchange.getRequestURI().getRawQuery();
+ String authorization =
exchange.getRequestHeaders().getFirst("Authorization");
+
+ // SSE open: GET /sse → emit endpoint event, then stream
responses
+ if ("GET".equals(httpMethod) && SSE_PATHS.contains(path)) {
+ if (authorization != null) {
+ RECORDED_AUTHORIZATIONS.add(authorization);
+ }
+ streamSseEvents(exchange);
+ return;
+ }
+
+ // SSE message: POST /message?sessionId=<id>
+ if ("POST".equals(httpMethod) && "/message".equals(path) &&
query != null
+ && query.startsWith("sessionId=")) {
+ String sessionId = query.substring("sessionId=".length());
+ SseSession sseSession = sseSessions.get(sessionId);
+ if (sseSession != null) {
+ if (authorization != null) {
+ RECORDED_AUTHORIZATIONS.add(authorization);
+ }
+ handleSseMessage(exchange, sseSession);
+ return;
+ }
+ }
+
+ // Streamable HTTP: POST /mcp
+ if ("POST".equals(httpMethod) &&
STREAMABLE_PATHS.contains(path)) {
+ if (authorization != null) {
+ RECORDED_AUTHORIZATIONS.add(authorization);
+ }
+ handleStreamableHttpMessage(exchange);
+ return;
+ }
+
+ exchange.sendResponseHeaders(STREAMABLE_PATHS.contains(path) ?
405 : 404, -1);
+ } finally {
+ exchange.close();
+ }
+ }
+
+ private void handleStreamableHttpMessage(HttpExchange exchange) throws
IOException {
+ String body = new String(exchange.getRequestBody().readAllBytes(),
StandardCharsets.UTF_8);
+ McpSchema.JSONRPCMessage message =
McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
+ if (message instanceof McpSchema.JSONRPCRequest request) {
+ McpSchema.JSONRPCResponse response =
mcpHandler.handleRequest(McpTransportContext.EMPTY, request).block();
+ byte[] json =
jsonMapper.writeValueAsString(response).getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type",
"application/json");
+ exchange.sendResponseHeaders(200, json.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(json);
+ }
+ } else if (message instanceof McpSchema.JSONRPCNotification
notification) {
+ mcpHandler.handleNotification(McpTransportContext.EMPTY,
notification).block();
+ exchange.sendResponseHeaders(202, -1);
+ } else {
+ exchange.sendResponseHeaders(400, -1);
+ }
+ }
+
+ private void handleSseMessage(HttpExchange exchange, SseSession
session) throws IOException {
+ String body = new String(exchange.getRequestBody().readAllBytes(),
StandardCharsets.UTF_8);
+ McpSchema.JSONRPCMessage message =
McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
+ if (message instanceof McpSchema.JSONRPCRequest request) {
+ McpSchema.JSONRPCResponse response =
mcpHandler.handleRequest(McpTransportContext.EMPTY, request).block();
+ session.events().add(jsonMapper.writeValueAsString(response));
+ } else if (message instanceof McpSchema.JSONRPCNotification
notification) {
+ mcpHandler.handleNotification(McpTransportContext.EMPTY,
notification).block();
+ }
+ exchange.sendResponseHeaders(202, -1);
+ }
+
+ private void streamSseEvents(HttpExchange exchange) throws IOException
{
+ String sessionId = UUID.randomUUID().toString();
+ SseSession session = new SseSession(new LinkedBlockingQueue<>());
+ sseSessions.put(sessionId, session);
+ try {
+ exchange.getResponseHeaders().set("Content-Type",
"text/event-stream");
+ exchange.sendResponseHeaders(200, 0);
+ OutputStream body = exchange.getResponseBody();
+ writeEvent(body, "endpoint", "/message?sessionId=" +
sessionId);
+ for (String event = session.events().take();
+ !END_OF_STREAM.equals(event);
+ event = session.events().take()) {
+ writeEvent(body, "message", event);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ sseSessions.remove(sessionId);
+ }
+ }
+
+ private static void writeEvent(OutputStream body, String event, String
data) throws IOException {
+ body.write(("event: " + event + "\ndata: " + data +
"\n\n").getBytes(StandardCharsets.UTF_8));
+ body.flush();
+ }
+ }
+}
diff --git
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
index cd9b0247358e..f93a3f104148 100644
---
a/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
+++
b/components/camel-spring-parent/camel-spring-ai/camel-spring-ai-chat/src/test/java/org/apache/camel/component/springai/chat/StubOAuthClientAuthenticationFactory.java
@@ -16,6 +16,11 @@
*/
package org.apache.camel.component.springai.chat;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+
import org.apache.camel.CamelContext;
import org.apache.camel.spi.OAuthClientAuthenticationFactory;
import org.apache.camel.spi.OAuthClientConfig;
@@ -23,9 +28,39 @@ import org.apache.camel.spi.OAuthClientConfig;
/**
* Stands in for camel-oauth in tests: returns a fixed token per profile,
without calling a token endpoint. Registered
* in {@code
META-INF/services/org/apache/camel/oauth-client-authentication-factory}.
+ *
+ * <p>
+ * Tests that need rotating tokens can call {@link #registerRotating(String,
String...)} before the test and
+ * {@link #reset(String)} after.
*/
public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenticationFactory {
+ private static final Map<String, Supplier<String>> TOKEN_SUPPLIERS = new
ConcurrentHashMap<>();
+
+ /**
+ * Registers a rotating token sequence for the given profile. Successive
calls to
+ * {@link #resolveToken(CamelContext, String)} return the tokens in order;
the last token is repeated.
+ */
+ static void registerRotating(String profileName, String... tokens) {
+ AtomicInteger idx = new AtomicInteger(0);
+ TOKEN_SUPPLIERS.put(profileName, () ->
tokens[Math.min(idx.getAndIncrement(), tokens.length - 1)]);
+ }
+
+ /**
+ * Registers a fixed token that can be changed later with another call.
Use this when the exact number of requests
+ * per session is unknown and each session must carry a specific token.
+ */
+ static void registerFixed(String profileName, String token) {
+ TOKEN_SUPPLIERS.put(profileName, () -> token);
+ }
+
+ /**
+ * Removes any rotating token supplier for the given profile, reverting to
the default fixed-token behavior.
+ */
+ static void reset(String profileName) {
+ TOKEN_SUPPLIERS.remove(profileName);
+ }
+
static String tokenFor(String profileName) {
return "token-for-" + profileName;
}
@@ -37,7 +72,8 @@ public class StubOAuthClientAuthenticationFactory implements
OAuthClientAuthenti
@Override
public String resolveToken(CamelContext context, String profileName) {
- return tokenFor(profileName);
+ Supplier<String> supplier = TOKEN_SUPPLIERS.get(profileName);
+ return supplier != null ? supplier.get() : tokenFor(profileName);
}
@Override
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
index 4ed623135627..31b03928009f 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
@@ -13,6 +13,18 @@ See the xref:camel-upgrade-recipes-tool.adoc[documentation]
page for details.
== Upgrading Camel 4.24 to 4.25
+=== camel-openai - oauthProfile takes precedence over apiKey
+
+When both `oauthProfile` and `apiKey` are set on a `camel-openai` endpoint,
`oauthProfile` now takes precedence and
+the `apiKey` is ignored. Before, `apiKey` took precedence over `oauthProfile`.
This reversal matches the option
+descriptions and the behaviour of the other AI components. Applications that
intentionally configured both options
+relying on `apiKey` taking precedence must remove the `oauthProfile` option or
set it to empty to restore the previous
+resolution order.
+
+Additionally, a misconfigured `oauthProfile` on the OpenAI API client (the
`oauthProfile` option on the endpoint
+itself, not on a nested `mcpServer.*`) will only be reported on the first
exchange rather than at route startup. This
+is an intentional trade-off that enables short-lived token refresh.
+
=== camel-alibaba-eventbridge - the client that the endpoint creates sends its
requests over HTTPS
The client that the `alibaba-eventbridge` endpoint creates now sends its
requests to EventBridge over HTTPS. Before,