Camel Components

AI Tool

Since Camel 4.22

Only consumer is supported

The AI Tool component exposes Camel routes as tools that AI models can call. Any AI producer component (such as LangChain4j Agent or Spring AI Chat) discovers registered tools using tag-based filtering.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ai-tool</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

ai-tool:toolName[?options]

Where toolName is the name the LLM sees and uses to invoke the tool.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The AI Tool component supports the following options which are listed below.

Name Description Default Type

argSchema (consumer)

Raw JSON Schema for tool input parameters. Supports inline JSON and resource references (classpath:, file:, resource:). Mutually exclusive with the parameter multi-value options. Use for nested objects, arrays, oneOf, and other complex schemas.

String

argumentsAsBody (consumer)

Whether to populate the message body with the tool arguments as a JSON string, excluding undeclared arguments and reserved names. Declared argument headers remain available. When disabled, the message body is left unchanged.

false

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

configuration (consumer)

The component configuration.

AiToolConfiguration

description (consumer)

Human-readable description of what this tool does. Passed verbatim to the LLM; be precise and action-oriented. When omitted, defaults to the tool name.

String

destructiveHint (consumer)

MCP hint that the tool may perform destructive or irreversible updates. Advisory for MCP clients; not enforced by Camel.

Boolean

idempotentHint (consumer)

MCP hint that repeating the tool call with the same arguments has no additional effect. Advisory for MCP clients; not enforced by Camel.

Boolean

openWorldHint (consumer)

MCP hint that the tool interacts with external systems outside the application’s control. Advisory for MCP clients; not enforced by Camel.

Boolean

outputParameters (consumer)

Tool output schema fields. Format: outputParameter.NAME=TYPE, outputParameter.NAME.description=TEXT. Supported types: string, integer, number, boolean. Mutually exclusive with outputSchema. This is a multi-value option with prefix: outputParameter.

Map

outputSchema (consumer)

Raw JSON Schema describing the tool’s structured output. Supports inline JSON and resource references (classpath:, file:, resource:). Mutually exclusive with the outputParameter multi-value options. When declared, the route body is parsed as JSON and exposed as structured content to MCP clients.

String

parameters (consumer)

Tool input parameters. Format: parameter.NAME=TYPE, parameter.NAME.description=TEXT, parameter.NAME.required=true or false, parameter.NAME.enum=val1,val2. Supported types: string, integer, number, boolean. Mutually exclusive with argSchema. This is a multi-value option with prefix: parameter.

Map

readOnlyHint (consumer)

MCP hint that the tool only reads data and does not modify state. Advisory for MCP clients; not enforced by Camel.

Boolean

returnDirect (consumer)

When true, AI producers that support agentic tool loops (such as camel-openai) return this tool’s result directly to the caller without sending it back to the model. Also published as an MCP tool annotation when the tool is exposed via camel-mcp-server.

false

Boolean

searchable (consumer)

When true, this route tool is eligible for tool search and is omitted from the initial model request while the producer has tool search enabled. When false, the tool stays directly visible to the model. Searchability is a visibility policy, not an authorization policy, and has no effect when tool search is disabled.

false

boolean

tags (consumer)

Comma-separated list of tags used to group tools. Producers filter the registry by these tags to select which tools to expose to the LLM. When omitted, the tool goes into a default pool available to all producers.

String

title (consumer)

Optional display title for MCP tool listings. Advisory hint for MCP clients only.

String

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

allowedRoles (security)

Comma-separated list of the roles a caller needs to call the tool, for example finance,controlling. Any one of them is enough unless allRolesRequired is set. The roles are checked before the route runs, against the caller’s roles in the exchange property CamelAiToolSecurityPrincipalRoles: a call without that property is refused. A value that is set but names no role refuses every call. Set it on the component as the default of every tool route, or per endpoint to replace it.

String

allRolesRequired (security)

Whether the caller needs all the roles in allowedRoles, rather than any one of them. Has no effect when allowedRoles is not set.

false

boolean

authorizationPolicy (security)

Reference to an org.apache.camel.spi.AuthorizationPolicy used to authorize tool calls before the route runs. Set it on the component to guard every tool route by construction, or per endpoint to override. The policy authorizes on trustworthy input only: the tool name comes from the route (never from model output), and the caller identity is carried as an exchange property set before the agent ran (for example by camel-spiffe or camel-keycloak), which the model cannot set. Authorize on exchange properties or validated tokens only, never on message headers (on a tool route the headers carry the model-controlled tool arguments). A denied call surfaces to the model as a short refusal rather than a stack trace.

AuthorizationPolicy

Endpoint Options

The AI Tool endpoint is configured using URI syntax:

ai-tool:toolName

With the following path and query parameters:

Path Parameters

Name Description Default Type

toolName (consumer)

Required The tool name. This is the name the LLM sees and uses to invoke the tool.

String

Query Parameters

Name Description Default Type

argSchema (consumer)

Raw JSON Schema for tool input parameters. Supports inline JSON and resource references (classpath:, file:, resource:). Mutually exclusive with the parameter multi-value options. Use for nested objects, arrays, oneOf, and other complex schemas.

String

argumentsAsBody (consumer)

Whether to populate the message body with the tool arguments as a JSON string, excluding undeclared arguments and reserved names. Declared argument headers remain available. When disabled, the message body is left unchanged.

false

boolean

description (consumer)

Human-readable description of what this tool does. Passed verbatim to the LLM; be precise and action-oriented. When omitted, defaults to the tool name.

String

destructiveHint (consumer)

MCP hint that the tool may perform destructive or irreversible updates. Advisory for MCP clients; not enforced by Camel.

Boolean

idempotentHint (consumer)

MCP hint that repeating the tool call with the same arguments has no additional effect. Advisory for MCP clients; not enforced by Camel.

Boolean

openWorldHint (consumer)

MCP hint that the tool interacts with external systems outside the application’s control. Advisory for MCP clients; not enforced by Camel.

Boolean

outputParameters (consumer)

Tool output schema fields. Format: outputParameter.NAME=TYPE, outputParameter.NAME.description=TEXT. Supported types: string, integer, number, boolean. Mutually exclusive with outputSchema. This is a multi-value option with prefix: outputParameter.

Map

outputSchema (consumer)

Raw JSON Schema describing the tool’s structured output. Supports inline JSON and resource references (classpath:, file:, resource:). Mutually exclusive with the outputParameter multi-value options. When declared, the route body is parsed as JSON and exposed as structured content to MCP clients.

String

parameters (consumer)

Tool input parameters. Format: parameter.NAME=TYPE, parameter.NAME.description=TEXT, parameter.NAME.required=true or false, parameter.NAME.enum=val1,val2. Supported types: string, integer, number, boolean. Mutually exclusive with argSchema. This is a multi-value option with prefix: parameter.

Map

readOnlyHint (consumer)

MCP hint that the tool only reads data and does not modify state. Advisory for MCP clients; not enforced by Camel.

Boolean

returnDirect (consumer)

When true, AI producers that support agentic tool loops (such as camel-openai) return this tool’s result directly to the caller without sending it back to the model. Also published as an MCP tool annotation when the tool is exposed via camel-mcp-server.

false

Boolean

searchable (consumer)

When true, this route tool is eligible for tool search and is omitted from the initial model request while the producer has tool search enabled. When false, the tool stays directly visible to the model. Searchability is a visibility policy, not an authorization policy, and has no effect when tool search is disabled.

false

boolean

tags (consumer)

Comma-separated list of tags used to group tools. Producers filter the registry by these tags to select which tools to expose to the LLM. When omitted, the tool goes into a default pool available to all producers.

String

title (consumer)

Optional display title for MCP tool listings. Advisory hint for MCP clients only.

String

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

allowedRoles (security)

Comma-separated list of the roles a caller needs to call the tool, for example finance,controlling. Any one of them is enough unless allRolesRequired is set. The roles are checked before the route runs, against the caller’s roles in the exchange property CamelAiToolSecurityPrincipalRoles: a call without that property is refused. A value that is set but names no role refuses every call. Set it on the component as the default of every tool route, or per endpoint to replace it.

String

allRolesRequired (security)

Whether the caller needs all the roles in allowedRoles, rather than any one of them. Has no effect when allowedRoles is not set.

false

boolean

authorizationPolicy (security)

Reference to an org.apache.camel.spi.AuthorizationPolicy used to authorize tool calls before the route runs. Set it on the component to guard every tool route by construction, or per endpoint to override. The policy authorizes on trustworthy input only: the tool name comes from the route (never from model output), and the caller identity is carried as an exchange property set before the agent ran (for example by camel-spiffe or camel-keycloak), which the model cannot set. Authorize on exchange properties or validated tokens only, never on message headers (on a tool route the headers carry the model-controlled tool arguments). A denied call surfaces to the model as a short refusal rather than a stack trace.

AuthorizationPolicy

Message Headers

The AI Tool component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelAiToolCallId (consumer)

Constant: TOOL_CALL_ID

The tool invocation identifier supplied by the calling framework. Absent when the framework does not supply one.

String

CamelAiToolConversationId (consumer)

Constant: CONVERSATION_ID

The conversation identifier supplied by the calling framework. Absent when the framework does not supply one.

String

Message Body

The message body at each side of the AI Tool component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

null

No body: each argument of the tool call is a header named as its parameter, a Map or a List for a nested JSON value. Undeclared arguments and names starting with camel are dropped.

Consumer reply

any

The tool result, as text: the body converted to a String, so a Map, a List or a POJO is sent as its toString(): marshal it to JSON first. No body gives No result. With outputSchema or outputParameter.NAME options the body must be JSON: a JSON String, a Map, a List, a number or a boolean, and bytes, a stream or another object fail the call.

Not known when outputSchema or outputParameters is set.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Basic Tool Definition

  • Java

  • XML

  • YAML

from("ai-tool:weather?tags=weather&description=Get current weather for a city" +
    "&parameter.city=string&parameter.city.description=The city name")
    .to("bean:weatherService");
<route>
  <from uri="ai-tool:weather?tags=weather&amp;description=Get current weather for a city&amp;parameter.city=string&amp;parameter.city.description=The city name"/>
  <to uri="bean:weatherService"/>
</route>
- route:
    from:
      uri: ai-tool:weather
      parameters:
        tags: weather
        description: "Get current weather for a city"
        parameter.city: string
        parameter.city.description: "The city name"
      steps:
        - to:
            uri: bean:weatherService

Tool with Multiple Parameters

  • Java

  • XML

  • YAML

from("ai-tool:calculator?tags=math" +
    "&description=Calculate a math expression" +
    "&parameter.a=number" +
    "&parameter.a.description=First operand" +
    "&parameter.a.required=true" +
    "&parameter.b=number" +
    "&parameter.b.description=Second operand" +
    "&parameter.b.required=true" +
    "&parameter.operation=string" +
    "&parameter.operation.description=The operation to perform" +
    "&parameter.operation.enum=add,subtract,multiply,divide")
    .to("direct:calculator");
<route>
  <from uri="ai-tool:calculator?tags=math&amp;description=Calculate a math expression&amp;parameter.a=number&amp;parameter.a.description=First operand&amp;parameter.a.required=true&amp;parameter.b=number&amp;parameter.b.description=Second operand&amp;parameter.b.required=true&amp;parameter.operation=string&amp;parameter.operation.description=The operation to perform&amp;parameter.operation.enum=add,subtract,multiply,divide"/>
  <to uri="direct:calculator"/>
</route>
- route:
    from:
      uri: ai-tool:calculator
      parameters:
        tags: math
        description: "Calculate a math expression"
        parameter.a: number
        parameter.a.description: "First operand"
        parameter.a.required: true
        parameter.b: number
        parameter.b.description: "Second operand"
        parameter.b.required: true
        parameter.operation: string
        parameter.operation.description: "The operation to perform"
        parameter.operation.enum: "add,subtract,multiply,divide"
      steps:
        - to:
            uri: direct:calculator

Complex Parameters with argSchema

Use argSchema when the flat parameter.* syntax is not expressive enough for nested objects, arrays, or other advanced JSON Schema constructs. argSchema is mutually exclusive with parameter.*.

  • YAML

- route:
    from:
      uri: ai-tool:createOrder
      parameters:
        tags: orders
        description: "Create an order"
        argSchema: |
          {
            "type": "object",
            "properties": {
              "customer": {
                "type": "object",
                "properties": {
                  "id": { "type": "string" }
                },
                "required": ["id"]
              },
              "items": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "sku": { "type": "string" },
                    "qty": { "type": "integer" }
                  }
                }
              }
            },
            "required": ["customer", "items"],
            "additionalProperties": false
          }
      steps:
        - to:
            uri: direct:createOrder

Top-level schema properties are exposed as exchange headers. Nested values are passed as Map or List objects.

argSchema also supports Camel resource references such as classpath:schemas/create-order.json.

The root schema must be a JSON Schema object with a top-level properties map. Camel always allowlists top-level property names when invoking the tool route, even if the schema sets additionalProperties: true. Nested fields are not flattened into headers; only top-level properties become exchange headers (Map/List/primitive values).

Structured Tool Output (outputSchema)

MCP tools can declare an outputSchema and return structuredContent (typed JSON) so clients parse tool results reliably instead of re-interpreting free text. Use outputParameter.* for flat field definitions or outputSchema for raw JSON Schema (mirroring the input-side parameter.* / argSchema pattern). The two options are mutually exclusive.

When an output schema is declared, the route body must be JSON (a JSON string, Map, or List). Camel parses it into structured content and forwards it through the MCP bridge as CallToolResult.structuredContent. The text representation remains available for LLM adapters (LangChain4j, Spring AI) that consume string tool results.

  • Java

  • YAML

from("ai-tool:getWeather?tags=weather&description=Get weather"
     + "&outputSchema=classpath:schemas/weather-result.json")
    .process(exchange -> exchange.getMessage().setBody(
        "{\"temperature\":21.5,\"unit\":\"celsius\"}"));
- route:
    from:
      uri: ai-tool:getWeather
      parameters:
        tags: weather
        description: "Get weather"
        outputParameter.temperature: number
        outputParameter.unit: string
      steps:
        - setBody:
            expression:
              constant:
                expression: '{"temperature":21.5,"unit":"celsius"}'

Flat outputParameter.* options use the same sub-option syntax as input parameter.*:

  • outputParameter.NAME=TYPE — field type (string, integer, number, boolean)

  • outputParameter.NAME.description=TEXT — field description in the generated JSON Schema

  • outputParameter.NAME.required=true — marks the field as required in the output schema

  • outputParameter.NAME.enum=val1,val2 — restricts allowed values

outputSchema supports Camel resource references such as classpath:schemas/weather-result.json.

MCP Tool Annotation Hints

When exposing ai-tool routes through the MCP Server component, you can declare optional behavioral hints aligned with the MCP specification (ToolAnnotations). MCP clients may use these hints for per-tool policy (for example auto-approving read-only tools or requiring confirmation before destructive ones).

These hints are advisory only — Camel does not enforce them. MCP clients must treat them as untrusted UX metadata (per the MCP specification), not as authorization. Inaccurate hints can mislead client-side confirmation flows.

  • Java

  • YAML

from("ai-tool:delete_order?tags=orders&description=Delete an order"
     + "&title=Delete order"
     + "&readOnlyHint=false"
     + "&destructiveHint=true"
     + "&idempotentHint=false"
     + "&openWorldHint=true")
    .to("direct:deleteOrder");
- route:
    from:
      uri: ai-tool:delete_order
      parameters:
        tags: orders
        description: "Delete an order"
        title: "Delete order"
        readOnlyHint: false
        destructiveHint: true
        idempotentHint: false
        openWorldHint: true
      steps:
        - to:
            uri: direct:deleteOrder

Supported options: title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint, and returnDirect. When a hint is omitted, it is not published; MCP clients then apply their own defaults (for example assuming destructive/open-world unless told otherwise). The returnDirect hint is also honoured by AI producers such as OpenAI when route tools are exposed via the tags option.

The title option maps to the MCP tool’s top-level title field (not ToolAnnotations.title).

Tool Arguments in the Body

By default, tool arguments are exposed as individual headers and the message body is left unchanged. Set argumentsAsBody=true to also populate the body with a JSON string containing the tool-call arguments. This is useful when mapping a complete JSON document, for example with Kaoto Data Mapper.

- route:
    from:
      uri: ai-tool:place_order
      parameters:
        description: Place a merchandise order
        argSchema: classpath:place-order.args.schema.json
        argumentsAsBody: true
      steps:
        - to:
            uri: direct:mapOrder

For a tool call with a customer name and two items, direct:mapOrder receives this JSON-string body:

{
  "customerName": "Alice",
  "items": [
    { "sku": "TSHIRT", "quantity": 2 },
    { "sku": "MUG", "quantity": 1 }
  ]
}

Nested objects, arrays and JSON value types are preserved. A call with no arguments produces {}. The body and individual argument headers include only declared arguments, after the same allowlist filtering. Camel logs a warning for each undeclared argument. Reserved names starting with camel or org.apache.camel. (case-insensitive) are excluded from both the body and argument headers. Missing required arguments still reject an invocation before the tool route runs. Required arguments are checked after reserved names are removed, so a required argument with a reserved name rejects the call even if the model supplied it. Rename such arguments to use names outside the reserved namespace. This option does not add full JSON Schema validation.

Invocation Identifiers

Tool routes receive CamelAiToolCallId and CamelAiToolConversationId when the calling adapter can supply them. These headers are populated independently of argumentsAsBody. An unavailable identifier is omitted rather than generated.

  • LangChain4j Agent supplies the tool execution request ID and the memory ID (converted to a string) as the conversation ID when the agent uses memory. Agents without memory omit the conversation header, including the framework’s default memory ID.

  • OpenAI supplies the tool-call ID. The Responses API also supplies its resolved conversation ID (CamelOpenAIConversationId or the conversationId option); chat-completion callbacks omit it.

  • Spring AI Chat supplies the CamelSpringAiChatConversationId from the calling exchange. Its tool callback does not supply a call ID.

  • MCP server tool callbacks currently do not propagate these identifiers.

For example, use ${header.CamelAiToolCallId} to correlate route processing with a particular tool invocation. Several calls in the same conversation can share CamelAiToolConversationId while having different call IDs.

Tag-Based Discovery

Tags group tools so that AI producers can select relevant subsets.

  • Java

  • XML

  • YAML

// Define tools with tags
from("ai-tool:weather?tags=weather,external-api&description=Get weather for a city" +
    "&parameter.city=string&parameter.city.description=The city name")
    .to("bean:weatherService");

from("ai-tool:lookupUser?tags=users&description=Look up a user by ID" +
    "&parameter.id=integer&parameter.id.description=The user ID&parameter.id.required=true")
    .to("bean:userService?method=findById(${header.id})");
<!-- Define tools with tags -->
<route>
  <from uri="ai-tool:weather?tags=weather,external-api&amp;description=Get weather for a city&amp;parameter.city=string&amp;parameter.city.description=The city name"/>
  <to uri="bean:weatherService"/>
</route>

<route>
  <from uri="ai-tool:lookupUser?tags=users&amp;description=Look up a user by ID&amp;parameter.id=integer&amp;parameter.id.description=The user ID&amp;parameter.id.required=true"/>
  <to uri="bean:userService?method=findById(${header.id})"/>
</route>
# Define tools with tags
- route:
    from:
      uri: ai-tool:weather
      parameters:
        tags: weather,external-api
        description: "Get weather for a city"
        parameter.city: string
        parameter.city.description: "The city name"
      steps:
        - to:
            uri: bean:weatherService

- route:
    from:
      uri: ai-tool:lookupUser
      parameters:
        tags: users
        description: "Look up a user by ID"
        parameter.id: integer
        parameter.id.description: "The user ID"
        parameter.id.required: true
      steps:
        - to:
            uri: "bean:userService?method=findById(${header.id})"

The calling exchange

Each tool invocation runs on a copy of the calling exchange — the exchange that drives the agent (the langchain4j-agent, openai or spring-ai-chat producer). The context the caller set before the agent ran is carried onto the tool route:

  • exchange properties — most importantly an authenticated caller’s identity kept as a property, so a tool route can be guarded on it (for example exchangeProperty.subject) and the model cannot forge it;

  • exchange variables.

The message itself is clean: the tool route receives only its own arguments (supplied by the model and placed on the message as headers), not the caller’s body or inbound headers, and a tool that sets no body returns No result rather than echoing the caller’s body back to the model. Any change the tool makes — to its message, body or exception — is isolated to the copy and does not leak back into the calling exchange.

The tool exchange runs in its own unit of work and with its own exchange id; it does not share the caller’s. So each tool call is independent: the tool route’s own onCompletion, error handler and useOriginalMessage() apply to the tool call rather than to the caller, parallel tool calls in a batch get distinct exchange ids, and an error handler cannot restore the caller’s message into the result.

All route-tool runtimes build the tool exchange the same way, so an authorization check on an exchange property behaves identically whether the agent loop is driven by camel-langchain4j-agent, camel-openai or camel-spring-ai-chat.

Authorizing tool calls

A tool call is a security boundary: an AI model decides, from its own output, which ai-tool route to invoke. Set an authorizationPolicy — a reference to an org.apache.camel.spi.AuthorizationPolicy bean — to authorize every call before the route runs. Set it on the component to guard every tool route by construction, or on a single endpoint to override.

When the rule is which roles the caller needs, the allowedRoles option states it on the endpoint and no policy bean is needed: see Authorizing by role below.

  • Java

  • YAML

// one policy guarding every ai-tool route
AiToolComponent ai = context.getComponent("ai-tool", AiToolComponent.class);
ai.getConfiguration().setAuthorizationPolicy(myAuthorizationPolicy);

from("ai-tool:transferFunds?tags=banking&description=Transfer funds")
    .to("bean:ledger");

// ...or override on a single endpoint
from("ai-tool:transferFunds?tags=banking&description=Transfer funds&authorizationPolicy=#myAuthorizationPolicy")
    .to("bean:ledger");
- route:
    from:
      uri: ai-tool:transferFunds
      parameters:
        tags: banking
        description: "Transfer funds"
        authorizationPolicy: "#myAuthorizationPolicy"
      steps:
        - to:
            uri: bean:ledger

The guard runs in front of the route: it wraps the route’s outer processor, so it executes before the route’s unit of work, tracing and error handling. A denied call (CamelAuthorizationException) is returned to the model as a short refusal it can relay — not as a tool result and not as a stack trace — regardless of the tool-execution error strategy. Because the guard runs in front of the route, a denial never enters the route’s unit of work, so it does not produce a route span. It is instead observable as described in Observing denials below.

The policy authorizes on trustworthy input only:

  • the tool name comes from the route (the tool’s id), never from model output;

  • the caller identity comes from an exchange property (or a validated token) set before the agent ran — for example by camel-spiffe or camel-keycloak. Authorize on properties or validated tokens only, never on message headers: on a tool route the headers carry the model-controlled tool arguments (and, on the langchain4j-agent path, the caller’s inbound HTTP headers), so a policy such as OPA with the default includeHeaders="*" would otherwise read attacker-influenced values.

Which runtimes carry the caller identity:

  • camel-langchain4j-agent, camel-openai and camel-spring-ai-chat all copy the calling exchange (see The calling exchange above), so the identity property reaches the tool route.

  • Over the MCP server the authenticated transport caller is carried onto the tool exchange as the CamelMcpSecurityPrincipal property (the raw transport principal — for the Vert.x streamable HTTP server, an io.vertx.ext.auth.User). Alongside it the server stamps a runtime-neutral view derived from that principal — CamelAiToolSecurityPrincipalName (a String) and CamelAiToolSecurityPrincipalRoles (a Collection<String>) — so a tool route or a policy can authorize on a stable name and roles without knowing the runtime type. Only the Vert.x streamable HTTP server (Camel Main / JBang) populates these today. There the name is the user subject (or the username/sub claim), and the roles come from the first of the authenticated token’s roles, Keycloak realm_access.roles, or groups claim that is an array (JWT/OIDC); a basic-auth caller (camel-main property-file auth) carries no roles in its principal, so CamelAiToolSecurityPrincipalRoles is not set for it. Each property is set only when the server could determine it, so treat a missing name or roles as unauthorized. The allowedRoles option checks CamelAiToolSecurityPrincipalRoles (see Authorizing by role below), so authorizing an MCP caller by role needs no code. Camel’s shipped identity/token policies (Keycloak, Spring Security, Shiro) do not consume these properties automatically yet, so any other rule over MCP, for example on the caller’s name or on a claim, still needs a policy (or route guard) that inspects CamelAiToolSecurityPrincipalName/CamelAiToolSecurityPrincipalRoles or the raw CamelMcpSecurityPrincipal.

Authorizing by role

Set allowedRoles on a tool to name the roles its caller needs, as a comma-separated list. The check needs no Java code. The caller needs one of the roles; with allRolesRequired=true the caller needs all of them. A role name is compared exactly.

  • Java

  • YAML

from("ai-tool:orderCosts?tags=erp&description=Costs of a production order&allowedRoles=finance,controlling")
    .to("bean:costs");

// ...or as the default of every ai-tool route, which an endpoint replaces with its own value
AiToolComponent ai = context.getComponent("ai-tool", AiToolComponent.class);
ai.getConfiguration().setAllowedRoles("finance,controlling");
- route:
    from:
      uri: ai-tool:orderCosts
      parameters:
        tags: erp
        description: "Costs of a production order"
        allowedRoles: finance,controlling
      steps:
        - to:
            uri: bean:costs

The caller’s roles are read only from the exchange property CamelAiToolSecurityPrincipalRoles (a Collection<String>). A role named in a message header or in a tool argument never counts: on a tool route the headers carry the tool arguments, which the model controls. A call without that property is refused.

  • Over the MCP server the server sets the property from the roles of the authenticated caller. That page says which claim of the token the roles are read from. A caller without roles, such as a basic-auth caller, is refused. Over stdio, or on an MCP server without authentication, no caller has roles, so a tool with allowedRoles refuses every call. The same holds on a runtime whose MCP engine does not set the property.

  • With camel-langchain4j-agent, camel-openai and camel-spring-ai-chat the calling route sets the same property before the agent runs, from the identity it has authenticated. The tool exchange is a copy of the calling exchange (see The calling exchange above), so the property reaches the tool route:

    from("platform-http:/assistant")
        // the roles of the caller this route has authenticated: here a bean reads them from the validated token
        .setProperty("CamelAiToolSecurityPrincipalRoles", method("callerIdentity", "roles"))
        .to("langchain4j-agent:assistant?agentConfiguration=#myConfig&tags=erp");

When a call is refused, the model gets the same short refusal as for a denial by an authorizationPolicy, and the denial is logged and published as described in Observing denials below. The log entry names the tool, the roles it asks for and, when the CamelAiToolSecurityPrincipalName property is set, the caller. The model is told none of this.

allowedRoles and authorizationPolicy can be set on the same tool, and then both must pass. The roles are checked first, and a call that fails them does not reach the policy. This combines a role with a rule that needs more than a role, for example a Cedar or OPA policy over attributes.

Set on the component, allowedRoles and allRolesRequired are the default of every tool route, and an endpoint’s own value replaces the component’s. An endpoint can therefore replace the component’s roles, but it cannot remove the check: a value that names no role, such as an empty one, refuses every call. The route still starts, and a WARN at its start names the tool. Only an option that is not set takes the component’s value; that includes an optional placeholder ({{?name}}) whose property is absent.

With a configuration bean

The options can also come from an AiToolConfiguration bean, given as the configuration option of the component or of an endpoint. The bean combines with the options set beside it, so authorizationPolicy and allowedRoles apply whether they are set as an option or in the bean:

  • On the component, an option set on the component wins over the value of the bean, in whatever order the two are set. An option that is not set takes the value of the bean.

  • On an endpoint, an option set on the endpoint wins over the value of the bean. An option that neither the endpoint nor the bean sets takes the value of the component. An endpoint with configuration=#toolDefaults is therefore still guarded by the authorizationPolicy and the allowedRoles of the component, unless the bean or the endpoint sets its own.

camel.component.ai-tool.configuration = #toolDefaults
# kept, and applied to every tool route
camel.component.ai-tool.authorization-policy = #myAuthorizationPolicy

Observing denials

Because the guard runs in front of the route, a denied call is caught before the route’s unit of work and so fires no exchange-lifecycle event or route span. Every denial is instead:

  • logged at WARN, and

  • published as an org.apache.camel.component.ai.tool.AiToolAuthorizationDeniedEvent — an org.apache.camel.ai.AiEvent.ToolCallDeniedEvent (a CamelEvent of type Ai) carrying the denied tool name, the tool exchange (for correlation), and the CamelAuthorizationException that refused the call. For a call that the allowedRoles check refused, its getPolicyId() returns allowedRoles.

Register an EventNotifier to count, log or alert on denials — for example to drive a micrometer counter — without changing what the model sees (still the short refusal). Match on the shared AiEvent.ToolCallDeniedEvent interface so the notifier does not depend on this component:

context.getManagementStrategy().addEventNotifier(new EventNotifierSupport() {
    @Override
    public void notify(CamelEvent event) {
        if (event instanceof AiEvent.ToolCallDeniedEvent denied) {
            meterRegistry.counter("ai.tool.authorization.denied", "tool", denied.getToolName()).increment();
        }
    }
});

The event is emitted best-effort: when no EventNotifier is registered nothing is published, and a failure to notify never affects the refusal returned to the model.

Tool search visibility

searchable controls whether a route tool is sent to the model immediately or only after a producer with tool search enabled finds it. The default is false, so the tool stays directly visible. searchable=true omits the tool from the initial model request and makes it eligible for search together with remote MCP tools.

Searchability is a visibility policy. It does not authorize the call. The allowedRoles and the authorizationPolicy of the tool are still applied when the model invokes it. With tool search disabled on the producer, searchable has no effect and the tool is exposed as before.

- route:
    from:
      uri: ai-tool:invoice
      parameters:
        tags: erp
        searchable: true
        description: "Look up an invoice by id"
        parameter.id: string
        parameter.id.required: true
      steps:
        - to:
            uri: bean:invoiceService

See Also