New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

@t2000/engine

Package Overview
Dependencies
Maintainers
1
Versions
303
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@t2000/engine

Agent engine for conversational finance — QueryEngine, financial tools, LLM orchestration

Source
npmnpm
Version
0.5.3
Version published
Weekly downloads
56
460%
Maintainers
1
Weekly downloads
 
Created
Source

@t2000/engine

Agent engine for conversational finance — powers the Audric consumer product.

QueryEngine orchestrates LLM conversations, financial tools, user confirmations, and MCP integrations into a single async-generator loop.

Quick Start

import { QueryEngine, AnthropicProvider, getDefaultTools } from '@t2000/engine';
import { T2000 } from '@t2000/sdk';

const agent = await T2000.create({ pin: process.env.T2000_PIN });

const engine = new QueryEngine({
  provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
  agent,
  tools: getDefaultTools(),
});

for await (const event of engine.submitMessage('What is my balance?')) {
  switch (event.type) {
    case 'text_delta':
      process.stdout.write(event.text);
      break;
    case 'tool_start':
      console.log(`\n[calling ${event.toolName}]`);
      break;
    case 'pending_action':
      // Write tool needs approval — client executes, then calls engine.resumeWithToolResult()
      break;
  }
}

Architecture

User message
    │
    ▼
QueryEngine.submitMessage()
    │
    ├── LLM Provider (Anthropic Claude)
    │       ├── text_delta events → streamed to client
    │       └── tool_use → dispatched to tool system
    │
    ├── Tool Orchestration (runTools)
    │       ├── Read-only tools  → parallel (Promise.allSettled)
    │       └── Write tools      → serial (TxMutex)
    │
    ├── Delegated Execution
    │       └── confirm-level tools yield pending_action
    │           → client executes on-chain → resumeWithToolResult()
    │
    └── MCP Integration
            ├── MCP Client (McpClientManager) → consume external MCPs
            └── MCP Server (buildMcpTools)    → expose tools to AI clients

Modules

ModuleExportPurpose
engine.tsQueryEngineStateful conversation loop with tool dispatch
tool.tsbuildToolTyped tool factory with Zod validation
orchestration.tsrunTools, TxMutexParallel reads, serial writes
streaming.tsserializeSSE, parseSSE, engineToSSESSE wire format
session.tsMemorySessionStoreIn-memory session store with TTL
context.tsestimateTokens, compactMessagesToken estimation + message compaction
cost.tsCostTrackerToken usage + USD cost tracking with budget limits
mcp.tsbuildMcpTools, registerEngineToolsExpose engine tools as MCP server
mcp-client.tsMcpClientManager, McpResponseCacheMulti-server MCP client with caching
mcp-tool-adapter.tsadaptMcpTool, adaptAllMcpToolsConvert MCP tools into engine Tool objects
navi-config.tsNAVI_MCP_CONFIG, NaviToolsNAVI MCP server configuration
navi-transforms.tstransformRates, transformBalance, ...Raw MCP response → engine types
navi-reads.tsfetchRates, fetchBalance, ...Composite MCP read functions
defillama-prices.tsfetchTokenPrices, clearPriceCacheBatch USD prices from DefiLlama (single price source)
tools/defillama.ts7 DefiLlama toolsYield pools, protocol info, token prices, price changes, chain TVL, fees, Sui protocols
tools/swap-quote.tsswapQuoteToolPreview swap route + price impact (read-only)
tools/swap.tsswapExecuteToolCetus Aggregator multi-DEX swap
tools/volo-stats.tsvoloStatsToolVOLO liquid staking stats (vSUI/SUI rate, APY, TVL)
tools/volo-stake.tsvoloStakeToolStake SUI → vSUI
tools/volo-unstake.tsvoloUnstakeToolUnstake vSUI → SUI
prompt.tsDEFAULT_SYSTEM_PROMPTAudric system prompt
providers/anthropic.tsAnthropicProviderAnthropic Claude LLM provider

Built-in Tools

Read Tools (14 — parallel, auto-approved)

ToolDescription
balance_checkAvailable, savings, debt, rewards, gas reserve (DefiLlama pricing)
savings_infoPositions, earnings, fund status
health_checkHealth factor with risk assessment
rates_infoCurrent supply/borrow APYs
transaction_historyRecent transaction log
swap_quotePreview swap route, output amount, and price impact (no execution)
volo_statsVOLO liquid staking stats — vSUI/SUI rate, APY, TVL
defillama_yield_poolsTop yield pools by APY, filterable by chain
defillama_protocol_infoProtocol TVL, category, chains
defillama_token_pricesCurrent USD prices for Sui tokens
defillama_price_changeToken price % change over period
defillama_chain_tvlChain TVL rankings
defillama_protocol_feesProtocol fees/revenue rankings
defillama_sui_protocolsSui ecosystem protocols — TVL, category, changes

Write Tools (10 — serial, confirmation required)

ToolDescription
save_depositDeposit to savings (optional asset for multi-asset NAVI deposits)
withdrawWithdraw from savings (optional asset for multi-asset withdrawals)
send_transferSend USDC to an address
borrowBorrow USDC against collateral
repay_debtRepay outstanding debt
claim_rewardsClaim pending yield rewards
pay_apiPay for an API service via MPP
swap_executeSwap any token pair via Cetus Aggregator (20+ DEXs)
volo_stakeStake SUI for vSUI (VOLO liquid staking)
volo_unstakeUnstake vSUI back to SUI

Configuration

interface EngineConfig {
  provider: LLMProvider;          // Required — LLM provider instance
  agent?: unknown;                // T2000 SDK instance (for tool execution)
  mcpManager?: unknown;           // McpClientManager (MCP-first reads)
  walletAddress?: string;         // User's Sui address (for MCP reads)
  tools?: Tool[];                 // Custom tool set (defaults to getDefaultTools())
  systemPrompt?: string;          // Override default Audric prompt
  model?: string;                 // LLM model override
  maxTurns?: number;              // Max conversation turns (default: 10)
  maxTokens?: number;             // Max tokens per response (default: 4096)
  costTracker?: {
    budgetLimitUsd?: number;      // Kill switch at USD threshold
    inputCostPerToken?: number;
    outputCostPerToken?: number;
  };
}

Event Types

The submitMessage() async generator yields EngineEvent:

EventFieldsWhen
text_deltatextLLM streams a text chunk
tool_starttoolName, toolUseId, inputTool execution begins
tool_resulttoolName, toolUseId, result, isErrorTool execution completes
pending_actionaction (PendingAction)Write tool awaiting client-side execution
turn_completestopReasonConversation turn finished
usageinputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?Token usage report
errorerrorUnrecoverable error

MCP Client Integration

Connect to external MCP servers (e.g., NAVI Protocol) for data:

import { McpClientManager, NAVI_MCP_CONFIG } from '@t2000/engine';

const mcpManager = new McpClientManager();
await mcpManager.connect(NAVI_MCP_CONFIG);

const engine = new QueryEngine({
  provider,
  agent,
  mcpManager,
  walletAddress: '0x...',
  tools: getDefaultTools(),
});

Read tools automatically use MCP when available, falling back to the SDK.

MCP Server Adapter

Expose engine tools to Claude Desktop, Cursor, or any MCP client:

import { registerEngineTools } from '@t2000/engine';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

const server = new McpServer({ name: 'audric', version: '0.1.0' });
registerEngineTools(server, getDefaultTools());

Custom Tools

import { z } from 'zod';
import { buildTool } from '@t2000/engine';

const myTool = buildTool({
  name: 'my_tool',
  description: 'Does something useful',
  inputSchema: z.object({ query: z.string() }),
  isReadOnly: true,
  permissionLevel: 'auto',
  async call(input, context) {
    return { data: { answer: 42 }, displayText: 'The answer is 42' };
  },
});

Development

pnpm --filter @t2000/engine build      # Build (tsup → ESM)
pnpm --filter @t2000/engine test       # Run tests (vitest)
pnpm --filter @t2000/engine typecheck  # TypeScript strict check
pnpm --filter @t2000/engine lint       # ESLint

License

MIT

Keywords

sui

FAQs

Package last updated on 03 Apr 2026

Related posts