Skip to content

Custom Tools

Custom Tools

Tools are functions that agents can call during execution. Define them in agents/tools/ and reference them by name in your agent definitions.

Defining a Tool

agents/tools/search-kb.ts
import { defineTool } from '@kernova/framework';
export default defineTool({
name: 'search-kb',
description: 'Search the company knowledge base for relevant articles',
parameters: {
query: {
type: 'string',
description: 'The search query',
required: true,
},
limit: {
type: 'number',
description: 'Maximum results to return',
default: 5,
},
},
execute: async ({ query, limit }, ctx) => {
ctx.log(`Searching KB for: ${query}`);
// Your implementation here
const results = await fetch(`https://api.mycompany.com/kb/search?q=${query}&limit=${limit}`);
return await results.json();
},
});

Tool Discovery

Tools are auto-discovered from these directories:

agents/tools/ ← Primary location
tools/ ← Alternative location

Any .ts or .js file that exports a defineTool() result will be registered.

Using Tools in Agents

Reference tools by their name field:

agents/support.agent.ts
export default defineAgent({
name: 'Support',
instructions: '...',
tools: ['search-kb', 'create-ticket', 'send-email'],
});

The agent’s LLM will see the tool descriptions and decide when to call them.

Tool Parameters

Parameter types supported:

TypeDescriptionExample
stringText input"search query"
numberNumeric value5, 3.14
booleanTrue/falsetrue
arrayList of values["tag1", "tag2"]
objectNested structure{ "key": "value" }
parameters: {
query: { type: 'string', description: 'Search query', required: true },
sort: { type: 'string', description: 'Order', enum: ['newest', 'relevance'], default: 'relevance' },
maxResults: { type: 'number', description: 'Max results', default: 10 },
includeArchived: { type: 'boolean', description: 'Include archived items' },
tags: { type: 'array', description: 'Filter by tags', items: { type: 'string' } },
}
FieldDescription
typeOne of the types above
descriptionShown to the model: say what the value means and what format you expect
requiredThe model must provide it
defaultUsed when the model leaves it out
enumThe only values allowed (strings). The model sees the list
itemsFor arrays, the type of each item (default string)

Typed arguments

execute gets its argument types from parameters, so there’s nothing to cast:

export default defineTool({
name: 'search-kb',
description: 'Search the knowledge base',
parameters: {
query: { type: 'string', description: 'Search query', required: true },
sort: { type: 'string', description: 'Order', enum: ['newest', 'relevance'], default: 'relevance' },
maxResults: { type: 'number', description: 'Max results' },
},
execute: async ({ query, sort, maxResults }) => {
// query: string, sort: 'newest' | 'relevance', maxResults: number | undefined
},
});

Required parameters and parameters with a default are always present; the others may be undefined. To type the arguments yourself instead, pass a type: defineTool<{ query: string }>({ ... }).

Arguments are checked before your tool runs

Models don’t always send what the schema asks for. Before execute runs, Kernova checks the arguments against parameters:

  • Missing required parameters, and values that can’t be converted, go back to the model as an error such as Invalid arguments: "sort" must be one of: newest, relevance (got "date")., and execute isn’t called. The model then usually retries correctly.
  • Numbers and booleans sent as text ("10", "true") are converted; arrays can arrive as JSON or as comma-separated text; enum values match regardless of case.
  • Defaults fill in missing parameters.

Tool Context

Every tool receives a context object as the second argument:

execute: async (params, ctx) => {
// Environment variables (from project secrets)
const apiKey = ctx.env.MY_API_KEY;
// Log messages (visible in monitoring)
ctx.log('Starting search...');
// User info (if available)
const userId = ctx.user?.id;
// Thread ID (`trigger_<name>` for trigger runs)
const thread = ctx.threadId;
// Whether a person asked for this, or a trigger is running on its own
if (ctx.autonomous) {
ctx.log(`Running for trigger ${ctx.trigger}`);
}
// Persistent storage, shared by the app's tools
const saved = await ctx.store.get<string[]>('search-kb:recent');
}

ctx.autonomous is true for trigger and schedule runs, and false for requests to an agent. Use it to ask more of actions nobody asked for, for example letting an agent send email when a user asks but not on its own:

execute: async ({ to, body }, ctx) => {
if (ctx.autonomous && !settings.autoSendEmail) {
return { blocked: true, error: 'Sending email on my own is turned off.' };
}
// ...
}
FieldDescription
envEnvironment variables
log(message)Log a message
user{ id } of the user the request is for, when known
threadIdConversation thread (trigger_<name> for trigger runs)
autonomoustrue for trigger and schedule runs, false for requests
triggerName of the trigger that started the run
agentRoute of the agent that called the tool
storePersistent key-value storage (below)

Saving data with ctx.store

Tools that remember things (habits, notes, settings, what they’ve already processed) can keep them in ctx.store, with no database code:

export default defineTool({
name: 'track-habit',
description: 'Log a habit for today, or list the last week',
parameters: {
action: { type: 'string', description: 'log or list', required: true, enum: ['log', 'list'] },
habit: { type: 'string', description: 'The habit, e.g. "exercise"' },
},
execute: async ({ action, habit }, ctx) => {
const log = (await ctx.store.get<Array<{ habit: string; date: string }>>('track-habit:log')) ?? [];
if (action === 'list') return { log: log.slice(-7) };
if (!habit) return { error: 'Which habit?' };
log.push({ habit, date: new Date().toISOString().slice(0, 10) });
await ctx.store.set('track-habit:log', log);
return { logged: true };
},
});
MethodDescription
get<T>(key)The value, or undefined
set(key, value)Saves any JSON-serializable value
delete(key)Removes it; true if it existed
list(prefix?)Keys starting with prefix, sorted

Values are kept in PostgreSQL when your app has a database (memory.url in kernova.config.ts, or DATABASE_URL), in a table named kernova_tool_store. Without one, they’re in kernova-data/tool-store.json, which suits local development; on a host whose disk is wiped on each deploy, set a database. The store is shared by all of the app’s tools, so start keys with your tool’s name.

Testing tools

runTool runs a tool the way an agent would, with the same argument checks, an in-memory store, and the log captured:

import { runTool } from '@kernova/framework';
import trackHabit from '../agents/tools/track-habit';
test('logs a habit', async () => {
const { result, store, logs } = await runTool(trackHabit, { action: 'log', habit: 'exercise' });
expect(result).toEqual({ logged: true });
expect(await store.get('track-habit:log')).toHaveLength(1);
});
test('refuses an unknown action without running', async () => {
const { result } = await runTool(trackHabit, { action: 'delete' });
expect(result).toEqual({ error: 'Invalid arguments: "action" must be one of: log, list (got "delete").' });
});

Pass a store to share data between runs (memoryToolStore({ ... }) starts one with values), and request details such as { threadId, user, autonomous: true } as the third argument.

Tool Options

OptionTypeDefaultDescription
namestringrequiredUnique tool name
descriptionstringrequiredDescription shown to the LLM
parametersobjectrequiredParameter schema
executefunctionrequiredImplementation
rateLimitnumber—Max calls per minute
requiresConfirmationbooleanfalseRequire user approval before executing

Examples

Database Query Tool

export default defineTool({
name: 'query-users',
description: 'Query the user database',
parameters: {
email: { type: 'string', description: 'Filter by email' },
plan: { type: 'string', description: 'Filter by plan', enum: ['free', 'pro', 'enterprise'] },
},
execute: async ({ email, plan }) => {
return await db.users.findMany({ where: { email, plan } });
},
});

HTTP API Tool

export default defineTool({
name: 'get-weather',
description: 'Get current weather for a city',
parameters: {
city: { type: 'string', description: 'City name', required: true },
},
execute: async ({ city }, ctx) => {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${ctx.env.WEATHER_API_KEY}`
);
return await res.json();
},
});

Confirmation-Required Tool

export default defineTool({
name: 'delete-account',
description: 'Permanently delete a user account',
parameters: {
userId: { type: 'string', description: 'User ID to delete', required: true },
},
requiresConfirmation: true,
execute: async ({ userId }) => {
await db.users.delete({ where: { id: userId } });
return { deleted: true };
},
});