npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@lumenlabs/lumen-tools

v1.0.6

Published

Node.js client for Lumen Core API

Readme

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

npm install @lumenlabs/lumen-tools

Quick Start

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:

// Initialize with API key
const client = new LumenClient("your-api-key");

Provider Management

Connect and manage OAuth providers:

// 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:

// 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 [email protected] 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:

// 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

// 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

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:

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

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 [email protected] 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:

// 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
  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)

# 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

# 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:

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 [email protected]