Tool class for managing agent capabilities

This class represents an external integration or utility that extends agent capabilities in the Mosaia platform. Tools enable agents to interact with external services, process data, and perform specialized tasks through well-defined interfaces.

Features:

  • Schema validation
  • Environment management
  • API integration
  • Data transformation
  • Error handling

Tools provide:

  • External service integration
  • Data processing capabilities
  • API access management
  • Input/output validation
  • Environment configuration

Common tool types:

  • API integrations
  • Database connectors
  • File processors
  • Data transformers
  • Service clients

Basic API tool:

import { Tool } from 'mosaia-node-sdk';

// Create a weather API tool
const weatherTool = new Tool({
name: 'weather-api',
friendly_name: 'Weather Service',
short_description: 'Get weather forecasts',
tool_schema: JSON.stringify({
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name or coordinates'
},
units: {
type: 'string',
enum: ['metric', 'imperial'],
default: 'metric'
}
},
required: ['location']
}),
required_environment_variables: ['WEATHER_API_KEY'],
source_url: 'https://api.weather.com'
});

await weatherTool.save();

Database tool:

// Create a database query tool
const dbTool = new Tool({
name: 'db-query',
friendly_name: 'Database Query',
short_description: 'Execute database queries',
tool_schema: JSON.stringify({
type: 'object',
properties: {
query: {
type: 'string',
description: 'SQL query to execute'
},
params: {
type: 'array',
items: { type: 'string' },
description: 'Query parameters'
},
timeout: {
type: 'number',
default: 30000
}
},
required: ['query']
}),
required_environment_variables: [
'DB_HOST',
'DB_USER',
'DB_PASS',
'DB_NAME'
],
metadata: {
type: 'database',
engine: 'postgresql',
version: '14',
max_connections: 10
}
});

if (dbTool.isActive()) {
console.log('Database tool ready');
console.log('Schema:', JSON.parse(dbTool.tool_schema));
}

Hierarchy (View Summary)

Constructors

  • Creates a new tool configuration

    Initializes a tool that extends agent capabilities through external integrations. Tools provide a standardized interface for agents to interact with external services and process data.

    Parameters

    • data: Partial<ToolInterface>

      Configuration data including: - name: Tool identifier - friendly_name: Display name - short_description: Brief description - tool_schema: JSON Schema for inputs - required_environment_variables: Required env vars - source_url: Integration endpoint - metadata: Additional tool data

    • Optionaluri: string

      Optional custom URI path for the tool endpoint

    Returns Tool

    Basic file processor:

    const fileTool = new Tool({
    name: 'file-processor',
    friendly_name: 'File Processor',
    short_description: 'Process and transform files',
    tool_schema: JSON.stringify({
    type: 'object',
    properties: {
    file_path: {
    type: 'string',
    description: 'Path to input file'
    },
    output_format: {
    type: 'string',
    enum: ['json', 'csv', 'xml'],
    default: 'json'
    }
    },
    required: ['file_path']
    })
    });

    API integration:

    const apiTool = new Tool({
    name: 'api-client',
    friendly_name: 'API Integration',
    short_description: 'Make API requests',
    tool_schema: JSON.stringify({
    type: 'object',
    properties: {
    method: {
    type: 'string',
    enum: ['GET', 'POST', 'PUT', 'DELETE']
    },
    endpoint: {
    type: 'string',
    pattern: '^/'
    },
    headers: {
    type: 'object',
    additionalProperties: true
    },
    body: {
    type: 'object',
    additionalProperties: true
    }
    },
    required: ['method', 'endpoint']
    }),
    required_environment_variables: [
    'API_KEY',
    'API_SECRET'
    ],
    source_url: 'https://api.service.com',
    metadata: {
    version: '1.0',
    rate_limit: 100,
    timeout: 5000
    }
    }, '/integrations/tool');

Accessors

  • get image(): Image

    Get the image functionality for this tool

    This getter provides access to the tool's image operations through the Image class. It allows for image uploads and other image-related operations specific to this tool.

    Returns Image

    A new Image instance configured for this tool

    const updatedTool = await tool.image.upload<Tool, GetToolPayload>(file);
    

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns ToolInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<ToolInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    • updates: Partial<ToolInterface>

      Object containing properties to update

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<ToolInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }
  • Like or unlike this tool

    Toggles the like status of this tool. If the tool is already liked, it will be unliked, and vice versa.

    Returns Promise<Tool>

    Promise that resolves to the updated tool instance

    await tool.like();
    console.log('Tool liked:', tool.liked);

    When API request fails