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.

GET/user/:addressFree

Get Position

Full position snapshot: collateral, debt, health factor, effective LTV. Read this before every action.

MCPget_market_ratesFree

Get Market Rates

Current Aave V3 borrow/supply APY, utilization, and TVL for WBTC, WETH, USDC on Arbitrum and Base. No auth required.

MCPget_liquidation_distanceFree

Get Liquidation Distance

Your health factor, current LTV, and exactly how far (in % price drop) you are from liquidation. Stack at 40% LTV needs a 49% drop — Aave average needs just 6%.

PUT/auto-deposit/:addressFee: 2% per conversion

Configure DCA

Set how much USDC to convert to BTC/ETH per cycle, which assets, and timing. The loop runs automatically from here.

PUT/auto-borrow/:addressFee: 2% per borrow

Enable Auto-Borrow Loop

Enable the compounding loop. Stack borrows more USDC when HF is healthy and re-invests it into BTC/ETH. Set hf_start and hf_pause thresholds.

MCPpreview_actionFree

Preview Action

Simulate any treasury action and receive a signed execution envelope before committing. Zero cost, zero risk.

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

Live

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

get_market_ratesBorrow/supply APY, utilization, TVL per asset and chain — no auth
get_liquidation_distanceHealth factor, LTV, and exact drop % to liquidation — no auth
get_portfolio_stateFull position: collateral, debt, effective LTV — no auth
get_policy_stateActive constraints, protection thresholds, delegation status
get_protection_statusBPL monitoring state, trigger distance, last action
preview_actionSimulate any treasury action before committing
relay_signed_transactionSubmit a signed transaction through the Stack gateway
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.

Ready to build an agent?

The API is live. Register your agent wallet and make your first call in minutes.

Open the App