The MegaAgent API provides programmatic access to the autonomous revenue generation system. All endpoints are RESTful and return JSON responses.
Production: https://api.megaagent.ai/v1
Development: http://localhost:8000/v1
The API version is included in the URL path. The current version is v1. Breaking changes will result in a new API version.
| 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> |
# 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/opportunitiesimport 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)GET /v1/opportunitiesQuery 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 /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
}
}
]
}
}POST /v1/opportunitiesRequest 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"]
}
}POST /v1/monetizer/quoteRequest 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"
}POST /v1/monetizer/executeRequest Body:
{
"quote_id": "quote_abc123",
"adjustments": {
"discount_percentage": 10,
"reason": "first_time_customer"
}
}POST /v1/revenue/eventsRequest 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 /v1/revenue/analyticsQuery 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
}
]
}
}GET /v1/portfolio/statusResponse:
{
"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
}
]
}POST /v1/portfolio/rebalanceRequest Body:
{
"strategy": "risk_parity",
"constraints": {
"max_position_size": 0.15,
"min_position_size": 0.01,
"target_risk": 0.05,
"turnover_limit": 0.20
}
}GET /v1/agentsResponse:
{
"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
}
}
]
}POST /v1/agents/{agent_id}/controlRequest Body:
{
"action": "scale",
"parameters": {
"replicas": 5,
"reason": "increased_load"
}
}// 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"
}# 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"}POST /v1/webhooksRequest Body:
{
"url": "https://your-domain.com/webhooks/megaagent",
"events": [
"opportunity.created",
"opportunity.executed",
"revenue.received",
"portfolio.rebalanced"
],
"secret": "whsec_your_webhook_secret",
"active": true
}{
"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"
}
]
}
}# 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){
"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"
}
}| 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 |
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}"}
)| 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 |
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: 95def 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 responseGET /v1/revenue/transactions?cursor=eyJpZCI6MTIzNDU2fQ&limit=50Response:
{
"data": [...],
"pagination": {
"cursor": "eyJpZCI6MTIzNTA2fQ",
"has_more": true,
"total_count": 15234
}
}GET /v1/opportunities?page=2&per_page=50Response:
{
"data": [...],
"pagination": {
"page": 2,
"per_page": 50,
"total": 523,
"pages": 11,
"prev_page": 1,
"next_page": 3
}
}GET /v1/opportunities?filter[status]=active&filter[score][gte]=0.8&filter[vertical][in]=saas,fintechGET /v1/opportunities?sort=-score,created_atSort Prefixes:
- No prefix: Ascending order
-prefix: Descending order
GET /v1/opportunities?fields=id,name,score,statusPOST /v1/batch/opportunitiesRequest 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"
}
}
]
}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}
)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();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)
}
}Base URL: https://sandbox.megaagent.ai/v1
Test Credentials:
{
"api_key": "test_sk_1234567890abcdef",
"webhook_secret": "test_whsec_abcdef1234567890"
}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- Added batch operations endpoint
- Improved rate limiting with burst support
- New webhook event types
- Performance improvements
- Initial API release
- Core endpoints for opportunities, monetization, revenue
- WebSocket support for real-time events
- comprehensive documentation
- Status Page: https://status.megaagent.ai
- API Health: https://api.megaagent.ai/v1/health
- Documentation: https://docs.megaagent.ai
- Support: support@megaagent.ai
- Community: https://community.megaagent.ai
- Uptime: 99.9%
- Response Time: < 200ms (p95)
- Support Response: < 24 hours