Camel Spring Boot

Mcp Server

The MCP Server starter exposes Camel routes registered via the ai-tool, ai-resource, and ai-prompt components as tools, resources (including URI templates), and prompts of a Model Context Protocol (MCP) server. The server is provided by Spring AI over streamable HTTP. No route is needed for the server itself: add the starter, tag the ai-tool routes to expose, and any MCP client (another Camel application, an IDE, a coding agent) can discover and use the published capabilities.

Tool semantics — tag-based opt-in (the untagged default pool is never exposed), flat-namespace collision refusal, per-call timeout and error sanitization — are owned by the runtime-agnostic camel-mcp-server-api bridge and are identical on every Camel runtime. Serving concerns (endpoint path, protocol, server identity) are owned by the Spring AI MCP server and configured via spring.ai.mcp.server.*; use spring.ai.mcp.server.protocol=STREAMABLE for the streamable HTTP transport.

Securing the MCP endpoint

The Spring AI MCP HTTP transport is authentication-agnostic. It does not authenticate requests or authorize tool, resource, and prompt operations. The MCP endpoint is served on the application’s HTTP port, so any client that can reach an unprotected endpoint can list and invoke the capabilities exposed by the server. Protecting the endpoint is the application’s responsibility.

Tools, resources, resource templates, and prompts use the same camel.mcp-server.tags selection. Nothing is exposed until tags are configured. The untagged default pools are never served; setting tags is not an authentication boundary.

OAuth 2.0 with Spring Security

For JWT bearer-token authentication, add Spring Security and its OAuth2 Resource Server starter. Let Spring Boot manage their versions:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Configure the authorization server issuer and select the Streamable HTTP transport:

spring.ai.mcp.server.protocol = STREAMABLE
spring.security.oauth2.resourceserver.jwt.issuer-uri = https://idp.example.com/issuer

# Application-specific properties used by this example; not Camel starter options.
# Canonical, externally visible URLs for this protected MCP resource.
mcp.security.resource-uri = https://mcp.example.com/mcp
mcp.security.resource-metadata-uri = https://mcp.example.com/.well-known/oauth-protected-resource/mcp

The following example protects the MCP endpoint and publishes OAuth 2.0 Protected Resource Metadata using the Spring Security 7 API. The metadata endpoint must be included in the security filter chain and permitted without 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.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class McpSecurityConfiguration {

    @Bean
    SecurityFilterChain mcpSecurity(
            HttpSecurity http,
            @Value("${mcp.security.resource-uri}") String resourceUri,
            @Value("${mcp.security.resource-metadata-uri}") String resourceMetadataUri)
            throws Exception {
        // Use operator-configured canonical URLs, never request-derived host information.
        BearerTokenAuthenticationEntryPoint bearerEntryPoint =
                new BearerTokenAuthenticationEntryPoint();
        bearerEntryPoint.setResourceMetadataParameterResolver(ignored -> resourceMetadataUri);

        return http
                .securityMatcher(
                        "/mcp", "/mcp/**",
                        "/.well-known/oauth-protected-resource",
                        "/.well-known/oauth-protected-resource/**")
                .csrf(csrf -> csrf.ignoringRequestMatchers("/mcp", "/mcp/**"))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/.well-known/oauth-protected-resource",
                                "/.well-known/oauth-protected-resource/**").permitAll()
                        .anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(Customizer.withDefaults())
                        .authenticationEntryPoint(bearerEntryPoint)
                        .protectedResourceMetadata(metadata -> metadata
                                .protectedResourceMetadataCustomizer(builder -> builder
                                        .resource(resourceUri)
                                        .authorizationServer("https://idp.example.com/issuer")
                                        .scope("mcp:access"))))
                .build();
    }
}

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

The resource value identifies the protected MCP endpoint. The metadata URL identifies the document that describes that resource; they are different values and both must be configured.

Both values must be canonical externally visible URLs. For deployments behind a reverse proxy, configure the public URLs used by MCP clients. Do not derive either value from the incoming request URL or from Host, Forwarded, or X-Forwarded-* headers. Such request headers must not define the protected resource’s identity. Configure forwarded-header processing separately and only when the proxy boundary is explicitly trusted.

The scope entry advertises a scope supported by this resource. It does not grant or enforce that scope by itself. To require the advertised scope for MCP requests, replace .anyRequest().authenticated() with:

.anyRequest().hasAuthority("SCOPE_mcp:access")

With Spring Security’s default JWT authority conversion, the corresponding scope must be present in the token. Applications with a custom JWT authority converter should use the authority names produced by that converter.

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.

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 from the authorities supplied by Spring Security’s configured authentication provider or JWT authority converter: the ROLE_ prefix is removed, FACTOR_* authorities are ignored, and SCOPE_* authorities become OAuth scopes. For JWT and opaque bearer-token authentication, the token subject and raw attributes are also propagated through McpToolCallContext as OAuth data. Raw claims such as roles, realm_access.roles, and groups are not promoted to Camel security roles. This preserves the application’s Spring Security authority-conversion policy. When claim-derived roles are required, configure the application’s JWT authority converter to grant the corresponding Spring authorities. The resulting Camel role names are unprefixed, for example MCP_ADMIN rather than ROLE_MCP_ADMIN.

A network policy that keeps the application port off untrusted networks is another useful layer of protection.

See the camel-mcp-server component documentation for the trust boundary this sits in: external MCP clients are untrusted senders under the Camel security model.

Maven coordinates

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-mcp-server-starter</artifactId>
</dependency>

Usage

Define tools as regular ai-tool routes and give them tags:

from("ai-tool:query_db?tags=crm&description=Query customer database"
     + "&parameter.customerId=string&parameter.customerId.required=true")
    .to("jdbc:dataSource");

or in YAML DSL:

- route:
    from:
      uri: "ai-tool:send_email"
      parameters:
        description: "Send email notification"
        tags: "notify"
        parameter.to: string
        parameter.to.description: "Recipient address"
        parameter.to.required: "true"
        parameter.subject: string
        parameter.priority: string
        parameter.priority.enum: "low,normal,high"
      steps:
        - to: "smtp://mail.example.com"

Tool parameters are declared with the parameter.NAME options: the value is the JSON type (string, integer, number, boolean), and the parameter.NAME.description, parameter.NAME.required and parameter.NAME.enum options refine the generated JSON Schema. Arguments arrive as message headers in the route (${header.customerId}).

Select the tags to expose in application.properties:

camel.mcp-server.tags = crm,notify

# per-call tool execution timeout (milliseconds, default 20000)
camel.mcp-server.tool-timeout = 10000
# per-read resource execution timeout (milliseconds, default 20000)
camel.mcp-server.resource-timeout = 10000
# per-request prompt execution timeout (milliseconds, default 20000)
camel.mcp-server.prompt-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:

from("ai-resource:app_config?resourceUri=camel:///config/app.json"
     + "&tags=crm&description=Application configuration&mimeType=application/json")
    .setBody(constant("{\"env\":\"production\"}"));

A resource template can expose resources selected by URI path variables:

from("ai-resource:customer_template?uriTemplate=camel:///customers/{customerId}"
     + "&tags=crm&description=Customer selected by id&mimeType=application/json")
    .process(exchange -> {
        String customerId = exchange.getMessage().getHeader(
                "CamelAiResourceTemplateVariable.customerId", String.class);

        // Validate the identifier against application policy before using it.
        if (customerId == null || !customerId.matches("[A-Za-z0-9-]{1,64}")) {
            throw new IllegalArgumentException("Invalid customer identifier");
        }

        exchange.getMessage().setBody("{\"customerId\":\"" + customerId + "\"}");
    });

A route declares either resourceUri for a fixed resource or uriTemplate for a resource template. Template variables are client input: validate them before using them in filesystem paths, database queries, authorization decisions, or downstream requests. Do not treat a syntactically valid URI variable as proof that the caller may access the referenced data.

Resources and resource templates are selected using the same camel.mcp-server.tags setting as tools. Their registration follows the Camel route lifecycle.

Prompts

Expose a prompt with an ai-prompt route. Prompt arguments are strings and arrive as message headers:

from("ai-prompt:greeting?tags=crm&description=Say hello&title=Greeting"
     + "&argument.name.description=Who to greet&argument.name.required=true")
    .setBody(simple("Hello ${header.name}"));

A string route result becomes one user message. For a multi-message result, return a list containing strings and/or maps with role and content fields. The supported roles are user and assistant. Content may be plain text or an MCP content block:

from("ai-prompt:multi_turn?tags=crm&description=Return a user and assistant message")
    .setBody(constant(List.of(
        "Plain user message",
        Map.of("role", "assistant", "content", "Assistant reply"))));

Prompt routes follow the same tag selection and route lifecycle rules. Content assembled from external systems, including resource content and prompt messages, must be treated as untrusted data. It may contain prompt injection instructions; do not grant such content authority over system instructions, tool permissions, or application security policy.

To advertise resource and prompt capabilities and their list-change notifications, configure the corresponding Spring AI server properties:

spring.ai.mcp.server.capabilities.resource = true
spring.ai.mcp.server.capabilities.prompt = true
spring.ai.mcp.server.resource-change-notification = true
spring.ai.mcp.server.prompt-change-notification = true

Origin validation

Camel’s principal-aware Streamable HTTP provider is selected only when spring.ai.mcp.server.protocol=STREAMABLE and the Camel transport activation condition is satisfied:

  • 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.

  • 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 endpoints but also wants Camel’s Origin validation.

  • Set camel.mcp-server.transport-enabled=false to keep Spring AI’s default provider even when Camel tags are configured. The Camel bridge remains enabled, but the selected provider does not automatically install Camel’s Origin validator or caller-context extractor.

  • When no tags are configured and transport-enabled is unset, Spring AI’s default provider is retained. Applications that expose only Spring-defined MCP capabilities therefore do not acquire Camel’s loopback-only Origin policy as a side effect of adding the starter.

When Camel’s provider is selected, it validates the Origin header on every MCP Streamable HTTP request, including POST, the SSE GET, and DELETE:

  • A request without an Origin header is accepted. Process-based MCP clients commonly omit this header.

  • A request with an allowed origin is accepted. Any other origin is rejected with HTTP 403 before it reaches an MCP operation.

  • When camel.mcp-server.allowed-origins is not set, only loopback origins are allowed: localhost, 127.0.0.1, and [::1], using HTTP or HTTPS and any port.

  • When configured, the property replaces the loopback defaults. Each entry is an exact origin or uses :* to match any port.

For example, to allow a remote browser client and local development tools:

camel.mcp-server.allowed-origins = https://app.example.com, http://localhost:*

Add the loopback origins explicitly to the list when you still need local browser-based clients. Scheme and host matching is case-insensitive, and default HTTP and HTTPS ports are normalized.

If Camel tags or Origin settings are configured while the Spring AI protocol is unset or uses SSE, the Camel Streamable HTTP provider is not installed. The starter logs a warning because Origin validation and caller-context extraction are not active in that configuration. Select spring.ai.mcp.server.protocol=STREAMABLE when those protections are required.

With the Spring AI 2.0.2 WebMVC transport, an Origin rejection currently returns HTTP 403 with a plain-text Invalid Origin header response body. The rejection occurs before MCP request dispatch, but this response body is not the JSON-RPC error envelope returned by the Camel Main HTTP engine. Treat the HTTP status and pre-dispatch rejection as the enforced transport security boundary; the response-envelope difference remains a runtime parity limitation of the current Spring AI WebMVC transport.

Origin validation is independent of CORS. Configure CORS separately when a browser client needs cross-origin response access; CORS response headers do not replace the server-side Origin check.

If the MCP server should only be reachable from the local machine, also bind the Spring Boot HTTP server to the loopback interface:

server.address = 127.0.0.1

An application-provided WebMvcStreamableServerTransportProvider takes precedence over Camel’s auto-configured transport. It does not automatically inherit Camel’s Origin validator or authenticated-caller context extractor. Both helpers are public so a custom provider can reuse Camel’s exact origin normalization, loopback defaults, and caller-context representation.

For example:

.securityValidator(CamelMcpServerTransportAutoConfiguration.createOriginValidator(
        "https://app.example.com,http://localhost:*"))
.contextExtractor(request -> SpringAiMcpTransportContext.extract(
        request, Map.of("application", "my-app")))

Pass null to createOriginValidator to use CamelMcpServerTransportAutoConfiguration.DEFAULT_ALLOWED_ORIGINS. The context-extractor overload composes application-owned entries with Camel’s authenticated caller entry; the reserved Camel context key cannot be overwritten. The extractor does not authenticate the request. The custom 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.

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 endpoint at /mcp.

Serving concerns are configured on the Spring AI MCP server — see the Spring AI MCP server documentation for the full list of spring.ai.mcp.server.* options. For example:

spring.ai.mcp.server.protocol = STREAMABLE
spring.ai.mcp.server.name = my-integration-app
spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp

Connecting MCP clients

Any MCP client can connect over streamable HTTP. Another Camel integration can consume the tools with the camel-openai MCP client and automatic tool execution:

from("direct:agent")
    .to("openai:chat-completion"
        + "?model={{llm.model}}"
        + "&autoToolExecution=true"
        + "&mcpServer.myCamelTools.transportType=streamableHttp"
        + "&mcpServer.myCamelTools.url=http://localhost:8080/mcp");

A coding agent or IDE is configured with the same URL, e.g. in an mcp.json-style client configuration:

{
  "mcpServers": {
    "my-integration-app": {
      "type": "http",
      "url": "http://localhost:8080/mcp"
    }
  }
}

Serving over stdio

Out of the box the tools are served over streamable HTTP: the starter brings in spring-ai-starter-mcp-server-webmvc. MCP clients that launch the server as a subprocess speak over stdin/stdout instead, which Spring AI serves with the plain spring-ai-starter-mcp-server. Swap the transport starter:

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-mcp-server-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server</artifactId>
    <version>2.0.0</version>
</dependency>

and enable the stdio transport:

spring.ai.mcp.server.stdio = true
spring.main.web-application-type = none
spring.main.banner-mode = off

# stdout carries the MCP protocol, so nothing else may be written to it
logging.threshold.console = OFF
logging.file.name = my-integration-app.log

Because stdout carries the MCP protocol, the application must not run as a web application, the banner has to be switched off and console logging has to be turned off — writing the log to a file instead. Leaving console logging on corrupts the protocol stream, as the Spring Boot startup log is then interleaved with the JSON-RPC messages.

A stdio server is launched by the client instead of being connected to over a URL:

{
  "mcpServers": {
    "my-integration-app": {
      "command": "java",
      "args": ["-jar", "/path/to/my-integration-app-1.0.0.jar"]
    }
  }
}

See the Spring AI MCP Server Boot Starter documentation for the transport options and the full list of spring.ai.mcp.server.* properties. On Quarkus the equivalent setup is described in the quarkus-mcp-server stdio guide.

Mixing with Spring-defined tools

Camel tools coexist with tools defined natively in Spring AI — both are served by the same MCP server and appear in the same tools/list. For example, a @McpTool-annotated bean:

@Component
public class CalculatorTools {

    @McpTool(name = "add_numbers", description = "Add two numbers")
    public String add(
            @McpToolParam(description = "First addend", required = true) int a,
            @McpToolParam(description = "Second addend", required = true) int b) {
        return String.valueOf(a + b);
    }
}

is exposed alongside the ai-tool routes. Spring-defined tools are registered when the server is created; Camel tools are added and removed dynamically with the route lifecycle. Choose distinct tool names — MCP has a flat tool namespace.

Dynamic tools

The exposed tool list follows the route lifecycle: stopping or suspending an ai-tool route removes its tool, starting or resuming it publishes the tool again, and connected clients are notified via notifications/tools/list_changed:

camelContext.getRouteController().stopRoute("query-db-route");   // tool disappears
camelContext.getRouteController().startRoute("query-db-route");  // tool is back

Error handling

Results returned to MCP clients are sanitized by the bridge: a route exception produces an isError result with the generic message Tool execution failed (the cause is logged server-side and never sent to the client), a missing or invalid argument returns the validation message, and a call exceeding camel.mcp-server.tool-timeout returns Tool execution timed out while the route keeps running until it completes on its own. Resource reads and prompt requests use the corresponding camel.mcp-server.resource-timeout and camel.mcp-server.prompt-timeout settings, each with a default of 20000 milliseconds.

On Camel Main and Camel JBang the equivalent setup is the camel-mcp-server module with the camel.server.mcp-* options; on Quarkus it is the camel-quarkus-mcp-server extension.

Spring Boot Auto-Configuration

The starter supports 7 options, which are listed below.

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