Tool Development

Create custom tools to extend Gemini CLI's capabilities. Learn how to design, implement, test, and deploy tools that integrate seamlessly with AI conversations.

Development Process

Step-by-step guide to creating custom tools

1

Define Tool Interface

Create the tool definition with parameters and description

Example:

const toolDefinition = {
  name: 'calculate_age',
  description: 'Calculate age based on birth date',
  parameters: {
    type: 'object',
    properties: {
      birthDate: {
        type: 'string',
        format: 'date',
        description: 'Birth date in YYYY-MM-DD format'
      },
      currentDate: {
        type: 'string',
        format: 'date',
        description: 'Current date (optional, defaults to today)'
      }
    },
    required: ['birthDate']
  }
};
2

Implement Tool Logic

Write the execution function that performs the tool's task

Example:

const executeFunction = async ({ birthDate, currentDate }) => {
  try {
    const birth = new Date(birthDate);
    const current = currentDate ? new Date(currentDate) : new Date();
    
    if (birth > current) {
      throw new Error('Birth date cannot be in the future');
    }
    
    const ageMs = current.getTime() - birth.getTime();
    const ageYears = Math.floor(ageMs / (1000 * 60 * 60 * 24 * 365.25));
    
    return `Age: ${ageYears} years old`;
  } catch (error) {
    return `Error: ${error.message}`;
  }
};
3

Register the Tool

Add the tool to Gemini CLI's tool registry

Example:

import { GeminiCLI } from '@google/generative-ai-cli';

const cli = new GeminiCLI();

// Create complete tool
const ageTool = {
  ...toolDefinition,
  execute: executeFunction
};

// Register the tool
cli.registerTool(ageTool);

// Verify registration
console.log('Registered tools:', cli.listTools().map(t => t.name));
4

Test the Tool

Test your tool to ensure it works correctly

Example:

// Test the tool directly
const result = await cli.executeTool('calculate_age', {
  birthDate: '1990-05-15'
});
console.log(result); // "Age: 34 years old"

// Test with AI
const response = await cli.ask(
  "How old would someone born on May 15, 1990 be today?",
  { tools: ['calculate_age'] }
);

Tool Template

Use this template as a starting point for your custom tools

import { Tool, ToolDefinition } from '@google/generative-ai-cli';

export const myCustomTool: ToolDefinition = {
  name: 'my_custom_tool',
  description: 'Description of what this tool does',
  parameters: {
    type: 'object',
    properties: {
      // Define your parameters here
      input: {
        type: 'string',
        description: 'Input parameter description'
      }
    },
    required: ['input']
  },
  execute: async (params) => {
    try {
      // Your tool logic here
      const { input } = params;
      
      // Process the input
      const result = processInput(input);
      
      // Return the result
      return result;
    } catch (error) {
      // Handle errors gracefully
      return `Error: ${error.message}`;
    }
  }
};

function processInput(input: string): string {
  // Your processing logic
  return `Processed: ${input}`;
}

Best Practices

Guidelines for creating effective and reliable tools

Tool Design

  • Keep tools focused on a single responsibility
  • Use clear, descriptive names and descriptions
  • Define comprehensive parameter schemas
  • Include examples in parameter descriptions
  • Handle edge cases gracefully

Error Handling

  • Always wrap execution in try-catch blocks
  • Return meaningful error messages
  • Validate input parameters
  • Handle network timeouts and failures
  • Log errors for debugging

Performance

  • Implement async operations properly
  • Add timeout handling for long operations
  • Cache results when appropriate
  • Minimize external dependencies
  • Use streaming for large responses

Security

  • Validate and sanitize all inputs
  • Avoid executing arbitrary code
  • Limit file system access
  • Use secure API endpoints
  • Handle sensitive data carefully

Testing Your Tools

Ensure your tools work correctly before deployment

Unit Testing

// Test tool execution directly
import { myCustomTool } from './my-tool';

describe('myCustomTool', () => {
  test('should process input correctly', async () => {
    const result = await myCustomTool.execute({
      input: 'test data'
    });
    
    expect(result).toBe('Processed: test data');
  });
  
  test('should handle errors gracefully', async () => {
    const result = await myCustomTool.execute({
      input: null
    });
    
    expect(result).toMatch(/Error:/);
  });
});

Integration Testing

// Test tool with Gemini CLI
import { GeminiCLI } from '@google/generative-ai-cli';

const cli = new GeminiCLI();
cli.registerTool(myCustomTool);

// Test tool registration
const tools = cli.listTools();
expect(tools.find(t => t.name === 'my_custom_tool')).toBeDefined();

// Test tool execution
const result = await cli.executeTool('my_custom_tool', {
  input: 'test'
});
expect(result).toBeDefined();

Common Tool Patterns

Reusable patterns for different types of tools

API Integration Tool

Pattern for tools that integrate with external APIs

const apiTool = {
  name: 'api_call',
  description: 'Make API calls to external services',
  parameters: {
    type: 'object',
    properties: {
      endpoint: { type: 'string', description: 'API endpoint URL' },
      method: { type: 'string', enum: ['GET', 'POST'], default: 'GET' },
      data: { type: 'object', description: 'Request payload' }
    },
    required: ['endpoint']
  },
  execute: async ({ endpoint, method = 'GET', data }) => {
    try {
      const response = await fetch(endpoint, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: data ? JSON.stringify(data) : undefined
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      return await response.json();
    } catch (error) {
      return `API Error: ${error.message}`;
    }
  }
};

Data Processing Tool

Pattern for tools that process and transform data

const processingTool = {
  name: 'data_processor',
  description: 'Process and transform data',
  parameters: {
    type: 'object',
    properties: {
      data: { type: 'array', description: 'Data to process' },
      operation: { 
        type: 'string', 
        enum: ['sort', 'filter', 'map', 'reduce'],
        description: 'Operation to perform'
      },
      criteria: { type: 'string', description: 'Processing criteria' }
    },
    required: ['data', 'operation']
  },
  execute: async ({ data, operation, criteria }) => {
    try {
      switch (operation) {
        case 'sort':
          return data.sort();
        case 'filter':
          return data.filter(item => item.includes(criteria));
        case 'map':
          return data.map(item => `${criteria}: ${item}`);
        case 'reduce':
          return data.reduce((acc, item) => acc + item, '');
        default:
          throw new Error(`Unknown operation: ${operation}`);
      }
    } catch (error) {
      return `Processing Error: ${error.message}`;
    }
  }
};

Related Resources

Explore more about tools and development