npm package: @rodgerai/tools
Description: Pre-built tools for Rodger.ai agents
Author: Rodger.ai
Latest version: 2.0.0

# @rodger/tools

Production-ready tool library for Rodger.ai agents. Pre-built, type-safe tools that work seamlessly with @rodger/core and @rodger/widgets.

## Features

- 5 Pre-built Tools - Cart builder, product lookup, quick actions, email signup, CTA buttons
- Type-Safe - Full TypeScript support with Zod validation
- Widget Integration - Pairs with @rodger/widgets for instant UI
- Vercel AI SDK v5 - Built on the latest AI SDK patterns
- Production-Ready - Battle-tested in real applications

## Installation

```bash
npm install @rodger/tools
# or
pnpm add @rodger/tools
```

## Quick Start

```typescript
import { createAgent } from '@rodger/core';
import { cartBuilder, productLookup } from '@rodger/tools';

const agent = createAgent({
  name: 'Shopping Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: {
    cartBuilder,
    productLookup
  }
});

// Agent automatically uses tools when needed
const response = await agent.chat('Show me recovery products');
```

## Available Tools

### 1. Cart Builder (UI-Interactive)

Creates a shopping cart preview that requires user approval before proceeding to checkout.

```typescript
import { cartBuilder } from '@rodger/tools';
import { createAgent } from '@rodger/core';

const agent = createAgent({
  name: 'Shopping Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { cartBuilder },
  systemPrompt: 'Help users build shopping carts. Always use cartBuilder to show cart previews.'
});
```

**Features:**
- Displays interactive cart preview
- Requires user approval before checkout
- Validates product data
- Shows product details, quantities, and prices

**Input Schema:**
```typescript
{
  protocolName: string;      // e.g., "Weight Loss Starter Kit"
  notes: string | null;       // Optional cart notes
  products: Array<{
    entityId: number;         // Product ID
    name: string;             // Product name
    quantity: number;         // Quantity (must be positive)
    price?: number;           // Optional price in cents
  }>;
}
```

**Output:**
```typescript
{
  requiresApproval: true,
  preview: {
    products: [...],
    protocolName: "Weight Loss Starter Kit",
    notes: "Take with food"
  },
  message: "Review your cart before proceeding to checkout"
}
```

**Widget:** Use with `CartBuilderUI` from @rodger/widgets

### 2. Product Lookup (Silent)

Searches a product catalog by category. Returns formatted product list directly to the agent.

```typescript
import { productLookup } from '@rodger/tools';

const agent = createAgent({
  name: 'Product Expert',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { productLookup },
  systemPrompt: 'Help users find products. Use productLookup to search the catalog.'
});
```

**Features:**
- Silent tool (no UI interaction needed)
- Searches by category
- Returns formatted product data
- No approval required

**Input Schema:**
```typescript
{
  category: 'recovery' | 'performance' | 'metabolic' | 'cognitive' | 'aging' | 'immune' | 'all'
}
```

**Output:**
```typescript
string // Formatted list: "ID: 123 | Product Name | $99.99 | 30 servings | https://..."
```

**Widget:** Use with `ProductLookupUI` from @rodger/widgets (optional)

### 3. Quick Actions (UI-Interactive)

Displays interactive button choices to guide the conversation.

```typescript
import { quickActions } from '@rodger/tools';

const agent = createAgent({
  name: 'Guide Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { quickActions },
  systemPrompt: 'Guide users with quick action buttons for common choices.'
});
```

**Features:**
- Shows multiple choice buttons
- Makes conversations more interactive
- Guides users through workflows
- Pre-fills prompts when clicked

**Input Schema:**
```typescript
{
  message: string;           // Message above buttons
  actions: Array<{
    label: string;           // Button text (short)
    prompt: string;          // Full prompt to send when clicked
  }>;                        // Minimum 2 actions required
}
```

**Output:**
```typescript
{
  message: "What would you like to do?",
  actions: [
    { label: "Browse Products", prompt: "Show me all products" },
    { label: "Get Recommendations", prompt: "Recommend products for me" }
  ]
}
```

**Widget:** Use with `QuickActionsWidget` from @rodger/widgets

### 4. Email Signup (Data Collection)

Collects user email addresses early in conversations.

```typescript
import { emailSignup } from '@rodger/tools';

const agent = createAgent({
  name: 'Onboarding Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { emailSignup },
  systemPrompt: 'Collect user emails to personalize recommendations.'
});
```

**Features:**
- Email validation
- Early conversation collection
- Success/error handling
- Personalization enabler

**Input Schema:**
```typescript
{
  email: string;             // User's email address
}
```

**Output:**
```typescript
{
  success: boolean;
  email: string | null;
  message: string;          // Feedback message
}
```

**Widget:** Use with `EmailSignupWidget` from @rodger/widgets

### 5. CTA Button (UI-Interactive)

Displays prominent call-to-action buttons for important actions.

```typescript
import { ctaButton } from '@rodger/tools';

const agent = createAgent({
  name: 'Sales Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { ctaButton },
  systemPrompt: 'Guide users to book consultations using CTA buttons.'
});
```

**Features:**
- Prominent button display
- Customizable styling (primary/secondary)
- Optional description text
- External link support

**Input Schema:**
```typescript
{
  label: string;             // Button text
  url: string;               // Link destination
  description?: string;      // Optional description above button
  variant?: 'primary' | 'secondary'; // Button style
}
```

**Output:**
```typescript
{
  label: "Book Your Consultation",
  url: "https://cal.com/consultation",
  description: "Schedule a free 15-minute call",
  variant: "primary"
}
```

**Widget:** Use with `CTAButtonWidget` from @rodger/widgets

## Tool Patterns

### UI-Interactive Tools

Tools that render UI components and often require user interaction:

- **Cart Builder** - Shows preview, requires approval
- **Quick Actions** - Shows button choices
- **CTA Button** - Shows prominent action button
- **Email Signup** - Shows email input form

**Pattern:**
```typescript
{
  requiresApproval?: true,   // Optional: requires user approval
  preview?: object,          // Data for widget rendering
  message: string            // Human-readable message
}
```

### Silent Tools

Tools that fetch data without UI interaction:

- **Product Lookup** - Searches catalog silently

**Pattern:**
```typescript
{
  // Returns data directly to agent
  // No approval required
  // No UI rendering (optional widget for display)
}
```

## Using Tools with Widgets

Combine tools with widgets for instant UI:

```typescript
// Backend: app/api/chat/route.ts
import { createAgent } from '@rodger/core';
import { cartBuilder, quickActions } from '@rodger/tools';

const agent = createAgent({
  name: 'Shopping Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { cartBuilder, quickActions }
});

// Frontend: components/Chat.tsx
import { Thread } from '@rodger/ui';
import { CartBuilderUI, QuickActionsWidget } from '@rodger/widgets';

<Thread
  widgets={{
    cartBuilder: CartBuilderUI,
    quickActions: QuickActionsWidget
  }}
/>
```

## Creating Custom Tools

Follow the Vercel AI SDK v5 patterns for consistent behavior:

### Basic Tool

```typescript
// my-tool/tool.ts
import { tool } from 'ai';
import { z } from 'zod';

export const myTool = tool({
  description: 'Clear description of what this tool does',
  inputSchema: z.object({
    input: z.string().describe('Input parameter description')
  }),
  execute: async ({ input }) => {
    // Tool implementation
    const result = await processInput(input);
    return result;
  }
});
```

### UI-Interactive Tool

```typescript
// ui-tool/tool.ts
import { tool } from 'ai';
import { z } from 'zod';

export const uiTool = tool({
  description: 'Tool that renders UI component',
  inputSchema: z.object({
    data: z.string()
  }),
  execute: async ({ data }) => {
    return {
      requiresApproval: true,  // Requires user interaction
      preview: {
        data                    // Data for widget
      },
      message: 'User-friendly message'
    };
  }
});
```

### File Structure

Organize custom tools consistently:

```
packages/tools/src/my-tool/
├── tool.ts          # Main tool definition
├── types.ts         # Zod schemas and TypeScript types
└── index.ts         # Barrel export
```

**types.ts:**
```typescript
import { z } from 'zod';

export const myToolInputSchema = z.object({
  input: z.string()
});

export type MyToolInput = z.infer<typeof myToolInputSchema>;
export type MyToolResult = {
  output: string;
};
```

**tool.ts:**
```typescript
import { tool } from 'ai';
import { myToolInputSchema } from './types';

export const myTool = tool({
  description: 'My custom tool',
  inputSchema: myToolInputSchema,
  execute: async ({ input }) => {
    return { output: input };
  }
});
```

**index.ts:**
```typescript
export { myTool } from './tool';
export type { MyToolInput, MyToolResult } from './types';
export { myToolInputSchema } from './types';
```

### Best Practices

1. **Clear Descriptions** - Help LLMs understand when to use your tool:

```typescript
tool({
  description: 'Search product catalog by category. Use when user asks about products, recommendations, or browsing.',
  // ...
})
```

2. **Detailed Parameter Descriptions** - Use Zod `.describe()`:

```typescript
inputSchema: z.object({
  query: z.string().describe('Search query (product name, category, or keyword)'),
  limit: z.number().optional().describe('Maximum results to return (default: 10)')
})
```

3. **Validation** - Validate inputs thoroughly:

```typescript
execute: async ({ email }) => {
  if (!email.includes('@')) {
    return { success: false, message: 'Invalid email' };
  }
  // Process email
}
```

4. **Error Handling** - Handle errors gracefully:

```typescript
execute: async ({ query }) => {
  try {
    const results = await searchAPI(query);
    return { results };
  } catch (error) {
    console.error('Search failed:', error);
    return { results: [], error: 'Search temporarily unavailable' };
  }
}
```

5. **TypeScript Types** - Export all types:

```typescript
export type {
  MyToolInput,
  MyToolResult
} from './my-tool';
```

## Environment Variables

Some tools may require configuration:

```env
# Product API (for productLookup)
NEXT_PUBLIC_APP_URL=https://your-app.com

# Custom tool APIs
MY_TOOL_API_KEY=your-api-key
```

Access in tools:

```typescript
execute: async ({ query }) => {
  const apiKey = process.env.MY_TOOL_API_KEY;
  const response = await fetch(API_URL, {
    headers: { Authorization: `Bearer ${apiKey}` }
  });
  return response.json();
}
```

## TypeScript Support

Full TypeScript support with exported types:

```typescript
import type {
  // Cart Builder
  CartBuilderInput,
  CartBuilderResult,
  CartProduct,

  // Product Lookup
  ProductCategory,
  ProductLookupInput,
  Product,

  // Quick Actions
  QuickActionsInput,
  QuickAction,
  QuickActionsResult,

  // Email Signup
  EmailSignupInput,
  EmailSignupResult,

  // CTA Button
  CtaButtonInput,
  CtaButtonResult
} from '@rodger/tools';
```

## Examples

### Multi-Tool Agent

```typescript
import { createAgent } from '@rodger/core';
import {
  cartBuilder,
  productLookup,
  quickActions,
  emailSignup,
  ctaButton
} from '@rodger/tools';

const agent = createAgent({
  name: 'E-commerce Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: {
    cartBuilder,
    productLookup,
    quickActions,
    emailSignup,
    ctaButton
  },
  systemPrompt: `You are a helpful shopping assistant.

  - Use productLookup to find products by category
  - Use cartBuilder to create cart previews
  - Use quickActions to guide users through choices
  - Use emailSignup to collect emails early in conversation
  - Use ctaButton for important actions like booking consultations

  Always be helpful and guide users naturally through their shopping journey.`
});
```

### Conditional Tool Use

```typescript
const agent = createAgent({
  name: 'Smart Assistant',
  llm: { provider: 'openai', model: 'gpt-4o' },
  tools: { productLookup, cartBuilder },
  systemPrompt: `
  When user asks about products:
  1. Use productLookup to search catalog
  2. Present options to user
  3. Use cartBuilder when user wants to purchase

  Always confirm before building cart.`
});
```

## Contributing

When adding new tools:

1. Create subdirectory: `src/my-tool/`
2. Create `types.ts` with Zod schemas and TypeScript types
3. Create `tool.ts` using `tool()` from 'ai'
4. Create `index.ts` for barrel exports
5. Export from `src/index.ts`
6. Add documentation to this README
7. Consider creating a widget in @rodger/widgets

## Related Packages

- **[@rodger/core](../core)** - Agent framework (required)
- **[@rodger/widgets](../widgets)** - UI widgets for tools
- **[@rodger/ui](../ui)** - React components for chat UIs

## Documentation

- [Full Documentation](https://docs.rodger.ai)
- [Creating Custom Tools](https://docs.rodger.ai/tools/creating-tools)
- [Tool Integration Guide](https://docs.rodger.ai/core-concepts/tools)

## License

MIT