Croway commented on code in PR #2094:
URL: 
https://github.com/apache/camel-spring-boot/pull/2094#discussion_r4575418179


##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java:
##########
@@ -0,0 +1,294 @@
+/*
+ * 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.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.server.McpSyncServerExchange;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.springframework.web.servlet.function.ServerRequest;
+
+/**
+ * Captures the authenticated HTTP caller when Spring AI creates the MCP 
transport context,
+ * and makes that caller available to Camel tool execution.
+ * <p>
+ * The identity is taken from the servlet request principal established by the 
application's
+ * security infrastructure. It is not derived from MCP tool arguments or 
client-supplied
+ * identity headers.
+ * <p>
+ * Spring Security is optional for applications using this starter. Its APIs 
are accessed
+ * reflectively, and reflective accessors are cached per Authentication 
implementation.
+ * <p>
+ * Spring authorities with the ROLE_ prefix are exposed without that prefix. 
SCOPE_ authorities
+ * are mapped to OAuth scopes, and FACTOR_ authorities are not treated as 
application roles.
+ * When the principal is a JwtAuthenticationToken, its subject, scopes and 
claims are also
+ * propagated to the Camel tool exchange.
+ * <p>
+ * Applications that provide their own {@code 
WebMvcStreamableServerTransportProvider}
+ * can preserve caller identity by installing
+ * {@code .contextExtractor(SpringAiMcpTransportContext::extract)} on its 
builder.
+ */
+public final class SpringAiMcpTransportContext {
+
+    static final String CALL_CONTEXT_KEY =
+            SpringAiMcpTransportContext.class.getName() + ".toolCallContext";
+
+    private static final String AUTHENTICATION_CLASS =
+            "org.springframework.security.core.Authentication";
+    private static final String GRANTED_AUTHORITY_CLASS =
+            "org.springframework.security.core.GrantedAuthority";
+    private static final String JWT_AUTHENTICATION_CLASS =
+            
"org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken";
+
+    private static final ClassValue<AuthenticationAccessors> ACCESSORS = new 
ClassValue<>() {
+        @Override
+        protected AuthenticationAccessors computeValue(Class<?> type) {
+            ClassLoader loader = type.getClassLoader();
+            if (loader == null) {
+                loader = SpringAiMcpTransportContext.class.getClassLoader();
+            }
+
+            try {
+                Class<?> authenticationType = 
Class.forName(AUTHENTICATION_CLASS, false, loader);
+                if (!authenticationType.isAssignableFrom(type)) {
+                    return AuthenticationAccessors.NONE;
+                }
+
+                Class<?> authorityType = 
Class.forName(GRANTED_AUTHORITY_CLASS, false, loader);
+                Method getAuthorities = 
authenticationType.getMethod("getAuthorities");
+                Method getAuthority = authorityType.getMethod("getAuthority");
+
+                Method getTokenAttributes = null;
+                try {
+                    Class<?> jwtAuthenticationType = 
Class.forName(JWT_AUTHENTICATION_CLASS, false, loader);
+                    if (jwtAuthenticationType.isAssignableFrom(type)) {
+                        getTokenAttributes = 
jwtAuthenticationType.getMethod("getTokenAttributes");
+                    }
+                } catch (ReflectiveOperationException | LinkageError | 
SecurityException ignored) {
+                    // OAuth2 Resource Server is optional.
+                }
+
+                return new AuthenticationAccessors(getAuthorities, 
getAuthority, getTokenAttributes);
+            } catch (ReflectiveOperationException | LinkageError | 
SecurityException e) {
+                return AuthenticationAccessors.NONE;
+            }
+        }
+    };
+
+    private SpringAiMcpTransportContext() {
+    }
+
+    /**
+     * Extracts the authenticated caller from the current HTTP request.
+     *
+     * @param request the Spring MVC request received by the MCP transport
+     * @return an MCP transport context containing the caller, or the empty 
context
+     */
+    public static McpTransportContext extract(ServerRequest request) {
+        Principal principal = request.principal().orElse(null);
+        if (principal == null) {
+            return McpTransportContext.EMPTY;
+        }
+
+        return McpTransportContext.create(Map.of(CALL_CONTEXT_KEY, 
toCallContext(principal)));
+    }
+
+    /**
+     * Retrieves the caller context attached to the MCP request by the 
transport extractor.
+     *
+     * @param exchange the MCP SDK server exchange
+     * @return the captured caller context, or the empty context
+     */
+    static McpToolCallContext from(McpSyncServerExchange exchange) {
+        if (exchange == null || exchange.transportContext() == null) {
+            return McpToolCallContext.EMPTY;
+        }
+
+        Object value = exchange.transportContext().get(CALL_CONTEXT_KEY);
+        return value instanceof McpToolCallContext context
+                ? context
+                : McpToolCallContext.EMPTY;
+    }
+
+    private static McpToolCallContext toCallContext(Principal principal) {
+        AuthenticationAccessors accessors = 
ACCESSORS.get(principal.getClass());
+        Set<String> roles = new LinkedHashSet<>();
+        Set<String> scopes = new LinkedHashSet<>();
+        Map<String, Object> claims = null;
+
+        if (accessors != AuthenticationAccessors.NONE) {
+            readAuthorities(principal, accessors, roles, scopes);
+            claims = readJwtClaims(principal, accessors);
+        }
+
+        String oauthSubject = null;
+        if (claims != null) {
+            Object subject = claims.get("sub");
+            if (subject instanceof String value && !value.isBlank()) {
+                oauthSubject = value;
+            }
+
+            addScopeClaim(scopes, claims.get("scope"));
+            addScopeClaim(scopes, claims.get("scp"));
+            addClaimRoles(claims, roles);

Review Comment:
   **Raw JWT claims are merged into the caller's roles.** `addClaimRoles` adds 
the `roles` / `realm_access.roles` / `groups` claims to the principal roles, on 
top of the authorities produced by the application's own 
`JwtAuthenticationConverter`. In a Spring app the converter is where the 
application decides which token claims become authorities, so this bypasses 
that decision.
   
   Example: an app maps only client roles (`resource_access.myapp.roles`) or 
only scopes to authorities. A Keycloak token whose `realm_access.roles` 
contains `admin` (granted for a different application) still ends up with 
`admin` in `McpToolCallContext.SECURITY_PRINCIPAL_ROLES_PROPERTY`. A route 
`AuthorizationPolicy` that requires `admin` then lets the call through, 
although Spring Security never granted `ROLE_admin`.
   
   Suggestion: on Spring Boot, derive roles only from 
`Authentication.getAuthorities()` and keep the raw claims available through the 
OAuth claims for routes that want them. If claim-based roles are needed for 
parity with Camel Main, make them opt-in and document the behaviour.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java:
##########
@@ -108,6 +136,280 @@ public void toolRemoved(String toolName) {
         }
     }
 
+    @Override
+    public void resourceAdded(McpServerResource 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");
+        }
+
+        McpSchema.Resource mcpResource = buildMcpResource(resource);
+
+        McpServerFeatures.SyncResourceSpecification spec =
+                new McpServerFeatures.SyncResourceSpecification(
+                        mcpResource,
+                        (exchange, request) -> {
+                            McpResourceReadResult result = 
resource.handler().read();
+
+                            if (result.isError()) {
+                                throw 
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
+                                        .message(result.errorMessage())
+                                        .build();
+                            }
+
+                            McpSchema.ResourceContents contents;
+
+                            if (result.blob() != null) {
+                                contents = new McpSchema.BlobResourceContents(
+                                        resource.uri(),
+                                        resource.mimeType(),
+                                        
Base64.getEncoder().encodeToString(result.blob()));
+                            } else {
+                                contents = new McpSchema.TextResourceContents(
+                                        resource.uri(),
+                                        resource.mimeType(),
+                                        result.text());
+                            }
+
+                            return new 
McpSchema.ReadResourceResult(List.of(contents));
+                        });
+
+        server.addResource(spec);
+        LOG.debug("MCP resource added: {}", resource.uri());
+    }
+
+    @Override
+    public void resourceRemoved(String resourceUri) {
+        try {
+            server.removeResource(resourceUri);
+            LOG.debug("MCP resource removed: {}", resourceUri);
+        } catch (Exception e) {
+            LOG.debug("Failed to remove MCP resource {}: {}", resourceUri, 
e.getMessage());
+        }
+    }
+
+    @Override
+    public boolean supportsResources() {
+        McpSchema.ServerCapabilities capabilities = 
server.getServerCapabilities();
+        return capabilities != null && capabilities.resources() != null;
+    }
+
+    @Override
+    public void resourceTemplateAdded(McpServerResourceTemplate 
resourceTemplate) {
+        if (server.listResourceTemplates().stream()
+                .anyMatch(existing -> 
existing.uriTemplate().equals(resourceTemplate.uriTemplate()))) {

Review Comment:
   **Only identical template strings are refused, not overlapping ones.** The 
engine contract (`McpServerEngine#resourceTemplateAdded`: "throws 
McpServerRefusedException to refuse an overlapping or otherwise unsupported 
template") asks for overlap detection. `McpServerBridge` checks overlap only 
among Camel's own templates, so a clash with a Spring-defined template gets 
through.
   
   Example: Spring defines `camel:///customers/{id}` and a Camel route defines 
`camel:///customers/{customerId}`. Both are registered. The SDK keeps templates 
in a `ConcurrentHashMap` and `findResourceTemplateSpecification` returns the 
first match, so which handler serves `resources/read camel:///customers/42` is 
not defined.
   
   Suggestion: refuse the template when it overlaps any template already 
registered on the server, using the same overlap rule the bridge applies to 
Camel templates.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.springboot.mcp.server;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import 
io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
+import 
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.component.mcp.server.McpServerOrigins;
+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.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import 
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Installs a principal-aware Spring AI WebMVC 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.
+ * <p>
+ * An application-defined {@link WebMvcStreamableServerTransportProvider} 
takes precedence.
+ */
+@AutoConfiguration(
+        beforeName = "org.springframework.ai.mcp.server.webmvc.autoconfigure."
+                + "McpServerStreamableHttpWebMvcAutoConfiguration")
+@ConditionalOnClass({
+        WebMvcStreamableServerTransportProvider.class,
+        JacksonMcpJsonMapper.class
+})
+@Conditional(McpServerStdioDisabledCondition.class)
+@ConditionalOnProperty(
+        prefix = "camel.mcp-server",
+        name = "enabled",
+        havingValue = "true",
+        matchIfMissing = true)
+@ConditionalOnProperty(
+        prefix = "spring.ai.mcp.server",
+        name = "protocol",
+        havingValue = "STREAMABLE",
+        matchIfMissing = false)
+@EnableConfigurationProperties({
+        McpServerStreamableHttpProperties.class,
+        McpServerConfigurationProperties.class
+})
+public class CamelMcpServerTransportAutoConfiguration {
+
+    private static final List<String> DEFAULT_ALLOWED_ORIGINS = List.of(
+            "http://localhost:*";, "https://localhost:*";,
+            "http://127.0.0.1:*";, "https://127.0.0.1:*";,
+            "http://[::1]:*";, "https://[::1]:*";);
+
+    @Bean
+    @ConditionalOnMissingBean(WebMvcStreamableServerTransportProvider.class)
+    WebMvcStreamableServerTransportProvider 
webMvcStreamableServerTransportProvider(

Review Comment:
   **This changes Origin handling for apps that don't expose any Camel 
capability.** With the starter on the classpath and 
`spring.ai.mcp.server.protocol=STREAMABLE`, this bean replaces Spring AI's 
default transport, which in 2.0.2 
(`McpServerStreamableHttpWebMvcAutoConfiguration`) sets no security validator. 
The replacement is active even when `camel.mcp-server.tags` is unset and Camel 
exposes nothing, so Spring-defined `@McpTool` / `@McpResource` endpoints 
suddenly accept only loopback origins.
   
   Example: a 4.23 app serving Spring `@McpTool` methods to a browser client at 
`https://app.example.com` gets HTTP 403 `Invalid Origin header` after 
upgrading. The only ways out are `camel.mcp-server.allowed-origins`, or 
`camel.mcp-server.enabled=false`, which also turns off the Camel bridge.
   
   Suggestion: add an upgrade-guide entry for this, and consider a dedicated 
switch for replacing the transport.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java:
##########
@@ -108,6 +136,280 @@ public void toolRemoved(String toolName) {
         }
     }
 
+    @Override
+    public void resourceAdded(McpServerResource 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");
+        }
+
+        McpSchema.Resource mcpResource = buildMcpResource(resource);
+
+        McpServerFeatures.SyncResourceSpecification spec =
+                new McpServerFeatures.SyncResourceSpecification(
+                        mcpResource,
+                        (exchange, request) -> {
+                            McpResourceReadResult result = 
resource.handler().read();
+
+                            if (result.isError()) {
+                                throw 
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
+                                        .message(result.errorMessage())
+                                        .build();
+                            }
+
+                            McpSchema.ResourceContents contents;
+
+                            if (result.blob() != null) {
+                                contents = new McpSchema.BlobResourceContents(
+                                        resource.uri(),
+                                        resource.mimeType(),
+                                        
Base64.getEncoder().encodeToString(result.blob()));
+                            } else {
+                                contents = new McpSchema.TextResourceContents(
+                                        resource.uri(),
+                                        resource.mimeType(),
+                                        result.text());
+                            }
+
+                            return new 
McpSchema.ReadResourceResult(List.of(contents));
+                        });
+
+        server.addResource(spec);
+        LOG.debug("MCP resource added: {}", resource.uri());
+    }
+
+    @Override
+    public void resourceRemoved(String resourceUri) {
+        try {
+            server.removeResource(resourceUri);
+            LOG.debug("MCP resource removed: {}", resourceUri);
+        } catch (Exception e) {
+            LOG.debug("Failed to remove MCP resource {}: {}", resourceUri, 
e.getMessage());
+        }
+    }
+
+    @Override
+    public boolean supportsResources() {
+        McpSchema.ServerCapabilities capabilities = 
server.getServerCapabilities();
+        return capabilities != null && capabilities.resources() != null;
+    }
+
+    @Override
+    public void resourceTemplateAdded(McpServerResourceTemplate 
resourceTemplate) {
+        if (server.listResourceTemplates().stream()
+                .anyMatch(existing -> 
existing.uriTemplate().equals(resourceTemplate.uriTemplate()))) {
+            throw new McpServerRefusedException(
+                    "An MCP resource template '" + 
resourceTemplate.uriTemplate() + "' is already registered");
+        }
+
+        McpSchema.ResourceTemplate.Builder builder = McpSchema.ResourceTemplate
+                .builder(resourceTemplate.uriTemplate(), 
resourceTemplate.name())
+                .description(resourceTemplate.description())
+                .mimeType(resourceTemplate.mimeType());
+
+        if (resourceTemplate.title() != null && 
!resourceTemplate.title().isBlank()) {
+            builder.title(resourceTemplate.title());
+        }
+
+        McpServerFeatures.SyncResourceTemplateSpecification spec =
+                new McpServerFeatures.SyncResourceTemplateSpecification(
+                        builder.build(),
+                        (exchange, request) -> {
+                            McpResourceReadResult result =
+                                    
resourceTemplate.handler().read(request.uri());
+
+                            if (result.isError()) {
+                                throw 
McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
+                                        .message(result.errorMessage())
+                                        .build();
+                            }
+
+                            McpSchema.ResourceContents contents;
+
+                            if (result.blob() != null) {
+                                contents = new McpSchema.BlobResourceContents(
+                                        request.uri(),
+                                        resourceTemplate.mimeType(),
+                                        
Base64.getEncoder().encodeToString(result.blob()));
+                            } else {
+                                contents = new McpSchema.TextResourceContents(
+                                        request.uri(),
+                                        resourceTemplate.mimeType(),
+                                        result.text());
+                            }
+
+                            return new 
McpSchema.ReadResourceResult(List.of(contents));
+                        });
+
+        server.addResourceTemplate(spec);
+        LOG.debug("MCP resource template added: {}", 
resourceTemplate.uriTemplate());
+    }
+
+    @Override
+    public void resourceTemplateRemoved(String uriTemplate) {
+        try {
+            server.removeResourceTemplate(uriTemplate);
+
+            // The MCP SDK does not emit resources/list_changed for template 
removal.
+            // Keep this explicit notification so clients see route lifecycle 
changes.
+            server.notifyResourcesListChanged();

Review Comment:
   **This notification is sent even when list-change notifications are 
disabled.** The SDK's own add/remove paths check 
`serverCapabilities.resources().listChanged()` before calling 
`notifyResourcesListChanged()` (`McpAsyncServer` 2.1.0). Here the call is 
unconditional, so with 
`spring.ai.mcp.server.resource-change-notification=false` clients still receive 
`notifications/resources/list_changed`. It is also sent when the template was 
not found, because the SDK only logs a warning in that case and does not throw.
   
   Suggestion: guard it with 
`Boolean.TRUE.equals(server.getServerCapabilities().resources().listChanged())`,
 and skip it when nothing was removed.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.springboot.mcp.server;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import 
io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
+import 
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.component.mcp.server.McpServerOrigins;
+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.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import 
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Installs a principal-aware Spring AI WebMVC 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.
+ * <p>
+ * An application-defined {@link WebMvcStreamableServerTransportProvider} 
takes precedence.
+ */
+@AutoConfiguration(
+        beforeName = "org.springframework.ai.mcp.server.webmvc.autoconfigure."
+                + "McpServerStreamableHttpWebMvcAutoConfiguration")
+@ConditionalOnClass({
+        WebMvcStreamableServerTransportProvider.class,
+        JacksonMcpJsonMapper.class
+})
+@Conditional(McpServerStdioDisabledCondition.class)
+@ConditionalOnProperty(
+        prefix = "camel.mcp-server",
+        name = "enabled",
+        havingValue = "true",
+        matchIfMissing = true)
+@ConditionalOnProperty(
+        prefix = "spring.ai.mcp.server",
+        name = "protocol",
+        havingValue = "STREAMABLE",
+        matchIfMissing = false)
+@EnableConfigurationProperties({
+        McpServerStreamableHttpProperties.class,
+        McpServerConfigurationProperties.class
+})
+public class CamelMcpServerTransportAutoConfiguration {
+
+    private static final List<String> DEFAULT_ALLOWED_ORIGINS = List.of(
+            "http://localhost:*";, "https://localhost:*";,
+            "http://127.0.0.1:*";, "https://127.0.0.1:*";,
+            "http://[::1]:*";, "https://[::1]:*";);
+
+    @Bean
+    @ConditionalOnMissingBean(WebMvcStreamableServerTransportProvider.class)
+    WebMvcStreamableServerTransportProvider 
webMvcStreamableServerTransportProvider(
+            @Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper,
+            McpServerStreamableHttpProperties serverProperties,
+            McpServerConfigurationProperties camelProperties) {
+
+        return WebMvcStreamableServerTransportProvider.builder()
+                .jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
+                .mcpEndpoint(serverProperties.getMcpEndpoint())
+                .keepAliveInterval(serverProperties.getKeepAliveInterval())
+                .disallowDelete(serverProperties.isDisallowDelete())
+                
.securityValidator(createOriginValidator(camelProperties.getAllowedOrigins()))
+                .contextExtractor(SpringAiMcpTransportContext::extract)
+                .build();
+    }
+
+    /**
+     * Creates the MCP SDK validator using Camel's shared origin parser and 
normalizer.
+     * Requests without an Origin header are accepted by the SDK validator.
+     */
+    // Spring AI 2.0.2 exposes only this deprecated validator type on the
+    // WebMVC transport builder.
+    @SuppressWarnings("deprecation")
+    private static ServerTransportSecurityValidator 
createOriginValidator(String configuredAllowedOrigins) {

Review Comment:
   **Apps with a custom transport can't reuse Camel's Origin policy.** The docs 
ask apps that define their own `WebMvcStreamableServerTransportProvider` to 
install "an Origin validator equivalent to, or stricter than" this one, but 
`createOriginValidator` and `DEFAULT_ALLOWED_ORIGINS` are private, so they have 
to re-implement the normalization and the loopback defaults. 
`SpringBootMcpServerCustomTransportTest` already differs: it uses 
`DefaultServerTransportSecurityValidator` directly, without the 
`McpServerOrigins` normalization.
   
   Similarly, `SpringAiMcpTransportContext.CALL_CONTEXT_KEY` is 
package-private, so an app that needs its own transport-context entries can't 
combine them with Camel's identity entry.
   
   Suggestion: expose the validator factory and defaults as public API, and 
offer a way to compose the context extractor with an application's own entries.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java:
##########
@@ -30,8 +31,8 @@
 public class McpServerConfigurationProperties {
 
     /**
-     * Whether to expose ai-tool routes as MCP tools through the Spring AI MCP 
server. Enabled by default when the
-     * starter is on the classpath.
+     * 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.

Review Comment:
   The `enabled` description was updated, but the `tags` javadoc just below 
(lines 40-41) still says "Comma-separated list of ai-tool tags to expose as MCP 
tools ... When not set, no tools are exposed." Tags now also select 
`ai-resource` and `ai-prompt` routes. Updating that javadoc and regenerating 
also fixes `mcp-server.json` and the options table in `mcp-server.adoc`.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpServerEngine.java:
##########
@@ -78,20 +90,36 @@ public void initialize(McpServerInfo info) {
 
     @Override
     public void toolAdded(McpServerTool tool) {
+        if (server.listTools().stream().anyMatch(existing -> 
existing.name().equals(tool.name()))) {
+            throw new McpServerRefusedException(
+                    "An MCP tool named '" + tool.name() + "' is already 
registered");
+        }
+
         String schema = tool.inputSchemaJson() != null ? 
tool.inputSchemaJson() : EMPTY_OBJECT_SCHEMA;
         McpSchema.Tool.Builder builder = McpSchema.Tool.builder(tool.name(), 
jsonMapper, schema)
                 .description(tool.description());
+
+        if (tool.outputSchemaJson() != null && 
!tool.outputSchemaJson().isBlank()) {
+            builder.outputSchema(jsonMapper, tool.outputSchemaJson());

Review Comment:
   **An invalid `outputSchema` fails startup instead of refusing this one 
tool.** `server.addTool` validates both schemas with 
`jsonSchemaValidator.assertConforms` (MCP Java SDK 2.1.0, 
`McpAsyncServer#addTool`) and fails with `IllegalArgumentException`. 
`McpServerBridge` only catches `McpServerRefusedException` around 
`engine.toolAdded`, so the exception propagates.
   
   Example: `ai-tool:x?outputSchema={"type":"obj"}` passes the ai-tool check 
(it is a JSON object), then fails CamelContext / route startup instead of 
logging an error and skipping the tool.
   
   Suggestion: catch `IllegalArgumentException` from `server.addTool` and 
rethrow it as `McpServerRefusedException`, plus a test with an invalid output 
schema.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.springboot.mcp.server;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import 
io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
+import 
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.component.mcp.server.McpServerOrigins;
+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.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import 
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Installs a principal-aware Spring AI WebMVC 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.
+ * <p>
+ * An application-defined {@link WebMvcStreamableServerTransportProvider} 
takes precedence.
+ */
+@AutoConfiguration(
+        beforeName = "org.springframework.ai.mcp.server.webmvc.autoconfigure."
+                + "McpServerStreamableHttpWebMvcAutoConfiguration")
+@ConditionalOnClass({
+        WebMvcStreamableServerTransportProvider.class,
+        JacksonMcpJsonMapper.class
+})
+@Conditional(McpServerStdioDisabledCondition.class)
+@ConditionalOnProperty(
+        prefix = "camel.mcp-server",
+        name = "enabled",
+        havingValue = "true",

Review Comment:
   **`havingValue = "true"` doesn't match how `CamelMcpServerAutoConfiguration` 
reads the same property.** That class uses `@ConditionalOnProperty(value = 
"camel.mcp-server.enabled", matchIfMissing = true)`, which matches any value 
other than `false`. Here only `true` matches.
   
   Example: with `camel.mcp-server.enabled=on` (which Spring binds to `true`), 
the bridge is active but this transport is not installed. There is no Origin 
validation, and every tool call gets `McpToolCallContext.EMPTY`, so role-based 
`AuthorizationPolicy` routes deny every caller. Nothing is logged.
   
   Suggestion: drop `havingValue` so both auto-configurations use the same 
condition.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java:
##########
@@ -0,0 +1,294 @@
+/*
+ * 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.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.server.McpSyncServerExchange;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.springframework.web.servlet.function.ServerRequest;
+
+/**
+ * Captures the authenticated HTTP caller when Spring AI creates the MCP 
transport context,
+ * and makes that caller available to Camel tool execution.
+ * <p>
+ * The identity is taken from the servlet request principal established by the 
application's
+ * security infrastructure. It is not derived from MCP tool arguments or 
client-supplied
+ * identity headers.
+ * <p>
+ * Spring Security is optional for applications using this starter. Its APIs 
are accessed
+ * reflectively, and reflective accessors are cached per Authentication 
implementation.
+ * <p>
+ * Spring authorities with the ROLE_ prefix are exposed without that prefix. 
SCOPE_ authorities
+ * are mapped to OAuth scopes, and FACTOR_ authorities are not treated as 
application roles.
+ * When the principal is a JwtAuthenticationToken, its subject, scopes and 
claims are also
+ * propagated to the Camel tool exchange.
+ * <p>
+ * Applications that provide their own {@code 
WebMvcStreamableServerTransportProvider}
+ * can preserve caller identity by installing
+ * {@code .contextExtractor(SpringAiMcpTransportContext::extract)} on its 
builder.
+ */
+public final class SpringAiMcpTransportContext {
+
+    static final String CALL_CONTEXT_KEY =
+            SpringAiMcpTransportContext.class.getName() + ".toolCallContext";
+
+    private static final String AUTHENTICATION_CLASS =
+            "org.springframework.security.core.Authentication";
+    private static final String GRANTED_AUTHORITY_CLASS =
+            "org.springframework.security.core.GrantedAuthority";
+    private static final String JWT_AUTHENTICATION_CLASS =

Review Comment:
   **Opaque-token callers get no subject or claims.** Claims are read only for 
`JwtAuthenticationToken`, but `getTokenAttributes()` is declared on 
`AbstractOAuth2TokenAuthenticationToken`, which `BearerTokenAuthentication` 
(token introspection, `oauth2ResourceServer(o -> o.opaqueToken(...))`) also 
extends. With opaque tokens the OAuth subject and claims are never set, so a 
route policy based on them denies every caller.
   
   Suggestion: look up `getTokenAttributes` on 
`AbstractOAuth2TokenAuthenticationToken` instead.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/McpServerConfigurationProperties.java:
##########
@@ -47,6 +48,13 @@ public class McpServerConfigurationProperties {
      */
     private long toolTimeout = 20000;

Review Comment:
   **No timeout options for resources and prompts.** This PR starts serving 
`ai-resource` and `ai-prompt` routes, but only `toolTimeout` is configurable. 
Camel's `McpServerConfiguration` has `setResourceTimeout` and 
`setPromptTimeout`, and `CamelMcpServerAutoConfiguration#camelMcpServerBridge` 
maps only `toolTimeout`, so Spring Boot users always get the built-in defaults. 
Camel Main lets users configure these.
   
   Suggestion: add `camel.mcp-server.resource-timeout` and 
`camel.mcp-server.prompt-timeout` and map them in 
`CamelMcpServerAutoConfiguration`.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/CamelMcpServerTransportAutoConfiguration.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.springboot.mcp.server;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
+import 
io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
+import 
io.modelcontextprotocol.server.transport.ServerTransportSecurityValidator;
+import org.apache.camel.component.mcp.server.McpServerOrigins;
+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.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import 
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import 
org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Installs a principal-aware Spring AI WebMVC 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.
+ * <p>
+ * An application-defined {@link WebMvcStreamableServerTransportProvider} 
takes precedence.
+ */
+@AutoConfiguration(
+        beforeName = "org.springframework.ai.mcp.server.webmvc.autoconfigure."
+                + "McpServerStreamableHttpWebMvcAutoConfiguration")
+@ConditionalOnClass({
+        WebMvcStreamableServerTransportProvider.class,
+        JacksonMcpJsonMapper.class
+})
+@Conditional(McpServerStdioDisabledCondition.class)
+@ConditionalOnProperty(
+        prefix = "camel.mcp-server",
+        name = "enabled",
+        havingValue = "true",
+        matchIfMissing = true)
+@ConditionalOnProperty(
+        prefix = "spring.ai.mcp.server",
+        name = "protocol",
+        havingValue = "STREAMABLE",

Review Comment:
   **With SSE, Origin validation and caller identity are silently missing.** 
When `spring.ai.mcp.server.protocol` is unset, Spring AI serves the SSE 
transport and this configuration does not apply. The Camel tools are still 
exposed, but with no Origin check and no caller identity, and nothing at 
runtime says so. A user who sets `camel.mcp-server.allowed-origins` and forgets 
the protocol believes Origin validation is active.
   
   Suggestion: log a WARN at startup when Camel capabilities are exposed (or 
`allowed-origins` is set) and the protocol is not `STREAMABLE`.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
docs/spring-boot/modules/ROOT/pages/starters/mcp-server.adoc:
##########
@@ -105,6 +234,155 @@ camel.mcp-server.tags = crm,notify
 camel.mcp-server.tool-timeout = 10000
 ----
 
+=== Resources and resource templates
+
+Expose a fixed resource with an `ai-resource` route. The route body supplies
+the resource content and the component metadata supplies its URI and MIME type:
+
+[source,java]
+----
+from("ai-resource:app_config?resourceUri=camel:///config/app.json"
+     + "&tags=crm&description=Application 
configuration&mimeType=application/json")
+    .setBody(constant("{\\"env\\":\\"production\\"}"));

Review Comment:
   AsciiDoc listing blocks show `\\"` literally, so this example (and the one 
at line 264) doesn't compile when copied: the Java string ends right after the 
first `\\`. These should be single-backslash escapes, for example 
`constant("{\"env\":\"production\"}")`.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
components-starter/camel-mcp-server-starter/src/main/java/org/apache/camel/springboot/mcp/server/SpringAiMcpTransportContext.java:
##########
@@ -0,0 +1,294 @@
+/*
+ * 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.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.server.McpSyncServerExchange;
+import org.apache.camel.component.mcp.server.McpToolCallContext;
+import org.springframework.web.servlet.function.ServerRequest;
+
+/**
+ * Captures the authenticated HTTP caller when Spring AI creates the MCP 
transport context,
+ * and makes that caller available to Camel tool execution.
+ * <p>
+ * The identity is taken from the servlet request principal established by the 
application's
+ * security infrastructure. It is not derived from MCP tool arguments or 
client-supplied
+ * identity headers.
+ * <p>
+ * Spring Security is optional for applications using this starter. Its APIs 
are accessed
+ * reflectively, and reflective accessors are cached per Authentication 
implementation.
+ * <p>
+ * Spring authorities with the ROLE_ prefix are exposed without that prefix. 
SCOPE_ authorities
+ * are mapped to OAuth scopes, and FACTOR_ authorities are not treated as 
application roles.
+ * When the principal is a JwtAuthenticationToken, its subject, scopes and 
claims are also
+ * propagated to the Camel tool exchange.
+ * <p>
+ * Applications that provide their own {@code 
WebMvcStreamableServerTransportProvider}
+ * can preserve caller identity by installing
+ * {@code .contextExtractor(SpringAiMcpTransportContext::extract)} on its 
builder.
+ */
+public final class SpringAiMcpTransportContext {
+
+    static final String CALL_CONTEXT_KEY =
+            SpringAiMcpTransportContext.class.getName() + ".toolCallContext";
+
+    private static final String AUTHENTICATION_CLASS =
+            "org.springframework.security.core.Authentication";
+    private static final String GRANTED_AUTHORITY_CLASS =
+            "org.springframework.security.core.GrantedAuthority";
+    private static final String JWT_AUTHENTICATION_CLASS =
+            
"org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken";
+
+    private static final ClassValue<AuthenticationAccessors> ACCESSORS = new 
ClassValue<>() {
+        @Override
+        protected AuthenticationAccessors computeValue(Class<?> type) {
+            ClassLoader loader = type.getClassLoader();
+            if (loader == null) {
+                loader = SpringAiMcpTransportContext.class.getClassLoader();
+            }
+
+            try {
+                Class<?> authenticationType = 
Class.forName(AUTHENTICATION_CLASS, false, loader);
+                if (!authenticationType.isAssignableFrom(type)) {
+                    return AuthenticationAccessors.NONE;
+                }
+
+                Class<?> authorityType = 
Class.forName(GRANTED_AUTHORITY_CLASS, false, loader);
+                Method getAuthorities = 
authenticationType.getMethod("getAuthorities");
+                Method getAuthority = authorityType.getMethod("getAuthority");
+
+                Method getTokenAttributes = null;
+                try {
+                    Class<?> jwtAuthenticationType = 
Class.forName(JWT_AUTHENTICATION_CLASS, false, loader);
+                    if (jwtAuthenticationType.isAssignableFrom(type)) {
+                        getTokenAttributes = 
jwtAuthenticationType.getMethod("getTokenAttributes");
+                    }
+                } catch (ReflectiveOperationException | LinkageError | 
SecurityException ignored) {
+                    // OAuth2 Resource Server is optional.
+                }
+
+                return new AuthenticationAccessors(getAuthorities, 
getAuthority, getTokenAttributes);
+            } catch (ReflectiveOperationException | LinkageError | 
SecurityException e) {
+                return AuthenticationAccessors.NONE;
+            }
+        }
+    };
+
+    private SpringAiMcpTransportContext() {
+    }
+
+    /**
+     * Extracts the authenticated caller from the current HTTP request.
+     *
+     * @param request the Spring MVC request received by the MCP transport
+     * @return an MCP transport context containing the caller, or the empty 
context
+     */
+    public static McpTransportContext extract(ServerRequest request) {
+        Principal principal = request.principal().orElse(null);
+        if (principal == null) {
+            return McpTransportContext.EMPTY;
+        }
+
+        return McpTransportContext.create(Map.of(CALL_CONTEXT_KEY, 
toCallContext(principal)));
+    }
+
+    /**
+     * Retrieves the caller context attached to the MCP request by the 
transport extractor.
+     *
+     * @param exchange the MCP SDK server exchange
+     * @return the captured caller context, or the empty context
+     */
+    static McpToolCallContext from(McpSyncServerExchange exchange) {
+        if (exchange == null || exchange.transportContext() == null) {
+            return McpToolCallContext.EMPTY;
+        }
+
+        Object value = exchange.transportContext().get(CALL_CONTEXT_KEY);
+        return value instanceof McpToolCallContext context
+                ? context
+                : McpToolCallContext.EMPTY;
+    }
+
+    private static McpToolCallContext toCallContext(Principal principal) {
+        AuthenticationAccessors accessors = 
ACCESSORS.get(principal.getClass());
+        Set<String> roles = new LinkedHashSet<>();
+        Set<String> scopes = new LinkedHashSet<>();
+        Map<String, Object> claims = null;
+
+        if (accessors != AuthenticationAccessors.NONE) {
+            readAuthorities(principal, accessors, roles, scopes);
+            claims = readJwtClaims(principal, accessors);
+        }
+
+        String oauthSubject = null;
+        if (claims != null) {
+            Object subject = claims.get("sub");
+            if (subject instanceof String value && !value.isBlank()) {
+                oauthSubject = value;
+            }
+
+            addScopeClaim(scopes, claims.get("scope"));
+            addScopeClaim(scopes, claims.get("scp"));
+            addClaimRoles(claims, roles);
+        }
+
+        return new McpToolCallContext(
+                principal,
+                principal.getName(),
+                List.copyOf(roles),
+                oauthSubject,
+                scopes.isEmpty() ? null : List.copyOf(scopes),
+                claims,
+                null);
+    }
+
+    private static void readAuthorities(
+            Principal principal,
+            AuthenticationAccessors accessors,
+            Set<String> roles,
+            Set<String> scopes) {
+
+        try {
+            Object authorities = accessors.getAuthorities().invoke(principal);
+            if (!(authorities instanceof Iterable<?> values)) {
+                return;
+            }
+
+            for (Object authority : values) {
+                if (authority == null) {
+                    continue;
+                }
+
+                Object value = accessors.getAuthority().invoke(authority);
+                if (value instanceof String name) {
+                    addAuthority(name, roles, scopes);
+                }
+            }
+        } catch (ReflectiveOperationException | LinkageError | 
SecurityException e) {
+            // An unavailable or unsupported authority representation fails 
closed.
+        }
+    }
+
+    private static Map<String, Object> readJwtClaims(
+            Principal principal, AuthenticationAccessors accessors) {
+
+        if (accessors.getTokenAttributes() == null) {
+            return null;
+        }
+
+        try {
+            Object value = accessors.getTokenAttributes().invoke(principal);
+            if (!(value instanceof Map<?, ?> values)) {
+                return null;
+            }
+
+            Map<String, Object> claims = new LinkedHashMap<>();
+            values.forEach((key, claim) -> {
+                if (key instanceof String name) {
+                    claims.put(name, claim);
+                }
+            });
+            return claims;
+        } catch (ReflectiveOperationException | LinkageError | 
SecurityException e) {
+            return null;
+        }
+    }
+
+    private static void addAuthority(String authority, Set<String> roles, 
Set<String> scopes) {
+        if (authority == null || authority.isBlank() || 
authority.startsWith("FACTOR_")) {
+            return;
+        }
+
+        if (authority.startsWith("SCOPE_")) {
+            addScope(scopes, authority.substring("SCOPE_".length()));
+        } else {
+            addRole(roles, authority);
+        }
+    }
+
+    private static void addRole(Set<String> roles, String role) {
+        if (role == null || role.isBlank() || role.startsWith("FACTOR_")) {
+            return;
+        }
+
+        String normalized = role.startsWith("ROLE_") ? 
role.substring("ROLE_".length()) : role;
+        if (!normalized.isBlank()) {
+            roles.add(normalized);
+        }
+    }
+
+    private static void addScopeClaim(Set<String> scopes, Object value) {
+        if (value instanceof String text) {
+            for (String scope : text.trim().split("\\s+")) {
+                addScope(scopes, scope);
+            }
+        } else if (value instanceof Iterable<?> values) {
+            for (Object scope : values) {
+                if (scope instanceof String name) {
+                    addScope(scopes, name);
+                }
+            }
+        }
+    }
+
+    private static void addScope(Set<String> scopes, String scope) {
+        if (scope != null && !scope.isBlank()) {
+            scopes.add(scope);
+        }
+    }
+
+    /**
+     * Mirrors the common claim shapes supported by the Camel Main MCP engine.
+     * The first available claim shape wins: roles, realm_access.roles, then 
groups.
+     */
+    private static void addClaimRoles(Map<String, Object> claims, Set<String> 
roles) {
+        Object value = claims.get("roles");
+
+        if (!(value instanceof Collection<?>)) {
+            Object realmAccess = claims.get("realm_access");
+            if (realmAccess instanceof Map<?, ?> realmMap) {
+                value = realmMap.get("roles");
+            }
+        }
+
+        if (!(value instanceof Collection<?>)) {
+            value = claims.get("groups");
+        }
+
+        if (value instanceof Collection<?> values) {
+            for (Object role : values) {
+                if (role instanceof String name) {
+                    addRole(roles, name);
+                }
+            }
+        }
+    }
+
+    private record AuthenticationAccessors(

Review Comment:
   Minor: the Conventions section of the repository `CLAUDE.md` says "Do NOT 
use Records or Lombok (unless already present in the file)". This file is new, 
so `AuthenticationAccessors` could be a small final class instead.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to