Teardrop

io.github.HASAVAGE由 GitHub 帳號 HASAVAGE 發布v1.0.0更新於 Oct 24, 2026

Teardrop MCP gateway: paid tools for autonomous agents (x402, credits).

已驗證Streamable HTTP可網頁執行效率與工作流商業與電商AI 與機器學習

概覽

AI 產生的概覽

Teardrop 是付費 MCP 閘道,讓代理使用按次計費的平台工具、代理間委派,以及排程或事件觸發的代理執行。

可以做什麼
Teardrop 透過 /tools/mcp 的 MCP 閘道提供 31 個面向呼叫方的內建工具,按次計費,代理也可在執行過程中呼叫這些工具。它支援代理間委派:用 discover_agents 尋找可選專家,用 delegate_to_agent 委派任務,並具備允許清單、配額、成本上限與信用計費。組織還能安排週期性無人值守執行、註冊 webhook 事件觸發器、把外部 MCP 伺服器發佈為商品,並以 USDC 結算作者收益。
適用情境
當助理需要呼叫按次計費的第三方或平台工具而不想逐一介接、需要把任務委派給其他代理,或需要具備歷史紀錄與回呼的排程與 webhook 觸發任務時,值得加入。它適合想要具備計費、配額與信譽中繼資料的託管閘道,而非自行維護工具伺服器的團隊。
執行需求
遠端 streamable HTTP 端點 說明的自架部署需要 Python 3.12+、Postgres 資料庫、LLM 供應商 API 金鑰(例如 OPENROUTER_API_KEY、ANTHROPIC_API_KEY、OPENAI_API_KEY 或 GOOGLE_API_KEY)、選用的 Redis,以及 JWT 用戶端憑證(JWT_CLIENT_ID、JWT_CLIENT_SECRET)。驗證方式為 Bearer 權杖、SIWE 或 x402 付款。
安裝前請注意
工具是付費的:按次呼叫或在執行的用量成本中計費,需要 x402 或預付信用結算,並受滾動支出上限約束,例如 MACHINE_ORG_DAILY_SPEND_LIMIT_USDC。憑證包括 JWT_CLIENT_SECRET、LLM 供應商 API 金鑰,以及之後無法再次取得的一次性 client_secret。SIWE 與結算錢包用於收益與提領。事件觸發器會把不受信任的 webhook 內容插入提示詞,X 廣播貼文會公開發佈輸出內容。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Teardrop,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/io.github.HASAVAGE%2Fteardrop/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "teardrop": {
      "type": "http",
      "url": "https://api.teardrop.dev/tools/mcp"
    }
  }
}

README

████████╗███████╗ █████╗ ██████╗ ██████╗ ██████╗  ██████╗ ██████╗╚══██╔══╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔═══██╗██╔══██╗   ██║   █████╗  ███████║██████╔╝██║  ██║██████╔╝██║   ██║██████╔╝   ██║   ██╔══╝  ██╔══██║██╔══██╗██║  ██║██╔══██╗██║   ██║██╔═══╝   ██║   ███████╗██║  ██║██║  ██║██████╔╝██║  ██║╚██████╔╝██║   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚═╝

Teardrop is a streaming API for applications and software agents to run tool-using AI workflows. Clients submit a message or task; Teardrop orchestrates a configured LLM (Anthropic, OpenAI, Google, or OpenRouter) and available tools, then streams structured results and UI events over Server-Sent Events (SSE). It supports AG-UI for streaming interaction, A2A for agent discovery and delegation, MCP for tool access, and optional x402 pay-per-request USDC settlement on Base.


Core Features

Agent-to-Agent (A2A) Delegation

Agents can discover opt-in specialists with the zero-cost discover_agents tool, including active published tool names, and securely delegate tasks via delegate_to_agent (both invoked during /agent/run). Features include allowlist control, JWT forwarding, per-run quotas, destination cost caps, optional advertised atomic-USDC task prices, and optional credit billing with org-level and caller-principal pause/24-hour spend-limit enforcement. A price above the effective allowlist cap returns error_type=advertised_price_exceeds_cap before funding; lower prices are rechecked against live budgets. Definitive non-delivery of a newly linked credit-funded delegation creates a reversal-linked refund, restoring the refunded amount to both rolling spend-cap calculations; ambiguous possibly_delivered calls remain held for explicit resolution. Refund rows created before migration 103 may be unlinked and restore balance without rolling-cap headroom.

For the full protocol specification, environment variables, allowlists, and billing event payloads, see docs/a2a-delegation.md.

Platform Tool Marketplace

Teardrop exposes 31 caller-facing built-in, metered tools through the marketplace catalog. Callers can invoke them:

  • Via the MCP gateway at GET /tools/mcp (direct tool invocation, billed per call).
  • As tools called during agent runs (via POST /agent/run when the agent decides to use them; billed in the run's usage cost).

For the complete list of tools, detailed descriptions, and their per-call prices, please refer to the docs/tools-catalog.md.

Enable with MARKETPLACE_ENABLED=true. When enabled, tools appear in GET /marketplace/catalog with qualified_name = "platform/{tool_name}" and tool_type = "platform". Catalog discovery supports category filtering, sort=popularity, single-tool detail pages, an author index at GET /marketplace/authors, author profiles, LLM-friendly discovery at GET /marketplace/llms.txt, and current effective prices at GET /marketplace/quote?tool={qualified_name}. The public catalog is the complete active published inventory for an author; authenticated agents can inspect their current org inventory at GET /agent/tools. The author index reports active published authors and aggregate call counts, then links clients to the existing author profile for tool details; it is not a list of remote A2A delegation URLs. Aggregate quality metrics are available at GET /.well-known/reputation.json. Marketplace authors can register external MCP servers and publish discovered tools as listings via POST /marketplace/import/preview and POST /marketplace/import/publish (organization admins or org-bound machine credentials).

MCP tools/list includes an observed-quality description for LLM clients and structured _meta["teardrop/reputation"] for programmatic clients when a tool has call history. The /tools/mcp surface lists platform tools (bare names, payable with x402 or credit) and published org tools ({org_slug}/{tool_name}, Bearer and credit only, listed only to Bearer callers), each with _meta["teardrop/price"]; the older /mcp/v1 surface was removed at its 2026-10-29 sunset. Catalog cost_usdc always equals the billed price on every surface; community tools with no author price use the platform default, and 0 means free. See docs/tools-catalog.md for the metadata contract.

Organizations can optionally publish one remote A2A endpoint in the public directory with PUT /marketplace/agent-registration, using an organization admin or an org-bound client-credentials token. Teardrop accepts HTTPS base URLs only, SSRF-checks them, discovers the remote Agent Card, and requires the /message:send endpoint used by the A2A client. The registry is separate from the outbound delegation allowlist: publishing makes an endpoint discoverable but does not authorize calls to it. GET /marketplace/agents lists opted-in endpoints with reputation metrics only after five distinct calling organizations; self-traffic, local failures, and ambiguous possibly_delivered outcomes are excluded. Its additive registered_at field is only a recency signal for new entrants and does not attest to quality or ownership. This machine-credential path covers endpoint registration and MCP tool publishing; withdrawal of earnings requires an organization admin or the owning SIWE wallet of a machine-provisioned organization.

Agent-owned webhook tools can be registered through POST /tools. Machine-provisioned organizations configure marketplace payouts through POST /marketplace/author-config with their owning SIWE wallet; the wallet is pinned to that identity unless an organization admin configures a treasury wallet. Author earnings recording no longer requires a payout configuration; self-calls remain excluded. Publishing new marketplace tools and requesting withdrawals still require a configured settlement wallet. Earnings recording remains best-effort, not a durable settlement-linked guarantee.

Platform tools are always available during agent runs, are not subscribable via POST /marketplace/subscriptions, and incur their marketplace prices (in addition to token costs). Per-org pricing overrides are supported via POST /admin/pricing/tools; for agent runs, tool_pricing_overrides takes precedence over marketplace catalog prices when both exist for the same tool.

Marketplace subscriptions are agent-run pins, not recurring payment plans or direct MCP access grants. Pinning selects a community tool for the org's /agent/run tool set; direct /tools/mcp calls do not require a pin and retain their authentication and billing requirements. In /agent/tools, the legacy access_mode="subscribed" means pinned, while "included" means no marketplace pin is needed, not free. Pins and inventory do not guarantee execution; see agent-run pins vs direct tool calls.

Marketplace Settlement & USDC Sweeping

Organizations can monetize their agents via a Marketplace. Withdrawals claim pending author earnings before sending USDC through Coinbase Developer Platform (CDP) to the configured settlement wallet. Confirmed transfers become settled; confirmed on-chain reverts release the earnings. Submission errors and unavailable confirmations remain in_flight, with earnings held to prevent automatic repayment. The sweep loop settles or releases in_flight withdrawals that recorded a transaction hash once that transaction is finalized and matches the claimed USDC transfer; operators must establish the chain outcome before resetting any other ambiguous withdrawal.

Auto-sweep is configured via MARKETPLACE_AUTO_SWEEP_ENABLED and related MARKETPLACE_* settings (see docs/configuration.md). Admin APIs: POST /admin/marketplace/sweep (manual sweep) and GET /admin/marketplace/settlement-balance.

Verified-Email Onboarding Credit

Teardrop can grant a small prepaid credit balance to newly verified organizations so a first agent run is possible without immediately setting up a wallet or card. This is disabled by default (ONBOARDING_CREDIT_ENABLED=false) and is intended only as a conversion aid, not as a source of withdrawable marketplace earnings.

The grant is awarded after a user consumes a single-use email verification token (GET /auth/verify-email). Token consumption, marking the user verified, and enqueueing eligibility are committed atomically; the grant is idempotent and retried by a background worker until it succeeds. Promotional credit can be used for platform tools, org webhook tools, MCP tools, and the base agent run cost, but cannot call marketplace author tools. A real top-up (Stripe, on-chain USDC, admin top-up, or refund) converts the org to normal credit status and removes the marketplace restriction. x402-paid SIWE calls are unaffected.

Check GET /billing/balance after verification to see the granted balance. See docs/configuration.md for the ONBOARDING_CREDIT_* settings.

Unattended (Scheduled) Agent Runs

Organizations can schedule recurring, unattended agent runs with integrated credit-only billing, stored execution history, and real-time status callbacks. Managed via the /agent/schedules API (POST/GET/PATCH/DELETE, plus GET /agent/schedules/{id}/runs for cursor-paginated results).

Due runs are claimed with a row-locking query (FOR UPDATE SKIP LOCKED) and execute concurrently with per-run failure isolation, so multiple worker instances can scale horizontally. Results are archived under scheduled_run_results and can be dispatched to an HTTPS-only, SSRF-checked callback URL. Use callback_format=text for a plain-text mobile notification; JSON remains the default. Configure via SCHEDULED_RUNS_* settings (see docs/configuration.md).

Scheduled analysis prompts can call the internal record_predictions tool with their exact structured payload and return only a concise narrative report. Teardrop labels those predictions asynchronously against future observations through the generalized labeling data plane; callbacks can therefore deliver the report to downstream notification systems while structured values remain available for ML evaluation. See docs/architecture.md and the LABELING_* settings in docs/configuration.md.

With VOR_ENABLED=true, external agents can also commit wallet-signed predictions through POST /labeling/predictions. Teardrop timestamps each prediction on the server, batches commitments into Merkle trees anchored on Base, and returns inclusion proofs from GET /labeling/predictions/{id}/proof. See the VOR_* settings in docs/configuration.md.

Pre-registered public tasks (currently oracle_deviation@1, which scores how far Chainlink ETH/USD drifts from a Uniswap v3 TWAP on Base) are scored from pinned, finalized on-chain reads. GET /scorecards/... publishes coverage-adjusted Brier scorecards without authentication; prediction payloads stay private.

Event-Triggered (Reactive) Runs

Beyond fixed intervals, organizations can register event triggers that run the agent in response to inbound webhooks (e.g. an on-chain event, a CRM update, a CI signal). An event trigger stores a prompt template; the inbound JSON payload is interpolated into it at dispatch time. Event triggers reuse the same execution core, credit billing, result history, and callback delivery as scheduled runs.

Managed via the /agent/event-triggers API (CRUD, secret rotation, and run polling). Inbound dispatch is POST /agent/events/{trigger_token}, authenticated with a per-trigger secret via the X-Teardrop-Trigger-Secret header, with optional idempotency keys and scalar-only, length-capped prompt interpolation to resist injection. Postgres execution leases enforce global and per-org concurrency (returning 429 when saturated).

Set next_trigger_id to another event trigger in the same organization to chain completed runs internally, without callback authentication. Chains are linear; EVENT_CHAIN_MAX_HOPS caps child hops (default: 2, allowing 3 runs including the root; 0 disables child dispatch). Results expose chain_id and zero-based hop_index. Child delivery is at most once: unavailable or saturated targets are audited and never retried.

Prompt templates interpolate untrusted payload data, so treat rendered prompts as untrusted input to the agent — scope event-trigger tools and credit limits accordingly. Configure via EVENT_TRIGGERS_* and EVENT_CHAIN_MAX_HOPS settings (see docs/configuration.md).

X (Twitter) Broadcast Posts

Organizations can configure scheduled runs to broadcast market analysis and opportunity verdicts directly to X (Twitter). Setting callback_format=x publishes the final output text to X via the v2 API using OAuth 1.0a authentication upon successful run completion, recording published tweet IDs in the immutable x_broadcasts audit ledger.

Broadcast runs require X_BROADCAST_ENABLED=true and a designated operator organization via X_BROADCAST_ORG_ID; schedules from any other organization are rejected with 403. To guard against elevated pay-per-usage API costs and phishing, output text containing URLs is rejected before publication. Configure via X_* settings (see docs/configuration.md).


Requirements

  • Python 3.12+
  • An API key for your chosen LLM provider: Anthropic, OpenAI, or Google AI (optional if using BYOK or self-hosted)
  • A Postgres database (local via Docker, or Neon for production)
  • Redis (optional, for caching — falls back to in-memory with TTL)

Setup (PowerShell)

1. Clone and enter the project

powershell
git clone https://github.com/teardrop-ai/teardrop.gitcd teardrop

2. Create and activate a virtual environment

powershell
python -m venv venv.\venv\Scripts\Activate.ps1

If you get a script execution error, run first:

powershell
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

3. Install dependencies

powershell
pip install -r requirements.txt

4. Configure environment

powershell
Copy-Item .env.example .env

Minimum required contents:

# Global LLM provider fallback: anthropic | openai | google | openrouter (default: openrouter)# Note: Each org can override via PUT /llm-configAGENT_PROVIDER=openrouter# Default model is ~deepseek/deepseek-flash-latest.# For OpenRouter DeepSeek models, Teardrop delegates provider eligibility to the API key's OpenRouter data policy.OPENROUTER_API_KEY=sk-or-...      # required if AGENT_PROVIDER=openrouter# ANTHROPIC_API_KEY=sk-ant-...     # required if AGENT_PROVIDER=anthropic# OPENAI_API_KEY=sk-...           # required if AGENT_PROVIDER=openai# GOOGLE_API_KEY=...              # required if AGENT_PROVIDER=google
DATABASE_URL=postgresql://teardrop:teardrop@localhost:5432/teardrop
# Optional: Redis for distributed caching# REDIS_URL=redis://localhost:6379/0

5. Generate RSA keys

The RSA keypair is generated automatically at app startup (into keys/). To generate it manually first (optional), run:

powershell
python scripts/generate_keys.py

6. Run database migrations

powershell
python -m migrations.runner

7. Seed default org and admin user

powershell
python scripts/seed_users.py

8. Run the API server

powershell
uvicorn teardrop.main:app --reload

Server starts at http://localhost:8000. Visit http://localhost:8000/docs for the interactive API explorer.


Deployment

Docker (local full stack)

powershell
docker compose build --pulldocker compose up

Starts Postgres + Teardrop API. Migrations run automatically at startup. Keys are generated at build time and mounted from ./keys/. Use docker compose build --pull before rebuilds so refreshed base images are picked up, and add --no-cache when you want a fully fresh rebuild.

Render (production)

The repo includes a render.yaml that configures a single Standard (1c-2g) web service instance connected to Neon Postgres and your shared Redis service. The default database budget is 7 connections: up to six application-pool connections plus one LangGraph checkpointer connection per instance. Confirm that this leaves headroom under the configured Neon connection limit before deploying or increasing instance count.

For the comprehensive list of environment variables, security credentials, database configurations, and rate-limiting limits, please refer to the dedicated docs/configuration.md reference guide.


Authentication

Teardrop issues RS256 JWTs. Protected business endpoints require a Bearer token. Public auth, registration, billing-pricing, health, documentation, agent-card, and the payment-gated POST /message:send A2A surfaces remain unauthenticated as described below.

1. Client credentials (machine-to-machine)

powershell
$resp = Invoke-RestMethod -Uri "http://localhost:8000/token" `    -Method Post -ContentType "application/json" `    -Body '{"client_id":"teardrop-client","client_secret":"<JWT_CLIENT_SECRET>"}'$token = $resp.access_token

The resulting JWT includes auth_method: "client_credentials". Set JWT_CLIENT_ID and JWT_CLIENT_SECRET in .env.

2. Email + password

powershell
$resp = Invoke-RestMethod -Uri "http://localhost:8000/token" `    -Method Post -ContentType "application/json" `    -Body '{"email":"[email protected]","secret":"<password>"}'

The resulting JWT includes auth_method: "email". Create users via POST /admin/users.

3. SIWE — Sign-In with Ethereum

SIWE lets Ethereum wallet holders authenticate without a password. The JWT issued includes auth_method: "siwe" and the caller's address.

1. GET  /auth/siwe/nonce   → { "nonce": "abc123..." }2. Construct an EIP-4361 SIWE message with that nonce3. Sign with your wallet (EIP-191)4. POST /token  { "siwe_message": "...", "siwe_signature": "0x..." }   → { "access_token": "..." }

SIWE tokens authenticate wallet identity, and new wallet addresses are auto-registered on first login. Machine-provisioned SIWE orgs use prepaid credit for agent runs; fund that credit through the agent funding loop below.

4. x402 payment-first bootstrap

An external agent can bootstrap an account without email, a human signup, or a prior JWT. Discover the flow from /.well-known/agent-card.json or the bootstrap block at /.well-known/x402 (also /.well-known/x402.json), then send POST /token with {"grant_type":"x402"}. Bootstrap discovery requires BILLING_ENABLED, MACHINE_PROVISIONING_ENABLED, and X402_ONBOARDING_ENABLED. Its payment requirements are separate from the top-level run-price accepts; discovery prices are advisory. The first token response is a 402 Payment Required containing the current x402 requirements for enough prepaid credit to pass the client-credential run reserve. Retry with the signed Payment-Signature (or legacy X-Payment) header.

On successful first settlement, Teardrop returns a short-lived access token plus a one-time client_id and client_secret. Store the secret immediately; it cannot be retrieved later. Use those credentials with the existing client-credentials /token flow for subsequent billable runs. Machine-provisioned orgs receive no promotional credit and start with the configured MACHINE_ORG_DAILY_SPEND_LIMIT_USDC rolling cap (default: $5.00 per 24 hours). An explicit operator-set org limit is preserved for trusted orgs; a zero stored limit resolves to the configured default.

Agent funding loop

Bootstrap once, then use the returned client credential to call GET /billing/topup/usdc/requirements?amount_usdc=... and sign the returned x402 requirements. Submit the signed header to POST /billing/topup/usdc before the prepaid balance is exhausted. Repeat grant_type=x402 payments are also accepted for an existing machine org; they reuse its client ID and omit client_secret. If the original secret is lost, authenticate with SIWE and use POST /org/credentials/regenerate.

Token expiry and refresh tokens

The email, client-credentials, and SIWE auth methods issue access tokens with a 30-minute expiry (expires_in: 1800 seconds in the token response). The x402 bootstrap also returns a 30-minute access token, but does not issue a refresh token. For applications that need sessions longer than 30 minutes, use refresh tokens from the email or SIWE flows:

  • Refresh tokens expire after 30 days and can be exchanged for a new access token + rotated refresh token.
  • Refresh token rotation is atomic with idempotency replay protection — if the same refresh token is submitted twice within the replay window, you'll receive the same new token pair instead of creating duplicates.
  • Single logout via POST /auth/logout revokes your refresh token, ending the session immediately.
powershell
# 1. Exchange refresh token for new access token + rotated refresh token$resp = Invoke-RestMethod -Uri "http://localhost:8000/auth/refresh" `    -Method Post -ContentType "application/json" `    -Headers @{ "Cookie" = "refresh_token=<your-refresh-token>" }    # OR pass as body: -Body '{"refresh_token":"<your-refresh-token>"}'
# New access token and rotated refresh token are in the response$newAccessToken = $resp.access_token$newRefreshToken = $resp.refresh_token  # Use this on your next refresh
# 2. Logout (revoke refresh token)Invoke-RestMethod -Uri "http://localhost:8000/auth/logout" `    -Method Post -ContentType "application/json" `    -Headers @{ Authorization = "Bearer $accessToken" }

LLM Configuration (Per-Org)

Organizations can configure their preferred LLM provider, model, routing strategy, and optionally bring their own API keys (BYOK). This unlocks:

  • Multi-provider choice: Use Anthropic, OpenAI, Google, or point at self-hosted endpoints (vLLM, Ollama, OpenRouter)
  • Bring Your Own Key (BYOK): Encrypt and store your own API credentials — Teardrop never sees your keys. BYOK orgs pay only platform orchestration fees (per-token when BYOK_TIER_PRICING_ENABLED=true, or a flat fee otherwise); the LLM provider is billed directly to their own key.
  • Smart routing: Automatically select models based on cost, speed, or quality
  • Self-hosted support: Use any OpenAI-compatible endpoint via api_base parameter

Org LLM config endpoints

MethodPathAuthDescription
GET/llm-configBearerGet your org's LLM config (or global defaults if not configured)
PUT/llm-configBearerSet or update org LLM config
DELETE/llm-configBearerDelete config, revert to global defaults

Example: Set org's LLM to GPT-4o with cost-based routing

powershell
$token = (Invoke-RestMethod -Uri "http://localhost:8000/token" `    -Method Post -ContentType "application/json" `    -Body '{"client_id":"teardrop-client","client_secret":"<secret>"}').access_token
Invoke-RestMethod -Uri "http://localhost:8000/llm-config" `    -Method Put -ContentType "application/json" `    -Headers @{ Authorization = "Bearer $token" } `    -Body @{        provider = "openai"        model = "gpt-4o"        routing_preference = "cost"  # or "speed", "quality", "default"        max_tokens = 4096        temperature = 0.7    } | ConvertTo-Json

For BYOK, add your own api_key (encrypted at rest). For self-hosted endpoints (vLLM, Ollama, or any OpenAI-compatible server), set api_base to your endpoint URL.

Reasoning hints are provider-specific: Google uses documented per-model thinking levels or budgets (none becomes low on Gemini 3.8 Flash); unknown Google model IDs retain provider defaults. OpenRouter receives reasoning.effort, subject to its model's supported efforts. Native OpenAI and Anthropic BYOK retain defaults. See reasoning effort compatibility for precedence and limits.

Routing preferences

When you set routing_preference to a value other than "default", Teardrop will automatically select a model from its standard pool based on your criteria:

PreferenceBehavior
defaultUse the provider/model you configured
costSelect the cheapest model (by tokens-in + tokens-out pricing)
speedSelect the fastest model (by p95 latency from live benchmarks; falls back to official specs for new deployments)
qualitySelect the highest quality model

Note: If you set BYOK (custom API key), routing is disabled — you always use your configured model.

LLM credit model

Teardrop prepaid credits (or on-chain x402 settlement) cover the full cost of every run, but the line item depends on whether the org uses platform LLM keys or BYOK:

ModeWho pays the LLM providerWhat Teardrop debits from the org
Platform keys (default)TeardropModel token cost from the run model's pricing_rules row, plus tool calls
BYOKThe org, directly through their own keyPlatform orchestration fee (flat BYOK_PLATFORM_FEE_USDC, default $0.001/run, or per-token orchestration pricing when BYOK_TIER_PRICING_ENABLED=true floored at that flat fee), plus tool calls. The fee appears as platform_fee_usdc in usage events and SSE billing events.

Tool calls are priced the same way on every surface and for every model: admin override, then the author or platform price, then the global pricing_rules.tool_call_cost. Model-specific rules price tokens only. A rule with no per-unit rates is flat-rate: its run_price_usdc covers tokens once per run (not per LLM turn), and tool calls are billed on top.

On agent runs, a tool call is billed when it succeeds or returns a tool-reported business error (for example, an unknown protocol or wallet). Infrastructure failures are not billed: timeouts, upstream outages or rate limits, invalid upstream responses, invalid arguments, and unexpected executor errors.

In other words, BYOK does not eliminate the need for Teardrop credits or x402 settlement — it only removes the LLM model cost from the Teardrop bill.


Model Benchmarks

Teardrop continuously tracks operational metrics for every LLM deployed. These benchmarks inform model-routing decisions.

Benchmarks endpoints

MethodPathAuthDescription
GET/models/benchmarks—Public: all models with catalogue metadata + live metrics
GET/models/benchmarks/orgBearerOrg-scoped: metrics for your org's usage only

Understanding the metrics

Each model entry includes catalogue metadata (provider, model, display_name, context_window, supports_tools, quality_tier, pricing) plus live benchmarks:

  • total_runs_7d: Number of runs using this model in the last 7 days (benchmarks only included if >= 10 runs)
  • avg_latency_ms: Average time (ms) from start to completion
  • p95_latency_ms: 95th percentile latency — the slowest 5% of runs
  • avg_cost_usdc_per_run: Average cost per run (input + output tokens + tools)
  • avg_tokens_per_sec: Streaming throughput (useful for real-time applications)
  • quality_tier: Static tier (1=best, 2=good) for quality-based routing

Billing & Payments (x402)

Teardrop implements the x402 payment protocol. When BILLING_ENABLED=true, requests must include payment. Set BILLING_ENABLED=false (default) to run without billing during development.

How it works

Teardrop implements the x402 payment protocol. When BILLING_ENABLED=true, requests must include payment. Set BILLING_ENABLED=false (default) to run without billing during development.

An unpaid POST /agent/run returns a 402 Payment Required with the x402 v2 PaymentRequired envelope (PAYMENT-REQUIRED header, plus legacy X-PAYMENT-REQUIRED). The client signs the payment and retries with a Payment-Signature header; Teardrop verifies it with the facilitator, streams the SSE response, and emits a BILLING_SETTLEMENT event with the on-chain tx_hash after the run.

Payment methods by auth type

Auth methodPayment mechanism
siweHuman-owned orgs: x402 on-chain (USDC, exact or upto scheme, per-request); machine-provisioned orgs: prepaid credit only, subject to the hard daily cap
client_credentialsOrg prepaid credit balance (off-chain debit)
emailOrg prepaid credit balance (off-chain debit)

The x402 payment-first bootstrap charges a reserve-sized x402 payment, settles it before issuing credentials, and credits the resulting atomic-USDC amount to the new org. It does not use the verified-email promotional grant. Authenticated machine credentials can use the larger, less frequent /billing/topup/usdc balance top-up path instead of paying per run.

x402 payment schemes

SchemeHow it worksConfig
exact (default)Client signs the exact run price; facilitator settles that amount.X402_SCHEME=exact
uptoClient signs a ceiling (X402_UPTO_MAX_AMOUNT); after the run, Teardrop settles the actual usage cost (≤ ceiling) via Permit2.X402_SCHEME=upto

upto client requirement: Before using X402_SCHEME=upto, the paying wallet must approve Permit2 for USDC on the target chain once: IERC20(USDC).approve(PERMIT2_ADDRESS, type(uint256).max). This is a one-time on-chain transaction per wallet. Clients that have not approved Permit2 can always use scheme: exact from the accepts array in the 402 response as a fallback.

Pricing

Pricing is dynamic via the pricing_rules database table. Current rates (usage-based v1):

MetricRate
Input tokens$0.0015 / 1k tokens
Output tokens$0.0075 / 1k tokens
Tool calls$0.001 / call default; platform tools use per-tool prices ($0.005 minimum, see docs/tools-catalog.md)
Minimum per run$0.01

Check live pricing: GET /billing/pricing

Running as x402 client (SIWE payments)

powershell
# 1. Get a SIWE JWT (see Authentication above)# 2. Call /agent/run — you'll get a 402 with payment requirements# 3. Construct and sign the x402 transferWithAuthorization (EIP-3009)# 4. Retry with the signed payment header
Invoke-RestMethod -Uri "http://localhost:8000/agent/run" `    -Method Post -ContentType "application/json" `    -Headers @{ Authorization = "Bearer $token"; "Payment-Signature" = "<x402-header>" } `    -Body '{"message":"What is the ETH balance of vitalik.eth?","thread_id":"session-1"}'

The stream will include a BILLING_SETTLEMENT event with the on-chain tx_hash after the run completes.

Credit top-up (machine callers)

Admins can add prepaid USDC credit to an org's balance:

powershell
Invoke-RestMethod -Uri "http://localhost:8000/admin/credits/topup" `    -Method Post -ContentType "application/json" `    -Headers @{ Authorization = "Bearer $adminToken" } `    -Body '{"org_id":"org-123","amount_usdc":1000000}'   # $1.00

For the full set of billing environment variables (BILLING_ENABLED, X402_*, BILLABLE_AUTH_METHODS, etc.), see docs/configuration.md.


A2A Delegation & Cross-Agent Revenue Routing

Teardrop agents can delegate tasks to remote A2A-compliant agents and charge those delegations back to the calling organization. This unlocks decentralized specialisation, built-in spend orchestration, and automatic revenue routing.

The machine-readable /.well-known/registry-benefits.json contract explains how organizations register an A2A endpoint, what discovery and advisory reputation benefits they receive, and which guarantees are intentionally not provided.

For a detailed protocol specification, system configurations, allowlists, and billing event payload structures, see the docs/a2a-delegation.md guide.


Publishing to Agentic Market

Use the full public URL of the paid A2A surface, for example https://api.teardrop.dev/message:send, with method POST. Do not register the bare origin https://api.teardrop.dev/ (GET / redirects to /docs, and POST / is not a paid entrypoint).

Agentic Market validators may probe /.well-known/x402, /.well-known/x402.json, and the configured endpoint URL. Teardrop serves those discovery aliases publicly and issues the x402 challenge on unpaid anonymous POST /message:send requests before body validation. The challenge includes the full x402 v2 PaymentRequired envelope (PAYMENT-REQUIRED), a legacy X-PAYMENT-REQUIRED alias, a top-level resource describing the paid surface (url, description, and the shared Teardrop serviceName, tags, and iconUrl), and extensions.bazaar describing the A2A request/response shape.

The MCP endpoint POST https://api.teardrop.dev/tools/mcp behaves the same way for validators: an anonymous POST whose body is empty or not a JSON-RPC message, or an anonymous GET whose Accept header does not include text/event-stream, receives an HTTP 402 whose extensions.bazaar declares a paid tools/call example (get_token_price) and is priced at that tool's cost. Unpaid anonymous tools/call requests receive per-tool MCP Bazaar metadata, including the tool's output schema (top-level fields only when the full schema would exceed the 402 header budget). Every MCP 402 resource also carries Bazaar service metadata (serviceName, tags, and iconUrl from AGENT_CARD_ICON_URL when it is an absolute http(s) URL) so catalogs can label the listing. SSE GETs, authenticated requests, MCP handshakes, and tools/list stay on the normal MCP transport.

The Bazaar lists each MCP tool separately, and only after a payment for that tool settles through the CDP facilitator. python -m scripts.seed_bazaar_listings --base-url https://api.teardrop.dev quotes every paid tool without paying; add --execute with TEARDROP_SEED_PRIVATE_KEY set to make one settled call per tool. It stops at the first failure and refuses to pay if the gateway's 402 lacks Bazaar metadata or output declarations. The CDP facilitator drops serviceName, tags, and iconUrl from MCP-type records, so the Teardrop brand reaches catalogs such as Agentic.Market only through the HTTP /message:send listing, which carries the same metadata; seed it once with --a2a --execute.

Publishing to Smithery

Teardrop automatically advertises its MCP tools via /.well-known/mcp/server-card.json. To distribute on Smithery:

  1. Copy the public base URL of your Teardrop instance into the Smithery URL Deployment wizard.
  2. Provide the following Configuration Schema (JSON) inside the Smithery CLI or publish wizard to expose x402 anonymous capability:
    json
    {  "type": "object",  "properties": {    "apiKey": {      "type": "string",      "title": "API Key",      "x-from": { "header": "x-teardrop-key" },      "x-to": { "header": "Authorization" }    }  }}
  3. Set the Display Name, Description, Homepage, and Icon within the Smithery dashboard to achieve the maximum 100/100 quality score.

Publishing to the MCP Registry

The official listing is io.github.HASAVAGE/teardrop at https://api.teardrop.dev/tools/mcp (Streamable HTTP, no package). Metadata lives in server.json at the repo root, and name must match the published namespace. To publish a new version: bump version and remotes in server.json, then from the repo root run mcp-publisher validate, mcp-publisher login github, and mcp-publisher publish.

API Reference

Teardrop provides interactive visual API explorers via OpenAPI at /docs (Swagger UI) and /redoc (ReDoc UI).

For a complete tabular list of all endpoints across Core, Auth, Billing, Marketplace, Wallets, Admin, Custom Tools, Memory, MCP Federation, and A2A Delegation surfaces, consult the docs/api-reference.md guide.


Running the MCP tool server (optional)

The tools can be served standalone over the MCP protocol for use with Claude Desktop, VS Code, or any MCP-compatible client:

powershell
# stdio transport (default – for Claude Desktop / VS Code)python tools/mcp_server.py
# HTTP SSE transportpython tools/mcp_server.py --transport=sse

How It Works

Teardrop uses portable agent nodes behind a LangGraph routing/checkpoint adapter and emits framework-neutral runtime events to its Server-Sent Events (SSE) layer.

For the complete architectural design, execution flow state diagrams, SSE stream event descriptions, and structured A2UI component schemas, consult the docs/architecture.md reference.


Database

Teardrop uses Postgres (Neon recommended for production, local via Docker for development).

Migrations

Active schema changes are in migrations/versions/. The current 102_squashed_baseline.sql replaces the historical files in migrations/archive/. Run migrations with:

powershell
python -m migrations.runner

For the active baseline, replacement manifest, and historical catalog of schema migrations, seed entries, and indexes, please refer to the docs/migrations.md catalog.

Neon (production)

Set DATABASE_URL to your Neon connection string. Plain postgresql:// is preferred; legacy postgresql+asyncpg:// values remain accepted.


Project structure

teardrop/  app.py              # FastAPI app, lifespan, middleware, background workers, router registration  main.py             # Compatibility entrypoint (re-exports teardrop.app)  routers/            # APIRouter modules (agent.py, billing.py, marketplace/, auth.py, system.py, discovery.py, admin/, org/, …)  config.py           # Settings via pydantic-settings (reads .env)  auth.py             # RS256 JWT & refresh tokens (email, client_credentials, SIWE)  users/              # Org + User models, CRUD, PBKDF2-SHA256 password hashing  billing/            # x402 billing layer, pricing, invoice queries, credit system  marketplace/        # Marketplace catalog, earnings, reputation, subscriptions, withdrawals  mcp_client/         # Per-org MCP client: CRUD, session pool, tool discovery  org_tools/          # Per-org custom webhook tools: CRUD, caching, execution  memory.py           # Per-org pgvector memory: LLM extraction, recall, CRUD  agent/              # LangGraph graph, nodes, LLM factory, runtime context/events  agent_runtime.py    # Agent run orchestration (scheduled/event-triggered runs)  mcp_gateway/        # MCP gateway middleware package (direct tool invocation + billing)tools/  registry.py         # ToolRegistry: versioned, with deprecation lifecycle  mcp_server.py       # Standalone MCPServer for MCP protocol clients  definitions/        # One file per tool (calculate, get_datetime, web_search, …)migrations/  runner.py           # Applies active SQL migrations and squash baselines  versions/           # Active SQL and .replaces manifests  archive/            # Git-only historical migrations superseded by baselinesshared/               # Internal shared utilities: db pool registry, audit inserts, webhook callerscripts/              # generate_keys.py, seed_users.py, audit_dependencies.py, export_api_spec.py, …

For the complete architectural design, execution flow state diagrams, SSE stream event descriptions, and structured A2UI component schemas, consult the docs/architecture.md reference.


Coinbase Developer Platform Integration

Teardrop can provision per-org USDC wallets via Coinbase Developer Platform (CDP) for receiving delegation payments and marketplace earnings. This requires a CDP account (cdp.coinbase.com) and an API key with wallet:create permission (Key ID, Key Secret, and Wallet Secret). Configure via the AGENT_WALLET_* and CDP_* environment variables (see docs/configuration.md). CDP charges $0.005 per operation; the free tier includes 5,000 ops/month.

Each org can hold one wallet per chain (e.g., Base Sepolia testnet, Base mainnet). Wallets auto-receive delegation payments and MCP marketplace earnings.


License

Teardrop is licensed under the Business Source License 1.1.

  • Free to use for non-production evaluation and development.
  • Commercial production use requires a commercial license from the maintainer.
  • Change Date: April 3, 2030 — on this date the code automatically converts to AGPL-3.0-only.

See LICENSE for full terms. For commercial licensing enquiries, see the contact address in the LICENSE file.

Contributions are welcome under the same license — see CONTRIBUTING.md. To report a security vulnerability, see SECURITY.md.

來源:README.md,提交 1d5f9a9

工具

35

assess_counterparty_risk

Assess Counterparty Risk

Return a decision-ready counterparty-risk verdict for an EVM address before funds or authority are committed. The result branches to high_risk, caution, acceptable, or insufficient_data with the evidence needed for the calling agent to act. Use when: Delegate this check before sending funds, granting approvals, or interacting with an unknown EVM address when the caller needs a bounded risk decision. Limitations: Analytics and heuristic risk assessment; not a credit bureau, fraud guarantee, or legal endorsement. Relies on DeBank indexing and on-chain Aave/Compound contract states. Alternatives: get_wallet_approvals, get_liquidation_risk, get_wallet_positions

輸入參數chain_idswallet_address必填

assess_market_resolution

Assess Market Resolution

Return a decision-ready resolution-risk verdict for one Polymarket market before an agent trades, quotes, or forecasts it. The result branches to tradeable, ambiguous, avoid, or insufficient_data and names the resolution basis (price_feed, official_source, media_consensus, unspecified), UMA dispute state, rule-wording risks, and executability (liquidity, spread) so the calling agent can act without reading the full rules. Use when: Call once per market before placing, quoting, or forecasting a Polymarket position when the caller needs to know whether the rules and resolution state make the outcome well-defined. Repeat calls within two minutes return cached data. Limitations: Heuristic analysis of Polymarket rule wording and Gamma API state; not a probability forecast, legal advice, or a guarantee of how UMA voters resolve. Does not read order-book depth, event-level augmented negative-risk settings, or clarifications published off-platform. Alternatives: web_search, http_fetch

輸入參數market必填

calculate

Calculate

Evaluate a safe arithmetic expression and return the numeric result. Supports +,-,*,/,**,%,sqrt,abs,round,floor,ceil,log,sin,cos,tan,pi,e. Use for derived figures (ratios, differences, percentages) that no tool output already provides. Use when: Use when an agent must derive a value that tool outputs do not already include, such as a ratio, spread, or percentage. Do not use to re-derive pre-computed fields like std_30d or dca_baseline_90d that get_token_price_historical returns. Limitations: Arithmetic only — no aggregation over tool history, no unit conversion, and no financial modeling beyond the listed functions. Errors return an error field rather than raising. Alternatives: get_token_price_historical, get_datetime

輸入參數expression必填

convert_currency

Convert Currency

Convert an amount between fiat currencies (USD, EUR, GBP) and crypto assets (BTC, ETH, USDC, SOL) and return the converted amount plus the exchange rate used. Use when: Use when an amount must be expressed in a different currency than the source data — for example converting a USD portfolio value into EUR, or a fiat amount into its crypto equivalent. For prices only, get_token_price returns the rate directly without a second call. Limitations: Spot-rate conversion at request time; no historical or forward rates, and no slippage or fee modeling. Actual swap execution differs — use get_dex_quote for executable on-chain quotes. Alternatives: get_token_price, get_dex_quote

輸入參數amount必填to_currency必填from_currency必填

decode_transaction

Decode Transaction

Decode a transaction's calldata into a human-readable function name and arguments, and return transaction status (1=success, 0=revert), gas used, and block number. Uses a supplied ABI when provided, otherwise 4byte.directory. Supports Ethereum mainnet and Base. Use when: Use when one known transaction must be explained — what function was called, with what arguments, and whether it succeeded. For wallet-wide activity patterns use get_wallet_history instead. Limitations: 4byte.directory matching can be ambiguous or absent for custom contracts; supply an ABI for precise decoding. One transaction per call; Ethereum mainnet and Base only. Alternatives: get_transaction, get_wallet_history

輸入參數tx_hash必填abi_jsonchain_id

delegate_to_agent

Delegate To Agent

Delegate a task to a remote A2A-compliant agent: discover its capabilities via its agent card, send it a message, handle payment, and return the result. Use only when no local platform tool can fulfil the request. Use when: Use when a task requires specialist capabilities beyond the local tool set. Call discover_agents first when the remote agent URL is unknown. Do not retry unchanged after error_type=advertised_price_exceeds_cap; pick another result or adjust the cap. Limitations: Requires an allowlisted remote URL and sufficient delegation budget; the remote agent's price and capability claims are read from its card and are not independently verified. Involves real payment. Alternatives: discover_agents, web_search

輸入參數agent_url必填task_typetask_description必填

discover_agents

Discover Agents

Find opt-in remote A2A agents, published tool capabilities, endpoints, and public reputation status. Use when: Use before delegate_to_agent when a specialist agent is needed but its URL is unknown. Limitations: Discovery is read-only and does not add an agent to the org allowlist; delegate_to_agent remains authoritative. Alternatives: delegate_to_agent

輸入參數qlimit

get_datetime

Get Datetime

Return the current UTC date and time as a formatted string and ISO 8601 timestamp, for grounding time-relative reasoning in the actual clock rather than training-data assumptions. Use when: Use when a task must anchor on the current date or time — computing ages, windows, deadlines, or 'as of today' context. The runtime context block already states the date, so call this only when a specific strftime format or a precise timestamp is needed. Limitations: UTC only — no timezone conversion. An unsupported strftime format silently falls back to the default format instead of erroring. Alternatives: calculate, get_block

輸入參數format

get_block

Get Block

Get block details (timestamp, gas used, base fee, miner, transaction count) for an Ethereum or Base block by number, hash, or 'latest'. Use to anchor events to a point in chain time. Use when: Use when a question depends on when a block occurred, how full it was, or its base fee — for example dating a transaction or checking congestion at a specific height. For current fee levels use get_gas_price instead. Limitations: One block per call; Ethereum mainnet and Base only. Historical base fee data depends on RPC node retention for older heights. Alternatives: get_transaction, get_gas_price

輸入參數chain_idblock_identifier

get_chain_metrics

Get Chain Metrics

Compare blockchain ecosystem health via DeFiLlama: current TVL, 7/30-day TVL change, and aggregate fee activity. Pass chains such as ['Ethereum', 'Arbitrum', 'Solana'] for a focused comparison, or omit chains to inspect the highest-TVL ecosystems. Use when: Use for ecosystem-level comparisons — which chains are growing, where fee activity concentrates, or how a chain's TVL trended. For a single protocol's economics use get_protocol_tvl instead. Limitations: Third-party DeFiLlama analytics; historical and fee fields fail open (null) for uncovered chains. Not a real-time measure of chain throughput or security. Alternatives: get_protocol_tvl, get_dex_volume

輸入參數dayslimitchains

get_dex_quote

Get Dex Quote

Get the best Uniswap v3 swap quote on Ethereum (chain_id=1) or Base (chain_id=8453) via direct on-chain QuoterV2 calls. Queries all four fee tiers (100/500/3000/10000 bps) in parallel and returns the tier with the highest output amount, along with per-tier breakdown. Inputs are raw uint256 amounts and EIP-55 checksummed addresses; native ETH is not quoted directly — pass the WETH address. Returns no_liquidity=true when no pool exists for the pair. Point-in-time quote at the returned block_number; do not cache. Use when: Choose when you need a best-execution Uniswap v3 swap quote on Ethereum or Base before executing a trade — e.g. price impact, output amount, or route selection. Limitations: Quotes raw uint256 amounts with EIP-55 checksummed addresses only; native ETH is not quoted directly (pass WETH). Point-in-time at the returned block_number — do not cache. Alternatives: get_token_price, get_dex_volume

輸入參數chain_idtoken_in必填amount_in必填token_out必填

get_dex_volume

Get Dex Volume

Compare decentralized exchange activity via DeFiLlama: 24h/7d/30-day volume, period-over-period changes, and each protocol's share of reported global 24-hour DEX volume. Filter by protocol and rank by a 1-, 7-, or 30-day lookback window. Use when: Use for landscape questions — which DEXs dominate volume, how activity shifted week-over-week, or a specific protocol's relative share. For executable swap pricing use get_dex_quote instead. Limitations: Third-party DeFiLlama reporting, not on-chain truth; coverage gaps understate smaller protocols. 24-hour share is computed against the unfiltered global total, so filtered results retain landscape context. Alternatives: get_dex_quote, get_chain_metrics

輸入參數limitprotocolslookback_days

get_defi_positions

Get Defi Positions

Block-accurate DeFi positions for a wallet across Aave v3, Compound v3, Uniswap v3 LP, and Lido on Ethereum or Base. Returns Aave account health (collateral, debt, health factor, LTV) with per-reserve breakdown, Compound v3 market positions, Uniswap v3 LP positions by token ID, and on Ethereum the Lido stETH/wstETH balances with the current wstETH-to-stETH equivalent. Per-protocol failures are isolated — other protocols still return. Use when: Use when a block-accurate single-wallet protocol snapshot is needed, including health factor and LP position detail. For broad all-chain discovery or net worth across many protocols use get_wallet_positions instead. Limitations: On-chain RPC view of four protocol families on Ethereum and Base only; does not discover wallets' unknown or long-tail protocol positions. Compound v3 reports only a boolean liquidation flag — never state a numeric Compound health factor. Errors list which protocols were unavailable. Alternatives: get_wallet_positions, get_liquidation_risk, get_wallet_portfolio

輸入參數chain_idwallet_address必填

get_gas_price

Get Gas Price

Get current EIP-1559 gas fees on Ethereum or Base: base fee, priority fee, next-block base fee estimate, and congestion (gas_used_ratio >0.5 busy, >0.9 very congested). Optional USD estimates cover a simple transfer and a swap-like transaction. Cached 10 seconds per chain. Use when: Use before advising a transaction — to time execution, size a gas budget, or judge congestion. Call once per decision; the 10-second cache makes rapid re-calls pointless. Limitations: Point-in-time estimate that changes every block; USD figures are rough heuristics at 21k/150k gas, not an execution quote. Ethereum mainnet and Base only. Alternatives: get_block, get_dex_quote

輸入參數chain_idinclude_usd_estimate

get_lending_rates

Get Lending Rates

Get current on-chain lending supply/borrow APYs for Aave v3 reserves and Compound v3 markets on Ethereum or Base, with per-asset snapshots and Compound utilization. Use for protocol-specific yield comparisons such as USDC on Aave vs Compound. Use when: Use for protocol-specific lending-rate questions (e.g. 'Aave vs Compound USDC rates'). Prefer over get_yield_rates when the protocols are known; use get_yield_rates for broad pool discovery across many protocols. Do not fall back to web_search when this returns errors — report them. Limitations: On-chain snapshots of Aave v3 and Compound v3 on Ethereum and Base only; not a multi-protocol yield aggregator. Rates are point-in-time and change per block. Returns an errors list — report each unavailable protocol explicitly and treat empty rates with empty errors as transient RPC unavailability. Alternatives: get_yield_rates, get_defi_positions, get_liquidation_risk

輸入參數assetschain_idprotocol

get_liquidation_risk

Get Liquidation Risk

Assess DeFi liquidation risk for up to 50 wallets across Aave v3 and Compound v3 on Ethereum or Base. Returns per-wallet health factor, tiered risk classification (liquidatable, critical, warning, caution, healthy, no_debt), and an overall_tier aggregate. Per-protocol failures are isolated — one protocol's RPC error does not blank the other's result. Use when: Use for multi-wallet batch risk assessment (2+ wallets). For a single-wallet DeFi analysis use get_defi_positions, which already includes risk metrics. Use assess_counterparty_risk when the question is counterparty trust rather than position health. Limitations: View-only scan of Aave v3 and Compound v3 on Ethereum and Base with hardcoded market addresses; not a liquidation simulation or guarantee. Compound v3 exposes only a boolean liquidation flag — no numeric health factor. Duplicate wallet addresses are silently removed. Alternatives: get_defi_positions, assess_counterparty_risk, get_wallet_positions

輸入參數chain_idwallet_addresses必填

get_token_approvals

Get Token Approvals

Block-accurate audit of ERC-20 allowances for a wallet across curated DeFi spenders (Uniswap, Aave, Compound, 1inch, 0x, OpenSea) on Ethereum or Base. Flags unlimited approvals by risk level (high=unknown spender, medium=trusted protocol, low=bounded). Use before swaps or after security incidents to detect active exploit vectors. Use when: Use for a free, block-accurate Ethereum/Base check of an address's exposure to the curated spender list. For broad all-chain spender discovery, hacked/abandoned flags, or NFT-adjacent exposure use get_wallet_approvals instead. Limitations: Covers only the tracked-asset registry and curated spenders — untracked tokens and custom spenders are excluded. Does not inspect NFT approvals or off-chain Permit2 sub-permits. An error field marks results as incomplete rather than clean. Alternatives: get_wallet_approvals, assess_counterparty_risk

輸入參數tokenschain_idspenderswallet_address必填

get_wallet_approvals

Get Wallet Approvals

Inspect a wallet's current ERC-20 token authorization exposure on one DeBank-supported chain. Returns discovered spenders, USD exposure, protocol attribution, and hacked or abandoned protocol flags. This is broader than the curated block-accurate get_token_approvals tool. Use when: Use when broad spender discovery or cross-chain security screening is needed. Call once per chain because DeBank requires a chain_id. Use get_token_approvals for a free, block-accurate Ethereum or Base scan of curated tokens and spenders. Limitations: The result is third-party analytics and may be stale. It covers token approvals only, not NFT approvals or off-chain Permit2 sub-permits; each chain consumes a separate billable provider call. Alternatives: get_token_approvals

輸入參數chain_id必填wallet_address必填

get_token_price

Get Token Price

Get current price, 24h change, market cap, FDV, and volume for one or more crypto tokens. Accepts ticker symbols, full names, or CoinGecko IDs; unknown symbols resolve automatically. Batch up to 50 tokens. Reuse price_usd/value_usd already returned by get_wallet_portfolio instead of re-calling. Use when: Use for spot pricing of named tokens — including batched multi-token queries. Do not call for tokens whose price get_wallet_portfolio already returned, or for address-only unknown tokens (report them as unrecognized). For historical windows use get_token_price_historical. Limitations: CoinGecko spot data; point-in-time and not an executable swap quote. Bare 0x addresses are not resolvable and should be treated as unknown tokens. Alternatives: get_token_price_historical, get_wallet_portfolio, get_dex_quote

輸入參數tokens必填vs_currency

get_protocol_tvl

Get Protocol Tvl

Get Total Value Locked for one or many DeFi protocols from DeFiLlama: current USD TVL, 7/30-day change, fees and revenue when reported, per-chain breakdown, and optional daily historical series. Batch multiple protocols via protocols=[...] — batch responses return one compact economic summary per protocol; single-protocol calls add chain and historical detail. Supports 3,000+ protocols; use DeFiLlama slugs ('aave-v3', 'uniswap-v3'); common aliases are auto-corrected. Use when: Use for protocol-level economic questions — size, growth, fees, or revenue of a specific protocol. For 2+ protocols always batch in one call rather than calling per-protocol. Pass include_historical=true with days when a trend is needed; without it the response is a current TVL scalar. For ecosystem-level chain comparisons use get_chain_metrics instead. Limitations: Third-party DeFiLlama analytics, not on-chain truth. Upstream revenue failures surface as revenue_error_type and null economic fields are data gaps — never fabricate values for them. Alternatives: get_chain_metrics, get_yield_rates, get_dex_volume

輸入參數daysprotocolprotocolsinclude_historical

get_token_price_historical

Get Token Price Historical

Get historical crypto prices over a 1–365 day window: period statistics (start, end, % change, high, low), a downsampled daily series, high_30d, std_30d, and dca_baseline_90d. Use for period comparisons and trend analysis; prefer over web_search for time-comparative financial queries. Pass stats_only=true when the daily series is unnecessary. Use when: Use for time-comparative financial questions — month-over-month, YTD, volatility, or DCA baselines. Prefer over web_search for such queries. Use the pre-computed stats directly; do not re-derive them with calculate. Limitations: Daily granularity (downsampled), max 365-day window, CoinGecko coverage only. Check dca_baseline_90d_partial before relying on the baseline — incomplete history yields a partial baseline. Alternatives: get_token_price, web_search

輸入參數daystokens必填stats_onlyvs_currency

get_yield_rates

Get Yield Rates

Get DeFi yield pool rates from DeFiLlama across 1,000+ protocols and all chains: pools sorted by APY with TVL, base/reward APY, and 7d/30d mean APY context, filterable by protocol, chain, min TVL, min/max APY, and symbol. Returns up to 50 pools. For protocol-specific lending comparisons (Aave vs Compound) prefer get_lending_rates. Use when: Use for broad cross-protocol yield discovery. Call at most once per request — filter with min_apy, max_apy, min_tvl_usd, and symbols_any in a single call, then sort client-side rather than re-calling. For protocol-specific rate questions use get_lending_rates. Limitations: Third-party DeFiLlama analytics; up to 50 pools per call. The `symbol` field lists underlying tokens (e.g. 'ETH-USDC') — filter client-side instead of re-calling with different arguments. Reward APY indicates reward-dependent yield; do not present spot APY as durable. Alternatives: get_lending_rates, get_protocol_tvl, get_token_price

輸入參數chainlimitmax_apymin_apyprotocolsmin_tvl_usdstable_onlysymbols_any

count_text_stats

Count Text Stats

Return word, character, sentence, and paragraph counts plus average words per sentence for a given text, for length checks and content sizing decisions. Use when: Use when output length must be validated or reported — e.g. verifying a summary meets a length contract or comparing document sizes. Do not use for semantic summarization; it counts only. Limitations: Pure counting on the provided text — no language detection, no reading-level or sentiment analysis, and no retrieval of external content. Alternatives: web_search, http_fetch

輸入參數text必填

http_fetch

Http Fetch

Fetch a web page and return its main text content, cleaned of markup. Use to read articles, documentation, and other resources referenced by URL. Blocks private and cloud-metadata addresses and re-validates every redirect hop. Use when: Use when a known URL's content is needed and structured tools cannot answer — e.g. reading a linked document or API docs. For general factual lookup prefer web_search; for token prices prefer get_token_price. Limitations: Read-only GET-style extraction returning cleaned text, not raw HTML or binary content. JS-heavy pages may yield little content; private/internal network targets are deliberately unreachable. Alternatives: web_search, get_token_price

輸入參數url必填max_chars

get_eth_balance

Get Eth Balance

Get the exact on-chain native ETH balance of an address on Ethereum or Base, in wei and ether. get_wallet_portfolio already includes native ETH in its holdings — call this only for a standalone balance without a portfolio scan. Use when: Use when a wallet's gas-availability or standalone ETH amount must be verified block-accurately. Do not call after or alongside get_wallet_portfolio — the holdings list already includes native ETH. Limitations: Native ETH only; ERC-20 balances require get_erc20_balance. Requires an EIP-55 checksummed address. Ethereum mainnet and Base only. Alternatives: get_wallet_portfolio, get_erc20_balance

輸入參數address必填chain_id

get_erc20_balance

Get Erc20 Balance

Get the exact on-chain ERC-20 balance of a wallet for one token contract, normalized by decimals and returned with the token's symbol. Use for a precise single-token check. Use when: Use when a specific token contract's balance must be verified block-accurately — e.g. confirming funds before an approval or transfer. For a multi-asset portfolio view use get_wallet_portfolio instead. Limitations: One token contract per call on Ethereum or Base; the contract address is required, so unknown tokens cannot be looked up by symbol. Returns raw balance data only — no USD valuation. Alternatives: get_wallet_portfolio, get_eth_balance

輸入參數chain_idtoken_address必填wallet_address必填

get_transaction

Get Transaction

Get details and receipt for one Ethereum or Base transaction by hash: bounded calldata, normalized event logs, transaction index, and receipt-derived effective gas price and fee when available. Use to verify a specific transaction's status and outcome. Use when: Use when one known transaction must be verified — status, logs, gas paid, or execution outcome. To understand what the calldata means use decode_transaction; for wallet-wide activity use get_wallet_history. Limitations: One transaction hash per call on Ethereum or Base; pending transactions may not resolve yet. Calldata is returned bounded, not decoded — use decode_transaction for semantic decoding. Alternatives: decode_transaction, get_block, get_wallet_history

輸入參數tx_hash必填chain_id

get_wallet_portfolio

Get Wallet Portfolio

Get aggregated token holdings with USD values for a wallet address. Tracks 19 major assets on Ethereum and 12 on Base, including spot, lending, liquid-staking, restaking, and stablecoin assets. Sorted by USD value. Returns up to 20 holdings. Includes native ETH balance in the holdings list — calling get_eth_balance separately after this is redundant. Use when: Choose when you need a wallet's overall token exposure and USD value on Ethereum or Base in one call. Call once per chain for a cross-chain comparison. Limitations: Tracks a fixed set of major assets per chain, not arbitrary tokens. Returns up to 20 holdings. Native ETH is included, so calling get_eth_balance separately is redundant. Alternatives: get_eth_balance, get_token_price, get_defi_positions

輸入參數chain_idwallet_address必填

get_wallet_history

Get Wallet History

Get one page of decoded transaction history for an EVM wallet across DeBank-supported chains. Returns send, receive, and approval categories with protocol, token, exchange, gas, and USD metadata. Use the returned next_cursor as start_time to page backward. Use when: Use for wallet activity discovery, protocol interaction history, exchange exposure, and gas analysis. Page backward with next_cursor for older activity. Use get_transaction or decode_transaction when one known transaction needs block-level details. Limitations: DeBank returns at most 20 entries per call and the data may be stale. This tool is not a complete ledger, PnL engine, or cost-basis calculator because historical execution prices and all transfer semantics are not guaranteed. Alternatives: get_transaction, decode_transaction

輸入參數chain_idspage_countstart_timewallet_address必填

get_wallet_positions

Get Wallet Positions

Get a wallet's DeFi positions across all DeBank-supported chains and protocols. Returns protocol-level positions, asset/debt/net USD values, optional token lists, aggregate exposure, and optional all-chain net worth. Set include_token_balances=true to also return DeBank's complete cross-chain wallet token list. Set include_token_lists=false for a compact balance and debt summary without nested position tokens. This covers substantially more protocols and chains than the block-accurate get_defi_positions tool. Use raw-RPC tools for liquidation, swap quotes, or other transaction-critical questions. Use when: Use for broad wallet discovery, portfolio allocation, protocol exposure, or cross-chain position questions. Set include_token_balances=true when complete wallet token discovery is required; otherwise the response only includes tokens attached to protocol positions. Set include_token_lists=false when only protocol balances, debt, or aggregate exposure are needed. Use get_defi_positions when the user needs a block-accurate Aave, Compound, Uniswap, or Lido snapshot. Limitations: DeBank portfolio data is third-party analytics and may be stale, including occasional long refresh delays. It is read-only, EVM wallet oriented, and does not prove current liquidation or execution state. include_token_balances adds a separate billable DeBank request; include_token_lists only changes response detail. Alternatives: get_defi_positions, get_wallet_portfolio, get_token_approvals

輸入參數wallet_address必填include_net_worthinclude_token_listsinclude_token_balances

read_contract

Read Contract

Call any view/pure function on a smart contract and return the decoded result, using a supplied ABI fragment. Supports historical reads via block_identifier and caller_address context for msg.sender-dependent views. Read-only: state-changing functions are rejected. Use when: Use when a protocol question needs a contract read that no higher-level tool covers — e.g. a niche view function or a protocol outside the standard tool set. Prefer purpose-built tools (get_defi_positions, get_lending_rates) for supported protocols. Limitations: Requires a valid ABI fragment; payable/nonpayable functions are rejected. Ethereum mainnet and Base only, with bounded RPC timeout and retry. Alternatives: get_defi_positions, get_lending_rates, get_token_approvals

輸入參數argschain_idargs_jsonabi_fragment必填function_name必填caller_addressblock_identifiercontract_address必填

record_predictions

Record Predictions

Record a complete structured prediction document for downstream evaluation. Call once with the exact machine-readable prediction; the human-readable report is provided separately. Use when: Use at the end of a scheduled analysis run to persist the machine-readable prediction for later scoring. Call exactly once with the complete prediction document — never partially or repeatedly. Limitations: Internal sink for scheduled analysis, not a caller-facing marketplace tool. Stores the prediction as given; no validation of prediction quality or deduplication across calls. Alternatives: get_datetime

輸入參數predictions必填

resolve_ens

Resolve Ens

Resolve an ENS name (e.g. 'vitalik.eth') to an Ethereum address, or an address to its primary ENS name, with avatar text record when available. Mainnet only. Use when: Use only when no 0x address is available and a name must become an address (or vice versa for attribution). If a 0x address is already present in the task or session, use it directly — resolution is redundant and adds latency. Limitations: Ethereum mainnet ENS only — no other chains or naming services. Reverse records are optional on ENS, so a valid address may legitimately have no primary name. Alternatives: get_wallet_portfolio, get_wallet_history

輸入參數name必填

validate_opportunity

Validate Opportunity

Return a decision-ready yield-opportunity verdict before capital is deployed. The result branches to sustainable, caution, unsustainable, or insufficient_data and gives the calling agent the evidence needed to proceed, pause, or reject the opportunity. Use when: Delegate this check before deploying capital into a DeFi yield pool or staking opportunity when the caller needs an independent sustainability and liquidity decision. Limitations: Heuristic economic assessment based on DeFiLlama analytics and CoinGecko pricing. Does not audit smart contract bytecode, protocol governance, or admin key security. Alternatives: get_yield_rates, get_protocol_tvl, get_lending_rates, assess_counterparty_risk

輸入參數pool_id必填

版本歷史

1
  1. v1.0.0最新Oct 13, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分

    請在儲存庫或註冊中心條目中宣告授權條款。