Complete reference for all methods available in the @buena/sdk package.

Installation & Setup

npm install @buena/sdk
import { BuenaSdk } from "@buena/sdk";

const buena = new BuenaSdk({
  security: {
    apiKey: "your-api-key",
  },
  serverURL: "https://api.buena.ai/api/v2",
});

Core API Methods

All API methods are accessed through buena.default.* and return promises.

Lead Management

listLeads(options?)

List all leads with optional filtering and pagination.

Parameters:

interface ListLeadsOptions {
  limit?: number; // Number of leads to return (default: 50, max: 100)
  offset?: number; // Offset for pagination (default: 0)
  sort?: string; // Sort field (created_at, updated_at, first_name, last_name)
  order?: "asc" | "desc"; // Sort order (default: desc)
  search?: string; // Search term for name/email
  company?: string; // Filter by company
  status?: "active" | "inactive" | "contacted"; // Filter by status
}

Returns:

interface ListLeadsResponse {
  data: Lead[];
  total: number;
  limit: number;
  offset: number;
}

interface Lead {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  company?: string;
  phone?: string;
  linkedinUrl?: string;
  status: "active" | "inactive" | "contacted";
  createdAt: Date;
  updatedAt: Date;
}

Example:

// List first 25 leads
const leads = await buena.default.listLeads({
  limit: 25,
  sort: "created_at",
  order: "desc",
});

console.log(`Found ${leads.total} leads`);
leads.data.forEach((lead) => {
  console.log(`${lead.firstName} ${lead.lastName} - ${lead.email}`);
});

// Search for leads
const searchResults = await buena.default.listLeads({
  search: "john",
  company: "example",
});

Errors:

  • 401 - Invalid API key
  • 403 - Insufficient permissions
  • 429 - Rate limit exceeded
  • 500 - Server error

createLead(leadData)

Create a new lead in your database.

Parameters:

interface CreateLeadRequest {
  firstName: string; // Required: Lead's first name
  lastName: string; // Required: Lead's last name
  email: string; // Required: Valid email address
  company?: string; // Optional: Company name
  phone?: string; // Optional: Phone number
  linkedinUrl?: string; // Optional: LinkedIn profile URL
  jobTitle?: string; // Optional: Job title
  location?: string; // Optional: Location/city
  notes?: string; // Optional: Additional notes
  tags?: string[]; // Optional: Array of tags
  customFields?: Record<string, any>; // Optional: Custom field data
}

Returns:

interface Lead {
  id: string; // Unique lead identifier
  firstName: string;
  lastName: string;
  email: string;
  company?: string;
  phone?: string;
  linkedinUrl?: string;
  jobTitle?: string;
  location?: string;
  notes?: string;
  tags?: string[];
  customFields?: Record<string, any>;
  status: "active"; // New leads are always active
  createdAt: Date;
  updatedAt: Date;
}

Example:

const newLead = await buena.default.createLead({
  firstName: "John",
  lastName: "Doe",
  email: "john.doe@example.com",
  company: "Example Corp",
  phone: "+1-555-123-4567",
  linkedinUrl: "https://linkedin.com/in/johndoe",
  jobTitle: "Software Engineer",
  location: "San Francisco, CA",
  notes: "Met at tech conference 2024",
  tags: ["conference", "engineer", "potential"],
});

console.log(`Created lead with ID: ${newLead.id}`);

Errors:

  • 400 - Invalid lead data (missing required fields, invalid email format)
  • 401 - Invalid API key
  • 409 - Lead with email already exists
  • 422 - Validation error (invalid phone format, invalid LinkedIn URL)
  • 429 - Rate limit exceeded
  • 500 - Server error

getLead(leadId)

Retrieve a specific lead by ID.

Parameters:

leadId: string; // Required: Unique lead identifier

Returns:

interface Lead {
  // Same as createLead response
}

Example:

const lead = await buena.default.getLead("lead_123456789");
console.log(`Lead: ${lead.firstName} ${lead.lastName}`);
console.log(`Company: ${lead.company}`);
console.log(`Created: ${lead.createdAt.toLocaleDateString()}`);

Errors:

  • 401 - Invalid API key
  • 404 - Lead not found
  • 500 - Server error

updateLead(leadId, updateData)

Update an existing lead’s information.

Parameters:

leadId: string; // Required: Unique lead identifier

interface UpdateLeadRequest {
  firstName?: string; // Optional: Update first name
  lastName?: string; // Optional: Update last name
  email?: string; // Optional: Update email (must be unique)
  company?: string; // Optional: Update company
  phone?: string; // Optional: Update phone
  linkedinUrl?: string; // Optional: Update LinkedIn URL
  jobTitle?: string; // Optional: Update job title
  location?: string; // Optional: Update location
  notes?: string; // Optional: Update notes
  tags?: string[]; // Optional: Replace tags array
  customFields?: Record<string, any>; // Optional: Update custom fields
  status?: "active" | "inactive" | "contacted"; // Optional: Update status
}

Returns:

interface Lead {
  // Updated lead object with new data
}

Example:

const updatedLead = await buena.default.updateLead("lead_123456789", {
  company: "New Company Inc",
  jobTitle: "Senior Software Engineer",
  status: "contacted",
  tags: ["contacted", "promoted", "hot-lead"],
  notes: "Promoted to senior role, very interested in our product",
});

console.log(`Updated lead: ${updatedLead.firstName} ${updatedLead.lastName}`);

Errors:

  • 400 - Invalid update data
  • 401 - Invalid API key
  • 404 - Lead not found
  • 409 - Email already exists (if updating email)
  • 422 - Validation error
  • 500 - Server error

deleteLead(leadId)

Permanently delete a lead from your database.

Parameters:

leadId: string; // Required: Unique lead identifier

Returns:

interface DeleteResponse {
  success: boolean;
  message: string;
  deletedId: string;
}

Example:

const result = await buena.default.deleteLead("lead_123456789");
if (result.success) {
  console.log(`Successfully deleted lead: ${result.deletedId}`);
} else {
  console.error(`Failed to delete lead: ${result.message}`);
}

Errors:

  • 401 - Invalid API key
  • 404 - Lead not found
  • 500 - Server error

API Key Management

listApiKeys()

List all API keys for your account.

Parameters: None

Returns:

interface ListApiKeysResponse {
  data: ApiKey[];
  total: number;
}

interface ApiKey {
  id: string;
  name: string;
  keyPreview: string; // First 8 chars + "..."
  permissions: string[]; // Array of permissions
  lastUsed?: Date; // Last usage timestamp
  isActive: boolean;
  createdAt: Date;
  expiresAt?: Date; // Optional expiration date
}

Example:

const apiKeys = await buena.default.listApiKeys();
console.log(`You have ${apiKeys.total} API keys:`);

apiKeys.data.forEach((key) => {
  console.log(
    `${key.name}: ${key.keyPreview} (${key.isActive ? "Active" : "Inactive"})`
  );
  console.log(`Permissions: ${key.permissions.join(", ")}`);
  if (key.lastUsed) {
    console.log(`Last used: ${key.lastUsed.toLocaleDateString()}`);
  }
});

Errors:

  • 401 - Invalid API key
  • 403 - Insufficient permissions
  • 500 - Server error

createApiKey(keyData)

Create a new API key for your account.

Parameters:

interface CreateApiKeyRequest {
  name: string; // Required: Descriptive name for the key
  permissions: string[]; // Required: Array of permissions
  expiresAt?: Date; // Optional: Expiration date
  description?: string; // Optional: Key description
}

// Available permissions:
// - "leads:read" - Read leads
// - "leads:write" - Create/update leads
// - "leads:delete" - Delete leads
// - "api_keys:read" - Read API keys
// - "api_keys:write" - Create API keys
// - "webhooks:read" - Read webhooks
// - "webhooks:write" - Create/update webhooks

Returns:

interface ApiKey {
  id: string;
  name: string;
  key: string; // Full API key (only returned on creation!)
  keyPreview: string;
  permissions: string[];
  isActive: boolean;
  createdAt: Date;
  expiresAt?: Date;
}

Example:

const newApiKey = await buena.default.createApiKey({
  name: "Integration API Key",
  permissions: ["leads:read", "leads:write"],
  description: "For CRM integration",
  expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year
});

console.log(`Created API key: ${newApiKey.name}`);
console.log(`Key: ${newApiKey.key}`); // SAVE THIS! Won't be shown again
console.log(`Permissions: ${newApiKey.permissions.join(", ")}`);

Errors:

  • 400 - Invalid key data (missing name, invalid permissions)
  • 401 - Invalid API key
  • 403 - Insufficient permissions
  • 422 - Validation error
  • 500 - Server error

System Health

healthCheck()

Check the API system status and your connection.

Parameters: None

Returns:

interface HealthCheckResponse {
  status: "healthy" | "degraded" | "down";
  timestamp: Date;
  version: string;
  services: {
    database: "healthy" | "degraded" | "down";
    redis: "healthy" | "degraded" | "down";
    api: "healthy" | "degraded" | "down";
  };
  responseTime: number; // Response time in milliseconds
}

Example:

const health = await buena.default.healthCheck();
console.log(`API Status: ${health.status}`);
console.log(`Version: ${health.version}`);
console.log(`Response Time: ${health.responseTime}ms`);

if (health.status === "healthy") {
  console.log("✅ All systems operational");
} else {
  console.log("⚠️ Some services may be experiencing issues");
  console.log("Service status:", health.services);
}

Errors:

  • 500 - Server error
  • 503 - Service unavailable

Error Handling

All methods can throw SDKError exceptions:

import { SDKError } from "@buena/sdk/models/errors";

try {
  const leads = await buena.default.listLeads();
} catch (error) {
  if (error instanceof SDKError) {
    console.error(`API Error ${error.statusCode}: ${error.message}`);

    // Handle specific error codes
    switch (error.statusCode) {
      case 401:
        console.error("Check your API key");
        break;
      case 429:
        console.error("Rate limit exceeded - wait before retrying");
        break;
      case 500:
        console.error("Server error - contact support if this persists");
        break;
      default:
        console.error("Unexpected error:", error.message);
    }
  } else {
    console.error("Network or other error:", error);
  }
}

Rate Limiting

The API enforces rate limits:

  • 100 requests per minute for most endpoints
  • 20 requests per minute for resource creation (createLead, createApiKey)

Rate limit headers are included in responses:

  • X-RateLimit-Limit - Total requests allowed
  • X-RateLimit-Remaining - Requests remaining
  • X-RateLimit-Reset - Unix timestamp when limit resets
// Handle rate limiting gracefully
async function createLeadWithRetry(
  leadData: CreateLeadRequest,
  maxRetries = 3
) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await buena.default.createLead(leadData);
    } catch (error) {
      if (error instanceof SDKError && error.statusCode === 429) {
        if (attempt === maxRetries) throw error;

        const resetTime = error.headers?.["x-ratelimit-reset"];
        const waitTime = resetTime
          ? parseInt(resetTime) * 1000 - Date.now()
          : 60000;

        console.log(
          `Rate limited. Waiting ${waitTime}ms before retry ${attempt + 1}...`
        );
        await new Promise((resolve) => setTimeout(resolve, waitTime));
      } else {
        throw error;
      }
    }
  }
}

TypeScript Support

The SDK includes full TypeScript definitions:

import {
  BuenaSdk,
  Lead,
  CreateLeadRequest,
  ListLeadsResponse,
  ApiKey,
  HealthCheckResponse,
} from "@buena/sdk";

// Type-safe lead creation
const leadData: CreateLeadRequest = {
  firstName: "Jane",
  lastName: "Smith",
  email: "jane@example.com",
};

const lead: Lead = await buena.default.createLead(leadData);

MCP Integration

The TypeScript SDK includes a built-in MCP (Model Context Protocol) server that enables AI assistants to directly interact with your Buena.ai data.

Starting the MCP Server

# Install the SDK globally or locally
npm install @buena/sdk

# Start the MCP server
BUENA_API_KEY=your-api-key npx @buena/sdk mcp

# Or with custom configuration
npx @buena/sdk mcp --port 3001 --log-level debug

AI Assistant Configuration

Claude Desktop Configuration:

{
  "mcpServers": {
    "buena": {
      "command": "npx",
      "args": ["@buena/sdk", "mcp"],
      "env": {
        "BUENA_API_KEY": "your-api-key-here"
      }
    }
  }
}

Available MCP Tools

The MCP server exposes these tools to AI assistants:

Lead Management Tools

  • buena_list_leads - Search and filter leads
  • buena_create_lead - Create new leads
  • buena_get_lead - Retrieve lead details
  • buena_update_lead - Update lead information
  • buena_delete_lead - Delete leads

API Management Tools

  • buena_list_api_keys - List API keys
  • buena_create_api_key - Create new API keys
  • buena_health_check - Check system status

MCP Usage Examples

Lead Search via AI Assistant:

Human: "Show me all leads from technology companies created this week"

AI Assistant executes:
buena_list_leads({
  search: "technology",
  sort: "created_at",
  order: "desc",
  limit: 50
})

Batch Lead Creation:

Human: "Create leads for these contacts: John Doe (john@acme.com, Acme Corp), Jane Smith (jane@techco.com, TechCo)"

AI Assistant executes:
buena_create_lead({
  firstName: "John",
  lastName: "Doe",
  email: "john@acme.com",
  company: "Acme Corp"
})

buena_create_lead({
  firstName: "Jane",
  lastName: "Smith",
  email: "jane@techco.com",
  company: "TechCo"
})

Lead Analysis Workflow:

Human: "Analyze my leads from the past month and suggest which ones to prioritize"

AI Assistant workflow:
1. buena_list_leads({ sort: "created_at", limit: 100 }) - Get recent leads
2. Analyze lead data (company size, job titles, engagement)
3. buena_update_lead() - Update high-priority leads with tags
4. Provide prioritization recommendations

MCP Server Configuration

Environment Variables:

BUENA_API_KEY=your-api-key          # Required: Your API key
BUENA_API_URL=https://custom-url    # Optional: Custom API endpoint
MCP_SERVER_PORT=3001               # Optional: Server port
MCP_LOG_LEVEL=debug                # Optional: Logging level

Configuration File (buena-mcp.config.json):

{
  "server": {
    "port": 3001,
    "logLevel": "info",
    "timeout": 30000
  },
  "api": {
    "baseUrl": "https://api.buena.ai/api/v2",
    "retries": 3,
    "retryDelay": 1000
  },
  "tools": {
    "enabled": [
      "buena_list_leads",
      "buena_create_lead",
      "buena_get_lead",
      "buena_update_lead",
      "buena_health_check"
    ],
    "limits": {
      "maxLeadsPerQuery": 100,
      "batchSize": 25
    }
  },
  "security": {
    "allowedOrigins": ["*"],
    "requireAuth": true
  }
}

Testing MCP Integration

Manual Server Test:

# Start server in test mode
BUENA_API_KEY=test-key npx @buena/sdk mcp --test

# Test tool availability
curl -X POST http://localhost:3001/mcp \
  -H "Content-Type: application/json" \
  -d '{"method": "tools/list"}'

Integration Test Script:

// test-mcp.ts
import { McpClient } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function testMcpIntegration() {
  const transport = new StdioClientTransport({
    command: "npx",
    args: ["@buena/sdk", "mcp"],
    env: { BUENA_API_KEY: process.env.BUENA_API_KEY },
  });

  const client = new McpClient(
    { name: "test-client", version: "1.0.0" },
    { capabilities: {} }
  );

  await client.connect(transport);

  try {
    // Test health check
    const health = await client.callTool({
      name: "buena_health_check",
      arguments: {},
    });
    console.log("Health check:", health);

    // Test lead listing
    const leads = await client.callTool({
      name: "buena_list_leads",
      arguments: { limit: 5 },
    });
    console.log("Sample leads:", leads);

    // Test lead creation
    const newLead = await client.callTool({
      name: "buena_create_lead",
      arguments: {
        firstName: "Test",
        lastName: "User",
        email: "test@example.com",
        company: "Test Company",
      },
    });
    console.log("Created lead:", newLead);
  } finally {
    await client.close();
  }
}

// Run test
testMcpIntegration().catch(console.error);

Advanced MCP Features

Custom Tool Extensions:

// extend-mcp-server.ts
import { Tool } from "@modelcontextprotocol/sdk/types.js";

export const customBuenaTools: Tool[] = [
  {
    name: "buena_lead_analytics",
    description: "Generate lead analytics and insights",
    inputSchema: {
      type: "object",
      properties: {
        dateRange: {
          type: "string",
          description:
            "Date range for analysis (last_7_days, last_30_days, etc.)",
          enum: ["last_7_days", "last_30_days", "last_90_days", "custom"],
        },
        groupBy: {
          type: "string",
          description: "Field to group analytics by",
          enum: ["company", "status", "source", "created_date"],
        },
        metrics: {
          type: "array",
          items: { type: "string" },
          description: "Metrics to calculate",
          default: ["count", "conversion_rate", "avg_deal_size"],
        },
      },
      required: ["dateRange"],
    },
  },
  {
    name: "buena_lead_scoring",
    description: "Calculate lead scores based on various factors",
    inputSchema: {
      type: "object",
      properties: {
        leadIds: {
          type: "array",
          items: { type: "string" },
          description: "Array of lead IDs to score",
        },
        scoringModel: {
          type: "string",
          description: "Scoring model to use",
          enum: ["basic", "advanced", "custom"],
          default: "basic",
        },
        factors: {
          type: "object",
          description: "Scoring factors and weights",
          properties: {
            companySize: { type: "number", default: 0.3 },
            jobTitle: { type: "number", default: 0.25 },
            industry: { type: "number", default: 0.2 },
            engagement: { type: "number", default: 0.25 },
          },
        },
      },
      required: ["leadIds"],
    },
  },
];

Batch Processing with MCP:

// batch-mcp-operations.ts
async function batchProcessLeads(
  mcpClient: McpClient,
  operations: Array<{
    action: "create" | "update" | "delete";
    data: any;
  }>
) {
  const results = [];
  const batchSize = 10;

  for (let i = 0; i < operations.length; i += batchSize) {
    const batch = operations.slice(i, i + batchSize);

    const batchPromises = batch.map(async (op) => {
      try {
        let result;
        switch (op.action) {
          case "create":
            result = await mcpClient.callTool({
              name: "buena_create_lead",
              arguments: op.data,
            });
            break;
          case "update":
            result = await mcpClient.callTool({
              name: "buena_update_lead",
              arguments: op.data,
            });
            break;
          case "delete":
            result = await mcpClient.callTool({
              name: "buena_delete_lead",
              arguments: { leadId: op.data.id },
            });
            break;
        }
        return { success: true, result, operation: op };
      } catch (error) {
        return { success: false, error: error.message, operation: op };
      }
    });

    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);

    // Add delay between batches to respect rate limits
    if (i + batchSize < operations.length) {
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

  return results;
}

MCP Troubleshooting

Common Issues and Solutions:

  1. Server Won’t Start

    # Check API key
    echo $BUENA_API_KEY
    
    # Test API connectivity
    curl -H "x-api-key: $BUENA_API_KEY" https://api.buena.ai/api/v2/health
    
  2. AI Assistant Connection Issues

    // Debug configuration
    {
      "mcpServers": {
        "buena": {
          "command": "npx",
          "args": ["@buena/sdk", "mcp", "--debug"],
          "env": {
            "BUENA_API_KEY": "your-key",
            "MCP_LOG_LEVEL": "debug"
          }
        }
      }
    }
    
  3. Tool Call Failures

    # Check server logs
    npx @buena/sdk mcp --log-level debug
    
    # Test individual tools
    curl -X POST http://localhost:3001/mcp/call \
      -H "Content-Type: application/json" \
      -d '{"method": "tools/call", "params": {"name": "buena_health_check", "arguments": {}}}'
    

Performance Optimization:

// Optimized MCP client configuration
const mcpClient = new McpClient(
  { name: "buena-client", version: "1.0.0" },
  {
    capabilities: {
      tools: {
        list: true,
        call: true,
      },
    },
  }
);

// Connection with retry logic
async function connectWithRetry(transport: Transport, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await mcpClient.connect(transport);
      console.log("MCP connection established");
      return;
    } catch (error) {
      console.log(`Connection attempt ${attempt} failed:`, error.message);
      if (attempt === maxRetries) throw error;
      await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
    }
  }
}

For complete MCP integration documentation and examples, see the MCP Integration Guide.