@dzapio/ai
v1.0.0
Published
DZap SDK and CLI for agent execution and wallet-aware prompts.
Downloads
69
Readme
DZap AI (@dzapio/ai)
This repository is a DeFi AI execution stack that ships four product surfaces from one codebase:
- TypeScript/JavaScript SDK (
DZapSDK) - Interactive CLI (
dzap,dzapai,DzapAI) - Express HTTP server (SSE chat + session/schedule endpoints)
- MCP server (stdio + streamable HTTP at
/mcp)
It also contains internal scheduling, retrieval (RAG over DZap docs), tool orchestration, and session-level logging.
Verified Deployment and Package Status (checked on May 26, 2026)
- Deployed URL:
https://nlp-ai-439689868940.europe-north1.run.app - NPM page:
https://www.npmjs.com/package/@dzapio/ai GET /on the deployed service responds successfully and returns a random wizard-style JSON message.- NPM package:
@dzapio/ai - Latest published NPM version at check time:
0.0.1 - Local repo package metadata is currently
name: dzapai,version: 1.0.0(not the same value as published@dzapio/aimetadata).
What This Repo Actually Implements
Core Runtime
DZapSDKis the main orchestrator.- User metadata is required for every ask call (
metadata.accountInfo[]). - Metadata sent to the LLM prompt is sanitized (only
blockchain,chain,user_account; private key is excluded from prompt text). - Session memory is in-process and keyed by generated UUID session IDs.
- Tool steps are streamed via callback (
onStep) with normalized input/output payloads. - Session logging records:
- metadata
- conversation timeline
- structured tool logs
- per-session summary counters
AI Model and Tool Calling
- Agent implementation uses
@ai-sdk/openaiwithgenerateText(...). - Default model:
gpt-4o-mini(DZAP_OPENAI_MODELoverride supported). - Tool choice is automatic.
- Max step count is capped (
stepCountIs(25)). - Retries and timeout are configurable (
DZAP_MODEL_MAX_RETRIES,DZAP_MODEL_TIMEOUT_MS).
Tool Exposure Pipeline
Tool flow is:
ToolFactory -> EXPOSED_TOOL_NAMES -> SDKToolsRegistry -> DZapSDK -> CLI / HTTP / MCP
All exposed tools are wrapped by SDKTool, which:
- runs zod parse validation when available
- executes tool code
- normalizes JSON-string outputs into structured objects when possible
- returns a typed execution result with duration and error details
Complete Exposed Tool Catalog (21 Tools)
Interactive tools (requires explicit user confirmation flow in some contexts): ChangeChainTool, PerformZapTool.
1) PriceTool
- Purpose: token price lookup for one or more token addresses on a chain
- Input:
tokenAddresses: string(comma-separated addresses)chainId: number
- Backend:
@dzapio/sdk(getTokenPrices)
2) BalanceTool
- Purpose: wallet token balances
- Input:
chainId: numberaccount: stringfor_user: boolean(used to signal UI-focused balance fetch)
- Backend:
https://zap.dzap.io/v1/user/balances
3) TokenAddressTool
- Purpose: symbol-to-address and decimals lookup from static chain token mapping
- Input:
symbol: stringchainId: number
- Returns symbol/chain/address/decimals payload
4) DollarToTokenAmountTool
- Purpose: converts USD amount to token amount using fetched token price
- Input:
tokenAddresses: stringchainId: numberamount: number
5) TrendingNewsTool
- Purpose: fetch hot approved crypto news
- Input:
tokens: string
- Backend: CryptoPanic API
6) TrendingTokenTool
- Purpose: fetch trending tokens
- Input: none
- Backend: CoinGecko trending endpoint
7) ZapCallDataGeneratorTool
- Purpose: generate and cache route/calldata for swap/bridge/zap execution
- Input:
srcToken,srcChainId,srcDecimalsdestToken,destChainId,destDecimalsaccount,recipientamount,decimalAmountsessionIdtype: "swap" | "bridge" | "zap"
- Behavior: stores route data in per-session zap registry
8) PerformZapTool (interactive)
- Purpose: execute previously generated session zap route on-chain
- Input:
sessionId: string
- Behavior:
- loads cached route
- optional user confirmation callback (SDK/CLI controlled)
- resolves RPC URL with priority:
DZAP_RPC_URL_<chainId>RPC_URL_<chainId>DZAP_RPC_URL- built-in public RPC fallback table
- handles approvals via
@dzapio/sdkallowance/approve flow - executes final transaction with
viem - waits for receipts
- clears cached zap data
- returns tx summary including explorer-style tracking link
9) PricePredictionTool
- Purpose: short-horizon price inference via Allora
- Input:
tokenSymbol: "BTC" | "ETH"
- Timeframe used:
EIGHT_HOURS
10) BridgeLinkGeneratorTool (deprecated)
- Purpose: build bridge URL
- Input:
fromAmount,fromChain,fromToken,toChain,toToken
- Base URL:
https://test.dzap.io/trade
11) SwapLinkGeneratorTool (deprecated)
- Purpose: build swap URL
- Input:
fromAmount,fromChain,fromToken,toChain,toToken
- Base URL:
https://test.dzap.io/trade
12) SentimentTool
- Purpose: text sentiment analysis
- Input:
text: string
- Output: sentiment label, score, comparative, positive/negative words
13) WebSearchTool
- Purpose: web search (general/news) using Tavily
- Input:
querytopic: "general" | "news"include_answer: booleanmax_results: numbertime_range: "day" | "week" | "month" | "year" | "d" | "w" | "m" | "y"days: numbersearch_depth: "basic" | "advanced"
14) DefiPositionsTool
- Purpose: DeFi positions for address/provider/chain
- Input:
address: stringchain: numberprovider: enum(available providers from static config)
- Backend:
https://zap.dzap.io/v1/user/positions
15) SheluderTool
- Purpose: create scheduled future action
- Input:
userId,chainaction: swap|bridge|zap|buy|sell|addLiquidity|removeLiquiditydata: string(JSON string payload)timeTrigger: ISO string- optional
onChainTrigger(contract,event,condition)
- Persists to SQLite
16) GetAllSchedulesTool
- Purpose: return all scheduled actions
- Input: none
17) RagOverDocsTool
- Purpose: retrieve relevant chunks from indexed DZap docs
- Input:
query: string
- Output:
documentsarray withsource,chunkIndex,text,score
18) PoolTool
- Purpose: pool data lookup by provider and chain
- Input:
chainId: numberprovider: enum(valid provider IDs)
19) RequestChainChangeTool
- Purpose: queue chain-switch request context in session
- Input:
chainID: numbersessionId: string
20) ChangeChainTool (interactive)
- Purpose: await user confirmation for chain switch
- Input:
chainID: numbersessionId: string
- Behavior:
- waits up to 120s for resolver response
- returns timeout message if unresolved
- session resolution is completed externally through
POST /zap/chain/:sessionId(defaultSdk.confirmChainChange(...))
21) ShowBalanceUITool
- Purpose: UI trigger only; does not fetch balances
- Input:
tokens: TokenEntry[](strict schema with address, symbol, decimals, price, balance fields, chainId, type, provider)
SDK API Surface (DZapSDK)
Constructor
new DZapSDK({
baseUrl?: string,
systemPrompt?: string,
systemPromptPath?: string
})initialize(options?)
await sdk.initialize({
syncProviders?: boolean, // pulls /config/providers and rewrites static providers JSON
initializeRetrieval?: boolean // initializes BM25 index over docsURLs.txt
});ask(input)
const result = await sdk.ask({
userQuery: string,
metadata: {
accountInfo: [{
blockchain: string,
chain: string,
user_account: string,
private_key?: string
}]
},
sessionId?: string,
transactionConfirmationMode?: "on" | "off",
onTransactionConfirmation?: async (request) => boolean,
onStep?: (step) => void
});Return payload includes:
sessionIdfinalTextchainId- optional
balanceData steps[]tool-step events
Other SDK methods
getChatHistory(sessionId)listTools()getTool(name)executeTool(name, input?)getSessionHistory(sessionId)(conversation + logs snapshot)getSchedulesByUserId(userId)confirmZap(sessionId, message)confirmChainChange(sessionId, message)runSchedulerOnce()startSchedulerLoop(intervalMs)
CLI Product Surface
Run:
DzapAI
# or
dzapai
# or
dzapCLI startup flow:
- initialize SDK
- load or collect wallet profile (
wallet,chain,blockchain,privateKey) - save profile to
~/.dzapai/config.json - enter interactive shell
Slash commands:
/help/tools/tool <Name> [JSON]/debug <on|off|show>/confirmmode <on|off|show>/profile/set wallet <value>/set chain <value>/set blockchain <value>/set privatekey <value>/session show/session new/session history/save/init/clear/exit
CLI UX features:
- markdown-aware terminal rendering
- concise tool-step summaries (or full payload view in debug mode)
- transaction confirmation card for on-chain execution
- runtime switch for mandatory tx approval prompts
HTTP Server Product Surface
Start:
npm run dev
# or compiled:
npm run build
npm startDefault port: 3001 (or PORT override).
Routes
GET /- random message payload
POST /ask_stream- SSE response stream
- emits tool step events and a final message event
- step event shape includes:
response.type = "step"response.tool_nameresponse.dataresponse.session_id
- final event shape includes:
response.type = "finalText"response.data(assistant final text)response.session_idresponse.chain_id- optional
response.balance_dataandresponse.balance_ui = true
- stream terminates with
data: [DONE] - expects body:
user_query: stringsession_id: stringmetadata.accountInfo[]
GET /stream_history?session_id=<id>- returns chat history for session
GET /sessions/:sessionId/history- returns detailed session snapshot (summary, metadata, conversation, logs)
GET /schedules/:userId- returns schedules for specific user
POST /zap/confirm/:sessionId- body
{ "message": "..." } - resolves pending zap interaction
- body
POST /zap/chain/:sessionId- body
{ "message": "..." } - resolves pending chain-change interaction
- body
POST /mcp,GET /mcp,DELETE /mcp- MCP Streamable HTTP transport
MCP Product Surface
Stdio MCP
npm run mcp:dev
# or
npm run build
npm run mcpPackaged CLI binary in this repo: dzap-mcp (wired in local package.json bin map).
HTTP MCP
When express server is running, MCP is available at /mcp.
Session behavior:
- initialize request creates MCP session
mcp-session-idheader identifies session on subsequent requests- delete closes associated server + transport
MCP Resources
dzap://tools/catalog- current tool catalogdzap://prompts/system- system prompt textdzap://docs/urls- docs URL list used by retrieval
MCP Prompts
wallet-overviewtool-execution-plan
Library exports for MCP embedding:
createDzapMcpServer(...)startDzapMcpServer(...)
Retrieval (RAG) Capabilities
Retrieval pipeline:
- read URLs from
src/static/docsURLs.txt - fetch HTML
- extract primary text with Readability
- fallback DOM cleanup + main content selection
- chunk text (
chunkSize=500,overlap=100) - build BM25 index
- retrieve top-k by lexical relevance score
Current indexed source URL list:
https://docs.dzap.io/https://docs.dzap.io/sdk/overviewhttps://docs.dzap.io/ai/mcphttps://docs.dzap.io/api-reference/config/fetch-supported-providers
Scheduler and Persistence
Storage:
- SQLite via
better-sqlite3 - default DB path:
schedules.db(override withDB_PATH)
Schema stores:
id,user_id,chain,action,datatime_trigger, optionalonchain_triggerstatus,created_at,updated_at
Statuses:
pending,running,done,error
Scheduler behavior:
- periodic loop from server startup (every 60s by default)
- fetches due pending jobs
- evaluates optional
onChainTrigger.conditionusingnew Function(...)with fetched context - marks status transitions
- execution hook currently stubbed (tool execution call point exists but not wired)
Static Intelligence Assets Included
From the bundled static files:
- Chains in
chain_IDs.json:48 - Token maps in
chain_symbol_to_token_address_mapping.json:48chains17,179symbol entries total
- DeFi providers in
defi_providers.json:43 - Pools in
pools.json:18,615records
Provider IDs currently present:
aave, aerodrome, balancer, bedrock, benqi, bima, blackhole, camelot, compound, curve, dragonswap, ethena, etherfi, euler, extrafi, extrafixlend, felix, fluid, funnel, gearbox, harmonix, hybra, hyperlend, hypurrfi, lagoon, moonwell, pancakeswap, projectx, puffer, quickswap, radiant, takara, sailor, segment, silo, sparklend, sushiswap, truf, ultrasolid, uniswap, velodrome, venus, yei
Chain map currently bundled in chain_IDs.json:
ethereum: 1
polygon: 137
bsc: 56
fire: 995
gnosis: 100
fantom: 250
avalanche: 43114
arbitrum: 42161
optimism: 10
zkSync: 324
base: 8453
scroll: 534352
manta: 169
blast: 81457
btc: 1000
solana: 7565164
telos: 40
core: 1116
rootstock: 30
bobaeth: 288
bobabnb: 56288
kava: 2222
arbitrumnova: 42170
polygonzkevm: 1101
tron: 728126428
linea: 59144
mantle: 5000
metis: 1088
bahamut: 5165
mode: 34443
merlin: 4200
zklink: 810180
taiko: 167000
sei: 1329
zetachain: 7000
moonbeam: 1284
moonriver: 1285
aurora: 1313161554
kroma: 255
bob: 60808
bitlayer: 200901
xlayer: 196
opbnb: 204
cronos: 25
kcc: 321
astar: 592
celo: 42220
sonic: 146Build, Package, and Deploy
Scripts
npm run build- transpilesrctodist/src(custom TypeScript transpile script)npm run dev- server from TS (ts-node)npm start- server from compiled JSnpm run mcp:dev- MCP stdio from TSnpm run mcp- MCP stdio from compiled JSnpm run cli- run compiled CLInpm test- jest (config present; no test directory currently in repo)npm run docker- build + run docker imagenpm run deploy- interactive Cloud Run deployment scriptnpm run pack:tester- build and generate.tgz
Docker
- Base image:
node:22 - Exposes:
3001 - Entrypoint:
node dist/src/server/index.js
Cloud Run Deploy Script (deploy.mjs)
Implements:
- staging vs production prompt
.envload + YAML generation for env vars- Docker build and push to Artifact Registry (region
europe-north1) - Cloud Run deploy with:
--session-affinity(important for MCP session continuity)--memory 512Mi--port 3001--allow-unauthenticated
Install from NPM (@dzapio/ai)
If you are consuming the published package:
npm install @dzapio/aiCLI global install:
npm install -g @dzapio/ai
dzapIf your environment has scoped registry rules pointing @dzapio to GitHub Packages, you may need to override registry settings for npmjs.org when installing this specific package.
Example override:
npm install @dzapio/ai --@dzapio:registry=https://registry.npmjs.orgEnvironment Variables
Required in practice
OPENAI_API_KEY(required by@ai-sdk/openaifor model calls)
Common runtime
PORT(default3001)DZAP_OPENAI_MODEL(defaultgpt-4o-mini)DZAP_MODEL_MAX_RETRIES(default2)DZAP_MODEL_TIMEOUT_MS(default4500000)LOG_LEVEL(defaultinfo, CLI/MCP set toerrorif unset)DB_PATH(defaultschedules.db)
RPC and transaction execution
DZAP_RPC_URL_<chainId>RPC_URL_<chainId>DZAP_RPC_URL
CLI behavior
DZAP_CLI_DEBUGDZAP_CONFIRM_TRANSACTIONS
MCP settings
DZAP_MCP_SERVER_NAME(defaultdzap-mcp-server)DZAP_MCP_SERVER_VERSION(default env package version or1.0.0)DZAP_MCP_SYNC_PROVIDERS(defaultfalse)DZAP_MCP_INIT_RETRIEVAL(defaulttrue)DZAP_MCP_HTTP_ENABLED(defaulttrue)DZAP_MCP_HTTP_TOKEN(optional) — when set, every/mcpHTTP request must sendAuthorization: Bearer <token>. Strongly recommended for any public deployment; if unset the endpoint is open and logs a warning.DZAP_MCP_ALLOWED_ORIGINS(optional) — comma-separatedOriginallowlist for the/mcpHTTP endpoint (blocks drive-by browser callers).
External data providers (with code-level fallbacks currently present)
CRYPTOPANIC_API_KEYTAVILY_API_KEYCOINSTATS_API_KEYMORALIS_API_KEY
Deployment-only
NPM_TOKEN(required by deploy script and.npmrcflow)
Modules Present but Not Currently Wired Into the Exposed Tool List
These exist in src/tools but are not in ToolFactory exposure:
CoinStatswrapper (src/tools/coinstats.ts)Moraliswrapper (src/tools/moralis.ts)LimitOrderhelper (src/tools/limitOrder.ts)
The ZapGPT class also exists, but active runtime uses CLIAgent in DZapSDK.
Minimal SDK Example
import { DZapSDK } from "@dzapio/ai";
const sdk = new DZapSDK();
await sdk.initialize({
initializeRetrieval: true,
syncProviders: false,
});
const result = await sdk.ask({
userQuery: "Show my balances",
metadata: {
accountInfo: [
{ blockchain: "evm", chain: "1", user_account: "0xabc..." }
]
},
transactionConfirmationMode: "on",
});
console.log(result.finalText);