bx-ai: MCP Clients and Servers
BoxLang is the AI-native software productivity platform for building, modernizing and running applications, with developers and AI agents working together.
MCP() BIF: the Client
MCP( mcpServer )
The argument picks the transport. Both clients implement IMCPClient, have the same methods and return the same MCPResponse.
| You pass |
You get |
The server is |
| A URL string |
MCPHttpClient |
A web service (HTTP, SSE answers are read) |
A struct with command |
MCPStdioClient |
A program the client launches and talks to over stdin and stdout |
Never create the client classes with new. MCPClient was renamed to MCPHttpClient; the BIF is the only way to build them.
// HTTP
mcpClient = MCP( "http://localhost:3000" ).withTimeout( 5000 ).withBearerToken( "secret" )
// Stdio: a child process
mcpClient = MCP( { command: [ "bxplaywright", "mcp" ], env: { HEADLESS: "true" } } )
tools = mcpClient.listTools()
result = mcpClient.send( "searchDocs", { query: "BoxLang" } )
mcpClient.close()
Methods (both transports)
| Method |
Purpose |
listTools( cursor="" ) |
Tools. Pass the nextCursor of a previous answer for the next page |
send( tool, args={}, context={} ) |
Call a tool. context is read by OAuth subject (see below), { chatRequest } when an agent calls |
listResources(), readResource( uri ) |
Resources |
listPrompts(), getPrompt( name, args={} ) |
Prompts |
getCapabilities() |
What the server answered to initialize |
withTimeout( ms ) |
Milliseconds to wait for each answer (default 30000) |
onSuccess( fn ), onError( fn ) |
Callbacks that receive each MCPResponse |
getStats(), getSummary(), resetStats() |
Call statistics |
close() |
Release the client. No-op for HTTP, shuts the child process down for stdio |
MCPResponse
Every call returns one. Nothing throws from a call, a failure is a response.
| Method |
Meaning |
isSuccess() / hasError() |
The call worked / failed |
getData() |
The result (empty struct on failure). Tools are in listTools().getData().tools |
getError() |
The message, empty on success |
getStatusCode() |
HTTP status. Stdio: 200 for an answer, 0 when none came |
getHeaders() |
HTTP headers, empty for stdio |
response = mcpClient.send( "search", { query: "BoxLang" } )
if ( response.isSuccess() ) {
println( response.getData() )
} else {
println( "Failed: #response.getError()#" )
}
HTTP-only Methods
withBearerToken( token ), withAuth( user, pass ), withHeaders( struct ), and the controls for URLs you do not fully trust, all off by default:
| Method |
Effect |
withUrlGuard( fn ) |
( url ) => boolean, called before every request. false or a throw refuses it |
withRedirects( false ) |
A redirect becomes a failed response |
withMaxResponseBytes( n ) |
Refuse an answer longer than n characters |
withHandshake() |
Send initialize and notifications/initialized once, keep the Mcp-Session-Id |
withHttpVersion( "HTTP/1.1" ) |
Default is HTTP/2; use HTTP/1.1 for a plain http server that mishandles the upgrade |
Stdio Servers (Child Processes)
mcpClient = MCP( {
command : [ "npx", "-y", "@modelcontextprotocol/server-github" ],
env : { GITHUB_PERSONAL_ACCESS_TOKEN: token },
cwd : "/srv/work",
inheritEnv : true,
maxRestarts : 2,
commandGuard: ( command ) => true,
timeout : 60000
} )
| Key |
Default |
Notes |
command |
required |
Array: executable then arguments. Never a shell string. No shell is ever used |
env |
{} |
Added to the child environment |
cwd |
current dir |
|
inheritEnv |
true |
false starts with only env. Then pass PATH (and often HOME) in env: npx fails with 'node': No such file or directory without it |
maxRestarts |
2 |
Consecutive relaunches of a dead server before giving up. Resets after an answer |
commandGuard |
none |
( command ) => boolean, called before every launch |
timeout |
30000 |
Milliseconds, per request and for the handshake |
Extra methods on the stdio client: isRunning(), getProtocolVersion(), getStderrTail() (last 50 stderr lines), getBaseURL() (stdio:<executable>).
Lifecycle
- Started on the first call (not at construction), one process per client, then the MCP handshake (
initialize, notifications/initialized; versions 2025-06-18, 2025-03-26, 2024-11-05)
- One reader thread matches answers to callers by JSON-RPC id, so threads can share a client
- The first call also waits for the launch and the handshake, inside
timeout. A program that downloads itself on its first run (npx -y pkg) needs a larger one, for example timeout: 120000
- A request that gets no answer in
timeout fails and a notifications/cancelled is sent. The client keeps working
- If the process dies, the call in flight fails (it is never repeated, a tool call could run twice). The next call starts the server again, up to
maxRestarts times in a row. A restarted server starts empty
- stderr goes to the
ai log (debug), never into the protocol. Lines on stdout that are not JSON-RPC are skipped
close() closes stdin, waits 2s, terminates the process and the processes it started, waits 2s, kills. It does not wait for a write stuck on a server that does not read. Live clients are also closed on module unload and JVM exit, but a client you never close keeps its process until then
Security: a stdio client runs a program. Never build command from user input.
- Module setting
mcp.stdio.allowedCommands. Empty allows any. A command without a directory (npx, npx.cmd) is matched by name, case-insensitive. A command with a directory (/usr/bin/npx, ./npx) must be listed with that exact path. The list limits the program, not its arguments (an allowed node can still run any code), and an unreadable setting refuses the command
commandGuard for rules a list cannot say. It sees only the command array, not env or cwd, so validate those yourself
- A refused command throws
MCPCommandRefused, also from withMCPServer and aiAgent(). A bad config throws InvalidArgument, and so does any option a stdio server does not have, such as the typo commandGaurd
- On Windows a
.cmd or .bat file (npx.cmd) runs through cmd.exe: never pass untrusted text as its arguments
inheritEnv: false stops secrets in your environment reaching the server
OAuth Sign In (HTTP only, 3.8.0)
For servers that ask each person to sign in (mail, calendars, trackers). withOAuth() follows the MCP authorization spec: Protected Resource Metadata (RFC 9728), authorization server metadata (RFC 8414 / OIDC), a client id (given clientId, then a Client ID Metadata Document, then Dynamic Client Registration), PKCE S256, the resource parameter (RFC 8707), the iss check (RFC 9207). Tokens refresh on their own, one refresh at a time per person, and a 401 refreshes and retries once.
mcpClient = MCP( "https://mail.example.com/mcp" ).withOAuth( {
redirectUri : "https://app.example.com/oauth/callback"
} )
started = mcpClient.startAuthorization( "default" ) // returns { authorizationUrl, ... }
location( started.authorizationUrl )
// at the callback route you own
signedIn = mcpClient.completeAuthorization( url.code, url.state, url.iss ?: "" )
tools = mcpClient.listTools() // now carries the token
response = mcpClient.send( "inbox", {} )
mcpClient.isAuthorized( "default" )
| Option |
Default |
Notes |
redirectUri |
|
Your callback route. Needed to sign in |
store |
"cache" |
"cache", "file", "jdbc", a class path, or an IMCPTokenStore instance |
storeOptions |
{} |
{ cacheName }, { path } (required for file), { datasource, table } |
subject |
"default" |
Whose tokens a call uses: a name or ( context ) => string |
discoverySubject |
"default" |
Whose tokens a call with no context uses, such as listing the tools when an agent starts: a name, or a function with no arguments |
scopes |
|
Left out: the scope from the 401, else everything the server supports |
clientId, clientSecret |
|
A client you registered yourself |
clientMetadataUrl |
|
HTTPS address of your Client ID Metadata Document |
clientName |
"bx-ai" |
Name shown at sign in when the client registers itself |
Per person: one client serves many people. subject: ( context ) => context.chatRequest.getUserId() uses the person talking to the agent (MCPTool passes { chatRequest } to send()). A call with no context, such as listTools() at agent start, uses discoverySubject ("default" when none): the list of tools is the server's and the same for everyone, so one signed in person is enough. With withHandshake( true ) each person also gets their own MCP session.
Stores: cache (default, in memory with the default cache), file (one JSON file per record, owner-only permissions), jdbc (table created when missing). They keep tokens as plain text, so protect the folder or table. To encrypt, implement bxModules.bxai.models.mcp.oauth.IMCPTokenStore: get( key ) (empty struct when none or expired), set( key, value, ttlSeconds=0 ), remove( key ), then pass the class as store with storeOptions, or an instance.
Agents: mcpServers: [ { url: "https://mail.example.com/mcp", oauth: { redirectUri: "...", subject: ( context ) => context.chatRequest.getUserId() } } ]. The agent lists tools when it starts; if nobody has signed in the listing fails, is logged, and the agent starts without that server's tools. After sign in, hand the signed-in client over again with agent.withMCPServer( mcpClient ).
Sign in needed: a call with no usable tokens returns a failed MCPResponse (nothing is sent) and fires onMCPAuthorizationRequired with client, baseURL, subject, reason, challenge, scope. reason is no_token, unauthorized or insufficient_scope (403: add event.scope to scopes and sign in again).
BoxRegisterInterceptor( ( event ) => {
link = event.client.startAuthorization( event.subject ).authorizationUrl
}, "onMCPAuthorizationRequired" )
Errors thrown by the methods you call: MCPOAuthNotEnabled, MCPOAuthMissingRedirectUri, MCPOAuthDiscoveryFailed, MCPOAuthNoClient, MCPOAuthRegistrationFailed, MCPOAuthInvalidState (unknown, used or older than ten minutes), MCPOAuthIssuerMismatch, MCPOAuthTokenError, MCPOAuthInsecureUrl (https only, plain http only for localhost and 127.0.0.1). Inside a call MCPAuthorizationRequired and MCPOAuthRefreshFailed become a failed response.
Giving MCP Tools to Agents and Models
aiAgent() and aiModel() take mcpServers, and both have withMCPServer( server, config ) and withMCPServers( servers ). The tools the server lists are wrapped and added.
agent = aiAgent(
name : "OpsAgent",
model : aiModel( provider: "openai" ),
mcpServers: [
"https://docs.example.com/mcp", // URL
{ url: "https://api.example.com/mcp", token: apiToken, prefix: "api" }, // HTTP struct
{ command: [ "bxplaywright", "mcp" ], prefix: "browser" }, // stdio struct
MCP( { command: [ "bxplaywright", "mcp" ] } ) // ready-made client
]
)
agent.run( "Check the docs" )
agent.closeMCPServers() // closes the clients the agent built itself
Registration options (in the struct, or in the second argument of withMCPServer):
| Option |
Effect |
prefix |
Tools are exposed as prefix__name; the server still gets the original name |
toolFilter |
Array of tool names. Only these are exposed (without it, every tool is) |
timeout |
Milliseconds |
HTTP structs also take token, user + password, headers, urlGuard, redirects, maxResponseBytes, handshake, httpVersion. Using one of those with a stdio struct throws InvalidArgument.
- A server that cannot be reached, cannot start or fails the handshake is logged to the
ai log and the agent carries on without its tools (no throw). A refused command does throw
closeMCPServers() leaves clients you passed in ready-made alone: close those yourself
listMCPServers() lists connected servers (url is stdio:<executable> for stdio) with their tool names
Events and Stats
onMCPClientRequest, onMCPClientResponse, onMCPClientError, and onMCPAuthorizationRequired (see OAuth). The data has client, baseURL (stdio:<executable> for stdio), transport (http or stdio), operation (tool, resource, prompt, discovery), name, and executionTime, response or error. The stdio handshake fires no events and is not counted.
BoxRegisterInterceptor( ( event ) => {
println( "#event.transport# #event.name# #event.executionTime#ms" )
}, "onMCPClientResponse" )
mcpClient.getSummary() returns totalCalls, successRate, avgResponseTime, totalToolCalls, totalErrors and more.
MCPServer(): Exposing Tools
mcpSrv = MCPServer( "my-tools", "Business tools" )
.registerTool( aiTool( "getCustomer", "Fetch a customer by id", ( required string id ) => fetchCustomer( id ) ) )
.registerResource( "config://app", "App config", () => getAppConfig() )
.registerPrompt( "greet", ( name ) => "Hello #name#", "Greeting prompt" )
response = mcpSrv.handleRequest( requestBody ) // JSON-RPC 2.0 in, out
MCPServer( name="default", description, version, cors, statsEnabled, force ). Also registerTools( array ), withBasicAuth( user, pass ), withApiKeyProvider( provider ).
Stdio server (a client launches it as a child process):
// mcp-stdio.bxs
import bxModules.bxai.models.mcp.MCPRequestProcessor
MCPServer( "default" ).registerTool( aiTool( "echo", "Echo", ( msg ) => msg ) )
systemOutput( "starting", true, true ) // stderr, not stdout
MCPRequestProcessor::processStdio( "default" ) // stops when stdin closes
Rules: only protocol messages on stdout (use systemOutput( text, true, true ) for human messages, println() writes to stdout); exit when stdin closes.
Rate Limiting and Trusted Proxies (servers)
Off by default. Checked before authentication, after the IP allowlist and CORS preflight (a preflight is never counted).
mcpServer( "myApp" )
.withTrustedProxies( [ "10.0.0.0/8" ] )
.withRateLimit( { limit: 100, window: 60, key: "ip", store: "cache", cacheName: "mcpLimits", failOpen: true } )
mcpServer( "myApp" ).withRateLimit( 100 ) // 100 per 60 s, per IP
mcpServer( "myApp" ).withRateLimit( false ) // opt out (also of the module default)
key: "ip" (default), "apiKey" (needs withApiKeyProvider() first; only a key the provider accepts is a bucket, others fall back to the IP), "global" (one bucket, not "server"), or a lambda ( requestData ) => string (an empty result means not limited)
store: "cache" (default, use a dedicated cacheName), "memory", a class path, or an instance of a class that implements bxModules.bxai.models.mcp.ratelimit.IRateLimitStore (increment( key, ttlSeconds, amount ), get( key ), remove( key ))
failOpen: true (default) lets requests through when the store fails, false answers 503
- Blocked: HTTP 429, JSON-RPC
-32002, Retry-After and X-RateLimit-Limit/Remaining/Reset (the X-RateLimit-* also on allowed responses)
- Logging never follows traffic: at most 10 warnings per minute per server and one summary line, not a setting. The
onMCPRateLimitHit event (data: mcpServer, serverName, key, keyType, limit, window, retryAfter, requestData) shares that budget. Exact numbers are in mcpSrv.getStats().security.rateLimitFailures and mcpSrv.getStats().rateLimit
limits: [ { limit: 60, window: 60 }, { limit: 1000, window: 3600 } ] gives several limits (minute and hour). A request must pass all, the others get the request back on a refusal, Retry-After is the longest wait. Windows must be different. limits replaces limit and window
mcpSrv.disableRateLimit() / enableRateLimit() / isRateLimitEnabled() switch checking and keep setup, counters and history (withRateLimit( false ) removes it, hasRateLimit() means configured). enableRateLimit() with nothing configured uses the module defaults
mcpSrv.resetRateLimit() deletes all counters (needs a store with IClearableRateLimitStore, the cache and memory stores have it, returns false otherwise), mcpSrv.resetRateLimitStats() clears stats and history
- History per client and UTC day in the cache:
retention days (module mcp.server.rateLimit.retentionDays, default 7, 0 none, max 365), historyFlushSeconds (30, min 5), historyMaxClients (500, 50 to 5000, the smallest fold into (other), totals stay exact). mcpSrv.getRateLimitReport( { days: 7, top: 20 } ) returns { since, days: [ { day, requests, blocked } ], topConsumers: [ { client, type, requests, blocked, peakPerMinute, pctOfLimit, lastBlockedAt } ], nodes, retentionDays }. IPs are plain, other keys a short hash. getStats().rateLimit has enabled, limits, topBlocked (today only)
mcpSrv.hasRateLimit(), mcpSrv.getRateLimiter().status( "ip:1.2.3.4" ) and .reset( "ip:1.2.3.4" )
- Module defaults:
mcp.server.rateLimit (enabled false, limit 60, window 60, key, store, cacheName, failOpen) and mcp.server.trustedProxies
withTrustedProxies( [ ips or CIDRs ] ): forwarded headers (X-Forwarded-For...) only count from those proxies, read from the right. Empty or [ "*" ] trusts them from anyone (the old behavior), only safe when clients can reach the server only through your proxy. The IP allowlist and the ip limit both use it
- The cache store is exact inside one JVM only, approximate across nodes
Common Pitfalls
Set withTrustedProxies() in production, otherwise a client can forge X-Forwarded-For to dodge an ip limit or an IP allowlist
server is a BoxLang scope, so name the variable mcpSrv. The shared rate limit key is "global"
mcpClient.callTool() and mcpClient.getResource() do not exist: use send() and readResource()
listTools() returns an MCPResponse, not an array: use .getData().tools
The failure check is hasError(), there is no isError()
The BIF is MCP( ... ); there is no startStdio(), the server entry is MCPRequestProcessor::processStdio()
command is an array. MCP( { command: "bxplaywright mcp" } ) throws InvalidArgument
withMCPServer( { command: [...], prefix: "x" } ) is fine: prefix and toolFilter can sit in the struct. MCP( { command: [...], prefix: "x" } ) throws, they only mean something to agents and models
Remember close() / agent.closeMCPServers() for stdio clients, otherwise the child process lives until module unload
aiAgent() takes name and model (an aiModel()), not agentName or aiModel: "openai". BoxLang ignores unknown named arguments, so a wrong name fails silently
withTimeout( ms ) is in milliseconds
withOAuth() is for the HTTP client only. A stdio server gets its credentials from env
The default cache token store is in memory: people sign in again after a restart. Use file, jdbc, a durable cache or your own store
client, server, form, url, request and local are reserved scopes in BoxLang: never use them as variable or argument names (mcpClient, mcpSrv, fields). In a web server a reserved name silently reads the real scope, so code that works in a script fails when served. The event data key client is a key, not a variable
startAuthorization() without a redirectUri throws MCPOAuthMissingRedirectUri
Do not retry a tool call that changes something unless the tool is safe to repeat
1---2name: bx-ai-mcp3description: "Use this skill when consuming or exposing MCP (Model Context Protocol) servers with bx-ai: the MCP() BIF for HTTP URLs and stdio child processes (MCP( { command: [ ... ] } )), MCPResponse, discovery and tool calls, signing in to OAuth protected MCP servers (withOAuth, startAuthorization, completeAuthorization, per person tokens with subject, token stores, onMCPAuthorizationRequired), giving MCP tools to agents and models (mcpServers, withMCPServer, withMCPServers, prefix, toolFilter, closeMCPServers), stdio lifecycle, restarts, timeouts and security (allowedCommands, commandGuard), client events and stats, creating MCP servers with MCPServer(), and securing them (withRateLimit, withTrustedProxies, withAllowedIPs, withApiKeyProvider, withBasicAuth)."4metadata:5 source: https://skillmd.com/skills/ortus-boxlang/bx-ai-mcp6---78# bx-ai: MCP Clients and Servers910> BoxLang is the AI-native software productivity platform for building, modernizing and running applications, with developers and AI agents working together.1112## `MCP()` BIF: the Client1314```javascript15MCP( mcpServer )16```1718The argument picks the transport. Both clients implement `IMCPClient`, have the same methods and return the same `MCPResponse`.1920| You pass | You get | The server is |21|----------|---------|---------------|22| A URL string | `MCPHttpClient` | A web service (HTTP, SSE answers are read) |23| A struct with `command` | `MCPStdioClient` | A program the client launches and talks to over stdin and stdout |2425Never create the client classes with `new`. `MCPClient` was renamed to `MCPHttpClient`; the BIF is the only way to build them.2627```javascript28// HTTP29mcpClient = MCP( "http://localhost:3000" ).withTimeout( 5000 ).withBearerToken( "secret" )3031// Stdio: a child process32mcpClient = MCP( { command: [ "bxplaywright", "mcp" ], env: { HEADLESS: "true" } } )3334tools = mcpClient.listTools()35result = mcpClient.send( "searchDocs", { query: "BoxLang" } )36mcpClient.close()37```3839## Methods (both transports)4041| Method | Purpose |42|--------|---------|43| `listTools( cursor="" )` | Tools. Pass the `nextCursor` of a previous answer for the next page |44| `send( tool, args={}, context={} )` | Call a tool. `context` is read by OAuth `subject` (see below), `{ chatRequest }` when an agent calls |45| `listResources()`, `readResource( uri )` | Resources |46| `listPrompts()`, `getPrompt( name, args={} )` | Prompts |47| `getCapabilities()` | What the server answered to `initialize` |48| `withTimeout( ms )` | Milliseconds to wait for each answer (default 30000) |49| `onSuccess( fn )`, `onError( fn )` | Callbacks that receive each `MCPResponse` |50| `getStats()`, `getSummary()`, `resetStats()` | Call statistics |51| `close()` | Release the client. No-op for HTTP, shuts the child process down for stdio |5253## `MCPResponse`5455Every call returns one. **Nothing throws from a call**, a failure is a response.5657| Method | Meaning |58|--------|---------|59| `isSuccess()` / `hasError()` | The call worked / failed |60| `getData()` | The result (empty struct on failure). Tools are in `listTools().getData().tools` |61| `getError()` | The message, empty on success |62| `getStatusCode()` | HTTP status. Stdio: `200` for an answer, `0` when none came |63| `getHeaders()` | HTTP headers, empty for stdio |6465```javascript66response = mcpClient.send( "search", { query: "BoxLang" } )67if ( response.isSuccess() ) {68 println( response.getData() )69} else {70 println( "Failed: #response.getError()#" )71}72```7374## HTTP-only Methods7576`withBearerToken( token )`, `withAuth( user, pass )`, `withHeaders( struct )`, and the controls for URLs you do not fully trust, all off by default:7778| Method | Effect |79|--------|--------|80| `withUrlGuard( fn )` | `( url ) => boolean`, called before every request. `false` or a throw refuses it |81| `withRedirects( false )` | A redirect becomes a failed response |82| `withMaxResponseBytes( n )` | Refuse an answer longer than `n` characters |83| `withHandshake()` | Send `initialize` and `notifications/initialized` once, keep the `Mcp-Session-Id` |84| `withHttpVersion( "HTTP/1.1" )` | Default is `HTTP/2`; use `HTTP/1.1` for a plain http server that mishandles the upgrade |8586## Stdio Servers (Child Processes)8788```javascript89mcpClient = MCP( {90 command : [ "npx", "-y", "@modelcontextprotocol/server-github" ],91 env : { GITHUB_PERSONAL_ACCESS_TOKEN: token },92 cwd : "/srv/work",93 inheritEnv : true,94 maxRestarts : 2,95 commandGuard: ( command ) => true,96 timeout : 6000097} )98```99100| Key | Default | Notes |101|-----|---------|-------|102| `command` | required | Array: executable then arguments. Never a shell string. No shell is ever used |103| `env` | `{}` | Added to the child environment |104| `cwd` | current dir | |105| `inheritEnv` | `true` | `false` starts with only `env`. Then pass `PATH` (and often `HOME`) in `env`: `npx` fails with `'node': No such file or directory` without it |106| `maxRestarts` | `2` | Consecutive relaunches of a dead server before giving up. Resets after an answer |107| `commandGuard` | none | `( command ) => boolean`, called before every launch |108| `timeout` | `30000` | Milliseconds, per request and for the handshake |109110Extra methods on the stdio client: `isRunning()`, `getProtocolVersion()`, `getStderrTail()` (last 50 stderr lines), `getBaseURL()` (`stdio:<executable>`).111112**Lifecycle**113- Started on the first call (not at construction), one process per client, then the MCP handshake (`initialize`, `notifications/initialized`; versions `2025-06-18`, `2025-03-26`, `2024-11-05`)114- One reader thread matches answers to callers by JSON-RPC id, so threads can share a client115- The first call also waits for the launch and the handshake, inside `timeout`. A program that downloads itself on its first run (`npx -y pkg`) needs a larger one, for example `timeout: 120000`116- A request that gets no answer in `timeout` fails and a `notifications/cancelled` is sent. The client keeps working117- If the process dies, the call in flight fails (it is never repeated, a tool call could run twice). The next call starts the server again, up to `maxRestarts` times in a row. A restarted server starts empty118- stderr goes to the `ai` log (debug), never into the protocol. Lines on stdout that are not JSON-RPC are skipped119- `close()` closes stdin, waits 2s, terminates the process and the processes it started, waits 2s, kills. It does not wait for a write stuck on a server that does not read. Live clients are also closed on module unload and JVM exit, but a client you never close keeps its process until then120121**Security**: a stdio client runs a program. Never build `command` from user input.122- Module setting `mcp.stdio.allowedCommands`. Empty allows any. A command without a directory (`npx`, `npx.cmd`) is matched by name, case-insensitive. A command with a directory (`/usr/bin/npx`, `./npx`) must be listed with that exact path. The list limits the program, not its arguments (an allowed `node` can still run any code), and an unreadable setting refuses the command123- `commandGuard` for rules a list cannot say. It sees only the command array, not `env` or `cwd`, so validate those yourself124- A refused command throws `MCPCommandRefused`, also from `withMCPServer` and `aiAgent()`. A bad config throws `InvalidArgument`, and so does any option a stdio server does not have, such as the typo `commandGaurd`125- On Windows a `.cmd` or `.bat` file (`npx.cmd`) runs through `cmd.exe`: never pass untrusted text as its arguments126- `inheritEnv: false` stops secrets in your environment reaching the server127128## OAuth Sign In (HTTP only, 3.8.0)129130For servers that ask each person to sign in (mail, calendars, trackers). `withOAuth()` follows the MCP authorization spec: Protected Resource Metadata (RFC 9728), authorization server metadata (RFC 8414 / OIDC), a client id (given `clientId`, then a Client ID Metadata Document, then Dynamic Client Registration), PKCE `S256`, the `resource` parameter (RFC 8707), the `iss` check (RFC 9207). Tokens refresh on their own, one refresh at a time per person, and a `401` refreshes and retries once.131132```javascript133mcpClient = MCP( "https://mail.example.com/mcp" ).withOAuth( {134 redirectUri : "https://app.example.com/oauth/callback"135} )136137started = mcpClient.startAuthorization( "default" ) // returns { authorizationUrl, ... }138location( started.authorizationUrl )139140// at the callback route you own141signedIn = mcpClient.completeAuthorization( url.code, url.state, url.iss ?: "" )142143tools = mcpClient.listTools() // now carries the token144response = mcpClient.send( "inbox", {} )145mcpClient.isAuthorized( "default" )146```147148| Option | Default | Notes |149|--------|---------|-------|150| `redirectUri` | | Your callback route. Needed to sign in |151| `store` | `"cache"` | `"cache"`, `"file"`, `"jdbc"`, a class path, or an `IMCPTokenStore` instance |152| `storeOptions` | `{}` | `{ cacheName }`, `{ path }` (required for file), `{ datasource, table }` |153| `subject` | `"default"` | Whose tokens a call uses: a name or `( context ) => string` |154| `discoverySubject` | `"default"` | Whose tokens a call with no context uses, such as listing the tools when an agent starts: a name, or a function with no arguments |155| `scopes` | | Left out: the scope from the `401`, else everything the server supports |156| `clientId`, `clientSecret` | | A client you registered yourself |157| `clientMetadataUrl` | | HTTPS address of your Client ID Metadata Document |158| `clientName` | `"bx-ai"` | Name shown at sign in when the client registers itself |159160**Per person**: one client serves many people. `subject: ( context ) => context.chatRequest.getUserId()` uses the person talking to the agent (`MCPTool` passes `{ chatRequest }` to `send()`). A call with no context, such as `listTools()` at agent start, uses `discoverySubject` (`"default"` when none): the list of tools is the server's and the same for everyone, so one signed in person is enough. With `withHandshake( true )` each person also gets their own MCP session.161162**Stores**: `cache` (default, in memory with the default cache), `file` (one JSON file per record, owner-only permissions), `jdbc` (table created when missing). They keep tokens as plain text, so protect the folder or table. To encrypt, implement `bxModules.bxai.models.mcp.oauth.IMCPTokenStore`: `get( key )` (empty struct when none or expired), `set( key, value, ttlSeconds=0 )`, `remove( key )`, then pass the class as `store` with `storeOptions`, or an instance.163164**Agents**: `mcpServers: [ { url: "https://mail.example.com/mcp", oauth: { redirectUri: "...", subject: ( context ) => context.chatRequest.getUserId() } } ]`. The agent lists tools when it starts; if nobody has signed in the listing fails, is logged, and the agent starts without that server's tools. After sign in, hand the signed-in client over again with `agent.withMCPServer( mcpClient )`.165166**Sign in needed**: a call with no usable tokens returns a failed `MCPResponse` (nothing is sent) and fires `onMCPAuthorizationRequired` with `client`, `baseURL`, `subject`, `reason`, `challenge`, `scope`. `reason` is `no_token`, `unauthorized` or `insufficient_scope` (403: add `event.scope` to `scopes` and sign in again).167168```javascript169BoxRegisterInterceptor( ( event ) => {170 link = event.client.startAuthorization( event.subject ).authorizationUrl171}, "onMCPAuthorizationRequired" )172```173174Errors thrown by the methods you call: `MCPOAuthNotEnabled`, `MCPOAuthMissingRedirectUri`, `MCPOAuthDiscoveryFailed`, `MCPOAuthNoClient`, `MCPOAuthRegistrationFailed`, `MCPOAuthInvalidState` (unknown, used or older than ten minutes), `MCPOAuthIssuerMismatch`, `MCPOAuthTokenError`, `MCPOAuthInsecureUrl` (https only, plain http only for `localhost` and `127.0.0.1`). Inside a call `MCPAuthorizationRequired` and `MCPOAuthRefreshFailed` become a failed response.175176## Giving MCP Tools to Agents and Models177178`aiAgent()` and `aiModel()` take `mcpServers`, and both have `withMCPServer( server, config )` and `withMCPServers( servers )`. The tools the server lists are wrapped and added.179180```javascript181agent = aiAgent(182 name : "OpsAgent",183 model : aiModel( provider: "openai" ),184 mcpServers: [185 "https://docs.example.com/mcp", // URL186 { url: "https://api.example.com/mcp", token: apiToken, prefix: "api" }, // HTTP struct187 { command: [ "bxplaywright", "mcp" ], prefix: "browser" }, // stdio struct188 MCP( { command: [ "bxplaywright", "mcp" ] } ) // ready-made client189 ]190)191192agent.run( "Check the docs" )193agent.closeMCPServers() // closes the clients the agent built itself194```195196Registration options (in the struct, or in the second argument of `withMCPServer`):197198| Option | Effect |199|--------|--------|200| `prefix` | Tools are exposed as `prefix__name`; the server still gets the original name |201| `toolFilter` | Array of tool names. Only these are exposed (without it, every tool is) |202| `timeout` | Milliseconds |203204HTTP structs also take `token`, `user` + `password`, `headers`, `urlGuard`, `redirects`, `maxResponseBytes`, `handshake`, `httpVersion`. **Using one of those with a stdio struct throws `InvalidArgument`.**205206- A server that cannot be reached, cannot start or fails the handshake is logged to the `ai` log and the agent carries on **without its tools** (no throw). A refused command does throw207- `closeMCPServers()` leaves clients you passed in ready-made alone: close those yourself208- `listMCPServers()` lists connected servers (`url` is `stdio:<executable>` for stdio) with their tool names209210## Events and Stats211212`onMCPClientRequest`, `onMCPClientResponse`, `onMCPClientError`, and `onMCPAuthorizationRequired` (see OAuth). The data has `client`, `baseURL` (`stdio:<executable>` for stdio), `transport` (`http` or `stdio`), `operation` (`tool`, `resource`, `prompt`, `discovery`), `name`, and `executionTime`, `response` or `error`. The stdio handshake fires no events and is not counted.213214```javascript215BoxRegisterInterceptor( ( event ) => {216 println( "#event.transport# #event.name# #event.executionTime#ms" )217}, "onMCPClientResponse" )218```219220`mcpClient.getSummary()` returns `totalCalls`, `successRate`, `avgResponseTime`, `totalToolCalls`, `totalErrors` and more.221222## `MCPServer()`: Exposing Tools223224```javascript225mcpSrv = MCPServer( "my-tools", "Business tools" )226 .registerTool( aiTool( "getCustomer", "Fetch a customer by id", ( required string id ) => fetchCustomer( id ) ) )227 .registerResource( "config://app", "App config", () => getAppConfig() )228 .registerPrompt( "greet", ( name ) => "Hello #name#", "Greeting prompt" )229230response = mcpSrv.handleRequest( requestBody ) // JSON-RPC 2.0 in, out231```232233`MCPServer( name="default", description, version, cors, statsEnabled, force )`. Also `registerTools( array )`, `withBasicAuth( user, pass )`, `withApiKeyProvider( provider )`.234235**Stdio server** (a client launches it as a child process):236237```javascript238// mcp-stdio.bxs239import bxModules.bxai.models.mcp.MCPRequestProcessor240MCPServer( "default" ).registerTool( aiTool( "echo", "Echo", ( msg ) => msg ) )241systemOutput( "starting", true, true ) // stderr, not stdout242MCPRequestProcessor::processStdio( "default" ) // stops when stdin closes243```244245Rules: only protocol messages on stdout (use `systemOutput( text, true, true )` for human messages, `println()` writes to stdout); exit when stdin closes.246247## Rate Limiting and Trusted Proxies (servers)248249Off by default. Checked before authentication, after the IP allowlist and CORS preflight (a preflight is never counted).250251```javascript252mcpServer( "myApp" )253 .withTrustedProxies( [ "10.0.0.0/8" ] )254 .withRateLimit( { limit: 100, window: 60, key: "ip", store: "cache", cacheName: "mcpLimits", failOpen: true } )255256mcpServer( "myApp" ).withRateLimit( 100 ) // 100 per 60 s, per IP257mcpServer( "myApp" ).withRateLimit( false ) // opt out (also of the module default)258```259260- `key`: `"ip"` (default), `"apiKey"` (needs `withApiKeyProvider()` first; only a key the provider accepts is a bucket, others fall back to the IP), `"global"` (one bucket, not `"server"`), or a lambda `( requestData ) => string` (an empty result means not limited)261- `store`: `"cache"` (default, use a dedicated `cacheName`), `"memory"`, a class path, or an instance of a class that implements `bxModules.bxai.models.mcp.ratelimit.IRateLimitStore` (`increment( key, ttlSeconds, amount )`, `get( key )`, `remove( key )`)262- `failOpen`: true (default) lets requests through when the store fails, false answers 503263- Blocked: HTTP 429, JSON-RPC `-32002`, `Retry-After` and `X-RateLimit-Limit/Remaining/Reset` (the `X-RateLimit-*` also on allowed responses)264- Logging never follows traffic: at most 10 warnings per minute per server and one summary line, not a setting. The `onMCPRateLimitHit` event (data: `mcpServer`, `serverName`, `key`, `keyType`, `limit`, `window`, `retryAfter`, `requestData`) shares that budget. Exact numbers are in `mcpSrv.getStats().security.rateLimitFailures` and `mcpSrv.getStats().rateLimit`265- `limits: [ { limit: 60, window: 60 }, { limit: 1000, window: 3600 } ]` gives several limits (minute and hour). A request must pass all, the others get the request back on a refusal, `Retry-After` is the longest wait. Windows must be different. `limits` replaces `limit` and `window`266- `mcpSrv.disableRateLimit()` / `enableRateLimit()` / `isRateLimitEnabled()` switch checking and keep setup, counters and history (`withRateLimit( false )` removes it, `hasRateLimit()` means configured). `enableRateLimit()` with nothing configured uses the module defaults267- `mcpSrv.resetRateLimit()` deletes all counters (needs a store with `IClearableRateLimitStore`, the cache and memory stores have it, returns false otherwise), `mcpSrv.resetRateLimitStats()` clears stats and history268- History per client and UTC day in the cache: `retention` days (module `mcp.server.rateLimit.retentionDays`, default 7, 0 none, max 365), `historyFlushSeconds` (30, min 5), `historyMaxClients` (500, 50 to 5000, the smallest fold into `(other)`, totals stay exact). `mcpSrv.getRateLimitReport( { days: 7, top: 20 } )` returns `{ since, days: [ { day, requests, blocked } ], topConsumers: [ { client, type, requests, blocked, peakPerMinute, pctOfLimit, lastBlockedAt } ], nodes, retentionDays }`. IPs are plain, other keys a short hash. `getStats().rateLimit` has `enabled`, `limits`, `topBlocked` (today only)269- `mcpSrv.hasRateLimit()`, `mcpSrv.getRateLimiter().status( "ip:1.2.3.4" )` and `.reset( "ip:1.2.3.4" )`270- Module defaults: `mcp.server.rateLimit` (`enabled` false, `limit` 60, `window` 60, `key`, `store`, `cacheName`, `failOpen`) and `mcp.server.trustedProxies`271- `withTrustedProxies( [ ips or CIDRs ] )`: forwarded headers (`X-Forwarded-For`...) only count from those proxies, read from the right. Empty or `[ "*" ]` trusts them from anyone (the old behavior), only safe when clients can reach the server only through your proxy. The IP allowlist and the `ip` limit both use it272- The cache store is exact inside one JVM only, approximate across nodes273274## Common Pitfalls275276- Set `withTrustedProxies()` in production, otherwise a client can forge `X-Forwarded-For` to dodge an `ip` limit or an IP allowlist277- `server` is a BoxLang scope, so name the variable `mcpSrv`. The shared rate limit key is `"global"`278279- `mcpClient.callTool()` and `mcpClient.getResource()` do not exist: use `send()` and `readResource()`280- `listTools()` returns an `MCPResponse`, not an array: use `.getData().tools`281- The failure check is `hasError()`, there is no `isError()`282- The BIF is `MCP( ... )`; there is no `startStdio()`, the server entry is `MCPRequestProcessor::processStdio()`283- `command` is an array. `MCP( { command: "bxplaywright mcp" } )` throws `InvalidArgument`284- `withMCPServer( { command: [...], prefix: "x" } )` is fine: `prefix` and `toolFilter` can sit in the struct. `MCP( { command: [...], prefix: "x" } )` throws, they only mean something to agents and models285- Remember `close()` / `agent.closeMCPServers()` for stdio clients, otherwise the child process lives until module unload286- `aiAgent()` takes `name` and `model` (an `aiModel()`), not `agentName` or `aiModel: "openai"`. BoxLang ignores unknown named arguments, so a wrong name fails silently287- `withTimeout( ms )` is in milliseconds288- `withOAuth()` is for the HTTP client only. A stdio server gets its credentials from `env`289- The default `cache` token store is in memory: people sign in again after a restart. Use `file`, `jdbc`, a durable cache or your own store290- `client`, `server`, `form`, `url`, `request` and `local` are reserved scopes in BoxLang: never use them as variable or argument names (`mcpClient`, `mcpSrv`, `fields`). In a web server a reserved name silently reads the real scope, so code that works in a script fails when served. The event data key `client` is a key, not a variable291- `startAuthorization()` without a `redirectUri` throws `MCPOAuthMissingRedirectUri`292- Do not retry a tool call that changes something unless the tool is safe to repeat