> For the complete documentation index, see [llms.txt](https://gotts.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gotts.gitbook.io/docs/gotts-safe-mcp-server/mcp-server/07-tools-advanced.md).

# CCA, Intelligence, External Data

> **Package**: `packages/safe/` | **Prerequisites**: [02-architecture.md](/docs/gotts-safe-mcp-server/mcp-server/02-architecture.md)
>
> CCA/token launch tools, intelligence tools, and external data tools via x402 (Phase 5-6). For other tool categories, see the [README](/docs/gotts-safe-mcp-server/mcp-server.md).

***

## CCA and Token Launch Tools

Tools for participating in Continuous Clearing Auctions (CCA), launching tokens via the Liquidity Launcher, and managing am-AMM pool auctions. CCA is live on mainnet across Ethereum, Unichain, Arbitrum, and Base (Feb 2, 2026). Contracts v1.1.0 audited by Spearbit and OpenZeppelin (Jan 2026).

#### `get_cca_state`

Get the current state of a Continuous Clearing Auction including clearing price, total bids, supply schedule, and time remaining.

**Parameters**:

| Name      | Type     | Required | Description            |
| --------- | -------- | -------- | ---------------------- |
| `auction` | `string` | Yes      | CCA contract address   |
| `chain`   | `string` | Yes      | Chain name or chain ID |

**Returns**:

```json
{
  "auctionAddress": "0xCCA...",
  "chain": "base",
  "status": "active",
  "token": { "symbol": "NEWTOKEN", "address": "0x1234..." },
  "clearingPrice": 0.0025,
  "totalBudgetCommitted": 1500000,
  "bidCount": 342,
  "supplySchedule": { "total": "1000000000", "released": "250000000" },
  "timeRemaining": "4h 23m",
  "endsAt": "2026-02-14T20:00:00Z"
}
```

***

#### `submit_cca_bid`

Submit a bid to a Continuous Clearing Auction with a budget and maximum price (FDV cap).

**Parameters**:

| Name       | Type     | Required | Description                                |
| ---------- | -------- | -------- | ------------------------------------------ |
| `auction`  | `string` | Yes      | CCA contract address                       |
| `budget`   | `string` | Yes      | Total budget in payment token (e.g., USDC) |
| `maxPrice` | `number` | Yes      | Maximum price (FDV) willing to pay         |
| `chain`    | `string` | Yes      | Chain name or chain ID                     |

**Returns**:

```json
{
  "status": "success",
  "txHash": "0xBID...",
  "bidId": "12345",
  "budget": "5000 USDC",
  "maxPrice": 0.005,
  "estimatedTokens": "1000000",
  "currentClearingPrice": 0.0025,
  "explorerUrl": "https://basescan.org/tx/0xBID..."
}
```

***

#### `exit_cca_bid`

Exit (withdraw) from an active CCA bid before the auction ends.

**Parameters**:

| Name      | Type     | Required | Description            |
| --------- | -------- | -------- | ---------------------- |
| `auction` | `string` | Yes      | CCA contract address   |
| `bidId`   | `string` | Yes      | Bid ID to exit         |
| `chain`   | `string` | Yes      | Chain name or chain ID |

***

#### `claim_cca_tokens`

Claim tokens after a CCA auction has ended. Tokens are distributed pro-rata based on clearing price.

**Parameters**:

| Name      | Type     | Required | Description            |
| --------- | -------- | -------- | ---------------------- |
| `auction` | `string` | Yes      | CCA contract address   |
| `chain`   | `string` | Yes      | Chain name or chain ID |

***

#### `launch_token`

Atomic token launch via the Liquidity Launcher: create UERC20 token, run CCA distribution, and seed V4 pool in a single multicall transaction.

**Parameters**:

| Name               | Type     | Required | Description                                                           |
| ------------------ | -------- | -------- | --------------------------------------------------------------------- |
| `name`             | `string` | Yes      | Token name                                                            |
| `symbol`           | `string` | Yes      | Token symbol                                                          |
| `totalSupply`      | `string` | Yes      | Total supply                                                          |
| `auctionPercent`   | `number` | No       | Percentage of supply for CCA. Default: 50.                            |
| `liquidityPercent` | `number` | No       | Percentage of supply for V4 pool. Default: 50.                        |
| `chain`            | `string` | Yes      | Chain name or chain ID                                                |
| `hookAddress`      | `string` | No       | V4 hook for the pool (e.g., anti-snipe, dynamic fees). Default: none. |

***

#### `get_amamm_state`

Get the current state of an am-AMM (Auction-Managed AMM) pool via Bunni v2, including the current manager, rent rate, deposit balance, and fee settings.

**Parameters**:

| Name    | Type     | Required | Description                     |
| ------- | -------- | -------- | ------------------------------- |
| `pool`  | `string` | Yes      | Bunni v2 pool or BidDog address |
| `chain` | `string` | Yes      | Chain name or chain ID          |

**Returns**:

```json
{
  "pool": "0xBUNNI...",
  "chain": "ethereum",
  "currentManager": "0xMGR...",
  "rent": "100 tokens/block",
  "depositRemaining": "72000 tokens",
  "blocksUntilExpiry": 720,
  "swapFee": "0.30%",
  "totalFeeRevenue24h": 15000,
  "auctionStatus": "active",
  "minimumBidIncrement": "1.1x"
}
```

***

#### `submit_amamm_bid`

Submit a bid for am-AMM pool management rights via BidDog contracts. Winning bidder becomes the pool manager: sets swap fees, receives all fee revenue, captures arbitrage.

**Parameters**:

| Name      | Type     | Required | Description                                        |
| --------- | -------- | -------- | -------------------------------------------------- |
| `pool`    | `string` | Yes      | BidDog contract address                            |
| `rent`    | `string` | Yes      | Rent per block in tokens                           |
| `deposit` | `string` | Yes      | Total deposit (must cover rent for initial period) |
| `chain`   | `string` | Yes      | Chain name or chain ID                             |

**Note**: Bids require a 1.1x minimum increment over the current rent. There is a default 7,200-block delay (\~24 hours) before a winning bid activates.

***

#### `get_amamm_bid_status`

Check the status of an am-AMM bid including activation countdown and competing bids.

**Parameters**:

| Name    | Type     | Required | Description             |
| ------- | -------- | -------- | ----------------------- |
| `pool`  | `string` | Yes      | BidDog contract address |
| `chain` | `string` | Yes      | Chain name or chain ID  |

***

**V4 Fee Collection Note**: Uniswap V4 has **no standalone `collect()` function**. Fees are auto-collected during any position modification. To collect fees without changing a position, use a **zero-delta modification** (increase liquidity by 0). This is a critical implementation detail for all V4 LP tools.

***

## Order Flow Intelligence Tools

Tools for measuring order flow toxicity and LP profitability. These metrics are the foundation of research-backed LP strategy: LVR (Loss-Versus-Rebalancing) quantifies the true cost of providing liquidity, VPIN measures informed trading flow, and the composite metrics tool combines them for actionable LP decisions.

***

#### `compute_vpin`

Compute Volume-Synchronized Probability of Informed Trading (VPIN) for a pool. VPIN measures order flow toxicity — high VPIN indicates the pool is dominated by informed/arbitrage traders, making LP less profitable. Uses Bulk Volume Classification (BVC) on trade-level data.

**Parameters**:

| Name       | Type     | Required | Description                                               |
| ---------- | -------- | -------- | --------------------------------------------------------- |
| `pool`     | `string` | Yes      | Pool address                                              |
| `chain`    | `string` | Yes      | Chain name or chain ID                                    |
| `buckets`  | `number` | No       | Number of volume buckets. Default: 50.                    |
| `lookback` | `string` | No       | Lookback period: "1h", "4h", "24h", "7d". Default: "24h". |

**Returns**:

```json
{
  "pool": "0x88e6...",
  "chain": "base",
  "vpin": 0.42,
  "interpretation": "MODERATE — 42% of volume is likely informed flow",
  "classification": {
    "safe": "VPIN < 0.3 — low toxicity, good for LPs",
    "moderate": "0.3-0.6 — mixed flow, proceed with caution",
    "toxic": "VPIN > 0.6 — dominated by arbitrage, LPs likely losing"
  },
  "timeSeries": [
    { "timestamp": "2026-02-19T00:00:00Z", "vpin": 0.38 },
    { "timestamp": "2026-02-19T06:00:00Z", "vpin": 0.45 },
    { "timestamp": "2026-02-19T12:00:00Z", "vpin": 0.42 }
  ],
  "methodology": "BVC (Bulk Volume Classification) with 50 equal-volume buckets over 24h trade data",
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Error Cases**:

* `INSUFFICIENT_TRADES`: Pool has fewer than 100 trades in lookback period
* `POOL_NOT_FOUND`: Pool not found

***

#### `compute_lvr`

Compute Loss-Versus-Rebalancing (LVR) for a pool. LVR = σ²/8 per unit time, representing the theoretical cost of providing liquidity vs. a rebalancing portfolio. The fee/LVR ratio determines if LP is profitable: ratio > 1.0 means fees exceed arbitrage losses.

**Parameters**:

| Name       | Type     | Required | Description                                                               |
| ---------- | -------- | -------- | ------------------------------------------------------------------------- |
| `pool`     | `string` | Yes      | Pool address                                                              |
| `chain`    | `string` | Yes      | Chain name or chain ID                                                    |
| `lookback` | `string` | No       | Lookback period: "1d", "7d", "30d". Default: "7d".                        |
| `method`   | `string` | No       | "realized" (historical) or "implied" (from options). Default: "realized". |

**Returns**:

```json
{
  "pool": "0x88e6...",
  "chain": "base",
  "fee": 500,
  "lvr": {
    "annualizedPct": 8.4,
    "periodPct": 1.6,
    "perBlockUsd": 0.012,
    "methodology": "σ²/8 with 7d realized volatility"
  },
  "feeRevenue": {
    "annualizedPct": 12.3,
    "periodPct": 2.35
  },
  "feeLvrRatio": {
    "ratio": 1.47,
    "interpretation": "PROFITABLE — fees exceed LVR by 47%",
    "threshold": "Ratio > 1.0 = LP profitable, < 1.0 = LP losing"
  },
  "l2Adjustment": {
    "applied": true,
    "note": "Base L2: LVR reduced ~40% vs Ethereum mainnet due to faster block times",
    "mainnetEquivalentLvr": 14.0
  },
  "volatility": {
    "realized7d": 0.62,
    "annualized": 0.62,
    "source": "realized"
  },
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Error Cases**:

* `INSUFFICIENT_DATA`: Less than 24 hours of price data
* `POOL_NOT_FOUND`: Pool not found

***

#### `get_order_flow_metrics`

Composite order flow intelligence combining VPIN, LVR, markout analysis, and JIT liquidity detection for a pool. This is the primary tool for LP profitability assessment.

**Parameters**:

| Name       | Type     | Required | Description                                        |
| ---------- | -------- | -------- | -------------------------------------------------- |
| `pool`     | `string` | Yes      | Pool address                                       |
| `chain`    | `string` | Yes      | Chain name or chain ID                             |
| `lookback` | `string` | No       | Lookback period: "1d", "7d", "30d". Default: "7d". |

**Returns**:

```json
{
  "pool": "0x88e6...",
  "chain": "base",
  "vpin": 0.42,
  "lvr": { "annualizedPct": 8.4, "feeLvrRatio": 1.47 },
  "markout": {
    "5block": -0.0012,
    "20block": -0.0028,
    "100block": -0.0041,
    "interpretation": "Negative markouts indicate LPs are losing to informed flow on average"
  },
  "jitLiquidity": {
    "jitPct": 3.2,
    "note": "3.2% of liquidity additions are JIT (same-block add+remove)"
  },
  "overallAssessment": {
    "lpProfitability": "PROFITABLE",
    "confidence": "HIGH",
    "recommendation": "Fee/LVR ratio of 1.47 suggests LP is profitable. VPIN is moderate — watch for spikes above 0.6.",
    "coveredCallCriterion": "PASS — expected fees exceed forgone option time premium (Hasbrouck et al.)"
  },
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Error Cases**:

* `INSUFFICIENT_DATA`: Less than 24 hours of trade data
* `POOL_NOT_FOUND`: Pool not found

***

## Intelligence Tools

These tools provide analytical capabilities for trading intelligence, risk assessment, LP strategy, and Agent Capital Markets metrics. They compose data from existing tools and external sources into actionable insights.

***

#### `discover_token`

Multi-source token discovery with comprehensive risk scoring. Extends `search_tokens` with risk analysis from 4 data sources: DexScreener, CoinGecko (x402), on-chain contract verification, and Uniswap subgraph.

**Parameters**:

| Name    | Type     | Required | Description                             |
| ------- | -------- | -------- | --------------------------------------- |
| `query` | `string` | Yes      | Token symbol, name, or contract address |
| `chain` | `string` | Yes      | Chain name or chain ID                  |

**Returns**:

```json
{
  "token": {
    "address": "0x...",
    "symbol": "TOKEN",
    "name": "Token Name",
    "decimals": 18,
    "chain": "ethereum",
    "chainId": 1
  },
  "discovery": {
    "sources": ["dexscreener", "coingecko", "onchain", "subgraph"],
    "poolCount": 5,
    "totalLiquidityUsd": 2450000,
    "volume24hUsd": 890000,
    "marketCapUsd": 15000000,
    "fdvUsd": 25000000,
    "circulatingSupply": "6000000"
  },
  "risk": {
    "rating": "CAUTION",
    "score": 62,
    "factors": {
      "contractAge": { "days": 45, "risk": "LOW" },
      "holderConcentration": { "top10Pct": 68.5, "risk": "HIGH" },
      "liquidityLockStatus": { "locked": false, "risk": "WARNING" },
      "honeypotDetection": {
        "buySucceeded": true,
        "sellSucceeded": true,
        "risk": "SAFE"
      },
      "taxDetection": { "buyTaxPct": 0, "sellTaxPct": 0, "risk": "SAFE" },
      "mempoolExposure": { "chain": "ethereum", "risk": "MEDIUM" }
    }
  },
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Risk Ratings**: `SAFE` (score >= 80), `CAUTION` (60-79), `WARNING` (40-59), `DANGER` (< 40).

**Error Cases**:

* `TOKEN_NOT_FOUND`: Token not found on any data source
* `CHAIN_NOT_SUPPORTED`: Chain not in supported list
* `DATA_SOURCE_ERROR`: One or more data sources failed (partial results returned with degraded flag)

***

#### `assess_mev_risk`

Assess MEV (Maximal Extractable Value) risk for a proposed swap. Analyzes sandwich attack probability, mempool exposure, and recommends mitigation strategies.

**Parameters**:

| Name       | Type     | Required | Description                                      |
| ---------- | -------- | -------- | ------------------------------------------------ |
| `tokenIn`  | `string` | Yes      | Input token symbol or address                    |
| `tokenOut` | `string` | Yes      | Output token symbol or address                   |
| `amount`   | `string` | Yes      | Trade size in tokenIn's smallest unit            |
| `chain`    | `string` | Yes      | Chain name or chain ID                           |
| `pool`     | `string` | No       | Specific pool address (auto-detected if omitted) |

**Returns**:

```json
{
  "riskLevel": "MEDIUM",
  "analysis": {
    "tradeSizeToLiquidity": 0.8,
    "tradeSizePct": "0.8% of pool liquidity",
    "priceImpactPct": 0.32,
    "sandwichFrequency": { "last24h": 12, "perTx": 0.03 },
    "mempoolExposure": "HIGH",
    "chainRisk": "Ethereum mainnet: PUBLIC mempool, high MEV activity"
  },
  "mitigations": [
    {
      "method": "UniswapX",
      "description": "Gasless, MEV-protected Dutch auction",
      "recommended": true
    },
    {
      "method": "Reduce size",
      "description": "Split into 3 trades of 33% each",
      "recommended": false
    }
  ],
  "estimatedMevCostUsd": 15.4,
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Risk Levels**: `LOW` (< 0.1% of pool liquidity), `MEDIUM` (0.1-1%), `HIGH` (1-5%), `CRITICAL` (> 5%).

**Error Cases**:

* `TOKEN_NOT_FOUND`: Token not found on specified chain
* `NO_POOL`: No pool found for the pair
* `INSUFFICIENT_DATA`: Not enough trade history to assess sandwich frequency

***

#### `compare_venues`

Compare execution quality across Uniswap and external DEX aggregators. Returns net output after gas for each venue to identify optimal execution.

**Parameters**:

| Name       | Type     | Required | Description                       |
| ---------- | -------- | -------- | --------------------------------- |
| `tokenIn`  | `string` | Yes      | Input token symbol or address     |
| `tokenOut` | `string` | Yes      | Output token symbol or address    |
| `amount`   | `string` | Yes      | Amount in tokenIn's smallest unit |
| `chain`    | `string` | Yes      | Chain name or chain ID            |

**Returns**:

```json
{
  "venues": [
    {
      "name": "Uniswap V3",
      "outputAmount": "1523400000",
      "outputAmountHuman": "1523.40",
      "priceImpactPct": 0.12,
      "gasEstimateUsd": 3.2,
      "netOutputUsd": 1520.2,
      "route": "USDC -> WETH (0.05% pool)"
    },
    {
      "name": "1inch",
      "outputAmount": "1525100000",
      "outputAmountHuman": "1525.10",
      "priceImpactPct": 0.1,
      "gasEstimateUsd": 4.8,
      "netOutputUsd": 1520.3,
      "route": "USDC -> WETH (split: 60% Uniswap V3, 40% Curve)"
    },
    {
      "name": "CoW Protocol",
      "outputAmount": "1524800000",
      "outputAmountHuman": "1524.80",
      "priceImpactPct": 0.08,
      "gasEstimateUsd": 0,
      "netOutputUsd": 1524.8,
      "route": "Batch auction (MEV-protected)"
    }
  ],
  "recommendation": {
    "venue": "CoW Protocol",
    "reason": "Highest net output after gas ($1524.80 vs $1520.20 for Uniswap V3)",
    "deltaVsUniswap": "+$4.60 (+0.30%)"
  },
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `TOKEN_NOT_FOUND`: Token not found on specified chain
* `AGGREGATOR_UNAVAILABLE`: External aggregator API unreachable (partial results returned)
* `CHAIN_NOT_SUPPORTED`: Chain not supported by one or more venues

***

#### `calculate_il`

Calculate impermanent loss for a Uniswap V3 concentrated liquidity position. Uses the exact V3 IL formula (not the simplified V2 approximation). Supports backtest mode against historical price data.

**Parameters**:

| Name         | Type     | Required | Description                                                          |
| ------------ | -------- | -------- | -------------------------------------------------------------------- |
| `token0`     | `string` | Yes      | First token symbol or address                                        |
| `token1`     | `string` | Yes      | Second token symbol or address                                       |
| `chain`      | `string` | Yes      | Chain name or chain ID                                               |
| `fee`        | `number` | No       | Fee tier (100, 500, 3000, 10000). Uses highest-liquidity if omitted. |
| `priceLower` | `number` | Yes      | Lower bound of price range (token1/token0)                           |
| `priceUpper` | `number` | Yes      | Upper bound of price range (token1/token0)                           |
| `entryPrice` | `number` | No       | Price at position entry. Default: current price.                     |
| `amount0`    | `string` | No       | Amount of token0 deposited (human-readable)                          |
| `backtest`   | `string` | No       | ISO 8601 start date for backtest mode (e.g., "2026-01-01")           |

**Returns**:

```json
{
  "position": {
    "token0": "WETH",
    "token1": "USDC",
    "fee": 3000,
    "priceLower": 2800,
    "priceUpper": 3600,
    "entryPrice": 3200,
    "currentPrice": 3050
  },
  "impermanentLoss": {
    "absoluteUsd": -42.3,
    "percentOfPosition": -0.84,
    "vsHold": "Position is worth $42.30 less than holding"
  },
  "feesEarned": {
    "totalUsd": 125.6,
    "token0Fees": "0.012 WETH",
    "token1Fees": "38.40 USDC",
    "dailyAvgUsd": 4.19
  },
  "netPnl": {
    "totalUsd": 83.3,
    "feesMinusIL": "+$83.30",
    "gasCosts": { "entryUsd": 8.5, "exitEstimateUsd": 8.5 },
    "netAfterGas": 66.3
  },
  "analysis": {
    "breakEvenDailyVolume": 450000,
    "optimalRangeWidth": "+/- 12% for this pair's historical volatility",
    "daysToBreakEven": 10.1
  },
  "backtest": null,
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `INVALID_RANGE`: priceLower >= priceUpper
* `NO_POOL`: No pool found for pair and fee tier
* `INSUFFICIENT_HISTORY`: Not enough historical data for backtest period

***

#### `get_agent_revenue`

Track all revenue streams for a self-funding agent's wallet. Aggregates income from x402 micropayments, LP fees, token creator fees, vault returns, protocol fee claims, and trading P\&L.

**Parameters**:

| Name      | Type     | Required | Description                                          |
| --------- | -------- | -------- | ---------------------------------------------------- |
| `address` | `string` | No       | Wallet address (defaults to configured agent wallet) |
| `chain`   | `string` | Yes      | Chain name or chain ID                               |
| `period`  | `string` | No       | Time period: "24h", "7d", "30d". Default: "7d".      |

**Returns**:

```json
{
  "address": "0x...",
  "chain": "base",
  "period": "7d",
  "streams": {
    "x402Income": { "totalUsd": 12.5, "txCount": 1250, "trend": "growing" },
    "lpFees": { "totalUsd": 245.8, "positionCount": 3, "trend": "stable" },
    "tokenCreatorFees": { "totalUsd": 0, "trend": "none" },
    "vaultReturns": { "totalUsd": 18.9, "trend": "growing" },
    "protocolFeeClaims": { "totalUsd": 0, "trend": "none" },
    "tradingPnl": { "totalUsd": -15.2, "tradeCount": 42, "trend": "declining" }
  },
  "summary": {
    "totalRevenueUsd": 262.0,
    "totalExpensesUsd": { "gasCosts": 8.4, "x402Outbound": 0.5 },
    "netPnlUsd": 253.1,
    "dailyAvgRevenueUsd": 36.14,
    "runwayDays": 182,
    "topStream": "lpFees (93.8%)"
  },
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `NO_WALLET`: No wallet address configured or provided
* `CHAIN_NOT_SUPPORTED`: Chain not in supported list

***

#### `simulate_price_impact`

Simulate the price impact of a trade at multiple sizes simultaneously against a specific pool. Returns exact output amounts, price impact percentages, and effective prices at each size. Useful for sizing trades optimally and detecting thin liquidity.

**Parameters**:

| Name       | Type       | Required | Description                                                                  |
| ---------- | ---------- | -------- | ---------------------------------------------------------------------------- |
| `tokenIn`  | `string`   | Yes      | Input token symbol or address                                                |
| `tokenOut` | `string`   | Yes      | Output token symbol or address                                               |
| `chain`    | `string`   | Yes      | Chain name or chain ID                                                       |
| `pool`     | `string`   | No       | Specific pool address. Auto-detects highest-liquidity if omitted.            |
| `sizes`    | `number[]` | No       | Array of trade sizes in USD. Default: `[100, 1000, 10000, 100000, 1000000]`. |

**Returns**:

```json
{
  "pair": "WETH/USDC",
  "pool": "0x88e6...",
  "chain": "base",
  "fee": 500,
  "currentPrice": 3245.67,
  "impacts": [
    {
      "sizeUsd": 100,
      "outputAmount": "0.03081 WETH",
      "effectivePrice": 3245.7,
      "priceImpactPct": 0.001,
      "slippageBps": 0.1
    },
    {
      "sizeUsd": 10000,
      "outputAmount": "3.079 WETH",
      "effectivePrice": 3247.8,
      "priceImpactPct": 0.07,
      "slippageBps": 6.6
    },
    {
      "sizeUsd": 100000,
      "outputAmount": "30.72 WETH",
      "effectivePrice": 3255.2,
      "priceImpactPct": 0.29,
      "slippageBps": 29.4
    },
    {
      "sizeUsd": 1000000,
      "outputAmount": "305.8 WETH",
      "effectivePrice": 3270.1,
      "priceImpactPct": 0.75,
      "slippageBps": 75.3
    }
  ],
  "liquidityDepth": {
    "depth1PctUsd": 15000000,
    "depth5PctUsd": 45000000,
    "note": "Pool can absorb ~$15M before 1% price impact"
  },
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Implementation**: For each size, calls `eth_call` against the pool's `swap` function with the exact amount to compute the real output using on-chain tick traversal. More accurate than off-chain estimation for pools with irregular tick distributions.

**Error Cases**:

* `NO_POOL`: No pool found for this pair
* `TOKEN_NOT_FOUND`: Token not recognized
* `SIMULATION_ERROR`: eth\_call simulation failed

***

#### `calculate_fee_switch_impact`

Model the impact of Uniswap's protocol fee activation on LP returns for a specific pool. The UNIfication governance proposal (Dec 2025, 125.3M UNI in favor) activated protocol fees: V2 LP fees dropped from 0.3% to 0.25% with a 0.05% protocol fee; V3 fees vary by pool tier. This tool quantifies the impact on any pool's LP economics.

**Parameters**:

| Name             | Type     | Required | Description                                                     |
| ---------------- | -------- | -------- | --------------------------------------------------------------- |
| `pool`           | `string` | Yes      | Pool address                                                    |
| `chain`          | `string` | Yes      | Chain name or chain ID                                          |
| `protocolFeeBps` | `number` | No       | Protocol fee in basis points. Default: auto-detected from pool. |

**Returns**:

```json
{
  "pool": "0x88e6...",
  "chain": "ethereum",
  "version": "v3",
  "feeTier": 500,
  "protocolFee": {
    "enabled": true,
    "feeBps": 50,
    "effectiveDate": "2026-01-15"
  },
  "impact": {
    "preFeeSwitch": {
      "lpFeeRate": "0.05%",
      "volume30dUsd": 2670000000,
      "lpFees30dUsd": 1335000,
      "lpFeeApy": 12.3
    },
    "postFeeSwitch": {
      "lpFeeRate": "0.04%",
      "volume30dUsd": 2670000000,
      "lpFees30dUsd": 1068000,
      "protocolFees30dUsd": 267000,
      "lpFeeApy": 9.84,
      "note": "Assuming volume stays constant"
    },
    "lpApyReduction": -2.46,
    "lpApyReductionPct": -20.0,
    "breakEvenVolumeIncrease": "25% more volume needed to restore pre-switch APY"
  },
  "recommendation": "Protocol fee reduces LP APY by ~20% on this pool. Consider tighter ranges to compensate with higher fee concentration, or evaluate if the reduced yield still exceeds alternatives.",
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Data Source**: On-chain pool state for fee configuration, subgraph for historical volume and fee data.

**Error Cases**:

* `POOL_NOT_FOUND`: Pool not found
* `FEE_NOT_ACTIVE`: Protocol fee has not been activated on this pool

***

#### `generate_cca_supply_schedule`

Generate a CCA (Continuous Clearing Auction) supply schedule with configurable curve types. TypeScript re-implementation of the official Python MCP tool with additional curve types and visualization.

**Parameters**:

| Name            | Type     | Required | Description                                                |
| --------------- | -------- | -------- | ---------------------------------------------------------- |
| `totalTokens`   | `string` | Yes      | Total tokens to distribute (e.g., "1000000")               |
| `numSteps`      | `number` | No       | Number of distribution steps. Default: 12.                 |
| `totalBlocks`   | `number` | Yes      | Total blocks for the auction duration                      |
| `curveType`     | `string` | No       | "convex" (default), "linear", "s-curve", "step"            |
| `alpha`         | `number` | No       | Curve steepness for convex type. Default: 1.2.             |
| `finalBlockPct` | `number` | No       | Percentage of tokens in final block (20-40%). Default: 30. |
| `tokenDecimals` | `number` | No       | Token decimals. Default: 18.                               |

**Returns**:

```json
{
  "schedule": {
    "steps": [
      { "step": 1, "blockDelta": 120, "mps": 583333, "tokensPct": 5.83 },
      { "step": 2, "blockDelta": 180, "mps": 583333, "tokensPct": 5.83 }
    ],
    "totalMps": 10000000,
    "encodedBytes": "0x...",
    "curveType": "convex",
    "alpha": 1.2
  },
  "visualization": "ASCII chart of token release rate over time",
  "validation": {
    "valid": true,
    "warnings": [],
    "totalMpsCheck": "10,000,000 MPS (exact)",
    "finalBlockPct": 30.0,
    "estimatedGasCost": "~180,000 gas"
  },
  "comparison": {
    "aztecCCA": "Aztec raised $60M from 17,000+ bidders with similar schedule parameters"
  }
}
```

**Error Cases**:

* `INVALID_CURVE`: Unsupported curve type
* `MPS_OVERFLOW`: Step mps exceeds 24-bit maximum (16,777,215)
* `BLOCK_OVERFLOW`: Step blockDelta exceeds 40-bit maximum
* `INVALID_FINAL_PCT`: Final block percentage outside 20-40% range

***

#### `generate_uniswap_link`

Generate deep links to the Uniswap web app with pre-filled parameters. Supports swap, LP, and pool creation URLs. Useful for user-in-the-loop workflows where the agent plans but the user confirms.

**Parameters**:

| Name       | Type     | Required | Description                                        |
| ---------- | -------- | -------- | -------------------------------------------------- |
| `type`     | `string` | Yes      | Link type: "swap", "add-liquidity", "create-pool"  |
| `chain`    | `string` | Yes      | Chain name or chain ID                             |
| `tokenIn`  | `string` | No       | Input token (required for swap)                    |
| `tokenOut` | `string` | No       | Output token (required for swap and add-liquidity) |
| `amount`   | `string` | No       | Pre-filled amount                                  |
| `fee`      | `number` | No       | Fee tier for add-liquidity (100, 500, 3000, 10000) |

**Returns**:

```json
{
  "url": "https://app.uniswap.org/swap?chain=base&inputCurrency=0x...&outputCurrency=0x...&value=500&field=INPUT",
  "type": "swap",
  "parameters": {
    "chain": "base",
    "tokenIn": "USDC",
    "tokenOut": "WETH",
    "amount": "500"
  },
  "note": "Only double-quote characters should be URL-encoded in query parameters. Braces and colons are sent as-is."
}
```

**Error Cases**:

* `INVALID_LINK_TYPE`: Unsupported link type
* `MISSING_PARAMS`: Required parameters for the link type not provided
* `TOKEN_NOT_FOUND`: Token not found on specified chain

***

#### `detect_account_type`

Detect whether an address is an EOA (Externally Owned Account) or a smart account (ERC-4337/Safe/etc.) by checking on-chain bytecode.

**Parameters**:

| Name      | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `address` | `string` | Yes      | Ethereum address to check |
| `chain`   | `string` | Yes      | Chain name or chain ID    |

**Returns**:

```json
{
  "address": "0x...",
  "type": "smart_account",
  "details": {
    "hasCode": true,
    "accountType": "safe",
    "supportsERC4337": true,
    "supportsERC7702": false
  },
  "recommendation": {
    "approvalFlow": "legacy (not Permit2)",
    "gasBuffer": "20-30% above estimate",
    "executionPath": "bundler submission via UserOperation"
  }
}
```

**Error Cases**:

* `INVALID_ADDRESS`: Not a valid Ethereum address
* `CHAIN_NOT_SUPPORTED`: Chain not in supported list

***

#### `submit_user_operation`

Submit a UserOperation to an ERC-4337 bundler for smart account execution. Handles gas estimation, bundler selection, and submission.

**Parameters**:

| Name      | Type     | Required | Description                                                        |
| --------- | -------- | -------- | ------------------------------------------------------------------ |
| `to`      | `string` | Yes      | Target contract address                                            |
| `data`    | `string` | Yes      | Encoded calldata (hex)                                             |
| `value`   | `string` | No       | ETH value in wei. Default: "0".                                    |
| `chain`   | `string` | Yes      | Chain name or chain ID                                             |
| `bundler` | `string` | No       | Preferred bundler: "pimlico", "alchemy", "stackup". Default: auto. |

**Returns**:

```json
{
  "userOpHash": "0x...",
  "bundler": "pimlico",
  "status": "submitted",
  "gasEstimate": {
    "callGasLimit": "200000",
    "verificationGasLimit": "100000",
    "preVerificationGas": "50000"
  }
}
```

**Error Cases**:

* `NOT_SMART_ACCOUNT`: Sender address is an EOA, not a smart account
* `BUNDLER_UNAVAILABLE`: Selected bundler is unreachable
* `USER_OP_REJECTED`: Bundler rejected the UserOperation (reverted in simulation)

***

#### `simulate_pool_scenario`

Simulate hypothetical LP position performance under configurable price trajectories and volume profiles. Supports multi-scenario comparison (bull/bear/sideways).

**Parameters**:

| Name         | Type     | Required | Description                                                                                              |
| ------------ | -------- | -------- | -------------------------------------------------------------------------------------------------------- |
| `token0`     | `string` | Yes      | First token symbol or address                                                                            |
| `token1`     | `string` | Yes      | Second token symbol or address                                                                           |
| `chain`      | `string` | Yes      | Chain name or chain ID                                                                                   |
| `fee`        | `number` | No       | Fee tier. Default: highest-liquidity pool.                                                               |
| `priceLower` | `number` | Yes      | Lower bound of LP range (token1/token0)                                                                  |
| `priceUpper` | `number` | Yes      | Upper bound of LP range (token1/token0)                                                                  |
| `amount0`    | `string` | Yes      | Amount of token0 to LP (human-readable)                                                                  |
| `scenarios`  | `string` | No       | JSON array of scenarios: `[{"name":"bull","priceChangePct":30,"volumeMultiplier":1.5,"daysHorizon":30}]` |

**Returns**:

```json
{
  "scenarios": [
    {
      "name": "bull",
      "priceChangePct": 30,
      "results": {
        "endPrice": 4160,
        "positionValueUsd": 5230,
        "feesEarnedUsd": 312,
        "ilUsd": -180,
        "netPnlUsd": 132,
        "vsHoldPnlUsd": -48,
        "inRangePct": 72
      }
    },
    {
      "name": "bear",
      "priceChangePct": -30,
      "results": { "...": "..." }
    }
  ],
  "recommendation": "The narrow range (+/- 15%) outperforms in sideways and mild bull scenarios but underperforms in high-volatility moves."
}
```

**Error Cases**:

* `INVALID_RANGE`: priceLower >= priceUpper
* `NO_POOL`: No pool found for pair and fee tier
* `INVALID_SCENARIO`: Malformed scenario JSON

***

#### `estimate_revert_risk`

Estimate the probability of a transaction reverting on-chain. Combines chain-specific revert rates, pool volatility, trade size, and stale state risk.

**Parameters**:

| Name    | Type     | Required | Description                     |
| ------- | -------- | -------- | ------------------------------- |
| `to`    | `string` | Yes      | Target contract address         |
| `data`  | `string` | Yes      | Encoded calldata (hex)          |
| `value` | `string` | No       | ETH value in wei. Default: "0". |
| `chain` | `string` | Yes      | Chain name or chain ID          |

**Returns**:

```json
{
  "revertProbability": 0.12,
  "riskLevel": "MEDIUM",
  "factors": {
    "chainRevertRate": {
      "rate": 0.08,
      "note": "L2 rollups: 80%+ of reverts are swap txs"
    },
    "poolVolatility": { "score": "HIGH", "priceChangeLast1h": 2.3 },
    "tradeSizeRisk": { "score": "LOW", "sizeVsLiquidity": 0.002 },
    "staleStateRisk": { "score": "LOW", "timeSinceLastBlock": "2s" }
  },
  "recommendations": {
    "gasPremium": "+15% priority fee to reduce inclusion delay",
    "deadline": "Set transaction deadline to 120 seconds",
    "slippage": "Increase slippage tolerance to 1% for this volatility level"
  }
}
```

**Error Cases**:

* `SIMULATION_FAILED`: Transaction reverts in eth\_call simulation
* `CHAIN_NOT_SUPPORTED`: Chain not in supported list

***

#### `advise_gas_optimization`

Recommend optimal timing, chain, and batching strategies to minimize gas costs for a given operation.

**Parameters**:

| Name      | Type     | Required | Description                                                     |
| --------- | -------- | -------- | --------------------------------------------------------------- |
| `type`    | `string` | Yes      | Operation type: "swap", "lp", "approval", "bridge"              |
| `urgency` | `string` | No       | "immediate", "within1h", "within24h". Default: "within1h".      |
| `chains`  | `string` | No       | Comma-separated chain names to compare. Default: all supported. |

**Returns**:

```json
{
  "currentCosts": {
    "ethereum": { "gasGwei": 25, "estimatedCostUsd": 8.5, "vs24hAvg": "+15%" },
    "base": { "gasGwei": 0.01, "estimatedCostUsd": 0.02, "vs24hAvg": "-5%" },
    "arbitrum": { "gasGwei": 0.1, "estimatedCostUsd": 0.15, "vs24hAvg": "+2%" }
  },
  "recommendation": {
    "chain": "base",
    "timing": "Execute now -- gas is below 24h average",
    "estimatedSavings": "$8.48 vs Ethereum mainnet",
    "batchingOpportunity": "Combine approval + swap via Permit2 to save ~21,000 gas"
  },
  "patterns": {
    "cheapestHour": "02:00-04:00 UTC (weekdays)",
    "cheapestDay": "Sunday"
  }
}
```

**Error Cases**:

* `INVALID_OPERATION`: Unsupported operation type
* `NO_POOL_ON_CHAIN`: Token pair has no pool on recommended chain

***

#### `discover_agents`

Query the ERC-8004 registry to discover agents by service type, chain, and minimum reputation tier. This is the primary high-level search entry point. For deeper inspection, use the `erc8004_*` prefix tools below.

**Parameters**:

| Name      | Type     | Required | Description                                                                             |
| --------- | -------- | -------- | --------------------------------------------------------------------------------------- |
| `service` | `string` | Yes      | Service type (e.g., "MEV protection", "LP management", "oracle")                        |
| `chain`   | `string` | No       | Filter by chain. Default: all chains.                                                   |
| `minTier` | `string` | No       | Minimum reputation tier: "basic", "verified", "trusted", "sovereign". Default: "basic". |
| `limit`   | `number` | No       | Max results. Default: 10.                                                               |

**Returns**:

```json
{
  "agents": [
    {
      "agentId": "42",
      "address": "0x...",
      "agentURI": "https://example.com/.well-known/agent-registration.json",
      "reputationScore": 87,
      "trustTier": "trusted",
      "capabilities": ["MEV protection", "swap execution"],
      "x402Enabled": true,
      "pricePerRequest": "$0.005"
    }
  ],
  "total": 1,
  "filters": { "service": "MEV protection", "chain": "all", "minTier": "basic" }
}
```

**A2A Agent Card Resolution (D-086)**: When `discover_agents` finds agents with A2A endpoints in their ERC-8004 registration file `services` array, it resolves the Agent Card and includes A2A skills in the response. This enables callers to discover both MCP tools and A2A skills from a single query. The resolution chain: on-chain agentURI -> registration file JSON -> services\[].name=="A2A" -> Agent Card JSON -> skills array.

**Agent0 SDK Integration (D-080)**: The tool uses the Agent0 SDK's `searchAgents()` and `searchAgentsByReputation()` functions for indexed, efficient search. Falls back to direct contract reads if the Agent0 subgraph is unavailable.

**Error Cases**:

* `REGISTRY_UNAVAILABLE`: ERC-8004 registry contract unreachable
* `NO_RESULTS`: No agents match the query criteria

***

## ERC-8004 Agent Registry Tools

Deep-dive companion tools for `discover_agents`. These tools query The Graph subgraphs indexing ERC-8004 smart contracts across multiple chains, covering all three registries: Identity, Reputation, and Validation. All tools are prefixed `erc8004_` to avoid collision when multiple MCP servers run simultaneously. All are read-only.

**Data sources**: The Graph ERC-8004 subgraphs (multi-chain), IPFS multi-gateway racing (agent metadata), ERC-8004 Reputation Registry subgraph, ERC-8004 Validation Registry subgraph.

***

#### `erc8004_search_agents`

Search for ERC-8004 registered AI agents by name. Supports optional protocol filtering (MCP or A2A) and chain filtering.

**Parameters**:

| Name       | Type     | Required | Default | Description                                                     |
| ---------- | -------- | -------- | ------- | --------------------------------------------------------------- |
| `query`    | `string` | Yes      | —       | Search query to match against agent names (case-insensitive)    |
| `protocol` | `string` | No       | —       | Filter by protocol: `"mcp"` or `"a2a"`                          |
| `chain`    | `string` | No       | —       | Filter by chain ID (e.g., `"1"` for mainnet, `"8453"` for Base) |
| `limit`    | `number` | No       | `20`    | Max results (1–100)                                             |

**Returns**: List of matching agents with name, ID, chain, owner, protocols, feedback count, active status, and description.

***

#### `erc8004_list_agents`

Browse ERC-8004 registered AI agents with pagination and sorting.

**Parameters**:

| Name            | Type     | Required | Default       | Description                                                           |
| --------------- | -------- | -------- | ------------- | --------------------------------------------------------------------- |
| `page`          | `number` | No       | `1`           | Page number (1-based)                                                 |
| `pageSize`      | `number` | No       | `20`          | Agents per page (1–100)                                               |
| `sortBy`        | `string` | No       | `"createdAt"` | Sort field: `createdAt`, `updatedAt`, `totalFeedback`, `lastActivity` |
| `sortDirection` | `string` | No       | `"desc"`      | `asc` or `desc`                                                       |
| `protocol`      | `string` | No       | —             | Filter by protocol: `"mcp"` or `"a2a"`                                |
| `chain`         | `string` | No       | —             | Filter by chain ID                                                    |

**Returns**: Paginated list with page info, sort metadata, and "next page" hint.

***

#### `erc8004_get_agent`

Get full details for a specific ERC-8004 agent by ID, including contract state, services, metadata, statistics, and recent feedback.

**Parameters**:

| Name      | Type     | Required | Description                                                                     |
| --------- | -------- | -------- | ------------------------------------------------------------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID (e.g., `"1:1213"` for mainnet, `"8453:42"` for Base) |

**Returns**: Full markdown document with Contract State, Description, Services (MCP/A2A endpoints), Identity (ENS, DID), Trust & Payments, Statistics, Timestamps, and Recent Feedback preview (last 3 entries).

***

#### `erc8004_get_agent_feedback`

Get all feedback and reviews for an ERC-8004 agent with scores, tags, review text, and MCP/A2A context.

**Parameters**:

| Name      | Type     | Required | Default | Description                  |
| --------- | -------- | -------- | ------- | ---------------------------- |
| `agentId` | `string` | Yes      | —       | Agent's subgraph entity ID   |
| `limit`   | `number` | No       | `50`    | Max feedback entries (1–100) |

**Returns**: Numbered feedback entries with score, client address, date, tags, and feedback file content (review text, MCP tool/prompt/resource context, A2A skills/contextId/taskId).

***

#### `erc8004_get_agent_stats`

Get engagement metrics, score breakdown, feedback tag analysis, and score distribution histogram for an agent.

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Engagement Metrics (total feedback, validations, last activity), Score Metrics (average feedback score as X.X/5.0), Feedback Tag Analysis (sorted by frequency), Score Distribution (visual histogram using `█` bars, 1–5 stars).

***

#### `erc8004_get_agent_metadata`

Get full on-chain and off-chain metadata for an agent. Fetches the IPFS registration file via multi-gateway racing.

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Two sections: On-Chain Metadata (all `AgentRegistrationFile` fields) and Off-Chain Metadata (IPFS JSON flattened into key-value pairs grouped by prefix: `[CERT]`, `[FITNESS]`, `[MODEL]`, `[SOCIAL]`, `[PRICING]`).

**IPFS multi-gateway racing**: Fetches from ipfs.io, cloudflare-ipfs.com, dweb.link, gateway.pinata.cloud simultaneously via `Promise.any()`. 15s timeout per gateway. CID validation before URL construction. 1MB response limit.

***

#### `erc8004_get_reputation_summary`

Get aggregated reputation from the Reputation Registry.

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Aggregated scores from `getSummary()`, tag breakdown, total feedback count, top feedback providers with average scores, and reputation trend (improving/declining/stable).

***

#### `erc8004_get_validation_status`

Check validation status from the Validation Registry (zkML, TEE attestation, or stake-secured re-execution).

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Current validation state, method, last validated timestamp, validation score, and validation history.

***

#### `erc8004_resolve_agent_services`

Parse the agent's registration file and return typed service endpoints (MCP, A2A, OASF, ENS, DID, email).

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Typed list of service endpoints with protocol, version, endpoint URL, capabilities (tools/skills/resources), and domain verification status via `/.well-known/agent-registration.json`.

***

#### `erc8004_evaluate_agent_trust`

Composite trust evaluation combining identity, reputation, and validation data from all three registries.

**Parameters**:

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `agentId` | `string` | Yes      | Agent's subgraph entity ID |

**Returns**: Identity verification status, reputation score and trend, validation status, and overall trust assessment with supporting evidence. Designed for pre-transaction counterparty evaluation.

***

### ERC-8004 MCP Resources

Resources expose read-only, subscribable data for LLM context. Registered via `registerResource`. Clients can subscribe for real-time updates when on-chain state changes.

#### Agent Profile Resources

* **`erc8004://agent/{agentId}/profile`** — Full agent profile data (identity, services, metadata)
* **`erc8004://agent/{agentId}/reputation`** — Agent reputation summary from the Reputation Registry
* **`erc8004://agent/{agentId}/validation`** — Agent validation status from the Validation Registry

#### Registry Statistics Resources

* **`erc8004://registry/stats`** — Global registry statistics (total agents, chains, protocols)
* **`erc8004://registry/stats/{chainId}`** — Per-chain registry statistics
* **`erc8004://registry/recent`** — Recently registered or updated agents

#### Reference Data Resources

* **`erc8004://config/chains`** — Supported chains with contract addresses, subgraph URLs, and status
* **`erc8004://config/contracts`** — Registry contract addresses per chain (Identity, Reputation, Validation)
* **`erc8004://config/tags`** — Known feedback tags and their descriptions

***

### ERC-8004 MCP Prompts

Pre-built prompt templates registered via `registerPrompt` that guide LLM interactions with registry data.

#### `erc8004_evaluate_trustworthiness`

Evaluate an agent's trustworthiness based on its on-chain identity, reputation history, and validation status. Accepts an `agentId` argument and assembles context from all three registries.

#### `erc8004_compare_agents`

Compare two or more agents by reputation score, validation status, service capabilities, and activity metrics. Accepts multiple `agentId` arguments.

#### `erc8004_find_agent_for_task`

Given a task description, find and recommend the best-suited registered agents based on their services, reputation, and domain tags.

#### `erc8004_audit_agent_feedback`

Analyze an agent's feedback history for patterns, anomalies, and overall sentiment trends.

***

### ERC-8004 Data Models

All types are defined in `src/types/agent.ts`. These interfaces define the canonical data structures for ERC-8004 agent registry data used across tools, resources, and prompts.

#### `AgentRegistrationFile`

On-chain registration metadata indexed by the subgraph from IPFS.

```typescript
interface AgentRegistrationFile {
  name: string | null;
  description: string | null;
  image: string | null;
  active: boolean | null;
  x402Support: boolean | null;
  supportedTrusts: string[]; // "reputation", "crypto-economic", "tee-attestation"
  mcpEndpoint: string | null;
  mcpVersion: string | null;
  mcpTools: string[];
  mcpPrompts: string[];
  mcpResources: string[];
  a2aEndpoint: string | null;
  a2aVersion: string | null;
  a2aSkills: string[];
  ens: string | null;
  did: string | null;
}
```

#### `Agent`

Core agent entity from the subgraph.

```typescript
interface Agent {
  id: string; // Subgraph entity ID (e.g., "1:1213" for mainnet)
  agentId: string; // On-chain agent ID
  chainId: string; // Network chain ID
  owner: string; // Ethereum address of the agent owner
  operators: string[]; // Authorized operator addresses
  agentURI: string | null; // IPFS URI to off-chain metadata
  createdAt: string; // Unix timestamp
  updatedAt: string; // Unix timestamp
  totalFeedback: string; // Total feedback count
  lastActivity: string; // Unix timestamp of last activity
  registrationFile: AgentRegistrationFile | null;
}
```

#### `Feedback` and `FeedbackFile`

```typescript
interface FeedbackFile {
  text: string | null; // Review text
  mcpTool: string | null; // MCP tool being reviewed
  mcpPrompt: string | null; // MCP prompt being reviewed
  mcpResource: string | null; // MCP resource being reviewed
  a2aSkills: string[]; // A2A skills being reviewed
  a2aContextId: string | null; // A2A conversation context
  a2aTaskId: string | null; // A2A task identifier
}

interface Feedback {
  id: string;
  value: string; // Raw score (0–500, maps to 0.0–5.0)
  tag1: string | null; // Primary tag
  tag2: string | null; // Secondary tag
  clientAddress: string; // Ethereum address of reviewer
  createdAt: string; // Unix timestamp
  revoked: boolean; // Whether this feedback has been revoked
  feedbackFile: FeedbackFile | null;
}
```

#### `AgentStats`

Aggregate statistics from the subgraph.

```typescript
interface AgentStats {
  totalFeedback: string;
  averageFeedbackValue: string;
  averageValidationScore: string;
  totalValidations: string;
  completedValidations: string;
  lastActivity: string;
}
```

#### `ReputationSummary`

Aggregated reputation data from the Reputation Registry.

```typescript
interface ReputationSummary {
  agentId: string;
  totalFeedback: string;
  averageScore: string;
  tagBreakdown: Record<string, number>;
  recentTrend: "improving" | "declining" | "stable";
  topProviders: Array<{
    address: string;
    feedbackCount: number;
    averageScore: string;
  }>;
}
```

#### `ValidationStatus`

Validation data from the Validation Registry.

```typescript
interface ValidationStatus {
  agentId: string;
  validated: boolean;
  method: "zkml" | "tee-attestation" | "stake-secured" | null;
  lastValidated: string | null; // Unix timestamp
  validationScore: string | null;
  history: Array<{
    timestamp: string;
    score: string;
    method: string;
  }>;
}
```

#### `AgentWithDetails`

Composite type used by detail views — extends `Agent` with feedback, stats, reputation, and validation.

```typescript
interface AgentWithDetails extends Agent {
  feedback: Feedback[];
  stats: AgentStats | null;
  reputation: ReputationSummary | null;
  validation: ValidationStatus | null;
}
```

#### `OffChainMetadata`

Raw IPFS JSON structure. Has known fields plus an open index signature for extended attributes.

```typescript
interface OffChainMetadata {
  name?: string;
  type?: string;
  image?: string;
  description?: string;
  active?: boolean;
  services?: Array<{
    name: string;
    version: string;
    endpoint: string;
    skills?: number;
    domains?: number;
  }>;
  registrations?: Array<{
    // Cross-registry registrations
    registry: string;
    chainId: string;
    agentId: string;
  }>;
  [key: string]: unknown; // CERT:*, FITNESS:*, MODEL:*, SOCIAL:*, PRICING:*, etc.
}
```

#### `ChainConfig`

Per-chain configuration for multi-chain ERC-8004 support.

```typescript
interface ChainConfig {
  chainId: string;
  name: string;
  enabled: boolean;
  subgraphUrl: string;
  contracts: {
    identity: string; // Identity Registry address
    reputation: string; // Reputation Registry address
    validation: string; // Validation Registry address
  };
}
```

***

## Hook Evaluation Tools

Tools for evaluating Uniswap V4 hooks before interacting with hooked pools. Critical safety layer — a BlockSec study found 36% of community hooks are potentially vulnerable. Reference exploits: Cork Protocol $11M (missing `onlyPoolManager`), Bunni v2 $8.4M (precision/rounding).

***

#### `hook_discover`

Query hook analytics platforms for V4 hooks by chain, category, TVL, and audit status.

**Parameters**:

| Name        | Type      | Required | Default | Description                                                                         |
| ----------- | --------- | -------- | ------- | ----------------------------------------------------------------------------------- |
| `chain`     | `string`  | No       | all     | Chain name or chain ID                                                              |
| `category`  | `string`  | No       | —       | Hook category: "mev-protection", "dynamic-fee", "twamm", "oracle", "access-control" |
| `minTvl`    | `number`  | No       | `0`     | Minimum TVL in USD                                                                  |
| `auditOnly` | `boolean` | No       | `false` | Only return hooks with verified audits                                              |
| `limit`     | `number`  | No       | `20`    | Max results                                                                         |

**Returns**:

```json
{
  "hooks": [
    {
      "address": "0x...",
      "name": "Bunni v2 am-AMM Hook",
      "chain": "ethereum",
      "category": "mev-protection",
      "tvl": 18290000,
      "volume24h": 4500000,
      "poolCount": 127,
      "auditStatus": "audited",
      "auditor": "OpenZeppelin",
      "permissionFlags": ["beforeSwap", "afterSwap", "beforeAddLiquidity"],
      "safetyScore": 92,
      "gasOverhead": "+45000 per swap"
    }
  ],
  "total": 413,
  "source": "hookrank.io"
}
```

**Data sources**: HookRank.io (primary), Dune V4 Hook Explorer (`dune.com/agaperste/v4-hook-explorer`).

**Error Cases**:

* `HOOKRANK_UNAVAILABLE`: HookRank.io API unreachable
* `NO_RESULTS`: No hooks match criteria

***

#### `hook_evaluate`

Evaluate a specific V4 hook's safety: decode permission flags, check audit status, analyze gas costs, and run vulnerability pattern matching.

**Parameters**:

| Name    | Type     | Required | Description            |
| ------- | -------- | -------- | ---------------------- |
| `hook`  | `string` | Yes      | Hook contract address  |
| `chain` | `string` | Yes      | Chain name or chain ID |

**Returns**:

```json
{
  "hook": "0x...",
  "chain": "ethereum",
  "permissionFlags": {
    "beforeInitialize": false,
    "afterInitialize": false,
    "beforeAddLiquidity": true,
    "afterAddLiquidity": false,
    "beforeRemoveLiquidity": false,
    "afterRemoveLiquidity": false,
    "beforeSwap": true,
    "afterSwap": true,
    "beforeDonate": false,
    "afterDonate": false,
    "beforeSwapReturnDelta": false,
    "afterSwapReturnDelta": true,
    "afterAddLiquidityReturnDelta": false,
    "afterRemoveLiquidityReturnDelta": false
  },
  "audit": {
    "status": "audited",
    "auditor": "OpenZeppelin",
    "reportUrl": "https://...",
    "inOpenZeppelinLibrary": true,
    "libraryVersion": "1.2.0"
  },
  "gasAnalysis": {
    "avgGasOverhead": 45000,
    "maxGasOverhead": 120000,
    "percentileP95": 68000
  },
  "vulnerabilityCheck": {
    "patterns": [
      {
        "pattern": "improper_access_control",
        "risk": "SAFE",
        "detail": "onlyPoolManager modifier present"
      },
      {
        "pattern": "delta_handling",
        "risk": "SAFE",
        "detail": "Proper BalanceDelta accounting"
      },
      {
        "pattern": "async_custody_theft",
        "risk": "SAFE",
        "detail": "No async unlock patterns"
      },
      {
        "pattern": "rounding_vulnerability",
        "risk": "LOW",
        "detail": "Uses SafeCast for all downcasts"
      },
      {
        "pattern": "reentrancy",
        "risk": "SAFE",
        "detail": "No external calls in callbacks"
      }
    ],
    "overallRisk": "LOW"
  },
  "recommendation": "SAFE — Audited by OpenZeppelin, in official library, low gas overhead, no vulnerability patterns detected."
}
```

**Error Cases**:

* `NOT_A_HOOK`: Address does not have hook permission bits encoded
* `HOOK_NOT_FOUND`: Hook not indexed by analytics platforms
* `CHAIN_NOT_SUPPORTED`: Chain not supported

***

#### `index_hook_registry`

Index and catalog V4 hooks from on-chain data, combining HookRank.io, Dune analytics, and direct contract reads. Returns a structured registry of hooks by category with deployment stats.

**Parameters**:

| Name       | Type     | Required | Description                                                                                       |
| ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------- |
| `chain`    | `string` | No       | Chain name or chain ID. Default: all chains.                                                      |
| `category` | `string` | No       | Filter: "dynamic-fee", "mev-protection", "twamm", "oracle", "access-control", "custom-accounting" |
| `minPools` | `number` | No       | Minimum number of pools using the hook. Default: 1.                                               |

**Returns**:

```json
{
  "totalHooks": 2547,
  "totalUniqueHooks": 1023,
  "chains": {
    "ethereum": { "hooks": 812, "pools": 1450 },
    "base": { "hooks": 623, "pools": 980 }
  },
  "categories": [
    {
      "name": "dynamic-fee",
      "count": 342,
      "topHook": "Aegis",
      "totalTvl": 245000000
    },
    {
      "name": "mev-protection",
      "count": 187,
      "topHook": "Bunni v2 am-AMM",
      "totalTvl": 189000000
    }
  ],
  "timestamp": "2026-02-19T12:00:00Z"
}
```

***

#### `get_hook_analytics`

Get detailed usage analytics for a specific V4 hook: pool count, TVL, volume, gas overhead, and user growth over time.

**Parameters**:

| Name    | Type     | Required | Description                   |
| ------- | -------- | -------- | ----------------------------- |
| `hook`  | `string` | Yes      | Hook contract address         |
| `chain` | `string` | Yes      | Chain name or chain ID        |
| `days`  | `number` | No       | Lookback period. Default: 30. |

**Returns**:

```json
{
  "hook": "0xHOOK...",
  "chain": "base",
  "name": "Dynamic Fee Hook",
  "poolCount": 127,
  "totalTvl": 45000000,
  "volume24h": 8500000,
  "volume7d": 52000000,
  "uniqueUsers7d": 3420,
  "avgGasOverhead": 45000,
  "growth": {
    "poolGrowth30d": "+23%",
    "tvlGrowth30d": "+45%",
    "volumeGrowth30d": "+12%"
  },
  "topPools": [
    {
      "pool": "0x...",
      "pair": "WETH/USDC",
      "tvl": 12000000,
      "volume24h": 3200000
    }
  ],
  "timestamp": "2026-02-19T12:00:00Z"
}
```

***

#### `get_dynamic_fee_template`

Get starter code template for a Uniswap V4 dynamic fee hook. Returns production-ready Solidity with configurable fee models (volatility-based, volume-based, time-based) and corresponding Foundry tests.

**Parameters**:

| Name       | Type     | Required | Description                                                                     |
| ---------- | -------- | -------- | ------------------------------------------------------------------------------- |
| `feeModel` | `string` | Yes      | Fee model: "volatility-oracle", "volume-weighted", "time-decay", "lvr-tracking" |
| `language` | `string` | No       | "solidity" (default)                                                            |

**Returns**:

```json
{
  "template": {
    "contract": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n...",
    "test": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n...",
    "feeModel": "volatility-oracle",
    "description": "Adjusts swap fee based on trailing volatility from a Chainlink oracle. Higher volatility → higher fee to compensate LPs for increased LVR."
  },
  "hookFlags": ["beforeSwap"],
  "estimatedGasOverhead": 35000,
  "references": [
    "Aegis dynamic fees: https://docs.aegis.finance",
    "LVR-tracking fees: arXiv:2602.09887"
  ]
}
```

***

#### `get_flash_accounting_template`

Get starter code template for a V4 hook using flash accounting (custom accounting pattern). Flash accounting enables hooks to custody tokens, implement custom swap curves, or batch operations using V4's singleton architecture.

**Parameters**:

| Name      | Type     | Required | Description                                                          |
| --------- | -------- | -------- | -------------------------------------------------------------------- |
| `pattern` | `string` | Yes      | Pattern: "custom-curve", "batch-swap", "token-custody", "yield-wrap" |

**Returns**:

```json
{
  "template": {
    "contract": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n...",
    "test": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n...",
    "pattern": "custom-curve",
    "description": "Hook implements a custom AMM curve using beforeSwapReturnDelta. Tokens are custodied by the hook, not the PoolManager."
  },
  "hookFlags": ["beforeSwap", "beforeSwapReturnDelta"],
  "securityNotes": [
    "CRITICAL: Must validate msg.sender == poolManager in all callbacks",
    "Must handle BalanceDelta correctly — return exact amounts claimed/owed",
    "Use SafeCast for all uint downcasts"
  ]
}
```

***

#### `v4_dynamic_fee_monitor`

Track dynamic fee changes over time on V4 pools with fee-setting hooks (e.g., Aegis per-block fees, Arrakis Pro volatility-based fees). Returns fee history, correlation with price volatility, and comparison against fixed-fee counterparts. Essential for evaluating whether dynamic-fee pools outperform static-fee pools.

**Parameters**:

| Name    | Type     | Required | Description                                   |
| ------- | -------- | -------- | --------------------------------------------- |
| `pool`  | `string` | Yes      | V4 pool address with a dynamic fee hook       |
| `chain` | `string` | Yes      | Chain name or chain ID                        |
| `days`  | `number` | No       | Lookback period in days. Default: 7. Max: 90. |

**Returns**:

```json
{
  "pool": "0xV4POOL...",
  "chain": "base",
  "hook": {
    "address": "0xHOOK...",
    "name": "Aegis Dynamic Fee",
    "feeModel": "per-block volatility-adjusted"
  },
  "feeHistory": {
    "current": 450,
    "min7d": 100,
    "max7d": 2500,
    "avg7d": 580,
    "median7d": 420,
    "stdDev7d": 340
  },
  "feeChanges": [
    {
      "blockNumber": 12345600,
      "timestamp": "2026-02-19T11:00:00Z",
      "oldFeeBps": 400,
      "newFeeBps": 600,
      "trigger": "price_movement",
      "priceChange1h": 1.8
    }
  ],
  "correlation": {
    "feeVsVolatility": 0.78,
    "feeVsVolume": 0.42,
    "note": "Fees are strongly correlated with price volatility (r=0.78)"
  },
  "vsFixedFee": {
    "fixedFeePool": "0x88e6...",
    "fixedFeeBps": 500,
    "dynamicAvgFeeBps": 580,
    "dynamicFeeRevenue7dUsd": 48200,
    "fixedFeeRevenue7dUsd": 44500,
    "dynamicPremiumPct": 8.3,
    "note": "Dynamic fee pool earned 8.3% more in fees over the past 7 days"
  },
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Data Source**: RPC event logs for `DynamicSwapFee` or hook-specific fee update events. Subgraph for volume and fee revenue comparison. Price volatility from `get_token_price_history`.

**Error Cases**:

* `NOT_DYNAMIC_FEE`: Pool does not have a dynamic fee hook
* `POOL_NOT_FOUND`: Pool not found
* `INSUFFICIENT_DATA`: Pool or hook is too new for meaningful analysis

***

## DeFi Context Tools

Free, keyless external data sources that provide cross-protocol context for Uniswap strategy decisions. These APIs require no authentication and have no per-request cost.

***

#### `get_protocol_tvl`

Query DefiLlama for total value locked (TVL) and volume data across DeFi protocols. Provides cross-protocol context: where capital is flowing, which protocols are growing or declining, and Uniswap's market share. DefiLlama's API is free, requires no API key, and covers 4,000+ protocols across all chains.

**Parameters**:

| Name       | Type     | Required | Description                                                                                       |
| ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------- |
| `protocol` | `string` | No       | Specific protocol slug (e.g., "uniswap", "aave-v3", "morpho"). If omitted, returns top protocols. |
| `chain`    | `string` | No       | Chain filter. Default: all chains.                                                                |
| `category` | `string` | No       | Protocol category: "dexes", "lending", "liquid-staking", "yield", "bridge". Default: all.         |
| `limit`    | `number` | No       | Max results (for top protocols). Default: 20.                                                     |

**Returns**:

```json
{
  "query": { "protocol": null, "chain": "base", "category": "dexes" },
  "protocols": [
    {
      "name": "Uniswap",
      "slug": "uniswap",
      "tvlUsd": 4200000000,
      "tvlChange24hPct": 2.1,
      "tvlChange7dPct": -1.5,
      "volume24hUsd": 1800000000,
      "fees24hUsd": 2700000,
      "chains": ["ethereum", "base", "arbitrum", "polygon"],
      "category": "dexes",
      "marketSharePct": 62.4
    }
  ],
  "totalTvlUsd": 6730000000,
  "source": "defillama",
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Data Source**: DefiLlama public API (`https://api.llama.fi/`). Free, no key, no rate limit for reasonable usage.

**Error Cases**:

* `PROTOCOL_NOT_FOUND`: Protocol slug not recognized by DefiLlama
* `DEFILLAMA_UNAVAILABLE`: DefiLlama API is unreachable (graceful degradation — returns cached data if available)

***

#### `get_funding_rates`

Query Hyperliquid for perpetual futures funding rates. Funding rates are a directional signal — positive rates mean longs pay shorts (bullish overcrowding), negative means shorts pay longs (bearish overcrowding). Critical context for LP range selection: high funding rates suggest directional moves that affect IL. Hyperliquid's API is free and requires no authentication.

**Parameters**:

| Name    | Type     | Required | Description                                                                     |
| ------- | -------- | -------- | ------------------------------------------------------------------------------- |
| `asset` | `string` | No       | Asset symbol (e.g., "ETH", "BTC"). If omitted, returns top 20 by open interest. |

**Returns**:

```json
{
  "assets": [
    {
      "symbol": "ETH",
      "fundingRate8h": 0.0042,
      "fundingRateAnnualized": 18.4,
      "openInterestUsd": 2800000000,
      "markPrice": 3245.67,
      "indexPrice": 3244.9,
      "nextFundingTime": "2026-02-19T16:00:00Z",
      "signal": {
        "direction": "LONG_CROWDED",
        "strength": "MODERATE",
        "note": "Positive funding (18.4% annualized) suggests longs are overcrowded. Potential for a correction. Consider wider LP ranges."
      }
    }
  ],
  "source": "hyperliquid",
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Signal Interpretation for LP Strategy**:

| Funding Rate    | Signal            | LP Implication                                         |
| --------------- | ----------------- | ------------------------------------------------------ |
| > 0.01% (8h)    | Strong long bias  | Widen range upward; higher IL risk from mean reversion |
| -0.01% to 0.01% | Neutral           | Standard range; low directional risk                   |
| < -0.01% (8h)   | Strong short bias | Widen range downward; higher IL risk from bounce       |

**Data Source**: Hyperliquid public REST API (`https://api.hyperliquid.xyz/info`). Free, no authentication, sub-second response.

**Error Cases**:

* `ASSET_NOT_FOUND`: Asset not listed on Hyperliquid
* `HYPERLIQUID_UNAVAILABLE`: API unreachable

***

## Yield Discovery Tools

Multi-source yield aggregation extending the existing `get_yield_opportunities` (Elsa x402) with deeper protocol-specific data and strategy composition.

***

#### `discover_yields`

Multi-source yield aggregation with risk-adjusted scoring. Queries DefiLlama, Morpho, Pendle, Aavescan, and Lido in parallel.

**Parameters**:

| Name            | Type     | Required | Default    | Description                                                           |
| --------------- | -------- | -------- | ---------- | --------------------------------------------------------------------- |
| `chain`         | `string` | No       | all        | Chain name or chain ID                                                |
| `asset`         | `string` | No       | —          | Filter by asset (e.g., "ETH", "USDC", "stETH")                        |
| `minTvl`        | `number` | No       | `100000`   | Minimum TVL in USD                                                    |
| `riskTolerance` | `string` | No       | `"medium"` | `"low"`, `"medium"`, `"high"`                                         |
| `category`      | `string` | No       | —          | `"lending"`, `"staking"`, `"lp"`, `"restaking"`, `"yield-derivative"` |
| `limit`         | `number` | No       | `20`       | Max results                                                           |

**Returns**:

```json
{
  "opportunities": [
    {
      "protocol": "Morpho",
      "type": "lending",
      "asset": "USDC",
      "chain": "base",
      "apy": { "base": 4.8, "reward": 1.2, "total": 6.0 },
      "tvl": 850000000,
      "riskScore": 85,
      "riskAdjustedYield": 5.1,
      "il7d": null,
      "source": "morpho-graphql"
    },
    {
      "protocol": "Pendle",
      "type": "yield-derivative",
      "asset": "stETH",
      "chain": "ethereum",
      "apy": { "implied": 5.2, "underlying": 4.1, "spread": 1.1 },
      "tvl": 320000000,
      "riskScore": 72,
      "riskAdjustedYield": 3.7,
      "signal": "Implied > underlying — consider buying PT for fixed rate lock-in",
      "source": "pendle-api"
    }
  ],
  "sources": ["defillama", "morpho-graphql", "pendle-api", "aavescan", "lido"],
  "timestamp": "2026-02-19T12:00:00Z"
}
```

**Data sources**: DefiLlama Pro API (13K+ pools), Morpho GraphQL (5K req/5min), Pendle API (implied vs underlying APY), Aavescan (`/v2/ecosystem/latest`), Lido (`eth-api.lido.fi/v1/protocol/steth/apr/last`).

**Error Cases**:

* `NO_OPPORTUNITIES`: No yields match criteria
* `DATA_SOURCE_PARTIAL`: One or more sources failed (partial results returned with degraded flag)

***

#### `compose_strategy`

Assemble multi-step yield strategies with entry/exit cost calculation.

**Parameters**:

| Name       | Type     | Required | Description                                                                             |
| ---------- | -------- | -------- | --------------------------------------------------------------------------------------- |
| `strategy` | `string` | Yes      | Strategy type: `"leveraged-staking"`, `"delta-neutral"`, `"yield-rotation"`, `"custom"` |
| `asset`    | `string` | Yes      | Base asset (e.g., "ETH", "USDC")                                                        |
| `amount`   | `string` | Yes      | Capital amount (human-readable)                                                         |
| `chain`    | `string` | Yes      | Chain name or chain ID                                                                  |

**Returns**:

```json
{
  "strategy": "leveraged-staking",
  "steps": [
    {
      "step": 1,
      "action": "Deposit 10 ETH into Lido for stETH",
      "protocol": "Lido",
      "estimatedGasUsd": 5.2
    },
    {
      "step": 2,
      "action": "Supply stETH to Morpho as collateral",
      "protocol": "Morpho",
      "estimatedGasUsd": 3.8
    },
    {
      "step": 3,
      "action": "Borrow 7.5 ETH at 75% LTV",
      "protocol": "Morpho",
      "estimatedGasUsd": 4.1
    },
    {
      "step": 4,
      "action": "Repeat steps 1-3 for 2 more loops",
      "protocol": "Morpho/Lido",
      "estimatedGasUsd": 24.0
    }
  ],
  "projectedYield": {
    "baseApy": 4.1,
    "leveragedApy": 16.4,
    "leverageMultiple": "4x",
    "netAfterBorrowCost": 12.8
  },
  "risks": {
    "liquidationPrice": "$2,100 ETH/USD",
    "healthFactor": 1.33,
    "borrowRateVolatility": "MEDIUM",
    "depeggingRisk": "LOW"
  },
  "entryCostUsd": 37.1,
  "exitCostUsd": 28.5,
  "breakEvenDays": 8
}
```

**Error Cases**:

* `INVALID_STRATEGY`: Unsupported strategy type
* `INSUFFICIENT_LIQUIDITY`: Not enough protocol liquidity for the requested amount
* `STRATEGY_RISK_TOO_HIGH`: Strategy risk exceeds configured tolerance

***

## Self-Improvement Loop Tools

Tools for recording execution data, comparing predictions against outcomes, detecting failure patterns, and tuning strategy parameters. Implements the CryptoTrade (EMNLP 2024) verbal reflection pattern (inner loop) and PRBO Bayesian optimization (outer loop).

***

#### `record_execution`

Log every agent action with the complete state vector for retrospective analysis.

**Parameters**:

| Name                | Type     | Required | Description                                                                                                                                                                                                    |
| ------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `executionId`       | `string` | Yes      | Unique execution identifier                                                                                                                                                                                    |
| `strategyName`      | `string` | Yes      | Strategy being executed                                                                                                                                                                                        |
| `actionType`        | `string` | Yes      | `"SWAP"`, `"ADD_LIQUIDITY"`, `"REMOVE_LIQUIDITY"`, `"REBALANCE"`, `"DEPOSIT"`, `"WITHDRAW"`                                                                                                                    |
| `portfolioSnapshot` | `string` | Yes      | JSON: current portfolio state (balances, positions, total value)                                                                                                                                               |
| `marketConditions`  | `string` | Yes      | JSON: prices, volatility, pool TVL, current tick, fee tier, gas price                                                                                                                                          |
| `decisionParams`    | `string` | Yes      | JSON: parameters used to make the decision                                                                                                                                                                     |
| `predictedOutcome`  | `string` | Yes      | JSON: expected return, fees, IL, confidence score                                                                                                                                                              |
| `reasoningChain`    | `string` | No       | Natural language reasoning that led to this decision                                                                                                                                                           |
| `txHash`            | `string` | No       | Transaction hash (if already broadcast)                                                                                                                                                                        |
| `reflection`        | `string` | No       | Reflexion pattern: natural-language self-reflection (what happened, why, what to do differently). When provided and `learning` profile is active, automatically stored as episodic memory via `store_episode`. |

**Returns**: Confirmation with `executionId` and timestamp. Stored in the execution log (TimescaleDB or local SQLite). When `reflection` is provided and `learning` profile active, also returns `episodeId`.

***

#### `record_outcome`

Capture actual results after settlement for comparison against predictions.

**Parameters**:

| Name              | Type     | Required | Description                                                                                                                                                                                            |
| ----------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `executionId`     | `string` | Yes      | Execution ID from `record_execution`                                                                                                                                                                   |
| `realizedPnl`     | `number` | Yes      | Realized profit/loss in USD                                                                                                                                                                            |
| `feesEarned`      | `number` | No       | Fees earned in USD (for LP actions)                                                                                                                                                                    |
| `impermanentLoss` | `number` | No       | IL in USD (for LP actions)                                                                                                                                                                             |
| `unrealizedPnl`   | `number` | No       | Unrealized P\&L in USD                                                                                                                                                                                 |
| `gasUsedUsd`      | `number` | Yes      | Gas cost in USD                                                                                                                                                                                        |
| `slippageActual`  | `number` | No       | Actual slippage in basis points                                                                                                                                                                        |
| `reflection`      | `string` | No       | Reflexion pattern: post-settlement self-reflection comparing predicted vs actual outcome. When provided and `learning` profile is active, updates the corresponding episodic memory with outcome data. |

**Returns**: Confirmation with computed reward signal components. When `reflection` is provided and `learning` profile active, also returns updated `episodeId`.

***

#### `compare_predicted_vs_actual`

Compute prediction error, drift score, and calibration metrics for an execution or a batch of executions.

**Parameters**:

| Name           | Type     | Required | Default | Description                                   |
| -------------- | -------- | -------- | ------- | --------------------------------------------- |
| `executionId`  | `string` | No       | —       | Single execution ID (omit for batch analysis) |
| `strategyName` | `string` | No       | —       | Filter by strategy                            |
| `period`       | `string` | No       | `"7d"`  | Lookback: `"24h"`, `"7d"`, `"30d"`            |

**Returns**:

```json
{
  "summary": {
    "totalExecutions": 42,
    "predictionErrorMean": -0.12,
    "predictionErrorStdDev": 0.45,
    "calibration": {
      "confidence80PctAccuracy": 0.76,
      "overconfident": true,
      "suggestion": "Reduce confidence scores by ~5% for better calibration"
    },
    "driftScore": 0.23,
    "driftTrend": "increasing"
  }
}
```

***

#### `get_failure_patterns`

Cluster failed or underperforming executions by common features and surface root cause hypotheses.

**Parameters**:

| Name           | Type     | Required | Default | Description                       |
| -------------- | -------- | -------- | ------- | --------------------------------- |
| `strategyName` | `string` | No       | —       | Filter by strategy                |
| `period`       | `string` | No       | `"30d"` | Lookback period                   |
| `minLoss`      | `number` | No       | `0`     | Minimum loss threshold to include |

**Returns**:

```json
{
  "patterns": [
    {
      "cluster": "high-volatility-rebalance",
      "count": 8,
      "avgLossUsd": -45.2,
      "commonFeatures": {
        "marketRegime": "strong_bear",
        "volatilityPercentile": ">90th",
        "gasGwei": ">50"
      },
      "hypothesis": "Rebalancing during high-volatility bear markets incurs excessive slippage and gas",
      "suggestedAdjustment": "Increase rebalance threshold by 2x during bear regimes"
    }
  ],
  "totalFailures": 12,
  "totalExecutions": 42
}
```

***

#### `generate_reinforcement_signal`

Compute composite reward signal from execution outcomes for parameter optimization.

**Parameters**:

| Name           | Type     | Required | Default | Description                       |
| -------------- | -------- | -------- | ------- | --------------------------------- |
| `executionId`  | `string` | No       | —       | Single execution (omit for batch) |
| `strategyName` | `string` | No       | —       | Filter by strategy                |
| `period`       | `string` | No       | `"7d"`  | Lookback period                   |

**Returns**:

```json
{
  "rewardSignal": {
    "R_total": 0.72,
    "components": {
      "R_pnl": { "value": 0.85, "weight": 0.3 },
      "R_fees": { "value": 0.9, "weight": 0.2 },
      "R_il": {
        "value": 0.45,
        "weight": 0.2,
        "note": "Uses LVR, not traditional IL"
      },
      "R_gas": { "value": 0.7, "weight": 0.15 },
      "R_risk": { "value": 0.6, "weight": 0.15 }
    },
    "formula": "R_total = w1·R_pnl + w2·R_fees + w3·R_il + w4·R_gas + w5·R_risk"
  }
}
```

***

#### `tune_parameters`

Apply Bayesian optimization or Thompson Sampling to adjust strategy parameters based on accumulated reward signals.

**Parameters**:

| Name            | Type     | Required | Default      | Description                                               |
| --------------- | -------- | -------- | ------------ | --------------------------------------------------------- |
| `strategyName`  | `string` | Yes      | —            | Strategy to tune                                          |
| `method`        | `string` | No       | `"bayesian"` | Optimization method: `"bayesian"`, `"thompson"`, `"grid"` |
| `maxIterations` | `number` | No       | `10`         | Max optimization iterations                               |

**Returns**:

```json
{
  "strategy": "eth-usdc-concentrated-lp",
  "currentParams": {
    "rangeWidth": 0.15,
    "rebalanceThreshold": 0.08,
    "feeSensitivity": 0.5,
    "positionSizePct": 0.25
  },
  "suggestedParams": {
    "rangeWidth": 0.18,
    "rebalanceThreshold": 0.1,
    "feeSensitivity": 0.55,
    "positionSizePct": 0.22
  },
  "expectedImprovement": "+8.2% risk-adjusted return",
  "safetyCheck": {
    "maxChangePerParam": "10%",
    "withinBounds": true,
    "riskConstraintsMet": true
  },
  "method": "bayesian",
  "iterations": 10
}
```

**Safety constraints**: Hard limits on max position sizes, min diversification, max parameter change per iteration (10% of current value). No unbounded parameter drift.

**Error Cases**:

* `INSUFFICIENT_DATA`: Not enough execution history for optimization (minimum 20 executions)
* `STRATEGY_NOT_FOUND`: No execution history for the specified strategy
* `SAFETY_CONSTRAINT_VIOLATION`: Suggested parameters violate safety bounds

***

## Memory and Knowledge Tools (DeFi Brain)

Persistent memory and self-improving knowledge tools. Implements the **Reflexion** pattern (per-operation self-reflection into episodic memory) and **ExpeL** pattern (cross-operation insight distillation into semantic memory) with Ebbinghaus-curve memory decay. Fully embedded in the MCP server process — zero external database dependencies.

> **Implementation guide**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §1–§10 contains complete code, schemas, and build patterns for the memory subsystem (`packages/safe/src/memory/`). This section specifies the tool API and architectural context; Part 1 shows how to build the internals.

Total tools in this section: **10** (4 original + 6 new). Active when `TOOL_PROFILE` includes `learning`.

### Memory Backend Architecture

The memory system uses a **dual-store architecture** embedded directly in the server process:

| Store                         | Technology                                                             | Schema                                                                                                                                                                                                                                                                                                                                                   | Purpose                                                                                                                                                                |
| ----------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Episodic Memory** (LanceDB) | `@lancedb/lancedb` ^0.26.2 (Lance columnar format)                     | `id: string`, `vector: float32[384]`, `text: string` (reflection), `tool: string`, `outcome: string` (JSON), `chain: string`, `tokenPair: string`, `timestamp: number`                                                                                                                                                                                   | Raw trade outcomes and per-operation self-reflections. Searched by hybrid BM25 full-text + vector similarity via Reciprocal Rank Fusion (RRF). Append-only, versioned. |
| **Semantic Memory** (SQLite)  | `better-sqlite3` ^11.0.0 + `sqlite-vec` ^0.1.7 + `drizzle-orm` ^0.45.1 | Drizzle schema for `insights` table: `id: integer PK (autoIncrement)`, `content: text`, `category: text` (enum), `confidence: real` (0–1), `stability: real` (seconds, default 604800 = 7 days), `accessCount: integer`, `createdAt: integer`, `lastAccessed: integer`, `chain: text`, `tokenPair: text`, `embedding: float32[384]` (vec0 virtual table) | Distilled cross-operation insights with confidence scores and decay metadata. Queried by structured SQL filters + optional KNN via `vec0` virtual tables.              |
| **Working Memory**            | In-process LRU cache (`lru-cache`)                                     | Key-value                                                                                                                                                                                                                                                                                                                                                | Regime state, session context, hot embeddings. Already shared with Gotts Safe's caching layer.                                                                         |

**Insight categories** (enum): `slippage`, `gas_timing`, `route_selection`, `pool_behavior`, `mev_pattern`, `liquidity_depth`, `volatility`, `fee_optimization`, `rebalance_timing`, `vault_strategy`, `emergency`, `general`.

**Why dual-store**: LanceDB excels at high-dimensional similarity search over 100K+ episodes but lacks relational query capabilities. SQLite provides fast structured queries (filter by confidence, category, chain) with `sqlite-vec` for lightweight KNN over the smaller insight pool (<10K entries). Episodes flow into LanceDB; consolidated insights flow into SQLite.

**Initialization sequence** (order matters — SQLite is synchronous, LanceDB is async, embedder is lazy):

```typescript
// packages/safe/src/memory/init.ts
const sqlite = initSqlite(path.join(dataDir, "defi-brain.db")); // 1. Instant (sync)
const lance = await initLance(path.join(dataDir, "defi-brain")); // 2. <100ms (async)
await Embedder.embed("warmup"); // 3. 2-3s cold start (lazy)
```

> Full setup: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §1 (init sequence), §2 (SQLite WAL + sqlite-vec + Drizzle migrations, LanceDB connection + FTS index).

#### Design Rationale

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §1–§10 — init sequence, storage setup, schemas, embedding pipeline, episode storage, insight management, decay, middleware, consolidation, production patterns. **Research**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 2 §1–§7 — CoALA, retrieval, self-improvement, DeFi ML, causal reasoning, reliability.

**Why these stores**: The dual-store design follows the CoALA cognitive architecture framework (Sumers et al., arXiv:2309.02427, TMLR 2024), which maps LLM agent memory to four types: working (LRU cache), episodic (LanceDB), semantic (SQLite), and procedural (skill library). Neither store alone provides both high-dimensional similarity search and structured relational queries — the two modes an autonomous DeFi agent needs most.

**Why local embeddings**: Local embedding generation via Transformers.js delivers 10-20ms per sentence versus 200-500ms for external API calls. This eliminates network latency, avoids API costs, enables air-gapped operation (critical for TEE deployments), and removes an external dependency from the critical path.

**Why Reflexion + ExpeL**: ReAct (Yao et al., ICLR 2023) provides reasoning+action but has no learning capability. Reflexion adds intra-task learning via verbal self-reflection (97% on decision-making benchmarks, 8% absolute boost from reflection). ExpeL adds inter-task transfer by distilling episodes into reusable insights. The combination gives both immediate per-trade learning and long-term knowledge accumulation — without model weight updates.

| Pattern   | Scope       | Learning             | Best For                            |
| --------- | ----------- | -------------------- | ----------------------------------- |
| ReAct     | Single pass | None                 | Baseline agent loops                |
| Reflexion | Intra-task  | Episodic reflections | Iterative per-operation improvement |
| ExpeL     | Inter-task  | Semantic insights    | Long-term cross-operation knowledge |

#### Reflexion Pattern

Per-operation self-reflection (Shinn et al., NeurIPS 2023). After every write operation, the agent generates a structured natural-language reflection:

```
What happened: Swapped 500 USDC → 0.1538 WETH. Slippage 0.02%.
Why: Low volatility period, V3 0.05% pool had deep liquidity.
What to do differently: None — execution was optimal. Store as positive example.
```

Reflections are embedded and stored in LanceDB as episodic memory. The `record_execution` and `record_outcome` tools in Self-Improvement accept an optional `reflection` field for this purpose.

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §5 — `storeEpisode()` function and hybrid BM25+vector search via `RRFReranker`.

```typescript
// Episode storage (from memory/episodic.ts — see Part 1 §5 for full code)
const vector = await Embedder.embed(episode.reflection);
await episodes.add([
  {
    id: crypto.randomUUID(),
    vector,
    text: episode.reflection,
    tool: episode.tool,
    outcome: JSON.stringify(episode.outcome),
    chain: episode.chain,
    tokenPair: episode.tokenPair,
    timestamp: Date.now(),
  },
]);
```

#### ExpeL Pattern

Cross-operation insight distillation (Zhao et al., ICLR 2024). The consolidation loop (default: every 4 hours) reviews recent episodes and applies operations to the insight pool:

| Operation    | Effect                                                        | Confidence Change             |
| ------------ | ------------------------------------------------------------- | ----------------------------- |
| **ADD**      | Create new insight from recurring episode pattern             | Starts at 0.6                 |
| **UPVOTE**   | Confirm existing insight (similar episode validates it)       | +0.1 (capped at 1.0)          |
| **DOWNVOTE** | Contradict existing insight (episode invalidates it)          | -0.15 (asymmetric for safety) |
| **EDIT**     | Refine insight content (re-embeds, resets confirmation count) | Unchanged                     |

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §6 — full `addInsight()`, `upvoteInsight()`, `downvoteInsight()`, `editInsight()` functions with Drizzle ORM + sqlite-vec dual-write.

#### Memory Decay (Ebbinghaus Curve)

Insights decay via: `R = e^(-t/S)` where `R` = retention (0–1), `t` = time since last access (seconds), `S` = stability (seconds). Stability values in the table below are shown in days for readability; the code stores and computes in seconds (e.g., 7 days = 604,800 seconds).

| Insight Type              | Base Stability   | Rationale                     |
| ------------------------- | ---------------- | ----------------------------- |
| MEV/exploit patterns      | 90 days          | Structural patterns persist   |
| Emergency exit conditions | 180+ days        | Critical safety knowledge     |
| Slippage/route patterns   | 14-30 days       | Market microstructure evolves |
| Gas price observations    | 7-14 days        | Highly volatile               |
| General observations      | 7 days (default) | Quick decay unless reinforced |

Each access increases stability by +50%. Insights below `GOTTS_MEMORY_DECAY_MIN_RETENTION` (default 0.1) are excluded from context injection but archived (not deleted).

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §7 — `retention()` and `reinforceStability()` functions.

```typescript
// Decay calculation (from memory/decay.ts — see Part 1 §7)
function retention(lastAccessedMs: number, stabilitySeconds: number): number {
  const elapsedSeconds = (Date.now() - lastAccessedMs) / 1000;
  return Math.exp(-elapsedSeconds / stabilitySeconds);
}

function reinforceStability(currentStability: number): number {
  return currentStability * 1.5; // +50% on each access
}
```

#### Context Injection Middleware

When the `learning` profile is active, a middleware layer runs before and after every tool execution:

1. **Pre-execution**: Embed tool parameters → query LanceDB for top-k similar episodes → query SQLite for relevant insights above confidence threshold → format as `memoryContext` object attached to tool handler
2. **Post-execution**: For write operations, generate reflection → store episode in LanceDB with outcome, reflection, chain, tokenPair metadata

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §8 — full `withMemory()` middleware wrapper.

The retrieve → augment → execute → reflect → store loop:

```typescript
// Middleware pattern (from memory/middleware.ts — see Part 1 §8)
async function withMemoryContext(args: unknown) {
  const queryVec = await Embedder.embed(JSON.stringify(args));
  // 1. RETRIEVE — query both stores in parallel
  const [episodes, insights] = await Promise.all([
    searchEpisodes(lanceTable, query, { limit: 3 }),
    getRelevantInsights(drizzleDb, queryVec, { minConfidence: 0.5, limit: 5 }),
  ]);
  // 2. AUGMENT — format as context
  const memoryContext = formatMemoryContext(insights, episodes);
  // 3. EXECUTE — run tool with memory
  const result = await handler(args, memoryContext);
  // 4. REFLECT — generate reflection (via MCP sampling)
  const reflection = await generateReflection(args, result);
  // 5. STORE — save episode
  await storeEpisode(lanceTable, {
    tool,
    context: args,
    outcome: result,
    reflection,
    chain,
    tokenPair,
  });
  return result;
}
```

Memory **only adjusts soft parameters** (slippage tolerance within bounds, timing recommendations, route preferences). Memory **cannot override** safety limits, token allowlist, spending caps, simulation requirements, or circuit breakers. See [09-safety.md § 6.15](/docs/gotts-safe-mcp-server/mcp-server/09-safety.md) for full safety constraints.

#### Chain Awareness

All memory operations include `chain` and `tokenPair` metadata. This enables:

* Chain-specific insights (e.g., "Base gas is 50-500x cheaper — rebalance more frequently")
* Pair-specific patterns (e.g., "WETH/USDC 0.05% consistently better than 0.30% for <$5K swaps")
* Cross-chain generalizations during consolidation (insights that hold across chains get higher confidence)

**Market regime detection**: The `classify_regime` tool runs a lightweight HMM (3–5 states: strong bull, weak bull, sideways, weak bear, strong bear) in-process using rolling log returns and volatility. Observable features include on-chain metrics sourced via existing MCP tools: TVL flows, DEX volume trends, stablecoin dominance, and funding rates. No external ML service required — the model state is persisted in SQLite between sessions.

#### Retrieval Strategy Enhancements

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §5 — hybrid search code with `RRFReranker`. **Research**: Part 2 §2 — MRL, HippoRAG, RAPTOR, Self-RAG, CRAG comparison.

**Hybrid search details**: LanceDB combines Tantivy-based BM25 full-text search with vector ANN via Reciprocal Rank Fusion (RRF). Keyword queries ("ETH/USDC 0.3% slippage") use BM25; semantic queries ("what happens during European hours") use vector similarity. RRF merges both ranked lists. At <100K vectors, flat brute-force is sufficient (1-3ms); create an IVF-PQ index only past 100K rows.

**Matryoshka MRL upgrade path** (Tier 1): Swap `Xenova/all-MiniLM-L6-v2` (384-dim) for `nomic-ai/nomic-embed-text-v1.5` (768-dim MRL). MRL embeddings are independently useful at any truncation — use 64-dim for fast candidate scan, then rerank with full 768-dim vectors. Delivers up to **14x speedup** at equivalent accuracy (Kusupati et al., NeurIPS 2022). Model ships with ONNX weights, confirmed working in Transformers.js. \~75MB q8, \~300-400MB RAM.

**Contextual retrieval** (Tier 2): Anthropic's technique (Sep 2024) prepends LLM-generated chunk context before embedding. For each memory episode, generate a 50-100 token contextual prefix using the LLM, then embed the concatenated text. Reduces top-20 retrieval failure rate by **49%** with hybrid BM25. Cost-effective at \~$1.02/M tokens with prompt caching.

**Self-RAG/CRAG correction** (Tier 2): Before using a cached insight, Self-RAG evaluates whether the retrieved content actually supports the current decision. CRAG triggers fallback to live on-chain data when retrieval quality is poor. For DeFi: if an insight says "0.05% pool has deeper liquidity" but current pool depth shows otherwise, flag for DOWNVOTE and use live data.

**ColBERT limitation**: No ONNX/WASM/Node.js path exists (Transformers.js Issue #851 open). For multi-vector benefits, store multiple aspect embeddings per episode as separate LanceDB rows and aggregate scores in application code.

#### DeFi-Specific Memory Applications

> For citations and extended analysis, see [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 2 §4.

Seven categories of DeFi operations directly improved by the memory system, each backed by empirical evidence:

1. **Gas timing optimization**: Weekend periods offer **25-40% savings** vs weekday peaks; 1-5am UTC sees lowest congestion. Blocknative's ML-based gas prediction achieves **>50% cost savings** vs standard estimation. On Base L2, sub-cent costs but learnable sequencer ordering patterns.
2. **Slippage prediction**: 0x Labs study (673K+ trades) — slippage varies meaningfully by AMM protocol, pair type, and time of day. Uniswap Labs study (534K trades) — memecoins have **\~80% higher probability of adverse slippage** vs stablecoins. Memory stores expected vs actual slippage per trade, building a model indexed by pair, size bucket, volatility regime, and pool depth.
3. **IL pattern recognition**: Concentrated V3/V4 positions experience **up to 10x the IL** of full-range positions. ML-based IL prediction achieves **1.2% MAE** vs 3.5% for traditional models. Memory tracks IL events indexed by pair, range width, holding period, and market conditions.
4. **Market regime detection**: HMM identifies distinct volatility states — Bitcoin exhibits **75% bear days vs 25% bull days**. Memory of regime-specific strategy performance enables adaptive selection: momentum during trends, protective during crises, range-bound during mean-reverting periods.
5. **MEV avoidance on Base**: January 2026 study — sandwich attacks on L2 rollups with private mempools are **rare and unprofitable** (>95% flagged patterns were false positives, median attacker PnL negative). Memory prevents overpaying for unnecessary MEV protection while tracking the rare genuine MEV events.
6. **Fee tier optimization**: V4 supports fully dynamic fees; **2,500+ hook-enabled pools** exist. Memory tracks fee revenue per unit of liquidity across configurations. Key insight: dynamic fee hooks should cap maximum fees at **2x the lowest competing pool's fee** to avoid driving volume to competitors.
7. **CCA auction bidding**: Memory of past CCA outcomes (clearing prices, demand curves, bid timing) enables predictive bidding. Validated by Aztec's $59M CCA from 17,000 bidders across 191 countries.

#### Production Reliability

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §10 — `opossum` setup code, ADWIN class sketch. **Research**: Part 2 §6 — conformal prediction, multi-agent debate, AgentSpec.

**Circuit breakers** (`opossum` ^8.0.0, 70K+ weekly downloads, Red Hat-supported): Wrap every external call (RPC nodes, price oracles, DEX routers, embedding model) in circuit breakers. Portfolio-level thresholds: warning at drawdown >3%, halt new positions at >7%, full stop at >13%.

```typescript
// Circuit breaker setup (from Part 1 §10)
import CircuitBreaker from "opossum";
const rpcBreaker = new CircuitBreaker(callRpc, {
  timeout: 5000,
  errorThresholdPercentage: 50,
  resetTimeout: 30000,
  volumeThreshold: 5,
});
rpcBreaker.fallback(() => ({ error: "RPC unavailable", fallback: true }));
```

**ADWIN drift detection** (Tier 1): Adaptive Windowing detects distributional changes with mathematical error guarantees. \~200 lines TypeScript — see Part 1 §10 for implementation sketch. One ADWIN instance per tracked metric (slippage, gas, pool depth, volatility). Triggers re-evaluation or DOWNVOTE of insights when market conditions shift.

**Conformal prediction** (Tier 3): Distribution-free coverage guarantees for position sizing. Fantazzini (2024) applied 4 Adaptive Conformal Inference algorithms to **4,000 crypto-assets** — FACI and SF-OGD provide precise VaR estimates where GARCH fails due to volatility clustering and structural breaks.

**Multi-agent debate** (Tier 2): For transactions above a configurable value threshold, deploy 3 specialized debating agents (risk analyst, opportunity seeker, market regime detector) over 2+ rounds. Significantly reduces hallucinations and reasoning errors (Du et al., ICML 2024). Implementable in TypeScript via prompt engineering.

#### Implementation Roadmap

> Full details in [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 2 §7.

| Tier       | Timeline | Key Enhancements                                                                                                            | Stack           |
| ---------- | -------- | --------------------------------------------------------------------------------------------------------------------------- | --------------- |
| **Tier 1** | Days     | MRL embeddings (nomic-embed-text-v1.5), LanceDB hybrid search activation, `opossum` circuit breakers, ADWIN drift detection | TypeScript only |
| **Tier 2** | Weeks    | Contextual retrieval, Self-RAG/CRAG correction, Voyager skill library, multi-agent debate                                   | TypeScript only |
| **Tier 3** | Months   | HippoRAG knowledge graph (`graphology` npm), temporal KG (MemoTime), conformal prediction, event-driven structured memory   | TypeScript only |

***

#### `store_strategy`

Persist strategy parameters, regime context, and performance expectations for retrieval in future sessions.

**Parameters**:

| Name                     | Type     | Required | Description                                     |
| ------------------------ | -------- | -------- | ----------------------------------------------- |
| `strategyName`           | `string` | Yes      | Unique strategy identifier                      |
| `parameters`             | `string` | Yes      | JSON: strategy parameters                       |
| `regimeContext`          | `string` | No       | JSON: market regime when strategy was developed |
| `performanceExpectation` | `string` | No       | JSON: expected returns, risk metrics            |
| `notes`                  | `string` | No       | Natural language notes about the strategy       |

**Returns**: Confirmation with strategy ID and timestamp.

***

#### `classify_regime`

Run market regime detection on current features. Returns regime label with probability distribution across all states.

**Parameters**:

| Name    | Type     | Required | Default  | Description                             |
| ------- | -------- | -------- | -------- | --------------------------------------- |
| `chain` | `string` | No       | `"base"` | Chain for market data                   |
| `asset` | `string` | No       | `"ETH"`  | Primary asset for regime classification |

**Returns**:

```json
{
  "currentRegime": "weak_bear",
  "probabilities": {
    "strong_bull": 0.05,
    "weak_bull": 0.15,
    "sideways": 0.2,
    "weak_bear": 0.45,
    "strong_bear": 0.15
  },
  "features": {
    "logReturn7d": -0.08,
    "rollingVolatility30d": 0.62,
    "tvlTrend": "declining",
    "stablecoinDominance": "rising",
    "fundingRate": -0.02
  },
  "confidence": 0.78,
  "lastTransition": "2026-02-15T08:00:00Z",
  "model": "hmm-5state"
}
```

***

#### `retrieve_strategies`

Retrieve strategies filtered by current market regime, protocol, and risk tolerance. Agents only see strategies that performed well in similar conditions.

**Parameters**:

| Name            | Type     | Required | Default    | Description                                       |
| --------------- | -------- | -------- | ---------- | ------------------------------------------------- |
| `regime`        | `string` | No       | current    | Market regime filter (auto-detected if omitted)   |
| `protocol`      | `string` | No       | —          | Filter by protocol (e.g., "uniswap-v4", "morpho") |
| `riskTolerance` | `string` | No       | `"medium"` | `"low"`, `"medium"`, `"high"`                     |
| `limit`         | `number` | No       | `10`       | Max results                                       |

**Returns**: Ranked list of strategies with parameters, historical performance in the queried regime, and confidence scores.

***

#### `assess_historical_exposure`

Query the risk knowledge graph for past exploit events, correlation breakdowns, and liquidation cascades affecting specific protocols or token pairs.

**Parameters**:

| Name       | Type     | Required | Description                                    |
| ---------- | -------- | -------- | ---------------------------------------------- |
| `protocol` | `string` | No       | Protocol name (e.g., "morpho", "aave", "lido") |
| `token`    | `string` | No       | Token symbol or address                        |
| `chain`    | `string` | No       | Chain name or chain ID                         |

**Returns**:

```json
{
  "exploitHistory": [
    {
      "date": "2025-05-15",
      "protocol": "Cork Protocol",
      "lossUsd": 11000000,
      "cause": "Missing onlyPoolManager access control on V4 hook",
      "relevance": "HIGH — same hook pattern as queried protocol"
    }
  ],
  "correlationBreakdowns": [
    {
      "event": "stETH depeg March 2025",
      "correlationShift": "ETH/stETH correlation dropped from 0.99 to 0.85",
      "impact": "Leveraged staking loops faced cascading liquidations"
    }
  ],
  "liquidationCascades": [],
  "riskAssessment": "MEDIUM — protocol has no exploit history but uses patterns similar to previously exploited contracts"
}
```

**Error Cases**:

* `NO_DATA`: No historical data available for the queried protocol/token
* `MEMORY_BACKEND_UNAVAILABLE`: Knowledge graph backend unreachable

***

### DeFi Brain Tools (6 new)

The following 6 tools implement the DeFi Brain memory system. They require the `learning` profile to be active (`TOOL_PROFILE=trader,learning` or `TOOL_PROFILE=vault,learning`).

***

#### `store_episode`

Record a trade outcome with self-reflection as episodic memory. Called after every write operation when the learning profile is active. Episodes are the raw material for the ExpeL consolidation loop.

**Annotations**: `readOnlyHint: false, destructiveHint: false, idempotentHint: true`

**Parameters**:

| Name         | Type     | Required | Description                                                                                                    |
| ------------ | -------- | -------- | -------------------------------------------------------------------------------------------------------------- |
| `tool`       | `string` | Yes      | Tool that was executed (e.g., `"execute_swap"`, `"vault_rebalance"`)                                           |
| `outcome`    | `string` | Yes      | JSON: execution outcome (amounts, prices, gas, slippage, success/failure)                                      |
| `reflection` | `string` | Yes      | Natural-language self-reflection: what happened, why, what to do differently                                   |
| `chain`      | `string` | Yes      | Chain name or chain ID                                                                                         |
| `tokenPair`  | `string` | No       | Token pair (e.g., `"WETH/USDC"`). Omit for non-pair operations.                                                |
| `importance` | `string` | No       | `"routine"` (7d stability), `"notable"` (30d), `"critical"` (90d), `"emergency"` (180d). Default: `"routine"`. |

**Returns**:

```json
{
  "episodeId": "ep_a1b2c3d4",
  "stored": true,
  "vectorDims": 384,
  "totalEpisodes": 1542,
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled (set `GOTTS_MEMORY_ENABLED=true`)
* `EMBEDDING_FAILED`: Failed to generate embedding vector
* `STORAGE_FULL`: Episode count exceeds `GOTTS_MEMORY_MAX_EPISODES`

***

#### `search_memory`

Semantic search across both episodic memories and semantic insights. Uses hybrid BM25 + vector similarity for episodes (LanceDB) and structured + KNN for insights (SQLite). Returns the most relevant memories for a given query.

**Annotations**: `readOnlyHint: true, destructiveHint: false, idempotentHint: true`

**Parameters**:

| Name            | Type     | Required | Default  | Description                                                          |
| --------------- | -------- | -------- | -------- | -------------------------------------------------------------------- |
| `query`         | `string` | Yes      | —        | Natural language search query (e.g., `"WETH/USDC slippage on Base"`) |
| `store`         | `string` | No       | `"both"` | Which store to search: `"episodes"`, `"insights"`, `"both"`          |
| `chain`         | `string` | No       | —        | Filter by chain                                                      |
| `tokenPair`     | `string` | No       | —        | Filter by token pair                                                 |
| `tool`          | `string` | No       | —        | Filter episodes by tool name                                         |
| `minConfidence` | `number` | No       | `0.0`    | Minimum confidence for insights (0–1)                                |
| `limit`         | `number` | No       | `10`     | Max results                                                          |

**Returns**:

```json
{
  "episodes": [
    {
      "episodeId": "ep_a1b2c3d4",
      "tool": "execute_swap",
      "reflection": "Swapped 500 USDC → WETH. Slippage was 0.02%, well below 0.05% prediction.",
      "outcome": {
        "amountIn": "500",
        "amountOut": "0.1538",
        "slippageBps": 2,
        "gasUsd": 0.38
      },
      "chain": "base",
      "tokenPair": "WETH/USDC",
      "timestamp": "2026-02-14T11:30:00Z",
      "relevanceScore": 0.92
    }
  ],
  "insights": [
    {
      "insightId": "ins_x9y8z7",
      "content": "USDC/WETH swaps on Base: V3 0.05% pool consistently outperforms 0.30% for amounts under $5K",
      "category": "route_selection",
      "confidence": 0.85,
      "stability": 21.0,
      "accessCount": 7,
      "chain": "base",
      "tokenPair": "WETH/USDC",
      "relevanceScore": 0.88
    }
  ],
  "totalResults": 2,
  "queryEmbeddingMs": 12
}
```

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled
* `EMBEDDING_FAILED`: Failed to embed query
* `NO_RESULTS`: No memories match the query and filters

***

#### `get_insights`

Retrieve semantic insights by category, confidence range, chain, or token pair. Unlike `search_memory`, this uses structured SQL queries without vector similarity — faster and deterministic.

**Annotations**: `readOnlyHint: true, destructiveHint: false, idempotentHint: true`

**Parameters**:

| Name            | Type     | Required | Default        | Description                                                             |
| --------------- | -------- | -------- | -------------- | ----------------------------------------------------------------------- |
| `category`      | `string` | No       | —              | Filter by insight category (see enum above)                             |
| `minConfidence` | `number` | No       | `0.5`          | Minimum confidence (0–1)                                                |
| `maxConfidence` | `number` | No       | `1.0`          | Maximum confidence (0–1)                                                |
| `chain`         | `string` | No       | —              | Filter by chain                                                         |
| `tokenPair`     | `string` | No       | —              | Filter by token pair                                                    |
| `sortBy`        | `string` | No       | `"confidence"` | Sort order: `"confidence"`, `"recency"`, `"stability"`, `"accessCount"` |
| `limit`         | `number` | No       | `20`           | Max results                                                             |

**Returns**:

```json
{
  "insights": [
    {
      "insightId": "ins_x9y8z7",
      "content": "USDC/WETH swaps on Base: V3 0.05% pool consistently outperforms 0.30% for amounts under $5K",
      "category": "route_selection",
      "confidence": 0.85,
      "stability": 21.0,
      "retention": 0.74,
      "accessCount": 7,
      "chain": "base",
      "tokenPair": "WETH/USDC",
      "createdAt": "2026-02-10T08:00:00Z",
      "lastAccessed": "2026-02-14T11:30:00Z"
    }
  ],
  "totalMatching": 1,
  "totalInsights": 342
}
```

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled
* `INVALID_CATEGORY`: Category not in the allowed enum

***

#### `manage_insight`

ExpeL operations on the semantic insight pool: ADD new insights, UPVOTE confirmed patterns, DOWNVOTE contradicted beliefs, or EDIT refined understanding. Used by the consolidation loop and directly by agents.

**Annotations**: `readOnlyHint: false, destructiveHint: false, idempotentHint: false`

**Parameters**:

| Name        | Type     | Required    | Description                                                 |
| ----------- | -------- | ----------- | ----------------------------------------------------------- |
| `operation` | `string` | Yes         | `"ADD"`, `"UPVOTE"`, `"DOWNVOTE"`, `"EDIT"`                 |
| `insightId` | `string` | Conditional | Required for UPVOTE, DOWNVOTE, EDIT. The insight to modify. |
| `content`   | `string` | Conditional | Required for ADD and EDIT. The insight text.                |
| `category`  | `string` | Conditional | Required for ADD. Insight category enum value.              |
| `chain`     | `string` | No          | Chain context for the insight                               |
| `tokenPair` | `string` | No          | Token pair context                                          |
| `reason`    | `string` | No          | Natural language reason for the operation (for audit trail) |

**Returns**:

```json
{
  "insightId": "ins_x9y8z7",
  "operation": "UPVOTE",
  "newConfidence": 0.85,
  "previousConfidence": 0.75,
  "stability": 21.0,
  "status": "active"
}
```

**Confidence change rules**:

* ADD: starts at 0.6
* UPVOTE: +0.1 (capped at 1.0)
* DOWNVOTE: -0.15 (asymmetric — easier to lose confidence than gain it, for safety)
* EDIT: re-embeds content and resets confirmation count; confidence unchanged
* When confidence reaches 0.0: insight is archived (not deleted) with `status: "archived"`

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled
* `INSIGHT_NOT_FOUND`: insightId does not exist
* `INSIGHT_ARCHIVED`: Cannot UPVOTE/EDIT an archived insight (confidence = 0.0)
* `INVALID_OPERATION`: Operation not one of ADD/UPVOTE/DOWNVOTE/EDIT
* `MISSING_CONTENT`: ADD or EDIT without content
* `INSIGHTS_FULL`: Insight count exceeds `GOTTS_MEMORY_MAX_INSIGHTS` (archive lowest-confidence first)

***

#### `consolidate_memories`

Trigger the ExpeL episodic-to-semantic distillation loop manually. Normally runs on a scheduled interval (`GOTTS_MEMORY_CONSOLIDATION_INTERVAL`), but can be invoked directly for immediate consolidation.

> **Implementation**: [memory-architecture.md](/docs/prd-shared/memory-architecture.md) Part 1 §9 — `startConsolidationLoop()` with episode clustering and ExpeL operation dispatch.

The consolidation loop:

1. Retrieves recent unconsolidated episodes from LanceDB
2. Clusters episodes by tool + chain + tokenPair
3. For each cluster, uses the LLM to identify patterns and generate insight operations (ADD/UPVOTE/DOWNVOTE/EDIT)
4. Applies operations to the SQLite insight pool
5. Marks episodes as consolidated
6. Runs decay pass: updates retention scores, archives insights below min retention

**Annotations**: `readOnlyHint: false, destructiveHint: false, idempotentHint: true`

**Parameters**:

| Name          | Type      | Required | Default | Description                                          |
| ------------- | --------- | -------- | ------- | ---------------------------------------------------- |
| `maxEpisodes` | `number`  | No       | `100`   | Max episodes to process in this consolidation run    |
| `dryRun`      | `boolean` | No       | `false` | If true, return proposed operations without applying |

**Returns**:

```json
{
  "episodesProcessed": 47,
  "operations": {
    "added": 3,
    "upvoted": 8,
    "downvoted": 1,
    "edited": 2
  },
  "insightsArchived": 0,
  "decayPassResults": {
    "insightsDecayed": 12,
    "belowThreshold": 2,
    "archived": 0
  },
  "durationMs": 2340,
  "nextScheduledAt": "2026-02-14T16:00:00Z"
}
```

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled
* `NO_UNCONSOLIDATED`: No new episodes to consolidate
* `CONSOLIDATION_IN_PROGRESS`: Another consolidation is already running

***

#### `get_memory_stats`

Memory health dashboard: episode and insight counts, storage sizes, decay status, embedding model info, and consolidation schedule.

**Annotations**: `readOnlyHint: true, destructiveHint: false, idempotentHint: true`

**Parameters**: None.

**Returns**:

```json
{
  "episodic": {
    "store": "lancedb",
    "totalEpisodes": 1542,
    "maxEpisodes": 100000,
    "oldestEpisode": "2026-01-15T08:00:00Z",
    "newestEpisode": "2026-02-14T11:30:00Z",
    "diskSizeMb": 4.2,
    "topTools": [
      { "tool": "execute_swap", "count": 842 },
      { "tool": "vault_rebalance", "count": 215 },
      { "tool": "add_liquidity", "count": 189 }
    ],
    "topChains": [
      { "chain": "base", "count": 1102 },
      { "chain": "ethereum", "count": 440 }
    ]
  },
  "semantic": {
    "store": "sqlite+sqlite-vec",
    "totalInsights": 342,
    "maxInsights": 10000,
    "activeInsights": 328,
    "archivedInsights": 14,
    "avgConfidence": 0.72,
    "avgRetention": 0.65,
    "diskSizeMb": 0.8,
    "byCategory": {
      "slippage": 45,
      "route_selection": 38,
      "gas_timing": 52,
      "rebalance_timing": 28,
      "vault_strategy": 19
    }
  },
  "embedding": {
    "model": "Xenova/all-MiniLM-L6-v2",
    "dims": 384,
    "dtype": "q8",
    "modelSizeMb": 23,
    "avgEmbedMs": 14,
    "loaded": true
  },
  "consolidation": {
    "lastRun": "2026-02-14T12:00:00Z",
    "nextScheduled": "2026-02-14T16:00:00Z",
    "intervalSeconds": 14400,
    "totalRuns": 42,
    "avgDurationMs": 1850
  },
  "config": {
    "decayBaseStabilityDays": 7,
    "minRetention": 0.1,
    "confidenceThreshold": 0.5,
    "retrieveLimit": 10
  }
}
```

**Error Cases**:

* `MEMORY_DISABLED`: Memory system not enabled

***

#### `get_market_intelligence`

Monitor market activity: large swaps, new LP positions, token launches, and volume spikes. Correlates with ERC-8004 agent identities when possible.

**Parameters**:

| Name            | Type     | Required | Description                                |
| --------------- | -------- | -------- | ------------------------------------------ |
| `chain`         | `string` | Yes      | Chain name or chain ID                     |
| `pool`          | `string` | No       | Filter to specific pool address            |
| `minAmountUsd`  | `number` | No       | Minimum event size in USD. Default: 10000. |
| `lookbackHours` | `number` | No       | Hours to look back. Default: 24. Max: 168. |

**Returns**:

```json
{
  "events": [
    {
      "type": "large_swap",
      "timestamp": "2026-02-14T11:30:00Z",
      "pool": "WETH/USDC 0.05%",
      "amountUsd": 250000,
      "direction": "buy WETH",
      "actor": { "address": "0x...", "agentId": "42", "trustTier": "trusted" }
    },
    {
      "type": "new_position",
      "timestamp": "2026-02-14T10:15:00Z",
      "pool": "WETH/USDC 0.30%",
      "liquidityUsd": 500000,
      "range": "2800-3600",
      "actor": { "address": "0x...", "agentId": null, "trustTier": null }
    }
  ],
  "summary": {
    "largeSwaps": 8,
    "newPositions": 3,
    "tokenLaunches": 1,
    "volumeSpikes": 0
  }
}
```

**Error Cases**:

* `CHAIN_NOT_SUPPORTED`: Chain not in supported list
* `NO_EVENTS`: No events matching criteria in the lookback window

***

## Dashboard & Observability Tools

Tools that power the Agent Management Dashboard in the Portal. These provide execution observability, interaction graphs, tool access introspection, and operator feedback mechanisms. See [prd/website/portal/02-agent-dashboard.md](/docs/website/website/portal/02-agent-dashboard.md) for the dashboard specification and [prd/website/portal/03-api-keys.md](/docs/website/website/portal/03-api-keys.md) for the three-tier API key model that governs access to these tools.

***

#### `get_agent_interactions`

Get the interaction graph for an agent — co-deposits, manager/depositor relationships, auction competition, peer feedback, and x402 payments between agents.

**Key Tier**: Read

**Parameters**:

| Name              | Type     | Required | Description                                                                                                        |
| ----------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------ |
| `agentId`         | `string` | Yes      | ERC-8004 agent ID                                                                                                  |
| `interactionType` | `string` | No       | Filter by type: `co_deposit`, `manager_depositor`, `auction_competitor`, `feedback`, `x402_payment`. Default: all. |
| `limit`           | `number` | No       | Max interactions to return. Default: 50.                                                                           |
| `chain`           | `string` | No       | Chain name or chain ID. Default: Base.                                                                             |

**Returns**:

```json
{
  "agentId": "42",
  "interactions": [
    {
      "type": "co_deposit",
      "otherAgentId": "87",
      "vault": "0xVAULT...",
      "weight": 3,
      "lastInteraction": "2026-02-20T15:00:00Z"
    },
    {
      "type": "manager_depositor",
      "otherAgentId": "15",
      "vault": "0xVAULT2...",
      "role": "manager",
      "weight": 1,
      "lastInteraction": "2026-02-18T10:00:00Z"
    }
  ],
  "totalInteractions": 12,
  "uniqueAgents": 8
}
```

**Error Cases**:

* `AGENT_NOT_FOUND`: Agent ID not registered in ERC-8004 registry
* `SUBGRAPH_UNAVAILABLE`: Interaction subgraph not deployed (Phase W5 dependency)

***

#### `get_tool_usage_stats`

Get per-tool usage statistics from the MCP server's internal execution log. Call counts, latency percentiles, error rates, and top error codes.

**Key Tier**: Read

**Parameters**:

| Name       | Type     | Required | Description                                                  |
| ---------- | -------- | -------- | ------------------------------------------------------------ |
| `agentId`  | `string` | No       | Filter by agent. Default: current agent.                     |
| `period`   | `string` | No       | Time period: `1h`, `24h`, `7d`, `30d`, `all`. Default: `7d`. |
| `category` | `string` | No       | Tool category filter. Default: all categories.               |

**Returns**:

```json
{
  "period": "7d",
  "tools": [
    {
      "name": "get_token_price",
      "category": "Data and Analytics",
      "callCount": 342,
      "lastCalled": "2026-02-21T14:30:00Z",
      "avgLatencyMs": 120,
      "p95LatencyMs": 280,
      "errorRate": 0.02,
      "topErrors": [
        { "code": "TOKEN_NOT_FOUND", "count": 5 },
        { "code": "RPC_TIMEOUT", "count": 2 }
      ]
    }
  ],
  "summary": {
    "totalCalls": 1847,
    "uniqueTools": 23,
    "overallErrorRate": 0.03
  }
}
```

**Error Cases**:

* `EXECUTION_LOG_UNAVAILABLE`: Server execution logging not enabled

***

#### `get_tool_access_matrix`

Get the tool access matrix for an agent — which tools are available, reputation-gated, profile-gated, or disabled at the agent's current reputation tier and tool profile.

**Key Tier**: Read

**Parameters**:

| Name      | Type     | Required | Description                            |
| --------- | -------- | -------- | -------------------------------------- |
| `agentId` | `string` | Yes      | ERC-8004 agent ID                      |
| `chain`   | `string` | No       | Chain name or chain ID. Default: Base. |

**Returns**:

```json
{
  "agentId": "42",
  "currentTier": "Basic",
  "currentProfile": "vault",
  "categories": [
    {
      "name": "Data and Analytics",
      "tools": 9,
      "available": 9,
      "reputationGated": 0,
      "profileGated": 0,
      "disabled": 0
    },
    {
      "name": "Trading",
      "tools": 5,
      "available": 3,
      "reputationGated": 2,
      "profileGated": 0,
      "disabled": 0,
      "gatedDetails": [
        { "tool": "submit_cross_chain_intent", "requiredTier": "Verified" },
        { "tool": "submit_uniswapx_order", "requiredTier": "Verified" }
      ]
    }
  ]
}
```

**Error Cases**:

* `AGENT_NOT_FOUND`: Agent ID not registered in ERC-8004 registry

***

#### `get_audit_log`

Get paginated execution history from the MCP server's internal audit log. Every tool invocation is recorded with parameters, result, timing, and transaction hash (if applicable).

**Key Tier**: Read

**Parameters**:

| Name         | Type      | Required | Description                                                        |
| ------------ | --------- | -------- | ------------------------------------------------------------------ |
| `agentId`    | `string`  | No       | Filter by agent. Default: current agent.                           |
| `actionType` | `string`  | No       | Filter: `read`, `write`, `vault`, `proxy`, `safety`. Default: all. |
| `tool`       | `string`  | No       | Filter by specific tool name.                                      |
| `startDate`  | `string`  | No       | ISO 8601 start date.                                               |
| `endDate`    | `string`  | No       | ISO 8601 end date.                                                 |
| `success`    | `boolean` | No       | Filter by success/failure.                                         |
| `limit`      | `number`  | No       | Results per page. Default: 50. Max: 200.                           |
| `offset`     | `number`  | No       | Pagination offset. Default: 0.                                     |

**Returns**:

```json
{
  "entries": [
    {
      "id": "audit_001",
      "timestamp": "2026-02-21T14:30:00Z",
      "tool": "vault_deposit",
      "actionType": "vault",
      "parameters": { "vault": "0xVAULT...", "amount": "100", "token": "USDC" },
      "result": "success",
      "resultSummary": "Deposited 100 USDC, received 99.85 shares",
      "txHash": "0xTX...",
      "delayTier": "Standard",
      "gasCostUsd": 0.02,
      "durationMs": 3200
    }
  ],
  "total": 1847,
  "offset": 0,
  "limit": 50
}
```

**Error Cases**:

* `AUDIT_LOG_UNAVAILABLE`: Server audit logging not enabled
* `INVALID_DATE_RANGE`: startDate is after endDate

***

#### `submit_operator_feedback`

Submit an operator directive to the agent's DeFi Brain. Stored as a semantic insight with `category=operator_directive` and `confidence=1.0` (never subject to time decay). The agent retrieves active directives during context injection.

**Key Tier**: Feedback

**Parameters**:

| Name           | Type     | Required | Description                                                                               |
| -------------- | -------- | -------- | ----------------------------------------------------------------------------------------- |
| `agentId`      | `string` | Yes      | ERC-8004 agent ID                                                                         |
| `feedbackType` | `string` | Yes      | One of: `strategy_preference`, `decision_correction`, `market_context`, `goal_adjustment` |
| `content`      | `string` | Yes      | The directive text                                                                        |
| `priority`     | `string` | No       | `low`, `medium`, `high`. Default: `medium`.                                               |
| `expiresAt`    | `string` | No       | ISO 8601 expiry date. Null = permanent.                                                   |

**Returns**:

```json
{
  "status": "stored",
  "insightId": "insight_042",
  "feedbackType": "strategy_preference",
  "content": "Prefer lower-risk vaults with < 5% drawdown",
  "priority": "high",
  "confidence": 1.0,
  "expiresAt": null,
  "storedAt": "2026-02-21T14:30:00Z"
}
```

**Error Cases**:

* `AGENT_NOT_FOUND`: Agent ID not registered
* `INVALID_FEEDBACK_TYPE`: feedbackType not in allowed list
* `CONTENT_TOO_LONG`: Content exceeds 2000 characters
* `INSUFFICIENT_KEY_TIER`: Requires Feedback key or higher

***

#### `get_operator_feedback`

List active operator directives from the DeFi Brain.

**Key Tier**: Read

**Parameters**:

| Name           | Type      | Required | Description                                           |
| -------------- | --------- | -------- | ----------------------------------------------------- |
| `agentId`      | `string`  | No       | Filter by agent. Default: current agent.              |
| `feedbackType` | `string`  | No       | Filter by type.                                       |
| `active`       | `boolean` | No       | Only active (non-archived) directives. Default: true. |
| `limit`        | `number`  | No       | Max results. Default: 50.                             |

**Returns**:

```json
{
  "directives": [
    {
      "insightId": "insight_042",
      "feedbackType": "strategy_preference",
      "content": "Prefer lower-risk vaults with < 5% drawdown",
      "priority": "high",
      "confidence": 1.0,
      "expiresAt": null,
      "submittedAt": "2026-02-21T14:30:00Z",
      "active": true
    }
  ],
  "total": 3
}
```

***

#### `get_agent_feedback_received`

Get peer feedback received by an agent from other agents via the ERC-8004 Reputation Registry.

**Key Tier**: Read

**Parameters**:

| Name          | Type     | Required | Description                      |
| ------------- | -------- | -------- | -------------------------------- |
| `agentId`     | `string` | Yes      | ERC-8004 agent ID                |
| `fromAgentId` | `string` | No       | Filter by feedback source agent. |
| `tag`         | `string` | No       | Filter by feedback tag.          |
| `limit`       | `number` | No       | Max results. Default: 50.        |

**Returns**:

```json
{
  "agentId": "42",
  "feedback": [
    {
      "fromAgentId": "87",
      "tag": "reliable_manager",
      "content": "Consistent yield delivery over 90 days",
      "attestationTx": "0xATTEST...",
      "timestamp": "2026-02-15T10:00:00Z"
    }
  ],
  "total": 5
}
```

**Error Cases**:

* `AGENT_NOT_FOUND`: Agent ID not registered in ERC-8004 registry

***

## External Data Tools (x402 Providers)

These tools acquire data from external x402-enabled APIs (pay-per-request, no API key required). Gotts Safe supports multiple x402 outbound providers through a generic client (`src/x402/client.ts`), each configured as a separate provider with independent base URLs but shared global spending limits. Requires x402 outbound client to be enabled (`X402_OUTBOUND_ENABLED=true`). Falls back to on-chain data if x402 is unavailable.

**Providers**:

| Provider  | Base URL                      | Endpoints | Cost Range       | Data Coverage                                              |
| --------- | ----------------------------- | --------- | ---------------- | ---------------------------------------------------------- |
| CoinGecko | `https://api.coingecko.com`   | 3         | $0.01/req        | Token data, trending pools, cross-DEX pool search          |
| Elsa      | `https://x402-api.heyelsa.ai` | 5         | $0.001-$0.02/req | Portfolio, wallet analytics, yield discovery, P\&L, quotes |

Both providers settle payments in USDC on Base (\~200ms). Elsa additionally supports payment in ELSA token via an alternate URL path (`/api/elsa/` instead of `/api/`). All tools include a `source` field in the response indicating which provider served the data.

### CoinGecko Tools

***

#### `get_onchain_token_data`

Get comprehensive token data from CoinGecko via x402 micropayment. Richer than `get_token_metadata`: includes price, supply, FDV, market cap, top pools, and liquidity across all DEXs.

**Parameters**:

| Name    | Type     | Required | Description                    |
| ------- | -------- | -------- | ------------------------------ |
| `token` | `string` | Yes      | Token contract address (0x...) |
| `chain` | `string` | Yes      | Chain name or chain ID         |

**Returns**:

```json
{
  "token": {
    "address": "0x...",
    "name": "Uniswap",
    "symbol": "UNI",
    "decimals": 18,
    "imageUrl": "https://..."
  },
  "market": {
    "priceUsd": 12.45,
    "priceChange24hPct": -1.8,
    "marketCapUsd": 7500000000,
    "fdvUsd": 12450000000,
    "totalSupply": "1000000000",
    "circulatingSupply": "602000000",
    "volume24hUsd": 180000000
  },
  "pools": {
    "topPools": [
      {
        "dex": "Uniswap V3",
        "pair": "UNI/WETH",
        "liquidityUsd": 45000000,
        "volume24hUsd": 12000000
      }
    ],
    "totalLiquidityUsd": 120000000,
    "poolCount": 42
  },
  "source": "coingecko-x402",
  "cost": "$0.01",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to CoinGecko failed
* `TOKEN_NOT_FOUND`: Token not found on CoinGecko for this network
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached

***

#### `get_trending_pools`

Get trending pools on a specific network sorted by trading activity, via CoinGecko x402. Complements `get_new_pools` (which finds recently created pools).

**Parameters**:

| Name    | Type     | Required | Description                        |
| ------- | -------- | -------- | ---------------------------------- |
| `chain` | `string` | Yes      | Chain name or chain ID             |
| `limit` | `number` | No       | Max results. Default: 20. Max: 50. |

**Returns**:

```json
{
  "pools": [
    {
      "address": "0x...",
      "dex": "Uniswap V3",
      "token0": { "symbol": "WETH", "address": "0x..." },
      "token1": { "symbol": "USDC", "address": "0x..." },
      "fee": "0.05%",
      "volume24hUsd": 85000000,
      "tvlUsd": 250000000,
      "priceChangeToken0_24h": -2.1,
      "txCount24h": 15420
    }
  ],
  "network": "eth",
  "source": "coingecko-x402",
  "cost": "$0.01",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: Payment failed
* `NETWORK_NOT_FOUND`: Chain not mapped to CoinGecko network slug
* `SPENDING_LIMIT_EXCEEDED`: Spending limit reached

***

#### `search_coingecko_pools`

Search pools across all DEXs and 250+ networks via CoinGecko x402. Broader than Uniswap-only `get_pools_by_token` -- includes Curve, Balancer, SushiSwap, and all other DEXs indexed by CoinGecko.

**Parameters**:

| Name    | Type     | Required | Description                                   |
| ------- | -------- | -------- | --------------------------------------------- |
| `query` | `string` | Yes      | Search query (token symbol, name, or address) |
| `chain` | `string` | No       | Filter by chain. Default: all networks.       |
| `limit` | `number` | No       | Max results. Default: 20. Max: 50.            |

**Returns**:

```json
{
  "pools": [
    {
      "address": "0x...",
      "network": "eth",
      "dex": "uniswap_v3",
      "token0": { "symbol": "WETH", "address": "0x..." },
      "token1": { "symbol": "USDC", "address": "0x..." },
      "volume24hUsd": 85000000,
      "tvlUsd": 250000000,
      "priceUsd": 3200.5
    }
  ],
  "total": 142,
  "source": "coingecko-x402",
  "cost": "$0.01",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: Payment failed
* `NO_RESULTS`: No pools match the query
* `SPENDING_LIMIT_EXCEEDED`: Spending limit reached

***

### Elsa Tools

Elsa (`https://x402-api.heyelsa.ai`) provides multi-chain portfolio analytics, wallet behavior analysis, yield discovery, P\&L reporting, and cross-DEX swap quotes via x402 micropayments. Costs range from $0.001 to $0.02 per request. Elsa supports payment in USDC (default) or ELSA token. See [Elsa x402 API docs](https://x402.heyelsa.ai/docs) for the full endpoint reference.

**Provider configuration**:

```json
{
  "x402": {
    "outbound": {
      "providers": {
        "elsa": {
          "baseUrl": "https://x402-api.heyelsa.ai",
          "enabled": true,
          "paymentToken": "usdc"
        }
      }
    }
  }
}
```

When `paymentToken` is `"elsa"`, requests route to `/api/elsa/` instead of `/api/`. Both paths return identical data.

***

#### `get_wallet_portfolio`

Get a comprehensive multi-chain portfolio for a wallet address via Elsa x402. Returns token balances, DeFi positions (lending, borrowing, LP), staking positions, and total portfolio value across all chains. Richer than `get_agent_balance` (which only returns token balances on a single chain).

**Parameters**:

| Name      | Type     | Required | Description                                           |
| --------- | -------- | -------- | ----------------------------------------------------- |
| `address` | `string` | No       | Wallet address. Default: the configured agent wallet. |

**Returns**:

```json
{
  "wallet_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
  "total_value_usd": 12345.67,
  "chains": ["ethereum", "base", "arbitrum"],
  "portfolio": {
    "balances": [
      {
        "asset": "USDC",
        "balance": "1250.50",
        "balance_usd": 1250.5,
        "chain": "base",
        "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
      },
      {
        "asset": "WETH",
        "balance": "3.25",
        "balance_usd": 10530.75,
        "chain": "ethereum",
        "address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
      }
    ],
    "defi_positions": [
      {
        "protocol": "Uniswap V3",
        "type": "liquidity",
        "pool": "WETH/USDC",
        "value_usd": 5200.0,
        "chain": "ethereum"
      }
    ],
    "staking_positions": [
      {
        "protocol": "Lido",
        "token": "stETH",
        "staked_amount": "2.0",
        "value_usd": 6480.0,
        "apy": 4.2,
        "chain": "ethereum"
      }
    ]
  },
  "source": "elsa-x402",
  "cost": "$0.01",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to Elsa failed
* `INVALID_ADDRESS`: Not a valid Ethereum address
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached
* `ELSA_SERVICE_UNAVAILABLE`: Elsa API is unreachable

***

#### `get_wallet_analysis`

Analyze wallet behavior and risk profile via Elsa x402. Returns trading patterns, risk indicators, activity frequency, and behavioral insights. Useful for evaluating counterparty wallets before OTC trades, or for agents assessing their own performance patterns.

**Parameters**:

| Name      | Type     | Required | Description                                           |
| --------- | -------- | -------- | ----------------------------------------------------- |
| `address` | `string` | No       | Wallet address. Default: the configured agent wallet. |

**Returns**:

```json
{
  "wallet_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
  "analysis": {
    "wallet_age_days": 842,
    "total_transactions": 1523,
    "trading_volume_30d_usd": 125000,
    "active_chains": ["ethereum", "base", "arbitrum"],
    "risk_profile": {
      "score": 72,
      "level": "MEDIUM",
      "factors": {
        "diversification": "HIGH",
        "transaction_frequency": "MODERATE",
        "protocol_exposure": "LOW",
        "smart_contract_interaction": "HIGH"
      }
    },
    "patterns": {
      "primary_activity": "DeFi trading",
      "preferred_dexs": ["Uniswap", "Curve"],
      "avg_trade_size_usd": 2500,
      "peak_activity_hours": "14:00-18:00 UTC"
    }
  },
  "source": "elsa-x402",
  "cost": "$0.02",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to Elsa failed
* `INVALID_ADDRESS`: Not a valid Ethereum address
* `INSUFFICIENT_HISTORY`: Wallet has too few transactions for meaningful analysis
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached
* `ELSA_SERVICE_UNAVAILABLE`: Elsa API is unreachable

***

#### `get_wallet_pnl`

Get a profit and loss report for a wallet over a time period via Elsa x402. Breaks down realized and unrealized P\&L, gas costs, and per-token performance. Complements the `get_agent_revenue` intelligence tool with actual on-chain P\&L data from a third-party source.

**Parameters**:

| Name      | Type     | Required | Description                                            |
| --------- | -------- | -------- | ------------------------------------------------------ |
| `address` | `string` | No       | Wallet address. Default: the configured agent wallet.  |
| `period`  | `string` | No       | Time period: "7d", "30d", "90d", "1y". Default: "30d". |

**Returns**:

```json
{
  "wallet_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
  "period": "30d",
  "pnl": {
    "total_pnl_usd": 1823.45,
    "realized_pnl_usd": 945.2,
    "unrealized_pnl_usd": 878.25,
    "gas_costs_usd": 42.3,
    "net_pnl_usd": 1781.15,
    "roi_pct": 8.2
  },
  "by_token": [
    {
      "token": "WETH",
      "pnl_usd": 1200.0,
      "trades": 12,
      "avg_entry_price": 3050.0,
      "current_price": 3240.0
    },
    {
      "token": "UNI",
      "pnl_usd": -45.5,
      "trades": 3,
      "avg_entry_price": 13.2,
      "current_price": 12.45
    }
  ],
  "by_category": {
    "trading": 945.2,
    "lp_fees": 623.25,
    "staking_rewards": 255.0
  },
  "source": "elsa-x402",
  "cost": "$0.015",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to Elsa failed
* `INVALID_ADDRESS`: Not a valid Ethereum address
* `INSUFFICIENT_HISTORY`: Not enough transaction history for the requested period
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached
* `ELSA_SERVICE_UNAVAILABLE`: Elsa API is unreachable

***

#### `get_yield_opportunities`

Discover yield opportunities across DeFi protocols via Elsa x402. Returns staking, lending, and LP opportunities ranked by APY with risk indicators. Broader than Uniswap-only pool APY data -- includes Lido, Aave, Compound, Morpho, and other protocols.

**Parameters**:

| Name      | Type     | Required | Description                                                                        |
| --------- | -------- | -------- | ---------------------------------------------------------------------------------- |
| `address` | `string` | No       | Wallet address for personalized suggestions. Default: the configured agent wallet. |

**Returns**:

```json
{
  "opportunities": [
    {
      "protocol": "Lido",
      "type": "staking",
      "asset": "ETH",
      "apy": 4.2,
      "tvl_usd": 32000000000,
      "risk": "LOW",
      "chain": "ethereum",
      "min_deposit": "0.01 ETH"
    },
    {
      "protocol": "Uniswap V3",
      "type": "liquidity",
      "asset": "WETH/USDC",
      "apy": 12.8,
      "tvl_usd": 245000000,
      "risk": "MEDIUM",
      "chain": "ethereum",
      "min_deposit": null
    },
    {
      "protocol": "Aave V3",
      "type": "lending",
      "asset": "USDC",
      "apy": 5.1,
      "tvl_usd": 8500000000,
      "risk": "LOW",
      "chain": "base",
      "min_deposit": "1 USDC"
    }
  ],
  "personalized": {
    "based_on_holdings": true,
    "suggestion": "Your idle 1,250 USDC on Base could earn ~5.1% APY on Aave V3"
  },
  "source": "elsa-x402",
  "cost": "$0.02",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to Elsa failed
* `INVALID_ADDRESS`: Not a valid Ethereum address
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached
* `ELSA_SERVICE_UNAVAILABLE`: Elsa API is unreachable

***

#### `get_elsa_swap_quote`

Get a cross-DEX swap quote via Elsa x402. Returns optimal routing, estimated output, price impact, and gas estimate. Useful as an additional venue for the `compare_venues` intelligence tool. Elsa routes across multiple DEXs and aggregators.

**Parameters**:

| Name       | Type     | Required | Description                                                               |
| ---------- | -------- | -------- | ------------------------------------------------------------------------- |
| `tokenIn`  | `string` | Yes      | Input token address (0x...)                                               |
| `tokenOut` | `string` | Yes      | Output token address (0x...)                                              |
| `amount`   | `string` | Yes      | Amount of input token (human-readable, e.g., "100")                       |
| `chain`    | `string` | Yes      | Chain name or chain ID                                                    |
| `address`  | `string` | No       | Wallet address for routing context. Default: the configured agent wallet. |
| `slippage` | `number` | No       | Slippage tolerance in percent. Default: 2.0.                              |

**Returns**:

```json
{
  "quote": {
    "tokenIn": {
      "symbol": "USDC",
      "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "amount": "100"
    },
    "tokenOut": {
      "symbol": "WETH",
      "address": "0x4200000000000000000000000000000000000006",
      "estimatedOutput": "0.0283",
      "estimatedOutputUsd": 99.55
    },
    "priceImpactPct": 0.12,
    "gasEstimateUsd": 0.45,
    "route": ["USDC", "WETH"],
    "chain": "base"
  },
  "source": "elsa-x402",
  "cost": "$0.01",
  "timestamp": "2026-02-14T12:00:00Z"
}
```

**Note**: This tool is read-only -- it returns a quote but does not execute the swap. For execution, use `execute_swap` which routes through Gotts Safe's own safety middleware. This quote is primarily useful as an additional data point for the `compare_venues` intelligence tool.

**Error Cases**:

* `X402_DISABLED`: x402 outbound client not enabled
* `X402_PAYMENT_FAILED`: USDC payment to Elsa failed
* `TOKEN_NOT_FOUND`: Token not found on the specified chain
* `NO_ROUTE`: No viable swap route found
* `SPENDING_LIMIT_EXCEEDED`: x402 hourly or daily spending limit reached
* `ELSA_SERVICE_UNAVAILABLE`: Elsa API is unreachable

***
