Skip to content

Tools

Updated

A language model only produces text. A tool lets it do more: look up today’s opening hours, fetch the weather, take the visitor to another wing of the museum. You write a tool as a small script of ordinary functions, declare each one with #pragma tool, and put the script in an AI Tool component on the agent. While it answers, the model can decide to call a tool by name with some input; the tool runs and its result goes back to the model, which uses it in its reply.

  • You have an agent; see Creating an agent.
  • Tool scripts use the same language as Behaviors, with their own directive. Read Scripting for the basics of directives such as #pragma and #define.
  • The model decides when to call a tool from its description. Telling it in the persona or a Skill when to use each tool helps a lot.

The AI Tool (comp-ai-tool, AIToolComponent) holds one tool script. An agent can carry several.

Prop Type Default Description
name string 'Tool' A label for the editor, at most 50 characters. The model never sees it: the callable names come from the script.
code string a starter script The tool script: one or more #pragma tool declarations and their functions.
  • In play, each tool script is compiled in a scope of its own and its tools become callable by the agent.
  • Switched off (the component, its entity or an ancestor), the tool stays known but does nothing when called. setEnabled(on) switches it.
  • Removed or unloaded with its scene, the tool goes away.

Each tool is one #pragma tool(...) directive that names a function in the same script:

#pragma tool(name = "…", description = "…", permissions = [ … ], parameters = { … }, action = fn)
Option Required Description
name yes How the model calls the tool: 1 to 64 letters, digits, _ or -, such as opening_hours. Unique among all running tools.
description yes What the tool does and when to use it. The model reads it to decide whether to call the tool.
action yes The name of the function that runs the tool.
permissions no Which modules the script may use: any of network, scenes, imports. Default [].
parameters no The input fields: field = Type, or field = { type = Type, default = …, min = …, max = … }. Omit it for a tool without input.

Parameter types are Number, Slider, Integer, Boolean, String, Color, Dropdown, Vector2, Vector3, Quaternion, Object3D, and Array<…> of them.

The action receives one plain object: the input the model gave, checked against parameters, with missing fields set to their defaults. Whatever it returns, or resolves to, is the tool’s result. Throwing an Error reports a failure to the model, which can then tell the visitor.

A script may declare several tools. It compiles and runs once, so its tools share helper functions and variables. Use separate AI Tool components when tools need separate state or separate permissions.

A tool script’s scope holds only the language itself: Math, JSON, Promise, Date, Intl, typed arrays and the like. There are no timers, no logging and no page access, and a tool never sees Behaviors: it has no self, no slots, and no on or emit. Each permission adds one module:

Permission Adds
network HttpRequest, for web requests.
scenes Scenes: list(), active(), load(id, options?), unload(id).
imports #pragma import(Name = "https://…"), to load a module from a URL.
Allowed in a tool script Not allowed
#pragma tool, #pragma import(Name = "url") with imports, #define, #undef, #if, #ifdef, #ifndef, #elif, #else, #endif, #error, #warning #pragma lifecycle, #pragma slot, #pragma enum, #pragma type, #pragma export, #pragma dont_unload, #editor_begin, #editor_end, #editor_only

#pragma tool is an error in a Behavior script: tools live only in AI Tool components.

The agent reports what its tools do through its Signal Emitters, as activity events:

Event When
AIAgent::tool-definition-loaded, AIAgent::tool-definition-failed A tool’s declaration was offered to the model, or could not be.
AIAgent::tool-requested The model asked to call a tool.
AIAgent::tool-completed, AIAgent::tool-failed, AIAgent::tool-cancelled The call returned, threw, or was cancelled.
AIAgent::tool-updated The agent’s tools changed.
ToolInventory.jx
#pragma lifecycle(startup)
function startup() {
const tools = findEntity('Guide').getComponents(AIToolComponent);
if (tools.length === 0) return log('The guide has no tools.');
for (const tool of tools) {
const declared = tool.props.code.split('pragma tool(').length - 1;
log(`"${tool.props.name}": ${declared} tool(s), ${tool.enabled ? 'on' : 'off'}`);
}
}
  • A quick check while building a scene: each component’s label, how many tools its script declares, and whether it is switched on.
  • props.code is the tool script as text; the Behavior only reads it and never runs it.
OpeningHours.tool.jx
// AI Tool script on the agent "Guide".
#pragma tool(
name = "opening_hours",
description = "The museum's opening hours for a weekday, such as monday or saturday.",
parameters = {
day = String
},
action = openingHours
)
const HOURS = {
monday: 'closed',
tuesday: '10:00 to 18:00',
wednesday: '10:00 to 18:00',
thursday: '10:00 to 21:00',
friday: '10:00 to 18:00',
saturday: '09:00 to 19:00',
sunday: '09:00 to 19:00',
};
function openingHours(input) {
const day = input.day.trim().toLowerCase();
if (!(day in HOURS)) throw new Error('Unknown day: ' + input.day);
return { day, hours: HOURS[day] };
}
  • The description tells the model what the tool does and what input it expects.
  • The action returns a plain object; the model turns it into a sentence for the visitor.
  • Throwing reports a clear failure, so the model can ask the visitor which day they meant.
MuseumTools.tool.jx
// AI Tool script on the agent "Guide". Its tools combine the network and scenes permissions.
#define WEATHER_URL "https://api.example.com/weather"
#pragma tool(
name = "current_weather",
description = "The current weather in a city: temperature in Celsius and a short summary.",
permissions = [network],
parameters = {
city = String,
units = { type = String, default = "metric" }
},
action = currentWeather
)
#pragma tool(
name = "list_wings",
description = "The museum wings the visitor can go to, with their ids.",
permissions = [scenes],
action = listWings
)
#pragma tool(
name = "go_to_wing",
description = "Take the visitor to a museum wing. Use an id from list_wings.",
permissions = [scenes],
parameters = {
id = String
},
action = goToWing
)
async function currentWeather(input) {
const query = new URLSearchParams({ city: input.city, units: input.units });
const data = await HttpRequest.get(WEATHER_URL + '?' + query).json();
return { temperature: data.temperature, summary: data.summary };
}
function listWings() {
return Scenes.list().filter((scene) => scene.id.startsWith('wing-'));
}
async function goToWing(input) {
if (!listWings().some((scene) => scene.id === input.id)) throw new Error('Unknown wing: ' + input.id);
await Scenes.load(input.id);
return 'Now in ' + input.id;
}
  • One script declares three tools that share the listWings helper.
  • units has a default, so the model may leave it out.
  • go_to_wing checks the id against list_wings before loading, so a made-up id fails cleanly instead of loading nothing.
  • Then tell the model when to use them, for example in the persona: “When the visitor asks about the weather, call current_weather. To move the visitor, call list_wings, then go_to_wing.”
ToolActivity.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with AI Tools and a Signal Emitter on 'guide:ai'.
// A UI Label named "Guide Status" shows what the guide is doing.
function startup() {
const status = findEntity('Guide Status').getComponent(UILabelComponent);
on('guide:ai', (event) => {
switch (event.eventType) {
case EventType.AIAgent.ToolRequested:
status.setProps({ text: 'Looking that up…' });
break;
case EventType.AIAgent.ToolFailed:
status.setProps({ text: 'That did not work.' });
break;
case EventType.AIAgent.ToolDefinitionFailed:
log('A tool could not be offered to the model. Check its #pragma tool declaration.');
break;
case EventType.AIAgent.Idle:
status.setProps({ text: '' });
break;
}
});
}
  • Tool calls can take a moment (a web request, a scene load); the label tells the visitor something is happening.
  • ToolDefinitionFailed is the event to watch while writing a tool: it signals a declaration the model could not use.
  • Idle marks the end of the turn, the right moment to clear the status.
StaffMode.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with an AI Persona and two AI Tools labelled
// "Visitor Tools" and "Staff Tools" (the second saved disabled), and a UI Switch
// "Staff mode" with a Signal Emitter on 'guide/staff'.
const VISITOR = 'You are the gallery guide. Help visitors find works and plan their visit.';
const STAFF = 'You assist museum staff. You may reset exhibits with the staff tools when asked.';
function startup() {
const guide = findEntity('Guide');
const tools = guide.getComponents(AIToolComponent);
const staffTools = tools.find((tool) => tool.props.name === 'Staff Tools');
const persona = guide.getComponent(AIPersonaComponent);
if (!staffTools) return log('No "Staff Tools" component on the guide.');
on('guide/staff', (event) => {
if (event.eventType !== EventType.UISwitch.Change) return;
staffTools.setEnabled(event.data.checked);
persona.setProps({ instructions: event.data.checked ? STAFF : VISITOR });
});
}
  • getComponents(AIToolComponent) lists every tool component; the editor label in props.name tells them apart.
  • A disabled tool does nothing when called, so switching it off is a simple way to withhold powerful actions.
  • Changing the instructions at the same time keeps the model’s expectations in line with what it can actually do.
  • A vague description. The model decides from the description alone. Say what the tool returns and when to use it.
  • Missing permissions. A tool that calls HttpRequest without network, or Scenes without scenes, finds them undefined. Declare what each tool needs.
  • Expecting Behavior globals. Tools have no log, findEntity, on, emit or self. They return data; Behaviors react through the agent’s events.
  • Duplicate tool names. Each name must be unique among all running tools, across agents too.
  • Putting #pragma tool in a Behavior. It is an error there. Put tool code in an AI Tool component.