npm package: @jinbacode/tools
Description: Pre-built tools for JinbaFlow workflows - CSV, Slack, OpenAI, Exa AI, Google Sheets integrations
Author: Carnot Tech
Latest version: 0.0.9

# @jinbacode/tools

Pre-built tools for JinbaFlow workflows, providing integrations with popular services and utilities.

## Installation

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

## Overview

This package provides a collection of ready-to-use tools that can be integrated into JinbaFlow workflows. Each tool follows a consistent interface pattern and includes TypeScript types, input/output validation, and error handling.

## Available Tools

### CSV Tools
Process CSV data with ease.

```typescript
import { csvTools } from "@jinbacode/tools";

const { readCsvFromUrl, writeCsv } = csvTools();

// Read CSV from URL
const { rows } = await readCsvFromUrl.execute({ 
  url: "https://example.com/data.csv" 
});

// Write data to CSV
const csvFile = await writeCsv.execute({ 
  rows: [{ name: "John", age: 30 }] 
});
```

### Slack Tools
Send messages to Slack channels.

```typescript
import { slackTools } from "@jinbacode/tools";

const { sendMessage } = slackTools({
  token: "xoxb-your-token", // or use SLACK_TOKEN env var
  channel: "#general",      // or use SLACK_CHANNEL env var
});

await sendMessage.execute({
  text: "Hello from JinbaFlow!",
  channel: "#specific-channel", // optional override
});
```

### OpenAI Tools
AI-powered text generation and structured data extraction.

```typescript
import { openaiTools } from "@jinbacode/tools";

const { invoke, invokeWithSchema } = openaiTools({
  apiKey: "sk-...",    // or use OPENAI_API_KEY env var
  model: "gpt-4",      // optional, defaults to gpt-4o-mini
});

// Text generation
const { text } = await invoke.execute({
  prompt: "Write a haiku about coding",
});

// Structured output
const { text: jsonOutput } = await invokeWithSchema.execute({
  prompt: "Extract customer data from: John Doe, john@example.com",
  schema: {
    type: "object",
    properties: {
      name: { type: "string" },
      email: { type: "string" },
    },
    required: ["name", "email"],
  },
});
```

### Exa AI Tools
Neural search across the web.

```typescript
import { exaTools } from "@jinbacode/tools";

const { search } = exaTools({
  apiKey: "exa_...", // or use EXA_API_KEY env var
});

const { results } = await search.execute({
  query: "latest AI breakthroughs",
  numResults: 5,
  type: "neural", // or "keyword", "auto"
});
```

### Rule Checker Tools
Validate data against business rules using AI.

```typescript
import { ruleCheckerTools } from "@jinbacode/tools";

const { check } = ruleCheckerTools();

const { status, reason } = await check.execute({
  rule: "Email must be from company domain",
  data: "user@gmail.com",
});
// status: "pass" | "fail" | "error"
```

### Google Sheets Tools
Read and write data to Google Sheets.

```typescript
import { googleSheetsTools } from "@jinbacode/tools";

const { addRow, getRows, updateRow, removeRow } = googleSheetsTools({
  serviceAccountEmail: "your-service-account@project.iam.gserviceaccount.com",
  privateKey: "-----BEGIN PRIVATE KEY-----\n...", // or use env vars
});

// Add a row
const { rowNumber } = await addRow.execute({
  spreadsheetId: "your-spreadsheet-id",
  values: { name: "John", email: "john@example.com" },
});

// Get rows
const { rows, totalRows } = await getRows.execute({
  spreadsheetId: "your-spreadsheet-id",
  limit: 10,
});

// Update a row
await updateRow.execute({
  spreadsheetId: "your-spreadsheet-id",
  rowNumber: 2,
  values: { status: "active" },
});

// Remove a row
await removeRow.execute({
  spreadsheetId: "your-spreadsheet-id",
  rowNumber: 3,
});
```

## Usage in Flows

Tools are designed to be used within JinbaFlow workflows:

```typescript
import { type Flow } from "@jinbacode/core";
import { csvTools, openaiTools } from "@jinbacode/tools";
import { z } from "zod";

const flow: Flow<z.ZodSchema, z.ZodSchema> = {
  id: "analyze-csv",
  name: "Analyze CSV Data",
  inputSchema: z.object({
    csvUrl: z.string().url(),
  }),
  outputSchema: z.object({
    summary: z.string(),
  }),
  execute: async (ctx, input) => {
    const { readCsvFromUrl } = csvTools();
    const { invoke } = openaiTools();
    
    // Read CSV data
    const { rows } = await readCsvFromUrl.execute({ 
      url: input.csvUrl 
    });
    
    // Analyze with AI
    const { text } = await invoke.execute({
      prompt: `Analyze this CSV data and provide insights: ${JSON.stringify(rows)}`,
    });
    
    return { summary: text };
  },
};
```

## Environment Variables

Tools can be configured using environment variables:

- `OPENAI_API_KEY` - OpenAI API key
- `SLACK_TOKEN` - Slack bot token
- `SLACK_CHANNEL` - Default Slack channel
- `EXA_API_KEY` - Exa AI API key
- `GOOGLE_SERVICE_ACCOUNT_EMAIL` - Google service account email
- `GOOGLE_PRIVATE_KEY` - Google service account private key
- `GOOGLE_SPREADSHEET_ID` - Default spreadsheet ID (for examples)

## Tool Architecture

Each tool follows the standard JinbaFlow tool interface:

```typescript
interface Tool<TInput, TOutput> {
  description: string;           // What the tool does
  inputSchema: z.ZodSchema;      // Input validation schema
  outputSchema: z.ZodSchema;     // Output validation schema
  execute: (input: TInput) => Promise<TOutput>;
}
```

## Creating Custom Tools

To create a custom tool, follow this pattern:

```typescript
import type { Tool } from "@jinbacode/core";
import { z } from "zod";

export function myCustomTools(): Record<string, Tool<z.ZodSchema, z.ZodSchema>> {
  return {
    doSomething: {
      description: "Does something useful",
      inputSchema: z.object({
        input: z.string().describe("The input value"),
      }),
      outputSchema: z.object({
        result: z.string().describe("The result"),
      }),
      execute: async (input) => {
        // Your implementation here
        return { result: `Processed: ${input.input}` };
      },
    },
  };
}
```

## Examples

See the `examples/` directory for complete working examples:

- `01_basic.ts` - CSV processing with Slack notifications
- `02_openai.ts` - AI-powered text generation
- `03_exa_search.ts` - Web search integration
- `04_google_sheets.ts` - Google Sheets CRUD operations

Run examples with:

```bash
pnpm tsx examples/01_basic.ts
```

### Google Sheets Setup

To use Google Sheets tools:

1. Create a Google Cloud project
2. Enable the Google Sheets API
3. Create a service account and download the JSON key
4. Share your spreadsheet with the service account email
5. Set environment variables:
   ```bash
   export GOOGLE_SERVICE_ACCOUNT_EMAIL="your-service-account@project.iam.gserviceaccount.com"
   export GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
   ```

## Error Handling

All tools include proper error handling:

- Missing credentials throw descriptive errors
- API failures are caught and re-thrown with context
- Input validation happens automatically via Zod schemas

## TypeScript Support

Full TypeScript support with:
- Typed inputs and outputs
- IntelliSense for all tool methods
- Compile-time validation
- Automatic type inference from schemas

## Contributing

When adding new tools:

1. Follow the existing tool pattern
2. Include comprehensive TypeScript types
3. Add input/output validation with Zod
4. Provide clear descriptions for all schema fields
5. Include working examples
6. Update documentation

## License

MIT