Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

AI & MCP Routing

ColdBox provides first-class AI routing via toAi() and toMCP(), enabling automatic registration of AI inference and Model Context Protocol endpoints.

ColdBox 8.1 introduces two powerful routing terminators for building AI-powered HTTP APIs:

  • toAi() — Registers four standard AI inference endpoints (invoke, stream, batch, info) for any IAiRunnable object

  • toMCP() — Registers a Model Context Protocol (MCP) server endpoint handled by MCPRequestProcessor

A third terminator, toAiGateway(), covers the other direction: a platform (Slack, Telegram, WhatsApp, a signed webhook) talking to your agent on its own terms, signatures and human approvals included.

Both terminators behave like the resources() terminator: a single declaration expands to multiple concrete routes and all shared route modifiers (.as(), .withModule(), .withDomain(), etc.) are inherited by every generated sub-route.


toAi()

Overview

route( "/api/assistant" ).toAi( "models.AssistantAgent" );

A single toAi() call registers four routes automatically:

HTTP Verb
Pattern
Calls on the runnable
Purpose

POST

/api/assistant/invoke

run( input, params, options )

Synchronous single-turn inference

POST

/api/assistant/stream

stream( onChunk, input, params, options )

Server-Sent Events (SSE) streaming output

POST

/api/assistant/batch

run() for each item in inputs[]

Batch inference

GET

/api/assistant/info

getName() (no call for description)

Metadata — name, description, endpoint list

Arguments

Argument
Type
Description

runnable

string or object

A WireBox ID string (resolved lazily on every request) or a live IAiRunnable instance

There's no separate name argument — sub-route names are derived from .as()/the route's own name if you've set one, or from the pattern otherwise, exactly like every other terminator.

Basic Example

This produces the following routes:

Modifier Inheritance

All standard route modifiers are inherited by every sub-route generated by toAi():

Invoke Endpoint

The invoke action calls run() on the runnable for a standard synchronous request/response cycle.

Request body (JSON):

Response (JSON):

input/params/options are all optional and forwarded as-is to runnable.run( input, params, options ). threadId is always present — see Conversational Context below.

Stream Endpoint

The stream action calls stream() on the runnable and pipes each chunk out as a Server-Sent Events (SSE) frame. The client should set Accept: text/event-stream. See Server-Sent Events for the underlying event.sse() mechanics this endpoint builds on.

Request body (JSON): same shape as invoke - { "input": ..., "params": {}, "options": {} }

SSE Response:

The leading thread frame carries the resolved threadId - the response header (below) isn't readable from a browser EventSource, so this is how a browser client learns a server-generated thread id in time to persist it.

Batch Endpoint

The batch action calls run() once per item in inputs[], sharing the same params/options (and resolved conversational context) across every item, and returns the results in the same order.

Request body (JSON):

Response (JSON):

An item that throws is reported inline instead of failing the whole batch: { "error": "<message>", "success": false }.

Info Endpoint

The info action (GET) returns metadata about the AI runnable and the sub-routes registered for it.

Response (JSON):

Conversational Context

Alongside input/params/options, the request body accepted by invoke, stream, and batch may carry userId, conversationId, and threadId. Whatever's resolved is merged into options before the runnable is called, so a runnable reads them at options.userId/options.conversationId/options.threadId with no interface changes:

Field
Behavior

userId

The request body's userId if supplied, else the framework's own request/session tracking identifier (Controller.getUserSessionIdentifier()) - so every call is attributable to someone

conversationId

Passed through only if supplied. No default is generated - an absent conversationId means the caller isn't tracking conversations

threadId

Passed through if supplied, otherwise a new one is generated. Always present in the result, so a follow-up call can continue the same thread

threadId is echoed back three ways, so it's usable from any client:

  • On the JSON response body (invoke/batch) as threadId

  • As an X-Thread-Id response header (all three sub-routes)

  • As a leading event: thread SSE frame on /stream (shown above)

A runnable that wants to persist conversation history reads the resolved context straight off options:

IAiRunnable Interface

Your agent class must implement IAiRunnable from the bx-ai module (or satisfy its duck-typed interface). The methods toAi() actually calls are:

params configures the operation (model knobs, temperature, etc, overriding whatever defaults the runnable has); options carries runtime context - userId/conversationId/threadId land here, alongside anything else you pass through the request body's options key.


toMCP()

Overview

toMCP() registers a Model Context Protocol server endpoint. MCP is an open standard that allows AI models to interact with external tools, data sources, and services via a uniform API.

Arguments

Argument
Type
Description

name

string

Optional route name. Defaults to the route pattern.

The actual MCP server to execute is resolved from the URL pattern. You can define either a static name or use the :mcpServer placeholder to select the server dynamically from the URL.

Static Server

Use the :mcpServer placeholder in your pattern to allow the URL to identify which MCP server to invoke:

Modifier Inheritance

Like toAi(), all modifiers are inherited:

MCP Server Registration

MCP servers are registered via WireBox or the ColdBox configuration. Refer to the BoxLang AI documentation and the Agentic ColdBox guide for details on building and registering MCP servers.


Using Both Together

Last updated

Was this helpful?