npm package: @lumenlabs/lumen-tools
Description: Node.js client for Lumen Core API
Author: Harsh Kumar
Latest version: 1.0.6

# lumen-tools

A powerful TypeScript SDK for seamlessly integrating Google, Notion, Airtable, Github, Slack... services with AI assistants through the Lumen platform. Build intelligent workflows with OAuth provider management, real-time webhooks, and OpenAI-compatible tool schemas.

## Features

- 🔗 **Provider Integration**: Simplified OAuth2 setup for all services
- 🛠️ **AI-Ready Tools**: OpenAI-compatible function schemas for seamless integration
- 🎣 **Real-time Webhooks**: Live notifications for Gmail, Calendar, Drive, Docs... events
- 📧 **Gmail Operations**: Send emails, manage messages and labels
- 📅 **Calendar Management**: Create events, manage schedules and invitations
- 📁 **Drive & Docs**: File operations and document management
- 🤖 **Multi-LLM Support**: Compatible with OpenAI, Claude, DeepSeek, LLama, Grok and more
- 🔐 **Secure Authentication**: Automated token management and refresh

## Installation

```bash
npm install @lumenlabs/lumen-tools
```

## Quick Start

```typescript
import { LumenClient, ProviderCredentials, App, Action } from "@lumenlabs/lumen-tools";
import OpenAI from "openai";

// Initialize the client
const client = new LumenClient("your-api-key");
const openai = new OpenAI({ apiKey: "your-openai-key" });
const userId = "your-user-id";

// Setup Google OAuth credentials
const googleCredentials: ProviderCredentials = {
  client_id: "your-google-client-id.apps.googleusercontent.com",
  client_secret: "your-google-client-secret",
  callback_url: "http://localhost:8000/api/oauth/callback",
};

// Connect Google provider
const connection = await client.connectProvider(
  userId,
  "google",
  googleCredentials,
  "calendar" // Service to connect e.g. gmail, calendar, drive, docs
);

console.log(`🔗 Visit: ${connection.redirect_url}`);

// After OAuth completion, get tools and start using AI
const tools = await client.tools.getToolSchemas([
  App.CALENDAR,
  Action.CALENDAR_CREATE_EVENT,
]);

const response = await openai.chat.completions.create({
  model: "gpt-4o-mini",
  tools: tools,
  messages: [
    {
      role: "user",
      content: "Create a meeting for tomorrow at 2 PM",
    },
  ],
});

// Execute the AI's tool calls
if (response.choices[0]?.message?.tool_calls) {
  const result = await client.provider.handleToolCalls(userId, response);
  console.log("✅ Action completed:", result);
}
```

## Core Components

### LumenClient

The main client for interacting with the Lumen platform:

```typescript
// Initialize with API key
const client = new LumenClient("your-api-key");
```

### Provider Management

Connect and manage OAuth providers:

```typescript
// Connect a provider (returns OAuth URL)
const connection = await client.connectProvider(
  userId,
  "google",
  credentials,
  "gmail" // Single service, e.g. gmail, calendar, drive, docs
);

// Handle OAuth callback after user authorization
const tokens = await client.handleOAuthCallback(authorizationCode, state);
```

### Tools Integration

Get AI-compatible tool schemas:

```typescript
// Get tools by App and Action
const tools = await client.tools.getToolSchemas([
  App.GMAIL, // All Gmail tools
  Action.GMAIL_SEND_EMAIL, // Specific action
]);

// Get all calendar tools
const calendarTools = await client.tools.getToolSchemas([App.CALENDAR]);

// Use with any compatible AI model
const response = await openai.chat.completions.create({
  model: "gpt-4o-mini",
  tools: tools, // Direct usage
  messages: [
    {
      role: "system",
      content:
        "You are a helpful assistant that can manage emails and calendar events.",
    },
    {
      role: "user",
      content:
        "Send an email to john@example.com and create a meeting for next week",
    },
  ],
});

// Execute AI tool calls
if (response.choices[0]?.message?.tool_calls) {
  const result = await client.provider.handleToolCalls(userId, response);
  console.log("Tool execution results:", result);
}
```

### Webhook Management

Set up real-time notifications for service events:

```typescript
// Gmail webhooks - monitor inbox for new messages
await client.triggers.setup({
  userId: userId,
  service: ServiceType.GMAIL,
  baseUrl: "https://your-domain.com/api/webhooks/notification",
  labelIds: ["INBOX"], // Monitor specific labels
  eventTypes: [EventType.GMAIL_NEW_MESSAGE],
  google_project_id: "your-gcp-project-id",
  topic_name: "gmail-notifications",
});

// Calendar webhooks - monitor event changes
await client.triggers.setup({
  userId: userId,
  service: ServiceType.CALENDAR,
  baseUrl: "https://your-domain.com/api/webhooks/notification",
  calendarId: "primary",
  eventTypes: [
    EventType.CALENDAR_EVENT_CREATED,
    EventType.CALENDAR_EVENT_UPDATED,
  ],
});

// Drive webhooks - monitor file changes
await client.triggers.setup({
  userId: userId,
  service: ServiceType.DRIVE,
  baseUrl: "https://your-domain.com/api/webhooks/notification",
  includeRemoved: true,
});

// Docs webhooks - monitor file changes
await client.triggers.setup({
  userId: userId,
  service: ServiceType.DOCS,
  baseUrl: "https://your-domain.com/api/webhooks/notification",
  includeRemoved: true,
});
```

## Available Services & Actions

### Apps and Actions

```typescript
// Apps (collections of related actions)
enum App {
  GMAIL = "gmail",
  CALENDAR = "calendar",
  DRIVE = "drive",
  DOCS = "docs",
}

// Specific Actions
enum Action {
  // Gmail actions
  GMAIL_SEND_EMAIL = "gmail.send_email",
  GMAIL_GET_MESSAGES = "gmail.get_messages",

  // Calendar actions
  CALENDAR_CREATE_EVENT = "calendar.create_event",
  CALENDAR_LIST_EVENTS = "calendar.list_events",

  // Drive actions
  DRIVE_UPLOAD_FILE = "drive.upload_file",
  DRIVE_LIST_FILES = "drive.list_files",

  // Docs actions
  DOCS_CREATE_DOCUMENT = "docs.create_document",
  DOCS_UPDATE_DOCUMENT = "docs.update_document",
}
```

### Service Types & Event Types

```typescript
enum ServiceType {
  GMAIL = "gmail",
  CALENDAR = "calendar",
  DRIVE = "drive",
  DOCS = "docs",
}

enum EventType {
  // Gmail events
  GMAIL_NEW_MESSAGE = "gmail.new_message",
  GMAIL_MESSAGE_DELETED = "gmail.message_deleted",
  GMAIL_MESSAGE_UPDATED = "gmail.message_updated",

  // Calendar events
  CALENDAR_EVENT_CREATED = "calendar.event_created",
  CALENDAR_EVENT_UPDATED = "calendar.event_updated",
  CALENDAR_EVENT_DELETED = "calendar.event_deleted",

  // Drive & Docs events
  DRIVE_FILE_CREATED = "drive.file_created",
  DRIVE_FILE_MODIFIED = "drive.file_modified",
  DRIVE_FILE_DELETED = "drive.file_deleted",
}
```

## Error Handling

The SDK provides comprehensive error handling:

```typescript
import {
  LumenError,
  AuthenticationError,
  NotFoundError,
  ValidationError,
} from "@lumenlabs/lumen-tools";

try {
  const connection = await client.connectProvider(
    userId,
    "google",
    credentials,
    "gmail"
  );
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("❌ Authentication failed:", error.message);
    // Handle re-authentication
  } else if (error instanceof ValidationError) {
    console.error("❌ Invalid parameters:", error.message);
    // Check your credentials and parameters
  } else if (error instanceof NotFoundError) {
    console.error("❌ Resource not found:", error.message);
    // Check if user/connection exists
  } else if (error instanceof LumenError) {
    console.error("❌ Lumen API error:", error.message);
    // Handle general API errors
  } else {
    console.error("❌ Unexpected error:", error);
  }
}
```

## Complete Integration Example

```typescript
import OpenAI from "openai";
import {
  LumenClient,
  ProviderCredentials,
  ServiceType,
  EventType,
  App,
  Action,
} from "@lumenlabs/lumen-tools";

async function buildAIAssistant() {
  try {
    // Initialize clients
    const client = new LumenClient("your-lumen-api-key");
    const openai = new OpenAI({ apiKey: "your-openai-key" });
    const userId = "user-12345";

    // Setup Google OAuth
    const googleCredentials: ProviderCredentials = {
      client_id: "your-client-id.apps.googleusercontent.com",
      client_secret: "your-client-secret",
      callback_url: "http://localhost:8000/api/oauth/callback",
    };

    // Connect Google services
    console.log("🔗 Connecting Google services...");
    const connection = await client.connectProvider(
      userId,
      "google",
      googleCredentials,
      "calendar"
    );

    if (connection.redirect_url) {
      console.log(`🌐 Please visit: ${connection.redirect_url}`);
      // In a real app, redirect user to this URL
      // After OAuth completion, the callback will be triggered
    }

    // Get AI-compatible tools
    console.log("🛠️ Loading tools...");
    const tools = await client.tools.getToolSchemas([
      App.CALENDAR,
      Action.CALENDAR_CREATE_EVENT,
      App.GMAIL,
      Action.GMAIL_SEND_EMAIL,
    ]);

    // Setup real-time webhooks
    console.log("🎣 Setting up webhooks...");
    await client.triggers.setup({
      userId: userId,
      service: ServiceType.GMAIL,
      baseUrl: "https://your-domain.com/api/webhooks/notification",
      labelIds: ["INBOX"],
      eventTypes: [EventType.GMAIL_NEW_MESSAGE],
      google_project_id: "your-gcp-project",
      topic_name: "gmail-notifications",
    });

    // AI Assistant interaction
    console.log("🤖 AI Assistant ready!");
    const response = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      tools: tools,
      messages: [
        {
          role: "system",
          content:
            "You are a helpful assistant that can create calendar events and send emails.",
        },
        {
          role: "user",
          content:
            "Create a team meeting for tomorrow at 2 PM, then send an email to team@company.com with the meeting details",
        },
      ],
    });

    // Execute AI's actions
    if (response.choices[0]?.message?.tool_calls) {
      console.log("🔧 Executing AI actions...");
      const result = await client.provider.handleToolCalls(userId, response);
      console.log("✅ Actions completed:", result);
    }

    console.log("\n📊 Setup Complete!");
    console.log(`Connection ID: ${connection.connection_id}`);
    console.log(`Tools Available: ${tools.length}`);
  } catch (error) {
    console.error("❌ Setup failed:", error);
  }
}

buildAIAssistant();
```

## OAuth Flow

The complete OAuth authentication flow:

```typescript
// 1. Initiate OAuth connection
const connection = await client.connectProvider(
  userId,
  "google",
  credentials,
  "gmail"
);

// 2. Redirect user to authorization URL
console.log(`Visit: ${connection.redirect_url}`);

// 3. Handle OAuth callback (in your callback endpoint)
app.get("/api/oauth/callback", async (req, res) => {
  const { code, state } = req.query;

  try {
    // Exchange code for tokens (handled automatically)
    const result = await client.handleOAuthCallback(code, state);
    res.json({ success: true, result });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// 4. Start using connected services
const tools = await client.tools.getToolSchemas([App.GMAIL]);
```

## Google Cloud Setup

### Required APIs

Enable these APIs in your Google Cloud Console:

- Gmail API
- Google Calendar API
- Google Drive API
- Google Docs API

### OAuth 2.0 Configuration

1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create credentials → OAuth 2.0 Client ID
3. Add authorized redirect URIs:
   ```
   http://localhost:8000/api/oauth/callback
   https://yourdomain.com/api/oauth/callback
   ```

### Pub/Sub Setup (for webhooks)

```bash
# Create topic
gcloud pubsub topics create gmail-notifications

# Create subscription
gcloud pubsub subscriptions create gmail-webhook-sub \
    --topic=gmail-notifications \
    --push-endpoint=https://yourdomain.com/api/webhooks/notification
```

## Environment Variables

```bash
# Required
LUMEN_API_KEY=your-lumen-api-key

# Google OAuth
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_PROJECT_ID=your-gcp-project-id

# Webhook endpoint
WEBHOOK_BASE_URL=https://yourdomain.com
```

## TypeScript Support

Full TypeScript definitions included:

```typescript
import type {
  LumenClient,
  ProviderCredentials,
  ConnectionResponse,
  ToolSchema,
  WebhookSetup,
  ToolCallsResult,
} from "@lumenlabs/lumen-tools";

// Type-safe tool handling
const handleAIResponse = async (
  response: OpenAI.Chat.Completions.ChatCompletion
): Promise<ToolCallsResult | null> => {
  if (response.choices[0]?.message?.tool_calls) {
    return await client.provider.handleToolCalls(userId, response);
  }
  return null;
};
```

## License

MIT License

## Author

Harsh Kumar [fyo9329@gmail.com](mailto:fyo9329@gmail.com)