From abd4445db652e5779a5851949a601c410ae71d22 Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Wed, 19 Aug 2026 17:32:01 +0800 Subject: [PATCH 1/7] docs(ai): reconcile canonical integration contracts - Lock the 24-market roster and account API behavior with live acceptance checks.\n- Publish raw Markdown and first-class CLI and SDK discovery paths.\n- Sync CLI, MCP, and Skills versions with structured output contracts. --- .github/workflows/gh-pages.yml | 23 +- CHANGELOG.md | 14 + docs/ai_support/ai_llms.md | 5 +- docs/ai_support/cli_and_sdk.md | 100 +++++ docs/ai_support/index.md | 5 +- docs/ai_support/justlend_skills.md | 75 ++-- docs/ai_support/mcp_server.md | 21 +- docs/developers/apis.md | 16 +- .../apis/agent-acceptance-latest.json | 73 ++++ docs/developers/apis/agent-acceptance.md | 14 +- docs/developers/apis/justlend_apis.yaml | 30 +- docs/developers/contracts.json | 10 +- docs/developers/contracts.schema.json | 6 +- docs/developers/contracts_overview.md | 4 +- docs/developers/justlend_v2.md | 2 +- docs/documents/aidocs/account_position.md | 2 +- docs/documents/aidocs/common_questions.md | 2 +- docs/documents/aidocs/index.md | 7 +- docs/documents/aidocs/mcp_tools.md | 406 +++++++++++------- docs/documents/aidocs/quickstart.md | 2 +- docs/documents/aidocs/source_of_truth.md | 24 +- docs/getting_started/overview.md | 2 +- docs/index.md | 6 +- docs/llms-full.txt | 50 ++- docs/llms.txt | 15 +- docs/overrides/base.html | 14 +- docs/resources/glossary.md | 4 +- hooks/copy_dotfiles.py | 23 +- mkdocs.yml | 2 + scripts/api-acceptance.mjs | 254 ++++++----- scripts/verify-ai-consistency.mjs | 119 +++++ 31 files changed, 985 insertions(+), 345 deletions(-) create mode 100644 docs/ai_support/cli_and_sdk.md create mode 100644 docs/developers/apis/agent-acceptance-latest.json mode change 100644 => 100755 scripts/api-acceptance.mjs create mode 100755 scripts/verify-ai-consistency.mjs diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index dd10e93..8a89dee 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -3,7 +3,9 @@ on: push: branches: - main # Trigger this workflow whenever the main branch changes - workflow_dispatch: # Allow manual triggering of this workflow via the "Run workflow" button on the GitHub UI Actions tab + workflow_dispatch: # Allow manual triggering of this workflow via the "Run workflow" button on the GitHub UI Actions tab + schedule: + - cron: '17 2 * * 1' # Weekly live contract check, Monday 02:17 UTC jobs: build: runs-on: ubuntu-latest @@ -14,6 +16,19 @@ jobs: persist-credentials: false # Disable auto-injection of GITHUB_TOKEN so a higher-privilege token can be supplied in later steps fetch-depth: 0 # Required by mkdocs-git-revision-date-localized-plugin to compute per-page last-updated + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Verify AI-readable source consistency + run: node scripts/verify-ai-consistency.mjs + + - name: Run live API agent acceptance + run: | + node scripts/api-acceptance.mjs --json > docs/developers/apis/agent-acceptance-latest.json + node -e "const r=require('./docs/developers/apis/agent-acceptance-latest.json'); if(!r.success||r.passed!==r.total) process.exit(1)" + - name: Setup Python uses: actions/setup-python@v4 with: @@ -31,13 +46,17 @@ jobs: pip install mkdocs-git-revision-date-localized-plugin==1.4.7 # per-page last-updated from git history - name: Build the document - run: mkdocs build # Build the MkDocs site + run: mkdocs build --strict - name: Verify security metadata output run: | test -f site/.nojekyll test -f site/.well-known/security.txt cmp docs/.well-known/security.txt site/.well-known/security.txt + test -f site/ai_support/cli_and_sdk.md + cmp docs/ai_support/cli_and_sdk.md site/ai_support/cli_and_sdk.md + grep -q 'type="text/markdown"' site/ai_support/cli_and_sdk/index.html + test -f site/developers/apis/agent-acceptance-latest.json - name: Add CNAME file run: echo 'docs.justlend.org' > site/CNAME diff --git a/CHANGELOG.md b/CHANGELOG.md index c46693b..06b28d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,20 @@ For the JustLend protocol itself, see governance proposals on [forum.justlend.or ## [Unreleased] +### Added — 2026-08-19 AI-readability contract pass + +- Added first-class CLI and V2 Utils discovery across navigation, `llms.txt`, `llms-full.txt`, AI source routing, JSON-LD, and a dedicated install/safety guide. +- Synced the agent surfaces to CLI `1.0.1`, full MCP `1.1.3`, and Skills `1.1.1`, including versioned success/error envelopes and published output schemas. +- Regenerated the site-local 98-tool MCP catalog with `outputSchema` coverage on every tool and documented the bundled Skills server's 9 structured outputs. +- Published canonical raw Markdown beside every rendered page and advertised it with `rel="alternate" type="text/markdown"` plus a visible source link. +- Added deterministic AI-consistency checks and a weekly, structured 9-probe live API acceptance artifact in CI. + +### Fixed — 2026-08-19 AI-readability contract pass + +- Reconciled the market inventory to **24 total (18 active + 6 legacy)** after expanding `app.justlend.org/marketNew` and cross-checking `/lend/jtoken` plus the MCP chain catalog; added the previously omitted active `jU` market everywhere. +- Corrected `/lend/account`: `addresses` is optional, omission returns the global account index, and the endpoint-specific default `pageSize` is 50. +- Added verification provenance and freshness metadata to `contracts.json` and its JSON Schema. + ### Added — 2026-05-22 API-style + reference-gap pass - **TronWeb call style unified across all developer pages.** Removed every `.methods.X()` (Web3.js-style) call from `developers/common_pitfalls.md` (10 occurrences) and `developers/supply_and_borrow_market/sbm.md` (admonition snippet) — now consistently using TronWeb 5.x direct style (`contract.method(args).call()` / `.send()`). Also dropped `.send({ from: addr })` (8 in common_pitfalls + 4 in sbm) in favor of the canonical TronWeb pattern of setting `tronWeb.defaultAddress` once. Both styles were technically supported, but the same file used both inconsistently. The `safeApprove` helper now throws early if `tronWeb.defaultAddress.base58` is unset (silent "no sender" failure was the most common confusion). diff --git a/docs/ai_support/ai_llms.md b/docs/ai_support/ai_llms.md index ae8776d..1a58ac3 100644 --- a/docs/ai_support/ai_llms.md +++ b/docs/ai_support/ai_llms.md @@ -30,6 +30,8 @@ JustLend DAO provides machine-readable documentation endpoints optimized for LLM | Validating a copy of `contracts.json` (schema check) | [`contracts.schema.json`](../developers/contracts.schema.json) (JSON Schema 2020-12) | | Contract calls, event decoding, and agent tooling | [`developers/abis/`](../developers/abis/jtoken.json) | | MCP tool routing and safety annotations | [`MCP Tool Catalog`](../documents/aidocs/mcp_tools.md) | +| Deterministic shell and CI automation | [JustLend CLI](cli_and_sdk.md#cli-deterministic-terminal-automation) | +| Embedded V2 browser or Node.js integration | [JustLend V2 Utils](cli_and_sdk.md#v2-utils-embedded-application-integration) | ## AI Docs scoring and retrieval hints @@ -43,7 +45,8 @@ The [`documents/aidocs`](../documents/aidocs/index.md) section is intentionally ## Notes for agents -- Treat the OpenAPI spec, MCP tools, `contracts.json`, and ABI JSON files as machine-readable sources of truth. +- Treat the OpenAPI spec, MCP tools, CLI JSON envelopes, `contracts.json`, and ABI JSON files as machine-readable sources of truth. +- Use the [CLI and V2 SDK guide](cli_and_sdk.md) to choose between terminal automation and embedded integration, and inspect side effects before any signature or broadcast. - Treat rendered pages as human-readable explanations and examples. - Respect documented precision rules: jTokens use 8 decimals; underlying assets use their own decimals; rates and mantissas are scaled by `1e18`. - Use Nile testnet for integration testing and Mainnet only when users explicitly intend production transactions. diff --git a/docs/ai_support/cli_and_sdk.md b/docs/ai_support/cli_and_sdk.md new file mode 100644 index 0000000..7d70bad --- /dev/null +++ b/docs/ai_support/cli_and_sdk.md @@ -0,0 +1,100 @@ +--- +title: JustLend CLI and V2 SDK +description: Official source-installable JustLend CLI and V2 utility library for deterministic terminal automation and embedded TRON application integrations, with JSON, exit-code, signing, and safety guidance. +tags: + - justlend + - cli + - sdk + - tronweb + - automation + - ai-support +--- + +# JustLend CLI and V2 SDK + +JustLend provides two source-distributed integration surfaces in addition to the HTTP API, MCP server, and Skills package: + +| Surface | Repository | Current version | Best for | Side effects | +|---------|------------|-----------------|----------|--------------| +| **JustLend CLI** | [`justlend/justlend-cli`](https://github.com/justlend/justlend-cli) | `1.0.1` | Deterministic terminal automation, CI jobs, dry-run transaction simulation, and machine-readable command output. | Mix of read-only and signing/broadcast commands; inspect the command class and simulate first. | +| **JustLend V2 Utils** | [`justlend/justlend-utils-v2`](https://github.com/justlend/justlend-utils-v2) | `1.0.0` | Embedding V2 vault, lending, liquidation, mining, WTRX, and energy-purchase flows in browser or Node.js applications. | Many exported methods build, sign, or broadcast transactions through the injected `TronWeb` instance. | + +Neither project is currently published to npm. Install from the official GitHub source rather than guessing an npm package name. + +## CLI: deterministic terminal automation + +```bash +git clone https://github.com/justlend/justlend-cli.git +cd justlend-cli +npm ci +npm run build +npm link +justlend --help +``` + +The CLI exposes 31 top-level command groups covering V1 and V2 lending, vaults, account positions, liquidation, sTRX and stUSDT staking, WTRX, energy rental, governance, mining, rewards, history, portfolio analysis, and transaction simulation. + +### Agent contract + +- Add `--json` for exactly one machine-readable success or error envelope, including parser and usage failures. Do not parse colorized human tables. +- Branch on the process exit code: `0` for success, non-zero for usage, validation, transport, simulation, signing, or broadcast failures. +- Pin output schema major `1`: success is `{ schemaVersion: "1.0.0", success: true, data }`; failure is `{ schemaVersion, success: false, error, code, retryable, hint? }`. +- Validate output with [`schemas/output-v1.schema.json`](https://github.com/justlend/justlend-cli/blob/main/schemas/output-v1.schema.json). Treat `retryable` as the retry signal; never blindly retry a write. +- Use `--dry-run --dry-run-owner
` first. Dry-run simulates and never signs or broadcasts. +- Use `--no-broadcast` for sign-only validation, then broadcast only after explicit human intent. +- In non-interactive or JSON mode, writes require `--yes`; that flag bypasses the local prompt and must not be added automatically. +- Prefer `--network nile` for integration tests. Mainnet writes are irreversible. + +```bash +# Read-only, machine-readable +justlend --json --network mainnet market list + +# No signer and no broadcast +justlend --json --network nile --dry-run \ + --dry-run-owner TYourAddress... strx stake 0.000001 +``` + +See the repository README for the complete command tree, response schema, retry policy, and side-effect classification. + +## V2 Utils: embedded application integration + +```bash +npm install github:justlend/justlend-utils-v2 +# or: pnpm add github:justlend/justlend-utils-v2 +``` + +Inject a ready `TronWeb` instance before calling contract helpers. In Node.js, also set the sender explicitly: + +```js +import { TronWeb } from 'tronweb'; +import { tronObj } from 'justlend-v2-utils'; + +const tronWeb = new TronWeb({ + fullHost: 'https://nile.trongrid.io', + privateKey: process.env.PRIVATE_KEY, +}); + +tronObj.tronWeb = tronWeb; +tronObj.defaultAccount = tronWeb.defaultAddress.base58; +tronObj.network = 'nile'; +``` + +### Agent safety rules + +1. Never invent contract addresses or market parameters. Resolve them from the live API, MCP tools, or [`contracts.json`](../developers/contracts.json). +2. Preserve amounts as decimal strings or `BigNumber` values; do not route token amounts through JavaScript `number`. +3. Inspect whether a helper is read-only or creates a transaction before calling it. `depositToVault`, `supplyCollateral`, `borrow`, `repay`, `liquidate`, `multiClaim`, and energy `purchase()` are write paths. +4. Keep private keys, signed transactions, and wallet session material out of prompts, logs, and tool output. +5. Use Nile and a non-production wallet for tests. Require explicit human confirmation immediately before a Mainnet signature or broadcast. +6. For energy purchases, supply the API URL and durable payment-risk storage explicitly; never fabricate pricing or payment-address fallbacks. + +## Which integration surface should an agent choose? + +| Need | Use | +|------|-----| +| Public read-only HTTP data | [OpenAPI](../developers/apis/justlend_apis.yaml) | +| Wallet-aware agent tools with discoverable schemas | [Full MCP server](mcp_server.md) | +| Read-only reusable agent instructions | [JustLend Skills](justlend_skills.md) | +| Reproducible shell/CI automation | **JustLend CLI** | +| Embedded browser or Node.js contract integration | **JustLend V2 Utils** | +| Deployed addresses and ABI lookup | [`contracts.json`](../developers/contracts.json) + [JSON ABIs](../developers/abis/index.md) | diff --git a/docs/ai_support/index.md b/docs/ai_support/index.md index 00d609c..b666354 100644 --- a/docs/ai_support/index.md +++ b/docs/ai_support/index.md @@ -12,7 +12,7 @@ tags: # AI Support -This section collects everything an AI agent or LLM tool needs to integrate with JustLend DAO: machine-readable documentation endpoints, the MCP server, JustLend Skills, and a compact AI/RAG documentation set. +This section collects everything an AI agent or LLM tool needs to integrate with JustLend DAO: machine-readable documentation endpoints, the MCP server, JustLend Skills, the official CLI and V2 utility library, and a compact AI/RAG documentation set. ## In this section @@ -21,6 +21,7 @@ This section collects everything an AI agent or LLM tool needs to integrate with | [AI / LLMs](ai_llms.md) | Machine-readable entry points — [`llms.txt`](/llms.txt), [`llms-full.txt`](/llms-full.txt), OpenAPI YAML, `contracts.json`, JSON ABIs — and which to use when. | | [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (98 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | | [JustLend Skills](justlend_skills.md) | The GitHub-distributed JustLend Skills project (9 read-only tools) for agent frameworks. | +| [CLI and V2 SDK](cli_and_sdk.md) | Source installation, versioning, JSON/exit-code contract, dry-run workflow, TronWeb injection, and write-safety rules. | | [AI Docs for Agents](../documents/aidocs/index.md) | Compact, RAG-oriented pages: source-of-truth routing, market/account/workflow guides, MCP safety policy, English/Chinese FAQs, and the full MCP tool catalog. | ## Machine-readable sources of truth @@ -38,5 +39,7 @@ For task-by-task routing (e.g. "what markets exist", "this address's health fact - **Read-only HTTP integration** → OpenAPI spec / `/lend/*` endpoints. - **Agent workflows and wallet actions** → MCP server tools. +- **Terminal / CI automation** → JustLend CLI with `--json` and exit-code checks. +- **Embedded browser or Node.js integration** → JustLend V2 Utils with an explicitly injected `TronWeb` instance. - **Addresses and ABIs** → `contracts.json` + `/developers/abis/`. - **Concepts and risk context** → the human documentation pages. diff --git a/docs/ai_support/justlend_skills.md b/docs/ai_support/justlend_skills.md index a563c53..20ffe73 100644 --- a/docs/ai_support/justlend_skills.md +++ b/docs/ai_support/justlend_skills.md @@ -9,6 +9,8 @@ description: "GitHub-distributed JustLend Skills — 9 read-only MCP tools and 5 JustLend Skills is a GitHub-distributed AI Agent skills project for the **JustLend DAO** protocol on TRON. Its local package identifier is `@justlend/justlend-skills`. It provides structured skill instructions and a lightweight **read-only** [MCP server](https://modelcontextprotocol.io/) (9 query tools) that enables AI agents (Claude Code, Claude Desktop, Cursor, Codex, etc.) to query market data, monitor account positions, and analyze DeFi lending information. +**Current version:** `1.1.1` · bundled MCP output schema: `1.0.0` + !!! important "Install from GitHub, not the npm registry" `@justlend/justlend-skills` is **not currently published to npm**. The scoped name identifies the cloned project for local tooling; it is not an installable registry package. Clone the [GitHub repository](https://github.com/justlend/justlend-skills) and run `bash install.sh`. Do **not** run `npm install @justlend/justlend-skills`. @@ -49,10 +51,10 @@ The project includes 5 structured skill modules in the `/skills` directory that The `justlend-lending-v1` skill works with the built-in 9 query tools. The other four skills provide instructional guidance and require the [full MCP server](mcp_server.md) for tool execution (and write operations). -## Featured Markets (CLI Quick Reference) +## Bundled Market Shortcuts !!! warning "Not an exhaustive market list" - The table below lists the **9 markets the bundled CLI examples target by symbol shortcut**. It is **not** the protocol's full market roster. The JustLend DAO protocol currently exposes **18 active + 6 legacy = 24 markets total** (see the single source of truth below). All 24 are queryable through the Skills MCP server via `get_supported_markets` / `get_all_markets` — the CLI shortcuts are just a convenience subset for human terminal use. + The table below lists the **8 static shortcuts** used by the bundled `get_token_balance` and `check_allowance` implementations. It is **not** the protocol's full market roster. The JustLend DAO protocol exposes **18 active + 6 legacy = 24 markets total**, including active `jU`. `get_all_markets` queries the visible live inventory; `get_supported_markets` returns only these 8 shortcuts. Use the full MCP server or `contracts.json` for the complete static address catalog. **Single source of truth for the live market list (in order of preference):** @@ -60,17 +62,16 @@ The `justlend-lending-v1` skill works with the built-in 9 query tools. The other 2. **Machine-readable address book** — [`/developers/contracts.json`](../developers/contracts.json) (regenerated from the MCP server's `chains.ts`). 3. **Rendered table** — [APIs §2 — jToken Address Reference](../developers/apis.md#2-jtoken-address-reference) (all 24 markets, legacy rows tagged). -| jToken | Underlying | Description | -|--------|-----------|-------------| -| jTRX | TRX | Native TRON token | -| jUSDT | USDT | Tether USD | -| jUSDD | USDD | Decentralized USD | -| jBTC | BTC | Bitcoin (TRC20) | -| jETH | ETH | Ethereum (TRC20) — dApp display name "ETH" (formerly "ETHOLD") | -| jETHB | ETHB | Ethereum bridged — dApp display name "ETHB" (formerly "ETH") | -| jSUN | SUN | SUN Token | -| jWIN | WIN | WINkLink | -| jHTX | HTX | HTX token | +| Shortcut | jToken | Underlying | Status / purpose | +|----------|--------|------------|------------------| +| `TRX` | jTRX | TRX | Active; native balance, no allowance | +| `USDT` | jUSDT | USDT | Active shortcut | +| `USDD` | jUSDD | USDD | Active shortcut | +| `USDC` | jUSDCOLD | USDCOLD | Legacy compatibility shortcut | +| `BTC` | jBTC | BTC | Active shortcut | +| `ETH` | jETH | ETH | Active shortcut | +| `SUN` | jSUN | SUN | Active shortcut | +| `WIN` | jWIN | WIN | Active shortcut | Markets currently **closed** to new supply/borrow (legacy, queryable but do not direct new deposits to them): `jUSDCOLD`, `jUSDDOLD`, `jUSDJ`, `jWBTT`, `jSUNOLD`, `jBUSDOLD`. @@ -91,6 +92,8 @@ Or install the cloned repository's dependencies manually: ```bash npm install +npm test # offline MCP schema/version/error-contract checks +npm run test:smoke # live 24-market inventory drift check ``` The `npm install` command above must be run **inside the cloned repository**; it does not install `@justlend/justlend-skills` from npm. The `install.sh` script installs those dependencies, creates `.env`, and prompts for your TronGrid API key. @@ -210,7 +213,7 @@ For quick checks directly from the terminal: ```bash node scripts/justlend_api.mjs markets # List all markets with APY node scripts/justlend_api.mjs dashboard # Protocol dashboard (TVL, users) -node scripts/justlend_api.mjs supported-markets # List supported markets & addresses +node scripts/justlend_api.mjs supported-markets # List 8 bundled shortcuts & addresses node scripts/justlend_api.mjs balance # Check TRX balance node scripts/justlend_api.mjs balance USDT # Check token balance node scripts/justlend_api.mjs account # Account health status @@ -266,13 +269,23 @@ Participate in JustLend DAO governance proposals. Deposit JST for voting power ( ### Tools (9 total, all read-only) -Every tool returns its result as JSON text (`content[0].text`). Input types and required flags are taken from each tool's `inputSchema`; all inputs are strings. +Every tool declares both `inputSchema` and `outputSchema`. For backward compatibility, successful calls keep the raw result as JSON text in `content[0].text`; schema-aware clients should consume `structuredContent`: + +```json +{ + "schemaVersion": "1.0.0", + "tool": "get_all_markets", + "result": [] +} +``` + +Pin schema major `1`. Input types and required flags come from each tool's `inputSchema`; all current arguments are strings and unknown properties are rejected. | Tool | Input (· required) | Output (key fields) | |------|--------------------|---------------------| | `get_all_markets` | _(none)_ | Array of markets — `symbol`, `supplyAPY`, `borrowAPY`, `miningAPY`, `tvl`, `totalSupply`, `totalBorrow` | | `get_dashboard` | _(none)_ | Protocol overview — `totalSupplyUSD`, `totalBorrowUSD`, `tvlUSD`, `userCount` | -| `get_supported_markets` | _(none)_ | Array — `symbol`, `jtokenAddress`, `underlyingAddress`, `decimals`, `isNative` | +| `get_supported_markets` | _(none)_ | 8-shortcut array — `symbol`, `jToken`, `underlying`, `decimals`, `isNative` | | `get_jtoken_details` | `jtokenAddr` · **required** | jToken detail — interest-rate-model params, `reserves`, `utilization`, mining rewards | | `get_account_summary` | `address` · **required** | `healthFactor`, `liquidityUSD`, `shortfallUSD`, `totalSupplyUSD`, `totalBorrowUSD`, `positions[]` | | `get_account_data_from_api` | `address` · **required** | Comprehensive account data — `positions[]`, accrued `rewards`, per-market balances | @@ -280,26 +293,34 @@ Every tool returns its result as JSON text (`content[0].text`). Input types and | `get_token_balance` | `address` · **required**, `token` · **required** | `{ address, token, balance }` — `token` is a symbol (USDT, USDD, …); `balance` in token units | | `check_allowance` | `address` · **required**, `asset` · **required** | `{ asset, allowance, needsApproval, note }`; native TRX → `allowance: "Infinity", needsApproval: false` | -> Inputs validate as JSON-Schema `string`. `address` must be a Base58 TRON address (`T…`, 34 chars); `token`/`asset` are symbols resolved to contract addresses internally; `jtokenAddr` is a jToken contract address. +> The bundled schema currently enforces JSON-string types and required fields, not a Base58 regex. Callers should still supply a valid Base58 TRON address (`T…`, 34 chars). `token`/`asset` are one of the 8 shortcut symbols resolved internally; `jtokenAddr` is a jToken contract address. ### Error Handling -Tool failures return a structured error result rather than throwing — the client sees `isError: true`: +Tool failures return a versioned structured error rather than throwing — the client sees `isError: true`, and the same JSON object appears in text and `structuredContent`: ```json -{ "content": [{ "type": "text", "text": "Error: " }], "isError": true } +{ + "schemaVersion": "1.0.0", + "tool": "get_all_markets", + "error": "HTTP 429 rate limit", + "errorCode": "rate_limit", + "retryable": true, + "hint": "Retry this read after exponential backoff and respect any Retry-After value." +} ``` -Common messages and how to recover: +Stable codes and how to recover: -| Message | Cause | Fix | -|---------|-------|-----| -| `API Error: ` | JustLend API returned a non-zero `code` | Retry; if it persists, verify the address/market exists | -| `Unknown asset: ` | `asset` / `token` symbol not recognized | Use a supported symbol (see `get_supported_markets`) | -| `Failed to read token balance` / `Failed to read allowance` | On-chain read returned empty (bad address or RPC hiccup) | Check the address format; retry on transient RPC errors | -| `TronGrid` 4xx / `429` | Missing or rate-limited `TRONGRID_API_KEY` | Set a valid key; back off on `429` | +| `errorCode` | Retryable | Agent action | +|-------------|:---------:|--------------| +| `invalid_input` | No | Correct the tool name, address, or shortcut symbol before retrying. | +| `authentication` | No | Set a valid local `TRONGRID_API_KEY`, then retry. | +| `rate_limit` | Yes | Back off exponentially and respect `Retry-After`. | +| `transient` | Yes | Retry the read with exponential backoff. | +| `internal` | No | Inspect server stderr and arguments; do not loop automatically. | -All tools are read-only, so a failure never leaves partial on-chain state — errors are safe to retry. +All tools are read-only, so a failure never leaves partial on-chain state. Even so, auto-retry only when `retryable: true`; corrective errors should not be repeated unchanged. ## Security diff --git a/docs/ai_support/mcp_server.md b/docs/ai_support/mcp_server.md index 0561541..adf20ca 100644 --- a/docs/ai_support/mcp_server.md +++ b/docs/ai_support/mcp_server.md @@ -1,6 +1,6 @@ --- title: JustLend MCP Server (full, read + write) -description: "@justlend/mcp-server-justlend v1.1.2 — 98 MCP tools across JustLend V1 (supply, borrow, repay, sTRX staking, energy rental, governance, mining) and V2 vaults/markets/liquidation, plus historical records and general TRON utilities. Dual-mode signing (browser TronLink or encrypted agent-wallet)." +description: "@justlend/mcp-server-justlend v1.1.3 — 98 MCP tools with versioned output schemas across JustLend V1 and V2, plus historical records and general TRON utilities. Dual-mode signing (browser TronLink or encrypted agent-wallet)." --- # MCP Server @@ -30,10 +30,10 @@ The JustLend MCP Server (`@justlend/mcp-server-justlend`) is a [Model Context Pr Beyond JustLend-specific operations, the server also exposes a full set of **general-purpose TRON chain utilities** — balance queries, block/transaction data, token metadata, TRX transfers, smart contract reads/writes, staking (Stake 2.0), multicall, and more. !!! note - Current version (**v1.1.2**) covers **JustLend V1** *and* **JustLend V2**. V1 is the Compound-V2-style pooled supply/borrow market (jTokens); V2 is an isolated-market + ERC4626-vault protocol. The two surfaces are namespaced — V1 tools like `get_market_data` / `supply`, V2 tools prefixed `moolah_*` / `get_moolah_*` (the `moolah` identifier is V2's on-chain/tool naming). See the [JustLend V2](../developers/justlend_v2.md) developer page for the protocol model and deployed contracts. + Current version (**v1.1.3**) covers **JustLend V1** *and* **JustLend V2**. V1 is the Compound-V2-style pooled supply/borrow market (jTokens); V2 is an isolated-market + ERC4626-vault protocol. The two surfaces are namespaced — V1 tools like `get_market_data` / `supply`, V2 tools prefixed `moolah_*` / `get_moolah_*` (the `moolah` identifier is V2's on-chain/tool naming). See the [JustLend V2](../developers/justlend_v2.md) developer page for the protocol model and deployed contracts. -!!! tip "v1.1.2 Update" - **v1.1.2** adds native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`) and hardens TRC20 approvals — USDT/USDC/USDJ defensively reset the allowance to `0` before a new non-zero `approve` (matching the official front-end; the reset tx is confirmed on-chain before re-approving), and `amount='0'` reliably revokes. Tool errors now also carry a **`retryable`** flag with a `transient` class (see the error contract below), so agents can distinguish safe-to-retry RPC hiccups from errors needing corrective action. The surface is now **98 tools**. **v1.1.0** introduced **JustLend V2** support (from 59): 30 V2 tools (vaults, markets, liquidation, dashboard/history, mining) + 7 historical-records tools, plus 4 V2 AI prompts (**14** total) and a V2 gas estimator. It also ships **AI-agent ergonomics** — structured self-healing tool errors (`{ error, errorCode, hint }`), self-describing amounts (`{ raw, decimals, _unit, display }`) on core reads, and hardened input schemas (Base58-address + decimal-amount validation). The machine-readable `mcp-api-list.md` catalog is regenerated from source (now 98 tools). All prior V1 safety work remains in place: TRC20 allowance checks before supply/repay, opt-in `max` approvals with revoke hints, typed broadcast handling, `toSafeCallValueNumber` guards on every broadcast/simulation path, mainnet fail-closed on pre-flight `REVERT`, constant-time `MCP_API_KEY` comparison, and governance failed-proposal filtering. +!!! tip "v1.1.3 Update" + **v1.1.3** makes every one of the **98 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. The generated `mcp-api-list.md` documents this contract for every tool. It also reconciles the V1 inventory to **24 markets (18 active + 6 legacy)** and restores active `jU` to the product table. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. All prior wallet, pre-flight, fail-closed HTTP-authentication, and HITL safeguards remain in place. ## Overview @@ -86,7 +86,7 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen ## Supported Markets -The protocol exposes 23 jToken markets in total (17 active + 6 paused legacy markets). Call `get_supported_markets` for the live list with addresses. The active markets are: +The protocol exposes **24 jToken markets in total (18 active + 6 legacy markets)**. This count was verified against the expanded market table at [app.justlend.org](https://app.justlend.org/), the live `/lend/jtoken` API, and the canonical contract directory on 2026-08-19. Call `get_supported_markets` for the live list with addresses. The active markets are: | jToken | Underlying | Description | |------------|-----------|-------------| @@ -107,6 +107,7 @@ The protocol exposes 23 jToken markets in total (17 active + 6 paused legacy mar | jBTT | BTT | BitTorrent token | | jNFT | NFT | APENFT | | jHTX | HTX | HTX token | +| jU | U | U token | ## Prerequisites @@ -576,6 +577,16 @@ For programmatic contract calls without re-fetching from Tronscan, the MCP serve ## Error contract +Every tool declares a common success `outputSchema`. Schema-aware clients should consume `structuredContent` and pin schema major `1`; older clients may continue reading the first text content item: + +```json +{ + "schemaVersion": "1.0.0", + "tool": "get_supported_markets", + "result": {} +} +``` + Every tool returns errors as structured JSON with `isError: true`, so an agent can branch without parsing prose: ```json diff --git a/docs/developers/apis.md b/docs/developers/apis.md index 5ae9122..9bb8d60 100644 --- a/docs/developers/apis.md +++ b/docs/developers/apis.md @@ -167,7 +167,7 @@ Endpoints that accept `pageNo` and `pageSize` return: ``` - `pageNo` is 1‑based. Default = `1`. -- `pageSize` default = `10`, **max = `1000`**. +- `pageSize` default = `10`, **max = `1000`**, except `/lend/account`, whose verified default is `50`. - Invalid or out-of-range `pageNo`/`pageSize` are often **silently ignored** (defaults applied, `200 SUCCESS`) rather than rejected — validate client-side. See [§1.6 Error responses](#16-error-responses). ### 1.6 Error responses @@ -350,24 +350,30 @@ Returns the on‑chain state of every Supply & Borrow market: rates, total suppl ### 3.2 `GET /lend/account` — User SBM positions -Returns each queried wallet's supply/borrow positions, health factor and totals. +Returns supply/borrow positions, health factors, and totals. With `addresses`, it filters to one or more wallets. Without `addresses`, it returns the global paginated account index; this read-only scan behavior and its 50-row default were verified on 2026-08-19. **Parameters** | Name | In | Type | Required | Description | |-----------------------|-------|---------|----------|-------------------------------------------------------------------------------| -| `addresses` | query | string | yes | One or more TRON addresses, **comma‑separated** (no spaces). | +| `addresses` | query | string | no | Optional TRON Base58 filter: one address or multiple **comma-separated** addresses (no spaces). Omit for the global account index. | | `minBorrowValueInTrx` | query | number | no | Only return accounts whose total borrow value (in TRX) is ≥ this threshold. | | `maxHealth` | query | number | no | Only return accounts whose health is ≤ this threshold (useful to find risky). | | `pageNo` | query | integer | no | 1‑based page number. Default `1`. | -| `pageSize` | query | integer | no | Page size. Default `10`, max `1000`. | +| `pageSize` | query | integer | no | Page size. Verified default `50`, max `1000`. | -**Example request** +**Example requests** ```http +# Filter to explicit wallets GET /lend/account?addresses=T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb,TXJgM...&pageNo=1&pageSize=20 + +# Global account scan (50 rows by default) +GET /lend/account?pageNo=1 ``` +Validate Base58 addresses client-side. The live service may silently accept malformed filters instead of returning a validation error. + **Response data** (real response captured 2026-07-15) ```json diff --git a/docs/developers/apis/agent-acceptance-latest.json b/docs/developers/apis/agent-acceptance-latest.json new file mode 100644 index 0000000..830ecbf --- /dev/null +++ b/docs/developers/apis/agent-acceptance-latest.json @@ -0,0 +1,73 @@ +{ + "schemaVersion": "1.0.0", + "generatedAt": "2026-08-19T09:25:24.647Z", + "base": "https://openapi.just.network", + "passed": 9, + "total": 9, + "success": true, + "results": [ + { + "name": "V1 market list", + "path": "/lend/jtoken", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V1 global account pagination", + "path": "/lend/account", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V1 sTRX + Energy Rental dashboard", + "path": "/lend/strx", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V1 mining APY map", + "path": "/mining/apy", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V1 high-risk account list", + "path": "/justlend/liquidate/highRiskAccountList", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V2 vault list", + "path": "/v2/index/vault/list", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V2 market list", + "path": "/v2/index/market/list", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V1 error contract (unknown path)", + "path": "/lend/nonExistentXYZ", + "httpStatus": 200, + "pass": true, + "failures": [] + }, + { + "name": "V2 error contract (missing params)", + "path": "/v2/vault/position", + "httpStatus": 200, + "pass": true, + "failures": [] + } + ] +} diff --git a/docs/developers/apis/agent-acceptance.md b/docs/developers/apis/agent-acceptance.md index 964a320..c27ce91 100644 --- a/docs/developers/apis/agent-acceptance.md +++ b/docs/developers/apis/agent-acceptance.md @@ -7,16 +7,17 @@ description: End-to-end evidence that an anonymous agent can call the JustLend p This page is the **end-to-end acceptance artifact** for the [JustLend DAO API](../apis.md): proof that an agent with nothing but the docs and an HTTP client can call the API and get responses matching the documented contract ([`justlend_apis.yaml`](justlend_apis.yaml)). -- **What it exercises:** every **anonymous GET** read endpoint (no wallet, no key, no auth) plus the V1 and V2 error contracts. -- **How to reproduce:** from the repo root, run `node scripts/api-acceptance.mjs` (Node ≥ 18, read-only, ~8 GET requests). Exit code `0` means every assertion holds. -- **Status: 8/8 probes passed** on the last run. If a re-run fails, the live service has drifted from the documented contract — update [`apis.md`](../apis.md) and the YAML, and record the new run here. +- **What it exercises:** representative anonymous GET read paths (no wallet, key, or auth), the canonical market inventory, `/lend/account` default pagination, and the V1/V2 error contracts. +- **How to reproduce:** from the repo root, run `node scripts/api-acceptance.mjs` (Node ≥ 18, read-only, 9 GET requests). Use `--json` for a versioned machine-readable report; exit code `0` means every assertion holds. +- **Status: 9/9 probes passed** on the last run. The latest structured artifact is [`agent-acceptance-latest.json`](agent-acceptance-latest.json). If a re-run fails, the live service has drifted from the documented contract — update [`apis.md`](../apis.md) and the YAML, and record the new run here. ## Last verified run ```text -JustLend API agent acceptance — 2026-07-15T08:09:17.239Z — base https://openapi.just.network +JustLend API agent acceptance — 2026-08-19T08:29:52.523Z — base https://openapi.just.network PASS V1 market list HTTP 200 /lend/jtoken +PASS V1 global account pagination HTTP 200 /lend/account PASS V1 sTRX + Energy Rental dashboard HTTP 200 /lend/strx PASS V1 mining APY map HTTP 200 /mining/apy PASS V1 high-risk account list HTTP 200 /justlend/liquidate/highRiskAccountList @@ -25,14 +26,15 @@ PASS V2 market list HTTP 200 /v2/index/market/list PASS V1 error contract (unknown path) HTTP 200 /lend/nonExistentXYZ PASS V2 error contract (missing params) HTTP 200 /v2/vault/position -8/8 endpoint probes passed. +9/9 endpoint probes passed. ``` ## What each probe asserts | Probe | Endpoint | Key assertions | |-------|----------|----------------| -| V1 market list | `/lend/jtoken` | HTTP 200; `code: 0`, `message: "SUCCESS"`; `tokenList` ≥ 20 entries; `supplyRate`/`cash`/`exchangeRate` are decimal **strings**; `borrowIndex` is a BigInt-safe integer string; `underlyingDecimal` is a JSON integer. | +| V1 market list | `/lend/jtoken` | HTTP 200; `code: 0`, `message: "SUCCESS"`; exactly 24 entries matching `contracts.json`, including `jU`; `supplyRate`/`cash`/`exchangeRate` are decimal **strings**; `borrowIndex` is a BigInt-safe integer string; `underlyingDecimal` is a JSON integer. | +| V1 global account pagination | `/lend/account` (no `addresses`) | `addresses` is optional; omitted `pageSize` returns 50 rows; `totalCount` and `totalPage` are positive integers. | | V1 sTRX dashboard | `/lend/strx` | `code: 0`; `stakeInfo.reserves` present as decimal string (key renamed from the historical `reserse`); `stakeInfo.decimal` serialized as the string `"18"`; `rentInfo` prices are decimal strings. | | V1 mining APY | `/mining/apy` | `code: 0`; one key per market (≥ 20); every value is `{ "USDD": "" }`. | | V1 high-risk list | `/justlend/liquidate/highRiskAccountList` | `code: 0`; `jtokens` is a plain **object map** (not an array); `updateTime` epoch-ms integer; account entries carry string `risk` / USD fields and integer `liquidateStatusStartTime`. | diff --git a/docs/developers/apis/justlend_apis.yaml b/docs/developers/apis/justlend_apis.yaml index 2495c70..bf72b02 100644 --- a/docs/developers/apis/justlend_apis.yaml +++ b/docs/developers/apis/justlend_apis.yaml @@ -694,14 +694,17 @@ paths: tags: - Supply and Borrow Market V1 summary: Get Account Information on V1 - description: Query to get the SBM user account information. (To pass parameters to obtain specific information, please click 「Test」and fill in the address information in the Query parameters section.) + description: >- + Query SBM account information. When `addresses` is provided, returns the matching + wallet or comma-separated wallets. When omitted, returns the global paginated account + index; the observed default page size for this endpoint is 50. This endpoint is read-only. operationId: getLendAccounts parameters: - - '$ref': '#/components/parameters/addresses' + - '$ref': '#/components/parameters/accountAddresses' - '$ref': '#/components/parameters/minBorrowValueInTrx' - '$ref': '#/components/parameters/maxHealth' - '$ref': '#/components/parameters/pageNo' - - '$ref': '#/components/parameters/pageSize' + - '$ref': '#/components/parameters/accountPageSize' responses: '200': description: >- @@ -1185,6 +1188,27 @@ components: format: int64 default: 10 maximum: 1000 + accountAddresses: + name: addresses + in: query + description: >- + Optional TRON Base58 wallet filter. Supply one address or multiple comma-separated + addresses with no spaces. Omit it to scan the global paginated account index. + required: false + schema: + type: string + pattern: '^(T[1-9A-HJ-NP-Za-km-z]{33})(,T[1-9A-HJ-NP-Za-km-z]{33})*$' + accountPageSize: + name: pageSize + in: query + description: Page size for `/lend/account`; observed default 50, maximum 1000. + required: false + schema: + type: integer + format: int64 + default: 50 + minimum: 1 + maximum: 1000 addresses: name: addresses in: query diff --git a/docs/developers/contracts.json b/docs/developers/contracts.json index 885e45f..843e887 100644 --- a/docs/developers/contracts.json +++ b/docs/developers/contracts.json @@ -4,7 +4,7 @@ "generated_by": "scripts/generate_contracts_json.py", "source_of_truth": "https://github.com/justlend/mcp-server-justlend/blob/main/src/core/chains.ts", "last_generated": "2026-06-26", - "schema_version": "1.1.0", + "schema_version": "1.2.0", "schema_version_policy": "Semantic versioning. MAJOR = breaking field rename or removal. MINOR = additive field (e.g. new role keys, new networks). PATCH = address corrections within an existing structure. Consumers should pin a MAJOR.", "address_formats": { "base58": "TRON Base58Check, T-prefixed, 34 chars — for wallets, Tronscan, TronWeb display, and end-user prompts.", @@ -15,7 +15,13 @@ "active": "Market is open for new supply and borrow. Use for new positions.", "legacy": "Market is closed to new supply and borrow. Contract is still queryable so existing positions can be unwound, but do not direct new deposits to it." }, - "comment": "All addresses are returned in three equivalent formats (see address_formats above). Network is recorded per record so consumers can mix Mainnet + Nile in one pass without context loss. Each entry under `networks.*.jtokens` carries an explicit `status` field (see status_values above) so consumers can filter `active` vs `legacy` without parsing prose elsewhere." + "comment": "All addresses are returned in three equivalent formats (see address_formats above). Network is recorded per record so consumers can mix Mainnet + Nile in one pass without context loss. Each entry under `networks.*.jtokens` carries an explicit `status` field (see status_values above) so consumers can filter `active` vs `legacy` without parsing prose elsewhere.", + "last_verified": "2026-08-19", + "verification_sources": [ + "https://app.justlend.org/", + "https://openapi.just.network/lend/jtoken", + "https://github.com/justlend/mcp-server-justlend/blob/main/src/core/chains.ts" + ] }, "networks": { "mainnet": { diff --git a/docs/developers/contracts.schema.json b/docs/developers/contracts.schema.json index 9bcaab2..e360128 100644 --- a/docs/developers/contracts.schema.json +++ b/docs/developers/contracts.schema.json @@ -23,11 +23,13 @@ "$defs": { "meta": { "type": "object", - "required": ["source_of_truth", "last_generated", "schema_version", "address_formats"], + "required": ["source_of_truth", "last_generated", "last_verified", "verification_sources", "schema_version", "address_formats"], "properties": { "generated_by": { "type": "string" }, "source_of_truth": { "type": "string", "format": "uri" }, "last_generated": { "type": "string", "format": "date" }, + "last_verified": { "type": "string", "format": "date", "description": "Date when the market count and addresses were last cross-checked against live product/API surfaces." }, + "verification_sources": { "type": "array", "minItems": 2, "items": { "type": "string", "format": "uri" }, "description": "Independent live or source-code surfaces used for the latest verification." }, "schema_version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$", "description": "Semantic version of this document's shape. Pin a MAJOR." }, "schema_version_policy": { "type": "string" }, "address_formats": { @@ -129,7 +131,7 @@ }, "jtokens": { "type": "object", - "description": "Per-market jToken records, keyed by jToken symbol. Mainnet exposes 17 active + 6 legacy = 23 markets.", + "description": "Per-market jToken records, keyed by jToken symbol. Mainnet exposes 18 active + 6 legacy = 24 markets.", "additionalProperties": { "$ref": "#/$defs/jtoken_record" } }, "interest_rate_models": { diff --git a/docs/developers/contracts_overview.md b/docs/developers/contracts_overview.md index bfcf68f..5604603 100644 --- a/docs/developers/contracts_overview.md +++ b/docs/developers/contracts_overview.md @@ -9,7 +9,7 @@ description: Architecture summary of every JustLend DAO contract on TRON — SBM * **Protocol:** JustLend DAO * **Network:** TRON Mainnet (Base58 addresses; see [`/developers/contracts.json`](contracts.json) for Mainnet + Nile addresses in Base58, EVM `0x` hex, and TRON-internal `41` hex) * **Architecture:** Compound V2 fork - * **Markets:** 17 active + 6 legacy = 23 jToken markets (authoritative list: [APIs §2](apis.md#2-jtoken-address-reference)) + * **Markets:** 18 active + 6 legacy = 24 jToken markets (authoritative list: [APIs §2](apis.md#2-jtoken-address-reference)) * **Upgrade pattern:** every contract listed below is either `Delegator → Delegate` (proxy + implementation, **upgradeable** by Governance) or **immutable**, explicitly tagged in the table. The page first gives a one-screen machine-readable summary table; deeper per-component prose follows. @@ -102,7 +102,7 @@ Single row per contract. Use this when integrating; treat the prose sections bel | Comptroller | `Unitroller` (entrypoint) | [`TGjYzgCyPobsNS9n6WcbdLVR9dH7mWqFx7`](https://tronscan.org/#/contract/TGjYzgCyPobsNS9n6WcbdLVR9dH7mWqFx7) | **Yes** (impl behind proxy) | Compound `Unitroller` (`_setPendingImplementation` + `_acceptImplementation`) | `enterMarkets`, `exitMarket`, `getAccountLiquidity`, `markets`, `closeFactorMantissa`, `liquidationIncentiveMantissa` | [`comptroller.json`](abis/comptroller.json) | [Comptroller](supply_and_borrow_market/comptroller.md) | | Comptroller | `Comptroller` (implementation) | [`TETm1bMHUm9135d5NmUgfkvqZQ4bk6DgWs`](https://tronscan.org/contract/TETm1bMHUm9135d5NmUgfkvqZQ4bk6DgWs/code) | Replaced via `Unitroller` | Implementation only | — (delegated through `Unitroller`) | [`comptroller.json`](abis/comptroller.json) | [Comptroller](supply_and_borrow_market/comptroller.md) | | SBM (TRX market) | `CErc20Delegator` (jTRX) | [`TE2RzoSV3wFK99w6J9UnnZ4vLfXYoxvRwP`](https://tronscan.org/#/contract/TE2RzoSV3wFK99w6J9UnnZ4vLfXYoxvRwP) | **Yes** (impl behind delegator) | Compound `CErc20Delegator` (`_setImplementation`) | `mint()` (payable, TRX), `borrow`, `repayBorrow` (payable), `redeem`, `redeemUnderlying`, `liquidateBorrow` (payable) | [`jtoken.json`](abis/jtoken.json) (plus [`jtrx-mint.json`](abis/jtrx-mint.json), [`jtrx-repay.json`](abis/jtrx-repay.json) for TRX-specific payable variants) | [SBM](supply_and_borrow_market/sbm.md) | -| SBM (TRC20 markets) | `CErc20Delegator` (per market, 22 instances) | See [`apis.md §2`](apis.md#2-jtoken-address-reference) | **Yes** per market | Compound `CErc20Delegator` (`_setImplementation`) | `mint(uint)`, `borrow`, `repayBorrow(uint)`, `redeem`, `redeemUnderlying`, `liquidateBorrow(address, uint, address)` | [`jtoken.json`](abis/jtoken.json) | [SBM](supply_and_borrow_market/sbm.md), [Deployed Contracts](deployed_contracts.md) | +| SBM (TRC20 markets) | `CErc20Delegator` (per market, 23 instances) | See [`apis.md §2`](apis.md#2-jtoken-address-reference) | **Yes** per market | Compound `CErc20Delegator` (`_setImplementation`) | `mint(uint)`, `borrow`, `repayBorrow(uint)`, `redeem`, `redeemUnderlying`, `liquidateBorrow(address, uint, address)` | [`jtoken.json`](abis/jtoken.json) | [SBM](supply_and_borrow_market/sbm.md), [Deployed Contracts](deployed_contracts.md) | | Interest Rate Model | `WhitePaperInterestRateModel` (linear) | Per market — see [Deployed Contracts](deployed_contracts.md) | **No** (immutable per deployment; new model contract per parameter change) | None | `getBorrowRate(cash, borrows, reserves)`, `getSupplyRate(cash, borrows, reserves, reserveFactorMantissa)` | [`interest-rate-model.json`](abis/interest-rate-model.json) | [Interest Rate Model](supply_and_borrow_market/interest_rate_model.md) | | Interest Rate Model | `JumpRateModelV2` (kinked) | Per market — see [Deployed Contracts](deployed_contracts.md) | **No** (immutable per deployment; new model contract per parameter change) | None | `getBorrowRate`, `getSupplyRate`, `multiplierPerBlock`, `jumpMultiplierPerBlock`, `kink`, `baseRatePerBlock` | [`interest-rate-model.json`](abis/interest-rate-model.json) | [Interest Rate Model](supply_and_borrow_market/interest_rate_model.md) | | Price Oracle | `PriceOracleProxy` (entrypoint) | [`TCKp2AzuhzV4B4Ahx1ej4mvQgHZ1kH7F7k`](https://tronscan.org/#/contract/TCKp2AzuhzV4B4Ahx1ej4mvQgHZ1kH7F7k) | **Yes** (impl behind proxy) | Address-only proxy (governance updates implementation pointer) | `getUnderlyingPrice(cToken)` | [`price-oracle.json`](abis/price-oracle.json) | [Price Oracle](supply_and_borrow_market/price_oracle.md) | diff --git a/docs/developers/justlend_v2.md b/docs/developers/justlend_v2.md index fcd74e9..d0abe8b 100644 --- a/docs/developers/justlend_v2.md +++ b/docs/developers/justlend_v2.md @@ -88,7 +88,7 @@ Addresses are the source-of-truth deployment config tracked in the MCP server's ## Using V2 via the MCP server -The [JustLend MCP Server](../ai_support/mcp_server.md) (v1.1.2+) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-98-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). +The [JustLend MCP Server](../ai_support/mcp_server.md) (current: v1.1.3) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-98-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). Contract ABIs (`MOOLAH_CORE_ABI`, `TRX_PROVIDER_ABI`, `MOOLAH_VAULT_ABI`, `PUBLIC_LIQUIDATOR_ABI`) are bundled in the MCP repo's [`src/core/abis.ts`](https://github.com/justlend/mcp-server-justlend/blob/main/src/core/abis.ts). For the full on-chain ABIs and contract data structures (`Position`, `MarketParams`, `MarketConfig`, `MarketAllocation`, …), see the [SBM V2 contract reference](supply_and_borrow_market/sbmV2.md). diff --git a/docs/documents/aidocs/account_position.md b/docs/documents/aidocs/account_position.md index 8025b40..536b3ff 100644 --- a/docs/documents/aidocs/account_position.md +++ b/docs/documents/aidocs/account_position.md @@ -37,7 +37,7 @@ The answer should summarize: ## OpenAPI fallback -Use `GET /lend/account?address={address}` from `https://openapi.just.network` for read-only integrations. +Use `GET /lend/account?addresses={address}` from `https://openapi.just.network` for read-only integrations. Schema: [`/developers/apis/justlend_apis.yaml`](../../developers/apis/justlend_apis.yaml) diff --git a/docs/documents/aidocs/common_questions.md b/docs/documents/aidocs/common_questions.md index c767f3a..c72ea98 100644 --- a/docs/documents/aidocs/common_questions.md +++ b/docs/documents/aidocs/common_questions.md @@ -37,7 +37,7 @@ Chinese: “USDT 存款年化多少?”、“TRX 借款 APY 多少?” ### How do I check a JustLend account position? -Use MCP `get_account_summary` with the user's TRON address and network. For HTTP integration, use `GET /lend/account?address={address}`. +Use MCP `get_account_summary` with the user's TRON address and network. For HTTP integration, use `GET /lend/account?addresses={address}`. Chinese: “查一下这个地址的 JustLend 仓位”、“这个地址健康因子是多少?” diff --git a/docs/documents/aidocs/index.md b/docs/documents/aidocs/index.md index 03aeafc..9887bcc 100644 --- a/docs/documents/aidocs/index.md +++ b/docs/documents/aidocs/index.md @@ -21,9 +21,10 @@ When multiple sources mention the same JustLend fact, agents should prefer them 1. **OpenAPI specification**: [`/developers/apis/justlend_apis.yaml`](../../developers/apis/justlend_apis.yaml) for public HTTP API routes, parameters, response schemas, units, and errors. 2. **MCP tools**: [`mcp_tools.md`](mcp_tools.md) and the live MCP server for tool names, input schemas, safety annotations, wallet mode, and transaction workflows. -3. **Contract directory**: [`/developers/contracts.json`](../../developers/contracts.json) for deployed contract addresses, network names, and active versus legacy market status. -4. **JSON ABIs**: [`/developers/abis/`](../../developers/abis/jtoken.json) for contract calls and event decoding. -5. **Human docs**: concept and developer pages for explanations, examples, and risk context. +3. **CLI / V2 Utils**: [`CLI and V2 SDK`](../../ai_support/cli_and_sdk.md) for deterministic terminal automation or embedded application integrations; inspect write side effects before signing. +4. **Contract directory**: [`/developers/contracts.json`](../../developers/contracts.json) for deployed contract addresses, network names, and active versus legacy market status. +5. **JSON ABIs**: [`/developers/abis/`](../../developers/abis/jtoken.json) for contract calls and event decoding. +6. **Human docs**: concept and developer pages for explanations, examples, and risk context. ## AI docs in this directory diff --git a/docs/documents/aidocs/mcp_tools.md b/docs/documents/aidocs/mcp_tools.md index 366170d..ea45084 100644 --- a/docs/documents/aidocs/mcp_tools.md +++ b/docs/documents/aidocs/mcp_tools.md @@ -38,7 +38,7 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ --- -## Generated MCP API List — `@justlend/mcp-server-justlend` v1.1.2 +## Generated MCP API List — `@justlend/mcp-server-justlend` v1.1.3 > **Machine-readable tool catalog (for offline routing).** Auto-generated by `scripts/gen-mcp-api-list.ts` from the `registerTool` definitions + Zod inputSchema + MCP annotations in the source — do not edit by hand; after changing any tool run `npx tsx scripts/gen-mcp-api-list.ts` to regenerate. > @@ -46,6 +46,20 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ **Total tools**: 98 | **Protocol**: MCP | **Transport**: stdio / HTTP(SSE) +## Common structured output contract (v1.0.0) + +Every tool declares an MCP `outputSchema`. Successful calls preserve the legacy text `content` and also return: + +```json +{ + "schemaVersion": "1.0.0", + "tool": "get_supported_markets", + "result": {} +} +``` + +Consume `structuredContent` when available; older clients may continue parsing the first text content item. Error results keep `isError: true` and the existing structured JSON error body. + **Read-only tools**: 58 | **Write tools**: 40 (of which marked destructive: 27) > ⚠️ Tools marked 🔴 **sign and broadcast TRON transactions that move real assets** — the client MUST require human confirmation (HITL) before executing. 🟡 tools only change local wallet/network config or start an interaction. Private keys are managed encrypted by `@bankofai/agent-wallet` or signed via the TronLink browser wallet, and are **never passed as tool arguments**. @@ -56,26 +70,29 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_wallet_address` -**Get Wallet Address** +**Get Wallet Address** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: Get the active wallet address. Returns browser wallet address if in browser mode, agent-wallet address if agent mode is selected, or a first-use wallet selection guide if no wallet mode has been chosen yet. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ### `list_wallets` -**List Wallets** +**List Wallets** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: List all wallets configured in agent-wallet. Shows wallet IDs, types, active status, and addresses. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ### `set_active_wallet` -**Set Active Wallet** +**Set Active Wallet** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: false - **Description**: Set the active wallet by wallet ID. Use list_wallets to see available wallet IDs. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -83,10 +100,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `connect_browser_wallet` -**Connect Browser Wallet** +**Connect Browser Wallet** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: false · openWorld: true - **Description**: Connect to a browser wallet (TronLink, TokenPocket) for signing transactions. RECOMMENDED: More secure than agent-wallet because private keys never leave your browser. This opens a browser window where the user must approve the connection. Tell the user to switch to their browser to approve. Blocks until the user acts or the request times out (5 min). After connecting, all write operations will use the browser wallet for signing. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -94,10 +112,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `set_wallet_mode` -**Set Wallet Mode** +**Set Wallet Mode** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: false - **Description**: Switch wallet signing mode. 'browser' (recommended, more secure): uses TronLink in your browser — private keys never leave the browser. 'agent': uses encrypted key stored in ~/.agent-wallet/. Selecting agent mode for the first time will create an encrypted agent-wallet if needed. Browser mode requires connect_browser_wallet first. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -105,18 +124,20 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_wallet_mode` -**Get Wallet Mode** +**Get Wallet Mode** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: Get the current wallet signing mode (browser, agent, or unset), connected address, and connection status. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ### `set_network` -**Set Global Network** +**Set Global Network** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: false - **Description**: Set the global default network used by all JustLend operations unless explicitly overridden. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -124,18 +145,20 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_network` -**Get Global Network** +**Get Global Network** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: Get the current global default network used by all JustLend operations. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ### `transfer_trx` -**Transfer TRX** +**Transfer TRX** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: false · openWorld: true - **Description**: Transfer TRX to another TRON address. Checks balance sufficiency (including gas) before sending. Typical cost: ~0 energy + ~270 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -145,10 +168,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `transfer_trc20` -**Transfer TRC20** +**Transfer TRC20** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: false · openWorld: true - **Description**: Transfer TRC20 tokens to another TRON address. You can pass a token symbol (e.g. 'USDT', 'JST', 'wstUSDT') or a contract address. Symbol resolution uses the server's known TRON token registry and JustLend underlying-token mappings. Amount is in human-readable units (e.g. '100' for 100 USDT). Checks balance sufficiency before sending. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -162,18 +186,20 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_supported_networks` -**Get Supported Networks** +**Get Supported Networks** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: List all supported TRON networks for JustLend. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ### `get_supported_markets` -**Get Supported Markets** +**Get Supported Markets** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: List all available JustLend lending markets (jTokens) with their addresses and underlying assets. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -181,10 +207,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_market_data` -**Get Market Data** +**Get Market Data** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get detailed market data for a specific JustLend market: supply/borrow APY, TVL, utilization, collateral factor, price, and status. Use jToken symbol like 'jUSDT' or 'jTRX'. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -193,10 +220,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_all_markets` -**Get All Markets** +**Get All Markets** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get overview data for ALL JustLend markets including supply APY, borrow APY, mining rewards APY, underlying staking yield, total supply APY, and TVL. Mining APY is calculated from on-chain supply mining programs (USDD/TRX dual mining, WBTC mining, etc.). totalSupplyAPY = base supply APY + underlying staking APY + mining APY. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -204,10 +232,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_protocol_summary` -**Get Protocol Summary** +**Get Protocol Summary** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get JustLend protocol-level info: Comptroller config, close factor, liquidation incentive, total markets. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -215,10 +244,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_account_summary` -**Get Account Summary** +**Get Account Summary** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a comprehensive view of a user's JustLend positions (supply, borrow, health factor). IMPORTANT: Returns a snapshot tied to a specific block. You MUST call this again after any transaction (supply, withdraw, etc.) to get updated balances and health factor. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -227,10 +257,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `check_allowance` -**Check Allowance** +**Check Allowance** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Check if the underlying TRC20 token has been approved for a jToken market. Must be approved before supply() or repay() for TRC20 markets. Not needed for jTRX. The returned 'allowance' is in human-readable token units (e.g. '1' means 1 USDT, not 1 raw unit). Compare it directly with the amount the user wants to supply/repay. 'allowanceUnit' indicates the token symbol. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -241,10 +272,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_trx_balance` -**Get TRX Balance** +**Get TRX Balance** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get TRX balance for an address. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -253,10 +285,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_token_balance` -**Get Token Balance** +**Get Token Balance** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get TRC20 token balance for an address. You can pass either a token symbol (e.g. 'USDD', 'USDT', 'ETH') or a contract address. When using a symbol, it resolves to the correct contract address from JustLend markets automatically. IMPORTANT: Always prefer using token symbols over raw addresses to avoid using outdated/wrong contract addresses. For example, use 'USDD' instead of a raw address — the old USDD (TPYmHEhy5n8TCEfYGqW2rPxsghSfzghPDn) is deprecated. The returned balance is already formatted in human-readable token units (decimals already applied). Do NOT divide the balance by decimals again. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -267,10 +300,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_wallet_balances` -**Get Wallet Token Balances (Batch)** +**Get Wallet Token Balances (Batch)** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Batch-fetch TRC20 token balances for a wallet across multiple JustLend markets in a single RPC call using the Multicall3 walletTokensBalance method. Returns human-readable balances (decimals already applied) for all specified tokens at once. Use this instead of calling get_token_balance repeatedly when you need balances for several tokens. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -280,10 +314,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_mining_rewards` -**Get Mining Rewards** +**Get Mining Rewards** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get mining rewards for supply markets (USDD, WBTC, etc.). Returns unclaimed rewards, mining APY, and reward breakdown from API. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -292,10 +327,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_usdd_mining_config` -**Get USDD Mining Config** +**Get USDD Mining Config** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: Get USDD mining configuration including mining periods, reward tokens (USDD/TRX dual mining), and schedule. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -303,20 +339,22 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_wbtc_mining_config` -**Get WBTC Mining Config** +**Get WBTC Mining Config** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false - **Description**: Get WBTC mining configuration and supply mining activity details. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none ## Lending Operations (10) ### `supply` -**Supply Assets** +**Supply Assets** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Supply (deposit) assets into a JustLend market to earn interest. For TRC20 markets, you must first call approve_underlying. For jTRX, TRX is sent directly. Returns a jToken balance representing your deposit. Typical cost: ~100,000 energy + ~310 bandwidth for TRC20, ~80,000 energy + ~280 bandwidth for TRX. Use estimate_lending_energy tool for precise estimates before executing. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -326,10 +364,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `withdraw` -**Withdraw Assets** +**Withdraw Assets** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Withdraw (redeem) supplied assets from a JustLend market. Specify the amount in underlying units. May fail if assets are used as collateral for active borrows. Typical cost: ~90,000 energy + ~300 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -339,10 +378,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `withdraw_all` -**Withdraw All** +**Withdraw All** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Withdraw ALL supplied assets from a JustLend market by redeeming all jTokens. Typical cost: ~90,000 energy + ~300 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -351,10 +391,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `borrow` -**Borrow Assets** +**Borrow Assets** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Borrow assets from a JustLend market against your collateral. You must have entered a market as collateral (enter_market) and have sufficient liquidity. Check your account_summary and health_factor before borrowing. Typical cost: ~100,000 energy + ~313 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -364,10 +405,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `repay` -**Repay Borrow** +**Repay Borrow** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Repay borrowed assets to a JustLend market. For TRC20 markets, must have approved underlying first. Use amount='max' to repay the full outstanding borrow. Typical cost: ~80,000~90,000 energy + ~280~320 bandwidth (TRX costs less than TRC20). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -377,10 +419,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `enter_market` -**Enter Market (Enable Collateral)** +**Enter Market (Enable Collateral)** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true - **Description**: Enable a jToken market as collateral. Required before borrowing against supplied assets. Once entered, your supply in this market counts towards your borrowing capacity. Typical cost: ~80,000 energy + ~300 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -389,10 +432,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `exit_market` -**Exit Market (Disable Collateral)** +**Exit Market (Disable Collateral)** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Disable a jToken market as collateral. Pre-checks: 1) market must have no outstanding borrows; 2) remaining collateral must still cover all borrows. Typical cost: ~50,000 energy + ~280 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -401,10 +445,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `approve_underlying` -**Approve Underlying Token** +**Approve Underlying Token** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true - **Description**: Approve the jToken contract to spend your underlying TRC20 tokens. Required before supply() or repay() for TRC20-backed markets (not needed for jTRX). Pass the EXACT amount you intend to use (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the jToken contract spend the user's entire balance, present and future, until revoked. Typical cost: ~23,000 energy + ~265 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -414,10 +459,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `claim_rewards` -**Claim Rewards** +**Claim Rewards** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: false · openWorld: true - **Description**: Claim accrued JustLend mining rewards for the configured wallet. Typical cost: ~60,000 energy + ~330 bandwidth. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -425,10 +471,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `estimate_lending_energy` -**Estimate Operation Resources** +**Estimate Operation Resources** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Estimate energy, bandwidth, and TRX cost for any JustLend operation BEFORE executing it. Covers ALL operations: supply, withdraw, withdraw_all, borrow, repay, approve, enter_market, exit_market, claim_rewards. Tries on-chain simulation first; falls back to historical typical values if simulation fails. Returns per-step breakdown (e.g. approve + mint for supply), total energy, total bandwidth, and estimated TRX cost. For supply/repay: automatically checks current allowance — if sufficient, the approve step is skipped. For approve: supports custom spender address (not just jToken). Use this tool whenever the user asks about gas/energy/cost for any lending operation. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -443,10 +490,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_proposal_list` -**Get Proposal List** +**Get Proposal List** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get the list of JustLend DAO governance proposals. Returns proposals with their status (Active, Passed, Defeated, etc.), vote counts, and details. Sorted by newest first. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -455,10 +503,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_user_vote_status` -**Get User Vote Status** +**Get User Vote Status** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's voting status across all governance proposals. Shows which proposals the user has voted on, their vote amounts (for/against/abstain), and which proposals have withdrawable votes. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -467,10 +516,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_vote_info` -**Get Vote Info** +**Get Vote Info** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get voting power info for a user: JST wallet balance, available (surplus) votes, total deposited votes, and votes currently cast in proposals. This is the key tool to check before voting — it shows how many votes are available to use. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -479,10 +529,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_locked_votes` -**Get Locked Votes** +**Get Locked Votes** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get the number of votes a user has locked in a specific proposal. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -492,10 +543,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `check_jst_allowance_for_voting` -**Check JST Voting Allowance** +**Check JST Voting Allowance** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Check if JST has been approved for the WJST voting contract. Must be approved before depositing JST to get votes. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -504,10 +556,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `approve_jst_for_voting` -**Approve JST for Voting** +**Approve JST for Voting** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true - **Description**: Approve JST token for the WJST voting contract. Required before depositing JST to get voting power. Pass the EXACT amount you intend to deposit (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the WJST contract spend the user's entire JST balance, present and future, until revoked. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -516,10 +569,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `deposit_jst_for_votes` -**Deposit JST for Votes** +**Deposit JST for Votes** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Deposit JST into the WJST contract to get voting power. Requires prior approval of JST for the WJST contract (use approve_jst_for_voting first). 1 JST = 1 Vote. Deposited JST can be withdrawn back after voting. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -528,10 +582,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `withdraw_votes_to_jst` -**Withdraw Votes to JST** +**Withdraw Votes to JST** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Withdraw WJST back to JST. Can only withdraw votes that are not currently locked in active proposals. Use get_vote_info to check your surplus (available) votes before withdrawing. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -540,10 +595,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `cast_vote` -**Cast Vote** +**Cast Vote** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Cast a vote on a governance proposal. You must have available votes (deposit JST first if needed). Support: true = vote FOR, false = vote AGAINST. You can add more votes to a proposal you already voted on. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -554,10 +610,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `withdraw_votes_from_proposal` -**Withdraw Votes from Proposal** +**Withdraw Votes from Proposal** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Withdraw (reclaim) votes from a completed or canceled proposal. Only works for proposals that are no longer active. After withdrawing, the votes become available again for other proposals or can be converted back to JST. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -568,10 +625,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_energy_rental_dashboard` -**Energy Rental Dashboard** +**Energy Rental Dashboard** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get JustLend energy rental market dashboard data including TRX price, exchange rate, total APY, energy per TRX, total supply, and other market parameters. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -579,10 +637,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_energy_rental_params` -**Energy Rental Parameters** +**Energy Rental Parameters** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get on-chain energy rental parameters: liquidation threshold, fee ratio, min fee, total delegated/frozen TRX, max rentable amount, rent paused status, usage charge ratio. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -590,10 +649,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `calculate_energy_rental_price` -**Calculate Energy Rental Price** +**Calculate Energy Rental Price** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Calculate the cost to rent a specific amount of energy for a given duration. Returns TRX amount needed, rental rate, fee, total prepayment, security deposit, and daily cost. For NEW rentals: provide energyAmount and durationHours. For RENEWALS: provide energyAmount and receiverAddress. The tool auto-detects existing rentals and calculates the incremental cost (subtracting existing security deposit). durationHours is optional for renewals (defaults to 0 = no additional time). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -604,10 +664,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_energy_rental_rate` -**Energy Rental Rate** +**Energy Rental Rate** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get the current energy rental rate for a given TRX amount. Returns rental rate, stable rate, and effective rate (max of both). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -616,10 +677,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_user_energy_rental_orders` -**User Energy Rental Orders** +**User Energy Rental Orders** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get a user's energy rental orders from JustLend. Can filter by role: 'renter' (orders where user is renting out), 'receiver' (orders where user receives energy), or 'all'. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -631,10 +693,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_energy_rent_info` -**Energy Rent Info** +**Energy Rent Info** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get on-chain energy rental info for a specific renter-receiver pair. Returns security deposit, rent balance, and whether an active rental exists. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -644,10 +707,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_return_rental_info` -**Return Rental Info** +**Return Rental Info** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get estimated refund info for returning/canceling an energy rental. Shows how much TRX would be refunded (estimatedRefundTrx), remaining rent, security deposit, usage rental cost, unrecovered energy, and daily rent cost. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -657,10 +721,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `rent_energy` -**Rent Energy** +**Rent Energy** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Rent energy from JustLend for a specified receiver address. Automatically calculates TRX needed based on energy amount. For NEW rentals: durationHours is required (minimum 1 hour), minimum energy is 300,000. For RENEWALS (existing active rental to the same receiver): durationHours is NOT needed — the remaining duration from the existing order is used automatically. Minimum energy for renewal is 50,000. Pre-checks: rental not paused, amount within limits, sufficient TRX balance. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -671,10 +736,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `return_energy_rental` -**Return Energy Rental** +**Return Energy Rental** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Return (cancel) an active energy rental. As a renter, provide the receiver address. As a receiver, provide the renter address. Pre-checks: active rental must exist between the two addresses. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -686,10 +752,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_strx_dashboard` -**sTRX Dashboard** +**sTRX Dashboard** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get sTRX staking dashboard data including TRX price, sTRX/TRX exchange rate, total APY, vote APY, total supply, unfreeze delay days, and energy stake per TRX. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -697,10 +764,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_strx_account` -**sTRX Account Info** +**sTRX Account Info** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get user's sTRX staking account info including staked amount, income, claimable rewards, withdrawn amount, and rental energy amount. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -709,10 +777,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_strx_balance` -**sTRX Balance** +**sTRX Balance** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Get the sTRX token balance for an address. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -721,10 +790,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `check_strx_withdrawal_eligibility` -**Check sTRX Withdrawal Eligibility** +**Check sTRX Withdrawal Eligibility** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: false · openWorld: true - **Description**: Check if user has TRX available to withdraw after sTRX unstaking unbonding period. Shows staked amount, claimable rewards, pending/completed unstake rounds, and withdrawal status. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -733,10 +803,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `stake_trx_to_strx` -**Stake TRX to sTRX** +**Stake TRX to sTRX** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Stake TRX via JustLend to receive sTRX tokens. sTRX earns staking rewards (vote APY + energy rental income). Pre-checks: sufficient TRX balance for staking amount + gas. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -745,10 +816,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `unstake_strx` -**Unstake sTRX** +**Unstake sTRX** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Unstake sTRX to receive TRX back. Note: unstaked TRX has an unbonding period (typically 14 days) before withdrawal. Pre-checks: sufficient sTRX balance. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -757,10 +829,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `claim_strx_rewards` -**Claim sTRX Rewards** +**Claim sTRX Rewards** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Claim all available sTRX staking rewards. Pre-checks: verifies there are claimable rewards before executing. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -770,10 +843,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `wrap_trx` -**Wrap TRX to WTRX** +**Wrap TRX to WTRX** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Wrap native TRX into WTRX (Wrapped TRX) at a 1:1 rate by sending TRX to the WTRX contract's payable deposit(). WTRX is a TRC20 representation of TRX used by DeFi protocols that can't hold native TRX (e.g. JustLend V2 / Moolah markets quoting WTRX). Reversible: unwrap_trx converts WTRX back to TRX 1:1. Pre-checks: sufficient TRX balance for the wrap amount + gas. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -782,24 +856,26 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `unwrap_trx` -**Unwrap WTRX to TRX** +**Unwrap WTRX to TRX** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Unwrap WTRX (Wrapped TRX) back into native TRX at a 1:1 rate via the WTRX contract's withdraw(uint256). No approval is needed — you burn your own WTRX. Reverses wrap_trx (1:1). Pre-checks: sufficient WTRX balance and native TRX for gas. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `amount` | string (pattern /^\d+(\.\d+)?$/) | ✅ | | Amount of WTRX to unwrap into TRX (human-readable decimal string, e.g. '1' or '10.5') | | `network` | string | — | | Network. Default: mainnet | -## JustLend V2 — Vaults (6) +## JustLend V2 (Moolah) — Vaults (6) ### `get_moolah_vaults` -**Get V2 Vaults** +**Get Moolah Vaults** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: List all JustLend V2 vaults with APY, TVL, and underlying token. Vaults are ERC4626 — deposit tokens to earn auto-compounding yield allocated across V2 markets. +- **Description**: List all JustLend V2 (Moolah) vaults with APY, TVL, and underlying token. Vaults are ERC4626 — deposit tokens to earn auto-compounding yield allocated across Moolah markets. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -808,10 +884,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_vault` -**Get V2 Vault** +**Get Moolah Vault** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get detailed info for a single V2 vault: APY, TVL, allocation, and the user's share balance if address is provided. vaultSymbol is 'TRX', 'USDT', or 'USDD'. +- **Description**: Get detailed info for a single Moolah vault: APY, TVL, allocation, and the user's share balance if address is provided. vaultSymbol is 'TRX', 'USDT', or 'USDD'. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -821,10 +898,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `approve_moolah_vault` -**Approve V2 Vault** +**Approve Moolah Vault** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true -- **Description**: Approve TRC20 token spending for a V2 vault before depositing. Not needed for TRX vaults. Pass the EXACT amount you intend to deposit (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the vault contract spend the user's entire balance, present and future, until revoked (amount='0'). +- **Description**: Approve TRC20 token spending for a Moolah vault before depositing. Not needed for TRX vaults. Pass the EXACT amount you intend to deposit (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the vault contract spend the user's entire balance, present and future, until revoked (amount='0'). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -834,51 +912,55 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `moolah_vault_deposit` -**V2 Vault Deposit** +**Moolah Vault Deposit** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Deposit assets into a V2 ERC4626 vault to earn yield. For TRC20 vaults (USDT, USDD), call approve_moolah_vault first. Returns vault shares representing your deposit. +- **Description**: Deposit assets into a Moolah ERC4626 vault to earn yield. For TRC20 vaults (USDT, USDD), call approve_moolah_vault first. Returns vault shares representing your deposit. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `vaultSymbol` | string | ✅ | | Vault symbol: 'TRX', 'USDT', or 'USDD' | -| `amount` | string | ✅ | | Amount of underlying to deposit (e.g. '1000' for 1000 USDT) | +| `amount` | string (pattern /^\d+(\.\d+)?$/) | ✅ | | Amount of underlying to deposit (e.g. '1000' for 1000 USDT) | | `network` | string | — | | Network. Default: mainnet | ### `moolah_vault_withdraw` -**V2 Vault Withdraw** +**Moolah Vault Withdraw** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Withdraw underlying assets from a V2 vault by specifying the asset amount. Use amount='max' to withdraw everything. No approval needed. +- **Description**: Withdraw underlying assets from a Moolah vault by specifying the asset amount. Use amount='max' to withdraw everything. No approval needed. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `vaultSymbol` | string | ✅ | | Vault symbol: 'TRX', 'USDT', or 'USDD' | -| `amount` | string | ✅ | | Amount of underlying to withdraw, or 'max' for full withdrawal | +| `amount` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Amount of underlying to withdraw, or 'max' for full withdrawal | | `network` | string | — | | Network. Default: mainnet | ### `moolah_vault_redeem` -**V2 Vault Redeem** +**Moolah Vault Redeem** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Redeem vault shares to receive underlying assets. Use shares='max' to redeem all shares. No approval needed. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `vaultSymbol` | string | ✅ | | Vault symbol: 'TRX', 'USDT', or 'USDD' | -| `shares` | string | ✅ | | Number of shares to redeem, or 'max' for all shares | +| `shares` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Number of shares to redeem, or 'max' for all shares | | `network` | string | — | | Network. Default: mainnet | -## JustLend V2 — Markets (8) +## JustLend V2 (Moolah) — Markets (8) ### `get_moolah_markets` -**Get V2 Markets** +**Get Moolah Markets** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: List JustLend V2 markets with borrow/supply APY, LLTV, utilization, and liquidity. Markets are isolated — each has its own loan token, collateral token, oracle, and LLTV. +- **Description**: List JustLend V2 (Moolah) markets with borrow/supply APY, LLTV, utilization, and liquidity. Markets are isolated — each has its own loan token, collateral token, oracle, and LLTV. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -889,10 +971,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_market` -**Get V2 Market** +**Get Moolah Market** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get full details for a single V2 market by its marketId (bytes32 hex). Includes APY, LLTV, utilization, total supply/borrow, and vaults supplying to this market. Use get_moolah_markets to find marketIds. +- **Description**: Get full details for a single Moolah market by its marketId (bytes32 hex). Includes APY, LLTV, utilization, total supply/borrow, and vaults supplying to this market. Use get_moolah_markets to find marketIds. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -901,10 +984,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_user_position` -**Get V2 User Position** +**Get Moolah User Position** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get a user's position in a specific V2 market: collateral, borrow amount, lltv, and risk ratio. risk close to 1.0 means the position is near liquidation — consider repaying or adding collateral. +- **Description**: Get a user's position in a specific Moolah market: collateral, borrow amount, lltv, and risk ratio. risk close to 1.0 means the position is near liquidation — consider repaying or adding collateral. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -914,80 +998,86 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `approve_moolah_proxy` -**Approve V2 Proxy** +**Approve Moolah Proxy** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true -- **Description**: Approve TRC20 token spending for the V2 core contract before supplying collateral or repaying. Not needed for TRX operations. Pass the EXACT amount you intend to use (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the V2 proxy spend the user's entire balance, present and future, until revoked (amount='0'). +- **Description**: Approve TRC20 token spending for the Moolah core contract before supplying collateral or repaying. Not needed for TRX operations. Pass the EXACT amount you intend to use (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the Moolah proxy spend the user's entire balance, present and future, until revoked (amount='0'). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `tokenAddress` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | ✅ | | TRC20 contract address (Base58) | | `tokenSymbol` | string | ✅ | | Token symbol for display (e.g. 'USDT') | -| `tokenDecimals` | number | ✅ | | Token decimals (e.g. 6 for USDT) | +| `tokenDecimals` | number (min 0, max 38) | ✅ | | Token decimals (e.g. 6 for USDT). Integer in [0, 38]. | | `amount` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Exact amount to approve (e.g. '100'), or 'max' for unlimited (NOT recommended; user must opt in). | | `network` | string | — | | Network. Default: mainnet | ### `moolah_supply_collateral` -**V2 Supply Collateral** +**Moolah Supply Collateral** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Supply collateral into a V2 market to enable borrowing. For TRC20 collateral, call approve_moolah_proxy first. For TRX collateral, TRX is sent directly with no prior approval. +- **Description**: Supply collateral into a Moolah market to enable borrowing. For TRC20 collateral, call approve_moolah_proxy first. For TRX collateral, TRX is sent directly with no prior approval. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) — from get_moolah_markets | -| `amount` | string | ✅ | | Amount of collateral to supply (e.g. '10000' for 10000 TRX) | +| `amount` | string (pattern /^\d+(\.\d+)?$/) | ✅ | | Amount of collateral to supply (e.g. '10000' for 10000 TRX) | | `network` | string | — | | Network. Default: mainnet | ### `moolah_withdraw_collateral` -**V2 Withdraw Collateral** +**Moolah Withdraw Collateral** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Withdraw collateral from a V2 market. Use amount='max' to withdraw all collateral (only allowed when no active borrows). Withdrawing too much while borrowing will revert — check health factor first. +- **Description**: Withdraw collateral from a Moolah market. Use amount='max' to withdraw all collateral (only allowed when no active borrows). Withdrawing too much while borrowing will revert — check health factor first. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) | -| `amount` | string | ✅ | | Amount of collateral to withdraw, or 'max' for all (requires no active borrows) | +| `amount` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Amount of collateral to withdraw, or 'max' for all (requires no active borrows) | | `network` | string | — | | Network. Default: mainnet | ### `moolah_borrow` -**V2 Borrow** +**Moolah Borrow** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Flexible V2 borrow entry point. Provide collateralAmount only → supply collateral without borrowing. Provide borrowAmount only → borrow against existing collateral. Provide both → supply collateral then borrow in two sequential transactions. Collateral must cover the borrow at the market's LLTV or the borrow tx reverts. +- **Description**: Flexible Moolah borrow entry point. Provide collateralAmount only → supply collateral without borrowing. Provide borrowAmount only → borrow against existing collateral. Provide both → supply collateral then borrow in two sequential transactions. Collateral must cover the borrow at the market's LLTV or the borrow tx reverts. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) — from get_moolah_markets | -| `collateralAmount` | string | — | | Collateral to supply first (e.g. '10000' TRX). Omit to skip. | -| `borrowAmount` | string | — | | Loan token amount to borrow (e.g. '500' USDT). Omit to skip. | +| `collateralAmount` | string (pattern /^\d+(\.\d+)?$/) | — | | Collateral to supply first (e.g. '10000' TRX). Omit to skip. | +| `borrowAmount` | string (pattern /^\d+(\.\d+)?$/) | — | | Loan token amount to borrow (e.g. '500' USDT). Omit to skip. | | `network` | string | — | | Network. Default: mainnet | ### `moolah_repay` -**V2 Repay** +**Moolah Repay** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Repay a V2 market loan. Use amount='max' to repay the full outstanding borrow (uses shares math for exact settlement). For TRC20 loan tokens, call approve_moolah_proxy first. For TRX loans, TRX is sent directly. +- **Description**: Repay a Moolah market loan. Use amount='max' to repay the full outstanding borrow (uses shares math for exact settlement). For TRC20 loan tokens, call approve_moolah_proxy first. For TRX loans, TRX is sent directly. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) | -| `amount` | string | ✅ | | Loan amount to repay, or 'max' for full repayment | +| `amount` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Loan amount to repay, or 'max' for full repayment | | `network` | string | — | | Network. Default: mainnet | -## JustLend V2 — Liquidation (5) +## JustLend V2 (Moolah) — Liquidation (5) ### `get_moolah_pending_liquidations` -**Get Pending Liquidations** +**Get Pending Liquidations** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: List V2 positions eligible or approaching liquidation. riskLevel > 1.0 means the position is liquidatable right now. Use minRiskLevel=0.9 to find positions near the threshold. +- **Description**: List Moolah positions eligible or approaching liquidation. riskLevel > 1.0 means the position is liquidatable right now. Use minRiskLevel=0.9 to find positions near the threshold. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1001,24 +1091,26 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_liquidation_quote` -**Get Liquidation Quote** +**Get Liquidation Quote** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Estimate the loan token cost to liquidate a position. Provide either seizedAssets (collateral to take) OR repaidShares (borrow shares to repay), not both. Returns the exact loan token amount needed. Use this before calling moolah_liquidate. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) | -| `seizedAssets` | string | — | | Collateral amount to seize (raw units). Provide this OR repaidShares. | -| `repaidShares` | string | — | | Borrow shares to repay (raw units). Provide this OR seizedAssets. | +| `seizedAssets` | string (pattern /^\d+$/) | — | | Collateral amount to seize (raw units). Provide this OR repaidShares. | +| `repaidShares` | string (pattern /^\d+$/) | — | | Borrow shares to repay (raw units). Provide this OR seizedAssets. | | `network` | string | — | | Network. Default: mainnet | ### `get_moolah_liquidation_records` -**Get Liquidation Records** +**Get Liquidation Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Historical liquidation events on V2 — both bot-executed and public liquidations. +- **Description**: Historical liquidation events on Moolah — both bot-executed and public liquidations. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1031,42 +1123,45 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `moolah_liquidate` -**V2 Liquidate** +**Moolah Liquidate** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Liquidate an undercollateralized V2 position. You must hold the loan token and have approved it via approve_liquidator_token. Provide EITHER seizedAssets (collateral to seize) OR repaidShares (borrow shares to repay), not both. Use get_moolah_liquidation_quote first to estimate the required loan token amount. +- **Description**: Liquidate an undercollateralized Moolah position. You must hold the loan token and have approved it via approve_liquidator_token. Provide EITHER seizedAssets (collateral to seize) OR repaidShares (borrow shares to repay), not both. Use get_moolah_liquidation_quote first to estimate the required loan token amount. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex) | | `borrower` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | ✅ | | Address of the borrower to liquidate (Base58) | -| `seizedAssets` | string | — | | Collateral units to seize (raw). Provide this OR repaidShares. | -| `repaidShares` | string | — | | Borrow shares to repay (raw). Provide this OR seizedAssets. | +| `seizedAssets` | string (pattern /^\d+$/) | — | | Collateral units to seize (raw). Provide this OR repaidShares. | +| `repaidShares` | string (pattern /^\d+$/) | — | | Borrow shares to repay (raw). Provide this OR seizedAssets. | | `network` | string | — | | Network. Default: mainnet | ### `approve_liquidator_token` -**Approve Liquidator Token** +**Approve Liquidator Token** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: true -- **Description**: Approve loan token spending for the V2 public liquidator contract. Required before calling moolah_liquidate. Pass the EXACT amount you intend to use (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the liquidator contract spend the user's entire balance, present and future, until revoked (amount='0'). +- **Description**: Approve loan token spending for the Moolah public liquidator contract. Required before calling moolah_liquidate. Pass the EXACT amount you intend to use (recommended). Pass amount='max' for unlimited approval ONLY when the user explicitly opts in — it lets the liquidator contract spend the user's entire balance, present and future, until revoked (amount='0'). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `tokenAddress` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | ✅ | | Loan token contract address (Base58) | | `tokenSymbol` | string | ✅ | | Token symbol for display (e.g. 'USDT') | -| `tokenDecimals` | number | ✅ | | Token decimals (e.g. 6 for USDT) | +| `tokenDecimals` | number (min 0, max 38) | ✅ | | Token decimals (e.g. 6 for USDT). Integer in [0, 38]. | | `amount` | string (pattern /^(\d+(\.\d+)?|max)$/) | ✅ | | Exact amount to approve (e.g. '100'), or 'max' for unlimited (NOT recommended; user must opt in). | | `network` | string | — | | Network. Default: mainnet | -## JustLend V2 — Dashboard & History (6) +## JustLend V2 (Moolah) — Dashboard & History (6) ### `get_moolah_dashboard` -**Get V2 Dashboard** +**Get Moolah Dashboard** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: JustLend V2 protocol overview: top vaults (APY, TVL) and top markets (borrow/supply rates). If address is provided, also includes the user's aggregated V2 position (total supply, borrow, health factor). +- **Description**: JustLend V2 (Moolah) protocol overview: top vaults (APY, TVL) and top markets (borrow/supply rates). If address is provided, also includes the user's aggregated V2 position (total supply, borrow, health factor). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1077,10 +1172,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_history` -**Get V2 History** +**Get Moolah History** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's JustLend V2 position history (net worth, supply, borrow over time) and recent transaction records (supply, borrow, repay, etc.). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1090,10 +1186,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_records` -**Get V2 Records** +**Get Moolah Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get a user's paginated V2 transaction history — supply, withdraw, borrow, repay, liquidate events. Distinct from get_moolah_history (which returns position curves + a small recent-txs preview) — this one is the full paginated record list. Works on both mainnet and nile. +- **Description**: Get a user's paginated V2 (Moolah) transaction history — supply, withdraw, borrow, repay, liquidate events. Distinct from get_moolah_history (which returns position curves + a small recent-txs preview) — this one is the full paginated record list. Works on both mainnet and nile. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1104,10 +1201,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_vault_history` -**Get V2 Vault History** +**Get Moolah Vault History** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Time series of a V2 vault's APY, TVL, and supply mining data. Returns currentSupplyUsd, supplyBaseApy, supplyMiningApy, and a historyRecords array. Use vaultAddress from get_moolah_vaults or chains.ts vault map. +- **Description**: Time series of a V2 Moolah vault's APY, TVL, and supply mining data. Returns currentSupplyUsd, supplyBaseApy, supplyMiningApy, and a historyRecords array. Use vaultAddress from get_moolah_vaults or chains.ts vault map. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1116,38 +1214,41 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `estimate_moolah_energy` -**Estimate V2 Energy** +**Estimate Moolah Energy** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Estimate energy, bandwidth, and TRX cost for a JustLend V2 write operation BEFORE executing it. Returns historical typical values (on-chain simulation for V2's tuple-args ops is not yet wired). Set isTRX=true when the underlying / loan / collateral token is native TRX (TrxProviderProxy route). Covers: vault_deposit, vault_withdraw, vault_redeem, approve_vault, supply_collateral, withdraw_collateral, borrow, repay, approve_proxy, liquidate, approve_liquidator. +- **Description**: Estimate energy, bandwidth, and TRX cost for a JustLend V2 (Moolah) write operation BEFORE executing it. Returns historical typical values (on-chain simulation for Moolah's tuple-args ops is not yet wired). Set isTRX=true when the underlying / loan / collateral token is native TRX (TrxProviderProxy route). Covers: vault_deposit, vault_withdraw, vault_redeem, approve_vault, supply_collateral, withdraw_collateral, borrow, repay, approve_proxy, liquidate, approve_liquidator. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| -| `operation` | enum(vault_deposit | vault_withdraw | vault_redeem | approve_vault | supply_collateral | withdraw_collateral | borrow | repay | approve_proxy | liquidate | approve_liquidator) | ✅ | | V2 operation to estimate | +| `operation` | enum(vault_deposit | vault_withdraw | vault_redeem | approve_vault | supply_collateral | withdraw_collateral | borrow | repay | approve_proxy | liquidate | approve_liquidator) | ✅ | | Moolah operation to estimate | | `isTRX` | boolean | — | | Whether the route uses native TRX (via TrxProviderProxy). Default: false | | `address` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | — | | Owner address for resource-sufficiency check. Default: configured wallet | | `network` | string | — | | Network. Default: mainnet | ### `get_moolah_market_history` -**Get V2 Market History** +**Get Moolah Market History** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Time series of a V2 market's borrow/supply APY, utilization, and totals. Returns current totalBorrow/totalCollateral + borrowApy/supplyApy + list[] of historical points. Use marketId (bytes32 hex) from get_moolah_markets. +- **Description**: Time series of a V2 Moolah market's borrow/supply APY, utilization, and totals. Returns current totalBorrow/totalCollateral + borrowApy/supplyApy + list[] of historical points. Use marketId (bytes32 hex) from get_moolah_markets. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `marketId` | string | ✅ | | Market ID (bytes32 hex, e.g. '0xabc...') | | `network` | string | — | | Network. Default: mainnet | -## JustLend V2 — Mining, Rewards & Estimator (5) +## JustLend V2 (Moolah) — Mining, Rewards & Estimator (5) ### `get_moolah_vault_mining_apy` -**Get V2 Vault Mining APY** +**Get Moolah Vault Mining APY** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get V2 mining APY for a single V2 vault. Returns the USDD / TRX APY split and total (encoded as a fraction, e.g. 0.123 = 12.3%). enabled=true means the vault is active in mining and qualifies for the fire-icon UI hint. +- **Description**: Get V2 mining APY for a single Moolah vault. Returns the USDD / TRX APY split and total (encoded as a fraction, e.g. 0.123 = 12.3%). enabled=true means the vault is active in mining and qualifies for the fire-icon UI hint. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1156,10 +1257,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_mining_resolver` -**Get V2 Mining Resolver** +**Get Moolah Mining Resolver** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Map every V2 vault with active mining to its USDD / TRX APY split. Used by the dashboard to prefetch fire-icon eligibility in one round-trip. Vaults with zero mining APY are excluded from the response. +- **Description**: Map every Moolah vault with active mining to its USDD / TRX APY split. Used by the dashboard to prefetch fire-icon eligibility in one round-trip. Vaults with zero mining APY are excluded from the response. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1167,10 +1269,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_mining_accruing` -**Get V2 Mining Accruing** +**Get Moolah Mining Accruing** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's accruing & settling V2 mining rewards across vaults. accruingUsd = current round still emitting; settlingUsd = previous round in the brief settlement window (miningStatus=2, currRewardStatus=1) — excluded otherwise so it doesn't double-count with already-published merkle airdrops. globalSettlementStatus=true means the backend reports any token in flux; treat per-token amounts as provisional. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1179,10 +1282,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_moolah_pending_mining_periods` -**Get V2 Pending Mining Periods** +**Get Moolah Pending Mining Periods** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's claimable V2 mining airdrop rounds (already settled and merkle-published). Each period includes merkleIndex, index, per-token amounts (raw + decimal-shifted), the merkle proof, and a USD total. Feed a periodKey directly into claim_moolah_mining_period to submit the on-chain multiClaim. Set includeClaimed=true to also return rounds the indexer marks as already claimed (default false matches the rewards card behaviour). +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1192,17 +1296,18 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `claim_moolah_mining_period` -**Claim V2 Mining Period** +**Claim Moolah Mining Period** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true -- **Description**: Claim a single V2 mining airdrop round via multiClaim() on the V2 merkle distributor. Pass periodKey from get_moolah_pending_mining_periods (preferred) or supply merkleIndex / index / amounts / proof directly. Pre-checks isClaimed() and merkleRoots() on-chain so the wallet does not pay gas for a guaranteed-revert tx. Mainnet currently errors with 'distributor not configured' until the V2 contract ships — nile testnet works. +- **Description**: Claim a single V2 mining airdrop round via multiClaim() on the Moolah merkle distributor. Pass periodKey from get_moolah_pending_mining_periods (preferred) or supply merkleIndex / index / amounts / proof directly. Pre-checks isClaimed() and merkleRoots() on-chain so the wallet does not pay gas for a guaranteed-revert tx. Mainnet currently errors with 'distributor not configured' until the V2 contract ships — nile testnet works. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `periodKey` | string | — | | Round key from get_moolah_pending_mining_periods (preferred) | | `merkleIndex` | union | — | | Override: merkle tree index | | `index` | union | — | | Override: leaf index inside the tree | -| `amounts` | union[] | — | | Override: token amounts in raw units, slot-aligned with the tree's tokenAddress[] | +| `amounts` | string[] | — | | Override: token amounts in raw units (integer strings), slot-aligned with the tree's tokenAddress[] | | `proof` | string[] | — | | Override: merkle proof (bytes32[]) | | `address` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | — | | Owner address used to refetch the airdrop entry when periodKey is supplied. Default: signing wallet | | `network` | string | — | | Network. Default: mainnet | @@ -1211,10 +1316,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_lending_records` -**Get V1 Lending Records** +**Get V1 Lending Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's V1 JustLend transaction history: supply, withdraw, borrow, repay, and collateral enable/disable. Paginated. Each record includes actionType (1-11), actionName (human-readable), token, amount, USD value, and txId. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1225,10 +1331,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_strx_records` -**Get sTRX Records** +**Get sTRX Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's sTRX staking history: stake, unstake, withdraw (after unbonding), and sTRX transfers. Each record has opType (1-6) and a human-readable opName. Paginated. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1239,10 +1346,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_vote_records` -**Get Vote Records** +**Get Vote Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's governance voting history: get_vote (JST → WJST deposits), votes cast for/against proposals, vote withdrawals, and JST conversions back. Each record has opType (1-6), opName, amount, and proposalId (for votes and withdrawals). Use get_user_vote_status for real-time current voting power. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1253,10 +1361,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_energy_rental_records` -**Get Energy Rental Records** +**Get Energy Rental Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Get a user's JustLend energy-rental history: rent, extend, rent_more, end, recycle actions. Distinct from get_user_energy_rental_orders which returns current active on-chain orders — this one returns the full historical action log. Paginated. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1267,10 +1376,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_claimable_rewards` -**Get Claimable Rewards** +**Get Claimable Rewards** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true - **Description**: Scan all JustLend V1 merkle airdrop distributors for a user's unclaimed rewards. Returns a map keyed by round; each entry includes the merkleIndex, index, amount(s), token symbol/address, and proof. Feed any returned key into claim_v1_mining_period to submit the on-chain multiClaim. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| @@ -1279,17 +1389,18 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `claim_v1_mining_period` -**Claim V1 Mining Period** +**Claim V1 Mining Period** - **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing - **annotations**: idempotent: false · openWorld: true - **Description**: Claim a single V1 mining airdrop round via multiClaim() on the appropriate merkle distributor. Pass `key` from get_claimable_rewards (preferred) or supply merkleIndex / index / amount / proof directly. Routing matches the front-app: amount[] → multi-merkle distributor (multi-token leaf); single + USDD → USDDNEW distributor; single + other → main distributor. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| | `key` | string | — | | Round key from get_claimable_rewards (preferred) | | `merkleIndex` | union | — | | Override: merkle tree index | | `index` | union | — | | Override: leaf index inside the tree | -| `amount` | union | — | | Override: token amount(s) in raw units; pass an array for multi-token leaves | +| `amount` | union | — | | Override: token amount(s) in raw units (integer strings); pass an array for multi-token leaves | | `proof` | string[] | — | | Override: merkle proof (bytes32[]) | | `tokenAddress` | union | — | | Override: token address(es) used for routing when the entry is single-token | | `tokenSymbol` | union | — | | Override: token symbol(s); useful when tokenAddress is missing | @@ -1300,10 +1411,11 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ ### `get_liquidation_records` -**Get V1 Liquidation Records** +**Get V1 Liquidation Records** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get a user's V1 JustLend liquidation history — both positions the user liquidated and positions where the user was liquidated. Distinct from get_moolah_liquidation_records which covers V2 liquidations. Paginated. Mainnet-only. +- **Description**: Get a user's V1 JustLend liquidation history — both positions the user liquidated and positions where the user was liquidated. Distinct from get_moolah_liquidation_records which covers V2 Moolah liquidations. Paginated. Mainnet-only. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | |-------|------|:--------:|---------|-------------| diff --git a/docs/documents/aidocs/quickstart.md b/docs/documents/aidocs/quickstart.md index 7a06ea0..be31ee9 100644 --- a/docs/documents/aidocs/quickstart.md +++ b/docs/documents/aidocs/quickstart.md @@ -35,7 +35,7 @@ JustLend DAO is a decentralized lending protocol on TRON based on the Compound V ## Minimal decision tree 1. **Question only needs public data**: use OpenAPI or read-only MCP tools. -2. **Question needs portfolio analysis for an address**: use MCP `get_account_summary` or OpenAPI `/lend/account?address={address}`. +2. **Question needs portfolio analysis for an address**: use MCP `get_account_summary` or OpenAPI `/lend/account?addresses={address}`. 3. **Question asks to execute an action**: use MCP only, read [`mcp_safety.md`](mcp_safety.md), require human confirmation, and never ask for private keys in chat. 4. **Question asks for contract addresses**: use `contracts.json` and specify network. 5. **Question asks for terms such as collateral factor, exchange rate, or mantissa**: use [`glossary.md`](glossary.md) and the full glossary page. diff --git a/docs/documents/aidocs/source_of_truth.md b/docs/documents/aidocs/source_of_truth.md index 0fd76d2..3680ec1 100644 --- a/docs/documents/aidocs/source_of_truth.md +++ b/docs/documents/aidocs/source_of_truth.md @@ -1,6 +1,6 @@ --- title: JustLend Source of Truth for AI Agents -description: How agents should choose between JustLend OpenAPI, MCP tools, contracts.json, ABI JSON files, llms.txt, and human documentation. +description: How agents should choose between JustLend OpenAPI, MCP tools, CLI, V2 Utils, contracts.json, ABI JSON files, llms.txt, and human documentation. tags: - justlend - source-of-truth @@ -26,16 +26,26 @@ Use this page to decide which JustLend documentation or runtime source an AI age - Package: `@justlend/mcp-server-justlend` - Best for: account analysis, market queries, transaction pre-flight, supply, borrow, repay, withdraw, sTRX staking, energy rental, governance voting, transfers, and general TRON utilities. -3. **Contract directory** — use for deployed addresses. +3. **JustLend CLI** — use for deterministic terminal and CI automation. + - Guide: [`CLI and V2 SDK`](../../ai_support/cli_and_sdk.md) + - Repository: [`justlend/justlend-cli`](https://github.com/justlend/justlend-cli) + - Best for: versioned JSON envelopes, process exit codes, dry-run simulation, scripted reads, and intentionally confirmed writes. + +4. **JustLend V2 Utils** — use for embedded browser or Node.js integrations. + - Guide: [`CLI and V2 SDK`](../../ai_support/cli_and_sdk.md) + - Repository: [`justlend/justlend-utils-v2`](https://github.com/justlend/justlend-utils-v2) + - Best for: application-owned V2 vault, market, liquidation, reward, WTRX, and energy workflows using an explicitly injected `TronWeb` instance. + +5. **Contract directory** — use for deployed addresses. - File: [`/developers/contracts.json`](../../developers/contracts.json) - Schema: [`/developers/contracts.schema.json`](../../developers/contracts.schema.json) - Best for: Mainnet/Nile contract addresses, Base58/EVM/TRON-hex formats, active vs. legacy market status. -4. **JSON ABI files** — use for contract calls and event decoding. +6. **JSON ABI files** — use for contract calls and event decoding. - Directory: [`/developers/abis/`](../../developers/abis/jtoken.json) - Best for: function signatures, event topics, jToken calls, Comptroller, PriceOracle, governance, sTRX, and Energy Rental contracts. -5. **Human documentation** — use for explanations and risk context. +7. **Human documentation** — use for explanations and risk context. - Examples: [Supply](../../getting_started/concepts/supply.md), [Borrow](../../getting_started/concepts/borrow.md), [Common Pitfalls](../../developers/common_pitfalls.md), [Glossary](../../resources/glossary.md) - Best for: conceptual explanations, integration pitfalls, examples, and user education. @@ -61,7 +71,9 @@ The public HTTP API returns decimal quantities as **JSON strings** (mostly de-sc | “What markets does JustLend support?” | MCP `get_supported_markets` or OpenAPI `/lend/jtoken` | `contracts.json` | | “What is the APY / TVL / utilization?” | MCP `get_market_data` / `get_all_markets` | OpenAPI `/lend/jtoken` | | “What is this address's health factor?” | MCP `get_account_summary` | OpenAPI `/lend/account?addresses={address}` | -| “Supply / borrow / repay / withdraw for me” | MCP guided prompt + tool | Human docs for explanation only | +| “Supply / borrow / repay / withdraw for me” | MCP guided prompt + tool | CLI dry-run, then explicit confirmation | +| “Automate this from a shell or CI job” | CLI `--json` + exit code | MCP tool call | +| “Embed V2 in my app” | V2 Utils + injected `TronWeb` | ABI JSON + application-owned integration | | “What contract address should I use?” | `contracts.json` | MCP `get_supported_markets` / `chains.ts` | | “How do I decode events?” | ABI JSON files | developer pages | | “Is a transaction safe?” | MCP pre-flight tools + safety docs | human review | @@ -82,4 +94,6 @@ When answering an integration question, include: - “查市场 / APY / TVL / 利用率” → MCP `get_market_data` / `get_all_markets` or OpenAPI [`justlend_apis.yaml`](../../developers/apis/justlend_apis.yaml). - “查我的仓位 / 健康度 / 清算风险” → MCP `get_account_summary` and [Account Positions](account_position.md). - “存款 / 借款 / 还款 / 赎回” → MCP write tools plus [MCP Safety Policy](mcp_safety.md). +- “命令行 / CI 自动化” → [JustLend CLI](../../ai_support/cli_and_sdk.md#cli-deterministic-terminal-automation) with `--json`, exit-code checks, and dry-run first. +- “前端 / Node.js 集成 V2” → [JustLend V2 Utils](../../ai_support/cli_and_sdk.md#v2-utils-embedded-application-integration) with an explicitly injected `TronWeb` instance. - “合约地址 / ABI / 事件解析” → [`contracts.json`](../../developers/contracts.json) and [`developers/abis/`](../../developers/abis/jtoken.json). diff --git a/docs/getting_started/overview.md b/docs/getting_started/overview.md index c900d45..a302e04 100644 --- a/docs/getting_started/overview.md +++ b/docs/getting_started/overview.md @@ -6,7 +6,7 @@ description: JustLend DAO is the largest lending protocol on TRON (Compound V2 a # Overview !!! info "Documentation freshness" - **Protocol:** JustLend DAO · **Network:** TRON Mainnet · **Markets:** 17 active + 6 legacy = 23 jToken markets ([authoritative list](../developers/apis.md#2-jtoken-address-reference)). Per-page `last-updated` is rendered in the footer (sourced from git commit history). For changelog see [CHANGELOG.md](https://github.com/justlend/justlend-docs/blob/main/CHANGELOG.md); for the machine-readable snapshot see [`/llms-full.txt`](../llms-full.txt) (header includes `last_generated` and `docs_commit`). + **Protocol:** JustLend DAO · **Network:** TRON Mainnet · **Markets:** 18 active + 6 legacy = 24 jToken markets ([authoritative list](../developers/apis.md#2-jtoken-address-reference)). Per-page `last-updated` is rendered in the footer (sourced from git commit history). For changelog see [CHANGELOG.md](https://github.com/justlend/justlend-docs/blob/main/CHANGELOG.md); for the machine-readable snapshot see [`/llms-full.txt`](../llms-full.txt) (header includes `last_generated` and `docs_commit`). JustLend DAO is a cutting-edge money market protocol powered by TRON, designed to create fund pools with interest rates determined by an algorithm based on the supply and demand of TRON assets. The protocol involves two main roles: suppliers and borrowers, who engage directly with the platform to earn or pay floating interest rates. diff --git a/docs/index.md b/docs/index.md index e5b501c..0111f2f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ description: Official documentation for JustLend DAO — the largest lending pro **JustLend DAO** is the largest lending protocol on TRON, built on the Compound V2 architecture. The protocol covers four integrated sub-protocols: -- **SBM (Supply & Borrow Market)** — supply TRX or TRC20 assets to earn interest; over-collateralize one asset to borrow another. **17 active + 6 legacy = 23 jToken markets** on TRON Mainnet ([authoritative list](developers/apis.md#2-jtoken-address-reference)). +- **SBM (Supply & Borrow Market)** — supply TRX or TRC20 assets to earn interest; over-collateralize one asset to borrow another. **18 active + 6 legacy = 24 jToken markets** on TRON Mainnet ([authoritative list](developers/apis.md#2-jtoken-address-reference)). - **sTRX** — one-click TRX liquid staking under Stake 2.0. Deposit TRX, receive sTRX (TRC20), earn voting + energy-rental yield. - **Energy Rental** — rent TRON Energy at 50–80% below the cost of burning TRX. - **Governance** — JST holders propose, vote, and execute on-chain via `GovernorBravo` + `Timelock`. @@ -21,7 +21,7 @@ description: Official documentation for JustLend DAO — the largest lending pro - **Users:** [Overview](getting_started/overview.md) · [Supply](getting_started/concepts/supply.md) · [Borrow](getting_started/concepts/borrow.md) · [Liquidations](getting_started/concepts/liquidations.md) · [Risks](getting_started/concepts/risks.md) - **Developers:** [Contracts Overview](developers/contracts_overview.md) · [SBM reference](developers/supply_and_borrow_market/sbm.md) · [Deployed Contracts](developers/deployed_contracts.md) · [APIs](developers/apis.md) -- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (98 tools)](ai_support/mcp_server.md) · [Skills (9 read-only tools, GitHub install)](ai_support/justlend_skills.md) +- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (98 tools)](ai_support/mcp_server.md) · [Skills (9 read-only tools, GitHub install)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) - **Governance:** [JIPs](governance/jips.md) · [Tokenomics (JST)](governance/tokenomics.md) · [Forum](https://forum.justlend.org) ## External @@ -29,4 +29,4 @@ description: Official documentation for JustLend DAO — the largest lending pro - **App:** - **Whitepaper (PDF):** - **Audits:** [Supply & Borrow](https://justlend.org/docs/justlend_audit_en.pdf) · [Staked TRX](https://justlend.org/docs/justlend_strx_audit_en.pdf) -- **GitHub:** [protocol](https://github.com/justlend/justlend-protocol) · [MCP server](https://github.com/justlend/mcp-server-justlend) · [Skills](https://github.com/justlend/justlend-skills) · [these docs](https://github.com/justlend/justlend-docs) +- **GitHub:** [protocol](https://github.com/justlend/justlend-protocol) · [MCP server](https://github.com/justlend/mcp-server-justlend) · [Skills](https://github.com/justlend/justlend-skills) · [CLI](https://github.com/justlend/justlend-cli) · [V2 Utils](https://github.com/justlend/justlend-utils-v2) · [these docs](https://github.com/justlend/justlend-docs) diff --git a/docs/llms-full.txt b/docs/llms-full.txt index ed428f2..ec9157b 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -9,11 +9,13 @@ | `last_generated` | **{{LAST_GENERATED}}** (ISO 8601, UTC date — substituted at build time) | | `docs_commit` | [`{{DOCS_COMMIT_SHORT}}`](https://github.com/justlend/justlend-docs/commit/{{DOCS_COMMIT}}) (the commit SHA this snapshot was built from — substituted at build time) | | `contracts_json_source` | [`/developers/contracts.json`](https://docs.justlend.org/developers/contracts.json) — see its `_meta.last_generated` for the address-data snapshot date | -| `mcp_server_version` | `@justlend/mcp-server-justlend` **v1.1.2** (sync date 2026-07-15) | +| `mcp_server_version` | `@justlend/mcp-server-justlend` **v1.1.3** (sync date 2026-08-19) | +| `skills_version` | `@justlend/justlend-skills` **v1.1.1** (GitHub distribution; not on npm) | +| `cli_version` | `justlend-cli` **v1.0.1** (GitHub source distribution; not on npm) | | `changelog` | [`CHANGELOG.md`](https://github.com/justlend/justlend-docs/blob/main/CHANGELOG.md) | | `regenerate` | This file is updated each time the docs change materially. If you fetched it more than ~30 days ago, refresh it before answering address / market / version questions. | -This document covers: protocol overview, core concepts (supply / borrow / withdraw / repay / liquidation / risks / sTRX / energy rental), governance, developer contract reference, deployed addresses (TRON mainnet + Nile), the HTTP API surface, and the AI integration story (Skills + MCP). For exhaustive function signatures, field-by-field response schemas, JSON ABIs, and machine-readable address formats, see the individual reference pages and the OpenAPI YAML. +This document covers: protocol overview, core concepts (supply / borrow / withdraw / repay / liquidation / risks / sTRX / energy rental), governance, developer contract reference, deployed addresses (TRON mainnet + Nile), the HTTP API surface, and the AI integration story (Skills + MCP + CLI + V2 Utils). For exhaustive function signatures, field-by-field response schemas, JSON ABIs, and machine-readable address formats, see the individual reference pages and the OpenAPI YAML. --- @@ -430,11 +432,11 @@ ABIs at `/developers/abis/` carry the canonical event signatures — derive `top ## 7. AI Agent Integration -JustLend ships two distinct AI Agent packages: +JustLend ships four complementary agent and developer integration surfaces: ### 7.1 JustLend Skills — GitHub distribution -Read-only skills package. Repo: . +Read-only skills package, version **v1.1.1**. Repo: . Install by cloning that repository and running `bash install.sh`. The local package identifier `@justlend/justlend-skills` is **not published to npm**; do not use `npm install @justlend/justlend-skills`. An `npm install` run inside the clone only installs the project's dependencies. @@ -442,6 +444,8 @@ Install by cloning that repository and running `bash install.sh`. The local pack - Also runs standalone as a **CLI** (`node scripts/justlend_api.mjs markets|dashboard|account ...`). - Requires `TRONGRID_API_KEY` (free at ). Supports `NETWORK=mainnet|nile`. - **No wallet, no signing, no write operations** — strictly read-only by design. +- All 9 tools declare a versioned `outputSchema`. Successes expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent` while preserving raw JSON text; failures expose `{ schemaVersion, tool, error, errorCode, retryable, hint }`. Auto-retry only `rate_limit` / `transient` errors. +- `get_supported_markets` lists only 8 bundled balance/allowance shortcuts. Use `get_all_markets`, the live API, or `contracts.json` for the canonical **24-market (18 active + 6 legacy)** roster. Skill modules: @@ -457,7 +461,7 @@ Built-in MCP tools (all read-only): `get_all_markets`, `get_dashboard`, `get_sup ### 7.2 Full MCP Server — `@justlend/mcp-server-justlend` -Read + write MCP server, **98 tools**, version **v1.1.2**. Repo: . Covers **JustLend V1 and V2** — the V1 tools plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. A machine-readable tool catalog ([`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md)) lists every tool's input schema and side-effect class for offline agent routing. +Read + write MCP server, **98 tools**, version **v1.1.3**. Repo: . Covers **JustLend V1 and V2** — the V1 tools plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. Every tool declares a common success `outputSchema`; successful calls preserve text content and add `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`. The generated [`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) lists input/output contracts and side-effect classes for offline routing. Capability domains: @@ -483,13 +487,35 @@ Guided prompts ship with the server (14 total): `getting_started`, `supply_asset **Machine-readable ABIs**: JSON files are available under . The upstream MCP server keeps the source TypeScript definitions in [`src/core/abis.ts`](https://github.com/justlend/mcp-server-justlend/blob/main/src/core/abis.ts); per-network contract addresses are mirrored in `/developers/contracts.json` from [`src/core/chains.ts`](https://github.com/justlend/mcp-server-justlend/blob/main/src/core/chains.ts). -### 7.3 Recommended source-of-truth priority for AI agents +### 7.3 JustLend CLI — deterministic terminal automation -1. **OpenAPI spec + the `https://openapi.just.network` HTTP API** — typed, versioned, machine-readable. -2. **MCP server tools** — structured, schema-defined, side-effects clearly marked. -3. **Rendered HTML docs** — for concept understanding; do not rely on free-text fields for precise numbers (APYs, TVL, tool counts, addresses) without cross-checking against (1) or (2). +Source-installable CLI, version **v1.0.1**. Repo: . It is not currently published to npm: clone the official repository, run `npm ci && npm run build`, then `npm link`. -### 7.4 Precision and units (AI must respect) +- 31 top-level command groups cover V1/V2 reads and writes, staking, energy rental, governance, rewards, history, portfolio, and simulation. +- Use `--json` and branch on the process exit code for agents and CI. Success is `{ schemaVersion: "1.0.0", success: true, data }`; failure is `{ schemaVersion, success: false, error, code, retryable, hint? }`, including parser/usage failures. Validate with `schemas/output-v1.schema.json`; never scrape human tables. +- Run `--dry-run --dry-run-owner
` before any write; dry-run does not sign or broadcast. +- `--no-broadcast` signs without sending. Mainnet broadcasts require explicit user intent; never add `--yes` automatically. +- Prefer Nile for integration tests. Full guidance: . + +### 7.4 JustLend V2 Utils — embedded browser / Node.js SDK + +Source-installable utility library, version **v1.0.0**. Repo: . Install with `npm install github:justlend/justlend-utils-v2`; it is not currently published to npm. + +- Covers V2 vaults, lending markets, liquidations, mining rewards, native TRX/WTRX handling, and energy purchase workflows. +- Inject a ready `TronWeb` instance and set the sender explicitly in Node.js. +- Preserve amount values as strings or `BigNumber`; never use JavaScript `number` for token quantities. +- Many helpers sign or broadcast. Resolve addresses from live/canonical sources, use Nile first, and require human confirmation before Mainnet writes. +- Never expose private keys or signed transaction payloads in prompts, logs, or agent output. + +### 7.5 Recommended source-of-truth priority for AI agents + +1. **OpenAPI spec + the `https://openapi.just.network` HTTP API** — typed, versioned, machine-readable public data. +2. **MCP server tools** — schema-discoverable agent workflows with side effects marked. +3. **JustLend CLI** — deterministic terminal/CI automation through versioned JSON and exit codes. +4. **JustLend V2 Utils** — embedded browser/Node.js integrations owned by the application. +5. **Rendered HTML docs** — concept understanding; cross-check dynamic values and exact machine contracts against sources 1–4. + +### 7.6 Precision and units (AI must respect) - **jToken balances**: scaled by `1e8` (8 decimals). - **Underlying TRC20 amounts**: each token's own decimals — TRX = 6, USDT = 6, USDC = 6, USDD = 18, BTC/WBTC = 8, ETH = 18, etc. Always call `decimals()` on the underlying before constructing a `mint` / `borrow` / `repayBorrow` amount. @@ -509,6 +535,8 @@ Guided prompts ship with the server (14 total): `getting_started`, `supply_asset - **GitHub (protocol)**: - **GitHub (Skills)**: - **GitHub (MCP server)**: +- **GitHub (CLI)**: +- **GitHub (V2 Utils)**: - **Terms of Service**: - **Privacy Policy**: @@ -521,4 +549,4 @@ Guided prompts ship with the server (14 total): `getting_started`, `supply_asset - The public OpenAPI service is unauthenticated and may throttle abusive clients. Keep `pageSize <= 1000`, cache stable market metadata, and retry `429` / transient `5xx` with exponential backoff and jitter. - Where this document gives APYs, TVL, or other dynamic numbers as examples (notably in the Energy Rental cost section), they reflect the moment the underlying example transactions were recorded and are not current. - Liquidation rules summarized here describe the contract-level mechanism. The official liquidation tool also enforces additional UX-level disclaimers — see . -- "Read-only" guarantees for the HTTP API and the Skills package are enforced by code paths (no signing keys), not just policy. The full MCP server is the only component that can submit transactions, and only through the encrypted agent-wallet. +- "Read-only" guarantees for the HTTP API and the bundled Skills MCP server are enforced by code paths (no signing keys), not just policy. The full MCP server, CLI, and V2 Utils can submit transactions through their configured wallet/signer paths; inspect side effects, simulate first, and require explicit human intent before signing or broadcasting. diff --git a/docs/llms.txt b/docs/llms.txt index 2c08707..478e0c5 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -9,6 +9,8 @@ - [OpenAPI 3.1 specification](https://docs.justlend.org/developers/apis/justlend_apis.yaml): Machine-readable contract for the public read-only HTTP API at `https://openapi.just.network`. Importable into Swagger UI, Postman, or any LLM tool. - [API reference (rendered)](https://docs.justlend.org/developers/apis): Swagger UI rendering of the OpenAPI spec. - [sitemap.xml](https://docs.justlend.org/sitemap.xml): Full list of indexable documentation pages. +- [JustLend CLI](https://github.com/justlend/justlend-cli) (v1.0.1): Source-installable terminal automation with versioned JSON output, stable exit codes, dry-run simulation, and explicit write safeguards. +- [JustLend V2 Utils](https://github.com/justlend/justlend-utils-v2) (v1.0.0): Source-installable browser/Node.js utility library for embedded V2 contract integrations; requires explicit `TronWeb` injection. ## Getting started @@ -63,9 +65,10 @@ ## AI Agent integration - [AI / LLMs](https://docs.justlend.org/ai_support/ai_llms): Human-readable directory for `llms.txt`, `llms-full.txt`, OpenAPI, contract JSON, and ABI JSON endpoints. -- [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills): GitHub-distributed read-only skills project + lightweight MCP server (**9 query tools**). Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. -- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.2, **98 tools**): Full read/write MCP server for JustLend V1 (supply, borrow, repay, withdraw, sTRX staking, energy rental, governance voting, mining rewards, transfers) and V2 vaults/markets/liquidation, plus historical records and general TRON utilities. Source: . -- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 98 tools with input schemas (param/type/required/default), side-effect class (read-only vs on-chain write/destructive) and HITL guidance. Generated from source, so it never drifts from the tool definitions. +- [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills) (v1.1.1): GitHub-distributed read-only skills project + lightweight MCP server (**9 query tools**) with versioned `outputSchema`, `structuredContent`, and machine-readable retry errors. Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. +- [CLI and V2 SDK integration guide](https://docs.justlend.org/ai_support/cli_and_sdk): Choose terminal/CI automation or embedded application integration; includes installation, version, output contract, signing, and broadcast safety rules. +- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **98 tools**): Full read/write MCP server for JustLend V1 and V2. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Source: . +- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 98 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. - [MCP source ABIs and network config](https://github.com/justlend/mcp-server-justlend): Upstream TypeScript definitions used to generate the docs JSON ABI and address files. ## API endpoints (read-only HTTP API) @@ -74,7 +77,7 @@ Base URL: `https://openapi.just.network`. Schema in [justlend_apis.yaml](https:/ - `GET /lend/jtoken` — All jToken markets with supply/borrow APY, mining rewards, TVL (aggregate for protocol-level totals). - `GET /lend/jtoken?address={jToken}` — Single jToken market details. -- `GET /lend/account?address={address}` — Account SBM positions, health factor, rewards (paginated). +- `GET /lend/account?addresses={address}` — Account SBM positions, health factor, rewards (paginated). - `GET /mining/reward?address={jToken}` · `GET /mining/apy` · `GET /mining/distributions?addr={address}` — Mining reward config / per-market APY / distribution snapshots. Refer to the OpenAPI spec for the full endpoint list, request parameters, response schemas, units, and error responses. @@ -97,8 +100,8 @@ Refer to the OpenAPI spec for the full endpoint list, request parameters, respon - **Address formats**: `contracts.json` includes Base58, EVM `0x` hex, and TRON-internal `41` hex. Rendered tables may show Base58 only. - **Precision**: jToken balances are returned in jToken units (8 decimals). Underlying token amounts use that token's own decimals (TRX = 6, USDT = 6, USDC = 6, BTC = 8, ETH = 18, etc.). Always check the underlying token's `decimals()` before submitting transactions. - **Rate limits**: The public OpenAPI service is unauthenticated and may throttle abusive clients. Keep `pageSize <= 1000`, cache market metadata, avoid tight polling loops, and retry `429` / `5xx` with exponential backoff. -- **Recommended source-of-truth priority**: (1) OpenAPI spec → (2) MCP server tools → (3) rendered docs. The HTML docs are for human reading; for programmatic use prefer the OpenAPI spec and MCP server. -- **Read-only vs. write**: The HTTP API and the JustLend Skills MCP server are read-only. Only `@justlend/mcp-server-justlend` exposes write tools. Write operations are clearly marked with `destructiveHint: true` and require an encrypted local wallet via `@bankofai/agent-wallet`. +- **Recommended source-of-truth priority**: (1) OpenAPI/live API for public HTTP data → (2) MCP for schema-discoverable agent workflows → (3) CLI for deterministic terminal automation → (4) V2 Utils for embedded application code → (5) rendered docs for concepts. The HTML docs are for human reading; for programmatic use prefer the OpenAPI spec and MCP server. +- **Read-only vs. write**: The HTTP API and bundled JustLend Skills MCP server are read-only. The full MCP server, CLI, and V2 Utils expose write paths. Inspect side-effect metadata or command classification, simulate first, and require explicit human intent before signing or broadcasting. ## Optional diff --git a/docs/overrides/base.html b/docs/overrides/base.html index 8a628f1..874d976 100644 --- a/docs/overrides/base.html +++ b/docs/overrides/base.html @@ -88,7 +88,10 @@ - + {% if page.file and page.file.src_uri and page.file.src_uri.endswith('.md') %} + + {% endif %} + {# Schema.org JSON-LD. Gives AI crawlers and search engines a structured #} {# entity for JustLend DAO: what it is, what runs it, where its machine- #} {# readable surfaces live. Emitted on every page so that any RAG chunk #} @@ -122,7 +125,9 @@ "sameAs": [ "https://github.com/justlend/justlend-protocol", "https://github.com/justlend/mcp-server-justlend", - "https://github.com/justlend/justlend-skills" + "https://github.com/justlend/justlend-skills", + "https://github.com/justlend/justlend-cli", + "https://github.com/justlend/justlend-utils-v2" ], "provider": { "@id": "https://justlend.org/#org" }, "documentation": "https://docs.justlend.org/llms.txt", @@ -267,8 +272,11 @@
{% block content %} {% include "partials/content.html" %} + {% if page.file and page.file.src_uri and page.file.src_uri.endswith('.md') %} +

View raw Markdown

+ {% endif %} - {% include "partials/footer.html" %} + {% include "partials/footer.html" %} {% endblock %}
diff --git a/docs/resources/glossary.md b/docs/resources/glossary.md index e71d279..027d639 100644 --- a/docs/resources/glossary.md +++ b/docs/resources/glossary.md @@ -166,11 +166,11 @@ The 48-hour minimum delay between a proposal succeeding (vote period closes with ### active (jToken status) -Open for new supply and borrow. The default state. 17 of 23 jToken markets are currently `active`. +Open for new supply and borrow. The default state. 18 of 24 jToken markets are currently `active`. ### legacy (jToken status) -**Closed to new supply and borrow.** Existing positions can still be unwound (`repayBorrow`, `redeem`, `redeemUnderlying`). The contract remains queryable indefinitely; addresses do not get reused. 6 of 23 jToken markets are currently `legacy`. The canonical list and per-market `status` field are in [`contracts.json`](../developers/contracts.json) and the [APIs §2 reference table](../developers/apis.md#2-jtoken-address-reference). See also: [Developer common pitfalls — legacy markets](../developers/common_pitfalls.md#10-legacy-markets). +**Closed to new supply and borrow.** Existing positions can still be unwound (`repayBorrow`, `redeem`, `redeemUnderlying`). The contract remains queryable indefinitely; addresses do not get reused. 6 of 24 jToken markets are currently `legacy`. The canonical list and per-market `status` field are in [`contracts.json`](../developers/contracts.json) and the [APIs §2 reference table](../developers/apis.md#2-jtoken-address-reference). See also: [Developer common pitfalls — legacy markets](../developers/common_pitfalls.md#10-legacy-markets). --- diff --git a/hooks/copy_dotfiles.py b/hooks/copy_dotfiles.py index 4326026..2039794 100644 --- a/hooks/copy_dotfiles.py +++ b/hooks/copy_dotfiles.py @@ -1,6 +1,6 @@ -"""MkDocs hooks: dotfile mirroring + AI-snapshot metadata substitution. +"""MkDocs hooks: machine-readable source publishing and snapshot metadata. -This module installs two `on_post_build` actions: +This module installs three `on_post_build` actions: 1. **Dotfile publishing.** MkDocs intentionally skips dotfile directories (anything starting with `.`) during the build pass. We need @@ -10,7 +10,12 @@ into `site/./`, and writes `site/.nojekyll` so GitHub Pages serves those directories instead of dropping them during Jekyll processing. -2. **Snapshot metadata substitution.** `docs/llms-full.txt §0` contains +2. **Raw Markdown publishing.** Every source `docs/**/*.md` file is copied + to the equivalent `site/**/*.md` URL alongside rendered HTML. Page templates + advertise that canonical source with `rel="alternate" type="text/markdown"`, + giving agents a stable raw representation without GitHub URL guessing. + +3. **Snapshot metadata substitution.** `docs/llms-full.txt §0` contains `{{LAST_GENERATED}}`, `{{DOCS_COMMIT}}`, and `{{DOCS_COMMIT_SHORT}}` placeholders. We replace them with the current build date and the current `git rev-parse HEAD` so the snapshot header always reflects @@ -43,6 +48,17 @@ def _copy_dotfile_dirs(docs_dir: Path, site_dir: Path) -> None: (site_dir / ".nojekyll").touch() +def _copy_markdown_sources(docs_dir: Path, site_dir: Path) -> None: + copied = 0 + for src in docs_dir.rglob("*.md"): + relative = src.relative_to(docs_dir) + dest = site_dir / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dest) + copied += 1 + print(f"[raw_markdown] published {copied} Markdown source files") + + def _current_git_sha(repo_root: Path) -> str: """Resolve the current commit SHA. Prefer `git rev-parse HEAD`; fall back to the `GITHUB_SHA` env var (set in GitHub Actions); fall back to `unknown`. @@ -84,4 +100,5 @@ def on_post_build(config, **kwargs) -> None: repo_root = docs_dir.parent _copy_dotfile_dirs(docs_dir, site_dir) + _copy_markdown_sources(docs_dir, site_dir) _substitute_snapshot_metadata(site_dir, repo_root) diff --git a/mkdocs.yml b/mkdocs.yml index e5386e7..e23b654 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -31,6 +31,7 @@ not_in_nav: | /.well-known/security.txt /developers/contracts.json /developers/contracts.schema.json + /developers/apis/agent-acceptance-latest.json /developers/abis/*.json nav: @@ -77,6 +78,7 @@ nav: - AI / LLMs: ai_support/ai_llms.md - MCP Server: ai_support/mcp_server.md - JustLend Skills: ai_support/justlend_skills.md + - CLI and V2 SDK: ai_support/cli_and_sdk.md - AI Docs for Agents: - Index: documents/aidocs/index.md - Source of Truth: documents/aidocs/source_of_truth.md diff --git a/scripts/api-acceptance.mjs b/scripts/api-acceptance.mjs old mode 100644 new mode 100755 index 3bbe39b..5b95ae9 --- a/scripts/api-acceptance.mjs +++ b/scripts/api-acceptance.mjs @@ -2,24 +2,29 @@ /** * JustLend public-API agent acceptance run. * - * Exercises the anonymous GET read endpoints of https://openapi.just.network - * end-to-end and asserts the documented contract: - * - success + business errors both arrive as HTTP 200, - * - V1 success code = 0 / "SUCCESS", V2 success code = 200 / "Success" (+ timestamp), - * - decimal quantities are JSON strings, - * - key response shapes match docs/developers/apis.md and - * docs/developers/apis/justlend_apis.yaml. + * Exercises anonymous GET endpoints at https://openapi.just.network and locks + * the documented response contract, canonical 24-market inventory, account + * pagination defaults, numeric formats, and V1/V2 business-error envelopes. * - * Usage: node scripts/api-acceptance.mjs - * Exit code 0 = all checks passed. Results feed docs/developers/apis/agent-acceptance.md. + * Usage: + * node scripts/api-acceptance.mjs + * node scripts/api-acceptance.mjs --json * - * Requires Node >= 18 (global fetch). Read-only; sends ~8 GET requests once. + * Exit code 0 = every check passed. Node >= 18 is required (global fetch). + * Read-only; sends nine GET requests once. */ +import { readFile } from 'node:fs/promises'; + const BASE = process.env.JUSTLEND_API_BASE ?? 'https://openapi.just.network'; +const JSON_MODE = process.argv.includes('--json'); const DECIMAL_STR = /^-?\d+(\.\d+)?$/; const HEX32 = /^0x[0-9a-fA-F]{64}$/; - +const contracts = JSON.parse( + await readFile(new URL('../docs/developers/contracts.json', import.meta.url), 'utf8'), +); +const canonicalMarkets = Object.values(contracts.networks.mainnet.jtokens); +const canonicalSymbols = new Set(canonicalMarkets.map((market) => market.symbol)); const results = []; async function probe(name, path, checks) { @@ -31,80 +36,103 @@ async function probe(name, path, checks) { const res = await fetch(url, { signal: AbortSignal.timeout(20_000) }); httpStatus = res.status; body = await res.json(); - for (const [label, fn] of Object.entries(checks)) { + for (const [label, check] of Object.entries(checks)) { try { - if (!fn(body, httpStatus)) failures.push(label); - } catch (e) { - failures.push(`${label} (threw: ${e.message})`); + if (!check(body, httpStatus)) failures.push(label); + } catch (error) { + failures.push(`${label} (threw: ${error.message})`); } } - } catch (e) { - failures.push(`request failed: ${e.message}`); + } catch (error) { + failures.push(`request failed: ${error.message}`); } results.push({ name, path, httpStatus, pass: failures.length === 0, failures }); return body; } -const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); +const isPlainObject = (value) => + value !== null && typeof value === 'object' && !Array.isArray(value); // ---------- V1 anonymous endpoints ---------- await probe('V1 market list', '/lend/jtoken', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 0': (b) => b.code === 0, - 'message === "SUCCESS"': (b) => b.message === 'SUCCESS', - 'tokenList is a non-trivial array': (b) => Array.isArray(b.data?.tokenList) && b.data.tokenList.length >= 20, - 'decimal fields are strings (supplyRate, cash, exchangeRate)': (b) => { - const t = b.data.tokenList[0]; - return [t.supplyRate, t.cash, t.exchangeRate].every((v) => typeof v === 'string' && DECIMAL_STR.test(v)); + 'HTTP 200': (_body, status) => status === 200, + 'code === 0': (body) => body.code === 0, + 'message === "SUCCESS"': (body) => body.message === 'SUCCESS', + [`tokenList matches canonical ${canonicalMarkets.length}-market directory`]: (body) => + Array.isArray(body.data?.tokenList) && body.data.tokenList.length === canonicalMarkets.length, + 'every canonical symbol is present, including jU': (body) => { + const actual = new Set(body.data?.tokenList?.map((token) => token.symbol) ?? []); + return actual.has('jU') && [...canonicalSymbols].every((symbol) => actual.has(symbol)); }, - 'borrowIndex is an integer string (BigInt-safe)': (b) => { - const v = b.data.tokenList[0].borrowIndex; - return typeof v === 'string' && /^\d+$/.test(v) && BigInt(v) >= 0n; + 'decimal fields are strings (supplyRate, cash, exchangeRate)': (body) => { + const token = body.data.tokenList[0]; + return [token.supplyRate, token.cash, token.exchangeRate] + .every((value) => typeof value === 'string' && DECIMAL_STR.test(value)); }, - 'underlyingDecimal is a JSON integer': (b) => Number.isInteger(b.data.tokenList[0].underlyingDecimal), - 'no fabricated fields (underlyingPriceInUsd/apy absent)': (b) => { - const t = b.data.tokenList[0]; - return !('underlyingPriceInUsd' in t) && !('apy' in t); + 'borrowIndex is an integer string (BigInt-safe)': (body) => { + const value = body.data.tokenList[0].borrowIndex; + return typeof value === 'string' && /^\d+$/.test(value) && BigInt(value) >= 0n; }, + 'underlyingDecimal is a JSON integer': (body) => + Number.isInteger(body.data.tokenList[0].underlyingDecimal), + 'no fabricated fields (underlyingPriceInUsd/apy absent)': (body) => { + const token = body.data.tokenList[0]; + return !('underlyingPriceInUsd' in token) && !('apy' in token); + }, +}); + +await probe('V1 global account pagination', '/lend/account', { + 'HTTP 200': (_body, status) => status === 200, + 'code === 0': (body) => body.code === 0, + 'addresses filter is optional': (body) => Array.isArray(body.data?.list), + 'omitted pageSize defaults to 50 rows': (body) => body.data?.list?.length === 50, + 'pagination totals are positive integers': (body) => + Number.isInteger(body.data?.totalCount) && body.data.totalCount > 50 && + Number.isInteger(body.data?.totalPage) && body.data.totalPage > 1, }); await probe('V1 sTRX + Energy Rental dashboard', '/lend/strx', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 0': (b) => b.code === 0, - 'stakeInfo.reserves present as decimal string (renamed from "reserse")': (b) => - typeof b.data?.stakeInfo?.reserves === 'string' && DECIMAL_STR.test(b.data.stakeInfo.reserves), - 'stakeInfo.decimal serialized as string': (b) => b.data.stakeInfo.decimal === '18', - 'rentInfo decimal strings': (b) => - typeof b.data?.rentInfo?.priceFor10KEnergByRent === 'string' && - DECIMAL_STR.test(b.data.rentInfo.priceFor10KEnergByRent), + 'HTTP 200': (_body, status) => status === 200, + 'code === 0': (body) => body.code === 0, + 'stakeInfo.reserves present as decimal string (renamed from "reserse")': (body) => + typeof body.data?.stakeInfo?.reserves === 'string' && + DECIMAL_STR.test(body.data.stakeInfo.reserves), + 'stakeInfo.decimal serialized as string': (body) => body.data.stakeInfo.decimal === '18', + 'rentInfo decimal strings': (body) => + typeof body.data?.rentInfo?.priceFor10KEnergByRent === 'string' && + DECIMAL_STR.test(body.data.rentInfo.priceFor10KEnergByRent), }); await probe('V1 mining APY map', '/mining/apy', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 0': (b) => b.code === 0, - 'one key per market (>= 20)': (b) => isPlainObject(b.data) && Object.keys(b.data).length >= 20, - 'values are { USDD: "" }': (b) => - Object.values(b.data).every((m) => typeof m?.USDD === 'string' && DECIMAL_STR.test(m.USDD)), + 'HTTP 200': (_body, status) => status === 200, + 'code === 0': (body) => body.code === 0, + 'one key per market (>= 20)': (body) => + isPlainObject(body.data) && Object.keys(body.data).length >= 20, + 'values are { USDD: "" }': (body) => + Object.values(body.data).every((market) => + typeof market?.USDD === 'string' && DECIMAL_STR.test(market.USDD)), }); await probe('V1 high-risk account list', '/justlend/liquidate/highRiskAccountList', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 0': (b) => b.code === 0, - 'jtokens is a plain object map (not an array)': (b) => - isPlainObject(b.data?.jtokens) && Object.values(b.data.jtokens).every((v) => typeof v === 'string'), - 'updateTime is epoch-ms integer': (b) => Number.isInteger(b.data.updateTime) && b.data.updateTime > 1_600_000_000_000, - 'accounts array with string risk/USD fields + integer liquidateStatusStartTime': (b) => { - if (!Array.isArray(b.data.accounts)) return false; - if (b.data.accounts.length === 0) return true; // empty snapshot is valid - const a = b.data.accounts[0]; + 'HTTP 200': (_body, status) => status === 200, + 'code === 0': (body) => body.code === 0, + 'jtokens is a plain object map (not an array)': (body) => + isPlainObject(body.data?.jtokens) && + Object.values(body.data.jtokens).every((value) => typeof value === 'string'), + 'updateTime is epoch-ms integer': (body) => + Number.isInteger(body.data.updateTime) && body.data.updateTime > 1_600_000_000_000, + 'accounts array with string risk/USD fields + integer liquidateStatusStartTime': (body) => { + if (!Array.isArray(body.data.accounts)) return false; + if (body.data.accounts.length === 0) return true; + const account = body.data.accounts[0]; return ( - typeof a.borrower === 'string' && - typeof a.risk === 'string' && DECIMAL_STR.test(a.risk) && - typeof a.totalBorrowUsd === 'string' && - Number.isInteger(a.liquidateStatusStartTime) && - Array.isArray(a.collateralTokenList) && - Array.isArray(a.borrowTokenList) + typeof account.borrower === 'string' && + typeof account.risk === 'string' && DECIMAL_STR.test(account.risk) && + typeof account.totalBorrowUsd === 'string' && + Number.isInteger(account.liquidateStatusStartTime) && + Array.isArray(account.collateralTokenList) && + Array.isArray(account.borrowTokenList) ); }, }); @@ -112,66 +140,90 @@ await probe('V1 high-risk account list', '/justlend/liquidate/highRiskAccountLis // ---------- V2 anonymous endpoints ---------- await probe('V2 vault list', '/v2/index/vault/list', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 200 (V2 success code)': (b) => b.code === 200, - 'message === "Success"': (b) => b.message === 'Success', - 'top-level timestamp (epoch ms)': (b) => Number.isInteger(b.timestamp) && b.timestamp > 1_600_000_000_000, - 'allVaults.list is an array': (b) => Array.isArray(b.data?.allVaults?.list), - 'vault entry shape (address + string tvl/apy + arrays)': (b) => { - const v = b.data.allVaults.list[0]; + 'HTTP 200': (_body, status) => status === 200, + 'code === 200 (V2 success code)': (body) => body.code === 200, + 'message === "Success"': (body) => body.message === 'Success', + 'top-level timestamp (epoch ms)': (body) => + Number.isInteger(body.timestamp) && body.timestamp > 1_600_000_000_000, + 'allVaults.list is an array': (body) => Array.isArray(body.data?.allVaults?.list), + 'vault entry shape (address + string tvl/apy + arrays)': (body) => { + const vault = body.data.allVaults.list[0]; return ( - typeof v?.vaultAddress === 'string' && - typeof v.tvl === 'string' && DECIMAL_STR.test(v.tvl) && - typeof v.apy === 'string' && - Array.isArray(v.tags) && Array.isArray(v.markets) && Array.isArray(v.allocations) + typeof vault?.vaultAddress === 'string' && + typeof vault.tvl === 'string' && DECIMAL_STR.test(vault.tvl) && + typeof vault.apy === 'string' && + Array.isArray(vault.tags) && Array.isArray(vault.markets) && + Array.isArray(vault.allocations) ); }, - 'user-scoped fields null without address': (b) => { - const v = b.data.allVaults.list[0]; - return v.userSupplyUsd === null && v.userSupplyAmount === null; + 'user-scoped fields null without address': (body) => { + const vault = body.data.allVaults.list[0]; + return vault.userSupplyUsd === null && vault.userSupplyAmount === null; }, }); await probe('V2 market list', '/v2/index/market/list', { - 'HTTP 200': (_b, s) => s === 200, - 'code === 200 (V2 success code)': (b) => b.code === 200, - 'allMarkets is an array (key is allMarkets, not allMarket)': (b) => Array.isArray(b.data?.allMarkets), - 'market id is 0x…bytes32 and lltv a decimal string': (b) => { - const m = b.data.allMarkets[0]; - return HEX32.test(m?.id ?? '') && typeof m.lltv === 'string' && DECIMAL_STR.test(m.lltv); + 'HTTP 200': (_body, status) => status === 200, + 'code === 200 (V2 success code)': (body) => body.code === 200, + 'allMarkets is an array (key is allMarkets, not allMarket)': (body) => + Array.isArray(body.data?.allMarkets), + 'market id is 0x…bytes32 and lltv a decimal string': (body) => { + const market = body.data.allMarkets[0]; + return HEX32.test(market?.id ?? '') && + typeof market.lltv === 'string' && DECIMAL_STR.test(market.lltv); }, - 'user-scoped fields null without address (ltv/risk/loanAmount)': (b) => { - const m = b.data.allMarkets[0]; - return m.ltv === null && m.risk === null && m.loanAmount === null; + 'user-scoped fields null without address (ltv/risk/loanAmount)': (body) => { + const market = body.data.allMarkets[0]; + return market.ltv === null && market.risk === null && market.loanAmount === null; }, }); // ---------- error-contract probes ---------- await probe('V1 error contract (unknown path)', '/lend/nonExistentXYZ', { - 'HTTP 200 even for business errors': (_b, s) => s === 200, - 'code === 404 in body': (b) => b.code === 404, - 'message explains the error': (b) => typeof b.message === 'string' && b.message.length > 0, - 'data omitted on V1 errors': (b) => !('data' in b), + 'HTTP 200 even for business errors': (_body, status) => status === 200, + 'code === 404 in body': (body) => body.code === 404, + 'message explains the error': (body) => + typeof body.message === 'string' && body.message.length > 0, + 'data omitted on V1 errors': (body) => !('data' in body), }); await probe('V2 error contract (missing params)', '/v2/vault/position', { - 'HTTP 200 even for business errors': (_b, s) => s === 200, - 'code !== 200 (e.g. 202 invalid parameters)': (b) => Number.isInteger(b.code) && b.code !== 200, - 'data is null on V2 errors': (b) => b.data === null, - 'timestamp still present': (b) => Number.isInteger(b.timestamp), + 'HTTP 200 even for business errors': (_body, status) => status === 200, + 'code !== 200 (e.g. 202 invalid parameters)': (body) => + Number.isInteger(body.code) && body.code !== 200, + 'data is null on V2 errors': (body) => body.data === null, + 'timestamp still present': (body) => Number.isInteger(body.timestamp), }); // ---------- report ---------- -const pad = (s, n) => String(s).padEnd(n); -let failed = 0; -console.log(`\nJustLend API agent acceptance — ${new Date().toISOString()} — base ${BASE}\n`); -for (const r of results) { - const status = r.pass ? 'PASS' : 'FAIL'; - if (!r.pass) failed++; - console.log(`${pad(status, 5)} ${pad(r.name, 42)} ${pad(`HTTP ${r.httpStatus ?? '—'}`, 9)} ${r.path}`); - for (const f of r.failures) console.log(` ✗ ${f}`); +const generatedAt = new Date().toISOString(); +const failed = results.filter((result) => !result.pass).length; +const report = { + schemaVersion: '1.0.0', + generatedAt, + base: BASE, + passed: results.length - failed, + total: results.length, + success: failed === 0, + results, +}; + +if (JSON_MODE) { + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); +} else { + const pad = (value, length) => String(value).padEnd(length); + console.log(`\nJustLend API agent acceptance — ${generatedAt} — base ${BASE}\n`); + for (const result of results) { + const status = result.pass ? 'PASS' : 'FAIL'; + console.log( + `${pad(status, 5)} ${pad(result.name, 42)} ` + + `${pad(`HTTP ${result.httpStatus ?? '—'}`, 9)} ${result.path}`, + ); + for (const failure of result.failures) console.log(` ✗ ${failure}`); + } + console.log(`\n${report.passed}/${report.total} endpoint probes passed.`); } -console.log(`\n${results.length - failed}/${results.length} endpoint probes passed.`); -process.exit(failed === 0 ? 0 : 1); + +process.exitCode = failed === 0 ? 0 : 1; diff --git a/scripts/verify-ai-consistency.mjs b/scripts/verify-ai-consistency.mjs new file mode 100755 index 0000000..958339a --- /dev/null +++ b/scripts/verify-ai-consistency.mjs @@ -0,0 +1,119 @@ +#!/usr/bin/env node +/** Deterministic cross-surface checks for agent-readable JustLend docs. */ + +import { readFile, readdir } from 'node:fs/promises'; +import { join, relative } from 'node:path'; + +const ROOT = new URL('../', import.meta.url); +const read = async (path) => readFile(new URL(path, ROOT), 'utf8'); +const failures = []; +const check = (condition, message) => { + if (!condition) failures.push(message); +}; + +async function filesUnder(path) { + const rootPath = new URL(path, ROOT); + const output = []; + async function walk(url) { + for (const entry of await readdir(url, { withFileTypes: true })) { + const child = new URL(`${entry.name}${entry.isDirectory() ? '/' : ''}`, url); + if (entry.isDirectory()) await walk(child); + else output.push(child); + } + } + await walk(rootPath); + return output; +} + +const contracts = JSON.parse(await read('docs/developers/contracts.json')); +const markets = Object.values(contracts.networks.mainnet.jtokens); +const active = markets.filter((market) => market.status === 'active'); +const legacy = markets.filter((market) => market.status === 'legacy'); +check(markets.length === 24, `contracts.json must expose 24 markets, found ${markets.length}`); +check(active.length === 18, `contracts.json must expose 18 active markets, found ${active.length}`); +check(legacy.length === 6, `contracts.json must expose 6 legacy markets, found ${legacy.length}`); +check(active.some((market) => market.symbol === 'jU'), 'jU must be present and active'); +check(contracts._meta.schema_version === '1.2.0', 'contracts.json schema_version must be 1.2.0'); +check(contracts._meta.last_verified === '2026-08-19', 'contracts.json last_verified must be 2026-08-19'); +check( + Array.isArray(contracts._meta.verification_sources) && + contracts._meta.verification_sources.length >= 2, + 'contracts.json must name at least two verification sources', +); + +const textFiles = (await filesUnder('docs/')).filter((url) => + /\.(md|txt|json|ya?ml)$/.test(url.pathname) && !url.pathname.endsWith('/CHANGELOG.md'), +); +const stalePatterns = [ + /17 active \+ 6 legacy = 23/, + /17 of 23 jToken markets/, + /6 of 23 jToken markets/, + /protocol exposes 23 jToken markets/i, + /23 jToken markets in total/i, + /per market, 22 instances/, + /\/lend\/account\?address=\{address\}/, +]; +for (const url of textFiles) { + const content = await readFile(url, 'utf8'); + for (const pattern of stalePatterns) { + if (pattern.test(content)) { + failures.push(`${relative(new URL('.', ROOT).pathname, url.pathname)} contains stale ${pattern}`); + } + } +} + +const requiredSnippets = { + 'docs/index.md': ['18 active + 6 legacy = 24', 'justlend-cli', 'justlend-utils-v2'], + 'docs/getting_started/overview.md': ['18 active + 6 legacy = 24'], + 'docs/developers/contracts_overview.md': ['18 active + 6 legacy = 24', 'per market, 23 instances'], + 'docs/ai_support/mcp_server.md': ['v1.1.3', '24 jToken markets in total', '| jU', '`outputSchema`', '`structuredContent`'], + 'docs/ai_support/justlend_skills.md': ['`1.1.1`', '8 static shortcuts', '`structuredContent`', '`rate_limit`'], + 'docs/ai_support/cli_and_sdk.md': ['justlend/justlend-cli', '`1.0.1`', 'schemas/output-v1.schema.json', 'justlend/justlend-utils-v2', '--dry-run'], + 'docs/llms.txt': ['justlend-cli', 'v1.1.3', 'v1.1.1', 'justlend-utils-v2', '/lend/account?addresses={address}'], + 'docs/llms-full.txt': ['JustLend CLI — deterministic terminal automation', 'v1.0.1', 'v1.1.3', 'v1.1.1', 'JustLend V2 Utils'], + 'docs/documents/aidocs/source_of_truth.md': ['JustLend CLI', 'JustLend V2 Utils'], +}; +for (const [path, snippets] of Object.entries(requiredSnippets)) { + const content = await read(path); + for (const snippet of snippets) check(content.includes(snippet), `${path} must include ${snippet}`); +} + +const openapi = await read('docs/developers/apis/justlend_apis.yaml'); +check( + /'\/lend\/account':[\s\S]*accountAddresses[\s\S]*accountPageSize/.test(openapi), + '/lend/account must use endpoint-specific account parameters', +); +check( + /accountAddresses:[\s\S]*required: false[\s\S]*accountPageSize:[\s\S]*default: 50/.test(openapi), + 'account addresses must be optional and pageSize must default to 50', +); + +const mcpCatalog = await read('docs/documents/aidocs/mcp_tools.md'); +check( + mcpCatalog.includes('`@justlend/mcp-server-justlend` v1.1.3'), + 'MCP catalog must identify upstream version 1.1.3', +); +check( + (mcpCatalog.match(/^### `[^`]+`$/gm) ?? []).length === 98, + 'MCP catalog must contain exactly 98 generated tool headings', +); +check( + (mcpCatalog.match(/^- \*\*Output schema\*\*:/gm) ?? []).length === 98, + 'MCP catalog must document output schema coverage for all 98 tools', +); + +const hook = await read('hooks/copy_dotfiles.py'); +const template = await read('docs/overrides/base.html'); +check(hook.includes('_copy_markdown_sources'), 'MkDocs hook must publish raw Markdown'); +check( + template.includes('type="text/markdown"') && template.includes('View raw Markdown'), + 'page template must advertise and visibly link raw Markdown', +); + +if (failures.length > 0) { + console.error(`AI consistency checks failed (${failures.length}):`); + for (const failure of failures) console.error(`- ${failure}`); + process.exitCode = 1; +} else { + console.log('PASS AI consistency: 24 markets (18 active + 6 legacy), jU present, CLI/SDK discoverable, API contract and raw Markdown verified.'); +} From d33d314945583c81a664acdddaa95c85a045050e Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Wed, 19 Aug 2026 18:29:12 +0800 Subject: [PATCH 2/7] docs(mcp): sync 103-tool release contract - Document quote-bound energy direct purchase and recovery safeguards. - Mark the legacy unauthenticated browser bridge as disabled. - Regenerate the full catalog and enforce 103 output schemas. --- docs/ai_support/index.md | 2 +- docs/ai_support/mcp_server.md | 66 ++++++++------ docs/developers/justlend_v2.md | 4 +- docs/documents/aidocs/common_questions.md | 2 +- docs/documents/aidocs/mcp_safety.md | 8 +- docs/documents/aidocs/mcp_tools.md | 87 ++++++++++++++++--- .../aidocs/supply_borrow_repay_withdraw.md | 2 +- docs/index.md | 2 +- docs/llms-full.txt | 6 +- docs/llms.txt | 6 +- scripts/verify-ai-consistency.mjs | 8 +- 11 files changed, 139 insertions(+), 54 deletions(-) diff --git a/docs/ai_support/index.md b/docs/ai_support/index.md index b666354..ec10d21 100644 --- a/docs/ai_support/index.md +++ b/docs/ai_support/index.md @@ -19,7 +19,7 @@ This section collects everything an AI agent or LLM tool needs to integrate with | Page | Use for | |------|---------| | [AI / LLMs](ai_llms.md) | Machine-readable entry points — [`llms.txt`](/llms.txt), [`llms-full.txt`](/llms-full.txt), OpenAPI YAML, `contracts.json`, JSON ABIs — and which to use when. | -| [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (98 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | +| [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (103 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | | [JustLend Skills](justlend_skills.md) | The GitHub-distributed JustLend Skills project (9 read-only tools) for agent frameworks. | | [CLI and V2 SDK](cli_and_sdk.md) | Source installation, versioning, JSON/exit-code contract, dry-run workflow, TronWeb injection, and write-safety rules. | | [AI Docs for Agents](../documents/aidocs/index.md) | Compact, RAG-oriented pages: source-of-truth routing, market/account/workflow guides, MCP safety policy, English/Chinese FAQs, and the full MCP tool catalog. | diff --git a/docs/ai_support/mcp_server.md b/docs/ai_support/mcp_server.md index adf20ca..8834297 100644 --- a/docs/ai_support/mcp_server.md +++ b/docs/ai_support/mcp_server.md @@ -1,6 +1,6 @@ --- title: JustLend MCP Server (full, read + write) -description: "@justlend/mcp-server-justlend v1.1.3 — 98 MCP tools with versioned output schemas across JustLend V1 and V2, plus historical records and general TRON utilities. Dual-mode signing (browser TronLink or encrypted agent-wallet)." +description: "@justlend/mcp-server-justlend v1.1.3 — 103 MCP tools with versioned output schemas across JustLend V1 and V2, secure energy direct purchase, historical records, general TRON utilities, and encrypted agent-wallet signing." --- # MCP Server @@ -13,9 +13,9 @@ This page is the human-readable reference for the full MCP server. For agent use - [Overview](#overview) — what this server is and how it differs from [Skills](justlend_skills.md). - [Installation](#installation) — npm, source, and Claude Desktop config. -- [Wallet setup (browser vs agent-wallet)](#wallet-setup-first-use-choice) — browser (TronLink TIP-6963) vs agent-wallet (encrypted local). +- [Wallet setup](#wallet-setup-first-use-choice) — encrypted agent-wallet; the legacy unauthenticated browser bridge is currently disabled. - [HTTP-mode authentication (`MCP_API_KEY`)](#http-mode-authentication-mcp_api_key) — stdio (local clients) is open; HTTP/SSE is fail-closed. -- [Tool catalog (98 tools)](#tools-98-total) — **V1**: Wallet & Network · Market Data · Account & Balances · Lending Operations · Mining & Rewards · JST Voting / Governance · Energy Rental · sTRX Staking · Transfers · General TRON. **V2**: Vaults · Markets · Liquidation · Dashboard/History · Mining. Plus Historical Records. +- [Tool catalog (103 tools)](#tools-103-total) — **V1**: Wallet & Network · Market Data · Account & Balances · Lending Operations · Mining & Rewards · JST Voting / Governance · Energy Rental / Direct Purchase · sTRX Staking · Transfers · General TRON. **V2**: Vaults · Markets · Liquidation · Dashboard/History · Mining. Plus Historical Records. - [Guided prompts](#prompts-ai-guided-workflows) — the 14 shipped MCP prompts (`supply_assets`, `analyze_portfolio`, `cast_vote`, `moolah_supply`, `moolah_borrow`, …). - [Security considerations](#security-considerations) — `destructiveHint`, dry-run mode, source-of-truth priority, HTTP-mode `MCP_API_KEY`. @@ -33,7 +33,7 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen Current version (**v1.1.3**) covers **JustLend V1** *and* **JustLend V2**. V1 is the Compound-V2-style pooled supply/borrow market (jTokens); V2 is an isolated-market + ERC4626-vault protocol. The two surfaces are namespaced — V1 tools like `get_market_data` / `supply`, V2 tools prefixed `moolah_*` / `get_moolah_*` (the `moolah` identifier is V2's on-chain/tool naming). See the [JustLend V2](../developers/justlend_v2.md) developer page for the protocol model and deployed contracts. !!! tip "v1.1.3 Update" - **v1.1.3** makes every one of the **98 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. The generated `mcp-api-list.md` documents this contract for every tool. It also reconciles the V1 inventory to **24 markets (18 active + 6 legacy)** and restores active `jU` to the product table. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. All prior wallet, pre-flight, fail-closed HTTP-authentication, and HITL safeguards remain in place. + **v1.1.3** makes every one of the **103 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. It also adds five fail-closed energy direct-purchase tools for configuration, quote, order recovery, payment-risk reconciliation, and explicitly confirmed purchase; reconciles the V1 inventory to **24 markets (18 active + 6 legacy)**; and restores active `jU` to the product table. The legacy unauthenticated browser-wallet bridge is disabled, so writes use encrypted agent-wallet signing. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. ## Overview @@ -62,15 +62,14 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen - **Token Approvals**: Manage TRC20 approvals for jToken contracts - **Energy Cost Estimation**: Estimate energy, bandwidth, and TRX cost for any lending operation before executing - **JST Voting / Governance**: View proposals, cast votes, deposit/withdraw JST for voting power, reclaim votes -- **Energy Rental**: Rent energy from JustLend, calculate rental prices, query rental orders, return/cancel rentals +- **Energy Rental + Direct Purchase**: Rent energy on-chain, or fetch an authoritative quote and explicitly confirm a separately configured service purchase with payer-scoped recovery and duplicate-payment protection - **sTRX Staking**: Stake TRX to receive sTRX, unstake sTRX, claim staking rewards, check withdrawal eligibility - Precision-safe BigInt/string math for TRX Sun conversion and 18-decimal sTRX balances/exchange-rate display -**Browser Wallet Signing** +**Wallet Signing** -- **TronLink Integration**: Connect TronLink or other browser wallets via `tronlink-signer` SDK -- **Sign-only mode**: Server builds transactions, browser only signs — private keys never leave the wallet -- **Dual wallet mode**: Users choose between `browser` (recommended) or `agent` (encrypted local storage) +- **Encrypted agent-wallet**: The supported signing mode stores encrypted keys under `~/.agent-wallet/` and reads `AGENT_WALLET_PASSWORD` from the server environment +- **Browser bridge disabled**: The legacy loopback browser bridge lacks request-level authentication; `connect_browser_wallet` and browser mode fail closed until an authenticated replacement is available **General TRON Chain** @@ -82,7 +81,7 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen - **Transfers**: Send TRX, transfer TRC20 tokens, approve spenders - **Staking (Stake 2.0)**: Freeze/unfreeze TRX for BANDWIDTH or ENERGY, withdraw expired unfreeze - **Address Utilities**: Hex ↔ Base58 conversion, address validation, resolution -- **Wallet**: Sign messages, secure key management via agent-wallet or browser wallet +- **Wallet**: Sign messages and transactions through encrypted agent-wallet; the unauthenticated browser bridge is disabled ## Supported Markets @@ -137,10 +136,9 @@ The script checks Node.js 20+, installs dependencies, builds the project, and ge ### Wallet Setup (First-Use Choice) -On first use, the server presents a wallet mode selection. Users choose between: +On first use, select **agent mode** with `set_wallet_mode` and `mode="agent"`. The legacy browser mode is disabled until its local bridge supports request-level authentication. -1. **Browser mode** (recommended): Connect TronLink via `connect_browser_wallet` — private keys never leave the browser -2. **Agent mode**: Encrypted local wallet via `set_wallet_mode` with `mode="agent"` — keys stored in `~/.agent-wallet/` +Agent-wallet stores encrypted keys under `~/.agent-wallet/`; set `AGENT_WALLET_PASSWORD` in the server environment. Private keys are **never** stored in environment variables by default. @@ -166,9 +164,9 @@ npx agent-wallet activate | Tool | Description | |------|-------------| | `get_wallet_address` | Shows current address, or returns first-use wallet selection guidance | -| `connect_browser_wallet` | Connect TronLink / browser wallet for signing | -| `set_wallet_mode` | Switch between `browser` and `agent` signing | -| `get_wallet_mode` | Show current signing mode and addresses | +| `connect_browser_wallet` | Return a safety notice while the unauthenticated browser bridge is disabled | +| `set_wallet_mode` | Select supported `agent` signing; `browser` currently fails closed | +| `get_wallet_mode` | Show agent-wallet status and report legacy browser mode as disabled | | `list_wallets` | List all wallets with IDs, types, addresses | | `set_active_wallet` | Switch active wallet by ID | @@ -181,6 +179,9 @@ npx agent-wallet import ### Environment Variables ```bash +# Required for non-interactive agent-wallet unlock +export AGENT_WALLET_PASSWORD="your_wallet_password" + # Strongly recommended — avoids TronGrid 429 rate limiting on mainnet export TRONGRID_API_KEY="your_trongrid_api_key" @@ -192,8 +193,15 @@ export MCP_CORS_ORIGIN="" # required allow-list if you bind to a non-lo # Required in HTTP mode — see "HTTP Mode Authentication" below for how to generate one export MCP_API_KEY="your_strong_random_secret" + +# Required only for energy direct purchase; there is no built-in production URL +export JUSTLEND_ENERGY_API_URL="https://energy-api.example" +# Temporary/custom endpoints also require this explicit trust opt-in +export JUSTLEND_ALLOW_UNTRUSTED_HOSTS="1" ``` +Energy direct purchase is fail-closed: load live limits with `get_energy_purchase_config`, obtain an authoritative `quote_energy_purchase`, show the exact payer/receivers/duration/TRX amount, and call `buy_energy_direct` with `confirmPayment=true` only after explicit confirmation. If submission is ambiguous, call `get_energy_payment_risk`; never sign a second payment while the first is unresolved. + ### HTTP Mode Authentication (`MCP_API_KEY`) **Most users do not need this.** Claude Desktop, Claude Code, and Cursor connect over **stdio** by default, which has no network surface and no auth. `MCP_API_KEY` only applies when you run the server in **HTTP/SSE mode** (`npm run start:http`). @@ -329,7 +337,7 @@ Add to `.mcp.json` in the project root: ``` !!! tip - No `TRON_PRIVATE_KEY` needed — choose browser-wallet signing or encrypted agent-wallet mode at runtime. + No `TRON_PRIVATE_KEY` is needed. Configure encrypted agent-wallet and pass `AGENT_WALLET_PASSWORD` through the server environment; browser signing is currently disabled. #### Cursor @@ -364,7 +372,7 @@ npm run dev ## API Reference -### Tools (98 total) +### Tools (103 total) !!! info "V1 + V2" The first ten groups below are **JustLend V1** (pooled jToken market). The **JustLend V2** groups (vaults / markets / liquidation / dashboard / mining) and **Historical Records** follow. V2 tools are namespaced `moolah_*` / `get_moolah_*`. @@ -374,9 +382,9 @@ npm run dev | Tool | Description | Write? | |------|-------------|--------| | `get_wallet_address` | Show wallet address or first-use wallet selection guidance | No | -| `connect_browser_wallet` | Connect TronLink / browser wallet for signing | Yes | -| `set_wallet_mode` | Switch between `browser` and `agent` signing | Yes | -| `get_wallet_mode` | Show current signing mode and addresses | No | +| `connect_browser_wallet` | Return a safety notice while the unauthenticated browser bridge is disabled | Yes | +| `set_wallet_mode` | Select supported `agent` signing; `browser` currently fails closed | Yes | +| `get_wallet_mode` | Show agent-wallet status and report browser mode as disabled | No | | `list_wallets` | List all wallets (IDs, types, addresses) | No | | `set_active_wallet` | Switch active wallet by wallet ID | No | | `get_supported_networks` | List available networks | No | @@ -453,6 +461,11 @@ npm run dev | `get_return_rental_info` | Return/cancel estimation (refund, remaining rent, daily cost) | No | | `rent_energy` | Rent energy for a receiver (with balance, pause, limit checks) | **Yes** | | `return_energy_rental` | Cancel an active rental (with active order check) | **Yes** | +| `get_energy_purchase_config` | Load live direct-purchase limits, durations, prices, and pool capacity | No | +| `quote_energy_purchase` | Obtain an authoritative quote without creating or paying for an order | No | +| `get_energy_purchase_order` | Recover an order by order ID or payment transaction ID | No | +| `get_energy_payment_risk` | Reconcile unresolved payer-scoped payment risks before another purchase | No | +| `buy_energy_direct` | Sign a quote-bound TRX payment after `confirmPayment=true`; configured backend validates and may broadcast | **Yes** | #### sTRX Staking @@ -600,7 +613,7 @@ Every tool returns errors as structured JSON with `isError: true`, so an agent c | `transient` | ✅ true | Network/RPC timeout, `SERVER_BUSY`, 429/5xx — retry read-only calls after a short backoff; **never** blindly re-broadcast a write (re-query state first). | | `insufficient_allowance` | ❌ false | Approve the spender first (`approve_underlying` / `approve_for_votes` / `approve_moolah_*`), then retry. | | `insufficient_balance` | ❌ false | Lower the amount or fund the wallet; verify with `get_trx_balance` / `get_token_balance`. | -| `wallet_not_configured` | ❌ false | Configure a wallet (`import_wallet` / `connect_browser_wallet`), then `set_active_wallet`. | +| `wallet_not_configured` | ❌ false | Run `npx agent-wallet start` (or import/generate via CLI), set `AGENT_WALLET_PASSWORD`, select `agent` mode, and activate the wallet. | | `execution_reverted` | ❌ false | Contract precondition failed (allowance / health / paused market) — simulate before broadcasting. | | `market_not_found` | ❌ false | Verify the market symbol/address against `get_supported_markets`. | | `invalid_address` | ❌ false | Use a Base58 TRON address (`T…`, 34 chars). | @@ -609,9 +622,9 @@ Only `transient` is safe to auto-retry; every other code requires a corrective a ## Security Considerations -- **Browser wallet (recommended)**: Private keys never leave TronLink — the `tronlink-signer` SDK sends unsigned transactions to the browser and receives signed results - **Encrypted agent-wallet**: Private keys are encrypted at rest in `~/.agent-wallet/` with file permissions `0600`/`0700` — never stored in environment variables or config files -- **No key in parameters**: All signing functions use the agent-wallet or browser wallet internally; private keys are never passed as function parameters or exposed via MCP tools +- **Browser bridge fail-closed**: The legacy unauthenticated loopback bridge is disabled; do not expose it until request-level authentication is available +- **No key in parameters**: Signing functions use agent-wallet internally; private keys are never passed as function parameters or exposed via MCP tools - **Import via CLI**: Use `npx agent-wallet import` from a terminal — private key import is not exposed as an MCP tool to avoid key exposure in AI conversation logs - **Explicit approvals**: TRC20/JST approval tools require an exact amount, while `max` remains available only when the user explicitly opts in - **Pre-flight checks**: Supply/repay validate allowance first, lending tools report energy/bandwidth sufficiency warnings, and reverted simulations are not broadcast @@ -659,6 +672,9 @@ Only `transient` is safe to auto-retry; every other code requires a corrective a **"Cancel my energy rental to TXxx..."** → AI calls `get_energy_rent_info` to verify active rental → calls `return_energy_rental` → confirms refund +**"Buy energy directly for these receiver addresses"** +→ AI calls `get_energy_purchase_config` → obtains `quote_energy_purchase` → shows payer, receivers, duration, and exact TRX amount → calls `buy_energy_direct` only after explicit confirmation → verifies with `get_energy_purchase_order`; ambiguous results route through `get_energy_payment_risk` before any retry + **"Stake 1000 TRX to earn sTRX rewards"** → AI uses `stake_trx` prompt: checks balance → checks exchange rate & APY → stakes TRX → verifies sTRX received @@ -669,7 +685,7 @@ Only `transient` is safe to auto-retry; every other code requires a corrective a → AI calls `check_strx_withdrawal_eligibility` to check unbonding status and completed withdrawal rounds **"Connect my TronLink wallet"** -→ AI calls `connect_browser_wallet`, opens browser window for user to approve in TronLink +→ AI explains that the legacy browser bridge is disabled, then guides the user to configure encrypted agent-wallet rather than bypassing the safety control **"How much energy will supplying 100 USDT cost?"** → AI calls `estimate_lending_energy` with operation=supply, market=jUSDT, amount=100, returns energy/bandwidth/TRX breakdown diff --git a/docs/developers/justlend_v2.md b/docs/developers/justlend_v2.md index d0abe8b..e6b09fe 100644 --- a/docs/developers/justlend_v2.md +++ b/docs/developers/justlend_v2.md @@ -43,7 +43,7 @@ V2 **vaults** are ERC4626 tokenized vaults that aggregate supply-side liquidity ### Liquidation -When a borrower's risk reaches the market `lltv`, anyone may liquidate through the **PublicLiquidatorProxy**: repay part of the debt (in the loan token) and seize the corresponding collateral at a discount. See `get_moolah_pending_liquidations` / `get_moolah_liquidation_quote` / `moolah_liquidate` in the [MCP server tool catalog](../ai_support/mcp_server.md#tools-98-total). +When a borrower's risk reaches the market `lltv`, anyone may liquidate through the **PublicLiquidatorProxy**: repay part of the debt (in the loan token) and seize the corresponding collateral at a discount. See `get_moolah_pending_liquidations` / `get_moolah_liquidation_quote` / `moolah_liquidate` in the [MCP server tool catalog](../ai_support/mcp_server.md#tools-103-total). ### Native TRX @@ -88,7 +88,7 @@ Addresses are the source-of-truth deployment config tracked in the MCP server's ## Using V2 via the MCP server -The [JustLend MCP Server](../ai_support/mcp_server.md) (current: v1.1.3) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-98-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). +The [JustLend MCP Server](../ai_support/mcp_server.md) (current: v1.1.3) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-103-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). Contract ABIs (`MOOLAH_CORE_ABI`, `TRX_PROVIDER_ABI`, `MOOLAH_VAULT_ABI`, `PUBLIC_LIQUIDATOR_ABI`) are bundled in the MCP repo's [`src/core/abis.ts`](https://github.com/justlend/mcp-server-justlend/blob/main/src/core/abis.ts). For the full on-chain ABIs and contract data structures (`Position`, `MarketParams`, `MarketConfig`, `MarketAllocation`, …), see the [SBM V2 contract reference](supply_and_borrow_market/sbmV2.md). diff --git a/docs/documents/aidocs/common_questions.md b/docs/documents/aidocs/common_questions.md index c72ea98..81cd816 100644 --- a/docs/documents/aidocs/common_questions.md +++ b/docs/documents/aidocs/common_questions.md @@ -107,6 +107,6 @@ Chinese: “怎么解析 Borrow 事件?”、“jToken ABI 在哪?” ### Should I use browser wallet or agent wallet? -Browser wallet is recommended for most users because private keys stay in TronLink or another browser wallet. Agent wallet is for local encrypted automation. Never paste private keys or seed phrases into chat. +Use encrypted agent-wallet for the current MCP release. The legacy browser-wallet bridge is disabled because its loopback transport lacks request-level authentication. Never bypass that control or paste private keys or seed phrases into chat; import or generate wallets through the local `agent-wallet` CLI. Chinese: “要不要导入私钥?”、“TronLink 和 agent wallet 哪个安全?” diff --git a/docs/documents/aidocs/mcp_safety.md b/docs/documents/aidocs/mcp_safety.md index 19c28b7..8007350 100644 --- a/docs/documents/aidocs/mcp_safety.md +++ b/docs/documents/aidocs/mcp_safety.md @@ -20,7 +20,7 @@ Use this page before any JustLend MCP workflow that may sign or broadcast a tran JustLend MCP tools fall into three practical classes: 1. **Read-only tools**: query markets, account state, balances, blocks, prices, rewards, or supported networks. These do not move assets. -2. **Local state / interaction tools**: connect browser wallet, set wallet mode, set network, select active wallet. These change local configuration or start a browser interaction. +2. **Local state / interaction tools**: set wallet mode, set network, and select the active wallet. These change local configuration. `connect_browser_wallet` currently returns a safety notice because the legacy unauthenticated bridge is disabled. 3. **On-chain write tools**: supply, borrow, repay, withdraw, approve, transfer, stake, unstake, vote, rent energy, return energy, deploy or write contracts. These may move assets or create obligations. Use [`mcp_tools.md`](mcp_tools.md) for the generated side-effect class and annotation of each tool. @@ -40,14 +40,16 @@ Before any on-chain write tool, the agent must show: Then ask for explicit confirmation. +For `buy_energy_direct`, the confirmation must be tied to the authoritative quote: show payer, every receiver, duration, and exact TRX amount. The configured backend validates and may broadcast the signed payment. If the result is ambiguous, call `get_energy_payment_risk` and do not sign a second payment while the first remains unresolved. + ## Private key rule Never ask the user to paste a private key or seed phrase into chat or MCP tool arguments. -Allowed wallet modes: +Supported wallet mode: -- **Browser wallet mode**: recommended. TronLink or another browser wallet signs transactions. Private keys never leave the wallet. - **Agent wallet mode**: encrypted local wallet managed by `@bankofai/agent-wallet`. Use CLI or local wallet management; do not pass private keys through MCP prompts. +- **Browser mode is disabled**: the legacy loopback bridge lacks request-level authentication. Do not bypass this fail-closed control; wait for an authenticated replacement. ## Approval rule diff --git a/docs/documents/aidocs/mcp_tools.md b/docs/documents/aidocs/mcp_tools.md index ea45084..4e1bf18 100644 --- a/docs/documents/aidocs/mcp_tools.md +++ b/docs/documents/aidocs/mcp_tools.md @@ -32,9 +32,9 @@ This docs-local page wraps the generated catalog from the MCP repository so RAG | Wallet and account risk | `get_wallet_address`, `get_account_summary`, `get_balances` | Read-only / wallet read | | Supply, borrow, repay, withdraw | `supply`, `borrow`, `repay`, `withdraw`, `withdraw_all`, `estimate_lending_energy` | Writes require HITL | | sTRX staking | `get_strx_dashboard`, `get_strx_account`, `stake_trx_to_strx`, `unstake_strx`, `claim_strx_rewards` | Writes require HITL | -| Energy rental | `get_energy_rental_dashboard`, `calculate_energy_rental_price`, `rent_energy`, `return_energy_rental` | Writes require HITL | +| Energy rental / direct purchase | `get_energy_rental_dashboard`, `rent_energy`, `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_payment_risk`, `buy_energy_direct` | Writes require HITL; direct purchase is quote-bound | -Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “查看我的仓位/健康度” maps to account summary; “帮我存款/借款/还款/赎回/质押/租能量” maps to write tools and must require explicit confirmation. +Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “查看我的仓位/健康度” maps to account summary; “帮我存款/借款/还款/赎回/质押/租能量/买能量” maps to write tools and must require explicit confirmation. --- @@ -44,7 +44,7 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ > > Lets an AI agent plan tool routing offline without connecting to the server. Side-effect classes align with the AI-Agent documentation standard baseline (Safe / Network Read / Remote Write / Destructive). -**Total tools**: 98 | **Protocol**: MCP | **Transport**: stdio / HTTP(SSE) +**Total tools**: 103 | **Protocol**: MCP | **Transport**: stdio / HTTP(SSE) ## Common structured output contract (v1.0.0) @@ -60,9 +60,9 @@ Every tool declares an MCP `outputSchema`. Successful calls preserve the legacy Consume `structuredContent` when available; older clients may continue parsing the first text content item. Error results keep `isError: true` and the existing structured JSON error body. -**Read-only tools**: 58 | **Write tools**: 40 (of which marked destructive: 27) +**Read-only tools**: 62 | **Write tools**: 41 (of which marked destructive: 28) -> ⚠️ Tools marked 🔴 **sign and broadcast TRON transactions that move real assets** — the client MUST require human confirmation (HITL) before executing. 🟡 tools only change local wallet/network config or start an interaction. Private keys are managed encrypted by `@bankofai/agent-wallet` or signed via the TronLink browser wallet, and are **never passed as tool arguments**. +> ⚠️ Tools marked 🔴 **sign and broadcast TRON transactions that move real assets** — the client MUST require human confirmation (HITL) before executing. 🟡 tools only change local wallet/network config or start an interaction. Private keys are managed encrypted by `@bankofai/agent-wallet` and are **never passed as tool arguments**. The legacy unauthenticated browser-wallet bridge is disabled. --- @@ -73,7 +73,7 @@ Consume `structuredContent` when available; older clients may continue parsing t **Get Wallet Address** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false -- **Description**: Get the active wallet address. Returns browser wallet address if in browser mode, agent-wallet address if agent mode is selected, or a first-use wallet selection guide if no wallet mode has been chosen yet. +- **Description**: Get the active agent-wallet address, or a first-use wallet setup guide if no wallet mode has been chosen yet. Legacy browser mode is disabled until its bridge supports request-level authentication. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none @@ -103,7 +103,7 @@ Consume `structuredContent` when available; older clients may continue parsing t **Connect Browser Wallet** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: false · openWorld: true -- **Description**: Connect to a browser wallet (TronLink, TokenPocket) for signing transactions. RECOMMENDED: More secure than agent-wallet because private keys never leave your browser. This opens a browser window where the user must approve the connection. Tell the user to switch to their browser to approve. Blocks until the user acts or the request times out (5 min). After connecting, all write operations will use the browser wallet for signing. +- **Description**: Browser wallet signing is temporarily disabled because the legacy local bridge lacks request-level authentication. Use agent-wallet with AGENT_WALLET_PASSWORD until an authenticated bridge is available. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | @@ -115,7 +115,7 @@ Consume `structuredContent` when available; older clients may continue parsing t **Set Wallet Mode** - **Side effect**: 🟡 State-changing (Write) — changes local wallet/network config or starts an interaction; client should confirm - **annotations**: idempotent: true · openWorld: false -- **Description**: Switch wallet signing mode. 'browser' (recommended, more secure): uses TronLink in your browser — private keys never leave the browser. 'agent': uses encrypted key stored in ~/.agent-wallet/. Selecting agent mode for the first time will create an encrypted agent-wallet if needed. Browser mode requires connect_browser_wallet first. +- **Description**: Switch wallet signing mode. 'agent' uses an encrypted key stored in ~/.agent-wallet/. Browser mode is disabled until the local bridge supports request-level authentication. Selecting agent mode for the first time will create an encrypted agent-wallet if needed. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) | Param | Type | Required | Default | Description | @@ -127,7 +127,7 @@ Consume `structuredContent` when available; older clients may continue parsing t **Get Wallet Mode** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: false -- **Description**: Get the current wallet signing mode (browser, agent, or unset), connected address, and connection status. +- **Description**: Get the current wallet signing mode and agent-wallet status. Legacy browser mode is reported as disabled. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none @@ -621,7 +621,74 @@ Consume `structuredContent` when available; older clients may continue parsing t | `proposalId` | number | ✅ | | The proposal ID to withdraw votes from | | `network` | string | — | | Network. Default: mainnet | -## Energy Rental (9) +## Energy Rental (14) + +### `get_energy_purchase_config` + +**Energy Purchase Config** +- **Side effect**: 🟢 Read-only (Safe / Network Read) +- **annotations**: idempotent: true · openWorld: true +- **Description**: Get live energy direct-purchase limits, supported durations, current unit prices, and pool capacity. Requires JUSTLEND_ENERGY_API_URL; there is intentionally no production URL or economic fallback. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) +- **Params**: none + +### `quote_energy_purchase` + +**Quote Energy Purchase** +- **Side effect**: 🟢 Read-only (Safe / Network Read) +- **annotations**: idempotent: true · openWorld: true +- **Description**: Get an authoritative, read-only quote for direct energy purchase. It does not create an order, sign, broadcast, or reserve funds. Limits and resource-pool exclusions are validated against live config. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) + +| Param | Type | Required | Default | Description | +|-------|------|:--------:|---------|-------------| +| `receiverAddresses` | string[] | ✅ | | One or more energy receiver addresses | +| `energyPerReceiver` | number (min 0, max 9007199254740991) | ✅ | | Energy amount for each receiver | +| `duration` | string (min len 1) | ✅ | | Duration exactly as advertised by get_energy_purchase_config | + +### `get_energy_purchase_order` + +**Energy Purchase Order** +- **Side effect**: 🟢 Read-only (Safe / Network Read) +- **annotations**: idempotent: true · openWorld: true +- **Description**: Get the current lifecycle state and delivery details for an energy purchase order. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) + +| Param | Type | Required | Default | Description | +|-------|------|:--------:|---------|-------------| +| `orderId` | union | ✅ | | Energy purchase order id | +| `orderToken` | string (min len 1) | — | | Optional X-Consumer-Order-Token returned when the order was accepted | + +### `get_energy_payment_risk` + +**Energy Payment Risk** +- **Side effect**: 🟢 Read-only (Safe / Network Read) +- **annotations**: idempotent: true · openWorld: true +- **Description**: Reconcile and return unresolved direct-purchase payment risks. If any result remains, do not sign a new payment. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) + +| Param | Type | Required | Default | Description | +|-------|------|:--------:|---------|-------------| +| `address` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | — | | Payer address. Default: configured wallet | +| `network` | string | — | | Network used to query the payment transaction. Default: configured network | + +### `buy_energy_direct` + +**Buy Energy Direct** +- **Side effect**: 🔴 On-chain write · high-risk (Remote Write / Destructive) — signs and broadcasts a TRON transaction moving real assets; the client MUST require human confirmation (HITL) before executing +- **annotations**: idempotent: false · openWorld: true +- **Description**: VALUE-MOVING OPERATION. Buy energy by signing a native TRX payment. The MCP server never broadcasts the payment locally; the configured energy service validates and may broadcast it. Call quote_energy_purchase first, show the payer, receivers, duration, and exact TRX amount to the user, and set confirmPayment=true only after the user explicitly confirms. Ambiguous submissions retry only the same signed transaction and block a new payment. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) + +| Param | Type | Required | Default | Description | +|-------|------|:--------:|---------|-------------| +| `receiverAddresses` | string[] | ✅ | | One or more energy receiver addresses | +| `energyPerReceiver` | number (min 0, max 9007199254740991) | ✅ | | Energy amount for each receiver | +| `duration` | string (min len 1) | ✅ | | Duration exactly as advertised by get_energy_purchase_config | +| `expectedAmountSun` | number (min 0, max 9007199254740991) | ✅ | | Exact total_sun from the quote explicitly confirmed by the user | +| `expectedPayAddress` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | ✅ | | Exact payment_address from the quote explicitly confirmed by the user | +| `confirmPayment` | literal | ✅ | | Must be true only after the user explicitly confirms this value-moving payment | +| `network` | string | — | | Signing network. Default: configured network | ### `get_energy_rental_dashboard` diff --git a/docs/documents/aidocs/supply_borrow_repay_withdraw.md b/docs/documents/aidocs/supply_borrow_repay_withdraw.md index d8ca172..93d8a01 100644 --- a/docs/documents/aidocs/supply_borrow_repay_withdraw.md +++ b/docs/documents/aidocs/supply_borrow_repay_withdraw.md @@ -21,7 +21,7 @@ These are write operations. They can sign and broadcast TRON transactions that m ## General safety workflow 1. Confirm network: `mainnet` for real funds, `nile` for testing. -2. Confirm wallet mode: browser wallet is preferred; agent-wallet is local encrypted fallback. +2. Confirm wallet mode: use encrypted `agent-wallet`; the legacy unauthenticated browser bridge is disabled. 3. Validate asset and market: use `get_market_data` or `get_supported_markets`. 4. Check account state: use `get_account_summary`. 5. Estimate energy and fees where possible. diff --git a/docs/index.md b/docs/index.md index 0111f2f..379286e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,7 +21,7 @@ description: Official documentation for JustLend DAO — the largest lending pro - **Users:** [Overview](getting_started/overview.md) · [Supply](getting_started/concepts/supply.md) · [Borrow](getting_started/concepts/borrow.md) · [Liquidations](getting_started/concepts/liquidations.md) · [Risks](getting_started/concepts/risks.md) - **Developers:** [Contracts Overview](developers/contracts_overview.md) · [SBM reference](developers/supply_and_borrow_market/sbm.md) · [Deployed Contracts](developers/deployed_contracts.md) · [APIs](developers/apis.md) -- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (98 tools)](ai_support/mcp_server.md) · [Skills (9 read-only tools, GitHub install)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) +- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (103 tools)](ai_support/mcp_server.md) · [Skills (9 read-only tools, GitHub install)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) - **Governance:** [JIPs](governance/jips.md) · [Tokenomics (JST)](governance/tokenomics.md) · [Forum](https://forum.justlend.org) ## External diff --git a/docs/llms-full.txt b/docs/llms-full.txt index ec9157b..169d426 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -461,17 +461,17 @@ Built-in MCP tools (all read-only): `get_all_markets`, `get_dashboard`, `get_sup ### 7.2 Full MCP Server — `@justlend/mcp-server-justlend` -Read + write MCP server, **98 tools**, version **v1.1.3**. Repo: . Covers **JustLend V1 and V2** — the V1 tools plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. Every tool declares a common success `outputSchema`; successful calls preserve text content and add `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`. The generated [`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) lists input/output contracts and side-effect classes for offline routing. +Read + write MCP server, **103 tools**, version **v1.1.3**. Repo: . Covers **JustLend V1 and V2** — including quote-bound energy direct purchase with payer-scoped recovery, plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. Every tool declares a common success `outputSchema`; successful calls preserve text content and add `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`. The generated [`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) lists input/output contracts and side-effect classes for offline routing. Capability domains: -- **Wallet & Network** (10 tools) — dual-mode signing: `browser` (TronLink via `tronlink-signer` SDK, TIP-6963; **recommended** — private keys never leave the wallet) or `agent` (encrypted local wallet under `~/.agent-wallet/`, managed by `@bankofai/agent-wallet`). Importing an existing key is intentionally CLI-only (`npx agent-wallet add`) — not exposed as an MCP tool, since MCP arguments can be logged by clients. Tools: `get_wallet_address`, `connect_browser_wallet`, `set_wallet_mode`, `get_wallet_mode`, `list_wallets`, `set_active_wallet`, `get_supported_networks`, `get_supported_markets`, `set_network`, `get_network`. +- **Wallet & Network** (10 tools) — supported writes use `agent` mode with an encrypted local wallet under `~/.agent-wallet/`, managed by `@bankofai/agent-wallet`. The legacy loopback browser bridge is disabled because it lacks request-level authentication; `connect_browser_wallet` returns a safety notice and selecting `browser` fails closed. Importing an existing key is intentionally CLI-only (`npx agent-wallet add`) — not exposed as an MCP tool, since MCP arguments can be logged by clients. Tools: `get_wallet_address`, `connect_browser_wallet`, `set_wallet_mode`, `get_wallet_mode`, `list_wallets`, `set_active_wallet`, `get_supported_networks`, `get_supported_markets`, `set_network`, `get_network`. - **Market Data** (3 tools) — contract queries first with API fallback; TTL caching (30–60s). `get_market_data`, `get_all_markets`, `get_protocol_summary`. - **Account & Balances** (5 tools) — Multicall3 batch queries (~2.5s vs ~8s legacy). Multicall3 on TRON Mainnet: `TX56WKxtja91Dybf2FdN4hZbDLyKVxxhAu` (verified on-chain — name = `Multicall3`, `getCurrentBlockTimestamp()` returns valid epoch). `get_account_summary`, `check_allowance`, `get_trx_balance`, `get_token_balance`, `get_wallet_balances`. - **Lending Operations** (10 tools) — `supply`, `withdraw`, `withdraw_all`, `borrow`, `repay`, `enter_market`, `exit_market`, `approve_underlying`, `claim_rewards`, `estimate_lending_energy`. Write tools marked with `destructiveHint: true`. - **Mining & Rewards** (3 tools) — `get_mining_rewards`, `get_usdd_mining_config`, `get_wbtc_mining_config`. - **JST Voting / Governance** (10 tools) — `get_proposal_list`, `get_user_vote_status`, `get_vote_info`, `get_locked_votes`, `check_jst_allowance_for_voting`, `approve_jst_for_voting`, `deposit_jst_for_votes`, `withdraw_votes_to_jst`, `cast_vote`, `withdraw_votes_from_proposal`. -- **Energy Rental** (9 tools) — dashboard, params, price calculator, rate, orders, rent info, return info, `rent_energy`, `return_energy_rental`. +- **Energy Rental / Direct Purchase** (14 tools) — nine rental tools plus `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_order`, `get_energy_payment_risk`, and explicitly confirmed `buy_energy_direct`. Direct purchase has no built-in service URL or economic fallback; it is quote-bound, stores only public risk identifiers, and never permits a second payment while the first result is ambiguous. - **sTRX Staking** (7 tools) — dashboard, account, balance, withdrawal-eligibility check, `stake_trx_to_strx`, `unstake_strx`, `claim_strx_rewards`. Staking paths use precision-safe string/BigInt math for TRX Sun conversion and 18-decimal sTRX balances/exchange-rate display. - **Transfers** (2 tools) — `transfer_trx`, `transfer_trc20`. - **General TRON utilities** (via the same tool set) — balances, blocks, transactions, contract read/write, multicall, TRC20/TRC721/TRC1155 metadata, transfers, Stake 2.0 freeze/unfreeze, address conversion, wallet management, message signing. diff --git a/docs/llms.txt b/docs/llms.txt index 478e0c5..1fe6329 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -60,15 +60,15 @@ - [MCP Safety Policy](https://docs.justlend.org/documents/aidocs/mcp_safety): Read-only vs write tools, wallet modes, private-key handling, and HITL confirmation. - [Common Questions](https://docs.justlend.org/documents/aidocs/common_questions): English and Chinese user questions mapped to tools and API sources. - [AI Glossary](https://docs.justlend.org/documents/aidocs/glossary): Compact definitions for JustLend / Compound V2 terms. -- [MCP Tool Catalog](https://docs.justlend.org/documents/aidocs/mcp_tools): Full generated catalog of all 98 MCP tools with schemas and safety annotations. +- [MCP Tool Catalog](https://docs.justlend.org/documents/aidocs/mcp_tools): Full generated catalog of all 103 MCP tools with schemas and safety annotations. ## AI Agent integration - [AI / LLMs](https://docs.justlend.org/ai_support/ai_llms): Human-readable directory for `llms.txt`, `llms-full.txt`, OpenAPI, contract JSON, and ABI JSON endpoints. - [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills) (v1.1.1): GitHub-distributed read-only skills project + lightweight MCP server (**9 query tools**) with versioned `outputSchema`, `structuredContent`, and machine-readable retry errors. Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. - [CLI and V2 SDK integration guide](https://docs.justlend.org/ai_support/cli_and_sdk): Choose terminal/CI automation or embedded application integration; includes installation, version, output contract, signing, and broadcast safety rules. -- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **98 tools**): Full read/write MCP server for JustLend V1 and V2. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Source: . -- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 98 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. +- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **103 tools**): Full read/write MCP server for JustLend V1 and V2, including quote-bound energy direct purchase with payer-scoped recovery. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Writes use encrypted agent-wallet; the legacy unauthenticated browser bridge is disabled. Source: . +- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 103 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. - [MCP source ABIs and network config](https://github.com/justlend/mcp-server-justlend): Upstream TypeScript definitions used to generate the docs JSON ABI and address files. ## API endpoints (read-only HTTP API) diff --git a/scripts/verify-ai-consistency.mjs b/scripts/verify-ai-consistency.mjs index 958339a..40c0dfa 100755 --- a/scripts/verify-ai-consistency.mjs +++ b/scripts/verify-ai-consistency.mjs @@ -94,12 +94,12 @@ check( 'MCP catalog must identify upstream version 1.1.3', ); check( - (mcpCatalog.match(/^### `[^`]+`$/gm) ?? []).length === 98, - 'MCP catalog must contain exactly 98 generated tool headings', + (mcpCatalog.match(/^### `[^`]+`$/gm) ?? []).length === 103, + 'MCP catalog must contain exactly 103 generated tool headings', ); check( - (mcpCatalog.match(/^- \*\*Output schema\*\*:/gm) ?? []).length === 98, - 'MCP catalog must document output schema coverage for all 98 tools', + (mcpCatalog.match(/^- \*\*Output schema\*\*:/gm) ?? []).length === 103, + 'MCP catalog must document output schema coverage for all 103 tools', ); const hook = await read('hooks/copy_dotfiles.py'); From 49e69bb1ddd2888efa22d06d1ce08a15546b604a Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Thu, 20 Aug 2026 11:54:15 +0800 Subject: [PATCH 3/7] fix(docs): align agent guidance with coordinated release - document all six skill workflows and the bundled read-only boundary\n- clarify backend-controlled Energy purchase broadcasts\n- validate AI contracts and strict builds on pull requests --- .github/workflows/gh-pages.yml | 4 ++++ docs/ai_support/cli_and_sdk.md | 1 + docs/ai_support/index.md | 2 +- docs/ai_support/justlend_skills.md | 22 +++++++++++++++------- docs/index.md | 2 +- docs/llms-full.txt | 9 +++++---- docs/llms.txt | 2 +- scripts/verify-ai-consistency.mjs | 2 +- 8 files changed, 29 insertions(+), 15 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 8a89dee..5f53200 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -3,6 +3,9 @@ on: push: branches: - main # Trigger this workflow whenever the main branch changes + pull_request: + branches: + - main # Validate AI contracts and strict docs builds before merge workflow_dispatch: # Allow manual triggering of this workflow via the "Run workflow" button on the GitHub UI Actions tab schedule: - cron: '17 2 * * 1' # Weekly live contract check, Monday 02:17 UTC @@ -62,6 +65,7 @@ jobs: run: echo 'docs.justlend.org' > site/CNAME - name: Deploy + if: github.event_name != 'pull_request' uses: JamesIves/github-pages-deploy-action@v4 with: token: ${{ secrets.TOKEN}} diff --git a/docs/ai_support/cli_and_sdk.md b/docs/ai_support/cli_and_sdk.md index 7d70bad..5d0ae40 100644 --- a/docs/ai_support/cli_and_sdk.md +++ b/docs/ai_support/cli_and_sdk.md @@ -42,6 +42,7 @@ The CLI exposes 31 top-level command groups covering V1 and V2 lending, vaults, - Validate output with [`schemas/output-v1.schema.json`](https://github.com/justlend/justlend-cli/blob/main/schemas/output-v1.schema.json). Treat `retryable` as the retry signal; never blindly retry a write. - Use `--dry-run --dry-run-owner
` first. Dry-run simulates and never signs or broadcasts. - Use `--no-broadcast` for sign-only validation, then broadcast only after explicit human intent. +- Energy direct purchase is the exception: it rejects `--no-broadcast` because the configured backend controls broadcast. Use `energy purchase quote` or `--dry-run` before the explicitly confirmed purchase instead. - In non-interactive or JSON mode, writes require `--yes`; that flag bypasses the local prompt and must not be added automatically. - Prefer `--network nile` for integration tests. Mainnet writes are irreversible. diff --git a/docs/ai_support/index.md b/docs/ai_support/index.md index ec10d21..9c4aa44 100644 --- a/docs/ai_support/index.md +++ b/docs/ai_support/index.md @@ -20,7 +20,7 @@ This section collects everything an AI agent or LLM tool needs to integrate with |------|---------| | [AI / LLMs](ai_llms.md) | Machine-readable entry points — [`llms.txt`](/llms.txt), [`llms-full.txt`](/llms-full.txt), OpenAPI YAML, `contracts.json`, JSON ABIs — and which to use when. | | [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (103 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | -| [JustLend Skills](justlend_skills.md) | The GitHub-distributed JustLend Skills project (9 read-only tools) for agent frameworks. | +| [JustLend Skills](justlend_skills.md) | Six workflow modules plus a bundled 9-tool read-only MCP server for agent frameworks. | | [CLI and V2 SDK](cli_and_sdk.md) | Source installation, versioning, JSON/exit-code contract, dry-run workflow, TronWeb injection, and write-safety rules. | | [AI Docs for Agents](../documents/aidocs/index.md) | Compact, RAG-oriented pages: source-of-truth routing, market/account/workflow guides, MCP safety policy, English/Chinese FAQs, and the full MCP tool catalog. | diff --git a/docs/ai_support/justlend_skills.md b/docs/ai_support/justlend_skills.md index 20ffe73..d372ab7 100644 --- a/docs/ai_support/justlend_skills.md +++ b/docs/ai_support/justlend_skills.md @@ -1,6 +1,6 @@ --- -title: JustLend Skills (read-only) -description: "GitHub-distributed JustLend Skills — 9 read-only MCP tools and 5 skill modules for AI agents to query JustLend market data, account health, and balances. CLI also available." +title: JustLend Skills +description: "GitHub-distributed JustLend Skills — 6 workflow modules plus a bundled 9-tool read-only MCP server for AI agents. CLI also available." --- # JustLend Skills @@ -17,10 +17,10 @@ JustLend Skills is a GitHub-distributed AI Agent skills project for the **JustLe It also works as a standalone **CLI tool** for quick market checks directly from the terminal. !!! note - This is a **read-only** query package. No write operations or transaction signing are supported. For write operations (supply, borrow, repay, withdraw, sTRX staking, energy rental, governance voting), use the full MCP server: [@justlend/mcp-server-justlend](mcp_server.md). + The bundled MCP server and standalone CLI are **read-only** and never sign transactions. The package's workflow skill files also cover writes such as lending, staking, energy rental/direct purchase, and governance; those actions route to the full MCP server: [@justlend/mcp-server-justlend](mcp_server.md), require a signing wallet, and require explicit confirmation. !!! note "Bundled server is read-only V1; V2 (Moolah) needs the full server" - The **bundled lite MCP server** (the 9 query tools) is **read-only JustLend V1** (the Compound V2-style pooled markets). The package also ships a `justlend-lending-v2` skill module with V2 instructions, but **V2 tool execution is not part of the lite server** — the `justlend-lending-v2`, `justlend-trx-staking`, `justlend-energy-rental`, and `justlend-governance-v1` modules require the [full MCP server](mcp_server.md). To *query* V2 (Moolah) read-only (vault APY/TVL, market parameters, user positions, liquidation candidates), use the full server's read-only `get_moolah_*` tools — e.g. `get_moolah_vaults`, `get_moolah_markets`, `get_moolah_user_position`, `get_moolah_dashboard` — documented in [MCP Server → JustLend V2 (Moolah)](mcp_server.md). Those read tools require no wallet; only the V2 *write* tools do. + The **bundled lite MCP server** (the 9 query tools) is **read-only JustLend V1** (the Compound V2-style pooled markets). The package also ships workflow modules whose execution is not part of the lite server — `justlend-lending-v2`, `justlend-trx-staking`, `justlend-energy-rental`, `justlend-energy-purchase`, and `justlend-governance-v1` require the [full MCP server](mcp_server.md). To *query* V2 (Moolah) read-only (vault APY/TVL, market parameters, user positions, liquidation candidates), use the full server's read-only `get_moolah_*` tools — e.g. `get_moolah_vaults`, `get_moolah_markets`, `get_moolah_user_position`, `get_moolah_dashboard` — documented in [MCP Server → JustLend V2 (Moolah)](mcp_server.md). Those read tools require no wallet; only the V2 *write* tools do. !!! tip "Companion references for agents using these tools" The tool outputs use protocol-specific terminology — `mantissa`, `borrowIndex`, `exchangeRate`, `collateralFactor`, `closeFactor`, `liquidationIncentive`, `status: active|legacy`. Each is defined in the [Glossary](../resources/glossary.md) with units and on-chain encoding. When asking the agent to *act* on a market (e.g. supply, repay), point it at [Common Pitfalls](../developers/common_pitfalls.md) first — the same gotchas (USDT `approve()` race, decimals mismatch, etc.) apply whether the agent uses Skills, the full MCP server, or raw TronWeb. @@ -39,17 +39,18 @@ It also works as a standalone **CLI tool** for quick market checks directly from ### Skill Modules -The project includes 5 structured skill modules in the `/skills` directory that provide AI agents with domain-specific instructions and workflows: +The project includes 6 structured skill modules in the `/skills` directory that provide AI agents with domain-specific instructions and workflows: | Skill | Description | MCP Server Required | |-------|-------------|---------------------| -| **justlend-lending-v1** | Market queries, account analysis, health factor monitoring | JustLend Skills (built-in) | +| **justlend-lending-v1** | V1 lending queries and supply/borrow/repay/withdraw workflows | Built-in for reads; Full MCP for writes | | **justlend-lending-v2** | JustLend V2 (Moolah) isolated markets + ERC4626 vaults: supply/borrow/liquidate | Full MCP Server | | **justlend-trx-staking** | Stake TRX for sTRX liquid staking tokens | Full MCP Server | | **justlend-energy-rental** | Rent TRON Energy at discounted rates (50-80% cheaper) | Full MCP Server | +| **justlend-energy-purchase** | Quote, confirm, track, and reconcile direct Energy purchases | Full MCP Server | | **justlend-governance-v1** | View proposals, deposit JST for voting power, cast votes | Full MCP Server | -The `justlend-lending-v1` skill works with the built-in 9 query tools. The other four skills provide instructional guidance and require the [full MCP server](mcp_server.md) for tool execution (and write operations). +The read-only portions of `justlend-lending-v1` work with the built-in 9 query tools. Its write flows and the other five skills require the [full MCP server](mcp_server.md) for tool execution. ## Bundled Market Shortcuts @@ -250,6 +251,13 @@ Rent TRON Energy from the JustLend marketplace at 50-80% lower cost than burning !!! note This skill requires the [full MCP server](mcp_server.md) for tool execution. +### Energy Direct Purchase (justlend-energy-purchase) + +Obtain an authoritative quote, confirm the exact `total_sun` payment, submit it for backend-controlled broadcast, track the order, and reconcile ambiguous payment results before initiating another purchase. + +!!! warning + This skill requires the [full MCP server](mcp_server.md), an explicitly configured energy API URL, and a signing wallet. Never expose a private key or signed transaction, and never retry with a second payment while payment risk is unresolved. + ### DAO Governance (justlend-governance-v1) Participate in JustLend DAO governance proposals. Deposit JST for voting power (1 JST = 1 Vote), cast votes, and reclaim votes after proposals end. diff --git a/docs/index.md b/docs/index.md index 379286e..4dfc9be 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,7 +21,7 @@ description: Official documentation for JustLend DAO — the largest lending pro - **Users:** [Overview](getting_started/overview.md) · [Supply](getting_started/concepts/supply.md) · [Borrow](getting_started/concepts/borrow.md) · [Liquidations](getting_started/concepts/liquidations.md) · [Risks](getting_started/concepts/risks.md) - **Developers:** [Contracts Overview](developers/contracts_overview.md) · [SBM reference](developers/supply_and_borrow_market/sbm.md) · [Deployed Contracts](developers/deployed_contracts.md) · [APIs](developers/apis.md) -- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (103 tools)](ai_support/mcp_server.md) · [Skills (9 read-only tools, GitHub install)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) +- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (103 tools)](ai_support/mcp_server.md) · [Skills (6 workflows + 9 bundled read-only tools)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) - **Governance:** [JIPs](governance/jips.md) · [Tokenomics (JST)](governance/tokenomics.md) · [Forum](https://forum.justlend.org) ## External diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 169d426..feae5c1 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -436,14 +436,14 @@ JustLend ships four complementary agent and developer integration surfaces: ### 7.1 JustLend Skills — GitHub distribution -Read-only skills package, version **v1.1.1**. Repo: . +Workflow skills package with a bundled read-only runtime, version **v1.1.1**. Repo: . Install by cloning that repository and running `bash install.sh`. The local package identifier `@justlend/justlend-skills` is **not published to npm**; do not use `npm install @justlend/justlend-skills`. An `npm install` run inside the clone only installs the project's dependencies. - Combines structured **skill instructions** (for any Claude-compatible agent — Claude Code, Claude Desktop, Cursor, Codex) with a lightweight built-in **read-only MCP server** exposing **9 query tools**. - Also runs standalone as a **CLI** (`node scripts/justlend_api.mjs markets|dashboard|account ...`). - Requires `TRONGRID_API_KEY` (free at ). Supports `NETWORK=mainnet|nile`. -- **No wallet, no signing, no write operations** — strictly read-only by design. +- The bundled MCP server and standalone CLI need no wallet and are strictly read-only. Write skill workflows route to the full MCP server, a signing wallet, and explicit confirmation. - All 9 tools declare a versioned `outputSchema`. Successes expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent` while preserving raw JSON text; failures expose `{ schemaVersion, tool, error, errorCode, retryable, hint }`. Auto-retry only `rate_limit` / `transient` errors. - `get_supported_markets` lists only 8 bundled balance/allowance shortcuts. Use `get_all_markets`, the live API, or `contracts.json` for the canonical **24-market (18 active + 6 legacy)** roster. @@ -451,10 +451,11 @@ Skill modules: | Skill | Function | Backend | |-------|----------|---------| -| `justlend-lending-v1` | Market queries, account analysis, health monitoring | Built-in MCP (read-only) | +| `justlend-lending-v1` | V1 queries and lending write workflows | Built-in reads; full MCP writes | | `justlend-lending-v2` | V2 isolated markets and ERC4626 vault guidance | Requires full MCP | | `justlend-trx-staking` | sTRX staking guidance | Requires full MCP (write) | | `justlend-energy-rental` | Energy rental guidance | Requires full MCP (write) | +| `justlend-energy-purchase` | Quote-bound direct Energy purchase and recovery | Requires full MCP (write) | | `justlend-governance-v1` | JIP voting guidance | Requires full MCP (write) | Built-in MCP tools (all read-only): `get_all_markets`, `get_dashboard`, `get_supported_markets`, `get_jtoken_details`, `get_account_summary`, `get_account_data_from_api`, `get_trx_balance`, `get_token_balance`, `check_allowance`. @@ -494,7 +495,7 @@ Source-installable CLI, version **v1.0.1**. Repo: ` before any write; dry-run does not sign or broadcast. -- `--no-broadcast` signs without sending. Mainnet broadcasts require explicit user intent; never add `--yes` automatically. +- `--no-broadcast` signs without sending for supported write commands. Energy direct purchase rejects it because the configured backend controls broadcast; use a quote or `--dry-run` before the explicitly confirmed purchase. Mainnet broadcasts require explicit user intent; never add `--yes` automatically. - Prefer Nile for integration tests. Full guidance: . ### 7.4 JustLend V2 Utils — embedded browser / Node.js SDK diff --git a/docs/llms.txt b/docs/llms.txt index 1fe6329..feb8567 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -65,7 +65,7 @@ ## AI Agent integration - [AI / LLMs](https://docs.justlend.org/ai_support/ai_llms): Human-readable directory for `llms.txt`, `llms-full.txt`, OpenAPI, contract JSON, and ABI JSON endpoints. -- [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills) (v1.1.1): GitHub-distributed read-only skills project + lightweight MCP server (**9 query tools**) with versioned `outputSchema`, `structuredContent`, and machine-readable retry errors. Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. +- [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills) (v1.1.1): GitHub-distributed workflow skills project (**6 modules**) plus a bundled read-only MCP server (**9 query tools**) with versioned `outputSchema`, `structuredContent`, and machine-readable retry errors. Write workflows route to the full MCP server and require confirmation. Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. - [CLI and V2 SDK integration guide](https://docs.justlend.org/ai_support/cli_and_sdk): Choose terminal/CI automation or embedded application integration; includes installation, version, output contract, signing, and broadcast safety rules. - [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **103 tools**): Full read/write MCP server for JustLend V1 and V2, including quote-bound energy direct purchase with payer-scoped recovery. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Writes use encrypted agent-wallet; the legacy unauthenticated browser bridge is disabled. Source: . - [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 103 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. diff --git a/scripts/verify-ai-consistency.mjs b/scripts/verify-ai-consistency.mjs index 40c0dfa..a9c873b 100755 --- a/scripts/verify-ai-consistency.mjs +++ b/scripts/verify-ai-consistency.mjs @@ -67,7 +67,7 @@ const requiredSnippets = { 'docs/getting_started/overview.md': ['18 active + 6 legacy = 24'], 'docs/developers/contracts_overview.md': ['18 active + 6 legacy = 24', 'per market, 23 instances'], 'docs/ai_support/mcp_server.md': ['v1.1.3', '24 jToken markets in total', '| jU', '`outputSchema`', '`structuredContent`'], - 'docs/ai_support/justlend_skills.md': ['`1.1.1`', '8 static shortcuts', '`structuredContent`', '`rate_limit`'], + 'docs/ai_support/justlend_skills.md': ['`1.1.1`', '6 structured skill modules', 'justlend-energy-purchase', '8 static shortcuts', '`structuredContent`', '`rate_limit`'], 'docs/ai_support/cli_and_sdk.md': ['justlend/justlend-cli', '`1.0.1`', 'schemas/output-v1.schema.json', 'justlend/justlend-utils-v2', '--dry-run'], 'docs/llms.txt': ['justlend-cli', 'v1.1.3', 'v1.1.1', 'justlend-utils-v2', '/lend/account?addresses={address}'], 'docs/llms-full.txt': ['JustLend CLI — deterministic terminal automation', 'v1.0.1', 'v1.1.3', 'v1.1.1', 'JustLend V2 Utils'], From 817d89c82631cdc212c23e4518192e5b9242a4af Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Thu, 20 Aug 2026 11:57:33 +0800 Subject: [PATCH 4/7] fix(ci): keep docs pull request checks deterministic - reserve live API acceptance for push, scheduled, and manual runs\n- keep source consistency and strict MkDocs validation on pull requests --- .github/workflows/gh-pages.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 5f53200..c4c56e7 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -28,6 +28,7 @@ jobs: run: node scripts/verify-ai-consistency.mjs - name: Run live API agent acceptance + if: github.event_name != 'pull_request' run: | node scripts/api-acceptance.mjs --json > docs/developers/apis/agent-acceptance-latest.json node -e "const r=require('./docs/developers/apis/agent-acceptance-latest.json'); if(!r.success||r.passed!==r.total) process.exit(1)" From e6b490956c05d8e1df708ba3d3c2e30e71319958 Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Thu, 20 Aug 2026 11:59:16 +0800 Subject: [PATCH 5/7] ci(docs): update GitHub Actions runtimes - move checkout, Node.js setup, and Python setup to Node 24-based releases\n- remove deprecated action runtime warnings from pull request validation --- .github/workflows/gh-pages.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index c4c56e7..3c9279d 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -14,13 +14,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 # Action that checks out the repository + uses: actions/checkout@v7 # Action that checks out the repository with: persist-credentials: false # Disable auto-injection of GITHUB_TOKEN so a higher-privilege token can be supplied in later steps fetch-depth: 0 # Required by mkdocs-git-revision-date-localized-plugin to compute per-page last-updated - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: node-version: 20 @@ -34,7 +34,7 @@ jobs: node -e "const r=require('./docs/developers/apis/agent-acceptance-latest.json'); if(!r.success||r.passed!==r.total) process.exit(1)" - name: Setup Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v7 with: python-version: 3.x # Install Python From 383d404d330432d9c0aad88562c2d931c4bf3f77 Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Mon, 24 Aug 2026 14:45:33 +0800 Subject: [PATCH 6/7] docs(ai): synchronize energy purchase contracts - publish the 104-tool MCP catalog with payer history - align API defaults and signed recovery-state disclosures - correct the CLI inventory to 30 top-level command groups --- CHANGELOG.md | 3 ++- docs/ai_support/cli_and_sdk.md | 6 ++++-- docs/ai_support/index.md | 2 +- docs/ai_support/justlend_skills.md | 4 ++-- docs/ai_support/mcp_server.md | 21 ++++++++++++--------- docs/developers/justlend_v2.md | 4 ++-- docs/documents/aidocs/mcp_tools.md | 26 ++++++++++++++++++++------ docs/index.md | 2 +- docs/llms-full.txt | 6 +++--- docs/llms.txt | 6 +++--- scripts/verify-ai-consistency.mjs | 17 +++++++++++------ 11 files changed, 61 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06b28d0..e0c8c3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ For the JustLend protocol itself, see governance proposals on [forum.justlend.or - Added first-class CLI and V2 Utils discovery across navigation, `llms.txt`, `llms-full.txt`, AI source routing, JSON-LD, and a dedicated install/safety guide. - Synced the agent surfaces to CLI `1.0.1`, full MCP `1.1.3`, and Skills `1.1.1`, including versioned success/error envelopes and published output schemas. -- Regenerated the site-local 98-tool MCP catalog with `outputSchema` coverage on every tool and documented the bundled Skills server's 9 structured outputs. +- Regenerated the site-local 104-tool MCP catalog with `outputSchema` coverage on every tool and documented the bundled Skills server's 9 structured outputs. - Published canonical raw Markdown beside every rendered page and advertised it with `rel="alternate" type="text/markdown"` plus a visible source link. - Added deterministic AI-consistency checks and a weekly, structured 9-probe live API acceptance artifact in CI. @@ -23,6 +23,7 @@ For the JustLend protocol itself, see governance proposals on [forum.justlend.or - Reconciled the market inventory to **24 total (18 active + 6 legacy)** after expanding `app.justlend.org/marketNew` and cross-checking `/lend/jtoken` plus the MCP chain catalog; added the previously omitted active `jU` market everywhere. - Corrected `/lend/account`: `addresses` is optional, omission returns the global account index, and the endpoint-specific default `pageSize` is 50. - Added verification provenance and freshness metadata to `contracts.json` and its JSON Schema. +- Aligned MCP, CLI, and Skills guidance with the official mainnet energy API default, public payer-history recovery, tokenless idempotent orders, exact signed-request persistence, and the CLI's actual 30 top-level command groups. ### Added — 2026-05-22 API-style + reference-gap pass diff --git a/docs/ai_support/cli_and_sdk.md b/docs/ai_support/cli_and_sdk.md index 5d0ae40..046a640 100644 --- a/docs/ai_support/cli_and_sdk.md +++ b/docs/ai_support/cli_and_sdk.md @@ -32,7 +32,7 @@ npm link justlend --help ``` -The CLI exposes 31 top-level command groups covering V1 and V2 lending, vaults, account positions, liquidation, sTRX and stUSDT staking, WTRX, energy rental, governance, mining, rewards, history, portfolio analysis, and transaction simulation. +The CLI exposes 30 top-level command groups covering V1 and V2 lending, vaults, account positions, liquidation, sTRX and stUSDT staking, WTRX, energy rental, governance, mining, rewards, history, portfolio analysis, and transaction simulation. ### Agent contract @@ -43,6 +43,8 @@ The CLI exposes 31 top-level command groups covering V1 and V2 lending, vaults, - Use `--dry-run --dry-run-owner
` first. Dry-run simulates and never signs or broadcasts. - Use `--no-broadcast` for sign-only validation, then broadcast only after explicit human intent. - Energy direct purchase is the exception: it rejects `--no-broadcast` because the configured backend controls broadcast. Use `energy purchase quote` or `--dry-run` before the explicitly confirmed purchase instead. +- Mainnet energy purchase uses the official `https://tegrow.ablesdxd.link` service by default. Nile requires an explicit matching custom `--energy-api-url`; the CLI rejects the production service on non-mainnet, including `buy --dry-run`. +- Use `energy purchase history ` to recover public in-progress/settled orders. An ambiguous result may retain the exact signed request in the local mode-`0600` risk file; it is redacted from output and blocks another payment until history reconciliation clears it. - In non-interactive or JSON mode, writes require `--yes`; that flag bypasses the local prompt and must not be added automatically. - Prefer `--network nile` for integration tests. Mainnet writes are irreversible. @@ -87,7 +89,7 @@ tronObj.network = 'nile'; 3. Inspect whether a helper is read-only or creates a transaction before calling it. `depositToVault`, `supplyCollateral`, `borrow`, `repay`, `liquidate`, `multiClaim`, and energy `purchase()` are write paths. 4. Keep private keys, signed transactions, and wallet session material out of prompts, logs, and tool output. 5. Use Nile and a non-production wallet for tests. Require explicit human confirmation immediately before a Mainnet signature or broadcast. -6. For energy purchases, supply the API URL and durable payment-risk storage explicitly; never fabricate pricing or payment-address fallbacks. +6. For energy purchases, use the official service only on mainnet, configure a matching service on non-mainnet, and preserve durable payment-risk state; never fabricate pricing or payment-address fallbacks. ## Which integration surface should an agent choose? diff --git a/docs/ai_support/index.md b/docs/ai_support/index.md index 9c4aa44..c3fb85f 100644 --- a/docs/ai_support/index.md +++ b/docs/ai_support/index.md @@ -19,7 +19,7 @@ This section collects everything an AI agent or LLM tool needs to integrate with | Page | Use for | |------|---------| | [AI / LLMs](ai_llms.md) | Machine-readable entry points — [`llms.txt`](/llms.txt), [`llms-full.txt`](/llms-full.txt), OpenAPI YAML, `contracts.json`, JSON ABIs — and which to use when. | -| [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (103 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | +| [MCP Server](mcp_server.md) | Install and run the JustLend MCP server (104 tools): account analysis, market queries, transaction pre-flight, and wallet-aware writes with HITL confirmation. | | [JustLend Skills](justlend_skills.md) | Six workflow modules plus a bundled 9-tool read-only MCP server for agent frameworks. | | [CLI and V2 SDK](cli_and_sdk.md) | Source installation, versioning, JSON/exit-code contract, dry-run workflow, TronWeb injection, and write-safety rules. | | [AI Docs for Agents](../documents/aidocs/index.md) | Compact, RAG-oriented pages: source-of-truth routing, market/account/workflow guides, MCP safety policy, English/Chinese FAQs, and the full MCP tool catalog. | diff --git a/docs/ai_support/justlend_skills.md b/docs/ai_support/justlend_skills.md index d372ab7..9a9a0c0 100644 --- a/docs/ai_support/justlend_skills.md +++ b/docs/ai_support/justlend_skills.md @@ -253,10 +253,10 @@ Rent TRON Energy from the JustLend marketplace at 50-80% lower cost than burning ### Energy Direct Purchase (justlend-energy-purchase) -Obtain an authoritative quote, confirm the exact `total_sun` payment, submit it for backend-controlled broadcast, track the order, and reconcile ambiguous payment results before initiating another purchase. +Obtain an authoritative quote, confirm the exact `total_sun` payment, submit it for backend-controlled broadcast, track token-bearing orders, recover tokenless results through public payer history, and reconcile ambiguous payment results before initiating another purchase. !!! warning - This skill requires the [full MCP server](mcp_server.md), an explicitly configured energy API URL, and a signing wallet. Never expose a private key or signed transaction, and never retry with a second payment while payment risk is unresolved. + This skill requires the [full MCP server](mcp_server.md) and a signing wallet. Mainnet uses the official `https://tegrow.ablesdxd.link` endpoint by default; a custom/test or non-mainnet service must be configured explicitly. Never expose a private key or signed transaction in tool output. The full server may retain the exact signed request in a local mode-`0600` recovery file after an ambiguous submission; never retry with a second payment while payment risk is unresolved. ### DAO Governance (justlend-governance-v1) diff --git a/docs/ai_support/mcp_server.md b/docs/ai_support/mcp_server.md index 8834297..06f3a72 100644 --- a/docs/ai_support/mcp_server.md +++ b/docs/ai_support/mcp_server.md @@ -1,6 +1,6 @@ --- title: JustLend MCP Server (full, read + write) -description: "@justlend/mcp-server-justlend v1.1.3 — 103 MCP tools with versioned output schemas across JustLend V1 and V2, secure energy direct purchase, historical records, general TRON utilities, and encrypted agent-wallet signing." +description: "@justlend/mcp-server-justlend v1.1.3 — 104 MCP tools with versioned output schemas across JustLend V1 and V2, secure energy direct purchase, historical records, general TRON utilities, and encrypted agent-wallet signing." --- # MCP Server @@ -15,7 +15,7 @@ This page is the human-readable reference for the full MCP server. For agent use - [Installation](#installation) — npm, source, and Claude Desktop config. - [Wallet setup](#wallet-setup-first-use-choice) — encrypted agent-wallet; the legacy unauthenticated browser bridge is currently disabled. - [HTTP-mode authentication (`MCP_API_KEY`)](#http-mode-authentication-mcp_api_key) — stdio (local clients) is open; HTTP/SSE is fail-closed. -- [Tool catalog (103 tools)](#tools-103-total) — **V1**: Wallet & Network · Market Data · Account & Balances · Lending Operations · Mining & Rewards · JST Voting / Governance · Energy Rental / Direct Purchase · sTRX Staking · Transfers · General TRON. **V2**: Vaults · Markets · Liquidation · Dashboard/History · Mining. Plus Historical Records. +- [Tool catalog (104 tools)](#tools-104-total) — **V1**: Wallet & Network · Market Data · Account & Balances · Lending Operations · Mining & Rewards · JST Voting / Governance · Energy Rental / Direct Purchase · sTRX Staking · Transfers · General TRON. **V2**: Vaults · Markets · Liquidation · Dashboard/History · Mining. Plus Historical Records. - [Guided prompts](#prompts-ai-guided-workflows) — the 14 shipped MCP prompts (`supply_assets`, `analyze_portfolio`, `cast_vote`, `moolah_supply`, `moolah_borrow`, …). - [Security considerations](#security-considerations) — `destructiveHint`, dry-run mode, source-of-truth priority, HTTP-mode `MCP_API_KEY`. @@ -33,7 +33,7 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen Current version (**v1.1.3**) covers **JustLend V1** *and* **JustLend V2**. V1 is the Compound-V2-style pooled supply/borrow market (jTokens); V2 is an isolated-market + ERC4626-vault protocol. The two surfaces are namespaced — V1 tools like `get_market_data` / `supply`, V2 tools prefixed `moolah_*` / `get_moolah_*` (the `moolah` identifier is V2's on-chain/tool naming). See the [JustLend V2](../developers/justlend_v2.md) developer page for the protocol model and deployed contracts. !!! tip "v1.1.3 Update" - **v1.1.3** makes every one of the **103 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. It also adds five fail-closed energy direct-purchase tools for configuration, quote, order recovery, payment-risk reconciliation, and explicitly confirmed purchase; reconciles the V1 inventory to **24 markets (18 active + 6 legacy)**; and restores active `jU` to the product table. The legacy unauthenticated browser-wallet bridge is disabled, so writes use encrypted agent-wallet signing. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. + **v1.1.3** makes every one of the **104 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. It also adds six fail-closed energy direct-purchase tools for configuration, quote, public payer history, order recovery, payment-risk reconciliation, and explicitly confirmed purchase; reconciles the V1 inventory to **24 markets (18 active + 6 legacy)**; and restores active `jU` to the product table. The legacy unauthenticated browser-wallet bridge is disabled, so writes use encrypted agent-wallet signing. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. ## Overview @@ -194,13 +194,15 @@ export MCP_CORS_ORIGIN="" # required allow-list if you bind to a non-lo # Required in HTTP mode — see "HTTP Mode Authentication" below for how to generate one export MCP_API_KEY="your_strong_random_secret" -# Required only for energy direct purchase; there is no built-in production URL +# Optional energy direct-purchase override; mainnet defaults to https://tegrow.ablesdxd.link export JUSTLEND_ENERGY_API_URL="https://energy-api.example" -# Temporary/custom endpoints also require this explicit trust opt-in +# Custom/test endpoints also require this explicit trust opt-in export JUSTLEND_ALLOW_UNTRUSTED_HOSTS="1" ``` -Energy direct purchase is fail-closed: load live limits with `get_energy_purchase_config`, obtain an authoritative `quote_energy_purchase`, show the exact payer/receivers/duration/TRX amount, and call `buy_energy_direct` with `confirmPayment=true` only after explicit confirmation. If submission is ambiguous, call `get_energy_payment_risk`; never sign a second payment while the first is unresolved. +Energy direct purchase is fail-closed: mainnet uses the official `https://tegrow.ablesdxd.link` service by default, while a non-mainnet signer requires a matching custom service. Load live limits with `get_energy_purchase_config`, obtain an authoritative `quote_energy_purchase`, show the exact payer/receivers/duration/TRX amount, and call `buy_energy_direct` with `confirmPayment=true` only after explicit confirmation. If submission is ambiguous or an idempotent response has no order token, query `get_energy_purchase_history` and then `get_energy_payment_risk`; never sign a second payment while the risk list is non-empty. + +After signing, an ambiguous result may store the exact signed request (signature plus raw transaction) in the local mode-`0600` `~/.mcp-server-justlend/energy-payment-risks.json` recovery file. The request remains broadcastable until expiry, is redacted from MCP output, and is removed only after public history confirms the payment/order or the backend deterministically rejects it before broadcast. ### HTTP Mode Authentication (`MCP_API_KEY`) @@ -372,7 +374,7 @@ npm run dev ## API Reference -### Tools (103 total) +### Tools (104 total) !!! info "V1 + V2" The first ten groups below are **JustLend V1** (pooled jToken market). The **JustLend V2** groups (vaults / markets / liquidation / dashboard / mining) and **Historical Records** follow. V2 tools are namespaced `moolah_*` / `get_moolah_*`. @@ -463,7 +465,8 @@ npm run dev | `return_energy_rental` | Cancel an active rental (with active order check) | **Yes** | | `get_energy_purchase_config` | Load live direct-purchase limits, durations, prices, and pool capacity | No | | `quote_energy_purchase` | Obtain an authoritative quote without creating or paying for an order | No | -| `get_energy_purchase_order` | Recover an order by order ID or payment transaction ID | No | +| `get_energy_purchase_order` | Query an order lifecycle by order ID, with an optional access token | No | +| `get_energy_purchase_history` | Query public in-progress and settled orders by payer address | No | | `get_energy_payment_risk` | Reconcile unresolved payer-scoped payment risks before another purchase | No | | `buy_energy_direct` | Sign a quote-bound TRX payment after `confirmPayment=true`; configured backend validates and may broadcast | **Yes** | @@ -673,7 +676,7 @@ Only `transient` is safe to auto-retry; every other code requires a corrective a → AI calls `get_energy_rent_info` to verify active rental → calls `return_energy_rental` → confirms refund **"Buy energy directly for these receiver addresses"** -→ AI calls `get_energy_purchase_config` → obtains `quote_energy_purchase` → shows payer, receivers, duration, and exact TRX amount → calls `buy_energy_direct` only after explicit confirmation → verifies with `get_energy_purchase_order`; ambiguous results route through `get_energy_payment_risk` before any retry +→ AI calls `get_energy_purchase_config` → obtains `quote_energy_purchase` → shows payer, receivers, duration, and exact TRX amount → calls `buy_energy_direct` only after explicit confirmation → verifies token-bearing results with `get_energy_purchase_order`; tokenless/ambiguous results route through `get_energy_purchase_history` and `get_energy_payment_risk` before any retry **"Stake 1000 TRX to earn sTRX rewards"** → AI uses `stake_trx` prompt: checks balance → checks exchange rate & APY → stakes TRX → verifies sTRX received diff --git a/docs/developers/justlend_v2.md b/docs/developers/justlend_v2.md index e6b09fe..4780663 100644 --- a/docs/developers/justlend_v2.md +++ b/docs/developers/justlend_v2.md @@ -43,7 +43,7 @@ V2 **vaults** are ERC4626 tokenized vaults that aggregate supply-side liquidity ### Liquidation -When a borrower's risk reaches the market `lltv`, anyone may liquidate through the **PublicLiquidatorProxy**: repay part of the debt (in the loan token) and seize the corresponding collateral at a discount. See `get_moolah_pending_liquidations` / `get_moolah_liquidation_quote` / `moolah_liquidate` in the [MCP server tool catalog](../ai_support/mcp_server.md#tools-103-total). +When a borrower's risk reaches the market `lltv`, anyone may liquidate through the **PublicLiquidatorProxy**: repay part of the debt (in the loan token) and seize the corresponding collateral at a discount. See `get_moolah_pending_liquidations` / `get_moolah_liquidation_quote` / `moolah_liquidate` in the [MCP server tool catalog](../ai_support/mcp_server.md#tools-104-total). ### Native TRX @@ -88,7 +88,7 @@ Addresses are the source-of-truth deployment config tracked in the MCP server's ## Using V2 via the MCP server -The [JustLend MCP Server](../ai_support/mcp_server.md) (current: v1.1.3) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-103-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). +The [JustLend MCP Server](../ai_support/mcp_server.md) (current: v1.1.3) exposes the full V2 surface under `moolah_*` / `get_moolah_*` tools — vaults, markets, liquidation, dashboard/history, and mining — plus four guided prompts (`moolah_supply`, `moolah_borrow`, `moolah_liquidate`, `moolah_portfolio`). See the [V2 tool groups](../ai_support/mcp_server.md#tools-104-total) and the [MCP Tool Catalog](../documents/aidocs/mcp_tools.md). Contract ABIs (`MOOLAH_CORE_ABI`, `TRX_PROVIDER_ABI`, `MOOLAH_VAULT_ABI`, `PUBLIC_LIQUIDATOR_ABI`) are bundled in the MCP repo's [`src/core/abis.ts`](https://github.com/justlend/mcp-server-justlend/blob/main/src/core/abis.ts). For the full on-chain ABIs and contract data structures (`Position`, `MarketParams`, `MarketConfig`, `MarketAllocation`, …), see the [SBM V2 contract reference](supply_and_borrow_market/sbmV2.md). diff --git a/docs/documents/aidocs/mcp_tools.md b/docs/documents/aidocs/mcp_tools.md index 4e1bf18..cf7c49b 100644 --- a/docs/documents/aidocs/mcp_tools.md +++ b/docs/documents/aidocs/mcp_tools.md @@ -29,10 +29,10 @@ This docs-local page wraps the generated catalog from the MCP repository so RAG | User intent | Prefer these MCP tools | Safety class | |-------------|------------------------|--------------| | Market list, APY, TVL, utilization | `get_supported_markets`, `get_market_data`, `get_all_markets` | Read-only | -| Wallet and account risk | `get_wallet_address`, `get_account_summary`, `get_balances` | Read-only / wallet read | +| Wallet and account risk | `get_wallet_address`, `get_account_summary`, `get_wallet_balances` | Read-only / wallet read | | Supply, borrow, repay, withdraw | `supply`, `borrow`, `repay`, `withdraw`, `withdraw_all`, `estimate_lending_energy` | Writes require HITL | | sTRX staking | `get_strx_dashboard`, `get_strx_account`, `stake_trx_to_strx`, `unstake_strx`, `claim_strx_rewards` | Writes require HITL | -| Energy rental / direct purchase | `get_energy_rental_dashboard`, `rent_energy`, `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_payment_risk`, `buy_energy_direct` | Writes require HITL; direct purchase is quote-bound | +| Energy rental / direct purchase | `get_energy_rental_dashboard`, `rent_energy`, `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_history`, `get_energy_payment_risk`, `buy_energy_direct` | Writes require HITL; direct purchase is quote-bound | Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “查看我的仓位/健康度” maps to account summary; “帮我存款/借款/还款/赎回/质押/租能量/买能量” maps to write tools and must require explicit confirmation. @@ -44,7 +44,7 @@ Chinese query aliases: “查询市场/APY/TVL” maps to market read tools; “ > > Lets an AI agent plan tool routing offline without connecting to the server. Side-effect classes align with the AI-Agent documentation standard baseline (Safe / Network Read / Remote Write / Destructive). -**Total tools**: 103 | **Protocol**: MCP | **Transport**: stdio / HTTP(SSE) +**Total tools**: 104 | **Protocol**: MCP | **Transport**: stdio / HTTP(SSE) ## Common structured output contract (v1.0.0) @@ -60,7 +60,7 @@ Every tool declares an MCP `outputSchema`. Successful calls preserve the legacy Consume `structuredContent` when available; older clients may continue parsing the first text content item. Error results keep `isError: true` and the existing structured JSON error body. -**Read-only tools**: 62 | **Write tools**: 41 (of which marked destructive: 28) +**Read-only tools**: 63 | **Write tools**: 41 (of which marked destructive: 28) > ⚠️ Tools marked 🔴 **sign and broadcast TRON transactions that move real assets** — the client MUST require human confirmation (HITL) before executing. 🟡 tools only change local wallet/network config or start an interaction. Private keys are managed encrypted by `@bankofai/agent-wallet` and are **never passed as tool arguments**. The legacy unauthenticated browser-wallet bridge is disabled. @@ -621,14 +621,14 @@ Consume `structuredContent` when available; older clients may continue parsing t | `proposalId` | number | ✅ | | The proposal ID to withdraw votes from | | `network` | string | — | | Network. Default: mainnet | -## Energy Rental (14) +## Energy Rental (15) ### `get_energy_purchase_config` **Energy Purchase Config** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Get live energy direct-purchase limits, supported durations, current unit prices, and pool capacity. Requires JUSTLEND_ENERGY_API_URL; there is intentionally no production URL or economic fallback. +- **Description**: Get live energy direct-purchase limits, supported durations, current unit prices, and pool capacity. Uses the official JustLend production API by default; JUSTLEND_ENERGY_API_URL overrides it. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - **Params**: none @@ -659,6 +659,20 @@ Consume `structuredContent` when available; older clients may continue parsing t | `orderId` | union | ✅ | | Energy purchase order id | | `orderToken` | string (min len 1) | — | | Optional X-Consumer-Order-Token returned when the order was accepted | +### `get_energy_purchase_history` + +**Energy Purchase History** +- **Side effect**: 🟢 Read-only (Safe / Network Read) +- **annotations**: idempotent: true · openWorld: true +- **Description**: Get public direct-purchase history for a payer address, including in-progress and settled orders. Use it to recover an accepted order when an idempotent retry returns no access token. +- **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) + +| Param | Type | Required | Default | Description | +|-------|------|:--------:|---------|-------------| +| `address` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | — | | Payer address. Default: configured wallet | +| `page` | number (min 0) | — | | History page (1-based; used with size) | +| `size` | number (min 0) | — | | Rows per page; omit for the backend default/all-history view | + ### `get_energy_payment_risk` **Energy Payment Risk** diff --git a/docs/index.md b/docs/index.md index 4dfc9be..65500ef 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,7 +21,7 @@ description: Official documentation for JustLend DAO — the largest lending pro - **Users:** [Overview](getting_started/overview.md) · [Supply](getting_started/concepts/supply.md) · [Borrow](getting_started/concepts/borrow.md) · [Liquidations](getting_started/concepts/liquidations.md) · [Risks](getting_started/concepts/risks.md) - **Developers:** [Contracts Overview](developers/contracts_overview.md) · [SBM reference](developers/supply_and_borrow_market/sbm.md) · [Deployed Contracts](developers/deployed_contracts.md) · [APIs](developers/apis.md) -- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (103 tools)](ai_support/mcp_server.md) · [Skills (6 workflows + 9 bundled read-only tools)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) +- **AI Agents:** [`/llms.txt`](llms.txt) · [`/llms-full.txt`](llms-full.txt) · [`/developers/contracts.json`](developers/contracts.json) · [OpenAPI 3.1 YAML](developers/apis/justlend_apis.yaml) · [JSON ABI catalog](developers/abis/index.md) · [AI / LLMs page](ai_support/ai_llms.md) · [Full MCP Server (104 tools)](ai_support/mcp_server.md) · [Skills (6 workflows + 9 bundled read-only tools)](ai_support/justlend_skills.md) · [CLI and V2 SDK](ai_support/cli_and_sdk.md) - **Governance:** [JIPs](governance/jips.md) · [Tokenomics (JST)](governance/tokenomics.md) · [Forum](https://forum.justlend.org) ## External diff --git a/docs/llms-full.txt b/docs/llms-full.txt index feae5c1..0aedcb2 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -462,7 +462,7 @@ Built-in MCP tools (all read-only): `get_all_markets`, `get_dashboard`, `get_sup ### 7.2 Full MCP Server — `@justlend/mcp-server-justlend` -Read + write MCP server, **103 tools**, version **v1.1.3**. Repo: . Covers **JustLend V1 and V2** — including quote-bound energy direct purchase with payer-scoped recovery, plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. Every tool declares a common success `outputSchema`; successful calls preserve text content and add `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`. The generated [`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) lists input/output contracts and side-effect classes for offline routing. +Read + write MCP server, **104 tools**, version **v1.1.3**. Repo: . Covers **JustLend V1 and V2** — including quote-bound energy direct purchase with public payer-history and payer-scoped recovery, plus `moolah_*` / `get_moolah_*` for V2 vaults, isolated markets, liquidation, dashboard/history, and mining. Every tool declares a common success `outputSchema`; successful calls preserve text content and add `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`. The generated [`mcp-api-list.md`](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) lists input/output contracts and side-effect classes for offline routing. Capability domains: @@ -472,7 +472,7 @@ Capability domains: - **Lending Operations** (10 tools) — `supply`, `withdraw`, `withdraw_all`, `borrow`, `repay`, `enter_market`, `exit_market`, `approve_underlying`, `claim_rewards`, `estimate_lending_energy`. Write tools marked with `destructiveHint: true`. - **Mining & Rewards** (3 tools) — `get_mining_rewards`, `get_usdd_mining_config`, `get_wbtc_mining_config`. - **JST Voting / Governance** (10 tools) — `get_proposal_list`, `get_user_vote_status`, `get_vote_info`, `get_locked_votes`, `check_jst_allowance_for_voting`, `approve_jst_for_voting`, `deposit_jst_for_votes`, `withdraw_votes_to_jst`, `cast_vote`, `withdraw_votes_from_proposal`. -- **Energy Rental / Direct Purchase** (14 tools) — nine rental tools plus `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_order`, `get_energy_payment_risk`, and explicitly confirmed `buy_energy_direct`. Direct purchase has no built-in service URL or economic fallback; it is quote-bound, stores only public risk identifiers, and never permits a second payment while the first result is ambiguous. +- **Energy Rental / Direct Purchase** (15 tools) — nine rental tools plus `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_order`, `get_energy_purchase_history`, `get_energy_payment_risk`, and explicitly confirmed `buy_energy_direct`. Mainnet uses `https://tegrow.ablesdxd.link` by default; non-mainnet requires a matching custom service. Direct purchase is quote-bound and, after signing, an ambiguous result may retain the exact signed request in a local mode-`0600` recovery file. The request is redacted from output and removed after public-history reconciliation or deterministic pre-broadcast rejection; a non-empty risk list blocks a second payment. - **sTRX Staking** (7 tools) — dashboard, account, balance, withdrawal-eligibility check, `stake_trx_to_strx`, `unstake_strx`, `claim_strx_rewards`. Staking paths use precision-safe string/BigInt math for TRX Sun conversion and 18-decimal sTRX balances/exchange-rate display. - **Transfers** (2 tools) — `transfer_trx`, `transfer_trc20`. - **General TRON utilities** (via the same tool set) — balances, blocks, transactions, contract read/write, multicall, TRC20/TRC721/TRC1155 metadata, transfers, Stake 2.0 freeze/unfreeze, address conversion, wallet management, message signing. @@ -492,7 +492,7 @@ Guided prompts ship with the server (14 total): `getting_started`, `supply_asset Source-installable CLI, version **v1.0.1**. Repo: . It is not currently published to npm: clone the official repository, run `npm ci && npm run build`, then `npm link`. -- 31 top-level command groups cover V1/V2 reads and writes, staking, energy rental, governance, rewards, history, portfolio, and simulation. +- 30 top-level command groups cover V1/V2 reads and writes, staking, energy rental, governance, rewards, history, portfolio, and simulation. Nested `energy purchase history ` recovers public in-progress and settled direct-purchase orders. - Use `--json` and branch on the process exit code for agents and CI. Success is `{ schemaVersion: "1.0.0", success: true, data }`; failure is `{ schemaVersion, success: false, error, code, retryable, hint? }`, including parser/usage failures. Validate with `schemas/output-v1.schema.json`; never scrape human tables. - Run `--dry-run --dry-run-owner
` before any write; dry-run does not sign or broadcast. - `--no-broadcast` signs without sending for supported write commands. Energy direct purchase rejects it because the configured backend controls broadcast; use a quote or `--dry-run` before the explicitly confirmed purchase. Mainnet broadcasts require explicit user intent; never add `--yes` automatically. diff --git a/docs/llms.txt b/docs/llms.txt index feb8567..dee949d 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -60,15 +60,15 @@ - [MCP Safety Policy](https://docs.justlend.org/documents/aidocs/mcp_safety): Read-only vs write tools, wallet modes, private-key handling, and HITL confirmation. - [Common Questions](https://docs.justlend.org/documents/aidocs/common_questions): English and Chinese user questions mapped to tools and API sources. - [AI Glossary](https://docs.justlend.org/documents/aidocs/glossary): Compact definitions for JustLend / Compound V2 terms. -- [MCP Tool Catalog](https://docs.justlend.org/documents/aidocs/mcp_tools): Full generated catalog of all 103 MCP tools with schemas and safety annotations. +- [MCP Tool Catalog](https://docs.justlend.org/documents/aidocs/mcp_tools): Full generated catalog of all 104 MCP tools with schemas and safety annotations. ## AI Agent integration - [AI / LLMs](https://docs.justlend.org/ai_support/ai_llms): Human-readable directory for `llms.txt`, `llms-full.txt`, OpenAPI, contract JSON, and ABI JSON endpoints. - [JustLend Skills](https://docs.justlend.org/ai_support/justlend_skills) (v1.1.1): GitHub-distributed workflow skills project (**6 modules**) plus a bundled read-only MCP server (**9 query tools**) with versioned `outputSchema`, `structuredContent`, and machine-readable retry errors. Write workflows route to the full MCP server and require confirmation. Clone and run `bash install.sh`; the local identifier `@justlend/justlend-skills` is **not published to npm**. - [CLI and V2 SDK integration guide](https://docs.justlend.org/ai_support/cli_and_sdk): Choose terminal/CI automation or embedded application integration; includes installation, version, output contract, signing, and broadcast safety rules. -- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **103 tools**): Full read/write MCP server for JustLend V1 and V2, including quote-bound energy direct purchase with payer-scoped recovery. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Writes use encrypted agent-wallet; the legacy unauthenticated browser bridge is disabled. Source: . -- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 103 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. +- [Full MCP Server](https://docs.justlend.org/ai_support/mcp_server) (`@justlend/mcp-server-justlend`, v1.1.3, **104 tools**): Full read/write MCP server for JustLend V1 and V2, including quote-bound energy direct purchase with public payer-history and payer-scoped recovery. Every tool declares `outputSchema`; successful calls expose `{schemaVersion, tool, result}` in `structuredContent` while preserving legacy text. Writes use encrypted agent-wallet; the legacy unauthenticated browser bridge is disabled. Source: . +- [MCP machine-readable tool catalog](https://github.com/justlend/mcp-server-justlend/blob/main/mcp-api-list.md) (`mcp-api-list.md`): Offline-loadable list of all 104 tools with input/output schemas, side-effect class (read-only vs on-chain write/destructive), and HITL guidance. Generated from source, so it never drifts from the tool definitions. - [MCP source ABIs and network config](https://github.com/justlend/mcp-server-justlend): Upstream TypeScript definitions used to generate the docs JSON ABI and address files. ## API endpoints (read-only HTTP API) diff --git a/scripts/verify-ai-consistency.mjs b/scripts/verify-ai-consistency.mjs index a9c873b..96c6907 100755 --- a/scripts/verify-ai-consistency.mjs +++ b/scripts/verify-ai-consistency.mjs @@ -66,9 +66,9 @@ const requiredSnippets = { 'docs/index.md': ['18 active + 6 legacy = 24', 'justlend-cli', 'justlend-utils-v2'], 'docs/getting_started/overview.md': ['18 active + 6 legacy = 24'], 'docs/developers/contracts_overview.md': ['18 active + 6 legacy = 24', 'per market, 23 instances'], - 'docs/ai_support/mcp_server.md': ['v1.1.3', '24 jToken markets in total', '| jU', '`outputSchema`', '`structuredContent`'], + 'docs/ai_support/mcp_server.md': ['v1.1.3', '104 tools', '24 jToken markets in total', '| jU', '`outputSchema`', '`structuredContent`', 'get_energy_purchase_history', 'https://tegrow.ablesdxd.link', 'exact signed request'], 'docs/ai_support/justlend_skills.md': ['`1.1.1`', '6 structured skill modules', 'justlend-energy-purchase', '8 static shortcuts', '`structuredContent`', '`rate_limit`'], - 'docs/ai_support/cli_and_sdk.md': ['justlend/justlend-cli', '`1.0.1`', 'schemas/output-v1.schema.json', 'justlend/justlend-utils-v2', '--dry-run'], + 'docs/ai_support/cli_and_sdk.md': ['justlend/justlend-cli', '`1.0.1`', '30 top-level command groups', 'energy purchase history ', 'schemas/output-v1.schema.json', 'justlend/justlend-utils-v2', '--dry-run'], 'docs/llms.txt': ['justlend-cli', 'v1.1.3', 'v1.1.1', 'justlend-utils-v2', '/lend/account?addresses={address}'], 'docs/llms-full.txt': ['JustLend CLI — deterministic terminal automation', 'v1.0.1', 'v1.1.3', 'v1.1.1', 'JustLend V2 Utils'], 'docs/documents/aidocs/source_of_truth.md': ['JustLend CLI', 'JustLend V2 Utils'], @@ -94,12 +94,17 @@ check( 'MCP catalog must identify upstream version 1.1.3', ); check( - (mcpCatalog.match(/^### `[^`]+`$/gm) ?? []).length === 103, - 'MCP catalog must contain exactly 103 generated tool headings', + (mcpCatalog.match(/^### `[^`]+`$/gm) ?? []).length === 104, + 'MCP catalog must contain exactly 104 generated tool headings', ); check( - (mcpCatalog.match(/^- \*\*Output schema\*\*:/gm) ?? []).length === 103, - 'MCP catalog must document output schema coverage for all 103 tools', + (mcpCatalog.match(/^- \*\*Output schema\*\*:/gm) ?? []).length === 104, + 'MCP catalog must document output schema coverage for all 104 tools', +); +check(mcpCatalog.includes('### `get_energy_purchase_history`'), 'MCP catalog must expose public energy purchase history'); +check( + mcpCatalog.includes('Uses the official JustLend production API by default'), + 'MCP catalog must document the official production API default', ); const hook = await read('hooks/copy_dotfiles.py'); From 271564090cbf803249c8d4a6ac0470181e2b8d13 Mon Sep 17 00:00:00 2001 From: BlackChar92 Date: Thu, 27 Aug 2026 16:24:25 +0800 Subject: [PATCH 7/7] docs(mcp): align payment-risk inspection contract - Refresh the generated catalog from MCP PR #30.\n- Document the no-argument configured-wallet risk check.\n- Keep recovery replay behind a separately confirmed purchase call. --- CHANGELOG.md | 2 +- docs/ai_support/justlend_skills.md | 6 +++--- docs/ai_support/mcp_server.md | 10 +++++----- docs/documents/aidocs/mcp_safety.md | 2 +- docs/documents/aidocs/mcp_tools.md | 8 ++------ docs/llms-full.txt | 2 +- scripts/verify-ai-consistency.mjs | 8 ++++++++ 7 files changed, 21 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0c8c3c..9fc14f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,7 @@ For the JustLend protocol itself, see governance proposals on [forum.justlend.or - Reconciled the market inventory to **24 total (18 active + 6 legacy)** after expanding `app.justlend.org/marketNew` and cross-checking `/lend/jtoken` plus the MCP chain catalog; added the previously omitted active `jU` market everywhere. - Corrected `/lend/account`: `addresses` is optional, omission returns the global account index, and the endpoint-specific default `pageSize` is 50. - Added verification provenance and freshness metadata to `contracts.json` and its JSON Schema. -- Aligned MCP, CLI, and Skills guidance with the official mainnet energy API default, public payer-history recovery, tokenless idempotent orders, exact signed-request persistence, and the CLI's actual 30 top-level command groups. +- Aligned MCP, CLI, and Skills guidance with the official mainnet energy API default, public payer-history recovery, tokenless idempotent orders, exact signed-request persistence, the configured-wallet/no-argument payment-risk check, and the CLI's actual 30 top-level command groups. ### Added — 2026-05-22 API-style + reference-gap pass diff --git a/docs/ai_support/justlend_skills.md b/docs/ai_support/justlend_skills.md index 9a9a0c0..243d0e1 100644 --- a/docs/ai_support/justlend_skills.md +++ b/docs/ai_support/justlend_skills.md @@ -47,7 +47,7 @@ The project includes 6 structured skill modules in the `/skills` directory that | **justlend-lending-v2** | JustLend V2 (Moolah) isolated markets + ERC4626 vaults: supply/borrow/liquidate | Full MCP Server | | **justlend-trx-staking** | Stake TRX for sTRX liquid staking tokens | Full MCP Server | | **justlend-energy-rental** | Rent TRON Energy at discounted rates (50-80% cheaper) | Full MCP Server | -| **justlend-energy-purchase** | Quote, confirm, track, and reconcile direct Energy purchases | Full MCP Server | +| **justlend-energy-purchase** | Quote, confirm, track, and safely inspect unresolved direct Energy purchases | Full MCP Server | | **justlend-governance-v1** | View proposals, deposit JST for voting power, cast votes | Full MCP Server | The read-only portions of `justlend-lending-v1` work with the built-in 9 query tools. Its write flows and the other five skills require the [full MCP server](mcp_server.md) for tool execution. @@ -253,10 +253,10 @@ Rent TRON Energy from the JustLend marketplace at 50-80% lower cost than burning ### Energy Direct Purchase (justlend-energy-purchase) -Obtain an authoritative quote, confirm the exact `total_sun` payment, submit it for backend-controlled broadcast, track token-bearing orders, recover tokenless results through public payer history, and reconcile ambiguous payment results before initiating another purchase. +Obtain an authoritative quote, confirm the exact `total_sun` payment, submit it for backend-controlled broadcast, track token-bearing orders, recover tokenless results through public payer history, and inspect the configured wallet’s unresolved risk state before initiating another purchase. !!! warning - This skill requires the [full MCP server](mcp_server.md) and a signing wallet. Mainnet uses the official `https://tegrow.ablesdxd.link` endpoint by default; a custom/test or non-mainnet service must be configured explicitly. Never expose a private key or signed transaction in tool output. The full server may retain the exact signed request in a local mode-`0600` recovery file after an ambiguous submission; never retry with a second payment while payment risk is unresolved. + This skill requires the [full MCP server](mcp_server.md) and a signing wallet. Mainnet uses the official `https://tegrow.ablesdxd.link` endpoint by default; a custom/test or non-mainnet service must be configured explicitly. Never expose a private key or signed transaction in tool output. The full server may retain the exact signed request in a local mode-`0600` recovery file after an ambiguous submission. The no-argument risk check is read-only and never replays it; never retry with a second payment while payment risk is unresolved. ### DAO Governance (justlend-governance-v1) diff --git a/docs/ai_support/mcp_server.md b/docs/ai_support/mcp_server.md index 06f3a72..c0b3465 100644 --- a/docs/ai_support/mcp_server.md +++ b/docs/ai_support/mcp_server.md @@ -33,7 +33,7 @@ Beyond JustLend-specific operations, the server also exposes a full set of **gen Current version (**v1.1.3**) covers **JustLend V1** *and* **JustLend V2**. V1 is the Compound-V2-style pooled supply/borrow market (jTokens); V2 is an isolated-market + ERC4626-vault protocol. The two surfaces are namespaced — V1 tools like `get_market_data` / `supply`, V2 tools prefixed `moolah_*` / `get_moolah_*` (the `moolah` identifier is V2's on-chain/tool naming). See the [JustLend V2](../developers/justlend_v2.md) developer page for the protocol model and deployed contracts. !!! tip "v1.1.3 Update" - **v1.1.3** makes every one of the **104 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. It also adds six fail-closed energy direct-purchase tools for configuration, quote, public payer history, order recovery, payment-risk reconciliation, and explicitly confirmed purchase; reconciles the V1 inventory to **24 markets (18 active + 6 legacy)**; and restores active `jU` to the product table. The legacy unauthenticated browser-wallet bridge is disabled, so writes use encrypted agent-wallet signing. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. + **v1.1.3** makes every one of the **104 tools** declare an MCP `outputSchema`. Successful calls preserve legacy text content and also expose `{ schemaVersion: "1.0.0", tool, result }` in `structuredContent`, so agents no longer need to infer output shape from prose. It also adds six fail-closed energy direct-purchase tools for configuration, quote, public payer history, order recovery, configured-wallet payment-risk inspection, and explicitly confirmed purchase; reconciles the V1 inventory to **24 markets (18 active + 6 legacy)**; and restores active `jU` to the product table. The legacy unauthenticated browser-wallet bridge is disabled, so writes use encrypted agent-wallet signing. **v1.1.2** added native **TRX ↔ WTRX** wrap/unwrap (`wrap_trx` / `unwrap_trx`), hardened TRC20 approvals, and added `retryable` error classification. **v1.1.0** introduced the V2 tool and prompt surface. ## Overview @@ -200,9 +200,9 @@ export JUSTLEND_ENERGY_API_URL="https://energy-api.example" export JUSTLEND_ALLOW_UNTRUSTED_HOSTS="1" ``` -Energy direct purchase is fail-closed: mainnet uses the official `https://tegrow.ablesdxd.link` service by default, while a non-mainnet signer requires a matching custom service. Load live limits with `get_energy_purchase_config`, obtain an authoritative `quote_energy_purchase`, show the exact payer/receivers/duration/TRX amount, and call `buy_energy_direct` with `confirmPayment=true` only after explicit confirmation. If submission is ambiguous or an idempotent response has no order token, query `get_energy_purchase_history` and then `get_energy_payment_risk`; never sign a second payment while the risk list is non-empty. +Energy direct purchase is fail-closed: mainnet uses the official `https://tegrow.ablesdxd.link` service by default, while a non-mainnet signer requires a matching custom service. Load live limits with `get_energy_purchase_config`, obtain an authoritative `quote_energy_purchase`, show the exact payer/receivers/duration/TRX amount, and call `buy_energy_direct` with `confirmPayment=true` only after explicit confirmation. If submission is ambiguous or an idempotent response has no order token, query `get_energy_purchase_history` and then call `get_energy_payment_risk` with no arguments. The risk check is read-only, is scoped to the configured wallet, and never replays a stored payment. Never sign a second payment while the risk list is non-empty; replay/reconciliation is allowed only inside a separately user-confirmed `buy_energy_direct` recovery attempt. -After signing, an ambiguous result may store the exact signed request (signature plus raw transaction) in the local mode-`0600` `~/.mcp-server-justlend/energy-payment-risks.json` recovery file. The request remains broadcastable until expiry, is redacted from MCP output, and is removed only after public history confirms the payment/order or the backend deterministically rejects it before broadcast. +After signing, an ambiguous result may store the exact signed request (signature plus raw transaction) in the local mode-`0600` `~/.mcp-server-justlend/energy-payment-risks.json` recovery file. The request remains broadcastable until expiry, is redacted from MCP output, and is removed only after public history confirms the payment/order or the backend deterministically rejects it before broadcast. `get_energy_payment_risk` only observes this state; it cannot clear or replay the request. ### HTTP Mode Authentication (`MCP_API_KEY`) @@ -467,7 +467,7 @@ npm run dev | `quote_energy_purchase` | Obtain an authoritative quote without creating or paying for an order | No | | `get_energy_purchase_order` | Query an order lifecycle by order ID, with an optional access token | No | | `get_energy_purchase_history` | Query public in-progress and settled orders by payer address | No | -| `get_energy_payment_risk` | Reconcile unresolved payer-scoped payment risks before another purchase | No | +| `get_energy_payment_risk` | Report configured-wallet payment risks without replaying a signed payment; accepts no arguments | No | | `buy_energy_direct` | Sign a quote-bound TRX payment after `confirmPayment=true`; configured backend validates and may broadcast | **Yes** | #### sTRX Staking @@ -676,7 +676,7 @@ Only `transient` is safe to auto-retry; every other code requires a corrective a → AI calls `get_energy_rent_info` to verify active rental → calls `return_energy_rental` → confirms refund **"Buy energy directly for these receiver addresses"** -→ AI calls `get_energy_purchase_config` → obtains `quote_energy_purchase` → shows payer, receivers, duration, and exact TRX amount → calls `buy_energy_direct` only after explicit confirmation → verifies token-bearing results with `get_energy_purchase_order`; tokenless/ambiguous results route through `get_energy_purchase_history` and `get_energy_payment_risk` before any retry +→ AI calls `get_energy_purchase_config` → obtains `quote_energy_purchase` → shows payer, receivers, duration, and exact TRX amount → calls `buy_energy_direct` only after explicit confirmation → verifies token-bearing results with `get_energy_purchase_order`; tokenless/ambiguous results route through public history and the no-argument, read-only `get_energy_payment_risk` check before any explicitly confirmed recovery attempt **"Stake 1000 TRX to earn sTRX rewards"** → AI uses `stake_trx` prompt: checks balance → checks exchange rate & APY → stakes TRX → verifies sTRX received diff --git a/docs/documents/aidocs/mcp_safety.md b/docs/documents/aidocs/mcp_safety.md index 8007350..f045127 100644 --- a/docs/documents/aidocs/mcp_safety.md +++ b/docs/documents/aidocs/mcp_safety.md @@ -40,7 +40,7 @@ Before any on-chain write tool, the agent must show: Then ask for explicit confirmation. -For `buy_energy_direct`, the confirmation must be tied to the authoritative quote: show payer, every receiver, duration, and exact TRX amount. The configured backend validates and may broadcast the signed payment. If the result is ambiguous, call `get_energy_payment_risk` and do not sign a second payment while the first remains unresolved. +For `buy_energy_direct`, the confirmation must be tied to the authoritative quote: show payer, every receiver, duration, and exact TRX amount. The configured backend validates and may broadcast the signed payment. If the result is ambiguous, query public payer history and call `get_energy_payment_risk` with no arguments. That configured-wallet check is read-only and never replays a stored payment. Do not sign a second payment while the first remains unresolved; any recovery replay must happen only inside a separately confirmed `buy_energy_direct` call. ## Private key rule diff --git a/docs/documents/aidocs/mcp_tools.md b/docs/documents/aidocs/mcp_tools.md index cf7c49b..1aeb006 100644 --- a/docs/documents/aidocs/mcp_tools.md +++ b/docs/documents/aidocs/mcp_tools.md @@ -678,13 +678,9 @@ Consume `structuredContent` when available; older clients may continue parsing t **Energy Payment Risk** - **Side effect**: 🟢 Read-only (Safe / Network Read) - **annotations**: idempotent: true · openWorld: true -- **Description**: Reconcile and return unresolved direct-purchase payment risks. If any result remains, do not sign a new payment. +- **Description**: Return unresolved direct-purchase payment risks for the configured wallet without replaying a signed payment. If any result remains, do not sign a new payment. - **Output schema**: common structured envelope v1.0.0 (`schemaVersion`, `tool`, `result`) - -| Param | Type | Required | Default | Description | -|-------|------|:--------:|---------|-------------| -| `address` | string (pattern /^T[1-9A-HJ-NP-Za-km-z]{33}$/) | — | | Payer address. Default: configured wallet | -| `network` | string | — | | Network used to query the payment transaction. Default: configured network | +- **Params**: none ### `buy_energy_direct` diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 0aedcb2..952531e 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -472,7 +472,7 @@ Capability domains: - **Lending Operations** (10 tools) — `supply`, `withdraw`, `withdraw_all`, `borrow`, `repay`, `enter_market`, `exit_market`, `approve_underlying`, `claim_rewards`, `estimate_lending_energy`. Write tools marked with `destructiveHint: true`. - **Mining & Rewards** (3 tools) — `get_mining_rewards`, `get_usdd_mining_config`, `get_wbtc_mining_config`. - **JST Voting / Governance** (10 tools) — `get_proposal_list`, `get_user_vote_status`, `get_vote_info`, `get_locked_votes`, `check_jst_allowance_for_voting`, `approve_jst_for_voting`, `deposit_jst_for_votes`, `withdraw_votes_to_jst`, `cast_vote`, `withdraw_votes_from_proposal`. -- **Energy Rental / Direct Purchase** (15 tools) — nine rental tools plus `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_order`, `get_energy_purchase_history`, `get_energy_payment_risk`, and explicitly confirmed `buy_energy_direct`. Mainnet uses `https://tegrow.ablesdxd.link` by default; non-mainnet requires a matching custom service. Direct purchase is quote-bound and, after signing, an ambiguous result may retain the exact signed request in a local mode-`0600` recovery file. The request is redacted from output and removed after public-history reconciliation or deterministic pre-broadcast rejection; a non-empty risk list blocks a second payment. +- **Energy Rental / Direct Purchase** (15 tools) — nine rental tools plus `get_energy_purchase_config`, `quote_energy_purchase`, `get_energy_purchase_order`, `get_energy_purchase_history`, `get_energy_payment_risk`, and explicitly confirmed `buy_energy_direct`. Mainnet uses `https://tegrow.ablesdxd.link` by default; non-mainnet requires a matching custom service. Direct purchase is quote-bound and, after signing, an ambiguous result may retain the exact signed request in a local mode-`0600` recovery file. The request is redacted from output and removed after public-history reconciliation or deterministic pre-broadcast rejection. The no-argument `get_energy_payment_risk` tool only reports unresolved state for the configured wallet and never replays a payment; a non-empty risk list blocks a second payment. - **sTRX Staking** (7 tools) — dashboard, account, balance, withdrawal-eligibility check, `stake_trx_to_strx`, `unstake_strx`, `claim_strx_rewards`. Staking paths use precision-safe string/BigInt math for TRX Sun conversion and 18-decimal sTRX balances/exchange-rate display. - **Transfers** (2 tools) — `transfer_trx`, `transfer_trc20`. - **General TRON utilities** (via the same tool set) — balances, blocks, transactions, contract read/write, multicall, TRC20/TRC721/TRC1155 metadata, transfers, Stake 2.0 freeze/unfreeze, address conversion, wallet management, message signing. diff --git a/scripts/verify-ai-consistency.mjs b/scripts/verify-ai-consistency.mjs index 96c6907..7da5344 100755 --- a/scripts/verify-ai-consistency.mjs +++ b/scripts/verify-ai-consistency.mjs @@ -102,6 +102,14 @@ check( 'MCP catalog must document output schema coverage for all 104 tools', ); check(mcpCatalog.includes('### `get_energy_purchase_history`'), 'MCP catalog must expose public energy purchase history'); +const riskSection = mcpCatalog.match(/### `get_energy_payment_risk`[\s\S]*?(?=\n### `)/)?.[0] ?? ''; +check( + riskSection.includes('for the configured wallet without replaying a signed payment') && + riskSection.includes('**Params**: none') && + !riskSection.includes('| `address` |') && + !riskSection.includes('| `network` |'), + 'MCP payment-risk docs must be no-argument, configured-wallet-only, and read-only', +); check( mcpCatalog.includes('Uses the official JustLend production API by default'), 'MCP catalog must document the official production API default',