Skip to content

Latest commit

 

History

History
981 lines (831 loc) · 19 KB

File metadata and controls

981 lines (831 loc) · 19 KB

MegaAgent API Reference

1. Overview

The MegaAgent API provides programmatic access to the autonomous revenue generation system. All endpoints are RESTful and return JSON responses.

Base URL

Production: https://api.megaagent.ai/v1
Development: http://localhost:8000/v1

API Versioning

The API version is included in the URL path. The current version is v1. Breaking changes will result in a new API version.

2. Authentication

2.1 Authentication Methods

Method Use Case Header Format
JWT Bearer User authentication Authorization: Bearer <token>
Service Token Service-to-service X-Service-Token: <token>
HMAC Signature Webhooks X-MegaAgent-Signature: t=<timestamp>,v1=<signature>

2.2 JWT Authentication

# Obtain JWT token
curl -X POST https://api.megaagent.ai/v1/auth/login   -H "Content-Type: application/json"   -d '{
    "email": "user@example.com",
    "password": "secure_password"
  }'

# Response
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 3600
}

# Use token in requests
curl -H "Authorization: Bearer <access_token>"   https://api.megaagent.ai/v1/opportunities

2.3 HMAC Signature Verification

import hmac
import hashlib

def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
    """Verify webhook HMAC signature."""
    parts = signature.split(',')
    timestamp = parts[0].split('=')[1]
    sig_hex = parts[1].split('=')[1]

    message = f"{timestamp}:{payload.decode()}".encode()
    expected_sig = hmac.new(
        secret.encode(),
        message,
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(sig_hex, expected_sig)

3. Core Resources

3.1 Opportunities

List Opportunities

GET /v1/opportunities

Query Parameters:

Parameter Type Description Default
status string Filter by status: pending, active, completed all
min_score float Minimum opportunity score 0.0
vertical string Filter by vertical all
page integer Page number 1
per_page integer Results per page 20

Response:

{
  "opportunities": [
    {
      "id": "opp_123abc",
      "name": "AI Analytics Dashboard",
      "vertical": "saas",
      "score": 0.87,
      "expected_irr": 0.45,
      "payback_months": 8,
      "moat_score": 0.75,
      "risk_score": 0.22,
      "scalability_score": 0.91,
      "status": "pending",
      "created_at": "2024-06-12T10:30:00Z",
      "metadata": {
        "market_size": 5000000000,
        "competition_level": "medium",
        "technical_complexity": "high"
      }
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 20,
    "total": 150,
    "pages": 8
  }
}

Get Opportunity

GET /v1/opportunities/{opportunity_id}

Response:

{
  "id": "opp_123abc",
  "name": "AI Analytics Dashboard",
  "vertical": "saas",
  "score": 0.87,
  "expected_irr": 0.45,
  "payback_months": 8,
  "moat_score": 0.75,
  "risk_score": 0.22,
  "scalability_score": 0.91,
  "status": "active",
  "created_at": "2024-06-12T10:30:00Z",
  "updated_at": "2024-06-12T14:20:00Z",
  "metadata": {
    "market_size": 5000000000,
    "competition_level": "medium",
    "technical_complexity": "high",
    "target_customers": ["startups", "smb", "enterprise"],
    "pricing_model": "subscription"
  },
  "economic_analysis": {
    "total_addressable_market": 5000000000,
    "serviceable_addressable_market": 500000000,
    "serviceable_obtainable_market": 50000000,
    "market_growth_rate": 0.25,
    "competitive_advantage_period": 24
  },
  "execution_plan": {
    "phases": [
      {
        "name": "MVP Development",
        "duration_days": 30,
        "resources_required": {
          "developers": 4,
          "designers": 1,
          "marketing": 1
        }
      }
    ]
  }
}

Create Opportunity

POST /v1/opportunities

Request Body:

{
  "name": "Blockchain Payment Gateway",
  "vertical": "fintech",
  "market_data": {
    "total_market_size": 10000000000,
    "growth_rate": 0.30,
    "competition_count": 15
  },
  "technical_requirements": {
    "complexity": "very_high",
    "time_to_market": 90,
    "required_expertise": ["blockchain", "payments", "security"]
  }
}

3.2 Monetization

Get Pricing Quote

POST /v1/monetizer/quote

Request Body:

{
  "product_id": "prod_456def",
  "segment_id": "seg_789ghi",
  "context": {
    "user_value_score": 0.75,
    "usage_history": {
      "api_calls_30d": 15000,
      "data_processed_gb": 250
    },
    "competitor_pricing": {
      "competitor_a": 99.00,
      "competitor_b": 149.00
    }
  }
}

Response:

{
  "quote_id": "quote_abc123",
  "product_id": "prod_456def",
  "segment_id": "seg_789ghi",
  "recommended_price": 79.00,
  "confidence_interval": {
    "lower": 69.00,
    "upper": 89.00,
    "confidence": 0.95
  },
  "pricing_method": "contextual_thompson",
  "optimization_metrics": {
    "expected_conversion": 0.15,
    "expected_ltv": 2400.00,
    "price_elasticity": -1.2
  },
  "expires_at": "2024-06-12T11:00:00Z"
}

Execute Pricing Strategy

POST /v1/monetizer/execute

Request Body:

{
  "quote_id": "quote_abc123",
  "adjustments": {
    "discount_percentage": 10,
    "reason": "first_time_customer"
  }
}

3.3 Revenue Tracking

Record Revenue Event

POST /v1/revenue/events

Request Body:

{
  "event_type": "payment_received",
  "amount": 79.00,
  "currency": "USD",
  "product_id": "prod_456def",
  "customer_id": "cust_123abc",
  "metadata": {
    "payment_method": "stripe",
    "invoice_id": "inv_789def",
    "subscription_id": "sub_456ghi"
  }
}

Response:

{
  "event_id": "evt_123abc",
  "status": "recorded",
  "timestamp": "2024-06-12T10:35:00Z",
  "transaction_hash": "0x1234567890abcdef",
  "ledger_entry": {
    "debit": {
      "account": "accounts_receivable",
      "amount": 79.00
    },
    "credit": {
      "account": "revenue_saas",
      "amount": 79.00
    }
  }
}

Get Revenue Analytics

GET /v1/revenue/analytics

Query Parameters:

Parameter Type Description Default
start_date date Start date (YYYY-MM-DD) 30 days ago
end_date date End date (YYYY-MM-DD) today
granularity string day, week, month day
group_by string product, vertical, customer_segment none

Response:

{
  "summary": {
    "total_revenue": 2450000.00,
    "recurring_revenue": 1800000.00,
    "one_time_revenue": 650000.00,
    "growth_rate": 0.23,
    "churn_rate": 0.05,
    "net_revenue_retention": 1.15
  },
  "time_series": [
    {
      "date": "2024-06-01",
      "revenue": 78500.00,
      "new_customers": 45,
      "churned_customers": 3,
      "expansion_revenue": 12000.00
    }
  ],
  "breakdown": {
    "by_product": [
      {
        "product_id": "prod_456def",
        "revenue": 980000.00,
        "percentage": 0.40
      }
    ],
    "by_vertical": [
      {
        "vertical": "saas",
        "revenue": 1470000.00,
        "percentage": 0.60
      }
    ]
  }
}

3.4 Portfolio Management

Get Portfolio Status

GET /v1/portfolio/status

Response:

{
  "portfolio_value": 125000000.00,
  "total_positions": 42,
  "active_positions": 38,
  "performance_metrics": {
    "total_return": 0.35,
    "annualized_return": 0.42,
    "sharpe_ratio": 2.1,
    "max_drawdown": 0.08,
    "value_at_risk": 0.04
  },
  "risk_metrics": {
    "portfolio_cvar": 0.045,
    "concentration_risk": 0.18,
    "correlation_risk": 0.22
  },
  "positions": [
    {
      "opportunity_id": "opp_123abc",
      "weight": 0.08,
      "current_value": 10000000.00,
      "unrealized_pnl": 2500000.00,
      "return": 0.25
    }
  ]
}

Rebalance Portfolio

POST /v1/portfolio/rebalance

Request Body:

{
  "strategy": "risk_parity",
  "constraints": {
    "max_position_size": 0.15,
    "min_position_size": 0.01,
    "target_risk": 0.05,
    "turnover_limit": 0.20
  }
}

3.5 Agent Management

List Agents

GET /v1/agents

Response:

{
  "agents": [
    {
      "id": "agent_123abc",
      "type": "vertical_agent",
      "vertical": "saas",
      "status": "active",
      "health_score": 0.95,
      "metrics": {
        "tasks_completed": 1523,
        "success_rate": 0.94,
        "average_latency_ms": 245
      },
      "resources": {
        "cpu_usage": 0.65,
        "memory_usage": 0.72,
        "concurrent_tasks": 5
      }
    }
  ]
}

Control Agent

POST /v1/agents/{agent_id}/control

Request Body:

{
  "action": "scale",
  "parameters": {
    "replicas": 5,
    "reason": "increased_load"
  }
}

4. Streaming APIs

4.1 WebSocket Events

// Connect to WebSocket
const ws = new WebSocket('wss://api.megaagent.ai/v1/events');

// Authentication
ws.send(JSON.stringify({
  type: 'auth',
  token: 'your-jwt-token'
}));

// Subscribe to events
ws.send(JSON.stringify({
  type: 'subscribe',
  channels: ['opportunities', 'revenue', 'alerts']
}));

// Handle messages
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Event:', data);
};

Event Types:

// Opportunity Created
{
  "type": "opportunity.created",
  "data": {
    "id": "opp_123abc",
    "name": "New SaaS Opportunity",
    "score": 0.92
  },
  "timestamp": "2024-06-12T10:30:00Z"
}

// Revenue Milestone
{
  "type": "revenue.milestone",
  "data": {
    "milestone": "monthly_target",
    "achieved": 2500000.00,
    "target": 2000000.00,
    "percentage": 125
  },
  "timestamp": "2024-06-12T23:59:59Z"
}

// System Alert
{
  "type": "system.alert",
  "data": {
    "severity": "warning",
    "component": "monetizer",
    "message": "High pricing variance detected",
    "details": {
      "product_id": "prod_456def",
      "variance": 0.35
    }
  },
  "timestamp": "2024-06-12T15:45:00Z"
}

4.2 Server-Sent Events (SSE)

# Subscribe to real-time metrics
curl -H "Authorization: Bearer <token>"   -H "Accept: text/event-stream"   https://api.megaagent.ai/v1/metrics/stream

# Response stream
event: metric
data: {"name": "revenue_total", "value": 125450000.00, "timestamp": "2024-06-12T10:30:00Z"}

event: metric
data: {"name": "active_opportunities", "value": 42, "timestamp": "2024-06-12T10:30:01Z"}

event: heartbeat
data: {"timestamp": "2024-06-12T10:30:30Z"}

5. Webhooks

5.1 Webhook Configuration

POST /v1/webhooks

Request Body:

{
  "url": "https://your-domain.com/webhooks/megaagent",
  "events": [
    "opportunity.created",
    "opportunity.executed",
    "revenue.received",
    "portfolio.rebalanced"
  ],
  "secret": "whsec_your_webhook_secret",
  "active": true
}

5.2 Webhook Payload

{
  "id": "evt_123abc",
  "type": "opportunity.executed",
  "created": "2024-06-12T10:30:00Z",
  "data": {
    "opportunity_id": "opp_123abc",
    "execution_time_ms": 4523,
    "result": "success",
    "artifacts": [
      {
        "type": "deployment",
        "url": "https://app-123.megaagent.ai"
      }
    ]
  }
}

5.3 Webhook Security

# Verify webhook signature
import hmac
import hashlib
from flask import request, abort

def verify_webhook():
    payload = request.get_data()
    signature = request.headers.get('X-MegaAgent-Signature')

    if not signature:
        abort(401)

    parts = signature.split(',')
    timestamp = parts[0].split('=')[1]
    sig_hex = parts[1].split('=')[1]

    # Verify timestamp is recent (within 5 minutes)
    if abs(int(timestamp) - int(time.time())) > 300:
        abort(401)

    # Verify signature
    expected = hmac.new(
        WEBHOOK_SECRET.encode(),
        f"{timestamp}:{payload.decode()}".encode(),
        hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(sig_hex, expected):
        abort(401)

6. Error Handling

6.1 Error Response Format

{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "Opportunity opp_123abc does not exist",
    "details": {
      "resource_type": "opportunity",
      "resource_id": "opp_123abc"
    },
    "request_id": "req_456def",
    "timestamp": "2024-06-12T10:30:00Z"
  }
}

6.2 Error Codes

Code HTTP Status Description
UNAUTHORIZED 401 Missing or invalid authentication
FORBIDDEN 403 Insufficient permissions
RESOURCE_NOT_FOUND 404 Resource does not exist
VALIDATION_ERROR 400 Invalid request parameters
RATE_LIMIT_EXCEEDED 429 Too many requests
INTERNAL_ERROR 500 Server error
SERVICE_UNAVAILABLE 503 Temporary outage

6.3 Retry Strategy

import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Configure retry strategy
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
)

adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("https://", adapter)

# Make request with automatic retry
response = session.get(
    "https://api.megaagent.ai/v1/opportunities",
    headers={"Authorization": f"Bearer {token}"}
)

7. Rate Limiting

7.1 Rate Limit Tiers

Tier Requests/Minute Burst Use Case
Free 60 10 Development
Basic 600 100 Small applications
Pro 6,000 1,000 Production
Enterprise Unlimited Custom High-volume

7.2 Rate Limit Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 600
X-RateLimit-Remaining: 595
X-RateLimit-Reset: 1718190600
X-RateLimit-Burst-Limit: 100
X-RateLimit-Burst-Remaining: 95

7.3 Handling Rate Limits

def make_request_with_rate_limit(url, headers):
    response = requests.get(url, headers=headers)

    if response.status_code == 429:
        # Get retry after from header
        retry_after = int(response.headers.get('Retry-After', 60))
        print(f"Rate limited. Retrying after {retry_after} seconds")
        time.sleep(retry_after)
        return make_request_with_rate_limit(url, headers)

    return response

8. Pagination

8.1 Cursor-Based Pagination

GET /v1/revenue/transactions?cursor=eyJpZCI6MTIzNDU2fQ&limit=50

Response:

{
  "data": [...],
  "pagination": {
    "cursor": "eyJpZCI6MTIzNTA2fQ",
    "has_more": true,
    "total_count": 15234
  }
}

8.2 Page-Based Pagination

GET /v1/opportunities?page=2&per_page=50

Response:

{
  "data": [...],
  "pagination": {
    "page": 2,
    "per_page": 50,
    "total": 523,
    "pages": 11,
    "prev_page": 1,
    "next_page": 3
  }
}

9. Filtering and Sorting

9.1 Filter Syntax

GET /v1/opportunities?filter[status]=active&filter[score][gte]=0.8&filter[vertical][in]=saas,fintech

9.2 Sort Syntax

GET /v1/opportunities?sort=-score,created_at

Sort Prefixes:

  • No prefix: Ascending order
  • - prefix: Descending order

9.3 Field Selection

GET /v1/opportunities?fields=id,name,score,status

10. Batch Operations

10.1 Batch Create

POST /v1/batch/opportunities

Request Body:

{
  "operations": [
    {
      "method": "POST",
      "path": "/opportunities",
      "body": {
        "name": "Opportunity 1",
        "vertical": "saas"
      }
    },
    {
      "method": "POST",
      "path": "/opportunities",
      "body": {
        "name": "Opportunity 2",
        "vertical": "fintech"
      }
    }
  ]
}

Response:

{
  "results": [
    {
      "status": 201,
      "body": {
        "id": "opp_123abc",
        "name": "Opportunity 1"
      }
    },
    {
      "status": 201,
      "body": {
        "id": "opp_456def",
        "name": "Opportunity 2"
      }
    }
  ]
}

11. API SDKs

11.1 Python SDK

from megaagent import Client

# Initialize client
client = Client(api_key="your-api-key")

# List opportunities
opportunities = client.opportunities.list(
    status="pending",
    min_score=0.8
)

# Create opportunity
opportunity = client.opportunities.create(
    name="New SaaS Product",
    vertical="saas",
    market_data={
        "total_market_size": 1000000000,
        "growth_rate": 0.25
    }
)

# Get pricing quote
quote = client.monetizer.get_quote(
    product_id="prod_123",
    segment_id="seg_456",
    context={"user_value_score": 0.8}
)

11.2 Node.js SDK

const MegaAgent = require('@megaagent/sdk');

// Initialize client
const client = new MegaAgent({
  apiKey: 'your-api-key'
});

// List opportunities
const opportunities = await client.opportunities.list({
  status: 'pending',
  minScore: 0.8
});

// Subscribe to events
client.events.on('opportunity.created', (event) => {
  console.log('New opportunity:', event.data);
});

// Start streaming
await client.events.connect();

11.3 Go SDK

package main

import (
    "github.com/megaagent/megaagent-go"
)

func main() {
    // Initialize client
    client := megaagent.NewClient("your-api-key")

    // List opportunities
    opportunities, err := client.Opportunities.List(&megaagent.OpportunityListParams{
        Status: megaagent.String("pending"),
        MinScore: megaagent.Float64(0.8),
    })

    if err != nil {
        log.Fatal(err)
    }

    // Process opportunities
    for _, opp := range opportunities.Data {
        fmt.Printf("Opportunity: %s (score: %.2f)\n", opp.Name, opp.Score)
    }
}

12. Testing

12.1 Sandbox Environment

Base URL: https://sandbox.megaagent.ai/v1

Test Credentials:

{
  "api_key": "test_sk_1234567890abcdef",
  "webhook_secret": "test_whsec_abcdef1234567890"
}

12.2 Test Data

Test IDs:

  • Always succeeds: test_success_*
  • Always fails: test_fail_*
  • Returns specific error: test_error_{code}_*

Example:

# This will always succeed
curl -X POST https://sandbox.megaagent.ai/v1/opportunities/test_success_123/execute

# This will return a 404 error
curl -X GET https://sandbox.megaagent.ai/v1/opportunities/test_error_404_abc

13. Changelog

Version 1.1.0 (2024-06-15)

  • Added batch operations endpoint
  • Improved rate limiting with burst support
  • New webhook event types
  • Performance improvements

Version 1.0.0 (2024-05-01)

  • Initial API release
  • Core endpoints for opportunities, monetization, revenue
  • WebSocket support for real-time events
  • comprehensive documentation

14. Support

API Status

Contact

SLA

  • Uptime: 99.9%
  • Response Time: < 200ms (p95)
  • Support Response: < 24 hours