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.

Last updated June 12, 2026

Agent test path

Start with a free no-auth call, connect the MCP endpoint, then preview a sandbox action before graduating to bearer auth or x402.

curl -s https://www.stackit.ai/api/v1/public/liquidation-distance?ltv=40 | jq
claude mcp add stackit https://www.stackit.ai/api/mcp

Full ladder: /docs/quickstart-agents or copy-paste Claude setup: /docs/claude-mcp-agent-setup

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.

Two Custody Paths

Wallet-sovereign (bring your own wallet)

Your agent keeps its own key. Actions return unsigned transactions; the agent signs and submits them to POST /api/v1/relay. Stackit.ai never sees a private key. This is the default for autonomous agents and pairs with x402 pay-per-call auth.

Delegated automation (managed treasuries)

The treasury wallet is owned by the operator. Stackit.ai automation is added as a revocable additional signer, and an on-wallet policy compiled from the approved strategy gates every transaction — deny-all until the operator approves delegation, revocable at any time. Delegation states are readable via get_policy_state: not_granted, approved_pending_funds, active, revoked_pending_settlement, revoked.

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

You never pay for safety. Deposits cost 2%, buys cost 2% of the amount converted, and borrowing costs 2% per execution — including the automated re-leverage cycles that rebuild your position as prices recover. The per-execution fee is disclosed when you enable the auto-borrow loop, every execution is itemized with its trigger, and downward legs and exits are always free. Model your expected cycle frequency and judge cost net of all fees.

GET/api/v1/treasuryFree

Get Treasury State

Full position snapshot: collateral, debt, health score, 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%.

POST/api/v1/treasuriesFree

Create Treasury

Register a treasury bound to a wallet with a policy preset (conservative, balanced, aggressive) and execution mode. Returns a treasury_id and api_key.

POST/api/v1/deposits + /api/v1/convertFee: 2% deposit + 2% buy

Deposit & Convert

Deposit USDC and convert into BTC/ETH. Deposits carry the 2% entry fee; converting carries the 2% buy fee. Wallet-mode treasuries get unsigned transactions to sign and relay.

POST/api/v1/borrowFee: 2% per execution

Borrow

Borrow against collateral within the policy ceiling. 2% of the amount borrowed, per execution — including automated re-leverage cycles. Aave's variable rate passes through.

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. The machine-readable spec is available at /openapi.json.

# 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.

claude mcp add stackit https://www.stackit.ai/api/mcp

Full install instructions and the complete tool reference live at /mcp.

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

Documented

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>

Walkthrough and machine-readable prices: /docs/x402 and /x402/prices.json.

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
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.

Do not charge yourself for safety

Protection actions carry no Stackit.ai fee. Network gas is paid from the user balance within published caps, which agents can read from get_policy_state.

Ready to build an agent?

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

Open the App