AI Agent Guide

Build AI Agents on Stackit.ai

AI agents interact with Stackit.ai through the same API as human users — with the same safety rails, hard limits, and liquidation protection. This guide covers how to build agents that manage treasury operations.

Core Principle

AI agents cannot break the safety rails. Auto-repay triggers and borrowing limits are enforced at the protocol level. An agent can request any action, but the system will reject anything that violates safety rules. Stackit.ai recommends a 60% LTV ceiling where protection is strongest — but the underlying lending protocol (currently Aave) supports higher LTV if needed. The system still protects you at higher levels, it just repays more aggressively. As Stackit.ai adds more lending protocols, options may expand further.

Safety Guarantees for Agents

60% Recommended LTV Ceiling

Default ceiling with strongest protection. Higher LTV is possible if the underlying protocol (currently Aave) allows — the system repays more aggressively at elevated levels.

Auto-Repay Protection

Triggers automatically during downturns. Agents don't need to implement their own protection logic.

Rejection with Reason

Unsafe requests return a 403 with a clear error explaining why and what the safe alternative is.

Full Audit Trail

Every agent action is logged with timestamps, API key, and parameters for compliance.

What Agents Can Do

Actions with a 2% fee are subject to volume discounts applied automatically as platform volume grows.

POST/api/v1/depositsFee: 2%

Deposit Funds

Initiate USDC deposits into the treasury. Agents can automate regular deposits on a schedule (daily, weekly) for dollar-cost averaging.

GET/api/v1/healthFree

Check Treasury Health

Query current LTV, health score, and auto-repay status. Use for monitoring, alerting, and decision-making.

GET/api/v1/treasuryFree

Get Treasury Status

Full treasury overview: holdings, balances, LTV, utilization. Use for reporting and analysis.

POST/api/v1/borrowFee: 2% + Aave rate

Borrow Against Holdings

Request a borrow within safe LTV limits. The system rejects requests that would breach safety rails. One-time 2% Stackit.ai fee plus Aave’s variable interest rate (set by Aave, not Stackit.ai).

POST/api/v1/convertFee: 2%

Convert USDC

Convert USDC to BTC or ETH. Use for rebalancing or increasing crypto exposure.

POST/api/v1/repayFree

Manual Repay

Repay outstanding borrows to reduce LTV. Useful when agents detect improving market conditions.

Integration Patterns

REST API (Available Now)

Direct HTTP calls to Stackit.ai endpoints. Works with any language or framework. Agents authenticate with an API key and call endpoints directly.

# Example: Check treasury health
curl -X GET https://api.stackit.ai/api/v1/health \
  -H "Authorization: Bearer sk_live_your_key"

# Example: Create a deposit
curl -X POST https://api.stackit.ai/api/v1/deposits \
  -H "Authorization: Bearer sk_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{"amount": 10000, "allocation": {"btc": 60, "eth": 40}}'

MCP Server

Coming Soon

Model Context Protocol server enabling Claude, ChatGPT, Gemini, and other AI platforms to discover and use Stackit.ai's treasury capabilities as native tools. Same safety guarantees as the REST API.

MCP Tools

preview_actionSimulate any treasury action and receive an unsigned Base transaction
relay_signed_transactionSubmit a signed transaction for relay and tracking
get_gateway_statusPoll any prior request by requestId

Wallet-sovereign: Stackit.ai never holds your keys. All actions return unsigned transactions — you sign and submit.

x402 Micropayment Auth

Live

Agents can authenticate by paying per request via the HTTP 402 protocol — no API key signup, no human approval loop. Ideal for ephemeral or autonomous agents that need instant access.

# Two auth paths — use whichever fits your agent

# Path 1: Bearer token (treasury-managed agents)
Authorization: Bearer sk_live_your_api_key

# Path 2: x402 micropayment (wallet-sovereign agents)
# Send payment header with request — no signup required
X-Payment: <base64-encoded payment proof>

Pre-Built Agent Skills

Pre-packaged agent skill definitions for common treasury workflows: DCA autopilot, expense borrowing, health monitoring, and rebalancing. Plug into any agent framework.

Agent Code Examples

Python SDK

Python
import requests

class StackitClient:
    def __init__(self, api_key: str, base_url="https://api.stackit.ai"):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

    def get_health(self):
        r = requests.get(f"{self.base_url}/api/v1/health", headers=self.headers)
        r.raise_for_status()
        return r.json()

    def get_treasury(self):
        r = requests.get(f"{self.base_url}/api/v1/treasury", headers=self.headers)
        r.raise_for_status()
        return r.json()

    def deposit(self, amount: float, allocation=None):
        body = {"amount": amount}
        if allocation:
            body["allocation"] = allocation
        r = requests.post(f"{self.base_url}/api/v1/deposits", json=body, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def borrow(self, amount: float, purpose=None):
        body = {"amount": amount}
        if purpose:
            body["purpose"] = purpose
        r = requests.post(f"{self.base_url}/api/v1/borrow", json=body, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def estimate(self, action: str, amount: float, target=None):
        body = {"action": action, "amount": amount}
        if target:
            body["target"] = target
        r = requests.post(f"{self.base_url}/api/v1/estimate", json=body, headers=self.headers)
        r.raise_for_status()
        return r.json()

# Usage
client = StackitClient("sk_live_your_key")
health = client.get_health()
print(f"Health: {health['health_score']}, LTV: {health['ltv']}%")

TypeScript / Node.js

TypeScript
class StackitClient {
  private baseUrl: string;
  private headers: Record<string, string>;

  constructor(apiKey: string, baseUrl = 'https://api.stackit.ai') {
    this.baseUrl = baseUrl;
    this.headers = {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    };
  }

  async getHealth() {
    const r = await fetch(`${this.baseUrl}/api/v1/health`, { headers: this.headers });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }

  async getTreasury() {
    const r = await fetch(`${this.baseUrl}/api/v1/treasury`, { headers: this.headers });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }

  async deposit(amount: number, allocation?: { btc: number; eth: number }) {
    const r = await fetch(`${this.baseUrl}/api/v1/deposits`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({ amount, allocation }),
    });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }

  async borrow(amount: number, purpose?: string) {
    const r = await fetch(`${this.baseUrl}/api/v1/borrow`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({ amount, purpose }),
    });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }

  async estimate(action: string, amount: number, target?: string) {
    const r = await fetch(`${this.baseUrl}/api/v1/estimate`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({ action, amount, target }),
    });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }
}

// Usage
const client = new StackitClient('sk_live_your_key');
const health = await client.getHealth();
console.log(`Health: ${health.health_score}, LTV: ${health.ltv}%`);

Full Workflow: Deposit → Monitor → Borrow → Repay

TypeScript
const client = new StackitClient('sk_live_your_key');

// Step 1: Estimate deposit fees
const estimate = await client.estimate('deposit', 50000);
console.log(`Fee: $${estimate.stackit_fee}, Net: $${estimate.net_amount}`);

// Step 2: Make the deposit
const deposit = await client.deposit(50000, { btc: 60, eth: 40 });
console.log(`Deposit ${deposit.deposit_id}: $${deposit.net_amount} deposited`);

// Step 3: Monitor health
const health = await client.getHealth();
console.log(`Health: ${health.health_score}, LTV: ${health.ltv}%`);

// Step 4: Borrow if healthy
if (health.ltv < 45) {
  const borrow = await client.borrow(15000, 'payroll-march');
  console.log(`Borrowed $${borrow.amount_usdc}, LTV: ${borrow.ltv_after}%`);
}

// Step 5: Repay when ready
const repay = await fetch('https://api.stackit.ai/api/v1/repay', {
  method: 'POST',
  headers: client.headers,
  body: JSON.stringify({ amount: 5000 }),
}).then(r => r.json());

console.log(`Repaid $${repay.amount_usdc}, LTV: ${repay.ltv_after}%`);

Example Use Cases

Treasury Autopilot

An AI agent monitors a company's cash flow and automatically deposits excess cash into BTC/ETH treasury on a regular schedule. The agent follows DCA rules and adjusts deposit amounts based on available cash.

Example Logic

Every Monday, check bank balance → if balance > $50K operating reserve → deposit excess into treasury with 60/40 BTC/ETH split.

Expense Management

An AI agent borrows against treasury holdings to cover business expenses, staying within safe LTV ranges. It labels each borrow by purpose for tracking.

Example Logic

Payroll due Friday → check available borrowing capacity → if LTV would stay under 45% → borrow $15K labeled 'payroll-march'.

Risk Monitoring

An AI agent continuously monitors health scores and LTV. It alerts human operators when attention is needed and can initiate defensive actions like manual repayment.

Example Logic

Every hour → GET /health → if health_score < 70 → alert team Slack channel → if LTV > 48% → initiate manual repay of 10% outstanding.

Multi-Treasury Management

A company with multiple business entities runs separate treasuries. An AI agent manages each independently, optimizing across all of them.

Example Logic

For each entity → check treasury status → rebalance if allocation drifted > 5% from target → report weekly summary to CFO.

Best Practices

Check health before acting

Always GET /health before POST operations. Use the health score to decide whether to proceed.

Handle 403 gracefully

A 403 means the safety rails blocked your request. Don't retry — adjust the amount or wait for conditions to improve.

Log everything

Store all API responses locally. This helps with debugging and gives you a complete audit trail.

Use purpose labels

When borrowing, include a purpose label (e.g., 'payroll', 'vendor-payment'). This makes treasury reporting much easier.

Respect rate limits

GET endpoints: 100/min. POST endpoints: 20/min. Use the X-RateLimit headers to pace your requests.

Don't implement your own safety logic

The protocol enforces all safety rules. You don't need to check LTV before borrowing — the system will reject unsafe requests. Focus on business logic, not risk management.

Generate a Keypair

Before registering an agent, generate an ECDSA keypair. The public key is submitted during registration. The private key stays with your agent and is used to sign transactions.

Node.js (viem)

import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'

const privateKey = generatePrivateKey()
const account = privateKeyToAccount(privateKey)

console.log('Private key (keep secret):', privateKey)
console.log('Public key (submit to Stackit.ai):', account.address)

Python (eth-account)

from eth_account import Account
import secrets

private_key = "0x" + secrets.token_hex(32)
account = Account.from_key(private_key)

print(f"Private key (keep secret): {private_key}")
print(f"Public key (submit to Stackit.ai): {account.address}")

Ready to build an agent?

Register your agent to get an API key and wallet — no human approval needed.

Register an Agent