Python SDK Integration

The official Python SDK for AIM provides one-line agent registration with automatic identity verification, capability detection, and MCP server discovery. Built for enterprise security with the simplicity of Stripe.

One-Line Setup
secure("agent-name")
Ed25519 Crypto
Military-grade security
Auto-Detection
MCPs & capabilities
Zero Config
Embedded credentials

System Requirements

Prerequisites

  • Python 3.7+ (3.10+ recommended)
  • keyring - Required for secure credential storage (will fail without it!)
  • PyNaCl - For Ed25519 cryptographic operations
  • requests - For HTTP communication
  • cryptography - For additional security features

⚠️ Important: The SDK will fail with "ModuleNotFoundError: No module named 'keyring'" if keyring is not installed. This is a hard requirement, not optional.

Installation

⚠️ NO pip install Available

# Download SDK from AIM Dashboard (Settings → SDK Download)
# There is NO pip package - SDK contains your pre-configured credentials

📦 Download SDK from Dashboard

The AIM SDK must be downloaded from your AIM dashboard as it contains your pre-configured credentials (zero config mode).

After downloading, install required dependencies:

pip install keyring PyNaCl requests cryptography

Note: keyring is required for secure credential storage. On Linux: sudo apt-get install python3-keyring

Why no pip package? The SDK contains your personal credentials and cannot be distributed via PyPI.

✅ Download Pre-Configured SDK (ONLY Option)

This is the ONLY way to get the AIM SDK. It comes with your embedded credentials - zero configuration required.

  1. 1. Login to AIM dashboard
  2. 2. Navigate to Settings → SDK Download
  3. 3. Click "Download Python SDK"
  4. 4. Extract the ZIP file to your project directory
  5. 5. Import and use: from aim_sdk import secure

💡 Tip: The downloaded SDK already contains your API keys and organization credentials. No configuration needed!

Quick Start

⚡ The Stripe Moment - One Line Registration

from aim_sdk import secure

# ONE LINE - That's it! Agent is registered, verified, and ready.
agent = secure("my-agent")

# Now use decorators for automatic verification
@agent.perform_action("read_database", resource="users_table")
def get_user_data(user_id):
    return database.query("SELECT * FROM users WHERE id = ?", user_id)

# The action is automatically verified before execution

Important: Always use the secure() function. This is the recommended enterprise-grade function that emphasizes security-first design.

Configuration

Zero Configuration Mode

If you downloaded the SDK from AIM dashboard, everything is pre-configured.

from aim_sdk import secure

# Zero-configuration mode - Downloads SDK with embedded credentials
# No API keys needed if you downloaded the SDK from AIM dashboard
agent = secure("my-agent")

# Everything is auto-detected:
# - AIM server URL
# - Organization credentials
# - MCP servers the agent talks to
# - Agent capabilities
print(f"Agent ID: {agent.agent_id}")
print(f"Trust Score: {agent.get_trust_score()}")

Manual Configuration

For pip install users or custom deployments.

from aim_sdk import secure

# Manual configuration for pip install users
agent = secure(
    "my-agent",
    api_key="aim_abc123...",  # Your AIM API key
    aim_url="https://api.aim.example.com"  # Your AIM server
)

# Optional: Override auto-detection
agent = secure(
    "my-agent",
    api_key="aim_abc123...",
    display_name="My Awesome Agent",
    description="Production agent for data processing",
    version="2.0.0",
    talks_to=["mcp-server-1", "mcp-server-2"],  # Manual MCP specification
    capabilities=["read_database", "write_file"],  # Manual capabilities
    auto_detect=False  # Disable auto-detection
)

Core Features

Action Verification with Decorators

Use decorators for automatic verification before sensitive operations.

from aim_sdk import secure

agent = secure("data-processor")

# Decorator automatically handles verification
@agent.perform_action("read_file", resource="/data/input.csv")
def process_csv_file(filepath):
    """This function is automatically verified before execution."""
    with open(filepath, 'r') as f:
        data = csv.reader(f)
        return list(data)

# Async support
@agent.perform_action("call_api", resource="https://api.example.com")
async def fetch_external_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# Context manager for manual verification
with agent.verify_action("write_database", resource="users_table"):
    # Action is verified, safe to proceed
    db.execute("INSERT INTO users VALUES (?)", user_data)

MCP Server Auto-Detection

Automatically discovers MCP servers from Claude Desktop configuration.

from aim_sdk import secure

# Automatically detects MCP servers from Claude Desktop config
agent = secure("my-agent")

# View detected MCP servers
detected_mcps = agent.get_detected_mcps()
for mcp in detected_mcps:
    print(f"Found MCP: {mcp['name']} - {mcp['command']}")

# Manual MCP specification (overrides auto-detection)
agent = secure(
    "my-agent",
    talks_to=[
        {"name": "filesystem", "command": "npx @modelcontextprotocol/server-filesystem"},
        {"name": "github", "command": "npx @modelcontextprotocol/server-github"}
    ]
)

# Report runtime MCP detection
agent.report_detected_mcps([
    {"name": "new-mcp", "command": "python mcp_server.py", "detected_at": "runtime"}
])

Capability Management

Fine-grained permission control with automatic capability detection.

from aim_sdk import secure

agent = secure("capability-demo")

# Auto-detected capabilities from code analysis
capabilities = agent.get_capabilities()
print(f"Agent has {len(capabilities)} capabilities")

# Request additional capability (requires admin approval)
agent.request_capability(
    capability_type="write_production_database",
    resource="/prod/database",
    justification="Required for data migration task"
)

# Check if action is allowed
if agent.can_perform("delete_user", resource="users_table"):
    # Safe to proceed
    delete_user(user_id)
else:
    print("Action not permitted - insufficient capabilities")

# Get capability violations
violations = agent.get_violations()
if violations:
    print(f"Warning: {len(violations)} capability violations detected")

Trust Score Monitoring

Real-time trust scoring with ML-powered risk assessment.

from aim_sdk import secure

agent = secure("trust-monitor")

# Get current trust score
trust_score = agent.get_trust_score()
print(f"Current trust score: {trust_score['score']}/100")
print(f"Risk level: {trust_score['risk_level']}")

# Get trust score factors
factors = trust_score['factors']
for factor, value in factors.items():
    print(f"  {factor}: {value}")

# Monitor trust score changes
@agent.on_trust_change
def handle_trust_change(old_score, new_score):
    if new_score < 70:
        alert_admin(f"Trust score dropped to {new_score}")

# Get trust score history
history = agent.get_trust_history(days=30)
for entry in history:
    print(f"{entry['timestamp']}: {entry['score']}")

Error Handling

from aim_sdk import secure
from aim_sdk.exceptions import (
    AIMError,
    AuthenticationError,
    VerificationError,
    ActionDeniedError
)

try:
    agent = secure("my-agent")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
    # Check API key or credentials
except AIMError as e:
    print(f"AIM error: {e}")
    # Handle general AIM errors

# Handle verification errors
try:
    @agent.perform_action("delete_database", resource="production")
    def dangerous_operation():
        # This might be denied
        pass

    dangerous_operation()
except ActionDeniedError as e:
    print(f"Action denied: {e.reason}")
    print(f"Required capability: {e.required_capability}")
except VerificationError as e:
    print(f"Verification failed: {e}")

Advanced Usage

from aim_sdk import secure
import asyncio

# Advanced configuration
agent = secure(
    "advanced-agent",
    api_key="aim_abc123...",

    # Retry configuration
    max_retries=3,
    retry_delay=1.0,

    # Timeout settings
    request_timeout=30,
    verification_timeout=5,

    # Caching
    enable_cache=True,
    cache_ttl=3600,

    # Debugging
    debug=True,
    log_level="DEBUG"
)

# Custom verification handler
@agent.verification_handler
def custom_verification(action, resource, context):
    """Custom logic before standard verification."""
    if context.get("emergency_override"):
        return True  # Skip verification in emergencies

    # Add custom checks
    if action == "delete" and "production" in resource:
        require_two_factor_auth()

    return None  # Continue with standard verification

# Batch operations
actions = [
    ("read_file", "/data/file1.csv"),
    ("read_file", "/data/file2.csv"),
    ("write_file", "/output/result.csv")
]

results = agent.verify_batch(actions)
for action, resource, allowed in results:
    print(f"{action} on {resource}: {'✓' if allowed else '✗'}")

# Performance monitoring
with agent.measure_performance():
    # Your code here
    process_large_dataset()

# Get performance metrics
metrics = agent.get_metrics()
print(f"Avg verification time: {metrics['avg_verification_time']}ms")
print(f"Total verifications: {metrics['total_verifications']}")

Testing

The SDK includes testing utilities for unit and integration tests.

import pytest
from aim_sdk import secure
from aim_sdk.testing import MockAIMClient

def test_agent_registration():
    """Test agent registration with AIM."""
    agent = secure("test-agent", api_key="test_key")
    assert agent.agent_id is not None
    assert agent.is_verified is True

def test_with_mock():
    """Test with mocked AIM client."""
    with MockAIMClient() as mock_agent:
        mock_agent.set_trust_score(85)
        mock_agent.allow_action("read_file", "/test/*")

        # Test your code
        @mock_agent.perform_action("read_file", "/test/data.txt")
        def read_test_file():
            return "test data"

        result = read_test_file()
        assert result == "test data"
        assert mock_agent.verify_called_with("read_file", "/test/data.txt")

@pytest.mark.integration
def test_real_aim_connection():
    """Integration test with real AIM server."""
    agent = secure("integration-test")

    # Test real verification
    with agent.verify_action("test_action", "test_resource"):
        pass  # Should succeed

    # Cleanup
    agent.cleanup()

Environment Variables

VariableDescriptionDefault
AIM_API_KEYAIM API key for authenticationNone (required)
AIM_URLAIM server URLhttp://localhost:8080
AIM_AGENT_NAMEDefault agent nameNone
AIM_AUTO_DETECTEnable auto-detectiontrue
AIM_DEBUGEnable debug loggingfalse
AIM_CACHE_TTLCache TTL in seconds3600

SDK Methods Reference

secure(name, **kwargs)

One-line agent registration (enterprise-grade security function)

agent.perform_action(action, resource)

Decorator for automatic action verification

agent.verify_action(action, resource)

Context manager for manual verification

agent.get_trust_score()

Get current trust score and risk assessment

agent.get_detected_mcps()

Get list of detected MCP servers

agent.get_capabilities()

Get list of agent capabilities

agent.request_capability(type, resource, justification)

Request additional capability (requires approval)

Requirements

  • • Python 3.8 or higher
  • • cryptography >= 41.0.0 (Ed25519 support)
  • • requests >= 2.31.0 (API communication)
  • • pydantic >= 2.0.0 (data validation)
  • • aiohttp >= 3.8.0 (async support, optional)