AgentSea

Concept

Tools

Tools extend agent capabilities by letting agents interact with external systems, perform calculations and manipulate data.

01What are tools?

A tool is a function an agent can call. The model decides when to call it. Each tool has:

  • A unique name and a description the model reads
  • A Zod schema for its parameters, checked before the tool runs
  • An execute function that receives the validated parameters and a context, and returns a result

02Built-in tools

AgentSea includes built-in tools, ready to register:

calculatorTool
Basic arithmetic calculations.
httpRequestTool
HTTP requests to external APIs, with retry configured.
fileReadTool, fileWriteTool, fileListTool
Read, write and list files and directories.
textSummaryTool
Word and character counts, and extraction of emails, URLs and numbers.
stringTransformTool
Uppercase, lowercase, titlecase, reverse, trim and slug.
figmaGetFileTool, figmaGetNodesTool, figmaGetImagesTool, figmaGetCommentsTool, figmaPostCommentTool
Read Figma files, nodes, images and comments, and post comments.
n8nExecuteWorkflowTool, n8nGetExecutionTool, n8nListWorkflowsTool, n8nTriggerWebhookTool, n8nGetWorkflowTool
Run and inspect n8n workflows, and trigger webhooks.
shellExecuteTool, codeEditTool, globTool, grepTool
Coding tools: run shell commands, edit code, find files by pattern and search file contents.
gitStatusTool, gitDiffTool, gitAddTool, gitCommitTool, gitLogTool, gitBranchTool
Git status, diff, add, commit, log and branch.

03Using built-in tools

TS
import {
  Agent,
  AnthropicProvider,
  ToolRegistry,
  calculatorTool,
  httpRequestTool,
  fileReadTool,
  textSummaryTool,
} from '@lov3kaizen/agentsea-core';

const toolRegistry = new ToolRegistry();
toolRegistry.register(calculatorTool);
toolRegistry.register(httpRequestTool);
toolRegistry.register(fileReadTool);
toolRegistry.register(textSummaryTool);

const agent = new Agent(
  {
    name: 'tool-agent',
    description: 'Uses tools to answer questions',
    model: 'claude-sonnet-4-6',
    provider: 'anthropic',
    tools: [calculatorTool, httpRequestTool, fileReadTool, textSummaryTool],
  },
  new AnthropicProvider(),
  toolRegistry,
);

// The agent calls tools when the model asks for them
const response = await agent.execute(
  'Calculate 42 * 58 and fetch the JSON at https://api.example.com/stats',
  context,
);

04Creating custom tools

A custom tool is an object that matches the Tool type. The schema field is parameters, and it is a Zod schema.

TS
import { Tool } from '@lov3kaizen/agentsea-core';
import { z } from 'zod';

export const databaseQueryTool: Tool = {
  name: 'database_query',
  description: 'Execute SQL queries on the database',
  parameters: z.object({
    query: z.string().describe('SQL query to execute'),
    params: z.array(z.any()).optional().describe('Query parameters'),
  }),
  execute: async (input) => {
    const { query, params = [] } = input;
    try {
      const results = await db.query(query, params); // your database client
      return {
        success: true,
        data: results,
        message: `Query executed successfully. ${results.length} rows returned.`,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
};

toolRegistry.register(databaseQueryTool);

05Schema validation

Tool parameters are Zod schemas. The registry parses them before calling execute. Common patterns:

TS
import { z } from 'zod';

// Strings with constraints
const nameSchema = z.object({
  name: z.string().min(1).max(100).describe('User name'),
});

// Numbers with ranges
const ageSchema = z.object({
  age: z.number().int().min(0).max(120).describe('User age'),
});

// Enums
const statusSchema = z.object({
  status: z.enum(['active', 'inactive', 'pending']).describe('Status'),
});

// Optional fields
const updateSchema = z.object({
  id: z.string().describe('User ID'),
  email: z.string().email().optional().describe('New email'),
  phone: z.string().optional().describe('New phone number'),
});

// Arrays
const bulkSchema = z.object({
  ids: z.array(z.string()).describe('User IDs to process'),
});

// Nested objects
const addressSchema = z.object({
  user: z.object({
    name: z.string(),
    address: z.object({
      street: z.string(),
      city: z.string(),
      zip: z.string(),
    }),
  }),
});

06Async tools

Tools can be async and call external services. Return a plain object with the result:

TS
import { Tool } from '@lov3kaizen/agentsea-core';
import { z } from 'zod';

export const weatherTool: Tool = {
  name: 'get_weather',
  description: 'Get the current weather for a city',
  parameters: z.object({
    city: z.string().describe('City name'),
  }),
  execute: async ({ city }) => {
    const response = await fetch(
      `https://weather.example.com/current?city=${encodeURIComponent(city)}`,
    );
    const data = await response.json();
    return { success: true, data };
  },
};

07Error handling

Handle expected failures inside the tool and return them as data. The model can read the message and recover.

TS
import { Tool } from '@lov3kaizen/agentsea-core';
import { z } from 'zod';

export const apiCallTool: Tool = {
  name: 'api_call',
  description: 'Make a GET request to an API endpoint',
  parameters: z.object({
    endpoint: z.string().url(),
  }),
  execute: async (input) => {
    try {
      const response = await fetch(input.endpoint, {
        signal: AbortSignal.timeout(5000), // 5 second timeout
      });

      if (!response.ok) {
        return {
          success: false,
          error: `HTTP error ${response.status}: ${response.statusText}`,
        };
      }

      return { success: true, data: await response.json() };
    } catch (error) {
      if (error instanceof Error && error.name === 'TimeoutError') {
        return { success: false, error: 'Request timed out' };
      }
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
};

Note

The registry does not catch errors for you. If execute throws, the registry rethrows it as Tool execution failed: .... Return an error object for failures you expect, and reserve exceptions for failures the agent cannot act on.

08Tool registry

The registry holds the tools available to an agent:

TS
import { ToolRegistry, calculatorTool, httpRequestTool, fileReadTool } from '@lov3kaizen/agentsea-core';

const toolRegistry = new ToolRegistry();

// Register one tool, or several at once
toolRegistry.register(calculatorTool);
toolRegistry.registerMany([httpRequestTool, fileReadTool]);

// Look up a tool by name
const calculator = toolRegistry.get('calculator');

// Check whether a tool exists
const exists = toolRegistry.has('calculator');

// List all registered tools
const allTools = toolRegistry.getAll();

// Remove a tool (returns true if it was registered)
toolRegistry.unregister('calculator');

// Clear everything
toolRegistry.clear();
register(tool)
Adds one tool.
registerMany(tools)
Adds several tools.
get(name)
Returns the tool or undefined.
has(name)
Returns true when the tool is registered.
getAll()
Returns every registered tool.
unregister(name)
Removes a tool. Returns true if it was present.
clear()
Removes all tools.

09MCP tools

The Model Context Protocol (MCP) lets you import tools from external servers. The MCPRegistry starts each server and converts its tools to AgentSea tools:

TS
import { Agent, AnthropicProvider, MCPRegistry, ToolRegistry } from '@lov3kaizen/agentsea-core';

const mcpRegistry = new MCPRegistry();
const toolRegistry = new ToolRegistry();

await mcpRegistry.addServer({
  name: 'filesystem',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-filesystem', '/home/user'],
  transport: 'stdio',
});

await mcpRegistry.addServer({
  name: 'github',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  transport: 'stdio',
  env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! },
});

// Tools from all connected servers, converted to AgentSea tools
const mcpTools = mcpRegistry.getTools();
toolRegistry.registerMany(mcpTools);

const agent = new Agent(
  {
    name: 'mcp-agent',
    description: 'Uses filesystem and GitHub tools',
    model: 'claude-sonnet-4-6',
    provider: 'anthropic',
    tools: mcpTools,
  },
  new AnthropicProvider(),
  toolRegistry,
);

For transports, server options and reconnect behavior, see the MCP overview.

10Isomorphic tools

Isomorphic tools separate a tool's definition from its implementation. Define the input and output schemas once, then provide a server implementation, a client implementation or both. The input and output types come from the Zod schemas.

Tool definition

TS
import { toolDefinition } from '@lov3kaizen/agentsea-core';
import { z } from 'zod';

const getUserDef = toolDefinition({
  name: 'get_user',
  description: 'Get user information from the database',
  inputSchema: z.object({
    userId: z.string().describe('The user ID to look up'),
  }),
  outputSchema: z.object({
    name: z.string(),
    email: z.string().email(),
    createdAt: z.string(),
  }),
});

// Server implementation: direct database access
const getUserServer = getUserDef.server(async ({ userId }, context) => {
  const user = await db.users.findUnique({ where: { id: userId } });
  return {
    name: user.name,
    email: user.email,
    createdAt: user.createdAt.toISOString(),
  };
});

// Client implementation: call an API
const getUserClient = getUserDef.client(async ({ userId }) => {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
});

const agent = new Agent({
  // ...
  tools: [getUserServer.toTool()],
});

Quick helpers

serverTool, clientTool and hybridTool create a tool in one call:

TS
import { serverTool, clientTool, hybridTool } from '@lov3kaizen/agentsea-core';
import { z } from 'zod';

// Server-only tool
const calculateTool = serverTool({
  name: 'calculate',
  description: 'Perform arithmetic operations',
  inputSchema: z.object({
    operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
    a: z.number(),
    b: z.number(),
  }),
  outputSchema: z.object({ result: z.number() }),
  execute: async ({ operation, a, b }) => {
    switch (operation) {
      case 'add': return { result: a + b };
      case 'subtract': return { result: a - b };
      case 'multiply': return { result: a * b };
      case 'divide': return { result: a / b };
    }
  },
});

// Client-only tool, runs in the browser
const showNotification = clientTool({
  name: 'show_notification',
  description: 'Show a browser notification',
  inputSchema: z.object({ title: z.string(), body: z.string() }),
  outputSchema: z.object({ shown: z.boolean() }),
  execute: ({ title, body }) => {
    new Notification(title, { body });
    return { shown: true };
  },
});

// Hybrid tool with a server and a client implementation
const userTool = hybridTool({
  name: 'get_user',
  description: 'Get user information',
  inputSchema: z.object({ userId: z.string() }),
  outputSchema: z.object({ name: z.string(), email: z.string() }),
  server: async ({ userId }) => db.users.findUnique({ where: { id: userId } }),
  client: async ({ userId }) => (await fetch(`/api/users/${userId}`)).json(),
});

Built-in isomorphic tools

The calculator has an isomorphic definition, with calculatorDef, calculatorServer and calculatorClient exported:

TS
import { calculatorServer } from '@lov3kaizen/agentsea-core';

const tools = [calculatorServer.toTool()];

const result = await calculatorServer.execute(
  { operation: 'add', a: 5, b: 3 },
  context,
);
// { result: 8 }

Type helpers

TS
import type { ToolInput, ToolOutput } from '@lov3kaizen/agentsea-core';
import { calculatorDef, calculatorServer } from '@lov3kaizen/agentsea-core';

type CalcInput = ToolInput<typeof calculatorDef>;
type CalcOutput = ToolOutput<typeof calculatorDef>;

function runCalculation(input: CalcInput): Promise<CalcOutput> {
  return calculatorServer.execute(input, context);
}

Converting to legacy tools

Use toLegacyTool and toLegacyTools to pass isomorphic tools to code that expects the Tool type:

TS
import { toLegacyTool, toLegacyTools } from '@lov3kaizen/agentsea-core';

const legacyCalc = toLegacyTool(calculatorServer);
const legacyTools = toLegacyTools([calculatorServer, getUserServer]);

toolRegistry.registerMany(legacyTools);

11Best practices

  • Descriptive names: use clear names such as database_query, not db.
  • Detailed descriptions: the model chooses tools from their descriptions.
  • Validation: validate every input with a Zod schema.
  • Errors: return error objects for expected failures. Exceptions are rethrown by the registry.
  • Timeouts: set a timeout on every external call.
  • Idempotency: make tools idempotent where you can.
  • Side effects: state any side effects in the description.
  • Rate limits: limit calls to expensive operations.
  • Only relevant tools: give each agent only the tools its job needs.

12Next steps