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 63329d36cb0 CAMEL-26360: camel-mcp-server-starter - apply transport
customizers, refuse features the server cannot serve, fix the docs (#2129)
63329d36cb0 is described below
commit 63329d36cb0627261fc1fd39ac1d97389e12b8de
Author: Federico Mariani <[email protected]>
AuthorDate: Thu Nov 26 10:45:19 2026 +0100
CAMEL-26360: camel-mcp-server-starter - apply transport customizers, refuse
features the server cannot serve, fix the docs (#2129)
* CAMEL-26360: camel-mcp-server-starter - fix the stdio recipe version, the
OAuth audience and the property descriptions in the docs
* CAMEL-26360: camel-mcp-server-starter - apply the transport customizers
and keep Spring AI's transport for an ASYNC server
* CAMEL-26360: camel-mcp-server-starter - refuse features the Spring AI
server cannot serve instead of failing or evicting application entries
* CAMEL-26360: camel-mcp-server-starter - the stdio recipe names the Spring
AI version only in the snippet
---
.../src/main/doc/intro.adoc | 31 ++-
.../src/main/doc/usage.adoc | 83 +++++-
.../src/main/docs/mcp-server.json | 15 +-
.../CamelMcpServerAsyncTypeAutoConfiguration.java | 92 +++++++
.../server/CamelMcpServerAutoConfiguration.java | 7 +
...lMcpServerModernTransportAutoConfiguration.java | 4 +-
...pServerStatelessTransportAutoConfiguration.java | 17 +-
.../CamelMcpServerTransportAutoConfiguration.java | 22 +-
.../server/CamelMcpServerTransportCondition.java | 24 +-
.../server/McpServerConfigurationProperties.java | 33 +--
.../mcp/server/SpringAiMcpServerEngine.java | 29 ++
.../mcp/server/SpringAiModernMcpServerEngine.java | 124 +++++++--
...rk.boot.autoconfigure.AutoConfiguration.imports | 1 +
.../mcp/server/CamelMcpServerAsyncTypeTest.java | 251 +++++++++++++++++
.../CamelMcpServerTransportCustomizerTest.java | 299 +++++++++++++++++++++
.../McpServerConfigurationPropertiesTest.java | 38 +++
.../mcp/server/SpringAiMcpServerEngineTest.java | 102 +++++++
.../server/SpringAiModernMcpServerEngineTest.java | 284 +++++++++++++++++++
...ingBootMcpServerToolCapabilityDisabledTest.java | 128 +++++++++
.../modules/ROOT/pages/starters/mcp-server.adoc | 124 +++++++--
20 files changed, 1621 insertions(+), 87 deletions(-)
diff --git
a/components-starter/camel-mcp-server-starter/src/main/doc/intro.adoc
b/components-starter/camel-mcp-server-starter/src/main/doc/intro.adoc
index 80ec3a60228..cee79de7360 100644
--- a/components-starter/camel-mcp-server-starter/src/main/doc/intro.adoc
+++ b/components-starter/camel-mcp-server-starter/src/main/doc/intro.adoc
@@ -44,13 +44,15 @@ Resource Server starter. Let Spring Boot manage their
versions:
</dependency>
----
-Configure the authorization server issuer and select the Streamable HTTP
-transport:
+Configure the authorization server issuer and the audience of the accepted
+tokens, and select the Streamable HTTP transport:
[source,properties]
----
spring.ai.mcp.server.protocol = STREAMABLE
spring.security.oauth2.resourceserver.jwt.issuer-uri =
https://idp.example.com/issuer
+# Accept only the tokens issued for this MCP server: its resource URI, as
mcp.security.resource-uri below.
+spring.security.oauth2.resourceserver.jwt.audiences =
https://mcp.example.com/mcp
# Application-specific properties used by this example; not Camel starter
options.
# Canonical, externally visible URLs for this protected MCP resource.
@@ -68,6 +70,7 @@ authentication so MCP clients can discover the authorization
server.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
@@ -77,6 +80,7 @@ import org.springframework.security.web.SecurityFilterChain;
public class McpSecurityConfiguration {
@Bean
+ @Order(1)
SecurityFilterChain mcpSecurity(
HttpSecurity http,
@Value("${mcp.security.resource-uri}") String resourceUri,
@@ -111,10 +115,27 @@ public class McpSecurityConfiguration {
}
----
+The `securityMatcher` limits this filter chain to the MCP endpoint and the
+metadata paths. Once the application defines a `SecurityFilterChain`, Spring
+Boot's default chain backs off, so requests to the other endpoints of the
+application match no chain and are not secured: keep a filter chain of the
+application for them, ordered after this one (a higher `@Order` value), as
+Spring Security requires a chain that matches any request to come last.
+
The issuer in `authorizationServer` must identify the authorization server
that issues tokens accepted by this resource server. Spring Security validates
-JWT bearer tokens using the configured issuer. Its protected-resource metadata
-support publishes the metadata document. For the `/mcp` endpoint, configure
+JWT bearer tokens using the configured issuer. Spring Boot checks the
+audience (`aud` claim) only when
+`spring.security.oauth2.resourceserver.jwt.audiences` is set: without it, a
+token that the same issuer minted for another API is accepted, while the MCP
+authorization specification requires the server to accept only the tokens
+issued for it. The setting applies to the `JwtDecoder` that Spring Boot
+auto-configures, and so to every filter chain that uses it: when other
+endpoints of the application accept tokens issued for another audience, give
+the MCP chain its own decoder that checks this audience instead, with
+`.jwt(jwt -> jwt.decoder(mcpJwtDecoder))`. Spring Security's protected-resource
+metadata support publishes the metadata document. For the `/mcp` endpoint,
+configure
`mcp.security.resource-uri` as `https://mcp.example.com/mcp` and
`mcp.security.resource-metadata-uri` as
`https://mcp.example.com/.well-known/oauth-protected-resource/mcp`.
@@ -147,7 +168,7 @@ The example ignores CSRF only for the MCP endpoint because
MCP clients send
bearer tokens rather than browser session-based CSRF tokens. Do not disable
CSRF protection globally when the application uses it for other endpoints.
If your MCP endpoint is configured at a path other than `/mcp`, update the
-security matchers and both canonical URL properties accordingly.
+security matchers, both canonical URL properties and the audience accordingly.
For MCP tool calls, the Camel Spring Boot engine captures the authenticated
Spring principal and its name. Camel roles and OAuth scopes are derived only
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 41da5a93335..4acef11dd02 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
@@ -130,6 +130,14 @@ spring.ai.mcp.server.resource-change-notification = true
spring.ai.mcp.server.prompt-change-notification = true
----
+When the Spring AI MCP server serves no tools, resources or prompts, for
+example with `spring.ai.mcp.server.capabilities.tool=false`, the Camel routes
+of that kind are not exposed: the application starts, the routes keep running,
+and the starter logs why they are not served. With `MODERN` (see
+<<_mcp_protocol_version_2026_07_28>>), such a property only stops Spring AI
+from auto-configuring the repository of that kind: a repository the
+application defines is still served.
+
=== Origin validation
Camel's principal-aware HTTP transport is selected only when
@@ -139,8 +147,9 @@ Camel's principal-aware HTTP transport is selected only when
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
- context needed by Camel route capabilities.
+ configured and the Spring AI MCP server is of the `SYNC` type (see
+ <<_server_type>>). This enables the Origin validator and authenticated
+ caller context needed by Camel route capabilities.
* Set `camel.mcp-server.transport-enabled=true` to select the Camel provider
even when no Camel tags are configured, for example when the application
exposes only Spring-defined `@McpTool`, `@McpResource`, or `@McpPrompt`
@@ -231,6 +240,36 @@ provider must still be configured with an authentication
mechanism and the
appropriate authorization policy. The `camel.mcp-server.allowed-origins`
property is applied only to Camel's auto-configured provider.
+To change a few settings of the transport rather than replace it, define
+`McpServerCustomizer` beans for its builder, as with Spring AI's own
+transports:
`McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>`
+for `STREAMABLE`, `McpServerCustomizer<WebMvcStatelessServerTransport.Builder>`
+for `STATELESS` and `McpServerCustomizer<WebMvcModernServerTransport.Builder>`
+for `MODERN`. When Camel's transport is selected, they are applied too, in
+their order and after Camel's settings, so a customizer takes precedence over
+Camel:
+
+* a customizer that sets other options, such as the maximum number of
+ sessions or the session idle timeout, keeps Camel's Origin validation and
+ authenticated caller context;
+* a customizer that sets its own security validator (`securityValidator`, or
+ `httpHeaderValidator` for `MODERN`) replaces Camel's Origin validation, and
+ `camel.mcp-server.allowed-origins` no longer applies;
+* a customizer that sets its own context extractor (`contextExtractor`)
+ replaces Camel's authenticated caller context, unless it builds the
+ context with `SpringAiMcpTransportContext.extract(request, entries)` as
+ shown above.
+
+[source,java]
+----
+@Bean
+McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
mcpTransportCustomizer() {
+ return builder -> builder
+ .maxSessions(1000)
+ .sessionIdleTimeout(Duration.ofMinutes(30));
+}
+----
+
The streamable HTTP transport has to be selected explicitly with
`spring.ai.mcp.server.protocol=STREAMABLE`; when the property is not set,
Spring AI serves the deprecated SSE transport instead and there is no
@@ -248,6 +287,20 @@ spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp
----
+=== Server type
+
+Whatever the protocol, the starter serves the Camel routes only on a Spring AI
+MCP server of the `SYNC` type: `spring.ai.mcp.server.type=SYNC`, the default.
+With `spring.ai.mcp.server.type=ASYNC`:
+
+* the Camel routes are not served, and the starter logs a warning when
+ `camel.mcp-server.tags` is configured;
+* Spring AI's transport is kept, without Camel's Origin validation and
+ authenticated caller context, unless
+ `camel.mcp-server.transport-enabled=true` is set with
+ `spring.ai.mcp.server.protocol` `STREAMABLE`, `STATELESS` or `MODERN` and
+ the stdio transport disabled.
+
=== Serving without sessions
With `spring.ai.mcp.server.protocol=STREAMABLE`, the Spring AI MCP server keeps
@@ -301,9 +354,13 @@ camel.mcp-server.tags = crm
The Camel routes are added to the tool, resource and prompt repositories that
Spring AI auto-configures, next to the application's own tools, resources and
prompts. A Camel route with the name or URI of one of them is refused, as with
-the other protocols. Camel's Origin validation and caller-context extraction
-apply to every request: the starter provides them to Spring AI's
-`WebMvcModernServerTransport` as `ServerHttpHeaderValidator` and
+the other protocols. A resource with the URI of a resource template, or a
+template with the URI of a resource, is refused too, because the Spring AI
+resource repository removes both together: when the application registers such
+an entry at runtime, after the Camel route, stopping the route removes it as
+well, and the starter logs a warning. Camel's Origin validation and
+caller-context extraction apply to every request: the starter provides them to
+Spring AI's `WebMvcModernServerTransport` as `ServerHttpHeaderValidator` and
`McpTransportContextExtractor` beans, and beans of those types defined by the
application take precedence.
@@ -315,8 +372,8 @@ Be aware that:
2026-07-28 first and fall back to `initialize` connect with 2026-07-28. Camel
Main and Camel JBang serve both kinds of client on the same endpoint (see
xref:components:others:mcp-server.adoc[MCP Server]);
-* only `spring.ai.mcp.server.type=SYNC`, the default, is supported: with
- `ASYNC`, the starter does not register the Camel routes;
+* as with the other protocols, only `spring.ai.mcp.server.type=SYNC`, the
+ default, is supported (see <<_server_type>>);
* if the application defines its own tool, resource or prompt repository, the
Camel routes of that kind are not served, and the starter logs a warning;
* protocol version 2026-07-28 is built on the `io.modelcontextprotocol.modern`
@@ -375,11 +432,19 @@ the plain `spring-ai-starter-mcp-server`. Swap the
transport starter:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server</artifactId>
- <version>2.0.0</version>
+ <!-- the Spring AI version of camel-mcp-server-starter -->
+ <version>2.1.0</version>
</dependency>
----
-and enable the stdio transport:
+The version of `spring-ai-starter-mcp-server` must be the Spring AI version
+the starter is built with: the version of `spring-ai-starter-mcp-server-webmvc`
+in the POM of `camel-mcp-server-starter`. Another
+version, including one that the dependency management of the application
+imposes, for example with an older Spring AI BOM, can lack MCP Java SDK types
+the starter uses, and the application then fails at startup.
+
+Then enable the stdio transport:
[source,properties]
----
diff --git
a/components-starter/camel-mcp-server-starter/src/main/docs/mcp-server.json
b/components-starter/camel-mcp-server-starter/src/main/docs/mcp-server.json
index 5da50b38751..d2bfaee338e 100644
--- a/components-starter/camel-mcp-server-starter/src/main/docs/mcp-server.json
+++ b/components-starter/camel-mcp-server-starter/src/main/docs/mcp-server.json
@@ -10,7 +10,7 @@
{
"name": "camel.mcp-server.allowed-origins",
"type": "java.lang.String",
- "description": "Comma-separated list of origins allowed to call the
Streamable HTTP MCP endpoint. Entries may be exact origins or use a wildcard
port, for example http:\/\/localhost:*. When unset, only loopback origins are
allowed. Requests without an Origin header are accepted. This setting is
applied when Camel's Streamable HTTP transport provider is selected.",
+ "description": "Comma-separated list of origins allowed to call the MCP
HTTP endpoint (protocol STREAMABLE, STATELESS or MODERN). Entries may be exact
origins or use a wildcard port, for example http:\/\/localhost:*. When unset,
only loopback origins are allowed. Requests without an Origin header are
accepted. This setting is applied when Camel's Origin validation is installed,
see camel.mcp-server.transport-enabled.",
"sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties"
},
{
@@ -24,13 +24,15 @@
"name": "camel.mcp-server.prompt-timeout",
"type": "java.lang.Long",
"description": "Per-request prompt execution timeout in milliseconds. A
request exceeding the timeout returns an error to the MCP client; the
underlying route may continue running until it completes.",
- "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties"
+ "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties",
+ "defaultValue": 20000
},
{
"name": "camel.mcp-server.resource-timeout",
"type": "java.lang.Long",
"description": "Per-read resource execution timeout in milliseconds. A
read exceeding the timeout returns an error to the MCP client; the underlying
route keeps running until it completes on its own.",
- "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties"
+ "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties",
+ "defaultValue": 20000
},
{
"name": "camel.mcp-server.tags",
@@ -41,13 +43,14 @@
{
"name": "camel.mcp-server.tool-timeout",
"type": "java.lang.Long",
- "description": "Per-call tool execution timeout in milliseconds. A call
exceeding the timeout returns an error result to the MCP client; the underlying
route keeps running until it completes on its own. The default is 20000
milliseconds.",
- "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties"
+ "description": "Per-call tool execution timeout in milliseconds. A call
exceeding the timeout returns an error result to the MCP client; the underlying
route keeps running until it completes on its own.",
+ "sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties",
+ "defaultValue": 20000
},
{
"name": "camel.mcp-server.transport-enabled",
"type": "java.lang.Boolean",
- "description": "Whether to replace Spring AI's default Streamable HTTP
transport with Camel's transport. When unset, replacement is enabled only when
{@code tags} is configured. Set this to true to enable Camel Origin validation
and caller-context extraction without Camel routes, or false to keep Spring
AI's provider while leaving the Camel bridge independently enabled.",
+ "description": "Whether to install Camel's Origin validation and
caller-context extraction on the Spring AI MCP HTTP transport (protocol
STREAMABLE, STATELESS or MODERN). When unset, they are installed only when
camel.mcp-server.tags is configured and spring.ai.mcp.server.type is SYNC, the
default. Set this to true to install them without Camel routes or with an ASYNC
server, or false to keep Spring AI's transport as is while leaving the Camel
bridge independently enabled.",
"sourceType":
"org.apache.camel.springboot.mcp.server.McpServerConfigurationProperties"
}
],
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeAutoConfiguration.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeAutoConfiguration.java
new file mode 100644
index 00000000000..cb330b2b07f
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeAutoConfiguration.java
@@ -0,0 +1,92 @@
+/*
+ * 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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.SmartInitializingSingleton;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.core.env.Environment;
+import org.springframework.util.StringUtils;
+
+/**
+ * Warns that the Camel routes are not served when the Spring AI MCP server is
of the {@code ASYNC} type
+ * ({@code spring.ai.mcp.server.type=ASYNC}), whatever the protocol: the Camel
routes are served only on a {@code SYNC}
+ * server, so {@link CamelMcpServerAutoConfiguration} backs off, and Camel's
HTTP transport is installed only with
+ * {@code camel.mcp-server.transport-enabled=true} (see {@link
CamelMcpServerTransportCondition}).
+ */
+@AutoConfiguration
+@ConditionalOnProperty(
+ prefix = "camel.mcp-server",
+ name = "enabled",
+ matchIfMissing = true)
+@ConditionalOnProperty(
+ prefix = "spring.ai.mcp.server",
+ name = "enabled",
+ havingValue = "true",
+ matchIfMissing = true)
+@ConditionalOnProperty(
+ prefix = "spring.ai.mcp.server",
+ name = "type",
+ havingValue = "ASYNC")
+@EnableConfigurationProperties(McpServerConfigurationProperties.class)
+public class CamelMcpServerAsyncTypeAutoConfiguration {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(CamelMcpServerAsyncTypeAutoConfiguration.class);
+
+ // a SmartInitializingSingleton is created even with
spring.main.lazy-initialization=true
+ @Bean
+ SmartInitializingSingleton camelMcpServerAsyncTypeWarning(
+ McpServerConfigurationProperties properties, Environment
environment) {
+ return () -> warnIfCamelRoutesAreSelected(properties, environment);
+ }
+
+ static void warnIfCamelRoutesAreSelected(McpServerConfigurationProperties
properties, Environment environment) {
+ if (!StringUtils.hasText(properties.getTags())) {
+ return;
+ }
+ if (isCamelTransportInstalled(properties, environment)) {
+ LOG.warn("Camel MCP routes tagged [{}] are configured, but
spring.ai.mcp.server.type is ASYNC: the"
+ + " Camel routes are served only on a SYNC Spring AI MCP
server, so they are not served. Set"
+ + " spring.ai.mcp.server.type=SYNC (the default) to serve
them.",
+ properties.getTags());
+ } else {
+ LOG.warn("Camel MCP routes tagged [{}] are configured, but
spring.ai.mcp.server.type is ASYNC: the"
+ + " Camel routes are served only on a SYNC Spring AI MCP
server, so they are not served, and"
+ + " Camel does not install its Origin validation and
caller-context extraction on the MCP"
+ + " transport. Set spring.ai.mcp.server.type=SYNC (the
default) to serve them.",
+ properties.getTags());
+ }
+ }
+
+ /**
+ * Whether Camel's transport is installed although the server is {@code
ASYNC}: only when it is explicitly enabled,
+ * for an HTTP protocol it supports and without stdio, as the transport
auto-configurations require (stdio is off
+ * when the property is missing or {@code false}, as in Spring AI's {@code
McpServerStdioDisabledCondition}).
+ */
+ private static boolean isCamelTransportInstalled(
+ McpServerConfigurationProperties properties, Environment
environment) {
+ String protocol =
environment.getProperty("spring.ai.mcp.server.protocol");
+ return Boolean.TRUE.equals(properties.getTransportEnabled())
+ && ("STREAMABLE".equalsIgnoreCase(protocol) ||
"STATELESS".equalsIgnoreCase(protocol)
+ || "MODERN".equalsIgnoreCase(protocol))
+ &&
"false".equalsIgnoreCase(environment.getProperty("spring.ai.mcp.server.stdio",
"false"));
+ }
+}
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 48695b9c09e..f37d115fca5 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
@@ -160,6 +160,9 @@ public class CamelMcpServerAutoConfiguration {
/**
* Matches when Spring AI auto-configured a synchronous MCP server: with
sessions ({@code SSE},
* {@code STREAMABLE}), stateless ({@code STATELESS}), or for MCP protocol
version 2026-07-28 ({@code MODERN}).
+ * The server type must be {@code SYNC} ({@code
spring.ai.mcp.server.type}, the default) for every protocol, as for
+ * Camel's transport (see {@link CamelMcpServerTransportCondition}): a
synchronous server of the application over an
+ * {@code ASYNC} one does not serve the Camel routes either.
*/
static final class OnSpringAiMcpServerCondition extends AnyNestedCondition
{
@@ -168,10 +171,14 @@ public class CamelMcpServerAutoConfiguration {
}
@ConditionalOnBean(McpSyncServer.class)
+ @ConditionalOnProperty(prefix = "spring.ai.mcp.server", name = "type",
havingValue = "SYNC",
+ matchIfMissing = true)
static final class OnSessionServer {
}
@ConditionalOnBean(McpStatelessSyncServer.class)
+ @ConditionalOnProperty(prefix = "spring.ai.mcp.server", name = "type",
havingValue = "SYNC",
+ matchIfMissing = true)
static final class OnStatelessServer {
}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerModernTransportAutoConfiguration.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerModernTransportAutoConfiguration.java
index 47756755d36..c1153529619 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerModernTransportAutoConfiguration.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerModernTransportAutoConfiguration.java
@@ -37,7 +37,9 @@ import org.springframework.web.servlet.function.ServerRequest;
* Spring AI builds that transport with the {@link ServerHttpHeaderValidator}
and the
* {@link McpTransportContextExtractor} beans of the application context, so
this configuration provides them and
* keeps Spring AI's endpoint and settings. A validator or an extractor of the
application takes precedence, and so
- * does a {@link WebMvcModernServerTransport} of the application.
+ * does a {@link WebMvcModernServerTransport} of the application. Spring AI
applies the {@code McpServerCustomizer}
+ * beans of the {@link WebMvcModernServerTransport.Builder} after these beans,
so a customizer can override them, as
+ * with the Streamable HTTP and stateless transports of Camel.
*/
@AutoConfiguration(
beforeName =
"org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerModernWebMvcAutoConfiguration")
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
index ac37fa806ad..c0b9be7c68c 100644
---
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
@@ -17,9 +17,11 @@
package org.apache.camel.springboot.mcp.server;
import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import org.springframework.ai.mcp.customizer.McpServerCustomizer;
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.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -38,6 +40,10 @@ import tools.jackson.databind.json.JsonMapper;
* endpoint, and adds Camel's Origin validation and a transport context
extractor for the authenticated caller
* identity.
* <p>
+ * As Spring AI does for its own transport, every {@code McpServerCustomizer}
of the
+ * {@link WebMvcStatelessServerTransport.Builder} is applied, in order, after
Camel's settings: a customizer can
+ * override them, for example by setting its own security validator or context
extractor, which then replaces Camel's.
+ * <p>
* An application-defined {@link WebMvcStatelessServerTransport} takes
precedence.
*/
@AutoConfiguration(
@@ -74,14 +80,17 @@ public class
CamelMcpServerStatelessTransportAutoConfiguration {
WebMvcStatelessServerTransport webMvcStatelessServerTransport(
@Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper,
McpServerStreamableHttpProperties serverProperties,
- McpServerConfigurationProperties camelProperties) {
+ McpServerConfigurationProperties camelProperties,
+
ObjectProvider<McpServerCustomizer<WebMvcStatelessServerTransport.Builder>>
customizers) {
- return WebMvcStatelessServerTransport.builder()
+ WebMvcStatelessServerTransport.Builder builder =
WebMvcStatelessServerTransport.builder()
.jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
.messageEndpoint(serverProperties.getMcpEndpoint())
.securityValidator(
CamelMcpServerTransportAutoConfiguration.createOriginValidator(camelProperties.getAllowedOrigins()))
- .contextExtractor(SpringAiMcpTransportContext::extract)
- .build();
+ .contextExtractor(SpringAiMcpTransportContext::extract);
+ // the customizers of the application come last, as with Spring AI's
own transport bean
+ customizers.orderedStream().forEach(customizer ->
customizer.customize(builder));
+ return builder.build();
}
}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java
index 3efc0474be1..3c25fb534d7 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java
@@ -25,9 +25,11 @@ import
io.modelcontextprotocol.server.transport.HeaderAccessor;
import io.modelcontextprotocol.server.transport.ServerHttpHeaderValidator;
import
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
import org.apache.camel.component.mcp.server.McpServerOrigins;
+import org.springframework.ai.mcp.customizer.McpServerCustomizer;
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.WebMvcStreamableServerTransportProvider;
+import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -42,8 +44,13 @@ import tools.jackson.databind.json.JsonMapper;
* Installs a principal-aware Spring AI WebMVC MCP transport.
* <p>
* This configuration runs before Spring AI's default WebMVC transport
configuration.
- * It preserves the Spring AI endpoint and keep-alive settings while adding a
transport
- * context extractor for authenticated caller identity.
+ * It preserves the Spring AI endpoint and keep-alive settings while adding
Camel's Origin
+ * validation and a transport context extractor for authenticated caller
identity.
+ * <p>
+ * As Spring AI does for its own transport, every {@code McpServerCustomizer}
of the
+ * {@link WebMvcStreamableServerTransportProvider.Builder} is applied, in
order, after Camel's
+ * settings: a customizer can override them, for example by setting its own
security validator
+ * or context extractor, which then replaces Camel's.
* <p>
* An application-defined {@link WebMvcStreamableServerTransportProvider}
takes precedence.
*/
@@ -88,16 +95,19 @@ public class CamelMcpServerTransportAutoConfiguration {
WebMvcStreamableServerTransportProvider
webMvcStreamableServerTransportProvider(
@Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper,
McpServerStreamableHttpProperties serverProperties,
- McpServerConfigurationProperties camelProperties) {
+ McpServerConfigurationProperties camelProperties,
+
ObjectProvider<McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>>
customizers) {
- return WebMvcStreamableServerTransportProvider.builder()
+ WebMvcStreamableServerTransportProvider.Builder builder =
WebMvcStreamableServerTransportProvider.builder()
.jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
.mcpEndpoint(serverProperties.getMcpEndpoint())
.keepAliveInterval(serverProperties.getKeepAliveInterval())
.disallowDelete(serverProperties.isDisallowDelete())
.securityValidator(createOriginValidator(camelProperties.getAllowedOrigins()))
- .contextExtractor(SpringAiMcpTransportContext::extract)
- .build();
+ .contextExtractor(SpringAiMcpTransportContext::extract);
+ // the customizers of the application come last, as with Spring AI's
own transport bean
+ customizers.orderedStream().forEach(customizer ->
customizer.customize(builder));
+ return builder.build();
}
/**
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCondition.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCondition.java
index 105b4cbe193..423eb18f52d 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCondition.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCondition.java
@@ -19,16 +19,22 @@ package org.apache.camel.springboot.mcp.server;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
+import org.springframework.core.env.PropertyResolver;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;
/**
- * Controls whether Camel replaces Spring AI's default Streamable HTTP
transport.
- * By default, replacement is enabled only when Camel MCP tags are configured.
- * The explicit transport-enabled property overrides that default.
+ * Controls whether Camel installs its HTTP transport (Origin validation and
authenticated caller identity) for the
+ * Spring AI MCP server of protocol {@code STREAMABLE}, {@code STATELESS} or
{@code MODERN}.
+ * <p>
+ * By default, it is installed only when Camel MCP tags are configured and the
Spring AI MCP server is of the
+ * {@code SYNC} type ({@code spring.ai.mcp.server.type}, the default), the
only type the Camel routes are served on.
+ * The explicit {@code camel.mcp-server.transport-enabled} property overrides
that default.
*/
public final class CamelMcpServerTransportCondition implements Condition {
+ static final String SERVER_TYPE_PROPERTY = "spring.ai.mcp.server.type";
+
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata
metadata) {
Boolean explicitlyEnabled = Binder.get(context.getEnvironment())
@@ -38,6 +44,16 @@ public final class CamelMcpServerTransportCondition
implements Condition {
return explicitlyEnabled;
}
- return
StringUtils.hasText(context.getEnvironment().getProperty("camel.mcp-server.tags"));
+ return
StringUtils.hasText(context.getEnvironment().getProperty("camel.mcp-server.tags"))
+ && isSyncServerType(context.getEnvironment());
+ }
+
+ /**
+ * Whether the Spring AI MCP server is of the {@code SYNC} type, with the
same rule as Spring AI's
+ * {@code @ConditionalOnProperty(name = "spring.ai.mcp.server.type",
havingValue = "SYNC", matchIfMissing = true)}.
+ */
+ static boolean isSyncServerType(PropertyResolver environment) {
+ String type = environment.getProperty(SERVER_TYPE_PROPERTY);
+ return type == null || "SYNC".equalsIgnoreCase(type);
}
}
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java
index 02c126cd0f2..701eb4ddd55 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java
@@ -16,13 +16,13 @@
*/
package org.apache.camel.springboot.mcp.server;
-import org.apache.camel.component.mcp.server.McpServerConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Bridge-owned configuration of the Camel MCP server. Serving concerns
(endpoint path, protocol, server identity)
* are owned by the Spring AI MCP server and configured via {@code
spring.ai.mcp.server.*}.
- * The Streamable HTTP transport also uses {@code allowed-origins} to validate
browser request origins.
+ * Camel's HTTP transport (protocol {@code STREAMABLE}, {@code STATELESS} or
{@code MODERN}) also uses
+ * {@code allowed-origins} to validate browser request origins.
* <p/>
* Note that {@code spring.ai.mcp.server.*} provides no authentication: the
MCP endpoint is served on the
* application's own HTTP port and must be protected by the application, for
example with a Spring Security filter
@@ -38,10 +38,11 @@ public class McpServerConfigurationProperties {
private boolean enabled = true;
/**
- * Whether to replace Spring AI's default Streamable HTTP transport with
Camel's transport.
- * When unset, replacement is enabled only when {@code tags} is
configured. Set this to true
- * to enable Camel Origin validation and caller-context extraction without
Camel routes, or
- * false to keep Spring AI's provider while leaving the Camel bridge
independently enabled.
+ * Whether to install Camel's Origin validation and caller-context
extraction on the Spring AI MCP HTTP transport
+ * (protocol STREAMABLE, STATELESS or MODERN). When unset, they are
installed only when camel.mcp-server.tags is
+ * configured and spring.ai.mcp.server.type is SYNC, the default. Set this
to true to install them without Camel
+ * routes or with an ASYNC server, or false to keep Spring AI's transport
as is
+ * while leaving the Camel bridge independently enabled.
*/
private Boolean transportEnabled;
@@ -52,30 +53,32 @@ public class McpServerConfigurationProperties {
*/
private String tags;
+ // the defaults are literals, not McpServerConstants, so that the
configuration metadata and the options table
+ // show them; McpServerConfigurationPropertiesTest checks they match
McpServerConstants
+
/**
* Per-call tool execution timeout in milliseconds. A call exceeding the
timeout returns an error result to the MCP
* client; the underlying route keeps running until it completes on its
own.
- * The default is 20000 milliseconds.
-*/
- private long toolTimeout = McpServerConstants.DEFAULT_TOOL_TIMEOUT;
+ */
+ private long toolTimeout = 20000;
/**
* Per-read resource execution timeout in milliseconds. A read exceeding
the timeout returns an error
* to the MCP client; the underlying route keeps running until it
completes on its own.
*/
- private long resourceTimeout = McpServerConstants.DEFAULT_RESOURCE_TIMEOUT;
+ private long resourceTimeout = 20000;
/**
* Per-request prompt execution timeout in milliseconds. A request
exceeding the timeout returns an error
* to the MCP client; the underlying route may continue running until it
completes.
*/
- private long promptTimeout = McpServerConstants.DEFAULT_PROMPT_TIMEOUT;
+ private long promptTimeout = 20000;
/**
- * Comma-separated list of origins allowed to call the Streamable HTTP MCP
endpoint.
- * Entries may be exact origins or use a wildcard port, for example
http://localhost:*.
- * When unset, only loopback origins are allowed. Requests without an
Origin header are accepted.
- * This setting is applied when Camel's Streamable HTTP transport provider
is selected.
+ * Comma-separated list of origins allowed to call the MCP HTTP endpoint
(protocol STREAMABLE, STATELESS or MODERN).
+ * Entries may be exact origins or use a wildcard port, for example
http://localhost:*. When unset, only loopback
+ * origins are allowed. Requests without an Origin header are accepted.
This setting is applied when Camel's Origin
+ * validation is installed, see camel.mcp-server.transport-enabled.
*/
private String allowedOrigins;
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 c2ab5e1176d..d97937ab00c 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
@@ -105,6 +105,9 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public void toolAdded(McpServerTool tool) {
+ if (!supportsTools()) {
+ throw capabilityMissing("MCP tool '" + tool.name() + "'", "tools",
"tool");
+ }
if (server.listTools().stream().anyMatch(existing ->
existing.name().equals(tool.name()))) {
throw new McpServerRefusedException(
"An MCP tool named '" + tool.name() + "' is already
registered");
@@ -154,6 +157,9 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public void resourceAdded(McpServerResource resource) {
+ if (!supportsResources()) {
+ throw capabilityMissing("MCP resource '" + resource.uri() + "'",
"resources", "resource");
+ }
if (server.listResources().stream().anyMatch(existing ->
existing.uri().equals(resource.uri()))) {
throw new McpServerRefusedException(
"An MCP resource with URI '" + resource.uri() + "' is
already registered");
@@ -209,6 +215,10 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
@Override
public void resourceTemplateAdded(McpServerResourceTemplate
resourceTemplate) {
+ if (!supportsResourceTemplates()) {
+ throw capabilityMissing(
+ "MCP resource template '" + resourceTemplate.uriTemplate()
+ "'", "resources", "resource");
+ }
List<McpSchema.ResourceTemplate> existingTemplates =
server.listResourceTemplates();
if (existingTemplates.stream()
.anyMatch(existing ->
existing.uriTemplate().equals(resourceTemplate.uriTemplate()))) {
@@ -325,6 +335,9 @@ public class SpringAiMcpServerEngine extends ServiceSupport
implements McpServer
@Override
public void promptAdded(McpServerPrompt prompt) {
+ if (!supportsPrompts()) {
+ throw capabilityMissing("MCP prompt '" + prompt.name() + "'",
"prompts", "prompt");
+ }
if (server.listPrompts().stream().anyMatch(existing ->
existing.name().equals(prompt.name()))) {
throw new McpServerRefusedException(
"An MCP prompt named '" + prompt.name() + "' is already
registered");
@@ -350,6 +363,22 @@ public class SpringAiMcpServerEngine extends
ServiceSupport implements McpServer
return capabilities != null && capabilities.prompts() != null;
}
+ private boolean supportsTools() {
+ McpSchema.ServerCapabilities capabilities = server.capabilities();
+ return capabilities != null && capabilities.tools() != null;
+ }
+
+ /**
+ * The MCP Java SDK rejects a feature of a capability the server does not
have with an
+ * {@link IllegalStateException}, which would fail the route; the feature
is refused instead, so the route and the
+ * other features keep being served.
+ */
+ private static McpServerRefusedException capabilityMissing(String feature,
String capability, String property) {
+ return new McpServerRefusedException(
+ feature + " is not served: the Spring AI MCP server has no " +
capability
+ + " capability (see
spring.ai.mcp.server.capabilities." + property + ")");
+ }
+
private static McpSchema.Resource buildMcpResource(McpServerResource
resource) {
McpSchema.Resource.Builder builder =
McpSchema.Resource.builder(resource.uri(), resource.name())
.description(resource.description())
diff --git
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngine.java
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngine.java
index 9c5e8928e91..44badadbeef 100644
---
a/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngine.java
+++
b/components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngine.java
@@ -21,16 +21,20 @@ import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
import io.modelcontextprotocol.modern.McpException;
import io.modelcontextprotocol.modern.McpSchema;
import io.modelcontextprotocol.modern.McpSchema.ErrorCodes;
import io.modelcontextprotocol.modern.server.McpSyncResponse;
import io.modelcontextprotocol.modern.server.feature.McpSyncPrompt;
+import io.modelcontextprotocol.modern.server.feature.McpSyncResource;
import io.modelcontextprotocol.modern.server.feature.McpSyncTool;
import io.modelcontextprotocol.modern.server.feature.ResourceTemplatesPage;
+import io.modelcontextprotocol.modern.server.feature.ResourcesPage;
import org.apache.camel.CamelContext;
import org.apache.camel.component.ai.resource.AiResourceUriTemplate;
import org.apache.camel.component.ai.tool.AiToolAnnotations;
@@ -61,8 +65,9 @@ import
org.springframework.ai.mcp.modern.SyncResourceTemplateRegistration;
* That server has no session: it takes its tools, resources and prompts from
repositories. The routes go into the
* in-memory repositories Spring AI auto-configures, next to the application's
own tools, resources and prompts, and
* those repositories tell the clients listening with {@code
subscriptions/listen} when a list changes. A route with the
- * name or URI of an entry already served is refused. A repository the
application defines itself cannot be added to,
- * so the routes of that kind are refused too.
+ * name or URI of an entry already served is refused, and so is a resource
with the URI of a resource template, or the
+ * reverse, because the repository removes both together. A repository the
application defines itself cannot be added
+ * to, so the routes of that kind are refused too.
* <p>
* The conversions mirror {@link SpringAiMcpServerEngine}, with the types of
the 2026-07-28 schema of the MCP Java SDK.
*/
@@ -82,6 +87,10 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
private final InMemorySyncResourceRepository resources;
private final InMemorySyncPromptRepository prompts;
private final McpJsonMapper jsonMapper = McpJsonDefaults.getMapper();
+ // what the routes registered, so that only these are removed: the
repository removes the resource and the template
+ // of a URI together, and the application can remove and register entries
too
+ private final Map<String, SyncResourceRegistration> camelResources = new
ConcurrentHashMap<>();
+ private final Map<String, SyncResourceTemplateRegistration> camelTemplates
= new ConcurrentHashMap<>();
private CamelContext camelContext;
/**
@@ -121,8 +130,9 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
public void toolAdded(McpServerTool tool) {
if (tools == null) {
throw new McpServerRefusedException(
- "MCP tool '" + tool.name() + "' is not served: the Spring
AI MCP server serves no tools, or"
- + " serves them from a
repository of the application");
+ "MCP tool '" + tool.name() + "' is not served: the Spring
AI MCP server serves no tools (see"
+ + "
spring.ai.mcp.server.capabilities.tool), or serves them from a"
+ + " repository of the
application");
}
McpSchema.Tool definition;
try {
@@ -181,7 +191,14 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
.build());
}
}
- return builder.build();
+ McpSchema.Tool definition = builder.build();
+ // the session and stateless servers check the schemas when a tool is
added, the tools feature of this server
+ // only when the tool is called: check them here, with the validator
Spring AI gives that feature, so the tool
+ // is refused instead
+ JsonSchemaValidator validator = McpJsonDefaults.getSchemaValidator();
+ validator.assertConforms("Tool '" + tool.name() + "' inputSchema",
definition.inputSchema());
+ validator.assertConforms("Tool '" + tool.name() + "' outputSchema",
definition.outputSchema());
+ return definition;
}
// ---- resources and resource templates
@@ -191,7 +208,15 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
if (resources == null) {
throw new McpServerRefusedException(
"MCP resource '" + resource.uri() + "' is not served: the
Spring AI MCP server serves no"
- + " resources, or serves them
from a repository of the application");
+ + " resources (see
spring.ai.mcp.server.capabilities.resource), or"
+ + " serves them from a
repository of the application");
+ }
+ // the repository's remove(uri) removes the template of that URI too
+ if (resources.findTemplate(null, resource.uri()) != null) {
+ throw new McpServerRefusedException(
+ "MCP resource '" + resource.uri() + "' is not served: a
resource template with the same URI is"
+ + " already registered, and
the Spring AI resource repository"
+ + " removes both together");
}
McpSchema.Resource.Builder builder =
McpSchema.Resource.builder(resource.uri(), resource.name())
.description(resource.description())
@@ -199,21 +224,35 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
if (resource.title() != null && !resource.title().isBlank()) {
builder.title(resource.title());
}
+ SyncResourceRegistration registration =
SyncResourceRegistration.of(builder.build(),
+ (ctx, request) -> McpSyncResponse.result(
+ readResult(resource.uri(), resource.mimeType(),
resource.handler().read())));
try {
- resources.add(SyncResourceRegistration.of(builder.build(), (ctx,
request) -> McpSyncResponse.result(
- readResult(resource.uri(), resource.mimeType(),
resource.handler().read()))));
+ resources.add(registration);
} catch (IllegalArgumentException e) {
throw new McpServerRefusedException(
"An MCP resource with URI '" + resource.uri() + "' is
already registered", e);
}
+ camelResources.put(resource.uri(), registration);
LOG.debug("MCP resource added: {}", resource.uri());
}
@Override
public void resourceRemoved(String resourceUri) {
- if (resources != null && resources.remove(resourceUri)) {
- LOG.debug("MCP resource removed: {}", resourceUri);
+ SyncResourceRegistration registration =
camelResources.remove(resourceUri);
+ // the repository serves a URI from its resource before any template:
another handler means the application
+ // removed the route's resource, and what it registered under that URI
since is left alone
+ if (registration == null || resources.find(null, resourceUri) !=
registration.handler()) {
+ return;
+ }
+ boolean templateToo = resources.findTemplate(null, resourceUri) !=
null;
+ resources.remove(resourceUri);
+ if (templateToo) {
+ LOG.warn("Removing MCP resource '{}' also removed the resource
template the application registered with"
+ + " the same URI after it: the Spring AI resource
repository removes both together",
+ resourceUri);
}
+ LOG.debug("MCP resource removed: {}", resourceUri);
}
@Override
@@ -227,7 +266,8 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
if (resources == null) {
throw new McpServerRefusedException(
"MCP resource template '" + uriTemplate + "' is not
served: the Spring AI MCP server serves no"
- + " resources, or serves them
from a repository of the application");
+ + " resources (see
spring.ai.mcp.server.capabilities.resource), or"
+ + " serves them from a
repository of the application");
}
List<McpSchema.ResourceTemplate> existingTemplates =
listResourceTemplates();
if (existingTemplates.stream().anyMatch(existing ->
existing.uriTemplate().equals(uriTemplate))) {
@@ -235,6 +275,13 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
"An MCP resource template '" + uriTemplate + "' is already
registered");
}
checkNoOverlap(uriTemplate, existingTemplates);
+ // the repository's remove(uri) removes the resource of that URI too
+ if (hasResource(uriTemplate, null)) {
+ throw new McpServerRefusedException(
+ "MCP resource template '" + uriTemplate + "' is not
served: a resource with the same URI is"
+ + " already registered, and
the Spring AI resource repository"
+ + " removes both together");
+ }
McpSchema.ResourceTemplate.Builder builder =
McpSchema.ResourceTemplate.builder(uriTemplate,
resourceTemplate.name())
@@ -243,22 +290,35 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
if (resourceTemplate.title() != null &&
!resourceTemplate.title().isBlank()) {
builder.title(resourceTemplate.title());
}
+ SyncResourceTemplateRegistration registration =
SyncResourceTemplateRegistration.of(builder.build(),
+ (ctx, request) ->
McpSyncResponse.result(readResult(request.uri(), resourceTemplate.mimeType(),
+ resourceTemplate.handler().read(request.uri()))));
try {
- resources.add(SyncResourceTemplateRegistration.of(builder.build(),
- (ctx, request) ->
McpSyncResponse.result(readResult(request.uri(), resourceTemplate.mimeType(),
- resourceTemplate.handler().read(request.uri())))));
+ resources.add(registration);
} catch (IllegalArgumentException e) {
throw new McpServerRefusedException(
"MCP resource template '" + uriTemplate + "' cannot be
registered: " + e.getMessage(), e);
}
+ camelTemplates.put(uriTemplate, registration);
LOG.debug("MCP resource template added: {}", uriTemplate);
}
@Override
public void resourceTemplateRemoved(String uriTemplate) {
- if (resources != null && resources.remove(uriTemplate)) {
- LOG.debug("MCP resource template removed: {}", uriTemplate);
+ SyncResourceTemplateRegistration registration =
camelTemplates.remove(uriTemplate);
+ // another template under that URI template means the application
removed the route's template, and what it
+ // registered under that URI since is left alone
+ if (registration == null || resources.findTemplate(null, uriTemplate)
!= registration.template()) {
+ return;
+ }
+ boolean resourceToo = hasResource(uriTemplate, registration.handler());
+ resources.remove(uriTemplate);
+ if (resourceToo) {
+ LOG.warn("Removing MCP resource template '{}' also removed the
resource the application registered with"
+ + " the same URI after it: the Spring AI resource
repository removes both together",
+ uriTemplate);
}
+ LOG.debug("MCP resource template removed: {}", uriTemplate);
}
@Override
@@ -266,6 +326,33 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
return resources != null;
}
+ /**
+ * Whether a resource, the application's included, is registered with this
URI. The repository serves a URI from
+ * its resource before any template, so when it finds no handler, or the
handler of the given template, there is
+ * none; otherwise the handler may be another template's, and the
resources are listed.
+ */
+ private boolean hasResource(String uri, McpSyncResource templateHandler) {
+ try {
+ // the in-memory repository does not read the request context
+ McpSyncResource handler = resources.find(null, uri);
+ if (handler == null || handler == templateHandler) {
+ return false;
+ }
+ } catch (RuntimeException e) {
+ // the URI template is not a read URI, which the template matcher
of the repository may reject
+ LOG.debug("Cannot look up MCP resource '{}' directly, listing the
resources: {}", uri, e.getMessage());
+ }
+ String cursor = null;
+ do {
+ ResourcesPage page = resources.list(null, cursor);
+ if (page.resources().stream().anyMatch(existing ->
existing.uri().equals(uri))) {
+ return true;
+ }
+ cursor = page.nextCursor();
+ } while (cursor != null);
+ return false;
+ }
+
/**
* All the resource templates served, the application's included, across
the pages of the repository.
*/
@@ -353,8 +440,9 @@ public class SpringAiModernMcpServerEngine extends
ServiceSupport implements Mcp
public void promptAdded(McpServerPrompt prompt) {
if (prompts == null) {
throw new McpServerRefusedException(
- "MCP prompt '" + prompt.name() + "' is not served: the
Spring AI MCP server serves no prompts,"
- + " or serves them from a
repository of the application");
+ "MCP prompt '" + prompt.name() + "' is not served: the
Spring AI MCP server serves no prompts"
+ + " (see
spring.ai.mcp.server.capabilities.prompt), or serves them"
+ + " from a repository of the
application");
}
McpSchema.Prompt.Builder builder =
McpSchema.Prompt.builder(prompt.name())
.description(prompt.description())
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 9bc92faa4a7..2f0904e11e4 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
@@ -18,3 +18,4 @@
org.apache.camel.springboot.mcp.server.CamelMcpServerAutoConfiguration
org.apache.camel.springboot.mcp.server.CamelMcpServerTransportAutoConfiguration
org.apache.camel.springboot.mcp.server.CamelMcpServerStatelessTransportAutoConfiguration
org.apache.camel.springboot.mcp.server.CamelMcpServerModernTransportAutoConfiguration
+org.apache.camel.springboot.mcp.server.CamelMcpServerAsyncTypeAutoConfiguration
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeTest.java
new file mode 100644
index 00000000000..447bbe16ddb
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerAsyncTypeTest.java
@@ -0,0 +1,251 @@
+/*
+ * 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.security.Principal;
+import java.util.List;
+import java.util.Optional;
+
+import io.modelcontextprotocol.modern.server.McpServer;
+import io.modelcontextprotocol.server.McpAsyncServer;
+import io.modelcontextprotocol.server.McpStatelessAsyncServer;
+import io.modelcontextprotocol.server.McpSyncServer;
+import io.modelcontextprotocol.server.McpTransportContextExtractor;
+import io.modelcontextprotocol.server.transport.HeaderAccessor;
+import io.modelcontextprotocol.server.transport.ServerHttpHeaderValidator;
+import
io.modelcontextprotocol.server.transport.ServerTransportSecurityException;
+import
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.mcp.server.McpServerBridge;
+import org.apache.camel.component.mcp.server.McpServerEngine;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import
org.springframework.ai.mcp.server.common.autoconfigure.McpServerJsonMapperAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerModernWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStatelessWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStreamableHttpWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcModernServerTransport;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcStatelessServerTransport;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcStreamableServerTransportProvider;
+import org.springframework.boot.autoconfigure.AutoConfigurations;
+import
org.springframework.boot.test.context.runner.WebApplicationContextRunner;
+import org.springframework.boot.test.system.CapturedOutput;
+import org.springframework.boot.test.system.OutputCaptureExtension;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.servlet.function.ServerRequest;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * With {@code spring.ai.mcp.server.type=ASYNC}, the Camel routes are not
served on any protocol: the bridge backs off,
+ * Spring AI's transport is kept unless {@code
camel.mcp-server.transport-enabled=true}, and a warning is logged when
+ * Camel tags are configured.
+ */
+@ExtendWith(OutputCaptureExtension.class)
+class CamelMcpServerAsyncTypeTest {
+
+ private static final String NOT_SERVED = "spring.ai.mcp.server.type is
ASYNC";
+ private static final String TRANSPORT_NOT_INSTALLED = "Camel does not
install its Origin validation and"
+ + " caller-context
extraction";
+
+ private final WebApplicationContextRunner streamable = new
WebApplicationContextRunner()
+ .withBean(CamelContext.class, () -> mock(CamelContext.class))
+ .withBean(McpAsyncServer.class, () -> mock(McpAsyncServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ McpServerStreamableHttpWebMvcAutoConfiguration.class,
+ CamelMcpServerAutoConfiguration.class,
+ CamelMcpServerTransportAutoConfiguration.class,
+ CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=STREAMABLE",
"spring.ai.mcp.server.type=ASYNC");
+
+ private final WebApplicationContextRunner stateless = new
WebApplicationContextRunner()
+ .withBean(CamelContext.class, () -> mock(CamelContext.class))
+ .withBean(McpStatelessAsyncServer.class, () ->
mock(McpStatelessAsyncServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ McpServerStatelessWebMvcAutoConfiguration.class,
+ CamelMcpServerAutoConfiguration.class,
+ CamelMcpServerStatelessTransportAutoConfiguration.class,
+ CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=STATELESS",
"spring.ai.mcp.server.type=ASYNC");
+
+ private final WebApplicationContextRunner modern = new
WebApplicationContextRunner()
+ .withBean(McpServer.class, () -> mock(McpServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ CamelMcpServerModernTransportAutoConfiguration.class,
+ McpServerModernWebMvcAutoConfiguration.class,
+ CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=MODERN",
"spring.ai.mcp.server.type=ASYNC");
+
+ @Test
+ void streamableKeepsSpringAiTransportAndWarns(CapturedOutput output) {
+ streamable.withPropertyValues("camel.mcp-server.tags=crm").run(context
-> {
+ assertThat(context).hasNotFailed();
+ assertThat(context).doesNotHaveBean(McpServerEngine.class);
+ assertThat(context).doesNotHaveBean(McpServerBridge.class);
+ WebMvcStreamableServerTransportProvider provider
+ =
context.getBean(WebMvcStreamableServerTransportProvider.class);
+ assertThat(callContext(provider)).isNull();
+ assertThat(ReflectionTestUtils.getField(provider,
"securityValidator"))
+ .isSameAs(ServerTransportSecurityValidator.NOOP);
+ });
+ assertThat(output).contains("Camel MCP routes tagged [crm] are
configured, but " + NOT_SERVED)
+ .contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void statelessKeepsSpringAiTransportAndWarns(CapturedOutput output) {
+ stateless.withPropertyValues("camel.mcp-server.tags=crm").run(context
-> {
+ assertThat(context).hasNotFailed();
+ assertThat(context).doesNotHaveBean(McpServerBridge.class);
+ WebMvcStatelessServerTransport transport =
context.getBean(WebMvcStatelessServerTransport.class);
+ assertThat(callContext(transport)).isNull();
+ assertThat(ReflectionTestUtils.getField(transport,
"securityValidator"))
+ .isSameAs(ServerTransportSecurityValidator.NOOP);
+ });
+
assertThat(output).contains(NOT_SERVED).contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void modernKeepsSpringAiValidatorAndExtractorAndWarns(CapturedOutput
output) {
+ modern.withPropertyValues("camel.mcp-server.tags=crm").run(context -> {
+ assertThat(context).hasNotFailed();
+
assertThat(context).doesNotHaveBean(ServerHttpHeaderValidator.class);
+
assertThat(context).doesNotHaveBean(McpTransportContextExtractor.class);
+ WebMvcModernServerTransport transport =
context.getBean(WebMvcModernServerTransport.class);
+ assertThat(callContext(transport)).isNull();
+ // Spring AI's default validator allows no Origin, where Camel's
allows the loopback origins
+ ServerHttpHeaderValidator validator
+ = (ServerHttpHeaderValidator)
ReflectionTestUtils.getField(transport, "httpHeaderValidator");
+ assertThatThrownBy(() ->
validator.validate(origin("http://localhost:8080")))
+ .isInstanceOf(ServerTransportSecurityException.class);
+ });
+
assertThat(output).contains(NOT_SERVED).contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void
syncServerOfTheApplicationOverAsyncServerDoesNotServeCamelRoutes(CapturedOutput
output) {
+ // a synchronous facade of the application over Spring AI's ASYNC
server
+ streamable.withBean(McpSyncServer.class, () ->
mock(McpSyncServer.class))
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ assertThat(context).doesNotHaveBean(McpServerEngine.class);
+ assertThat(context).doesNotHaveBean(McpServerBridge.class);
+
assertThat(callContext(context.getBean(WebMvcStreamableServerTransportProvider.class))).isNull();
+ });
+
assertThat(output).contains(NOT_SERVED).contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void explicitlyEnabledTransportIsStillInstalled(CapturedOutput output) {
+ streamable.withPropertyValues("camel.mcp-server.tags=crm",
"camel.mcp-server.transport-enabled=true")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ assertThat(context).doesNotHaveBean(McpServerBridge.class);
+
assertThat(callContext(context.getBean(WebMvcStreamableServerTransportProvider.class)))
+ .isInstanceOf(McpToolCallContext.class);
+ });
+
assertThat(output).contains(NOT_SERVED).doesNotContain(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void
explicitlyEnabledTransportIsNotInstalledWithoutHttpProtocol(CapturedOutput
output) {
+ new WebApplicationContextRunner()
+
.withConfiguration(AutoConfigurations.of(CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.type=ASYNC",
"camel.mcp-server.tags=crm",
+ "camel.mcp-server.transport-enabled=true")
+ .run(context -> assertThat(context).hasNotFailed());
+
assertThat(output).contains(NOT_SERVED).contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void explicitlyEnabledTransportIsNotInstalledWithStdio(CapturedOutput
output) {
+ streamable.withPropertyValues("camel.mcp-server.tags=crm",
"camel.mcp-server.transport-enabled=true",
+ "spring.ai.mcp.server.stdio=on")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+
assertThat(context).doesNotHaveBean(WebMvcStreamableServerTransportProvider.class);
+ });
+
assertThat(output).contains(NOT_SERVED).contains(TRANSPORT_NOT_INSTALLED);
+ }
+
+ @Test
+ void noWarningWhenSpringAiServerIsDisabled(CapturedOutput output) {
+ new WebApplicationContextRunner()
+
.withConfiguration(AutoConfigurations.of(CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.type=ASYNC",
"spring.ai.mcp.server.enabled=false",
+ "camel.mcp-server.tags=crm")
+ .run(context -> assertThat(context).hasNotFailed());
+ assertThat(output).doesNotContain(NOT_SERVED);
+ }
+
+ @Test
+ void noWarningWithoutCamelTags(CapturedOutput output) {
+ streamable.run(context -> {
+ assertThat(context).hasNotFailed();
+
assertThat(callContext(context.getBean(WebMvcStreamableServerTransportProvider.class))).isNull();
+ });
+ assertThat(output).doesNotContain(NOT_SERVED);
+ }
+
+ @Test
+ void noWarningForSyncServer(CapturedOutput output) {
+ new WebApplicationContextRunner()
+
.withConfiguration(AutoConfigurations.of(CamelMcpServerAsyncTypeAutoConfiguration.class))
+ .withPropertyValues("camel.mcp-server.tags=crm",
"spring.ai.mcp.server.type=SYNC")
+ .run(context -> assertThat(context).hasNotFailed());
+ assertThat(output).doesNotContain(NOT_SERVED);
+ }
+
+ @Test
+ void noWarningWhenCamelIntegrationIsDisabled(CapturedOutput output) {
+ streamable.withPropertyValues("camel.mcp-server.tags=crm",
"camel.mcp-server.enabled=false")
+ .run(context -> assertThat(context).hasNotFailed());
+ assertThat(output).doesNotContain(NOT_SERVED);
+ }
+
+ private static HeaderAccessor origin(String origin) {
+ return new HeaderAccessor() {
+ @Override
+ public List<String> getHeader(String name) {
+ return "Origin".equalsIgnoreCase(name) ? List.of(origin) :
List.of();
+ }
+
+ @Override
+ public List<String> getHeaderNames() {
+ return List.of("Origin");
+ }
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Object callContext(Object transport) {
+ McpTransportContextExtractor<ServerRequest> extractor
+ = (McpTransportContextExtractor<ServerRequest>)
ReflectionTestUtils.getField(transport,
+ "contextExtractor");
+ ServerRequest request = mock(ServerRequest.class);
+ when(request.principal()).thenReturn(Optional.of((Principal) () ->
"async-test-user"));
+ return
extractor.extract(request).get(SpringAiMcpTransportContext.CALL_CONTEXT_KEY);
+ }
+}
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCustomizerTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCustomizerTest.java
new file mode 100644
index 00000000000..95c8487a983
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportCustomizerTest.java
@@ -0,0 +1,299 @@
+/*
+ * 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.security.Principal;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.modern.server.McpServer;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
+import io.modelcontextprotocol.server.McpSyncServer;
+import io.modelcontextprotocol.server.McpTransportContextExtractor;
+import io.modelcontextprotocol.server.transport.ServerHttpHeaderValidator;
+import
io.modelcontextprotocol.server.transport.ServerTransportSecurityException;
+import
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.junit.jupiter.api.Test;
+import org.springframework.ai.mcp.customizer.McpServerCustomizer;
+import
org.springframework.ai.mcp.server.common.autoconfigure.McpServerJsonMapperAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerModernWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStatelessWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.autoconfigure.McpServerStreamableHttpWebMvcAutoConfiguration;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcModernServerTransport;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcStatelessServerTransport;
+import
org.springframework.ai.mcp.server.webmvc.transport.WebMvcStreamableServerTransportProvider;
+import org.springframework.boot.autoconfigure.AutoConfigurations;
+import
org.springframework.boot.test.context.runner.WebApplicationContextRunner;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.servlet.function.ServerRequest;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The {@code McpServerCustomizer} beans of the Spring AI transport builders
are applied to Camel's transports as
+ * Spring AI applies them to its own: in order, after Camel's settings, so
that a customizer can override them.
+ */
+class CamelMcpServerTransportCustomizerTest {
+
+ private static final ServerTransportSecurityValidator
APPLICATION_VALIDATOR = headers -> {
+ };
+
+ private static final McpTransportContextExtractor<ServerRequest>
APPLICATION_EXTRACTOR
+ = request -> McpTransportContext.create(Map.of("application",
"my-app"));
+
+ private final WebApplicationContextRunner streamable = new
WebApplicationContextRunner()
+ .withBean(CamelContext.class, () -> mock(CamelContext.class))
+ .withBean(McpSyncServer.class, () -> mock(McpSyncServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ McpServerStreamableHttpWebMvcAutoConfiguration.class,
+ CamelMcpServerAutoConfiguration.class,
+ CamelMcpServerTransportAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=STREAMABLE");
+
+ private final WebApplicationContextRunner stateless = new
WebApplicationContextRunner()
+ .withBean(CamelContext.class, () -> mock(CamelContext.class))
+ .withBean(McpStatelessSyncServer.class, () ->
mock(McpStatelessSyncServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ McpServerStatelessWebMvcAutoConfiguration.class,
+ CamelMcpServerAutoConfiguration.class,
+ CamelMcpServerStatelessTransportAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=STATELESS");
+
+ private final WebApplicationContextRunner modern = new
WebApplicationContextRunner()
+ .withBean(McpServer.class, () -> mock(McpServer.class))
+ .withConfiguration(AutoConfigurations.of(
+ McpServerJsonMapperAutoConfiguration.class,
+ CamelMcpServerModernTransportAutoConfiguration.class,
+ McpServerModernWebMvcAutoConfiguration.class))
+ .withPropertyValues("spring.ai.mcp.server.protocol=MODERN");
+
+ @Configuration(proxyBeanMethods = false)
+ static class StreamableMaxSessionsCustomizer {
+
+ @Bean
+ McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
maxSessionsCustomizer() {
+ return builder -> builder.maxSessions(7);
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ static class StreamableOrderedCustomizers {
+
+ @Bean
+ @Order(2)
+ McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
lastCustomizer() {
+ return builder -> builder.maxSessions(2);
+ }
+
+ @Bean
+ @Order(1)
+ McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
firstCustomizer() {
+ return builder -> builder.maxSessions(1);
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ static class StreamableSecurityCustomizer {
+
+ @SuppressWarnings("deprecation")
+ @Bean
+ McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
securityCustomizer() {
+ return builder ->
builder.securityValidator(APPLICATION_VALIDATOR).contextExtractor(APPLICATION_EXTRACTOR);
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ static class StatelessEndpointCustomizer {
+
+ @Bean
+ McpServerCustomizer<WebMvcStatelessServerTransport.Builder>
endpointCustomizer() {
+ return builder -> builder.messageEndpoint("/custom-mcp");
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ static class StatelessSecurityCustomizer {
+
+ @SuppressWarnings("deprecation")
+ @Bean
+ McpServerCustomizer<WebMvcStatelessServerTransport.Builder>
securityCustomizer() {
+ return builder ->
builder.securityValidator(APPLICATION_VALIDATOR).contextExtractor(APPLICATION_EXTRACTOR);
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ static class ModernValidatorCustomizer {
+
+ static final ServerHttpHeaderValidator VALIDATOR = headers -> {
+ };
+
+ @Bean
+ McpServerCustomizer<WebMvcModernServerTransport.Builder>
validatorCustomizer() {
+ return builder -> builder.httpHeaderValidator(VALIDATOR);
+ }
+ }
+
+ @Test
+ void streamableCustomizerIsAppliedToSpringAiTransportWithoutCamelTags() {
+
streamable.withUserConfiguration(StreamableMaxSessionsCustomizer.class).run(context
-> {
+ assertThat(context).hasNotFailed();
+ WebMvcStreamableServerTransportProvider provider
+ =
context.getBean(WebMvcStreamableServerTransportProvider.class);
+ assertThat(ReflectionTestUtils.getField(provider,
"maxSessions")).isEqualTo(7L);
+ assertThat(callContext(extractor(provider))).isNull();
+ });
+ }
+
+ @Test
+ void streamableCustomizerIsAppliedToCamelTransport() {
+ streamable.withUserConfiguration(StreamableMaxSessionsCustomizer.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcStreamableServerTransportProvider provider
+ =
context.getBean(WebMvcStreamableServerTransportProvider.class);
+ assertThat(ReflectionTestUtils.getField(provider,
"maxSessions")).isEqualTo(7L);
+ // the customizer does not replace them: Camel's caller
identity and Origin validation remain
+
assertThat(callContext(extractor(provider))).isInstanceOf(McpToolCallContext.class);
+ assertRejectsRemoteOrigin(securityValidator(provider));
+ });
+ }
+
+ @Test
+ void streamableCustomizersAreAppliedInOrder() {
+ streamable.withUserConfiguration(StreamableOrderedCustomizers.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ assertThat(ReflectionTestUtils.getField(
+
context.getBean(WebMvcStreamableServerTransportProvider.class), "maxSessions"))
+ .isEqualTo(2L);
+ });
+ }
+
+ @Test
+ void streamableCustomizerOverridesCamelValidatorAndExtractor() {
+ streamable.withUserConfiguration(StreamableSecurityCustomizer.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcStreamableServerTransportProvider provider
+ =
context.getBean(WebMvcStreamableServerTransportProvider.class);
+
assertThat(securityValidator(provider)).isSameAs(APPLICATION_VALIDATOR);
+
assertThat(extractor(provider)).isSameAs(APPLICATION_EXTRACTOR);
+ });
+ }
+
+ @Test
+ void statelessCustomizerIsAppliedToSpringAiTransportWithoutCamelTags() {
+
stateless.withUserConfiguration(StatelessEndpointCustomizer.class).run(context
-> {
+ assertThat(context).hasNotFailed();
+ WebMvcStatelessServerTransport transport =
context.getBean(WebMvcStatelessServerTransport.class);
+ assertThat(ReflectionTestUtils.getField(transport,
"mcpEndpoint")).isEqualTo("/custom-mcp");
+ assertThat(callContext(extractor(transport))).isNull();
+ });
+ }
+
+ @Test
+ void statelessCustomizerIsAppliedToCamelTransport() {
+ stateless.withUserConfiguration(StatelessEndpointCustomizer.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcStatelessServerTransport transport =
context.getBean(WebMvcStatelessServerTransport.class);
+ assertThat(ReflectionTestUtils.getField(transport,
"mcpEndpoint")).isEqualTo("/custom-mcp");
+ // the customizer does not replace them: Camel's caller
identity and Origin validation remain
+
assertThat(callContext(extractor(transport))).isInstanceOf(McpToolCallContext.class);
+ assertRejectsRemoteOrigin(securityValidator(transport));
+ });
+ }
+
+ @Test
+ void statelessCustomizerOverridesCamelValidatorAndExtractor() {
+ stateless.withUserConfiguration(StatelessSecurityCustomizer.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcStatelessServerTransport transport =
context.getBean(WebMvcStatelessServerTransport.class);
+
assertThat(securityValidator(transport)).isSameAs(APPLICATION_VALIDATOR);
+
assertThat(extractor(transport)).isSameAs(APPLICATION_EXTRACTOR);
+ });
+ }
+
+ @Test
+ void modernTransportUsesCamelValidatorWithoutCustomizer() {
+ modern.withPropertyValues("camel.mcp-server.tags=crm").run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcModernServerTransport transport =
context.getBean(WebMvcModernServerTransport.class);
+ assertThat(ReflectionTestUtils.getField(transport,
"httpHeaderValidator"))
+
.isSameAs(context.getBean(ServerHttpHeaderValidator.class));
+
assertThat(callContext(extractor(transport))).isInstanceOf(McpToolCallContext.class);
+ });
+ }
+
+ @Test
+ void modernCustomizerOverridesCamelValidator() {
+ modern.withUserConfiguration(ModernValidatorCustomizer.class)
+ .withPropertyValues("camel.mcp-server.tags=crm")
+ .run(context -> {
+ assertThat(context).hasNotFailed();
+ WebMvcModernServerTransport transport =
context.getBean(WebMvcModernServerTransport.class);
+ assertThat(ReflectionTestUtils.getField(transport,
"httpHeaderValidator"))
+ .isSameAs(ModernValidatorCustomizer.VALIDATOR);
+
assertThat(callContext(extractor(transport))).isInstanceOf(McpToolCallContext.class);
+ });
+ }
+
+ private static void
assertRejectsRemoteOrigin(ServerTransportSecurityValidator validator) {
+ assertThatThrownBy(() -> validator.validateHeaders(Map.of("Origin",
List.of("https://evil.example"))))
+ .isInstanceOf(ServerTransportSecurityException.class);
+ assertThatCode(() -> validator.validateHeaders(Map.of("Origin",
List.of("http://localhost:8080"))))
+ .doesNotThrowAnyException();
+ }
+
+ private static ServerTransportSecurityValidator securityValidator(Object
transport) {
+ Object value = ReflectionTestUtils.getField(transport,
"securityValidator");
+ assertThat(value).isInstanceOf(ServerTransportSecurityValidator.class);
+ return (ServerTransportSecurityValidator) value;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static McpTransportContextExtractor<ServerRequest>
extractor(Object transport) {
+ Object value = ReflectionTestUtils.getField(transport,
"contextExtractor");
+ assertThat(value).isInstanceOf(McpTransportContextExtractor.class);
+ return (McpTransportContextExtractor<ServerRequest>) value;
+ }
+
+ private static Object
callContext(McpTransportContextExtractor<ServerRequest> extractor) {
+ ServerRequest request = mock(ServerRequest.class);
+ when(request.principal()).thenReturn(Optional.of((Principal) () ->
"customizer-test-user"));
+ return
extractor.extract(request).get(SpringAiMcpTransportContext.CALL_CONTEXT_KEY);
+ }
+}
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationPropertiesTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationPropertiesTest.java
new file mode 100644
index 00000000000..2d9cc11fa1c
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationPropertiesTest.java
@@ -0,0 +1,38 @@
+/*
+ * 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 org.apache.camel.component.mcp.server.McpServerConstants;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The timeout defaults are literals, so that the configuration metadata shows
them: they must stay those of the
+ * bridge.
+ */
+class McpServerConfigurationPropertiesTest {
+
+ @Test
+ void timeoutDefaultsAreThoseOfTheBridge() {
+ McpServerConfigurationProperties properties = new
McpServerConfigurationProperties();
+
+
assertThat(properties.getToolTimeout()).isEqualTo(McpServerConstants.DEFAULT_TOOL_TIMEOUT);
+
assertThat(properties.getResourceTimeout()).isEqualTo(McpServerConstants.DEFAULT_RESOURCE_TIMEOUT);
+
assertThat(properties.getPromptTimeout()).isEqualTo(McpServerConstants.DEFAULT_PROMPT_TIMEOUT);
+ }
+}
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngineTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngineTest.java
index 20adef652a3..2ff7ff959ab 100644
---
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngineTest.java
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngineTest.java
@@ -19,11 +19,17 @@ package org.apache.camel.springboot.mcp.server;
import java.util.List;
import java.util.Map;
+import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServerFeatures;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.server.McpSyncServer;
import io.modelcontextprotocol.spec.McpSchema;
+import io.modelcontextprotocol.spec.McpStatelessServerTransport;
+import io.modelcontextprotocol.spec.McpStreamableServerTransportProvider;
import org.apache.camel.component.mcp.server.McpResourceTemplateReadHandler;
+import org.apache.camel.component.mcp.server.McpServerPrompt;
import org.apache.camel.component.mcp.server.McpServerRefusedException;
+import org.apache.camel.component.mcp.server.McpServerResource;
import org.apache.camel.component.mcp.server.McpServerResourceTemplate;
import org.apache.camel.component.mcp.server.McpServerTool;
import org.apache.camel.component.mcp.server.McpToolCallHandler;
@@ -40,6 +46,9 @@ import static org.mockito.Mockito.when;
class SpringAiMcpServerEngineTest {
+ private static final McpSchema.ServerCapabilities RESOURCES_CAPABILITY
+ = McpSchema.ServerCapabilities.builder().resources(false,
true).build();
+
@Test
void reportsResourcesAndPromptsFromActualServerCapabilities() {
McpSyncServer server = mock(McpSyncServer.class);
@@ -68,6 +77,7 @@ class SpringAiMcpServerEngineTest {
@Test
void refusesOverlappingSpringDefinedResourceTemplates() {
McpSyncServer server = mock(McpSyncServer.class);
+ when(server.getServerCapabilities()).thenReturn(RESOURCES_CAPABILITY);
SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
McpSchema.ResourceTemplate existing = McpSchema.ResourceTemplate
.builder("camel:///customers/{id}", "spring-customers")
@@ -86,6 +96,7 @@ class SpringAiMcpServerEngineTest {
@Test
void ignoresUnsupportedSpringTemplateWhenUriSchemesDiffer() {
McpSyncServer server = mock(McpSyncServer.class);
+ when(server.getServerCapabilities()).thenReturn(RESOURCES_CAPABILITY);
SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
McpSchema.ResourceTemplate existing = McpSchema.ResourceTemplate
.builder("document://{id}", "spring-document")
@@ -100,6 +111,7 @@ class SpringAiMcpServerEngineTest {
@Test
void refusesUnsupportedSpringTemplateWhenUriSchemesMatch() {
McpSyncServer server = mock(McpSyncServer.class);
+ when(server.getServerCapabilities()).thenReturn(RESOURCES_CAPABILITY);
SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
McpSchema.ResourceTemplate existing = McpSchema.ResourceTemplate
.builder("camel://{id}", "spring-camel")
@@ -118,6 +130,7 @@ class SpringAiMcpServerEngineTest {
@Test
void translatesInvalidToolSchemaIntoServerRefusal() {
McpSyncServer server = mock(McpSyncServer.class);
+
when(server.getServerCapabilities()).thenReturn(McpSchema.ServerCapabilities.builder().tools(true).build());
SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
when(server.listTools()).thenReturn(List.of());
doThrow(new IllegalArgumentException("invalid JSON schema"))
@@ -158,6 +171,95 @@ class SpringAiMcpServerEngineTest {
verify(absentServer, never()).notifyResourcesListChanged();
}
+ @Test
+ void
sessionServerWithoutToolsCapabilityRefusesToolsAndServesTheOtherFeatures() {
+ // without list-change notifications, which the mocked transport
cannot send
+ McpSyncServer server =
McpServer.sync(mock(McpStreamableServerTransportProvider.class))
+
.capabilities(McpSchema.ServerCapabilities.builder().resources(false,
false).prompts(false).build())
+ .build();
+ SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
+
+ assertThatThrownBy(() -> engine.toolAdded(tool("crm_lookup")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP tool 'crm_lookup' is not served")
+ .hasMessageContaining("no tools capability")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.tool");
+
+ engine.resourceAdded(resource("camel:///crm/config"));
+
engine.resourceTemplateAdded(resourceTemplate("camel:///crm/customers/{id}"));
+ engine.promptAdded(prompt("crm_prompt"));
+ assertThat(server.listTools()).isEmpty();
+
assertThat(server.listResources()).extracting(McpSchema.Resource::uri).containsExactly("camel:///crm/config");
+
assertThat(server.listResourceTemplates()).extracting(McpSchema.ResourceTemplate::uriTemplate)
+ .containsExactly("camel:///crm/customers/{id}");
+
assertThat(server.listPrompts()).extracting(McpSchema.Prompt::name).containsExactly("crm_prompt");
+ }
+
+ @Test
+ void
statelessServerWithoutToolsCapabilityRefusesToolsAndServesTheOtherFeatures() {
+ McpStatelessSyncServer server =
McpServer.sync(mock(McpStatelessServerTransport.class))
+
.capabilities(McpSchema.ServerCapabilities.builder().resources(false,
false).prompts(false).build())
+ .build();
+ SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
+
+ assertThatThrownBy(() -> engine.toolAdded(tool("crm_lookup")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP tool 'crm_lookup' is not served")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.tool");
+
+ engine.resourceAdded(resource("camel:///crm/config"));
+ engine.promptAdded(prompt("crm_prompt"));
+ assertThat(server.listTools()).isEmpty();
+
assertThat(server.listResources()).extracting(McpSchema.Resource::uri).containsExactly("camel:///crm/config");
+
assertThat(server.listPrompts()).extracting(McpSchema.Prompt::name).containsExactly("crm_prompt");
+ }
+
+ @Test
+ void
serverWithoutResourcesAndPromptsCapabilitiesRefusesThemAndServesTools() {
+ McpSyncServer server =
McpServer.sync(mock(McpStreamableServerTransportProvider.class))
+
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
+ .build();
+ SpringAiMcpServerEngine engine = new SpringAiMcpServerEngine(server);
+
+ assertThatThrownBy(() ->
engine.resourceAdded(resource("camel:///crm/config")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP resource 'camel:///crm/config' is
not served")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.resource");
+ assertThatThrownBy(() ->
engine.resourceTemplateAdded(resourceTemplate("camel:///crm/customers/{id}")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP resource template
'camel:///crm/customers/{id}' is not served")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.resource");
+ assertThatThrownBy(() -> engine.promptAdded(prompt("crm_prompt")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP prompt 'crm_prompt' is not served")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.prompt");
+
+ engine.toolAdded(tool("crm_lookup"));
+
assertThat(server.listTools()).extracting(McpSchema.Tool::name).containsExactly("crm_lookup");
+ }
+
+ private static McpServerTool tool(String name) {
+ McpServerTool tool = mock(McpServerTool.class);
+ when(tool.name()).thenReturn(name);
+ when(tool.description()).thenReturn("A tool");
+ return tool;
+ }
+
+ private static McpServerResource resource(String uri) {
+ McpServerResource resource = mock(McpServerResource.class);
+ when(resource.uri()).thenReturn(uri);
+ when(resource.name()).thenReturn("crm_config");
+ when(resource.mimeType()).thenReturn("text/plain");
+ return resource;
+ }
+
+ private static McpServerPrompt prompt(String name) {
+ McpServerPrompt prompt = mock(McpServerPrompt.class);
+ when(prompt.name()).thenReturn(name);
+ when(prompt.arguments()).thenReturn(List.of());
+ return prompt;
+ }
+
private static McpServerResourceTemplate resourceTemplate(String
uriTemplate) {
return new McpServerResourceTemplate() {
@Override
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngineTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngineTest.java
new file mode 100644
index 00000000000..671352cdde2
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringAiModernMcpServerEngineTest.java
@@ -0,0 +1,284 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.modern.McpSchema;
+import io.modelcontextprotocol.modern.server.McpSyncResponse;
+import io.modelcontextprotocol.util.DefaultMcpUriTemplateManagerFactory;
+import io.modelcontextprotocol.util.McpUriTemplateManager;
+import org.apache.camel.component.mcp.server.McpServerPrompt;
+import org.apache.camel.component.mcp.server.McpServerRefusedException;
+import org.apache.camel.component.mcp.server.McpServerResource;
+import org.apache.camel.component.mcp.server.McpServerResourceTemplate;
+import org.apache.camel.component.mcp.server.McpServerTool;
+import org.junit.jupiter.api.Test;
+import org.springframework.ai.mcp.modern.InMemorySyncResourceRepository;
+import org.springframework.ai.mcp.modern.InMemorySyncToolRepository;
+import org.springframework.ai.mcp.modern.SyncResourceRegistration;
+import org.springframework.ai.mcp.modern.SyncResourceTemplateRegistration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class SpringAiModernMcpServerEngineTest {
+
+ private static final String OBJECT_SCHEMA = "{\"type\":\"object\"}";
+
+ private static final String INVALID_SCHEMA = "{\"type\":\"obj\"}";
+
+ @Test
+ void refusesAToolWithAnInvalidOutputSchemaAndServesTheOtherTools() {
+ InMemorySyncToolRepository tools =
InMemorySyncToolRepository.builder().build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(tools, null, null);
+
+ assertThatThrownBy(() -> engine.toolAdded(tool("bad_output",
OBJECT_SCHEMA, INVALID_SCHEMA)))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP tool 'bad_output' has an invalid
input or output schema")
+ .hasMessageContaining("outputSchema is not a valid JSON Schema
2020-12 document")
+ .hasCauseInstanceOf(IllegalArgumentException.class);
+
+ engine.toolAdded(tool("good", OBJECT_SCHEMA, OBJECT_SCHEMA));
+ assertThat(tools.list(null,
null).tools()).extracting(McpSchema.Tool::name).containsExactly("good");
+ }
+
+ @Test
+ void refusesAToolWithAnInvalidInputSchema() {
+ InMemorySyncToolRepository tools =
InMemorySyncToolRepository.builder().build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(tools, null, null);
+
+ assertThatThrownBy(() -> engine.toolAdded(tool("bad_input",
INVALID_SCHEMA, null)))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("inputSchema is not a valid JSON Schema
2020-12 document");
+
+ assertThat(tools.list(null, null).tools()).isEmpty();
+ }
+
+ @Test
+ void
refusesAResourceWithTheUriOfAnApplicationTemplateAndKeepsTheTemplate() {
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder()
+ .resourceTemplate(applicationTemplate("docs://guide"))
+ .build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+ assertThatThrownBy(() ->
engine.resourceAdded(resource("docs://guide")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP resource 'docs://guide' is not
served")
+ .hasMessageContaining("a resource template with the same URI
is already registered");
+
+ // another Camel resource is served, and removing it leaves the
application's template alone
+ engine.resourceAdded(resource("docs://camel"));
+ assertThat(resources.list(null,
null).resources()).extracting(McpSchema.Resource::uri)
+ .containsExactly("docs://camel");
+ engine.resourceRemoved("docs://camel");
+ assertThat(resources.list(null, null).resources()).isEmpty();
+ assertThat(resources.listTemplates(null, null).resourceTemplates())
+
.extracting(McpSchema.ResourceTemplate::uriTemplate).containsExactly("docs://guide");
+ }
+
+ @Test
+ void
refusesATemplateWithTheUriOfAnApplicationResourceAndKeepsTheResource() {
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder()
+ .resource(applicationResource("docs://guide/{id}"))
+ .build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+ assertThatThrownBy(() ->
engine.resourceTemplateAdded(resourceTemplate("docs://guide/{id}")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP resource template
'docs://guide/{id}' is not served")
+ .hasMessageContaining("a resource with the same URI is already
registered");
+
+ // another Camel template is served, and removing it leaves the
application's resource alone
+
engine.resourceTemplateAdded(resourceTemplate("camel:///customers/{id}"));
+ assertThat(resources.listTemplates(null, null).resourceTemplates())
+
.extracting(McpSchema.ResourceTemplate::uriTemplate).containsExactly("camel:///customers/{id}");
+ engine.resourceTemplateRemoved("camel:///customers/{id}");
+ assertThat(resources.listTemplates(null,
null).resourceTemplates()).isEmpty();
+ assertThat(resources.list(null,
null).resources()).extracting(McpSchema.Resource::uri)
+ .containsExactly("docs://guide/{id}");
+ }
+
+ @Test
+ void refusesACamelResourceAndTemplateWithTheSameUri() {
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder().build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+ engine.resourceAdded(resource("camel:///customers/{id}"));
+ assertThatThrownBy(() ->
engine.resourceTemplateAdded(resourceTemplate("camel:///customers/{id}")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("a resource with the same URI is already
registered");
+ engine.resourceRemoved("camel:///customers/{id}");
+
+
engine.resourceTemplateAdded(resourceTemplate("camel:///customers/{id}"));
+ assertThatThrownBy(() ->
engine.resourceAdded(resource("camel:///customers/{id}")))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("a resource template with the same URI
is already registered");
+ assertThat(resources.listTemplates(null, null).resourceTemplates())
+
.extracting(McpSchema.ResourceTemplate::uriTemplate).containsExactly("camel:///customers/{id}");
+ assertThat(resources.list(null, null).resources()).isEmpty();
+ }
+
+ @Test
+ void removingARouteLeavesWhatTheApplicationRegisteredUnderItsUriSince() {
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder().build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+ // the application replaces the route's template with a resource of
the same URI
+
engine.resourceTemplateAdded(resourceTemplate("camel:///customers/{id}"));
+ resources.remove("camel:///customers/{id}");
+ resources.add(applicationResource("camel:///customers/{id}"));
+ engine.resourceTemplateRemoved("camel:///customers/{id}");
+ assertThat(resources.list(null,
null).resources()).extracting(McpSchema.Resource::uri)
+ .containsExactly("camel:///customers/{id}");
+
+ // and the route's resource with a template of the same URI
+ engine.resourceAdded(resource("docs://guide"));
+ resources.remove("docs://guide");
+ resources.add(applicationTemplate("docs://guide"));
+ engine.resourceRemoved("docs://guide");
+ assertThat(resources.listTemplates(null, null).resourceTemplates())
+
.extracting(McpSchema.ResourceTemplate::uriTemplate).containsExactly("docs://guide");
+ }
+
+ @Test
+ void
removingARouteRemovesItsResourceEvenWhenTheApplicationRegisteredATemplateWithTheSameUriAfterIt()
{
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder().build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+ engine.resourceAdded(resource("docs://guide"));
+ resources.add(applicationTemplate("docs://guide"));
+ engine.resourceRemoved("docs://guide");
+
+ // the route's resource is no longer served; the repository cannot
keep the template (a WARN is logged)
+ assertThat(resources.list(null, null).resources()).isEmpty();
+ assertThat(resources.listTemplates(null,
null).resourceTemplates()).isEmpty();
+ }
+
+ @Test
+ void servesTemplatesWithATemplateMatcherThatRejectsUnexpandedUris() {
+ DefaultMcpUriTemplateManagerFactory defaults = new
DefaultMcpUriTemplateManagerFactory();
+ InMemorySyncResourceRepository resources =
InMemorySyncResourceRepository.builder()
+ .uriTemplateManagerFactory(uriTemplate -> {
+ McpUriTemplateManager delegate =
defaults.create(uriTemplate);
+ return new McpUriTemplateManager() {
+ @Override
+ public List<String> getVariableNames() {
+ return delegate.getVariableNames();
+ }
+
+ @Override
+ public Map<String, String>
extractVariableValues(String uri) {
+ return delegate.extractVariableValues(uri);
+ }
+
+ @Override
+ public boolean matches(String uri) {
+ if (uri.contains("{")) {
+ throw new IllegalArgumentException("Not a read
URI: " + uri);
+ }
+ return delegate.matches(uri);
+ }
+
+ @Override
+ public boolean isUriTemplate(String uri) {
+ return delegate.isUriTemplate(uri);
+ }
+ };
+ })
+ .build();
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, resources, null);
+
+
engine.resourceTemplateAdded(resourceTemplate("camel:///customers/{id}"));
+ engine.resourceTemplateAdded(resourceTemplate("camel:///orders/{id}"));
+ assertThat(resources.listTemplates(null,
null).resourceTemplates()).hasSize(2);
+
+ engine.resourceTemplateRemoved("camel:///customers/{id}");
+ engine.resourceTemplateRemoved("camel:///orders/{id}");
+ assertThat(resources.listTemplates(null,
null).resourceTemplates()).isEmpty();
+ }
+
+ @Test
+ void refusesEveryFeatureTheServerDoesNotServeNamingTheCapability() {
+ SpringAiModernMcpServerEngine engine = new
SpringAiModernMcpServerEngine(null, null, null);
+
+ assertThatThrownBy(() -> engine.toolAdded(tool("crm_lookup",
OBJECT_SCHEMA, null)))
+ .isInstanceOf(McpServerRefusedException.class)
+ .hasMessageContaining("MCP tool 'crm_lookup' is not served")
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.tool");
+ assertThatThrownBy(() ->
engine.resourceAdded(resource("camel:///crm/config")))
+ .isInstanceOf(McpServerRefusedException.class)
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.resource");
+ assertThatThrownBy(() ->
engine.resourceTemplateAdded(resourceTemplate("camel:///crm/customers/{id}")))
+ .isInstanceOf(McpServerRefusedException.class)
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.resource");
+ assertThatThrownBy(() -> engine.promptAdded(prompt("crm_prompt")))
+ .isInstanceOf(McpServerRefusedException.class)
+
.hasMessageContaining("spring.ai.mcp.server.capabilities.prompt");
+ }
+
+ private static SyncResourceRegistration applicationResource(String uri) {
+ return SyncResourceRegistration.of(McpSchema.Resource.builder(uri,
"app_resource").build(),
+ (ctx, request) ->
McpSyncResponse.result(applicationContent(request.uri())));
+ }
+
+ private static SyncResourceTemplateRegistration applicationTemplate(String
uriTemplate) {
+ return SyncResourceTemplateRegistration.of(
+ McpSchema.ResourceTemplate.builder(uriTemplate,
"app_template").build(),
+ (ctx, request) ->
McpSyncResponse.result(applicationContent(request.uri())));
+ }
+
+ private static McpSchema.ReadResourceResult applicationContent(String uri)
{
+ return McpSchema.ReadResourceResult.builder(
+ List.of(McpSchema.TextResourceContents.builder(uri,
"app").build())).build();
+ }
+
+ private static McpServerTool tool(String name, String inputSchema, String
outputSchema) {
+ McpServerTool tool = mock(McpServerTool.class);
+ when(tool.name()).thenReturn(name);
+ when(tool.description()).thenReturn("A tool");
+ when(tool.inputSchemaJson()).thenReturn(inputSchema);
+ when(tool.outputSchemaJson()).thenReturn(outputSchema);
+ return tool;
+ }
+
+ private static McpServerResource resource(String uri) {
+ McpServerResource resource = mock(McpServerResource.class);
+ when(resource.uri()).thenReturn(uri);
+ when(resource.name()).thenReturn("camel_resource");
+ when(resource.mimeType()).thenReturn("text/plain");
+ return resource;
+ }
+
+ private static McpServerResourceTemplate resourceTemplate(String
uriTemplate) {
+ McpServerResourceTemplate template =
mock(McpServerResourceTemplate.class);
+ when(template.uriTemplate()).thenReturn(uriTemplate);
+ when(template.name()).thenReturn("camel_template");
+ when(template.mimeType()).thenReturn("text/plain");
+ return template;
+ }
+
+ private static McpServerPrompt prompt(String name) {
+ McpServerPrompt prompt = mock(McpServerPrompt.class);
+ when(prompt.name()).thenReturn(name);
+ when(prompt.arguments()).thenReturn(List.of());
+ return prompt;
+ }
+}
diff --git
a/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerToolCapabilityDisabledTest.java
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerToolCapabilityDisabledTest.java
new file mode 100644
index 00000000000..7619c61d232
--- /dev/null
+++
b/components-starter/camel-mcp-server-starter/src/test/java/org/apache/camel/springboot/mcp/server/SpringBootMcpServerToolCapabilityDisabledTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.util.List;
+
+import io.modelcontextprotocol.modern.server.feature.McpSyncToolRepository;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
+import io.modelcontextprotocol.server.McpSyncServer;
+import io.modelcontextprotocol.spec.McpSchema;
+import org.apache.camel.CamelContext;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.ai.mcp.modern.InMemorySyncPromptRepository;
+import org.springframework.ai.mcp.modern.InMemorySyncResourceRepository;
+import org.springframework.boot.WebApplicationType;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * With {@code spring.ai.mcp.server.capabilities.tool=false}, the Camel {@code
ai-tool} routes are refused, whatever the
+ * protocol: the application starts, the routes keep running, and the Camel
resources and prompts are served.
+ */
+class SpringBootMcpServerToolCapabilityDisabledTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = { "SSE", "STREAMABLE", "STATELESS", "MODERN" })
+ void toolRoutesAreRefusedAndTheOtherFeaturesAreServed(String protocol) {
+ try (ConfigurableApplicationContext context = new
SpringApplicationBuilder(TestConfiguration.class)
+ .web(WebApplicationType.SERVLET)
+ .properties(
+ "server.port=0",
+ "spring.main.banner-mode=off",
+ "spring.ai.mcp.server.protocol=" + protocol,
+ "spring.ai.mcp.server.capabilities.tool=false",
+ "camel.mcp-server.tags=crm",
+ "camel.main.run-controller=false")
+ .run()) {
+ CamelContext camelContext = context.getBean(CamelContext.class);
+
assertThat(camelContext.getRouteController().getRouteStatus("crm-tool")).isEqualTo(ServiceStatus.Started);
+ assertThat(toolNames(context, protocol)).isEmpty();
+ assertThat(resourceUris(context,
protocol)).containsExactly("camel:///crm/config");
+ assertThat(promptNames(context,
protocol)).containsExactly("crm_prompt");
+ }
+ }
+
+ private static List<String> toolNames(ConfigurableApplicationContext
context, String protocol) {
+ return switch (protocol) {
+ case "STATELESS" ->
context.getBean(McpStatelessSyncServer.class).listTools().stream()
+ .map(McpSchema.Tool::name).toList();
+ // without the capability, Spring AI defines no tool repository,
and the server serves no tools
+ case "MODERN" ->
context.getBeanProvider(McpSyncToolRepository.class).stream()
+ .flatMap(repository -> repository.list(null,
null).tools().stream())
+ .map(tool -> tool.name()).toList();
+ default ->
context.getBean(McpSyncServer.class).listTools().stream()
+ .map(McpSchema.Tool::name).toList();
+ };
+ }
+
+ private static List<String> resourceUris(ConfigurableApplicationContext
context, String protocol) {
+ return switch (protocol) {
+ case "STATELESS" ->
context.getBean(McpStatelessSyncServer.class).listResources().stream()
+ .map(McpSchema.Resource::uri).toList();
+ case "MODERN" ->
context.getBean(InMemorySyncResourceRepository.class).list(null,
null).resources().stream()
+ .map(resource -> resource.uri()).toList();
+ default ->
context.getBean(McpSyncServer.class).listResources().stream()
+ .map(McpSchema.Resource::uri).toList();
+ };
+ }
+
+ private static List<String> promptNames(ConfigurableApplicationContext
context, String protocol) {
+ return switch (protocol) {
+ case "STATELESS" ->
context.getBean(McpStatelessSyncServer.class).listPrompts().stream()
+ .map(McpSchema.Prompt::name).toList();
+ case "MODERN" ->
context.getBean(InMemorySyncPromptRepository.class).list(null,
null).prompts().stream()
+ .map(prompt -> prompt.name()).toList();
+ default ->
context.getBean(McpSyncServer.class).listPrompts().stream()
+ .map(McpSchema.Prompt::name).toList();
+ };
+ }
+
+ @Configuration
+ @EnableAutoConfiguration
+ public static class TestConfiguration {
+
+ @Bean
+ public RouteBuilder routes() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("ai-tool:crm_lookup?tags=crm&description=Look up a
customer")
+ .routeId("crm-tool")
+ .setBody(constant("customer"));
+
+
from("ai-resource:crm_config?resourceUri=camel:///crm/config&tags=crm"
+ + "&description=The CRM
configuration&mimeType=text/plain")
+ .routeId("crm-resource")
+ .setBody(constant("config"));
+
+ from("ai-prompt:crm_prompt?tags=crm&description=A CRM
prompt")
+ .routeId("crm-prompt")
+ .setBody(constant("Summarize the customer"));
+ }
+ };
+ }
+ }
+}
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 a6ce3c965dd..b883d5f1342 100644
--- a/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
+++ b/docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc
@@ -49,13 +49,15 @@ Resource Server starter. Let Spring Boot manage their
versions:
</dependency>
----
-Configure the authorization server issuer and select the Streamable HTTP
-transport:
+Configure the authorization server issuer and the audience of the accepted
+tokens, and select the Streamable HTTP transport:
[source,properties]
----
spring.ai.mcp.server.protocol = STREAMABLE
spring.security.oauth2.resourceserver.jwt.issuer-uri =
https://idp.example.com/issuer
+# Accept only the tokens issued for this MCP server: its resource URI, as
mcp.security.resource-uri below.
+spring.security.oauth2.resourceserver.jwt.audiences =
https://mcp.example.com/mcp
# Application-specific properties used by this example; not Camel starter
options.
# Canonical, externally visible URLs for this protected MCP resource.
@@ -73,6 +75,7 @@ authentication so MCP clients can discover the authorization
server.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
@@ -82,6 +85,7 @@ import org.springframework.security.web.SecurityFilterChain;
public class McpSecurityConfiguration {
@Bean
+ @Order(1)
SecurityFilterChain mcpSecurity(
HttpSecurity http,
@Value("${mcp.security.resource-uri}") String resourceUri,
@@ -116,10 +120,27 @@ public class McpSecurityConfiguration {
}
----
+The `securityMatcher` limits this filter chain to the MCP endpoint and the
+metadata paths. Once the application defines a `SecurityFilterChain`, Spring
+Boot's default chain backs off, so requests to the other endpoints of the
+application match no chain and are not secured: keep a filter chain of the
+application for them, ordered after this one (a higher `@Order` value), as
+Spring Security requires a chain that matches any request to come last.
+
The issuer in `authorizationServer` must identify the authorization server
that issues tokens accepted by this resource server. Spring Security validates
-JWT bearer tokens using the configured issuer. Its protected-resource metadata
-support publishes the metadata document. For the `/mcp` endpoint, configure
+JWT bearer tokens using the configured issuer. Spring Boot checks the
+audience (`aud` claim) only when
+`spring.security.oauth2.resourceserver.jwt.audiences` is set: without it, a
+token that the same issuer minted for another API is accepted, while the MCP
+authorization specification requires the server to accept only the tokens
+issued for it. The setting applies to the `JwtDecoder` that Spring Boot
+auto-configures, and so to every filter chain that uses it: when other
+endpoints of the application accept tokens issued for another audience, give
+the MCP chain its own decoder that checks this audience instead, with
+`.jwt(jwt -> jwt.decoder(mcpJwtDecoder))`. Spring Security's protected-resource
+metadata support publishes the metadata document. For the `/mcp` endpoint,
+configure
`mcp.security.resource-uri` as `https://mcp.example.com/mcp` and
`mcp.security.resource-metadata-uri` as
`https://mcp.example.com/.well-known/oauth-protected-resource/mcp`.
@@ -152,7 +173,7 @@ The example ignores CSRF only for the MCP endpoint because
MCP clients send
bearer tokens rather than browser session-based CSRF tokens. Do not disable
CSRF protection globally when the application uses it for other endpoints.
If your MCP endpoint is configured at a path other than `/mcp`, update the
-security matchers and both canonical URL properties accordingly.
+security matchers, both canonical URL properties and the audience accordingly.
For MCP tool calls, the Camel Spring Boot engine captures the authenticated
Spring principal and its name. Camel roles and OAuth scopes are derived only
@@ -325,6 +346,14 @@ spring.ai.mcp.server.resource-change-notification = true
spring.ai.mcp.server.prompt-change-notification = true
----
+When the Spring AI MCP server serves no tools, resources or prompts, for
+example with `spring.ai.mcp.server.capabilities.tool=false`, the Camel routes
+of that kind are not exposed: the application starts, the routes keep running,
+and the starter logs why they are not served. With `MODERN` (see
+<<_mcp_protocol_version_2026_07_28>>), such a property only stops Spring AI
+from auto-configuring the repository of that kind: a repository the
+application defines is still served.
+
=== Origin validation
Camel's principal-aware HTTP transport is selected only when
@@ -334,8 +363,9 @@ Camel's principal-aware HTTP transport is selected only when
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
- context needed by Camel route capabilities.
+ configured and the Spring AI MCP server is of the `SYNC` type (see
+ <<_server_type>>). This enables the Origin validator and authenticated
+ caller context needed by Camel route capabilities.
* Set `camel.mcp-server.transport-enabled=true` to select the Camel provider
even when no Camel tags are configured, for example when the application
exposes only Spring-defined `@McpTool`, `@McpResource`, or `@McpPrompt`
@@ -426,6 +456,36 @@ provider must still be configured with an authentication
mechanism and the
appropriate authorization policy. The `camel.mcp-server.allowed-origins`
property is applied only to Camel's auto-configured provider.
+To change a few settings of the transport rather than replace it, define
+`McpServerCustomizer` beans for its builder, as with Spring AI's own
+transports:
`McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>`
+for `STREAMABLE`, `McpServerCustomizer<WebMvcStatelessServerTransport.Builder>`
+for `STATELESS` and `McpServerCustomizer<WebMvcModernServerTransport.Builder>`
+for `MODERN`. When Camel's transport is selected, they are applied too, in
+their order and after Camel's settings, so a customizer takes precedence over
+Camel:
+
+* a customizer that sets other options, such as the maximum number of
+ sessions or the session idle timeout, keeps Camel's Origin validation and
+ authenticated caller context;
+* a customizer that sets its own security validator (`securityValidator`, or
+ `httpHeaderValidator` for `MODERN`) replaces Camel's Origin validation, and
+ `camel.mcp-server.allowed-origins` no longer applies;
+* a customizer that sets its own context extractor (`contextExtractor`)
+ replaces Camel's authenticated caller context, unless it builds the
+ context with `SpringAiMcpTransportContext.extract(request, entries)` as
+ shown above.
+
+[source,java]
+----
+@Bean
+McpServerCustomizer<WebMvcStreamableServerTransportProvider.Builder>
mcpTransportCustomizer() {
+ return builder -> builder
+ .maxSessions(1000)
+ .sessionIdleTimeout(Duration.ofMinutes(30));
+}
+----
+
The streamable HTTP transport has to be selected explicitly with
`spring.ai.mcp.server.protocol=STREAMABLE`; when the property is not set,
Spring AI serves the deprecated SSE transport instead and there is no
@@ -443,6 +503,20 @@ spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp
----
+=== Server type
+
+Whatever the protocol, the starter serves the Camel routes only on a Spring AI
+MCP server of the `SYNC` type: `spring.ai.mcp.server.type=SYNC`, the default.
+With `spring.ai.mcp.server.type=ASYNC`:
+
+* the Camel routes are not served, and the starter logs a warning when
+ `camel.mcp-server.tags` is configured;
+* Spring AI's transport is kept, without Camel's Origin validation and
+ authenticated caller context, unless
+ `camel.mcp-server.transport-enabled=true` is set with
+ `spring.ai.mcp.server.protocol` `STREAMABLE`, `STATELESS` or `MODERN` and
+ the stdio transport disabled.
+
=== Serving without sessions
With `spring.ai.mcp.server.protocol=STREAMABLE`, the Spring AI MCP server keeps
@@ -496,9 +570,13 @@ camel.mcp-server.tags = crm
The Camel routes are added to the tool, resource and prompt repositories that
Spring AI auto-configures, next to the application's own tools, resources and
prompts. A Camel route with the name or URI of one of them is refused, as with
-the other protocols. Camel's Origin validation and caller-context extraction
-apply to every request: the starter provides them to Spring AI's
-`WebMvcModernServerTransport` as `ServerHttpHeaderValidator` and
+the other protocols. A resource with the URI of a resource template, or a
+template with the URI of a resource, is refused too, because the Spring AI
+resource repository removes both together: when the application registers such
+an entry at runtime, after the Camel route, stopping the route removes it as
+well, and the starter logs a warning. Camel's Origin validation and
+caller-context extraction apply to every request: the starter provides them to
+Spring AI's `WebMvcModernServerTransport` as `ServerHttpHeaderValidator` and
`McpTransportContextExtractor` beans, and beans of those types defined by the
application take precedence.
@@ -510,8 +588,8 @@ Be aware that:
2026-07-28 first and fall back to `initialize` connect with 2026-07-28. Camel
Main and Camel JBang serve both kinds of client on the same endpoint (see
xref:components:others:mcp-server.adoc[MCP Server]);
-* only `spring.ai.mcp.server.type=SYNC`, the default, is supported: with
- `ASYNC`, the starter does not register the Camel routes;
+* as with the other protocols, only `spring.ai.mcp.server.type=SYNC`, the
+ default, is supported (see <<_server_type>>);
* if the application defines its own tool, resource or prompt repository, the
Camel routes of that kind are not served, and the starter logs a warning;
* protocol version 2026-07-28 is built on the `io.modelcontextprotocol.modern`
@@ -570,11 +648,19 @@ the plain `spring-ai-starter-mcp-server`. Swap the
transport starter:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server</artifactId>
- <version>2.0.0</version>
+ <!-- the Spring AI version of camel-mcp-server-starter -->
+ <version>2.1.0</version>
</dependency>
----
-and enable the stdio transport:
+The version of `spring-ai-starter-mcp-server` must be the Spring AI version
+the starter is built with: the version of `spring-ai-starter-mcp-server-webmvc`
+in the POM of `camel-mcp-server-starter`. Another
+version, including one that the dependency management of the application
+imposes, for example with an older Spring AI BOM, can lack MCP Java SDK types
+the starter uses, and the application then fails at startup.
+
+Then enable the stdio transport:
[source,properties]
----
@@ -675,11 +761,11 @@ The starter supports 7 options, which are listed below.
[width="100%",cols="2,5,^1,2",options="header"]
|===
| Name | Description | Default | Type
-| camel.mcp-server.allowed-origins | Comma-separated list of origins allowed
to call the Streamable HTTP MCP endpoint. Entries may be exact origins or use a
wildcard port, for example http://localhost:*. When unset, only loopback
origins are allowed. Requests without an Origin header are accepted. This
setting is applied when Camel's Streamable HTTP transport provider is selected.
| | String
+| camel.mcp-server.allowed-origins | Comma-separated list of origins allowed
to call the MCP HTTP endpoint (protocol STREAMABLE, STATELESS or MODERN).
Entries may be exact origins or use a wildcard port, for example
http://localhost:*. When unset, only loopback origins are allowed. Requests
without an Origin header are accepted. This setting is applied when Camel's
Origin validation is installed, see camel.mcp-server.transport-enabled. | |
String
| camel.mcp-server.enabled | Whether to enable Camel MCP integration for
ai-tool, ai-resource, and ai-prompt routes through the Spring AI MCP server.
Enabled by default when the starter is on the classpath. | true | Boolean
-| camel.mcp-server.prompt-timeout | Per-request prompt execution timeout in
milliseconds. A request exceeding the timeout returns an error to the MCP
client; the underlying route may continue running until it completes. | | Long
-| camel.mcp-server.resource-timeout | Per-read resource execution timeout in
milliseconds. A read exceeding the timeout returns an error to the MCP client;
the underlying route keeps running until it completes on its own. | | Long
+| camel.mcp-server.prompt-timeout | Per-request prompt execution timeout in
milliseconds. A request exceeding the timeout returns an error to the MCP
client; the underlying route may continue running until it completes. | 20000 |
Long
+| camel.mcp-server.resource-timeout | Per-read resource execution timeout in
milliseconds. A read exceeding the timeout returns an error to the MCP client;
the underlying route keeps running until it completes on its own. | 20000 | Long
| camel.mcp-server.tags | Comma-separated tag patterns used to select ai-tool,
ai-resource, and ai-prompt routes for MCP exposure. Only matching routes are
published; the untagged default pools are never exposed. When not set, no Camel
tools, resources, resource templates, or prompts are published. | | String
-| camel.mcp-server.tool-timeout | Per-call tool execution timeout in
milliseconds. A call exceeding the timeout returns an error result to the MCP
client; the underlying route keeps running until it completes on its own. The
default is 20000 milliseconds. | | Long
-| camel.mcp-server.transport-enabled | Whether to replace Spring AI's default
Streamable HTTP transport with Camel's transport. When unset, replacement is
enabled only when \{@code tags} is configured. Set this to true to enable Camel
Origin validation and caller-context extraction without Camel routes, or false
to keep Spring AI's provider while leaving the Camel bridge independently
enabled. | | Boolean
+| camel.mcp-server.tool-timeout | Per-call tool execution timeout in
milliseconds. A call exceeding the timeout returns an error result to the MCP
client; the underlying route keeps running until it completes on its own. |
20000 | Long
+| camel.mcp-server.transport-enabled | Whether to install Camel's Origin
validation and caller-context extraction on the Spring AI MCP HTTP transport
(protocol STREAMABLE, STATELESS or MODERN). When unset, they are installed only
when camel.mcp-server.tags is configured and spring.ai.mcp.server.type is SYNC,
the default. Set this to true to install them without Camel routes or with an
ASYNC server, or false to keep Spring AI's transport as is while leaving the
Camel bridge independently [...]
|===