> ## Documentation Index
> Fetch the complete documentation index at: https://docs.heylua.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Lua — AI Agent Platform

> Build AI agents that integrate with your entire business using TypeScript

<img src="https://mintcdn.com/luaglobal/NNnbZwzU4fGTYSKM/images/hero.png?fit=max&auto=format&n=NNnbZwzU4fGTYSKM&q=85&s=106784ab0c917a5fa89172b9d825044c" alt="Build AI Agents That Do Anything" width="1400" height="594" data-path="images/hero.png" />

<Note>
  **Vibe Code Your AI Agent** - Lua is built for AI-assisted development. Use Cursor, Windsurf, GitHub Copilot, or any AI coding IDE to build, test, and deploy agents fast.
</Note>

## Connect Your AI IDE to Lua Docs

Get instant access to Lua documentation directly in your coding environment via MCP (Model Context Protocol).

<CardGroup cols={2}>
  <Card title="Connect to Cursor" icon="bolt" href="cursor://anysphere.cursor-deeplink/mcp/install?name=lua-docs&config=eyJ1cmwiOiJodHRwczovL2RvY3MuaGV5bHVhLmFpL21jcCJ9">
    **One-click install** - Click to add Lua docs to Cursor
  </Card>

  <Card title="Connect to VS Code" icon="code" href="vscode://settings/mcp">
    Add `https://docs.heylua.ai/mcp` to your MCP servers
  </Card>
</CardGroup>

<Accordion title="Manual MCP Setup (Cursor, VS Code, Claude, etc.)">
  Add this to your MCP configuration:

  ```json theme={null}
  {
    "mcpServers": {
      "lua-docs": {
        "url": "https://docs.heylua.ai/mcp"
      }
    }
  }
  ```

  **MCP Server URL:** `https://docs.heylua.ai/mcp`

  Works with: Cursor, VS Code, Claude, Windsurf, and any MCP-compatible tool.
</Accordion>

<Card title="AI Agent Building Guide" icon="robot" href="/ai-guide">
  **Complete workflow for AI IDEs** - Authentication, testing strategies, sandbox vs production, common gotchas, and the full build-test-deploy cycle optimized for Cursor, Windsurf, and GitHub Copilot.
</Card>

***

## What is Lua?

**Lua is a developer platform for building AI agents that integrate with your entire business.**

Write TypeScript functions that connect to any API - your CRM, payment processor, inventory system, or any third-party service - and Lua transforms them into conversational AI capabilities. Your customers chat naturally ("Where's my order?" or "Book me a table"), and your AI agent takes real actions by calling the functions you wrote.

<CardGroup cols={3}>
  <Card title="Vibe Coding Ready" icon="wand-magic-sparkles">
    **Built for AI IDEs** - Cursor, Windsurf, GitHub Copilot

    All commands are non-interactive. Let AI write your agent.
  </Card>

  <Card title="Integrate With ANY API" icon="plug">
    **Your Backend** - CRM, ERP, databases

    **External Services** - Stripe, Shopify, SendGrid
  </Card>

  <Card title="TypeScript-Native" icon="code">
    Full type safety with Zod validation

    Live reload, testing, instant deployment
  </Card>
</CardGroup>

## Two Powerful Products

<Tabs>
  <Tab title="🛠️ Lua CLI">
    **Build AI agents with custom capabilities using TypeScript**

    The development framework for creating AI skills that connect to your APIs.

    ### What You Get

    * TypeScript framework for building tools
    * Live reload development environment
    * Optional Platform APIs (Products, Baskets, Orders, Vector Search, Templates)
    * 30+ working examples
    * One-command deployment

    ### Quick Start

    <CodeGroup>
      ```bash npm theme={null}
      npm install -g lua-cli
      lua auth configure
      lua init
      lua chat
      ```

      ```bash yarn theme={null}
      yarn global add lua-cli
      lua auth configure
      lua init
      lua chat
      ```

      ```bash pnpm theme={null}
      pnpm add -g lua-cli
      lua auth configure
      lua init
      lua chat
      ```
    </CodeGroup>

    <Card title="Explore Lua CLI" icon="terminal" href="/getting-started/quick-start">
      Build your first AI agent in 5 minutes
    </Card>
  </Tab>

  <Tab title="💬 LuaPop Widget">
    **Embeddable AI chat widget for your website**

    Add your AI agent to any website with a single script tag.

    ### What You Get

    * One-line integration (CDN or NPM)
    * Fully customizable styling
    * Voice chat capabilities
    * Mobile-responsive
    * Event tracking
    * Works with any framework

    ### Quick Start

    ```html theme={null}
    <script src="https://lua-ai-global.github.io/lua-pop/lua-pop.umd.js"></script>
    <script>
      window.LuaPop.init({
        agentId: "your-agent-id",
        position: "bottom-right"
      });
    </script>
    ```

    <Card title="Explore LuaPop Widget" icon="comments" href="/chat-widget/introduction">
      Add AI chat to your website in 2 minutes
    </Card>
  </Tab>
</Tabs>

## How It Works

<Steps>
  <Step title="Write TypeScript Functions">
    Create tools that integrate with your APIs

    ```typescript theme={null}
    class OrderLookupTool implements LuaTool {
      async execute(input: { orderId: string }) {
        // Call YOUR API
        const response = await fetch(`https://your-api.com/orders/${input.orderId}`);
        return await response.json();
      }
    }
    ```
  </Step>

  <Step title="Bundle Into Skills">
    Group related tools together

    ```typescript theme={null}
    const customerService = new LuaSkill({
      name: "customer-service",
      tools: [new OrderLookupTool(), new CreateTicketTool()]
    });
    ```
  </Step>

  <Step title="Configure Your Agent">
    Use `LuaAgent` to configure everything in one place

    ```typescript theme={null}
    export const agent = new LuaAgent({
      name: "support-assistant",
      persona: "You are a helpful customer support agent...",
      skills: [customerService]
    });
    ```
  </Step>

  <Step title="Test with Interactive Chat">
    Chat with your agent to test everything works

    ```bash theme={null}
    lua chat
    ```

    Select sandbox mode to test with your local skills
  </Step>

  <Step title="Deploy Your Agent">
    Push to production with one command

    ```bash theme={null}
    lua push && lua deploy
    ```
  </Step>

  <Step title="Users Chat, AI Takes Actions">
    Your users interact naturally, AI calls your tools

    **User**: "What's the status of order #12345?"

    **AI**: *Calls OrderLookupTool with your API* → "Your order shipped yesterday and will arrive tomorrow!"
  </Step>
</Steps>

<Note>
  **Testing Individual Tools**: Need to test a specific tool with exact inputs? Use `lua test` to test tools one at a time. For most development, `lua chat` is faster for testing complete workflows.
</Note>

## Beyond Skills and Tools

Lua agents go beyond skills and tools with a full set of primitives for production use cases:

<CardGroup cols={2}>
  <Card title="LuaAgent" icon="robot">
    **Unified Configuration** - Configure your entire agent in one place

    Combines persona, skills, webhooks, jobs, and processors
  </Card>

  <Card title="LuaWebhook" icon="webhook">
    **HTTP Endpoints** - Receive events from external services

    Stripe payments, Shopify orders, GitHub deployments, etc.
  </Card>

  <Card title="LuaJob" icon="clock">
    **Scheduled Tasks** - Automate recurring operations

    Daily reports, cleanup jobs, monitoring with cron patterns
  </Card>

  <Card title="Jobs API" icon="plus">
    **Dynamic Scheduling** - Create jobs from tools at runtime

    User reminders, follow-ups, deferred work
  </Card>

  <Card title="PreProcessor" icon="filter">
    **Message Filtering** - Process messages before your agent

    Spam detection, profanity filters, routing, validation
  </Card>

  <Card title="PostProcessor" icon="paper-plane">
    **Response Formatting** - Enhance responses after generation

    Disclaimers, branding, translation, formatting
  </Card>
</CardGroup>

### Complete Example

```typescript theme={null}
import { 
  LuaAgent, 
  LuaSkill, 
  LuaWebhook, 
  LuaJob,
  PreProcessor,
  PostProcessor 
} from 'lua-cli';

// Skills
import { customerServiceSkill } from './skills/customer-service';
import { productSkill } from './skills/products';

// Webhooks
const paymentWebhook = new LuaWebhook({
  name: 'stripe-payment',
  execute: async (event) => {
    if (event.type === 'payment.succeeded') {
      // Handle payment confirmation
      await notifyCustomer(event.data);
    }
  }
});

// Scheduled Jobs
const dailyReportJob = new LuaJob({
  name: 'daily-report',
  schedule: { type: 'cron', pattern: '0 9 * * *' },
  execute: async (job) => {
    const user = await job.user();
    await user.send([{ type: 'text', text: 'Daily report ready!' }]);
  }
});

// Message Processing
const profanityFilter = new PreProcessor({
  name: 'profanity-filter',
  execute: async (message, user) => {
    if (containsProfanity(message.content)) {
      return { block: true, response: "Please keep it respectful." };
    }
    return { block: false };
  }
});

const addDisclaimer = new PostProcessor({
  name: 'add-disclaimer',
  execute: async (user, message, response, channel) => {
    return {
      modifiedResponse: response + "\n\n_AI-generated content for informational purposes._"
    };
  }
});

// Complete Agent Configuration
export const agent = new LuaAgent({
  name: "enterprise-assistant",
  
  persona: `You are a professional enterprise assistant.
  
Your role:
- Help with customer inquiries
- Process orders and payments
- Provide product information

Communication:
- Professional and efficient
- Clear and accurate
- Proactive and helpful`,

  
  skills: [customerServiceSkill, productSkill],
  webhooks: [paymentWebhook],
  jobs: [dailyReportJob],
  preProcessors: [profanityFilter],
  postProcessors: [addDisclaimer]
});
```

**Learn more:**

* [LuaAgent API](/api/luaagent)
* [LuaWebhook API](/api/luawebhook)
* [LuaJob API](/api/luajob)
* [Jobs API](/api/jobs)
* [PreProcessor API](/api/preprocessor)
* [PostProcessor API](/api/postprocessor)

## Complete Flexibility: Choose Your Integration Approach

One of Lua's core strengths is flexibility. You can integrate with your existing systems, use our optional Platform APIs, or mix both approaches. Here's how each approach works:

<Tabs>
  <Tab title="Your APIs Only">
    ### 100% Custom Integration

    Connect directly to your existing backend, databases, and third-party services. This gives you complete control over your business logic, data, and infrastructure.

    ```typescript theme={null}
    import { LuaTool, env } from 'lua-cli';
    import { z } from 'zod';

    // Connect to YOUR systems
    class YourCustomTool implements LuaTool {
      name = "your_custom_action";
      description = "Performs actions specific to your business";
      inputSchema = z.object({ param: z.string() });
      
      async execute(input) {
        // YOUR API
        const apiKey = env('YOUR_API_KEY');
        const response = await fetch('https://your-backend.com/api/endpoint', {
          headers: { 'Authorization': `Bearer ${apiKey}` }
        });
        
        // YOUR business logic
        const data = await response.json();
        return processYourData(data);
      }
    }
    ```

    **Perfect for:**

    * Existing infrastructure and systems
    * Custom business requirements
    * Enterprise integrations
    * Any industry or use case
    * Complete control over data and logic

    **Real Examples:**

    * CRM: Salesforce, HubSpot, your custom CRM
    * E-commerce: Shopify, WooCommerce, Magento, your custom store
    * ERP: SAP, Oracle, your internal systems
    * Payments: Stripe, PayPal, Square, your payment gateway
    * Databases: PostgreSQL, MongoDB, MySQL, your data warehouse
  </Tab>

  <Tab title="Platform APIs">
    ### Optional Built-In Helpers

    For common e-commerce and data storage needs, we provide ready-to-use APIs. These are completely optional shortcuts.

    ```typescript theme={null}
    import { Products, Baskets, Orders, Data } from 'lua-cli';

    class QuickShopTool implements LuaTool {
      name = "shop_assistant";
      description = "Help users browse and purchase products";
      
      async execute(input: { query: string }) {
        // Platform APIs - no backend needed
        const products = await Products.search(input.query);
        const basket = await Baskets.create({ currency: 'USD' });
        
        // Add items to cart
        await Baskets.addItem(basket.id, {
          id: products[0].id,
          price: products[0].price,
          quantity: 1
        });
        
        return { products, basketId: basket.id };
      }
    }
    ```

    **Available Platform APIs:**

    * **Products** - E-commerce catalog management
    * **Baskets** - Shopping cart functionality
    * **Orders** - Order processing and tracking
    * **Data** - Vector search and data storage
    * **User** - User profile management

    **Perfect for:**

    * Building e-commerce quickly
    * Need vector/semantic search
    * Rapid prototyping and MVPs
    * Don't have backend infrastructure yet
    * Want to focus on AI experience first
  </Tab>

  <Tab title="Mix Both (Recommended)">
    ### Best of Both Worlds

    Most production applications use a hybrid approach: your critical business systems combined with Platform helpers where they add value.

    ```typescript theme={null}
    import { Data, env } from 'lua-cli';

    class HybridSearchTool implements LuaTool {
      name = "comprehensive_search";
      description = "Search across all your data sources";
      
      async execute(input: { query: string }) {
        // 1. YOUR Shopify store for products
        const shopifyProducts = await fetch(
          `https://your-store.myshopify.com/admin/api/2024-01/products.json`,
          { 
            headers: { 
              'X-Shopify-Access-Token': env('SHOPIFY_TOKEN') 
            }
          }
        ).then(r => r.json());
        
        // 2. Platform vector search for FAQs and docs
        const helpArticles = await Data.search('help_articles', input.query, 5);
        
        // 3. YOUR custom database for user history
        const userHistory = await fetch(
          `https://your-api.com/users/${input.userId}/history`,
          {
            headers: { 'Authorization': `Bearer ${env('YOUR_API_KEY')}` }
          }
        ).then(r => r.json());
        
        return {
          products: shopifyProducts.products,
          help: helpArticles.data,
          history: userHistory
        };
      }
    }
    ```

    **Perfect for:**

    * Most production applications
    * Pragmatic, flexible solutions
    * Using best tool for each job
    * Extending existing systems
    * Adding AI-powered search to your stack

    **Common Patterns:**

    * Your product catalog + Platform vector search
    * Your authentication + Platform data storage
    * Your payment system + Platform product management
    * Your CRM + Platform semantic search
  </Tab>
</Tabs>

## Detailed Integration Examples

### Example 1: Pure Custom - CRM Integration

Connect to your existing CRM system (Salesforce, HubSpot, or custom):

```typescript theme={null}
import { LuaTool, LuaSkill, env } from 'lua-cli';
import { z } from 'zod';

class GetCustomerTool implements LuaTool {
  name = "get_customer";
  description = "Look up customer in your CRM";
  inputSchema = z.object({ 
    email: z.string().email() 
  });

  async execute(input: { email: string }) {
    // Call YOUR CRM API
    const response = await fetch(
      `https://your-crm.com/api/customers/${input.email}`,
      {
        headers: { 
          'X-API-Key': env('YOUR_CRM_API_KEY'),
          'Content-Type': 'application/json'
        }
      }
    );
    
    if (!response.ok) {
      throw new Error('Customer not found');
    }
    
    return await response.json();
  }
}

class CreateTicketTool implements LuaTool {
  name = "create_ticket";
  description = "Create support ticket in your system";
  inputSchema = z.object({
    customerId: z.string(),
    subject: z.string(),
    description: z.string()
  });

  async execute(input) {
    const response = await fetch('https://your-crm.com/api/tickets', {
      method: 'POST',
      headers: {
        'X-API-Key': env('YOUR_CRM_API_KEY'),
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(input)
    });
    
    return await response.json();
  }
}

const crmSkill = new LuaSkill({
  name: "crm-integration",
  description: "Access our CRM system for customer support",
  tools: [new GetCustomerTool(), new CreateTicketTool()]
});

// Configure agent
export const agent = new LuaAgent({
  name: "crm-support-agent",
  persona: "You are a customer support specialist. Help users by looking up their information and creating support tickets when needed.",
  skills: [crmSkill]
});
```

### Example 2: Platform APIs - Quick E-commerce

Build an e-commerce assistant using Platform APIs:

```typescript theme={null}
import { LuaAgent, LuaTool, LuaSkill, Products, Baskets } from 'lua-cli';
import { z } from 'zod';

class ShopAssistantTool implements LuaTool {
  name = "add_to_cart";
  description = "Add product to shopping cart";
  inputSchema = z.object({
    productId: z.string(),
    quantity: z.number().min(1)
  });
  
  async execute(input: { productId: string; quantity: number }) {
    // Use Platform APIs
    const product = await Products.getById(input.productId);
    const basket = await Baskets.create({ currency: 'USD' });
    
    await Baskets.addItem(basket.id, {
      id: input.productId,
      price: product.price,
      quantity: input.quantity
    });
    
    return { 
      basketId: basket.id,
      product: product.name,
      quantity: input.quantity,
      total: product.price * input.quantity
    };
  }
}

const shopSkill = new LuaSkill({
  name: "shop-assistant",
  description: "Help users shop and add items to cart",
  tools: [new ShopAssistantTool()]
});

// Configure agent
export const agent = new LuaAgent({
  name: "shop-assistant",
  persona: "You are a friendly shopping assistant. Help users find products and add them to their cart.",
  skills: [shopSkill]
});
```

### Example 3: Hybrid - Real Business Solution

Combine your systems with Platform helpers:

```typescript theme={null}
import { LuaAgent, LuaSkill, LuaTool, Data, env } from 'lua-cli';
import { z } from 'zod';

class CompleteSearchTool implements LuaTool {
  name = "smart_search";
  description = "Search across all data sources intelligently";
  inputSchema = z.object({
    query: z.string(),
    userId: z.string().optional()
  });
  
  async execute(input: { query: string; userId?: string }) {
    // 1. Search YOUR product API/database
    const yourProducts = await fetch('https://your-api.com/search', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env('YOUR_API_KEY')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ query: input.query })
    }).then(r => r.json());
    
    // 2. Use Platform vector search for FAQs and documentation
    const faqResults = await Data.search('faqs', input.query, 5, 0.7);
    
    // 3. If user provided, get their purchase history from YOUR system
    let userHistory = null;
    if (input.userId) {
      userHistory = await fetch(
        `https://your-api.com/users/${input.userId}/purchases`,
        {
          headers: { 'Authorization': `Bearer ${env('YOUR_API_KEY')}` }
        }
      ).then(r => r.json());
    }
    
    // 4. Combine and return all results
    return {
      products: yourProducts,
      faqs: faqResults.map(e => ({ id: e.id, question: e.question, answer: e.answer })),
      userHistory,
      message: `Found ${yourProducts.length} products and ${faqResults.length} help articles`
    };
  }
}

const hybridSkill = new LuaSkill({
  name: "hybrid-search",
  description: "Search across all your systems and our platform",
  tools: [new CompleteSearchTool()]
});

// Configure agent
export const agent = new LuaAgent({
  name: "hybrid-assistant",
  persona: "You are a comprehensive search assistant. Help users find information across products, FAQs, and their history.",
  skills: [hybridSkill]
});
```

## Real-World Use Cases

Lua can power AI agents for virtually any industry or use case. Here are some common scenarios:

<CardGroup cols={2}>
  <Card title="E-commerce" icon="cart-shopping">
    **Shopping Assistant**

    * Product search and recommendations
    * Cart management and checkout
    * Order tracking and updates
    * Customer support and FAQs

    **Integrate with:** Shopify, WooCommerce, Magento, your custom store, or Platform APIs
  </Card>

  <Card title="Customer Support" icon="headset">
    **24/7 AI Support Agent**

    * Ticket creation and management
    * Knowledge base search
    * Order lookups and status updates
    * Escalation to human agents

    **Integrate with:** Zendesk, Freshdesk, Intercom, your ticketing system
  </Card>

  <Card title="SaaS Products" icon="window-maximize">
    **In-App AI Assistant**

    * User onboarding and tutorials
    * Feature guidance and help
    * Account management
    * Usage analytics and insights

    **Integrate with:** Your product APIs, analytics platforms, auth systems
  </Card>

  <Card title="Internal Tools" icon="building">
    **AI-Powered Operations**

    * Access ERP, CRM, and databases
    * Generate reports and analytics
    * Automate workflows
    * Data lookups and updates

    **Integrate with:** Your internal systems, SAP, Oracle, Salesforce
  </Card>

  <Card title="Finance & Banking" icon="building-columns">
    **Account Management**

    * Balance inquiries and transfers
    * Transaction history
    * Payment processing
    * Report generation

    **Integrate with:** Your banking APIs, Stripe, Plaid, accounting systems
  </Card>

  <Card title="Healthcare" icon="heart-pulse">
    **Patient Portal Assistant**

    * Appointment scheduling
    * Prescription lookups
    * Doctor directory search
    * Health record access

    **Integrate with:** Your EMR, appointment systems, patient databases
  </Card>

  <Card title="HR & Recruiting" icon="user-tie">
    **Employee Assistant**

    * Policy and benefits search
    * Leave requests and approvals
    * Onboarding support
    * Document access

    **Integrate with:** BambooHR, Workday, your HR systems
  </Card>

  <Card title="Logistics" icon="truck">
    **Shipping & Tracking**

    * Multi-carrier tracking
    * Shipping quotes and labels
    * Delivery status updates
    * Route optimization

    **Integrate with:** UPS, FedEx, USPS APIs, your logistics system
  </Card>
</CardGroup>

## Why Developers Love Lua

<AccordionGroup>
  <Accordion title="🤖 Vibe Coding Ready">
    Built for AI-assisted development. All CLI commands are non-interactive, meaning Cursor, Windsurf, GitHub Copilot, and other AI coding tools can execute commands directly. Connect docs via MCP for instant context. Build agents faster with AI helping you code.
  </Accordion>

  <Accordion title="🔓 No Vendor Lock-In">
    Build on your own infrastructure. Integrate with any API you choose. Not tied to our Platform APIs - they're completely optional. Your data stays with your systems, your authentication remains yours.
  </Accordion>

  <Accordion title="⚡ Fast Development">
    Live reload during development means instant feedback. TypeScript autocomplete guides you. Test your agent with `lua chat` immediately. Deploy with one command. Build in minutes what would take days with other platforms.
  </Accordion>

  <Accordion title="🎯 Full Control">
    Your code, your logic, your data. Complete control over authentication, business rules, error handling, and integrations. Not limited by platform constraints - if you can code it in TypeScript, you can build it.
  </Accordion>

  <Accordion title="🚀 Production Ready">
    Version management built-in. Sandbox for testing before production. Environment variables for secrets. One-command deployment. Monitoring and logs. Everything you need for enterprise production use.
  </Accordion>

  <Accordion title="🛠️ Real Developer Tools">
    Actual TypeScript code, not YAML configs or no-code builders. Zod validation for type-safe inputs. Proper testing with `lua test` and `lua chat`. Modern dev workflow you already know.
  </Accordion>

  <Accordion title="🎁 Optional Platform Helpers">
    Platform APIs available when you need quick e-commerce or vector search. But they're completely optional - use them or don't, it's your choice. Most developers use a hybrid approach.
  </Accordion>
</AccordionGroup>

## Platform Architecture

Understanding how Lua works helps you build better agents:

### Skills and Tools

**Tools** are TypeScript classes that implement `LuaTool`:

* Each tool performs one specific action
* Tools have names, descriptions, and input schemas
* The AI decides when to call each tool based on context

**Skills** are bundles of related tools:

* Group tools that work together
* Each skill can have multiple tools
* Skills can be versioned and deployed independently

### Development Workflow

```bash theme={null}
# Local development with live reload
lua chat

# Test specific tools with exact inputs
lua test

# Push your code to the cloud
lua push

# Deploy to production
lua deploy

# Or combine push and deploy
lua push && lua deploy
```

### Testing Strategies

**Interactive Testing (`lua chat`):**

* Best for testing complete workflows
* Chat naturally and see tools called in real-time
* Choose sandbox mode to test local code before deploying
* Fast iteration during development

**Individual Tool Testing (`lua test`):**

* Test specific tools with exact inputs
* Useful for debugging edge cases
* Validates schemas and error handling
* Good for automated testing

## Security and Best Practices

### Environment Variables

Always use environment variables for API keys and secrets:

```typescript theme={null}
import { env } from 'lua-cli';

const apiKey = env('YOUR_API_KEY');
const dbPassword = env('DATABASE_PASSWORD');
```

Set environment variables with:

```bash theme={null}
lua env set YOUR_API_KEY "your-key-here"
```

### Error Handling

Implement proper error handling in your tools:

```typescript theme={null}
class SafeTool implements LuaTool {
  async execute(input) {
    try {
      const response = await fetch('https://api.example.com/data');
      
      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      // Log error for debugging
      console.error('Tool execution failed:', error);
      
      // Return user-friendly message
      return {
        error: true,
        message: 'Sorry, I encountered an issue. Please try again.'
      };
    }
  }
}
```

### Input Validation

Use Zod schemas for type-safe validation:

```typescript theme={null}
import { z } from 'zod';

class ValidatedTool implements LuaTool {
  inputSchema = z.object({
    email: z.string().email(),
    amount: z.number().positive(),
    date: z.string().datetime()
  });
  
  async execute(input) {
    // Input is guaranteed to match schema
    // TypeScript knows the types
  }
}
```

## Feature Highlights

<CardGroup cols={3}>
  <Card title="Any API" icon="link">
    REST, GraphQL, WebSockets - integrate with anything callable from TypeScript
  </Card>

  <Card title="TypeScript" icon="code">
    Full type safety with autocomplete and IntelliSense
  </Card>

  <Card title="Live Reload" icon="bolt">
    Instant feedback during development with auto-recompilation
  </Card>

  <Card title="Optional Platform APIs" icon="database">
    Ready-to-use helpers for e-commerce and vector search
  </Card>

  <Card title="Voice Chat" icon="microphone">
    Voice interactions built into LuaPop widget
  </Card>

  <Card title="One-Command Deploy" icon="rocket">
    Production deployment in seconds
  </Card>
</CardGroup>

## Get Started

<CardGroup cols={2}>
  <Card title="🤖 AI Agent Building Guide" icon="robot" href="/ai-guide">
    **For Cursor, Windsurf, Copilot** - Complete workflow for AI IDEs

    Non-interactive commands, testing strategies, deployment

    → Best for vibe coding
  </Card>

  <Card title="🛠️ Quick Start Tutorial" icon="code" href="/getting-started/quick-start">
    **Lua CLI** - Create AI agents that integrate with your APIs

    Install CLI, write TypeScript tools, deploy instantly

    → 5 minute quick start
  </Card>

  <Card title="💬 Add Chat Widget" icon="comments" href="/chat-widget/quick-start">
    **LuaPop Widget** - Embed AI chat on your website

    One script tag, fully customizable, works anywhere

    → 2 minute setup
  </Card>

  <Card title="📚 Connect Docs to Your IDE" icon="plug" href="#connect-your-ai-ide-to-lua-docs">
    **MCP Server** - Get Lua docs in Cursor, VS Code, Claude

    One-click install for instant documentation access

    → Scroll up for setup
  </Card>
</CardGroup>

## Learning Path

<Steps>
  <Step title="Understand Core Concepts">
    Learn how Lua enables AI agents to take real actions through your code

    <Card title="Skills and Tools" icon="book" href="/concepts/skills-and-tools" />
  </Step>

  <Step title="Build Your First Agent">
    Follow a complete tutorial from installation to deployment

    <Card title="First Skill Tutorial" icon="graduation-cap" href="/getting-started/first-skill" />
  </Step>

  <Step title="Explore Integration Options">
    See examples of external APIs, Platform APIs, and hybrid approaches

    <Card title="API Integration Guide" icon="plug" href="/concepts/platform-apis" />
  </Step>

  <Step title="Deploy to Production">
    Add the chat widget to your website and go live

    <Card title="Chat Widget Setup" icon="rocket" href="/chat-widget/installation" />
  </Step>
</Steps>

## Popular Resources

<CardGroup cols={2}>
  <Card title="Quick Start Guide" icon="play" href="/getting-started/quick-start">
    Get your first AI agent running in 5 minutes
  </Card>

  <Card title="API Integration" icon="plug" href="/concepts/platform-apis">
    Learn how to integrate with your APIs or use Platform APIs
  </Card>

  <Card title="Complete API Reference" icon="book-open" href="/api/overview">
    Full documentation for all classes and methods
  </Card>

  <Card title="30+ Working Examples" icon="layer-group" href="/examples/overview">
    External APIs, Platform APIs, and hybrid approaches
  </Card>

  <Card title="CLI Commands" icon="terminal" href="/cli/overview">
    Complete command reference and workflows
  </Card>

  <Card title="Chat Widget Setup" icon="comments" href="/chat-widget/quick-start">
    Add AI chat to your website in 2 minutes
  </Card>
</CardGroup>

## Featured Demos

See complete, production-ready implementations:

<CardGroup cols={3}>
  <Card title="E-commerce Assistant" icon="cart-shopping" href="/demos/ecommerce-assistant">
    Complete shopping experience with cart and checkout

    **Uses:** Platform APIs (Products, Baskets, Orders)
  </Card>

  <Card title="Customer Support" icon="headset" href="/demos/customer-support">
    Zendesk integration with AI knowledge base

    **Uses:** Zendesk API + Platform Data (vector search)
  </Card>

  <Card title="Financial Onboarding" icon="building-columns" href="/demos/financial-onboarding">
    KYC verification with document upload

    **Uses:** Stripe Identity + Platform Data
  </Card>

  <Card title="HR Assistant" icon="user-tie" href="/demos/hr-assistant">
    Employee management and policy search

    **Uses:** BambooHR + Platform Data
  </Card>

  <Card title="Logistics Tracker" icon="truck" href="/demos/logistics-tracker">
    Multi-carrier shipping (UPS, FedEx, USPS)

    **Uses:** Multiple external APIs
  </Card>

  <Card title="View All 11 Demos" icon="layer-group" href="/demos/overview">
    Customer-facing and internal agent solutions

    **See:** Complete code for all use cases
  </Card>
</CardGroup>

## Enterprise Features

<CardGroup cols={2}>
  <Card title="Security" icon="shield">
    Token-based auth, HTTPS only, secure environment variables, session isolation
  </Card>

  <Card title="Scalability" icon="chart-line">
    Auto-scaling infrastructure, CDN delivery, WebSocket optimization
  </Card>

  <Card title="Compliance" icon="check-circle">
    GDPR ready, SOC 2 compliant, data residency options, audit logs
  </Card>

  <Card title="Support" icon="life-ring">
    Technical support, migration assistance, dedicated success team
  </Card>
</CardGroup>

## Need Help?

<CardGroup cols={3}>
  <Card title="Discord Community" icon="discord" href="https://discord.gg/SRPEuwCzaD">
    Chat with other builders and get real-time help
  </Card>

  <Card title="Documentation" icon="book" href="/getting-started/quick-start">
    Complete guides and tutorials
  </Card>

  <Card title="Support" icon="envelope" href="mailto:support@heylua.ai">
    Email our team
  </Card>
</CardGroup>

***

<Card title="Ready to Build Your First Agent?" icon="rocket" href="/getting-started/quick-start" horizontal>
  Complete quick start tutorial with step-by-step instructions →
</Card>
