> For the complete documentation index, see [llms.txt](https://ai.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai.ortusbooks.com/main-components/agents/tools-and-mcp.md).

# Tools & MCP

Tools, the Global Tool Registry, MCP server seeding, and the ClosureTool pattern for building AI agents with real-world capabilities.

{% hint style="info" %}
**Since BoxLang AI v3.0+**
{% endhint %}

Agents use tools to perform real-world actions — querying databases, calling APIs, running calculations, and more. In v3.0, tools can also be sourced from the Global Tool Registry and from remote MCP servers.

## Basic Tool Usage

```javascript
// Inline lambda tool
weatherTool = aiTool(
    "get_weather",
    "Get current weather for a location",
    location => getWeatherData( location )
).describeLocation( "City and country, e.g. Boston, MA" )

agent = aiAgent(
    name : "WeatherBot",
    tools: [ weatherTool ]
)

response = agent.run( "What's the weather in Paris?" )
// Agent automatically calls get_weather("Paris")
```

## Global Tool Registry (v3.0+)

The Tool Registry is a module-wide singleton that stores tools by name (optionally namespaced by module). Agents can look up tools by name at runtime instead of holding direct references.

```javascript
// Register tools centrally
aiToolRegistry()
    .register( weatherTool, module: "my-app" )
    .register( calculatorTool )

// Resolve tools by name when creating agents
agent = aiAgent(
    name : "Assistant",
    tools: aiToolRegistry().resolveTools( [
        "get_weather@my-app",
        "calculate"
    ] )
)
```

### Registering with Shorthand

```javascript
// Register directly from function reference
aiToolRegistry().register(
    name       : "search_products",
    description: "Search the product catalog",
    callback   : searchProducts
)
```

### `@AITool` Annotation Scanning

Annotate methods with `@AITool` and scan a class or package path:

```javascript
class MyTools {
    @AITool( "Search the product catalog" )
    function search_products( required string query ) {
        return queryProductDB( query )
    }

    @AITool( { name: "get_order", description: "Look up an order by ID" } )
    function get_order( required string orderId ) {
        return queryOrderDB( orderId )
    }
}

// Scan and register all @AITool methods at startup
aiToolRegistry().scan( new MyTools(), module: "my-app" )

// Use in agent
agent = aiAgent(
    name : "SalesBot",
    tools: aiToolRegistry().resolveTools( [ "search_products@my-app", "get_order@my-app" ] )
)
```

### Registry API

| Method                                            | Description                              |
| ------------------------------------------------- | ---------------------------------------- |
| `register( tool, module )`                        | Register an `ITool` instance             |
| `register( name, description, callback, module )` | Shorthand — builds `ClosureTool`         |
| `scan( instanceOrPath, module )`                  | Scan `@AITool` annotations               |
| `get( key )`                                      | Get a tool by name or `name@module` key  |
| `has( key )`                                      | Check if a tool exists                   |
| `resolveTools( array )`                           | Convert string keys to `ITool` instances |
| `unregister( key )`                               | Remove a tool                            |
| `getKeys()`                                       | List all registered keys                 |

See [Tool Registry](https://ai.ortusbooks.com/main-components/tool-registry.md) for the full reference.

## Built-in Audio Tools (v3.1+) 🎙️

The `bx-ai` module automatically registers three audio tools at startup. Opt in by including their keys in your agent's `tools` array — no registration code required.

| Tool Key          | Description                                                                                                                           |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `speak@bxai`      | Convert text to speech; returns the absolute path to the saved audio file (auto-generates a temp file if no `outputFile` is provided) |
| `transcribe@bxai` | Transcribe a local audio file path or URL to plain text                                                                               |
| `translate@bxai`  | Translate any-language audio to English text                                                                                          |

```javascript
agent = aiAgent(
    name         : "VoiceAssistant",
    instructions : "You are a helpful voice assistant. Speak responses aloud and transcribe audio on request.",
    tools        : [ "now@bxai", "speak@bxai", "transcribe@bxai", "translate@bxai" ]
)

// Agent calls speak@bxai — returns the path to the generated mp3
agent.run( "Welcome the user and tell them today's date" )

// Agent calls transcribe@bxai — returns plain transcript text
agent.run( "Transcribe /recordings/meeting.mp3" )

// Agent calls translate@bxai — returns English translation
agent.run( "Translate the Spanish audio at /audio/mensaje.mp3" )
```

> 💡 The `speak@bxai` tool writes to a temporary file automatically when the agent does not supply an `outputFile`. For production use, instruct the agent to provide a specific output path or post-process the returned path.

See [Audio & Speech](https://ai.ortusbooks.com/main-components/audio.md) for full details on providers, voices, and formats.

## Built-in Web Search Tool (v3.2+) 🔍

The `bx-ai` module auto-registers `webSearch@bxai` at startup. Agents can opt in by adding the key in their `tools` array.

| Tool Key         | Description                                                                                                            |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `webSearch@bxai` | Search the web through configured providers (`http`, `brave`, `google`, `tavily`, `exa`) and return normalized results |

```javascript
agent = aiAgent(
    name         : "ResearchAgent",
    instructions : "Use web search for current information and cite source URLs.",
    tools        : [ "webSearch@bxai" ]
)

response = agent.run( "Find the most recent BoxLang AI 3.2 highlights" )
```

`webSearch@bxai` is ideal for fact-checking, current events, and retrieval tasks that require fresh data.

See [Web Search Tools](https://ai.ortusbooks.com/main-components/web-search.md) for provider configuration and examples.

## Built-in FileSystem Tools (v3.1+) 📂

`FileSystemTools` gives agents the ability to read, write, move, delete, and list files and directories on the local filesystem. It is **not auto-registered** — you must opt in explicitly, which lets you apply path guards that restrict the AI to specific directories.

### Tool Keys

| Tool Key               | Description                                                                  |
| ---------------------- | ---------------------------------------------------------------------------- |
| `readFile@bxai`        | Read a file and return its text content                                      |
| `writeFile@bxai`       | Write (overwrite) text to a file; creates parent dirs as needed              |
| `appendFile@bxai`      | Append text to a file; creates the file if it does not exist                 |
| `fileMetadata@bxai`    | Return file metadata (name, size, MIME type, modified date) as JSON          |
| `pathExists@bxai`      | Check whether a file or directory exists (`"true"` / `"false"`)              |
| `deleteFile@bxai`      | Delete a file ⚠️ irreversible                                                |
| `moveFile@bxai`        | Move or rename a file                                                        |
| `copyFile@bxai`        | Copy a file to a new location                                                |
| `listDirectory@bxai`   | List directory contents as a JSON array; supports glob filters and recursion |
| `createDirectory@bxai` | Create a directory including any missing parent directories                  |
| `deleteDirectory@bxai` | Recursively delete a directory and all its contents ⚠️ irreversible          |

### Registration with Path Guards

```javascript
import bxModules.bxai.models.tools.filesystem.FileSystemTools;

// Restrict to specific directories (strongly recommended)
aiToolRegistry().scanClass(
    new FileSystemTools( allowedPaths: [ "/workspace/data", "/tmp/ai-output" ] ),
    "bxai"
)

// Allow any path — use only in fully-trusted environments
aiToolRegistry().scanClass( new FileSystemTools(), "bxai" )
```

Every path argument is resolved to its canonical form before the guard check runs. This blocks directory-traversal tricks like `../../etc/passwd` even if the AI constructs them.

### Example: Coding Agent

```javascript
agent = aiAgent(
    name         : "CodingAssistant",
    instructions : "You are a coding assistant. You can read, write, and organize project files.",
    tools        : [
        "readFile@bxai",
        "writeFile@bxai",
        "listDirectory@bxai",
        "createDirectory@bxai",
        "fileMetadata@bxai",
        "pathExists@bxai"
    ]
)

// Agent reads a file and rewrites it with improvements
agent.run( "Read src/App.bx and add a descriptive header comment at the top" )

// Agent scans the project for all BoxLang files
agent.run( "List all .bx files under src/ recursively and summarize what each one does" )

// Agent creates an output structure
agent.run( "Create a reports/ directory and write an audit.md file with a summary of findings" )
```

### Example: File listing with glob filter

```javascript
// listDirectory supports glob patterns and recursive search
agent.run(
    "List all JSON and YAML config files under /project/config — use the pattern *.json|*.yaml"
)
```

> 🔐 `deleteFile@bxai` and `deleteDirectory@bxai` are irreversible. Consider omitting them from agents that only need read or write access.

## ClosureTool Pattern

`ClosureTool` wraps a lambda directly without going through `aiTool()`:

```javascript
import bxModules.bxai.models.tools.ClosureTool;

searchTool = new ClosureTool(
    "search_docs",
    "Search documentation",
    query => searchIndex( query )
)

agent = aiAgent(
    name : "DocBot",
    tools: [ searchTool ]
)
```

## Accessing `_chatRequest` in Tools

Tools receive the live `AiChatRequest` as `_chatRequest` in their arguments — useful for reading the current model, adding context, or adjusting behavior:

```javascript
contextTool = aiTool(
    "log_context",
    "Log information about the current request",
    ( args ) => {
        model   = args._chatRequest.getModel()
        history = args._chatRequest.getMessages()
        writeLog( "Tool called during #model# with #history.len()# messages" )
        return "Logged"
    }
)
```

## MCP Server Seeding (v3.0+)

Connect agents to MCP servers, either remote servers behind a URL or programs that run as a child process (see [Stdio Servers](#stdio-servers-child-processes)). The tools each server lists are fetched when the agent is built and made available to the agent:

```javascript
agent = aiAgent(
    name      : "ResearchAgent",
    mcpServers: [
        {
            url       : "http://localhost:3000/mcp",
            toolFilter: [ "web_search", "fetch_page" ]
        },
        {
            url       : "http://internal-tools/mcp",
            toolFilter: [ "query_crm" ]
        }
    ]
)

// The agent can use web_search, fetch_page, and query_crm from the MCP servers
response = agent.run( "Find recent news about BoxLang" )
```

You can also attach servers one at a time with `withMCPServer( server, config )`, where `server` is a URL, a stdio struct (`{ command: [ ... ] }`) or a pre-configured `IMCPClient`, or in one call with `withMCPServers( servers )`.

### MCP Server Options

Each server entry takes a `url` plus any of these options:

| Option             | Type     | What it does                                                                                                                                                                |
| ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `token`            | string   | Bearer token sent with every request                                                                                                                                        |
| `user`, `password` | string   | Basic authentication                                                                                                                                                        |
| `headers`          | struct   | Extra HTTP headers                                                                                                                                                          |
| `timeout`          | numeric  | Request timeout in milliseconds                                                                                                                                             |
| `toolFilter`       | array    | Expose **only** these tools. Without it every tool the server lists is exposed                                                                                              |
| `prefix`           | string   | Expose tools as `prefix__name`, so two servers cannot clash                                                                                                                 |
| `urlGuard`         | function | Called with the URL before every request. Return `false` or throw to refuse it                                                                                              |
| `redirects`        | boolean  | `false` stops the client from following redirects                                                                                                                           |
| `maxResponseBytes` | numeric  | Refuse an answer longer than this many characters                                                                                                                           |
| `handshake`        | boolean  | Send the MCP `initialize` handshake before the first call                                                                                                                   |
| `oauth`            | struct   | Sign in to the server with OAuth: `{ redirectUri, store, subject, scopes, ... }`. See [OAuth Sign In](https://ai.ortusbooks.com/model-context-protocol-mcp/client/oauth.md) |
| `httpVersion`      | string   | `HTTP/2` (the default) or `HTTP/1.1`. Use `HTTP/1.1` for a server on a plain http address that does not handle the HTTP/2 upgrade                                           |

> 💡 The older `toolNames` key shown in earlier examples is ignored. It never limited which tools the agent can call. Use `toolFilter`. Likewise the bearer token option is `token`.

### Stdio Servers (Child Processes)

Many MCP servers are programs you launch, such as `bxplaywright mcp` or `npx -y @modelcontextprotocol/server-github`. Give the entry a `command` instead of a `url`:

```javascript
agent = aiAgent(
    name      : "BrowserAgent",
    model     : aiModel( provider: "openai" ),
    mcpServers: [
        {
            command   : [ "bxplaywright", "mcp" ],
            env       : { HEADLESS: "true" },
            prefix    : "browser",
            toolFilter: [ "browser_visit", "browser_click" ]
        }
    ]
)

response = agent.run( "Open boxlang.io and tell me the title of the page" )

// Shut the child processes down when you are done
agent.closeMCPServers()
```

The same works with `withMCPServer( { command: [ ... ] }, { prefix: "browser" } )` and `withMCPServers( [ ... ] )`, and the list can mix URLs and commands.

| Option                 | Type     | What it does                                                                                   |
| ---------------------- | -------- | ---------------------------------------------------------------------------------------------- |
| `command`              | array    | **Required.** The executable followed by its arguments, one element each. Never a shell string |
| `env`                  | struct   | Environment variables added to the child process                                               |
| `cwd`                  | string   | Working directory of the child process                                                         |
| `inheritEnv`           | boolean  | `false` starts the child with only `env`. Default `true`                                       |
| `maxRestarts`          | numeric  | How many times in a row a dead server is started again. Default `2`                            |
| `commandGuard`         | function | `( command ) => boolean`, called before every launch. Return `false` to refuse it              |
| `timeout`              | numeric  | Milliseconds to wait for each answer. Default `30000`                                          |
| `toolFilter`, `prefix` |          | Same as for URL servers                                                                        |

* The options that only exist for HTTP (`token`, `user`, `password`, `headers`, `urlGuard`, `redirects`, `maxResponseBytes`, `httpVersion`, `handshake`, `oauth`) throw `InvalidArgument` for a stdio server, and so does any option the server does not have, such as the typo `commandGaurd`. `prefix` and `toolFilter` can sit in the same struct as the `command`.
* The first call waits for the launch and the handshake, and `timeout` covers that wait. A program that downloads itself on its first run (`npx -y ...`) can need more than the default 30 seconds: use a larger `timeout`, for example `120000`.
* A server that cannot start, exits at once or fails the handshake is written to the `ai` log and the agent carries on without its tools. A command **refused** by the `mcp.stdio.allowedCommands` setting or by `commandGuard` throws `MCPCommandRefused` instead.
* `closeMCPServers()` closes the clients the agent built itself. A client you pass in ready-made is yours to close.

{% hint style="warning" %}
A stdio server is a program that runs on your machine with your permissions. Do not build the `command` from user input. See the [security section](https://ai.ortusbooks.com/model-context-protocol-mcp/client/stdio.md#security) of the stdio guide for the allow list and the command guard.
{% endhint %}

See [MCP Stdio Client](https://ai.ortusbooks.com/model-context-protocol-mcp/client/stdio.md) for the lifecycle, restarts, timeouts and logging.

### Keep Servers From Clashing: `prefix`

Two servers can each offer a tool called `search`, and the model cannot tell them apart. A prefix fixes that. The model sees `boxlang__search` and `coldbox__search`, and each server still receives the original name `search`:

```javascript
agent = aiAgent( name: "DocsAgent" )
    .withMCPServer( "https://boxlang.example.com/mcp", { prefix: "boxlang" } )
    .withMCPServer( "https://coldbox.example.com/mcp", { prefix: "coldbox" } )
```

### Expose Only the Safe Tools: `toolFilter`

A server may offer a tool that writes data, for example `sendFeedback`. Name the tools you accept and the model never sees the rest:

```javascript
agent = aiAgent( name: "DocsAgent" )
    .withMCPServer(
        "https://boxlang.example.com/mcp",
        { toolFilter: [ "searchDocumentation", "getPage" ] }
    )
```

### Limit What a Server Can Reach

When server addresses come from users or settings, add a guard, turn redirects off and cap the answer size:

```javascript
agent = aiAgent( name: "SafeAgent" )
    .withMCPServer(
        userSuppliedUrl,
        {
            urlGuard        : ( url ) => !isPrivateAddress( url ),
            redirects       : false,
            maxResponseBytes: 200000,
            timeout         : 10000
        }
    )
```

`isPrivateAddress()` stands for your own check, BoxLang does not ship one. A refused URL means the tools of that server are not added, and the failure is written to the `ai` log. See [Controlling What a Client Can Reach](https://ai.ortusbooks.com/model-context-protocol-mcp/client.md#controlling-what-a-client-can-reach) for how each option works. To decide per call whether a tool may run, use [middleware](https://github.com/ortus-boxlang/bx-ai-docs/tree/v2.x/main-components/middleware.md).

### MCP Authentication

```javascript
agent = aiAgent(
    name      : "SecureAgent",
    mcpServers: [
        {
            url       : "https://tools-server/mcp",
            toolFilter: [ "search" ],
            token     : server.bearerToken,
            headers   : { "X-Tenant-ID": "acme" }
        }
    ]
)
```

## Dynamic Tool Assignment

```javascript
function getToolsForRole( required string userRole ) {
    if ( userRole == "admin" ) {
        return aiToolRegistry().resolveTools( [ "admin_tool", "user_tool", "report_tool" ] )
    }
    return aiToolRegistry().resolveTools( [ "user_tool" ] )
}

agent = aiAgent( name: "ContextAgent" )
    .setTools( getToolsForRole( currentUser.role ) )
```

## Related Pages

* [Tool Registry](https://ai.ortusbooks.com/main-components/tool-registry.md) — Full registry reference
* [AI Tools](https://ai.ortusbooks.com/main-components/tools.md) — `aiTool()` BIF reference
* [Skills](https://ai.ortusbooks.com/main-components/agents/skills.md) — Injecting knowledge vs. calling tools
* [MCP Server](https://ai.ortusbooks.com/model-context-protocol-mcp/server.md) — Building your own MCP server
* [MCP Client](https://ai.ortusbooks.com/model-context-protocol-mcp/client.md) — Consuming MCP servers directly


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://ai.ortusbooks.com/main-components/agents/tools-and-mcp.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
