CUGA LogoCUGA AGENT
Usage

API Integration

Integrate your own APIs and tools with CUGA

Learn how to integrate your own APIs, tools, and services with CUGA to extend its capabilities.

🚀 Integration Overview

CUGA supports multiple integration methods:

  • OpenAPI/Swagger: REST APIs with OpenAPI specifications
  • FastAPI Endpoints: Python functions wrapped as API endpoints
  • MCP Servers: Model Context Protocol servers
  • Custom Tools: Python functions and classes

🌐 OpenAPI Integration

Supported Formats

CUGA can integrate with any API that provides:

  • OpenAPI 3.0+ specification
  • Swagger 2.0 specification
  • JSON Schema definitions

Integration Steps

1. API Registration

Add your API to agent/api/config/mcp_servers.yaml:

# Example: Petstore API
- petstore:
    url: http://localhost:8080/openapi.json
    type: openapi
    auth:
      type: none  # or "bearer", "basic", "api_key"

# Example: Custom API with authentication
- myapi:
    url: https://api.example.com/openapi.json
    type: openapi
    auth:
      type: bearer
      value: Bearer your-token-here

2. API Configuration

Configure API behavior in configurations/apis.toml:

[apis.petstore]
# API-specific settings
timeout = 30
max_retries = 3
cache_enabled = true
cache_ttl = 300

[apis.myapi]
# Custom API settings
timeout = 60
max_retries = 5
rate_limit = 100  # requests per minute

3. Verify Integration

# Check registered APIs
cuga apis list

# Test API connectivity
cuga apis test petstore

# Show API details
cuga apis info petstore

Example: Petstore API

1. Start Petstore Container

# Stop existing container
docker stop petstore 2>/dev/null
docker rm petstore 2>/dev/null

# Pull and run Petstore
docker pull openapitools/openapi-petstore
docker run -d \
  -e OPENAPI_BASE_PATH=/v3 \
  -e DISABLE_API_KEY=1 \
  -e DISABLE_OAUTH=1 \
  -p 8080:8080 \
  --name petstore \
  openapitools/openapi-petstore

2. Register with CUGA

# agent/api/config/mcp_servers.yaml
- petstore:
    url: http://localhost:8080/openapi.json
    type: openapi
    auth:
      type: none

3. Test Integration

# Start CUGA demo
cuga start demo

# Try queries like:
"show me all available pets in the petstore"
"add a new pet named Fluffy to the store"
"find pets by status available"

🐍 FastAPI Integration

Wrapping Python Functions

Convert your Python functions into API endpoints:

1. Create FastAPI Server

# my_tools.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
from typing import Dict, List

app = FastAPI(title="My Tools API")

# Sample data
contacts_db = {
    "john@example.com": {"name": "John Doe", "role": "Developer"},
    "jane@example.com": {"name": "Jane Smith", "role": "Manager"}
}

class Contact(BaseModel):
    name: str
    role: str

@app.get("/contacts/{email}")
def get_contact(email: EmailStr):
    """
    Retrieve details of a contact identified by their email.
    """
    if email not in contacts_db:
        raise HTTPException(404, "Contact not found")
    return contacts_db[email]

@app.get("/contacts")
def list_contacts():
    """
    List all available contacts.
    """
    return list(contacts_db.values())

@app.post("/contacts")
def create_contact(contact: Contact):
    """
    Create a new contact.
    """
    # Implementation here
    return {"message": "Contact created", "contact": contact}

2. Run the Server

# Install dependencies
pip install fastapi uvicorn

# Run server
uvicorn my_tools:app --host 0.0.0.0 --port 8111 --reload

3. Register with CUGA

# agent/api/config/mcp_servers.yaml
- mytools:
    url: http://localhost:8111/openapi.json
    type: openapi
    auth:
      type: none

4. Test Integration

# Start CUGA
cuga start demo

# Try queries like:
"get contact information for john@example.com"
"list all available contacts"
"create a new contact for Alice Johnson"

Advanced FastAPI Features

Authentication

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

security = HTTPBearer()

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.credentials != "valid-token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token"
        )
    return credentials.credentials

@app.get("/secure/contacts")
def get_secure_contacts(token: str = Depends(verify_token)):
    return list(contacts_db.values())

Rate Limiting

from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get("/contacts")
@limiter.limit("10/minute")
def list_contacts(request: Request):
    return list(contacts_db.values())

🔧 MCP Server Integration

Model Context Protocol

MCP servers provide structured tool access:

1. MCP Server Configuration

# agent/api/config/mcp_servers.yaml
- my_mcp_server:
    url: localhost:8000
    type: mcp
    auth:
      type: none
    tools:
      - get_weather
      - calculate_distance
      - send_notification

2. MCP Server Implementation

# mcp_server.py
import asyncio
from mcp.server import Server
from mcp.types import Tool, TextContent

server = Server("my-tools")

@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="get_weather",
            description="Get current weather for a location",
            inputSchema={
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "get_weather":
        location = arguments.get("location", "Unknown")
        return [TextContent(type="text", text=f"Weather in {location}: Sunny")]
    
    return [TextContent(type="text", text="Tool not found")]

if __name__ == "__main__":
    asyncio.run(server.run())

🛠️ Custom Tool Integration

Python Function Tools

Register Python functions directly:

1. Define Tools

# custom_tools.py
from typing import Dict, Any

def calculate_revenue(accounts: list, multiplier: float = 1.0) -> Dict[str, Any]:
    """
    Calculate total revenue from a list of accounts.
    
    Args:
        accounts: List of account dictionaries
        multiplier: Revenue multiplier factor
    
    Returns:
        Dictionary with revenue calculations
    """
    total_revenue = sum(account.get('revenue', 0) for account in accounts)
    adjusted_revenue = total_revenue * multiplier
    
    return {
        "total_revenue": total_revenue,
        "adjusted_revenue": adjusted_revenue,
        "account_count": len(accounts),
        "multiplier": multiplier
    }

def analyze_performance(accounts: list) -> Dict[str, Any]:
    """
    Analyze account performance metrics.
    """
    if not accounts:
        return {"error": "No accounts provided"}
    
    revenues = [acc.get('revenue', 0) for acc in accounts]
    return {
        "total_revenue": sum(revenues),
        "average_revenue": sum(revenues) / len(revenues),
        "max_revenue": max(revenues),
        "min_revenue": min(revenues),
        "top_performers": sorted(accounts, key=lambda x: x.get('revenue', 0), reverse=True)[:3]
    }

2. Register Tools

# agent/api/config/mcp_servers.yaml
- custom_tools:
    type: python
    module: custom_tools
    functions:
      - calculate_revenue
      - analyze_performance

3. Use Tools

# Start CUGA
cuga start demo

# Try queries like:
"calculate revenue for all accounts with a 1.2 multiplier"
"analyze the performance of our top accounts"

🔐 Authentication & Security

Authentication Types

Bearer Token

- secure_api:
    url: https://api.secure.com/openapi.json
    type: openapi
    auth:
      type: bearer
      value: Bearer your-token-here

API Key

- api_key_api:
    url: https://api.example.com/openapi.json
    type: openapi
    auth:
      type: api_key
      name: X-API-Key
      value: your-api-key-here

Basic Authentication

- basic_auth_api:
    url: https://api.example.com/openapi.json
    type: openapi
    auth:
      type: basic
      username: your-username
      password: your-password

OAuth 2.0

- oauth_api:
    url: https://api.example.com/openapi.json
    type: openapi
    auth:
      type: oauth2
      client_id: your-client-id
      client_secret: your-client-secret
      token_url: https://auth.example.com/token

Environment Variables

Store sensitive credentials securely:

- secure_api:
    url: https://api.secure.com/openapi.json
    type: openapi
    auth:
      type: bearer
      value: Bearer ${SECURE_API_TOKEN}
# Set in .env file
export SECURE_API_TOKEN="your-secure-token-here"

📊 API Management

API Registry Commands

# List registered APIs
cuga apis list

# Show API details
cuga apis info myapi

# Test API connectivity
cuga apis test myapi

# Refresh API schemas
cuga apis refresh

# Remove API
cuga apis remove myapi

API Health Monitoring

# Check API health
cuga apis health

# Monitor API performance
cuga apis monitor

# View API logs
cuga apis logs myapi

🧪 Testing Integration

Integration Testing

1. API Connectivity Test

# Test basic connectivity
cuga apis test myapi

# Test with authentication
cuga apis test myapi --auth

# Test specific endpoints
cuga apis test myapi --endpoint /contacts

2. End-to-End Testing

# Start CUGA with your API
cuga start demo

# Test natural language queries
"get contacts from my custom API"
"analyze data from the integrated service"

3. Performance Testing

# Load test your API
cuga apis load-test myapi --requests 100

# Stress test
cuga apis stress-test myapi --duration 300

🔍 Troubleshooting

Common Integration Issues

IssueSolution
🔴 API not foundCheck mcp_servers.yaml configuration
🔴 Authentication failedVerify credentials and auth type
🔴 Schema parsing errorCheck OpenAPI specification validity
🔴 Connection timeoutVerify URL and network connectivity
🔴 CORS errorsConfigure CORS headers in your API server

Debug Commands

# Check API registration
cuga apis list --verbose

# Test API connectivity
cuga apis test myapi --debug

# View API logs
cuga apis logs myapi --tail

# Check configuration
cuga config show --section apis

Debug Tools

# Validate OpenAPI spec
curl -s https://api.example.com/openapi.json | jq .

# Test API endpoint directly
curl -H "Authorization: Bearer token" https://api.example.com/endpoint

# Check CUGA logs
cuga logs --service api-registry

📚 Best Practices

API Design

  1. Clear Documentation: Provide comprehensive OpenAPI specifications
  2. Consistent Naming: Use consistent naming conventions
  3. Error Handling: Implement proper error responses
  4. Rate Limiting: Add rate limiting for production APIs
  5. Versioning: Use API versioning for stability

Security

  1. Authentication: Implement proper authentication
  2. Authorization: Use role-based access control
  3. Input Validation: Validate all input parameters
  4. HTTPS: Use HTTPS for all external APIs
  5. Audit Logging: Log all API interactions

Performance

  1. Caching: Implement appropriate caching strategies
  2. Pagination: Use pagination for large datasets
  3. Compression: Enable response compression
  4. Connection Pooling: Use connection pooling
  5. Monitoring: Monitor API performance metrics

📚 Next Steps

After integrating your APIs:

  1. Save & Reuse: Explore workflow persistence
  2. Evaluation: Test with benchmarks
  3. Development: Test and debug
  4. Advanced Features: Explore advanced capabilities

APIs integrated? Explore Save & Reuse next!