This is an automated email from the ASF dual-hosted git repository.
Croway pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git
The following commit(s) were added to refs/heads/main by this push:
new 20297393afc CAMEL-27145: camel-mcp-server-starter - serve the Camel
routes on the Spring AI stateless MCP server
20297393afc is described below
commit 20297393afc51bdcd660d99159900006be13da00
Author: croway <[email protected]>
AuthorDate: Wed Nov 18 14:24:04 2026 +0100
CAMEL-27145: camel-mcp-server-starter - serve the Camel routes on the
Spring AI stateless MCP server
With spring.ai.mcp.server.protocol=STATELESS, Spring AI auto-configures an
McpStatelessSyncServer instead of an McpSyncServer, and the starter
registered
nothing. The engine now publishes into either server, and Camel's Origin
validation and caller-context extraction are installed on the stateless
WebMVC
transport too. Each request is served without a session, so restarts and
several
instances without session affinity no longer end the client's session.
---
.../src/main/doc/usage.adoc | 47 ++-
.../server/CamelMcpServerAutoConfiguration.java | 48 +++-
...pServerStatelessTransportAutoConfiguration.java | 87 ++++++
.../mcp/server/SpringAiMcpServerEngine.java | 316 ++++++++++++++++++---
.../mcp/server/SpringAiMcpTransportContext.java | 15 +-
...rk.boot.autoconfigure.AutoConfiguration.imports | 1 +
.../server/SpringBootMcpServerStatelessTest.java | 186 ++++++++++++
.../modules/ROOT/pages/starters/mcp-server.adoc | 47 ++-
8 files changed, 682 insertions(+), 65 deletions(-)
diff --git
a/components-starter/camel-mcp-server-starter/src/main/doc/usage.adoc
b/components-starter/camel-mcp-server-starter/src/main/doc/usage.adoc
index 30d398e11de..85660415941 100644
--- a/components-starter/camel-mcp-server-starter/src/main/doc/usage.adoc
+++ b/components-starter/camel-mcp-server-starter/src/main/doc/usage.adoc
@@ -132,9 +132,10 @@ spring.ai.mcp.server.prompt-change-notification = true
=== Origin validation
-Camel's principal-aware Streamable HTTP provider is selected only when
-`spring.ai.mcp.server.protocol=STREAMABLE` and the Camel transport activation
-condition is satisfied:
+Camel's principal-aware HTTP transport is selected only when
+`spring.ai.mcp.server.protocol` is `STREAMABLE` or `STATELESS` (see
+<<_serving_without_sessions>>) and the Camel transport activation condition is
+satisfied:
* By default, the Camel provider is selected when `camel.mcp-server.tags` is
configured. This enables the Origin validator and authenticated caller
@@ -177,10 +178,11 @@ browser-based clients. Scheme and host matching is
case-insensitive, and
default HTTP and HTTPS ports are normalized.
If Camel tags or Origin settings are configured while the Spring AI protocol
-is unset or uses SSE, the Camel Streamable HTTP provider is not installed.
+is unset or uses SSE, the Camel HTTP transport is not installed.
The starter logs a warning because Origin validation and caller-context
extraction are not active in that configuration. Select
-`spring.ai.mcp.server.protocol=STREAMABLE` when those protections are required.
+`spring.ai.mcp.server.protocol=STREAMABLE` (or `STATELESS`) when those
+protections are required.
With the Spring AI 2.0.2 WebMVC transport, an Origin rejection currently
returns HTTP 403 with a plain-text `Invalid Origin header` response body.
@@ -244,6 +246,41 @@ spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp
----
+=== Serving without sessions
+
+With `spring.ai.mcp.server.protocol=STREAMABLE`, the Spring AI MCP server keeps
+a session for each client in memory: the session ends when the application
+restarts, and a request that reaches another instance finds no session, so
+several instances need session affinity in front of them.
+
+With `spring.ai.mcp.server.protocol=STATELESS`, Spring AI serves each request
on
+its own, and the starter registers the Camel routes on that stateless server.
+No `Mcp-Session-Id` is returned, so a restart or another instance is invisible
+to the client. Camel's Origin validation and caller-context extraction apply as
+with `STREAMABLE`, through `WebMvcStatelessServerTransport`; an
+application-provided `WebMvcStatelessServerTransport` takes precedence.
+
+[source,properties]
+----
+spring.ai.mcp.server.protocol = STATELESS
+camel.mcp-server.tags = crm
+----
+
+Without a session, the server cannot send anything outside the answer to a
+request:
+
+* clients are not notified when Camel routes add or remove tools, resources or
+ prompts; they see the change at their next list request,
+* a `GET` on the endpoint (the stream for server-initiated messages) is
answered
+ with HTTP 405,
+* features that need a server-initiated request, such as sampling or
+ elicitation, are not available.
+
+The stateless mode serves the MCP protocol versions that open with an
+`initialize` handshake (2025-11-25 and earlier). Protocol version 2026-07-28,
+which has no session by design, is not served by this starter yet: it needs
+Spring AI 2.1.0.
+
=== Connecting MCP clients
Any MCP client can connect over streamable HTTP. Another Camel integration
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAutoConfiguration.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAutoConfiguration.java
index 4b73c002fcf..3b22b53dcc2 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAutoConfiguration.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAutoConfiguration.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.springboot.mcp.server;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.server.McpSyncServer;
import org.apache.camel.CamelContext;
import org.apache.camel.component.mcp.server.McpServerBridge;
@@ -24,22 +25,28 @@ import
org.apache.camel.component.mcp.server.McpServerEngine;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import
org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
/**
* Auto-configures the Camel MCP server bridge over the Spring AI MCP server:
every ai-tool route whose tags match
- * {@code camel.mcp-server.tags} is exposed as an MCP tool of the
auto-configured {@link McpSyncServer}.
+ * {@code camel.mcp-server.tags} is exposed as an MCP tool of the
auto-configured {@link McpSyncServer}, or of the
+ * {@link McpStatelessSyncServer} when {@code
spring.ai.mcp.server.protocol=STATELESS}.
*/
@AutoConfiguration(after = CamelAutoConfiguration.class,
- afterName =
"org.springframework.ai.mcp.server.common.autoconfigure.McpServerAutoConfiguration")
-@ConditionalOnBean(McpSyncServer.class)
+ afterName = {
+
"org.springframework.ai.mcp.server.common.autoconfigure.McpServerAutoConfiguration",
+
"org.springframework.ai.mcp.server.common.autoconfigure.McpServerStatelessAutoConfiguration"
})
+@Conditional(CamelMcpServerAutoConfiguration.OnSpringAiMcpServerCondition.class)
@ConditionalOnProperty(value = "camel.mcp-server.enabled", matchIfMissing =
true)
@EnableConfigurationProperties(McpServerConfigurationProperties.class)
public class CamelMcpServerAutoConfiguration {
@@ -49,8 +56,12 @@ public class CamelMcpServerAutoConfiguration {
@Bean(initMethod = "", destroyMethod = "")
// Camel handles the lifecycle of this bean
@ConditionalOnMissingBean(McpServerEngine.class)
- McpServerEngine camelMcpServerEngine(McpSyncServer mcpSyncServer) {
- return new SpringAiMcpServerEngine(mcpSyncServer);
+ McpServerEngine camelMcpServerEngine(
+ ObjectProvider<McpSyncServer> mcpSyncServer,
ObjectProvider<McpStatelessSyncServer> mcpStatelessSyncServer) {
+ McpSyncServer server = mcpSyncServer.getIfAvailable();
+ return server != null
+ ? new SpringAiMcpServerEngine(server)
+ : new
SpringAiMcpServerEngine(mcpStatelessSyncServer.getObject());
}
@Bean(initMethod = "", destroyMethod = "")
@@ -88,11 +99,11 @@ public class CamelMcpServerAutoConfiguration {
}
String protocol =
environment.getProperty("spring.ai.mcp.server.protocol");
- if (!"STREAMABLE".equalsIgnoreCase(protocol)) {
+ if (!"STREAMABLE".equalsIgnoreCase(protocol) &&
!"STATELESS".equalsIgnoreCase(protocol)) {
LOG.warn("Camel MCP routes or Origin settings are configured, but "
- + "spring.ai.mcp.server.protocol is not STREAMABLE.
Camel's Origin validation "
+ + "spring.ai.mcp.server.protocol is neither STREAMABLE
nor STATELESS. Camel's Origin validation "
+ "and authenticated caller-context extraction are not
active; configure "
- + "spring.ai.mcp.server.protocol=STREAMABLE to enable
them.");
+ + "spring.ai.mcp.server.protocol=STREAMABLE or STATELESS
to enable them.");
return;
}
@@ -100,11 +111,30 @@ public class CamelMcpServerAutoConfiguration {
? properties.getTransportEnabled()
: tagsConfigured;
if (!transportActive) {
- LOG.warn("Camel MCP routes or Origin settings are configured, but
Camel's Streamable HTTP "
+ LOG.warn("Camel MCP routes or Origin settings are configured, but
Camel's HTTP "
+ "transport replacement is disabled. Origin validation
and caller-context "
+ "extraction are not installed. Set
camel.mcp-server.transport-enabled=true "
+ "or configure those features on the
application-provided transport.");
}
}
+ /**
+ * Matches when Spring AI auto-configured a synchronous MCP server: with
sessions ({@code SSE},
+ * {@code STREAMABLE}) or stateless ({@code STATELESS}).
+ */
+ static final class OnSpringAiMcpServerCondition extends AnyNestedCondition
{
+
+ OnSpringAiMcpServerCondition() {
+ super(ConfigurationPhase.REGISTER_BEAN);
+ }
+
+ @ConditionalOnBean(McpSyncServer.class)
+ static final class OnSessionServer {
+ }
+
+ @ConditionalOnBean(McpStatelessSyncServer.class)
+ static final class OnStatelessServer {
+ }
+ }
+
}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerStatelessTransportAutoConfiguration.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerStatelessTransportAutoConfiguration.java
new file mode 100644
index 00000000000..e66681717bd
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerStatelessTransportAutoConfiguration.java
@@ -0,0 +1,87 @@
+/*
+ * 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.springboot.mcp.server;
+
+import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import
org.springframework.ai.mcp.server.common.autoconfigure.McpServerStdioDisabledCondition;
+import
org.springframework.ai.mcp.server.common.autoconfigure.properties.McpServerStreamableHttpProperties;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcStatelessServerTransport;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Installs a principal-aware Spring AI WebMVC stateless MCP transport ({@code
spring.ai.mcp.server.protocol=STATELESS}),
+ * the counterpart of {@link CamelMcpServerTransportAutoConfiguration} for the
Streamable HTTP transport.
+ * <p>
+ * This configuration runs before Spring AI's default WebMVC stateless
transport configuration. It keeps the Spring AI
+ * endpoint, and adds Camel's Origin validation and a transport context
extractor for the authenticated caller
+ * identity.
+ * <p>
+ * An application-defined {@link WebMvcStatelessServerTransport} takes
precedence.
+ */
+@AutoConfiguration(
+ beforeName = "org.springframework.ai.mcp.server.webmvc.autoconfigure."
+ + "McpServerStatelessWebMvcAutoConfiguration")
+@ConditionalOnClass({
+ WebMvcStatelessServerTransport.class,
+ JacksonMcpJsonMapper.class
+})
+@Conditional({
+ McpServerStdioDisabledCondition.class,
+ CamelMcpServerTransportCondition.class
+})
+@ConditionalOnProperty(
+ prefix = "camel.mcp-server",
+ name = "enabled",
+ matchIfMissing = true)
+@ConditionalOnProperty(
+ prefix = "spring.ai.mcp.server",
+ name = "protocol",
+ havingValue = "STATELESS",
+ matchIfMissing = false)
+@EnableConfigurationProperties({
+ McpServerStreamableHttpProperties.class,
+ McpServerConfigurationProperties.class
+})
+public class CamelMcpServerStatelessTransportAutoConfiguration {
+
+ // Spring AI 2.0.2's builder still takes the deprecated
ServerTransportSecurityValidator, see
+ // CamelMcpServerTransportAutoConfiguration#createOriginValidator
+ @SuppressWarnings("deprecation")
+ @Bean
+ @ConditionalOnMissingBean(WebMvcStatelessServerTransport.class)
+ WebMvcStatelessServerTransport webMvcStatelessServerTransport(
+ @Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper,
+ McpServerStreamableHttpProperties serverProperties,
+ McpServerConfigurationProperties camelProperties) {
+
+ return WebMvcStatelessServerTransport.builder()
+ .jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
+ .messageEndpoint(serverProperties.getMcpEndpoint())
+ .securityValidator(
+
CamelMcpServerTransportAutoConfiguration.createOriginValidator(camelProperties.getAllowedOrigins()))
+ .contextExtractor(SpringAiMcpTransportContext::extract)
+ .build();
+ }
+}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java
index 5abbb5c5cd6..d22358a7049 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java
@@ -21,11 +21,16 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.function.BiFunction;
+import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.server.McpServerFeatures;
+import io.modelcontextprotocol.server.McpStatelessServerFeatures;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.server.McpSyncServer;
+import io.modelcontextprotocol.server.McpSyncServerExchange;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import org.apache.camel.CamelContext;
@@ -49,9 +54,11 @@ import org.slf4j.LoggerFactory;
/**
* {@link McpServerEngine} publishing tools into the Spring AI MCP server:
{@code toolAdded}/{@code toolRemoved} map to
* the auto-configured {@link McpSyncServer}'s {@code addTool}/{@code
removeTool}, which emit
- * {@code notifications/tools/list_changed} to connected clients. Serving
concerns (endpoint path, protocol, server
- * identity) are owned by the Spring AI MCP server configuration ({@code
spring.ai.mcp.server.*}), which provides
- * no authentication - the endpoint must be protected by the application.
+ * {@code notifications/tools/list_changed} to connected clients. With {@code
spring.ai.mcp.server.protocol=STATELESS},
+ * Spring AI auto-configures an {@link McpStatelessSyncServer} instead: every
request is served on its own, without a
+ * session, and clients are not notified of changes. Serving concerns
(endpoint path, protocol, server identity) are
+ * owned by the Spring AI MCP server configuration ({@code
spring.ai.mcp.server.*}), which provides no authentication -
+ * the endpoint must be protected by the application.
*/
public class SpringAiMcpServerEngine extends ServiceSupport implements
McpServerEngine {
@@ -65,12 +72,19 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
}
""";
- private final McpSyncServer server;
+ private final ServerOperations server;
private final McpJsonMapper jsonMapper = McpJsonDefaults.getMapper();
private CamelContext camelContext;
public SpringAiMcpServerEngine(McpSyncServer server) {
- this.server = server;
+ this.server = new SessionServerOperations(server);
+ }
+
+ /**
+ * Publishes into the Spring AI stateless MCP server ({@code
spring.ai.mcp.server.protocol=STATELESS}).
+ */
+ public SpringAiMcpServerEngine(McpStatelessSyncServer server) {
+ this.server = new StatelessServerOperations(server);
}
@Override
@@ -107,24 +121,20 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
applyAnnotations(builder, tool.annotations());
McpSchema.Tool mcpTool = builder.build();
- McpServerFeatures.SyncToolSpecification spec =
McpServerFeatures.SyncToolSpecification.builder()
- .tool(mcpTool)
- .callHandler((exchange, request) -> {
- Map<String, Object> arguments = request.arguments() !=
null ? request.arguments() : Map.of();
- McpToolCallResult result = tool.handler().call(
- arguments,
SpringAiMcpTransportContext.from(exchange));
- McpSchema.CallToolResult.Builder resultBuilder =
McpSchema.CallToolResult.builder()
- .addTextContent(result.text())
- .isError(result.isError());
-
- if (result.structuredContent() != null) {
-
resultBuilder.structuredContent(result.structuredContent());
- }
-
- return resultBuilder.build();
- })
- .build();
- server.addTool(spec);
+ server.addTool(mcpTool, (transportContext, request) -> {
+ Map<String, Object> arguments = request.arguments() != null ?
request.arguments() : Map.of();
+ McpToolCallResult result = tool.handler().call(
+ arguments,
SpringAiMcpTransportContext.from(transportContext));
+ McpSchema.CallToolResult.Builder resultBuilder =
McpSchema.CallToolResult.builder()
+ .addTextContent(result.text())
+ .isError(result.isError());
+
+ if (result.structuredContent() != null) {
+
resultBuilder.structuredContent(result.structuredContent());
+ }
+
+ return resultBuilder.build();
+ });
} catch (IllegalArgumentException e) {
throw new McpServerRefusedException(
"MCP tool '" + tool.name() + "' has an invalid input or
output schema: " + e.getMessage(), e);
@@ -151,10 +161,9 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
McpSchema.Resource mcpResource = buildMcpResource(resource);
- McpServerFeatures.SyncResourceSpecification spec =
- new McpServerFeatures.SyncResourceSpecification(
+ server.addResource(
mcpResource,
- (exchange, request) -> {
+ (transportContext, request) -> {
McpResourceReadResult result =
resource.handler().read();
if (result.isError()) {
@@ -179,8 +188,6 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
return
McpSchema.ReadResourceResult.builder(List.of(contents)).build();
});
-
- server.addResource(spec);
LOG.debug("MCP resource added: {}", resource.uri());
}
@@ -196,7 +203,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public boolean supportsResources() {
- McpSchema.ServerCapabilities capabilities =
server.getServerCapabilities();
+ McpSchema.ServerCapabilities capabilities = server.capabilities();
return capabilities != null && capabilities.resources() != null;
}
@@ -257,10 +264,9 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
builder.title(resourceTemplate.title());
}
- McpServerFeatures.SyncResourceTemplateSpecification spec =
- new McpServerFeatures.SyncResourceTemplateSpecification(
+ server.addResourceTemplate(
builder.build(),
- (exchange, request) -> {
+ (transportContext, request) -> {
McpResourceReadResult result =
resourceTemplate.handler().read(request.uri());
@@ -286,8 +292,6 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
return
McpSchema.ReadResourceResult.builder(List.of(contents)).build();
});
-
- server.addResourceTemplate(spec);
LOG.debug("MCP resource template added: {}",
resourceTemplate.uriTemplate());
}
@@ -303,7 +307,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
server.removeResourceTemplate(uriTemplate);
- McpSchema.ServerCapabilities capabilities =
server.getServerCapabilities();
+ McpSchema.ServerCapabilities capabilities = server.capabilities();
if (capabilities != null && capabilities.resources() != null
&&
Boolean.TRUE.equals(capabilities.resources().listChanged())) {
// MCP Java SDK 2.1.0 does not notify on template removal;
notify only when advertised.
@@ -321,7 +325,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public boolean supportsResourceTemplates() {
- McpSchema.ServerCapabilities capabilities =
server.getServerCapabilities();
+ McpSchema.ServerCapabilities capabilities = server.capabilities();
return capabilities != null && capabilities.resources() != null;
}
@@ -332,7 +336,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
"An MCP prompt named '" + prompt.name() + "' is already
registered");
}
- server.addPrompt(buildPromptSpecification(prompt));
+ server.addPrompt(buildPrompt(prompt), (transportContext, request) ->
getPrompt(prompt, request));
LOG.debug("MCP prompt added: {}", prompt.name());
}
@@ -348,7 +352,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public boolean supportsPrompts() {
- McpSchema.ServerCapabilities capabilities =
server.getServerCapabilities();
+ McpSchema.ServerCapabilities capabilities = server.capabilities();
return capabilities != null && capabilities.prompts() != null;
}
@@ -368,8 +372,7 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
* This adapter uses the MCP Java SDK types directly. The equivalent Camel
Main
* helper lives in camel-mcp-server, which is deliberately not a
dependency here.
*/
- private McpServerFeatures.SyncPromptSpecification buildPromptSpecification(
- McpServerPrompt prompt) {
+ private static McpSchema.Prompt buildPrompt(McpServerPrompt prompt) {
McpSchema.Prompt.Builder builder =
McpSchema.Prompt.builder(prompt.name())
.description(prompt.description())
@@ -384,9 +387,10 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
builder.title(prompt.title());
}
- return new McpServerFeatures.SyncPromptSpecification(
- builder.build(),
- (exchange, request) -> {
+ return builder.build();
+ }
+
+ private McpSchema.GetPromptResult getPrompt(McpServerPrompt prompt,
McpSchema.GetPromptRequest request) {
Map<String, String> arguments = new LinkedHashMap<>();
if (request.arguments() != null) {
@@ -426,7 +430,6 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
return McpSchema.GetPromptResult.builder(messages)
.description(result.description())
.build();
- });
}
private McpSchema.PromptMessage toPromptMessage(McpPromptMessage message) {
@@ -517,4 +520,229 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
return scheme.matches("[A-Za-z][A-Za-z0-9+.-]*") ? scheme : null;
}
+ /**
+ * The calls the engine makes on a Spring AI MCP server, whether it keeps
sessions or not. Every handler receives
+ * the MCP transport context of the request, which carries the caller
identity.
+ */
+ private interface ServerOperations {
+
+ McpSchema.ServerCapabilities capabilities();
+
+ List<McpSchema.Tool> listTools();
+
+ void addTool(
+ McpSchema.Tool tool,
+ BiFunction<McpTransportContext, McpSchema.CallToolRequest,
McpSchema.CallToolResult> handler);
+
+ void removeTool(String name);
+
+ List<McpSchema.Resource> listResources();
+
+ void addResource(
+ McpSchema.Resource resource,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler);
+
+ void removeResource(String uri);
+
+ List<McpSchema.ResourceTemplate> listResourceTemplates();
+
+ void addResourceTemplate(
+ McpSchema.ResourceTemplate template,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler);
+
+ void removeResourceTemplate(String uriTemplate);
+
+ List<McpSchema.Prompt> listPrompts();
+
+ void addPrompt(
+ McpSchema.Prompt prompt,
+ BiFunction<McpTransportContext, McpSchema.GetPromptRequest,
McpSchema.GetPromptResult> handler);
+
+ void removePrompt(String name);
+
+ void notifyResourcesListChanged();
+ }
+
+ /**
+ * The Spring AI MCP server that keeps a session per client ({@code SSE}
or {@code STREAMABLE}).
+ */
+ private record SessionServerOperations(McpSyncServer server) implements
ServerOperations {
+
+ private static McpTransportContext transportContext(
+ McpSyncServerExchange exchange) {
+ return exchange != null ? exchange.transportContext() : null;
+ }
+
+ @Override
+ public McpSchema.ServerCapabilities capabilities() {
+ return server.getServerCapabilities();
+ }
+
+ @Override
+ public List<McpSchema.Tool> listTools() {
+ return server.listTools();
+ }
+
+ @Override
+ public void addTool(
+ McpSchema.Tool tool,
+ BiFunction<McpTransportContext, McpSchema.CallToolRequest,
McpSchema.CallToolResult> handler) {
+ server.addTool(McpServerFeatures.SyncToolSpecification.builder()
+ .tool(tool)
+ .callHandler((exchange, request) ->
handler.apply(transportContext(exchange), request))
+ .build());
+ }
+
+ @Override
+ public void removeTool(String name) {
+ server.removeTool(name);
+ }
+
+ @Override
+ public List<McpSchema.Resource> listResources() {
+ return server.listResources();
+ }
+
+ @Override
+ public void addResource(
+ McpSchema.Resource resource,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler) {
+ server.addResource(new McpServerFeatures.SyncResourceSpecification(
+ resource, (exchange, request) ->
handler.apply(transportContext(exchange), request)));
+ }
+
+ @Override
+ public void removeResource(String uri) {
+ server.removeResource(uri);
+ }
+
+ @Override
+ public List<McpSchema.ResourceTemplate> listResourceTemplates() {
+ return server.listResourceTemplates();
+ }
+
+ @Override
+ public void addResourceTemplate(
+ McpSchema.ResourceTemplate template,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler) {
+ server.addResourceTemplate(new
McpServerFeatures.SyncResourceTemplateSpecification(
+ template, (exchange, request) ->
handler.apply(transportContext(exchange), request)));
+ }
+
+ @Override
+ public void removeResourceTemplate(String uriTemplate) {
+ server.removeResourceTemplate(uriTemplate);
+ }
+
+ @Override
+ public List<McpSchema.Prompt> listPrompts() {
+ return server.listPrompts();
+ }
+
+ @Override
+ public void addPrompt(
+ McpSchema.Prompt prompt,
+ BiFunction<McpTransportContext, McpSchema.GetPromptRequest,
McpSchema.GetPromptResult> handler) {
+ server.addPrompt(new McpServerFeatures.SyncPromptSpecification(
+ prompt, (exchange, request) ->
handler.apply(transportContext(exchange), request)));
+ }
+
+ @Override
+ public void removePrompt(String name) {
+ server.removePrompt(name);
+ }
+
+ @Override
+ public void notifyResourcesListChanged() {
+ server.notifyResourcesListChanged();
+ }
+ }
+
+ /**
+ * The Spring AI stateless MCP server ({@code STATELESS}): no session, so
no notification can reach a client.
+ */
+ private record StatelessServerOperations(McpStatelessSyncServer server)
implements ServerOperations {
+
+ @Override
+ public McpSchema.ServerCapabilities capabilities() {
+ return server.getServerCapabilities();
+ }
+
+ @Override
+ public List<McpSchema.Tool> listTools() {
+ return server.listTools();
+ }
+
+ @Override
+ public void addTool(
+ McpSchema.Tool tool,
+ BiFunction<McpTransportContext, McpSchema.CallToolRequest,
McpSchema.CallToolResult> handler) {
+
server.addTool(McpStatelessServerFeatures.SyncToolSpecification.builder()
+ .tool(tool)
+ .callHandler(handler)
+ .build());
+ }
+
+ @Override
+ public void removeTool(String name) {
+ server.removeTool(name);
+ }
+
+ @Override
+ public List<McpSchema.Resource> listResources() {
+ return server.listResources();
+ }
+
+ @Override
+ public void addResource(
+ McpSchema.Resource resource,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler) {
+ server.addResource(new
McpStatelessServerFeatures.SyncResourceSpecification(resource, handler));
+ }
+
+ @Override
+ public void removeResource(String uri) {
+ server.removeResource(uri);
+ }
+
+ @Override
+ public List<McpSchema.ResourceTemplate> listResourceTemplates() {
+ return server.listResourceTemplates();
+ }
+
+ @Override
+ public void addResourceTemplate(
+ McpSchema.ResourceTemplate template,
+ BiFunction<McpTransportContext, McpSchema.ReadResourceRequest,
McpSchema.ReadResourceResult> handler) {
+ server.addResourceTemplate(new
McpStatelessServerFeatures.SyncResourceTemplateSpecification(template,
handler));
+ }
+
+ @Override
+ public void removeResourceTemplate(String uriTemplate) {
+ server.removeResourceTemplate(uriTemplate);
+ }
+
+ @Override
+ public List<McpSchema.Prompt> listPrompts() {
+ return server.listPrompts();
+ }
+
+ @Override
+ public void addPrompt(
+ McpSchema.Prompt prompt,
+ BiFunction<McpTransportContext, McpSchema.GetPromptRequest,
McpSchema.GetPromptResult> handler) {
+ server.addPrompt(new
McpStatelessServerFeatures.SyncPromptSpecification(prompt, handler));
+ }
+
+ @Override
+ public void removePrompt(String name) {
+ server.removePrompt(name);
+ }
+
+ @Override
+ public void notifyResourcesListChanged() {
+ // a stateless server has no session to notify
+ }
+ }
+
}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java
index 4d03cd21cf5..f87089f0fcc 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java
@@ -146,11 +146,22 @@ public final class SpringAiMcpTransportContext {
* @return the captured caller context, or the empty context
*/
static McpToolCallContext from(McpSyncServerExchange exchange) {
- if (exchange == null || exchange.transportContext() == null) {
+ return from(exchange != null ? exchange.transportContext() : null);
+ }
+
+ /**
+ * Retrieves the caller context attached to the MCP request by the
transport extractor, as the stateless MCP server
+ * passes it to the handlers.
+ *
+ * @param transportContext the MCP transport context of the request
+ * @return the captured caller context, or the empty context
+ */
+ static McpToolCallContext from(McpTransportContext transportContext) {
+ if (transportContext == null) {
return McpToolCallContext.EMPTY;
}
- Object value = exchange.transportContext().get(CALL_CONTEXT_KEY);
+ Object value = transportContext.get(CALL_CONTEXT_KEY);
return value instanceof McpToolCallContext context
? context
: McpToolCallContext.EMPTY;
diff --git
a/components-starter/camel-mcp-server-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
b/components-starter/camel-mcp-server-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
index df27bbf2747..00dee30b4c7 100644
---
a/components-starter/camel-mcp-server-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
+++
b/components-starter/camel-mcp-server-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -16,3 +16,4 @@
## ---------------------------------------------------------------------------
org.apache.camel.springboot.mcp.server.CamelMcpServerAutoConfiguration
org.apache.camel.springboot.mcp.server.CamelMcpServerTransportAutoConfiguration
+org.apache.camel.springboot.mcp.server.CamelMcpServerStatelessTransportAutoConfiguration
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerStatelessTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerStatelessTest.java
new file mode 100644
index 00000000000..147f6672c54
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerStatelessTest.java
@@ -0,0 +1,186 @@
+/*
+ * 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.springboot.mcp.server;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Base64;
+import java.util.Map;
+
+import io.modelcontextprotocol.client.McpClient;
+import io.modelcontextprotocol.client.McpSyncClient;
+import
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
+import io.modelcontextprotocol.spec.McpSchema;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mcp.server.McpServerEngine;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.apache.camel.test.spring.junit6.CamelSpringBootTest;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.Customizer;
+import
org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import org.springframework.security.web.SecurityFilterChain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The Spring AI stateless MCP server ({@code
spring.ai.mcp.server.protocol=STATELESS}) serves the Camel routes
+ * (CAMEL-27145): no session is created, Camel's Origin validation applies,
and the authenticated caller reaches the
+ * route.
+ */
+@EnableAutoConfiguration
+@CamelSpringBootTest
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = {
SpringBootMcpServerStatelessTest.TestConfiguration.class },
+ properties = {
+ "spring.main.banner-mode=off",
+ "spring.ai.mcp.server.protocol=STATELESS",
+ "camel.mcp-server.tags=stateless",
+ "camel.main.run-controller=false" })
+public class SpringBootMcpServerStatelessTest {
+
+ private static final String AUTHORIZATION = "Basic " + Base64.getEncoder()
+
.encodeToString("mcp-user:mcp-secret".getBytes(StandardCharsets.UTF_8));
+
+ private static final String INITIALIZE = """
+
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25",
+ "capabilities":{},"clientInfo":{"name":"test","version":"1"}}}""";
+
+ private static final HttpClient HTTP = HttpClient.newHttpClient();
+
+ @LocalServerPort
+ private int port;
+
+ @Autowired
+ private McpServerEngine engine;
+
+ @Configuration
+ public static class TestConfiguration {
+
+ @Bean
+ public InMemoryUserDetailsManager mcpTestUsers() {
+ return new InMemoryUserDetailsManager(
+
User.withUsername("mcp-user").password("{noop}mcp-secret").roles("MCP_USER").build());
+ }
+
+ @Bean
+ public SecurityFilterChain mcpTestSecurityFilterChain(HttpSecurity
http) throws Exception {
+ return http
+ .csrf(csrf -> csrf.ignoringRequestMatchers("/mcp"))
+ .authorizeHttpRequests(authorize -> authorize
+ .requestMatchers("/mcp").authenticated()
+ .anyRequest().permitAll())
+ .httpBasic(Customizer.withDefaults())
+ .build();
+ }
+
+ @Bean
+ public RouteBuilder routes() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("ai-tool:say_hello?tags=stateless&description=Say
hello"
+ +
"¶meter.name=string¶meter.name.required=true")
+ .setBody(simple("Hello ${header.name}"));
+
+ from("ai-tool:who_am_i?tags=stateless&description=Return
the authenticated caller")
+ .process(exchange ->
exchange.getMessage().setBody("name=" + exchange.getProperty(
+
McpToolCallContext.SECURITY_PRINCIPAL_NAME_PROPERTY)));
+ }
+ };
+ }
+ }
+
+ @Test
+ void engineIsBoundToTheStatelessServer() {
+ assertThat(engine).isInstanceOf(SpringAiMcpServerEngine.class);
+ }
+
+ @Test
+ void clientCallsToolsWithoutSession() {
+ McpSyncClient client = McpClient
+
.sync(HttpClientStreamableHttpTransport.builder("http://localhost:" + port)
+ .addHttpRequestCustomizer(
+ (builder, method, endpoint, body, context) ->
builder.header("Authorization",
+ AUTHORIZATION))
+ .build())
+ .requestTimeout(Duration.ofSeconds(10))
+ .initializationTimeout(Duration.ofSeconds(10))
+ .build();
+ try {
+ client.initialize();
+
+
assertThat(client.listTools().tools()).extracting(McpSchema.Tool::name)
+ .containsExactlyInAnyOrder("say_hello", "who_am_i");
+ McpSchema.CallToolResult hello = client.callTool(
+
McpSchema.CallToolRequest.builder("say_hello").arguments(Map.of("name",
"Camel")).build());
+ assertThat(hello.content().toString()).contains("Hello Camel");
+ McpSchema.CallToolResult caller = client.callTool(
+
McpSchema.CallToolRequest.builder("who_am_i").arguments(Map.of()).build());
+ assertThat(caller.content().toString()).contains("name=mcp-user");
+ } finally {
+ client.closeGracefully();
+ }
+ }
+
+ @Test
+ void initializeReturnsNoSessionAndGetIsNotAllowed() throws Exception {
+ HttpResponse<String> initialize = post(INITIALIZE, null);
+ assertThat(initialize.statusCode()).isEqualTo(200);
+
assertThat(initialize.headers().firstValue("Mcp-Session-Id")).isEmpty();
+
+ HttpResponse<String> get = HTTP.send(request(null).header("Accept",
"text/event-stream").GET().build(),
+ HttpResponse.BodyHandlers.ofString());
+ assertThat(get.statusCode()).isEqualTo(405);
+ }
+
+ @Test
+ void originIsValidated() throws Exception {
+ assertThat(post(INITIALIZE,
"http://localhost:3000").statusCode()).isEqualTo(200);
+ assertThat(post(INITIALIZE,
"https://attacker.example").statusCode()).isEqualTo(403);
+ }
+
+ private HttpResponse<String> post(String body, String origin) throws
Exception {
+ HttpRequest.Builder builder = request(origin)
+ .header("Content-Type", "application/json")
+ .header("Accept", "application/json, text/event-stream")
+ .POST(HttpRequest.BodyPublishers.ofString(body));
+ return HTTP.send(builder.build(),
HttpResponse.BodyHandlers.ofString());
+ }
+
+ private HttpRequest.Builder request(String origin) {
+ HttpRequest.Builder builder =
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/mcp"))
+ .timeout(Duration.ofSeconds(10))
+ .header("Authorization", AUTHORIZATION);
+ if (origin != null) {
+ builder.header("Origin", origin);
+ }
+ return builder;
+ }
+}
diff --git a/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
b/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
index fb761de95fb..fded0f8619d 100644
--- a/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
+++ b/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
@@ -327,9 +327,10 @@ spring.ai.mcp.server.prompt-change-notification = true
=== Origin validation
-Camel's principal-aware Streamable HTTP provider is selected only when
-`spring.ai.mcp.server.protocol=STREAMABLE` and the Camel transport activation
-condition is satisfied:
+Camel's principal-aware HTTP transport is selected only when
+`spring.ai.mcp.server.protocol` is `STREAMABLE` or `STATELESS` (see
+<<_serving_without_sessions>>) and the Camel transport activation condition is
+satisfied:
* By default, the Camel provider is selected when `camel.mcp-server.tags` is
configured. This enables the Origin validator and authenticated caller
@@ -372,10 +373,11 @@ browser-based clients. Scheme and host matching is
case-insensitive, and
default HTTP and HTTPS ports are normalized.
If Camel tags or Origin settings are configured while the Spring AI protocol
-is unset or uses SSE, the Camel Streamable HTTP provider is not installed.
+is unset or uses SSE, the Camel HTTP transport is not installed.
The starter logs a warning because Origin validation and caller-context
extraction are not active in that configuration. Select
-`spring.ai.mcp.server.protocol=STREAMABLE` when those protections are required.
+`spring.ai.mcp.server.protocol=STREAMABLE` (or `STATELESS`) when those
+protections are required.
With the Spring AI 2.0.2 WebMVC transport, an Origin rejection currently
returns HTTP 403 with a plain-text `Invalid Origin header` response body.
@@ -439,6 +441,41 @@ spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp
----
+=== Serving without sessions
+
+With `spring.ai.mcp.server.protocol=STREAMABLE`, the Spring AI MCP server keeps
+a session for each client in memory: the session ends when the application
+restarts, and a request that reaches another instance finds no session, so
+several instances need session affinity in front of them.
+
+With `spring.ai.mcp.server.protocol=STATELESS`, Spring AI serves each request
on
+its own, and the starter registers the Camel routes on that stateless server.
+No `Mcp-Session-Id` is returned, so a restart or another instance is invisible
+to the client. Camel's Origin validation and caller-context extraction apply as
+with `STREAMABLE`, through `WebMvcStatelessServerTransport`; an
+application-provided `WebMvcStatelessServerTransport` takes precedence.
+
+[source,properties]
+----
+spring.ai.mcp.server.protocol = STATELESS
+camel.mcp-server.tags = crm
+----
+
+Without a session, the server cannot send anything outside the answer to a
+request:
+
+* clients are not notified when Camel routes add or remove tools, resources or
+ prompts; they see the change at their next list request,
+* a `GET` on the endpoint (the stream for server-initiated messages) is
answered
+ with HTTP 405,
+* features that need a server-initiated request, such as sampling or
+ elicitation, are not available.
+
+The stateless mode serves the MCP protocol versions that open with an
+`initialize` handshake (2025-11-25 and earlier). Protocol version 2026-07-28,
+which has no session by design, is not served by this starter yet: it needs
+Spring AI 2.1.0.
+
=== Connecting MCP clients
Any MCP client can connect over streamable HTTP. Another Camel integration