From 11722160eea4eb55328b468f73af3bf464145f1c Mon Sep 17 00:00:00 2001 From: Dan Goosewin Date: Mon, 7 Jul 2025 23:28:35 -0700 Subject: [PATCH 1/2] feat: cli launch --- fern/cli/authentication.mdx | 462 +++++++++++++++++++++++++ fern/cli/mcp-integration.mdx | 393 +++++++++++++++++++++ fern/cli/overview.mdx | 247 +++++++++++++ fern/cli/project-integration.mdx | 350 +++++++++++++++++++ fern/cli/webhook-testing.mdx | 440 +++++++++++++++++++++++ fern/debugging.mdx | 12 + fern/docs.yml | 16 + fern/guides.mdx | 8 + fern/quickstart/introduction.mdx | 34 ++ fern/quickstart/phone.mdx | 15 + fern/quickstart/web.mdx | 14 + fern/resources.mdx | 1 + fern/sdk/mcp-server.mdx | 10 + fern/server-url.mdx | 16 + fern/server-url/developing-locally.mdx | 18 + fern/tools/custom-tools.mdx | 31 ++ fern/workflows/quickstart.mdx | 14 + 17 files changed, 2081 insertions(+) create mode 100644 fern/cli/authentication.mdx create mode 100644 fern/cli/mcp-integration.mdx create mode 100644 fern/cli/overview.mdx create mode 100644 fern/cli/project-integration.mdx create mode 100644 fern/cli/webhook-testing.mdx diff --git a/fern/cli/authentication.mdx b/fern/cli/authentication.mdx new file mode 100644 index 000000000..38a50bfd4 --- /dev/null +++ b/fern/cli/authentication.mdx @@ -0,0 +1,462 @@ +--- +title: Authentication management +description: Manage multiple Vapi accounts and environments with the CLI +--- + +## Overview + +The Vapi CLI supports sophisticated authentication management, allowing you to work with multiple accounts, organizations, and environments seamlessly. This is perfect for developers who work across different teams, manage client accounts, or need to switch between production and staging environments. + +**In this guide, you'll learn to:** +- Authenticate with your Vapi account +- Manage multiple accounts simultaneously +- Switch between organizations and environments +- Configure API keys and tokens + +## Quick start + + + + Authenticate with your primary account: + ```bash + vapi login + ``` + This opens your browser for secure OAuth authentication. + + + + View your authentication status: + ```bash + vapi auth status + ``` + + + + Add additional accounts without logging out: + ```bash + vapi auth login + ``` + + + + Switch between authenticated accounts: + ```bash + vapi auth switch production + ``` + + + +## Authentication methods + +### OAuth login (recommended) + +The default authentication method uses OAuth for maximum security: + +```bash +vapi login +# Opens browser for authentication +# Securely stores tokens locally +``` + +Benefits: +- No manual API key handling +- Automatic token refresh +- Secure credential storage +- Organization access management + +### API key authentication + +For CI/CD or scripting, use API keys: + +```bash +# Via environment variable +export VAPI_API_KEY=your-api-key +vapi assistant list + +# Via command flag +vapi assistant list --api-key your-api-key +``` + +### Configuration file + +Store API keys in configuration: + +```yaml +# ~/.vapi-cli.yaml +api_key: your-api-key +base_url: https://api.vapi.ai # Optional custom endpoint +``` + +## Multi-account management + +### Understanding accounts + +Each authenticated account includes: +- **User identity** - Your email and user ID +- **Organization** - The Vapi organization you belong to +- **API access** - Permissions and API keys +- **Environment** - Production, staging, or custom + +### Viewing accounts + +List all authenticated accounts: + +```bash +vapi auth status +``` + +Output: +``` +🔐 Vapi Authentication Status + +Active Account: + ✓ Email: john@company.com + ✓ Organization: Acme Corp (org_abc123) + ✓ Environment: Production + ✓ API Key: sk-prod_****efgh + +Other Accounts: + • jane@agency.com - ClientCo (org_xyz789) [staging] + • john@personal.com - Personal (org_def456) [production] + +Total accounts: 3 +``` + +### Adding accounts + +Add accounts without affecting existing ones: + +```bash +# Add another account +vapi auth login + +# You'll be prompted to: +# 1. Open browser for authentication +# 2. Choose an account alias (e.g., "staging", "client-a") +# 3. Confirm organization access +``` + +### Switching accounts + +Switch between accounts instantly: + +```bash +# Switch by alias +vapi auth switch staging + +# Switch by email +vapi auth switch jane@agency.com + +# Interactive selection +vapi auth switch +# Shows menu of available accounts +``` + +### Account aliases + +Assign meaningful aliases to accounts: + +```bash +# During login +vapi auth login --alias production + +# Update existing +vapi auth alias john@company.com production + +# Use aliases +vapi auth switch production +``` + +## Common workflows + +### Development vs production + + + + ```bash + # Development work + vapi auth switch dev + vapi assistant create --name "Test Assistant" + + # Production deployment + vapi auth switch prod + vapi assistant create --name "Customer Support" + ``` + + + + ```bash + # Client A work + vapi auth switch client-a + vapi phone list + + # Client B work + vapi auth switch client-b + vapi workflow list + ``` + + + + ```bash + # Personal development + vapi auth switch personal + vapi init + + # Team project + vapi auth switch team + vapi assistant list + ``` + + + +### Account information + +Get detailed information about current account: + +```bash +vapi auth whoami +``` + +Output: +```json +{ + "user": { + "id": "user_abc123", + "email": "john@company.com", + "name": "John Doe" + }, + "organization": { + "id": "org_abc123", + "name": "Acme Corp", + "plan": "enterprise" + }, + "permissions": [ + "assistants:read", + "assistants:write", + "calls:create", + "billing:view" + ] +} +``` + +### Token management + +View and manage API tokens: + +```bash +# View current token (masked) +vapi auth token + +# Show full token (careful!) +vapi auth token --show + +# Refresh token +vapi auth refresh +``` + +## Security best practices + +### Credential storage + +The CLI stores credentials securely: + +- **macOS**: Keychain +- **Linux**: Secret Service API / keyring +- **Windows**: Credential Manager + +### Environment isolation + +Keep environments separate: + +```bash +# Never mix environments +vapi auth switch prod +vapi assistant list # Production assistants + +vapi auth switch dev +vapi assistant list # Development assistants +``` + +### CI/CD integration + +For automated workflows: + +```yaml +# GitHub Actions example +env: + VAPI_API_KEY: ${{ secrets.VAPI_PROD_KEY }} + +steps: + - name: Deploy Assistant + run: | + vapi assistant create --file assistant.json +``` + +### Revoking access + +Remove accounts when no longer needed: + +```bash +# Logout from current account +vapi auth logout + +# Logout from specific account +vapi auth logout jane@agency.com + +# Logout from all accounts +vapi auth logout --all +``` + +## Advanced features + +### Custom API endpoints + +For on-premise or custom deployments: + +```bash +# Login to custom endpoint +vapi login --base-url https://vapi.company.internal + +# Or configure in file +echo "base_url: https://vapi.company.internal" >> ~/.vapi-cli.yaml +``` + +### Service accounts + +For server applications: + +```bash +# Create service account in dashboard +# Then configure: +export VAPI_API_KEY=service_account_key +export VAPI_ORG_ID=org_abc123 +``` + +### Proxy configuration + +For corporate environments: + +```bash +# HTTP proxy +export HTTP_PROXY=http://proxy.company.com:8080 +export HTTPS_PROXY=http://proxy.company.com:8080 + +# SOCKS proxy +export ALL_PROXY=socks5://proxy.company.com:1080 +``` + +## Troubleshooting + + + + Configure default browser: + + ```bash + # macOS + export BROWSER="Google Chrome" + + # Linux + export BROWSER=firefox + + # Windows + set BROWSER=chrome + ``` + + + + If you see authentication errors: + + ```bash + # Refresh current token + vapi auth refresh + + # Or re-login + vapi login + ``` + + + + For credential storage problems: + + ```bash + # macOS: Reset keychain access + security unlock-keychain + + # Linux: Install keyring + sudo apt-get install gnome-keyring + + # Use file storage instead + vapi config set storage file + ``` + + + + If you can't access organization resources: + + 1. Verify organization membership in dashboard + 2. Check account permissions + 3. Re-authenticate: + ```bash + vapi auth logout + vapi login + ``` + + + +## Best practices + +### Account naming + +Use clear, consistent aliases: + +```bash +# Good aliases +vapi auth login --alias prod-acme +vapi auth login --alias dev-personal +vapi auth login --alias staging-client + +# Avoid unclear aliases +vapi auth login --alias test1 +vapi auth login --alias new +``` + +### Regular maintenance + +Keep your authentication clean: + +```bash +# Monthly review +vapi auth status + +# Remove unused accounts +vapi auth logout old-client@example.com + +# Update tokens +vapi auth refresh --all +``` + +### Team documentation + +Document account structure for your team: + +```markdown +## Vapi Accounts + +- `prod`: Production (org_abc123) +- `staging`: Staging environment (org_abc124) +- `dev`: Shared development (org_abc125) + +To switch: `vapi auth switch ` +``` + +## Next steps + +With authentication configured: + +- **[Create assistants](/quickstart/phone):** Build voice assistants +- **[Initialize projects](/cli/project-integration):** Add Vapi to your codebase +- **[Test webhooks](/cli/webhook-testing):** Debug locally with any account + +--- + +**Security tip:** Always use OAuth login for interactive use and API keys only for automation. Never commit API keys to version control! \ No newline at end of file diff --git a/fern/cli/mcp-integration.mdx b/fern/cli/mcp-integration.mdx new file mode 100644 index 000000000..34024c2b6 --- /dev/null +++ b/fern/cli/mcp-integration.mdx @@ -0,0 +1,393 @@ +--- +title: MCP integration +description: Turn your IDE into a Vapi expert with Model Context Protocol +--- + +## Overview + +The Model Context Protocol (MCP) integration transforms your IDE's AI assistant into a Vapi expert. Once configured, your IDE gains complete, accurate knowledge of Vapi's APIs, features, and best practices - eliminating AI hallucinations and outdated information. + +**In this guide, you'll learn to:** +- Set up MCP in supported IDEs +- Understand what knowledge is provided +- Use your enhanced IDE effectively +- Troubleshoot common issues + +## Quick start + +Run the setup command to auto-configure all supported IDEs: + +```bash +vapi mcp setup +``` + +Or configure a specific IDE: + +```bash +vapi mcp setup cursor # For Cursor +vapi mcp setup windsurf # For Windsurf +vapi mcp setup vscode # For VSCode with Copilot +``` + +## What is MCP? + +Model Context Protocol is a standard that allows AI assistants to access structured knowledge and tools. When you set up MCP for Vapi: + +- Your IDE's AI gains access to complete Vapi documentation +- Code suggestions become accurate and up-to-date +- Examples use real, working Vapi patterns +- API hallucinations are eliminated + +## Supported IDEs + + + + AI-first code editor with deep MCP integration + + **Setup:** Creates `.cursor/mcp.json` + + + Codeium's AI-powered IDE + + **Setup:** Creates `.windsurf/mcp.json` + + + With GitHub Copilot extension + + **Setup:** Configures Copilot settings + + + +## How it works + +### What gets configured + +The MCP setup creates configuration files that connect your IDE to the Vapi MCP server: + + + + **File:** `.cursor/mcp.json` + ```json + { + "servers": { + "vapi-docs": { + "command": "npx", + "args": ["@vapi-ai/mcp-server"] + } + } + } + ``` + + + **File:** `.windsurf/mcp.json` + ```json + { + "servers": { + "vapi-docs": { + "command": "npx", + "args": ["@vapi-ai/mcp-server"] + } + } + } + ``` + + + **Settings:** Updates workspace settings + ```json + { + "github.copilot.advanced": { + "mcp.servers": { + "vapi-docs": { + "command": "npx", + "args": ["@vapi-ai/mcp-server"] + } + } + } + } + ``` + + + +### What knowledge is provided + +Your IDE gains access to: + +- **Complete API Reference** - Every endpoint, parameter, and response +- **Code Examples** - Working samples for all features +- **Integration Guides** - Step-by-step implementation patterns +- **Best Practices** - Recommended approaches and patterns +- **Latest Features** - Always up-to-date with new releases +- **Troubleshooting** - Common issues and solutions + +## Using your enhanced IDE + +### Example prompts + +Once MCP is configured, try these prompts in your IDE: + + + + **Prompt:** "How do I create a voice assistant with Vapi?" + + Your IDE will provide accurate code like: + ```typescript + import { VapiClient } from "@vapi-ai/server-sdk"; + + const client = new VapiClient({ token: process.env.VAPI_API_KEY }); + + const assistant = await client.assistants.create({ + name: "Customer Support", + model: { + provider: "openai", + model: "gpt-4", + systemPrompt: "You are a helpful customer support agent..." + }, + voice: { + provider: "11labs", + voiceId: "rachel" + } + }); + ``` + + + + **Prompt:** "Show me how to handle Vapi webhooks" + + Get complete webhook examples: + ```typescript + app.post('/webhook', async (req, res) => { + const { type, call, assistant } = req.body; + + switch (type) { + case 'call-started': + console.log(`Call ${call.id} started`); + break; + case 'speech-update': + console.log(`User said: ${req.body.transcript}`); + break; + case 'function-call': + // Handle tool calls + const { functionName, parameters } = req.body.functionCall; + const result = await handleFunction(functionName, parameters); + res.json({ result }); + return; + } + + res.status(200).send(); + }); + ``` + + + + **Prompt:** "How do I set up call recording with custom storage?" + + Get detailed implementation: + ```typescript + const assistant = await client.assistants.create({ + name: "Recorded Assistant", + recordingEnabled: true, + artifactPlan: { + recordingEnabled: true, + videoRecordingEnabled: false, + recordingPath: "s3://my-bucket/recordings/{call_id}" + }, + credentialIds: ["aws-s3-credential-id"] + }); + ``` + + + +### Best practices + + + + Ask detailed questions about Vapi features: + - ✅ "How do I transfer calls to a human agent in Vapi?" + - ❌ "How do I transfer calls?" + + + + Ask for working code samples: + - "Show me a complete example of..." + - "Generate a working implementation of..." + + + + Specify SDK versions when needed: + - "Using @vapi-ai/web v2.0, how do I..." + - "What's the latest way to..." + + + +## Configuration options + +### Check status + +View current MCP configuration: + +```bash +vapi mcp status +``` + +Output: +``` +MCP Configuration Status: +✓ Cursor: Configured (.cursor/mcp.json) +✗ Windsurf: Not configured +✓ VSCode: Configured (workspace settings) + +Vapi MCP Server: v1.2.3 (latest) +``` + +### Update server + +Keep the MCP server updated: + +```bash +# Update to latest version +npm update -g @vapi-ai/mcp-server + +# Or reinstall +npm install -g @vapi-ai/mcp-server@latest +``` + +### Remove configuration + +Remove MCP configuration: + +```bash +# Remove from all IDEs +vapi mcp remove + +# Remove from specific IDE +vapi mcp remove cursor +``` + +## How MCP tools work + +The Vapi MCP server provides these tools to your IDE: + + + + Semantic search across all Vapi docs + + **Example:** "How to handle voicemail detection" + + + Retrieve code samples for any feature + + **Example:** "WebSocket connection example" + + + Get detailed API endpoint information + + **Example:** "POST /assistant parameters" + + + Step-by-step guides for complex features + + **Example:** "Workflow implementation guide" + + + +## Troubleshooting + + + + If your IDE isn't using the MCP knowledge: + + 1. **Restart your IDE** after configuration + 2. **Check the logs** in your IDE's output panel + 3. **Verify npm is accessible** from your IDE + 4. **Ensure MCP server is installed** globally + + ```bash + # Verify installation + npm list -g @vapi-ai/mcp-server + ``` + + + + For permission issues: + + ```bash + # Install with proper permissions + sudo npm install -g @vapi-ai/mcp-server + + # Or use a Node version manager + nvm use 18 + npm install -g @vapi-ai/mcp-server + ``` + + + + If you're getting old API information: + + 1. Update the MCP server: + ```bash + npm update -g @vapi-ai/mcp-server + ``` + + 2. Clear your IDE's cache + 3. Restart the IDE + + + + For different projects needing different configs: + + - MCP configuration is per-workspace + - Run `vapi mcp setup` in each project + - Configuration won't conflict between projects + + + +## Advanced usage + +### Custom MCP configuration + +Modify the generated MCP configuration for advanced needs: + +```json +{ + "servers": { + "vapi-docs": { + "command": "npx", + "args": ["@vapi-ai/mcp-server"], + "env": { + "VAPI_MCP_LOG_LEVEL": "debug" + } + } + } +} +``` + +### Using with teams + +Share MCP configuration with your team: + +1. **Commit the config files** (`.cursor/mcp.json`, etc.) +2. **Document the setup** in your README +3. **Include in onboarding** for new developers + +Example README section: +```markdown +## Development Setup + +This project uses Vapi MCP for enhanced IDE support: + +1. Install Vapi CLI: `curl -sSL https://vapi.ai/install.sh | bash` +2. Set up MCP: `vapi mcp setup` +3. Restart your IDE +``` + +## Next steps + +With MCP configured: + +- **[Initialize a project](/cli/project-integration):** Add Vapi to your codebase +- **[Test webhooks locally](/cli/webhook-testing):** Debug without external tunnels +- **[Explore API Reference](/api-reference):** See what your IDE now knows + +--- + +**Pro tip:** After setting up MCP, try asking your IDE to "Create a complete Vapi voice assistant with error handling and logging" - watch it generate production-ready code with all the right patterns! \ No newline at end of file diff --git a/fern/cli/overview.mdx b/fern/cli/overview.mdx new file mode 100644 index 000000000..8a46fd8a6 --- /dev/null +++ b/fern/cli/overview.mdx @@ -0,0 +1,247 @@ +--- +title: Vapi CLI +description: Command-line interface for building voice AI applications faster +--- + +## Overview + +The Vapi CLI is the official command-line interface that brings world-class developer experience to your terminal and IDE. Build, test, and deploy voice AI applications without leaving your development environment. + +**In this guide, you'll learn to:** +- Install and authenticate with the Vapi CLI +- Initialize Vapi in existing projects +- Manage assistants, phone numbers, and workflows from your terminal +- Test webhooks locally without external tunnels +- Turn your IDE into a Vapi expert with MCP integration + +## Installation + +Install the Vapi CLI in seconds with our automated scripts: + + + + ```bash + curl -sSL https://vapi.ai/install.sh | bash + ``` + + + ```powershell + iex ((New-Object System.Net.WebClient).DownloadString('https://vapi.ai/install.ps1')) + ``` + + + ```bash + docker run -it ghcr.io/vapiai/cli:latest --help + ``` + + + +## Quick start + + + + Connect your Vapi account: + ```bash + vapi login + ``` + This opens your browser for secure OAuth authentication. + + + + Add Vapi to an existing project: + ```bash + vapi init + ``` + The CLI auto-detects your tech stack and sets up everything you need. + + + + Build a voice assistant: + ```bash + vapi assistant create + ``` + Follow the interactive prompts to configure your assistant. + + + +## Key features + +### 🚀 Project integration + +Drop Vapi into any existing codebase with intelligent auto-detection: + +```bash +vapi init +# Detected: Next.js application +# ✓ Installed @vapi-ai/web SDK +# ✓ Generated components/VapiButton.tsx +# ✓ Created pages/api/vapi/webhook.ts +# ✓ Added environment template +``` + +Supports React, Vue, Next.js, Python, Go, Flutter, React Native, and dozens more frameworks. + +### 🤖 MCP integration + +Turn your IDE into a Vapi expert with Model Context Protocol: + +```bash +vapi mcp setup +``` + +Your IDE's AI assistant (Cursor, Windsurf, VSCode) gains complete, accurate knowledge of Vapi's APIs and best practices. No more hallucinated code or outdated examples. + +### 🔗 Local webhook testing + +Debug webhooks instantly without ngrok: + +```bash +vapi listen --forward-to localhost:3000/webhook +``` + +All webhook events get forwarded to your local server in real-time with helpful debugging information. + +### 🔐 Multi-account management + +Switch between organizations and environments seamlessly: + +```bash +# List all authenticated accounts +vapi auth status + +# Switch between accounts +vapi auth switch production + +# Add another account +vapi auth login +``` + +### 📱 Complete feature parity + +Everything you can do in the dashboard, now in your terminal: + +- **Assistants**: Create, update, list, and delete voice assistants +- **Phone numbers**: Purchase, configure, and manage phone numbers +- **Calls**: Make outbound calls and view call history +- **Workflows**: Manage conversation flows (visual editing in dashboard) +- **Campaigns**: Create and manage AI phone campaigns at scale +- **Tools**: Configure custom functions and integrations +- **Webhooks**: Set up and test event delivery +- **Logs**: View system logs, call logs, and debug issues + +## Common commands + + + + ```bash + # List all assistants + vapi assistant list + + # Create a new assistant + vapi assistant create + + # Get assistant details + vapi assistant get + + # Update an assistant + vapi assistant update + + # Delete an assistant + vapi assistant delete + ``` + + + + ```bash + # List your phone numbers + vapi phone list + + # Purchase a new number + vapi phone create + + # Update number configuration + vapi phone update + + # Release a number + vapi phone delete + ``` + + + + ```bash + # List recent calls + vapi call list + + # Make an outbound call + vapi call create + + # Get call details + vapi call get + + # End an active call + vapi call end + ``` + + + + ```bash + # View system logs + vapi logs list + + # View call-specific logs + vapi logs calls + + # View error logs + vapi logs errors + + # View webhook logs + vapi logs webhooks + ``` + + + +## Configuration + +The CLI stores configuration in `~/.vapi-cli.yaml`. You can also use environment variables: + +```bash +# Set API key via environment +export VAPI_API_KEY=your-api-key + +# View current configuration +vapi config get + +# Update configuration +vapi config set + +# Manage analytics preferences +vapi config analytics disable +``` + +## Auto-updates + +The CLI automatically checks for updates and notifies you when new versions are available: + +```bash +# Check for updates manually +vapi update check + +# Update to latest version +vapi update +``` + +## Next steps + +Now that you have the Vapi CLI installed: + +- **[Initialize a project](/cli/project-integration):** Add Vapi to your existing codebase +- **[Set up MCP](/cli/mcp-integration):** Enhance your IDE with Vapi intelligence +- **[Test webhooks locally](/cli/webhook-testing):** Debug without external tunnels +- **[Manage authentication](/cli/authentication):** Work with multiple accounts + +--- + +**Resources:** +- [GitHub Repository](https://github.com/VapiAI/cli) +- [Report Issues](https://github.com/VapiAI/cli/issues) +- [Discord Community](https://discord.gg/vapi) \ No newline at end of file diff --git a/fern/cli/project-integration.mdx b/fern/cli/project-integration.mdx new file mode 100644 index 000000000..a2579d523 --- /dev/null +++ b/fern/cli/project-integration.mdx @@ -0,0 +1,350 @@ +--- +title: Project integration +description: Initialize Vapi in your existing projects with intelligent auto-detection +--- + +## Overview + +The `vapi init` command intelligently integrates Vapi into your existing codebase. It automatically detects your framework, installs the appropriate SDK, and generates production-ready code examples tailored to your project structure. + +**In this guide, you'll learn to:** +- Initialize Vapi in any project +- Understand what files are generated +- Customize the initialization process +- Work with different frameworks + +## Quick start + +Navigate to your project directory and run: + +```bash +cd my-project +vapi init +``` + +The CLI will: +1. Detect your project type and framework +2. Install the appropriate Vapi SDK +3. Generate example components and API routes +4. Create environment configuration templates +5. Provide next steps specific to your setup + +## How it works + +### Framework detection + +The CLI analyzes your project structure to identify: +- **Package files**: `package.json`, `requirements.txt`, `go.mod`, etc. +- **Configuration files**: Framework-specific configs +- **Project structure**: Directory patterns and file extensions +- **Dependencies**: Installed packages and libraries + +### What gets generated + +Based on your framework, the CLI generates: + + + + ```bash + vapi init + # Detected: Next.js application + ``` + + **Generated files:** + - `components/VapiButton.tsx` - Voice call button component + - `pages/api/vapi/webhook.ts` - Webhook handler endpoint + - `lib/vapi-client.ts` - Vapi client setup + - `.env.example` - Environment variables template + + **Installed packages:** + - `@vapi-ai/web` - Web SDK for browser integration + - `@vapi-ai/server-sdk` - Server SDK for webhooks + + + + ```bash + vapi init + # Detected: Python application + ``` + + **Generated files:** + - `vapi_example.py` - Basic assistant example + - `webhook_handler.py` - Flask/FastAPI webhook handler + - `requirements.txt` - Updated with Vapi SDK + - `.env.example` - Environment variables template + + **Installed packages:** + - `vapi-server-sdk` - Python server SDK + + + + ```bash + vapi init + # Detected: Node.js application + ``` + + **Generated files:** + - `vapi-example.js` - Basic usage example + - `webhook-server.js` - Express webhook handler + - `.env.example` - Environment variables template + + **Installed packages:** + - `@vapi-ai/server-sdk` - TypeScript/JavaScript SDK + + + +## Supported frameworks + +### Frontend frameworks + + + + - Create React App + - Vite + - Custom webpack + + + - Vue 3 + - Nuxt.js + - Vite + + + - Angular 12+ + - Ionic + + + - App Router + - Pages Router + - API Routes + + + - SvelteKit + - Vite + + + - HTML/CSS/JS + - Webpack + - Parcel + + + +### Mobile frameworks + + + + - Expo + - Bare workflow + + + - iOS & Android + - Web support + + + +### Backend frameworks + + + + - Express + - Fastify + - Koa + + + - Django + - FastAPI + - Flask + + + - Gin + - Echo + - Fiber + + + - Rails + - Sinatra + + + - Spring Boot + - Quarkus + + + - ASP.NET Core + - Blazor + + + +## Advanced options + +### Specify target directory + +Initialize in a specific directory: + +```bash +vapi init /path/to/project +``` + +### Skip SDK installation + +Generate only example files without installing packages: + +```bash +vapi init --skip-install +``` + +### Force framework + +Override auto-detection: + +```bash +vapi init --framework react +vapi init --framework python +``` + +### Custom templates + +Use your own templates: + +```bash +vapi init --template @myorg/vapi-templates +``` + +## Environment setup + +After initialization, configure your environment: + + + + ```bash + cp .env.example .env + ``` + + + + Get your API key from the [Vapi Dashboard](https://dashboard.vapi.ai/): + ```bash + VAPI_API_KEY=your-api-key-here + ``` + + + + For local development: + ```bash + VAPI_WEBHOOK_URL=https://your-domain.com/api/vapi/webhook + ``` + + + +## Common patterns + +### Adding to monorepos + +For monorepos, run init in the specific package: + +```bash +cd packages/web-app +vapi init + +cd ../api-server +vapi init +``` + +### CI/CD integration + +Add to your build process: + +```yaml +# GitHub Actions example +- name: Setup Vapi + run: | + curl -sSL https://vapi.ai/install.sh | bash + vapi init --skip-install +``` + +### Docker environments + +Include in your Dockerfile: + +```dockerfile +# Install Vapi CLI +RUN curl -sSL https://vapi.ai/install.sh | bash + +# Initialize project +RUN vapi init --skip-install +``` + +## Troubleshooting + + + + If the CLI can't detect your framework: + + 1. Ensure you're in the project root + 2. Check for required config files + 3. Use `--framework` flag to specify manually + + ```bash + vapi init --framework react + ``` + + + + For permission issues during SDK installation: + + ```bash + # npm projects + sudo npm install + + # Python projects + pip install --user vapi-server-sdk + ``` + + + + If files already exist, the CLI will: + + 1. Ask for confirmation before overwriting + 2. Create backup files (`.backup` extension) + 3. Show a diff of changes + + Use `--force` to skip confirmations: + ```bash + vapi init --force + ``` + + + +## Next steps + +After initializing your project: + +- **[Test locally](/cli/webhook-testing):** Use `vapi listen` to test webhooks +- **[Create assistants](/quickstart/phone):** Build your first voice assistant +- **[Set up MCP](/cli/mcp-integration):** Enhance your IDE with Vapi intelligence + +--- + +**Example output:** + +```bash +$ vapi init +🔍 Analyzing project... +✓ Detected: Next.js 14 application + +📦 Installing dependencies... +✓ Installed @vapi-ai/web@latest +✓ Installed @vapi-ai/server-sdk@latest + +📝 Generating files... +✓ Created components/VapiButton.tsx +✓ Created app/api/vapi/webhook/route.ts +✓ Created lib/vapi-client.ts +✓ Created .env.example + +🎉 Vapi initialized successfully! + +Next steps: +1. Copy .env.example to .env +2. Add your VAPI_API_KEY +3. Run: npm run dev +4. Test the voice button at http://localhost:3000 +``` \ No newline at end of file diff --git a/fern/cli/webhook-testing.mdx b/fern/cli/webhook-testing.mdx new file mode 100644 index 000000000..6ad086a4f --- /dev/null +++ b/fern/cli/webhook-testing.mdx @@ -0,0 +1,440 @@ +--- +title: Local webhook testing +description: Test webhooks locally without ngrok using vapi listen +--- + +## Overview + +The `vapi listen` command enables real-time webhook testing on your local development server without external tunneling services like ngrok. This dramatically speeds up development by letting you test webhook integrations instantly. + +**In this guide, you'll learn to:** +- Set up local webhook forwarding +- Debug webhook events in real-time +- Configure advanced forwarding options +- Handle different webhook types + +## Quick start + +Forward Vapi webhooks to your local server: + +```bash +vapi listen --forward-to localhost:3000/webhook +``` + +That's it! All webhook events from Vapi will be forwarded to your local endpoint in real-time. + +## How it works + + + + The CLI starts a webhook server on port 4242 (configurable) + + + + A secure tunnel is established between Vapi and your local server + + + + All webhook events are forwarded to your specified endpoint + + + + Events are displayed in your terminal for debugging + + + +## Basic usage + +### Standard forwarding + +Forward to your local development server: + +```bash +# Forward to localhost:3000/webhook +vapi listen --forward-to localhost:3000/webhook + +# Short form +vapi listen -f localhost:3000/webhook +``` + +### Custom port + +Use a different port for the webhook listener: + +```bash +# Listen on port 8080 instead of default 4242 +vapi listen --forward-to localhost:3000/webhook --port 8080 +``` + +### Skip TLS verification + +For development with self-signed certificates: + +```bash +vapi listen --forward-to https://localhost:3000/webhook --skip-verify +``` + + +Only use `--skip-verify` in development. Never in production. + + +## Understanding the output + +When you run `vapi listen`, you'll see: + +```bash +$ vapi listen --forward-to localhost:3000/webhook + +🎧 Vapi Webhook Listener +📡 Listening on: https://vapi-webhooks.ngrok.io/abc123 +📍 Forwarding to: http://localhost:3000/webhook + +✓ Webhook URL configured in your Vapi account + +Waiting for webhook events... + +[2024-01-15 10:30:45] POST /webhook +Event: call-started +Call ID: call_abc123def456 +Status: 200 OK (45ms) + +[2024-01-15 10:30:52] POST /webhook +Event: speech-update +Transcript: "Hello, how can I help you?" +Status: 200 OK (12ms) +``` + +## Webhook event types + +The listener forwards all Vapi webhook events: + + + + - `call-started` - Call initiated + - `call-ended` - Call completed + - `call-failed` - Call encountered an error + + + + - `speech-update` - Real-time transcription + - `transcript` - Final transcription + - `voice-input` - User speaking detected + + + + - `function-call` - Tool/function invoked + - `assistant-message` - Assistant response + - `conversation-update` - Conversation state change + + + + - `error` - Error occurred + - `recording-ready` - Call recording available + - `analysis-ready` - Call analysis complete + + + +## Advanced configuration + +### Headers and authentication + +The listener adds helpful headers to forwarded requests: + +```http +X-Forwarded-For: vapi-webhook-listener +X-Original-Host: vapi-webhooks.ngrok.io +X-Webhook-Event: call-started +X-Webhook-Timestamp: 1705331445 +``` + +Your server receives the exact webhook payload from Vapi with these additional headers for debugging. + +### Filtering events + +Filter specific event types (coming soon): + +```bash +# Only forward call events +vapi listen --forward-to localhost:3000 --filter "call-*" + +# Multiple filters +vapi listen --forward-to localhost:3000 --filter "call-started,call-ended" +``` + +### Response handling + +The listener expects standard HTTP responses: + +- **200-299**: Success, event processed +- **400-499**: Client error, event rejected +- **500-599**: Server error, will retry + +## Development workflow + +### Typical setup + + + + ```bash + # In terminal 1 + npm run dev # Your app on localhost:3000 + ``` + + + + ```bash + # In terminal 2 + vapi listen --forward-to localhost:3000/api/vapi/webhook + ``` + + + + Use the Vapi dashboard or API to trigger webhooks + + + + See events in both terminals and debug your handler + + + +### Example webhook handler + + +```typescript title="Node.js/Express" +app.post('/api/vapi/webhook', async (req, res) => { + const { type, call, timestamp } = req.body; + + console.log(`Webhook received: ${type} at ${timestamp}`); + + switch (type) { + case 'call-started': + console.log(`Call ${call.id} started with ${call.customer.number}`); + break; + + case 'speech-update': + console.log(`User said: ${req.body.transcript}`); + break; + + case 'function-call': + const { functionName, parameters } = req.body.functionCall; + console.log(`Function called: ${functionName}`, parameters); + + // Return function result + const result = await processFunction(functionName, parameters); + return res.json({ result }); + + case 'call-ended': + console.log(`Call ended. Duration: ${call.duration}s`); + break; + } + + res.status(200).send(); +}); +``` + +```python title="Python/FastAPI" +from fastapi import FastAPI, Request +from datetime import datetime + +app = FastAPI() + +@app.post("/api/vapi/webhook") +async def handle_webhook(request: Request): + data = await request.json() + event_type = data.get("type") + call = data.get("call", {}) + timestamp = data.get("timestamp") + + print(f"Webhook received: {event_type} at {timestamp}") + + if event_type == "call-started": + print(f"Call {call.get('id')} started") + + elif event_type == "speech-update": + print(f"User said: {data.get('transcript')}") + + elif event_type == "function-call": + function_call = data.get("functionCall", {}) + function_name = function_call.get("functionName") + parameters = function_call.get("parameters") + + # Process function and return result + result = await process_function(function_name, parameters) + return {"result": result} + + elif event_type == "call-ended": + print(f"Call ended. Duration: {call.get('duration')}s") + + return {"status": "ok"} +``` + +```go title="Go/Gin" +func handleWebhook(c *gin.Context) { + var data map[string]interface{} + if err := c.ShouldBindJSON(&data); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + + eventType := data["type"].(string) + fmt.Printf("Webhook received: %s\n", eventType) + + switch eventType { + case "call-started": + call := data["call"].(map[string]interface{}) + fmt.Printf("Call %s started\n", call["id"]) + + case "speech-update": + fmt.Printf("User said: %s\n", data["transcript"]) + + case "function-call": + functionCall := data["functionCall"].(map[string]interface{}) + result := processFunction( + functionCall["functionName"].(string), + functionCall["parameters"], + ) + c.JSON(200, gin.H{"result": result}) + return + + case "call-ended": + fmt.Println("Call ended") + } + + c.JSON(200, gin.H{"status": "ok"}) +} +``` + + +## Testing scenarios + +### Simulating errors + +Test error handling in your webhook: + +```bash +# Your handler returns 500 +vapi listen --forward-to localhost:3000/webhook-error + +# Output shows: +# Status: 500 Internal Server Error (23ms) +# Response: {"error": "Database connection failed"} +``` + +### Load testing + +Test with multiple concurrent calls: + +```bash +# Terminal 1: Start listener +vapi listen --forward-to localhost:3000/webhook + +# Terminal 2: Trigger multiple calls via API +for i in {1..10}; do + vapi call create --to "+1234567890" & +done +``` + +### Debugging specific calls + +Filter logs by call ID: + +```bash +# Coming soon +vapi listen --forward-to localhost:3000 --call-id call_abc123 +``` + +## Security considerations + + +The `vapi listen` command is designed for development only. In production, use proper webhook endpoints with authentication. + + +### Best practices + +1. **Never expose sensitive data** in console logs +2. **Validate webhook signatures** in production +3. **Use HTTPS** for production endpoints +4. **Implement proper error handling** +5. **Set up monitoring** for production webhooks + +### Production webhook setup + +For production, configure webhooks in the Vapi dashboard: + +```typescript +// Production webhook with signature verification +app.post('/webhook', verifyVapiSignature, async (req, res) => { + // Your production handler +}); +``` + +## Troubleshooting + + + + If you see "connection refused": + + 1. **Verify your server is running** on the specified port + 2. **Check the endpoint path** matches your route + 3. **Ensure no firewall** is blocking local connections + + ```bash + # Test your endpoint directly + curl -X POST http://localhost:3000/webhook -d '{}' + ``` + + + + For timeout issues: + + 1. **Check response time** - Vapi expects < 10s response + 2. **Avoid blocking operations** in webhook handlers + 3. **Use async processing** for heavy operations + + ```typescript + // Good: Quick response + app.post('/webhook', async (req, res) => { + // Queue for processing + await queue.add('process-webhook', req.body); + res.status(200).send(); + }); + ``` + + + + If events aren't appearing: + + 1. **Check CLI authentication** - `vapi auth whoami` + 2. **Verify account access** to the resources + 3. **Ensure events are enabled** in assistant config + + ```bash + # Re-authenticate if needed + vapi login + ``` + + + + For HTTPS endpoints: + + ```bash + # Development only - skip certificate verification + vapi listen --forward-to https://localhost:3000 --skip-verify + + # Or use HTTP for local development + vapi listen --forward-to http://localhost:3000 + ``` + + + +## Next steps + +Now that you can test webhooks locally: + +- **[Build webhook handlers](/server-url/events):** Learn about all webhook events +- **[Implement tools](/tools/custom-tools):** Add custom functionality +- **[Set up production webhooks](/server-url):** Deploy to production + +--- + +**Pro tip:** Keep `vapi listen` running while developing - you'll see all events in real-time and can iterate quickly on your webhook handlers without deployment delays! \ No newline at end of file diff --git a/fern/debugging.mdx b/fern/debugging.mdx index 4df5e0b67..55a545f29 100644 --- a/fern/debugging.mdx +++ b/fern/debugging.mdx @@ -122,6 +122,18 @@ Navigate to `Observe > Webhook Logs` to: