Developer docs

OpenAI SDK

Self-hosted OpenAI Agents SDK integration for VeTrade with hosted MCP and local VeChain execution.

VeTrade now publishes a self-hosted Node integration for the official OpenAI Agents SDK at agents/openai-sdk/.

This path keeps the same safety boundary as the rest of VeTrade:

  • the public MCP server stays read-only
  • signing stays local through PRIVATE_KEY or privateKeyFile
  • fee delegation stays local through GAS_PAYER_PRIVATE_KEY or gasPayerPrivateKeyFile
  • live execution reuses the published localExecution.mjs helper instead of rebuilding VeChain submission logic in a second codepath

This rollout is self-hosted Node only. It does not target Agent Builder, hosted key custody, or a remote VeTrade signing service.

Choose planning or execution

Planning: install the package, provide OPENAI_API_KEY, and run the read-only example. No wallet key is needed. Keep executionPolicy.allowedActions: [].

Local execution: complete planning setup first, then configure a local signer and a narrow execution policy. Fund input tokens and gas. An enabled live tool can submit a real transaction; hosted MCP itself still does not sign.

Install · Read-only example · Live example · Policy.

What this package gives you

  • buildVetradeAgent(config) for a reusable OpenAI agent entrypoint
  • OpenAI hosted MCP access to the public VeTrade read-only tools
  • local function tools for:

- quote_swap

- execute_swap

- execute_transfer

- execute_swap_transfer_exact_in

- execute_swap_transfer_exact_out

- create_limit_order

- cancel_limit_order

- cancel_all_limit_orders

- list_limit_orders

- get_limit_order_status

  • hosted MCP tools for read-only planning, discovery, validation, and readiness inspection
  • overlapping hosted task tools such as transfer, swap_transfer_exact_in, swap_transfer_exact_out, swap, create_limit_order, and cancel_limit_order stay available only when the matching local live tool is not enabled
  • typed execution policy checks before broadcast
  • compact execution results with signer, tx id, gas, fees, settlement or order status, warnings, runtimeSource, and timings

Package location

agents/openai-sdk/

Install

From agents/openai-sdk/:

npm install
npm run build

The agent run still uses OpenAI’s Responses API, so export OPENAI_API_KEY before running the examples.

For live execution, also provide signer material through one of these:

  • PRIVATE_KEY in the environment
  • privateKeyFile in the agent config
  • PRIVATE_KEY_FILE in the example scripts
  • optional sponsor gas payer through GAS_PAYER_PRIVATE_KEY in the environment
  • optional sponsor gas payer through gasPayerPrivateKeyFile in the agent config
  • optional GAS_PAYER_PRIVATE_KEY_FILE in the example scripts
  • optional defaultGasPaymentMode: 'sender' | 'gas_payer' in the agent config

Do not pass raw private keys in tool arguments.

The OpenAI SDK path reuses the same deterministic local execution cache as localExecution.mjs at $CODEX_HOME/state/vetrade-ai/localExecutionState.json (under ~/.codex when CODEX_HOME is unset). Identical execution inputs can reuse a prior result. Inspect the stored transaction ID and its receipt before deliberately starting another identical transaction; clearing state is not recovery for an uncertain submission.

Local execution setup

Use this package when you want one self-hosted agent that can plan through the hosted MCP surface and sign locally.

  1. Export OPENAI_API_KEY plus PRIVATE_KEY or PRIVATE_KEY_FILE.
  2. If you want VIP-191 fee delegation by default, also export GAS_PAYER_PRIVATE_KEY or GAS_PAYER_PRIVATE_KEY_FILE, or configure gasPayerPrivateKeyFile.
  3. Keep executionPolicy narrow so the agent only has the actions and token pairs you actually want.
  4. Let the agent use local quote_swap for quote-only asks and local execute_* tools for live transfer, swap, swap-transfer, or limit-order submission.
  5. The hosted MCP surface remains available for lower-level planning, discovery, validation, readiness, and advanced prepare work, plus overlapping task tools only when the matching local live tool is disabled.
  6. Use local quote_swap, list_limit_orders, and get_limit_order_status for the default human-friendly read path, and use hosted prepare_swap_bundle, get_execution_readiness, or the inspect_*_readiness tools when you explicitly want a lower-level or summary-first flow outside the local wrappers.

Hosted task tools return an executionPackage as the planning handoff. Local wrappers validate that package before signing; the package itself is not settlement.

Hosted vs local tool surface

  • Local quote_swap, list_limit_orders, and get_limit_order_status always own the default human-friendly read path in this package.
  • Local execute_transfer, execute_swap, execute_swap_transfer_exact_in, execute_swap_transfer_exact_out, create_limit_order, and cancel_limit_order own live submission when they are enabled.
  • buildVetradeAgent hides the overlapping hosted task tool for each local wrapper so the model does not bypass the safer local signer path.
  • Hosted discovery, validation, readiness, and advanced prepare tools stay available.
  • If you want an overlapping hosted task tool back for planning or debugging, disable the matching local live action in executionPolicy.allowedActions or call the hosted MCP server directly.

The SDK uses an explicit hosted-tool allowlist. It currently omits hosted quote and the thor_* tools available on the full MCP server; its local quote_swap remains the human-amount quote interface. Use a direct MCP client for the wider chain-read catalog.

Minimal read-only agent

Prerequisites: Node, the installed package and OPENAI_API_KEY. From agents/openai-sdk/, run the shipped example:

npx tsx examples/readOnlyAgent.ts

Expected: a structured run result describing supported tokens and readiness inspection, with no transaction broadcast. Model wording and current token data vary. The example source is:

import { buildVetradeAgent } from '../src/index.js';

const { run } = buildVetradeAgent({
  executionPolicy: {
    allowedActions: [],
    recipientMode: 'signer_only'
  }
});

const result = await run(
  'List the supported VeTrade tokens and explain how to inspect swap readiness without signing anything.'
);
console.log(JSON.stringify(result, null, 2));

Minimal live transfer agent

Prerequisites: planning setup, a local PRIVATE_KEY_FILE, funded VET and VTHO or configured sponsor, and an independently verified recipient. Save this example as examples/liveTransferAgent.ts; replace friend.vet with your intended recipient. Run npx tsx examples/liveTransferAgent.ts only when you intend to submit the transfer.

Expected: either an instructive preflight failure or a transaction ID with receipt/settlement results. Verify the final recipient and actual amount; a tool call alone is not confirmation. Never put a private key in the prompt or tool arguments.

import { buildVetradeAgent } from '../src/index.js';

const { run } = buildVetradeAgent({
  privateKeyFile: process.env.PRIVATE_KEY_FILE,
  gasPayerPrivateKeyFile: process.env.GAS_PAYER_PRIVATE_KEY_FILE,
  defaultGasPaymentMode: process.env.DEFAULT_GAS_PAYMENT_MODE === 'gas_payer' ? 'gas_payer' : 'sender',
  executionPolicy: {
    allowedActions: ['execute_transfer'],
    maxInputPerSymbol: { VET: '5' },
    requireFreshQuote: true,
    allowStaleQuoteExecution: false,
    recipientMode: 'recipient_optional'
  }
});

const result = await run('Send 1 VET to friend.vet.');
console.log(JSON.stringify(result, null, 2));

Execution policy

The first package version supports:

  • allowedActions
  • allowedTokenPairs
  • maxInputPerSymbol
  • maxSlippageBps
  • requireFreshQuote
  • allowStaleQuoteExecution
  • recipientMode: 'signer_only' | 'recipient_optional'

Use recipientMode: 'signer_only' when every live action must settle back to the signer. Use recipientMode: 'recipient_optional' when execute_transfer, execute_swap_transfer_exact_in, or execute_swap_transfer_exact_out may target another resolved recipient.

The execution service validates the policy at startup, then re-checks signer, balances, freshness, and bundle validation immediately before broadcast. Economics remain advisory warning data in the returned preview and execution results instead of a local submit gate.

Field-level MCP validation errors now flow through the SDK client, so agent-visible failures include the failing argument summary instead of only a generic retry message.

Local tool inputs

The local function tools intentionally use human-readable amounts:

  • quote_swap

- inputToken: symbol or address

- outputToken: symbol or address

- amount: decimal string such as "1.5"

- optional slippageBps, maxHops, maxSplits, outputMode

  • execute_swap

- inputToken: symbol or address

- outputToken: symbol or address

- amount: decimal string such as "1.5"

- optional gasPaymentMode: 'inherit' | 'sender' | 'gas_payer', slippageBps, maxHops, maxSplits, outputMode

  • execute_transfer

- token: symbol or address

- amount: decimal string such as "1.5"

- recipient: VeChain address or .vet name

- optional gasPaymentMode, outputMode

  • execute_swap_transfer_exact_in

- inputToken: symbol or address

- outputToken: symbol or address

- amount: decimal input amount such as "1.5"

- recipient: VeChain address or .vet name

- optional gasPaymentMode, slippageBps, maxHops, maxSplits, outputMode

  • execute_swap_transfer_exact_out

- inputToken: symbol or address

- outputToken: symbol or address

- amount: decimal final output amount such as "1.5"

- recipient: VeChain address or .vet name

- optional gasPaymentMode, slippageBps, maxHops, maxSplits, outputMode

  • create_limit_order

- inputToken: symbol or address

- outputToken: symbol or address

- amount: decimal string

- exactly one of targetPrice or minAmountOut

- optional gasPaymentMode, outputMode

  • cancel_limit_order

- orderId

- optional gasPaymentMode, unwrapVvetOnCancel

- optional outputMode

  • cancel_all_limit_orders

- optional inputToken

- optional outputToken

- optional gasPaymentMode

  • list_limit_orders

- optional maker

- optional status, inputToken, outputToken, page, pageSize

  • get_limit_order_status

- orderId

The package now treats the hosted MCP executionPackage as the canonical planning artifact. For quote-only reads, the local quote_swap tool resolves symbols, converts the human amount into base units, calls hosted quote_swap, and returns compact route-aware results. For transfers and swap-transfers, the SDK consumes the hosted transfer, swap_transfer_exact_in, and swap_transfer_exact_out packages directly, preserves recipient .vet resolution metadata, and signs locally. For swaps, the local helper consumes the hosted swap package directly and derives the signer address from PRIVATE_KEY or privateKeyFile. When sponsor material is configured, the same helper can optionally use VIP-191 fee delegation with defaultGasPaymentMode: 'gas_payer' or a per-call gasPaymentMode override. For limit orders, the SDK consumes the hosted create_limit_order and cancel_limit_order packages directly instead of rebuilding clauses locally, and it adds typed one-shot management helpers for list, status, and cancel-all.

Inspect tools

The public MCP server also exposes compact readiness helpers and lower-level advanced tools for callers that intentionally need more control:

  • inspect_swap_readiness
  • inspect_limit_order_creation_readiness
  • inspect_limit_order_cancellation_readiness
  • quote_swap
  • prepare_swap_bundle
  • prepare_limit_order
  • prepare_limit_order_cancellation

Use these only when an agent needs a summary-first preflight answer or a lower-level bundle flow instead of the default hosted transfer, swap_transfer_exact_in, swap_transfer_exact_out, swap, create_limit_order, cancel_limit_order, list_limit_orders, or get_limit_order_status path.

Published examples

  • https://vetrade.vet/examples/ai/openai-sdk/readOnlyAgent.ts
  • https://vetrade.vet/examples/ai/openai-sdk/liveSwapAgent.ts
  • https://vetrade.vet/examples/ai/openai-sdk/limitOrdersAgent.ts
  • https://vetrade.vet/examples/ai/openai-sdk/README.md

Boundaries

  • VeTrade MCP stays read-only
  • signing stays local
  • live submission still revalidates signer, freshness, and validation before broadcast while reporting economics as advisory data
  • this package is a reference integration, not a hosted VeTrade execution service

Recovery

For schema failures, correct the reported fields before retrying. For missing credentials, configure them only in your local runtime. For a submitted transaction timeout, inspect the transaction ID and receipt before another attempt. Do not clear the local execution cache until you have checked whether the earlier submission completed. Error reference.