Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(mcp-packages): preview-before-spend tools and per-group enablement across the local MCP servers

nirholas63be753889a7
diff --git a/packages/agentcore-payments-mcp/src/index.js b/packages/agentcore-payments-mcp/src/index.js
index 4bf4ea18e..ef5f98d29 100755
--- a/packages/agentcore-payments-mcp/src/index.js
+++ b/packages/agentcore-payments-mcp/src/index.js
@@ -29,6 +29,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { def as createSession } from './tools/create-session.js';
import { def as payWithSession } from './tools/pay-with-session.js';
+import { def as quoteSessionPayment } from './tools/quote-session-payment.js';
import { def as checkSession } from './tools/check-session.js';
import { def as listSessions } from './tools/list-sessions.js';
import { def as cancelSession } from './tools/cancel-session.js';
@@ -38,6 +39,7 @@ const { version: PKG_VERSION } = require('../package.json');
export const TOOLS = [
createSession,
+ quoteSessionPayment,
payWithSession,
checkSession,
listSessions,
diff --git a/packages/agentcore-payments-mcp/src/tools/quote-session-payment.js b/packages/agentcore-payments-mcp/src/tools/quote-session-payment.js
new file mode 100644
index 000000000..3d16280b8
--- /dev/null
+++ b/packages/agentcore-payments-mcp/src/tools/quote-session-payment.js
@@ -0,0 +1,75 @@
+// `quote_session_payment` — the quote that must run before pay_with_session.
+//
+// Probes the endpoint for its live x402 price through /api/pay/simulate (one
+// unpaid request, exactly what any x402 client does before deciding to pay) and,
+// when a session id is supplied, replays that price through the session's own
+// remaining budget, per-transaction ceiling and host allowlist. Nothing is
+// signed, no credit moves, no row is written.
+
+import { z } from 'zod';
+import { apiRequest } from '../lib/api.js';
+import { THREE_WS_SESSION } from '../config.js';
+
+// Wide enough to price any single call when no session policy is supplied.
+const PRICE_ONLY_POLICY = { budget_usd: 1000, max_per_tx_usd: null, allowed_hosts: [], expiry_seconds: 3600 };
+
+export const def = {
+ name: 'quote_session_payment',
+ title: 'Quote an x402 payment against a payment session (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Quote pay_with_session before it runs: the live x402 price of the endpoint and, when you pass session_id ' +
+ '(with THREE_WS_SESSION set), whether that session would settle it: its remaining budget, per-transaction ' +
+ 'ceiling and host allowlist, and the budget left afterwards. Makes one unpaid probe request and moves ' +
+ 'nothing. Show the price to the user, get a clear yes, then call pay_with_session with the same url and ' +
+ 'method, the returned quote_id and confirm_payment: true.',
+ inputSchema: {
+ url: z.string().url().describe('The x402 endpoint URL that will be paid.'),
+ method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method. Default: GET.'),
+ body: z.record(z.any()).optional().describe('JSON body for POST requests (some endpoints price by body).'),
+ session_id: z.string().uuid().optional().describe('The payment session that will pay. Needs THREE_WS_SESSION.'),
+ },
+ async handler(args) {
+ let session = null;
+ let policy = PRICE_ONLY_POLICY;
+ if (args.session_id) {
+ if (!THREE_WS_SESSION) {
+ throw Object.assign(new Error('session_id needs THREE_WS_SESSION so the session can be read.'), { code: 'no_session' });
+ }
+ ({ session } = await apiRequest(`/api/pay/session/${args.session_id}`, { auth: true }));
+ policy = {
+ budget_usd: Number(session.remaining_usd ?? session.budget_usd),
+ max_per_tx_usd: session.max_per_tx_usd ?? null,
+ allowed_hosts: session.allowed_hosts ?? [],
+ expiry_seconds: 3600,
+ network: session.network ?? 'solana',
+ };
+ }
+ const sim = await apiRequest('/api/pay/simulate', {
+ method: 'POST',
+ body: { policy, calls: [{ url: args.url, method: args.method ?? 'GET', ...(args.body ? { body: args.body } : {}) }] },
+ });
+ const step = sim.timeline?.[0] ?? null;
+ return {
+ ok: true,
+ url: args.url,
+ method: args.method ?? 'GET',
+ price_usd: step?.amount_usd ?? null,
+ pricing: step?.pricing ?? null,
+ outcome: step?.outcome ?? 'unpriced',
+ ...(session
+ ? {
+ session: { id: args.session_id, status: session.status, remaining_usd: session.remaining_usd, max_per_tx_usd: session.max_per_tx_usd, allowed_hosts: session.allowed_hosts },
+ // The simulator lifts a budget under the session minimum, so the
+ // remaining balance is checked here against the real number.
+ would_settle:
+ step?.outcome === 'free' ||
+ (step?.outcome === 'settles' && Number(step.amount_usd) <= Number(session.remaining_usd)),
+ refused_by: step?.rejected_by ?? null,
+ reason: step?.reason ?? null,
+ remaining_after_usd: step?.remaining_after_usd ?? null,
+ }
+ : {}),
+ };
+ },
+};
diff --git a/packages/agora-mcp/src/index.js b/packages/agora-mcp/src/index.js
index c9fe701e7..99874c5f7 100755
--- a/packages/agora-mcp/src/index.js
+++ b/packages/agora-mcp/src/index.js
@@ -41,10 +41,10 @@ import { def as agoraPulse } from './tools/pulse.js';
import { def as agoraCitizens } from './tools/citizens.js';
import { def as agoraPassport } from './tools/passport.js';
import { def as agoraProfessions } from './tools/professions.js';
-import { def as agoraRegister } from './tools/register.js';
+import { def as agoraRegister, quoteDef as agoraQuoteRegister } from './tools/register.js';
import { def as agoraClaimTask } from './tools/claim-task.js';
import { def as agoraCompleteTask } from './tools/complete-task.js';
-import { def as agoraPostTask } from './tools/post-task.js';
+import { def as agoraPostTask, quoteDef as agoraQuoteTask } from './tools/post-task.js';
// Single source of truth for the advertised server version — package.json.
const require = createRequire(import.meta.url);
@@ -56,9 +56,11 @@ export const TOOLS = [
agoraCitizens,
agoraPassport,
agoraProfessions,
+ agoraQuoteRegister,
agoraRegister,
agoraClaimTask,
agoraCompleteTask,
+ agoraQuoteTask,
agoraPostTask,
];
diff --git a/packages/agora-mcp/src/lib/agenc.js b/packages/agora-mcp/src/lib/agenc.js
index 05562cba7..877bc2f1f 100644
--- a/packages/agora-mcp/src/lib/agenc.js
+++ b/packages/agora-mcp/src/lib/agenc.js
@@ -308,3 +308,48 @@ export function resolveRewardMint(cluster, mint) {
const m = String(mint || '').trim();
return m || THREE_MINT;
}
+
+const PUBLIC_RPC = {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+};
+
+/**
+ * Read the signer's live balances for a preview: native SOL, and the reward
+ * mint's token balance when the escrow is an SPL token. Read-only.
+ * @param {{ cluster: 'mainnet'|'devnet', pubkey: string, mint?: string|null }} input
+ */
+export async function signerBalances({ cluster, pubkey, mint = null }) {
+ const { Connection } = await import('@solana/web3.js');
+ const conn = new Connection(RPC_URL || PUBLIC_RPC[cluster], 'confirmed');
+ const owner = new PublicKey(pubkey);
+ const lamports = await conn.getBalance(owner, 'confirmed');
+ let token = null;
+ if (mint) {
+ const res = await conn.getParsedTokenAccountsByOwner(owner, { mint: new PublicKey(mint) });
+ const atomic = res.value.reduce((sum, a) => sum + BigInt(a.account.data.parsed.info.tokenAmount.amount), 0n);
+ const decimals = res.value[0]?.account.data.parsed.info.tokenAmount.decimals ?? null;
+ token = { mint, amountAtomic: String(atomic), decimals };
+ }
+ return { lamports, sol: lamports / 1e9, token };
+}
+
+/**
+ * Resolve where a registration would land without signing: the derived agent
+ * id and PDA, and whether that agent already exists on-chain (in which case a
+ * register call spends nothing).
+ */
+export async function previewRegistration({ cluster, identityRef, baseUrl }) {
+ const s = await sdk();
+ const ident = await deriveIdentity(identityRef, baseUrl);
+ const client = await readClient(cluster);
+ const pda = s.deriveAgenCAgentPda(client, ident.agentIdHex);
+ const existing = await s.getAgenCAgent(client, pda);
+ return {
+ agentIdHex: ident.agentIdHex,
+ agentPda: pda.toBase58(),
+ existed: Boolean(existing),
+ metadataUri: ident.metadataUri,
+ source: ident.source,
+ };
+}
diff --git a/packages/agora-mcp/src/tools/post-task.js b/packages/agora-mcp/src/tools/post-task.js
index 0e9e5062b..b1261d1db 100644
--- a/packages/agora-mcp/src/tools/post-task.js
+++ b/packages/agora-mcp/src/tools/post-task.js
@@ -10,6 +10,7 @@ import { z } from 'zod';
import {
postTask,
+ signerBalances,
resolveSigner,
pickCluster,
deriveIdentity,
@@ -126,7 +127,34 @@ export const def = {
.optional()
.describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),
},
- async handler(args) {
+ handler: (args) => runPost(args, { preview: false }),
+};
+
+const { secret: _secretDesc, ...quoteShapeBase } = def.inputSchema;
+
+/**
+ * `agora_quote_task`: the preview that must run before agora_post_task. It
+ * resolves every input the post would use (reward, mint, deadline, required
+ * capabilities, creator id) and reads the signer's live balance, without
+ * signing or escrowing anything.
+ */
+export const quoteDef = {
+ name: 'agora_quote_task',
+ title: 'Quote an Agora bounty (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Quote agora_post_task before it runs: the exact reward that would be locked in escrow and its asset, the ' +
+ 'deadline, required capabilities, task type, the creator agent id, the signing wallet and its live balance, ' +
+ 'and whether that balance covers the escrow. Signs nothing and escrows nothing. Show it to the user, get a ' +
+ 'clear yes, then call agora_post_task with the same arguments, the returned quote_id and confirm_spend: true.',
+ inputSchema: {
+ ...quoteShapeBase,
+ secret: z.string().optional().describe('Base58 secret of the signing wallet. Only its public key is read. Falls back to AGORA_SECRET_KEY.'),
+ },
+ handler: (args) => runPost(args, { preview: true }),
+};
+
+async function runPost(args, { preview }) {
const description = String(args?.description ?? '').trim();
if (!description) throw Object.assign(new Error('description is required'), { code: 'validation_error' });
@@ -170,6 +198,28 @@ export const def = {
// Derive the creator id last (this loads the write SDK).
const creatorAgentId = await resolveCreatorAgentId(args);
+ if (preview) {
+ const balances = await signerBalances({ cluster, pubkey, mint: rewardMint });
+ const held = rewardMint ? BigInt(balances.token?.amountAtomic ?? '0') : BigInt(balances.lamports);
+ return {
+ ok: true,
+ cluster,
+ wallet: pubkey,
+ creatorAgentId,
+ escrow: {
+ amountAtomic: String(rewardAmount),
+ mint: rewardMint,
+ symbol: cluster === 'mainnet' ? (rewardMint === THREE_MINT ? '$THREE' : null) : 'SOL',
+ },
+ requiredCapabilities: String(requiredCapabilities),
+ maxWorkers: args?.maxWorkers != null ? Number(args.maxWorkers) : 1,
+ taskType: args?.taskType || 'Exclusive',
+ deadline,
+ balance: { sol: balances.sol, token: balances.token },
+ balanceCoversEscrow: held >= rewardAmount,
+ };
+ }
+
const result = await postTask({
cluster,
secretKey,
@@ -204,8 +254,7 @@ export const def = {
explorerUrl: explorerTx(result.txSignature, cluster),
task: result.task,
};
- },
-};
+}
/** Resolve the creator's 32-byte AgenC agent id from an explicit id or an identity. */
async function resolveCreatorAgentId(args) {
diff --git a/packages/agora-mcp/src/tools/register.js b/packages/agora-mcp/src/tools/register.js
index 0054d4861..6d93ff71a 100644
--- a/packages/agora-mcp/src/tools/register.js
+++ b/packages/agora-mcp/src/tools/register.js
@@ -9,7 +9,7 @@
import { z } from 'zod';
-import { registerCitizen, resolveSigner, pickCluster, explorerTx } from '../lib/agenc.js';
+import { registerCitizen, previewRegistration, signerBalances, resolveSigner, pickCluster, explorerTx } from '../lib/agenc.js';
import { THREE_WS_BASE } from '../config.js';
import { apiRequest } from '../lib/api.js';
@@ -76,7 +76,29 @@ export const def = {
.optional()
.describe('Base58 64-byte secret key of the signing wallet. Falls back to AGORA_SECRET_KEY. Never logged or transmitted.'),
},
- async handler(args) {
+ handler: (args) => runRegister(args, { preview: false }),
+};
+
+/**
+ * `agora_quote_register`: the preview that must run before agora_register.
+ * Derives the agent id and PDA the registration would create, reports an
+ * identity that is already registered (which stakes nothing), and checks the
+ * stake against the signer's live SOL balance, without signing.
+ */
+export const quoteDef = {
+ name: 'agora_quote_register',
+ title: 'Quote an Agora registration (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Quote agora_register before it runs: the derived AgenC agent id and PDA, whether that identity is already ' +
+ 'registered (then nothing is staked), the stake in lamports the protocol would hold, the signing wallet and ' +
+ 'its live SOL balance. Signs nothing. Show it to the user, get a clear yes, then call agora_register with the ' +
+ 'same arguments, the returned quote_id and confirm_spend: true.',
+ inputSchema: def.inputSchema,
+ handler: (args) => runRegister(args, { preview: true }),
+};
+
+async function runRegister(args, { preview }) {
const handle = args?.handle ? String(args.handle).trim() : undefined;
const erc8004AgentId = args?.erc8004AgentId ?? undefined;
const mplCoreAsset = args?.mplCoreAsset ? String(args.mplCoreAsset).trim() : undefined;
@@ -107,6 +129,29 @@ export const def = {
? String(args.endpoint).trim()
: `${THREE_WS_BASE}/agents/${defaultAgentLabel(identityRef)}`;
+ if (preview) {
+ const [plan, balances] = await Promise.all([
+ previewRegistration({ cluster, identityRef, baseUrl: THREE_WS_BASE }),
+ signerBalances({ cluster, pubkey }),
+ ]);
+ const staked = plan.existed ? 0 : stakeLamports;
+ return {
+ ok: true,
+ cluster,
+ wallet: pubkey,
+ professions: keys,
+ capabilityBits: String(capabilities),
+ endpoint,
+ agentId: plan.agentIdHex,
+ agentPda: plan.agentPda,
+ alreadyRegistered: plan.existed,
+ stakeLamports: staked,
+ stakeSol: staked / 1e9,
+ balanceSol: balances.sol,
+ balanceCoversStake: balances.lamports >= staked,
+ };
+ }
+
const result = await registerCitizen({
cluster,
secretKey,
@@ -144,8 +189,7 @@ export const def = {
onchain: result.agent,
citizen,
};
- },
-};
+}
// Stable label for the default endpoint when no handle was given (mpl/erc id).
function defaultAgentLabel(ref) {
diff --git a/packages/avatar-agent-mcp/src/index.js b/packages/avatar-agent-mcp/src/index.js
index 553ef8fb5..9cb366185 100755
--- a/packages/avatar-agent-mcp/src/index.js
+++ b/packages/avatar-agent-mcp/src/index.js
@@ -33,10 +33,14 @@ import { def as speak } from './tools/speak.js';
import { def as walletCreate } from './tools/wallet-create.js';
import { def as walletBalance } from './tools/wallet-balance.js';
import { def as walletSend } from './tools/wallet-send.js';
+import { def as walletSendPreview } from './tools/wallet-send-preview.js';
import { def as pumpSnapshot } from './tools/pump-snapshot.js';
import { def as pumpBuy } from './tools/pump-buy.js';
+import { def as pumpBuyQuote } from './tools/pump-buy-quote.js';
import { def as pumpLaunch } from './tools/pump-launch.js';
+import { def as pumpLaunchPreview } from './tools/pump-launch-preview.js';
import { def as pumpCollect } from './tools/pump-collect.js';
+import { def as pumpCollectPreview } from './tools/pump-collect-preview.js';
import { def as ensSnsResolve } from './tools/ens-sns-resolve.js';
// Single source of truth for the advertised server identity — package.json.
@@ -62,11 +66,15 @@ export const TOOLS = [
// Wallet
walletCreate,
walletBalance,
+ walletSendPreview,
walletSend,
// pump.fun
pumpSnapshot,
+ pumpBuyQuote,
pumpBuy,
+ pumpLaunchPreview,
pumpLaunch,
+ pumpCollectPreview,
pumpCollect,
// Identity
ensSnsResolve,
@@ -96,10 +104,11 @@ export function buildServer() {
'Avatar flow: list_avatars → list_animations → spawn_avatar (preset "default"/"cz" or any GLB) → dress_avatar → ' +
'render_avatar (pose + camera orbit + ARKit-52 expression → real PNG) → speak. generate_avatar text/image-to-3D ' +
'via Replicate. wallet_create (optional vanity grinder) gives the avatar a Solana wallet; wallet_balance, ' +
- 'wallet_send for SOL ops. ' +
- 'pump.fun: pump_snapshot for live market data (target="three" for $three); pump_buy via Jupiter, optional Jito ' +
- 'bundle; pump_launch is an atomic Jito-bundled launch with separate funder + creator; pump_collect_fees drains ' +
- 'pump.fun creator-fee vaults atomically. ens_sns_resolve for .eth / .sol names.',
+ 'wallet_send_preview then wallet_send for SOL ops. ' +
+ 'pump.fun: pump_snapshot for live market data (target="three" for $three); pump_buy_quote then pump_buy via Jupiter, optional Jito ' +
+ 'bundle; pump_launch_preview then pump_launch is an atomic Jito-bundled launch with separate funder + creator; ' +
+ 'pump_collect_preview then pump_collect_fees drains pump.fun creator-fee vaults atomically. ' +
+ 'Every value-moving tool is off until enabled (THREE_WS_TOOLS) and needs its preview id plus its confirm flag. ens_sns_resolve for .eth / .sol names.',
},
);
diff --git a/packages/avatar-agent-mcp/src/lib/jupiter-buy.js b/packages/avatar-agent-mcp/src/lib/jupiter-buy.js
index dfd224668..02f2cd024 100644
--- a/packages/avatar-agent-mcp/src/lib/jupiter-buy.js
+++ b/packages/avatar-agent-mcp/src/lib/jupiter-buy.js
@@ -35,7 +35,7 @@ function settleStatus(wait) {
const SOL_MINT = 'So11111111111111111111111111111111111111112';
-async function fetchJupiterQuote({ inputMint = SOL_MINT, outputMint, amount, slippageBps = 500 }) {
+export async function fetchJupiterQuote({ inputMint = SOL_MINT, outputMint, amount, slippageBps = 500 }) {
const url = `https://lite-api.jup.ag/swap/v1/quote?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=${slippageBps}`;
const r = await fetch(url);
if (!r.ok) {
diff --git a/packages/avatar-agent-mcp/src/lib/previews.js b/packages/avatar-agent-mcp/src/lib/previews.js
new file mode 100644
index 000000000..ccac33e6d
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/lib/previews.js
@@ -0,0 +1,224 @@
+// Spend-nothing previews for the four value-moving tools.
+//
+// Each preview reads the same live state the executing tool will read (the
+// signer's balance, a Jupiter quote, the creator-fee vault) and runs the same
+// policy checks (spend cap, recipient allowlist, tip clamp), but never builds a
+// signed transaction. What it returns is exactly what a person needs to approve
+// the real call: who pays, who receives, how much, and whether it would be
+// refused. A refusal is reported in `blockers`, never thrown, so the preview can
+// always be shown.
+
+import { PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
+
+import { getConnection, isValidPubkey, keypairFromSecret, loadSigner } from './solana.js';
+import { fetchJupiterQuote } from './jupiter-buy.js';
+import {
+ MAX_SOL_PER_TX,
+ RECIPIENT_ALLOWLIST,
+ RENT_EXEMPT_LAMPORTS,
+ clampJitoTipSol,
+ clampPriorityMicroLamports,
+ enforceMinBuffer,
+} from './spend-policy.js';
+
+// Base fee per signature plus the compute-unit price the tools pay. The unit
+// limits match what each signing lib sets on its transactions.
+const BASE_FEE_LAMPORTS = 5000;
+// Headroom the launch and collect libs require the funder to hold on top of
+// the tip, for the fees of their bundle transactions.
+const BUNDLE_FEE_HEADROOM_SOL = 0.002;
+
+const toSol = (lamports) => Number(lamports) / LAMPORTS_PER_SOL;
+
+function priorityFeeLamports(microLamports, units) {
+ return Math.ceil((clampPriorityMicroLamports(microLamports) * units) / 1_000_000);
+}
+
+function capBlocker(sol, label) {
+ return Number(sol) > MAX_SOL_PER_TX
+ ? { code: 'over_spend_cap', message: `${label}: ${sol} SOL exceeds the per-tx cap of ${MAX_SOL_PER_TX} SOL.` }
+ : null;
+}
+
+function allowlistBlocker(pubkey, label) {
+ if (!RECIPIENT_ALLOWLIST || RECIPIENT_ALLOWLIST.has(String(pubkey))) return null;
+ return { code: 'recipient_not_allowed', message: `${label} ${pubkey} is not in RECIPIENT_ALLOWLIST.` };
+}
+
+async function balanceLamports(pubkey) {
+ return getConnection().getBalance(new PublicKey(pubkey), 'confirmed');
+}
+
+/** Resolve a signer's public key without keeping the keypair around. */
+function signerAddress(secret, fallbackToEnv) {
+ const kp = fallbackToEnv ? loadSigner(secret) : keypairFromSecret(secret);
+ return kp.publicKey.toBase58();
+}
+
+/** wallet_send: sender, recipient, amount, fee, and the balance left after. */
+export async function previewWalletSend({ secret, to, sol, priorityMicroLamports = 100000 }) {
+ const blockers = [];
+ if (!isValidPubkey(to)) blockers.push({ code: 'invalid_destination', message: `Not a valid Solana pubkey: ${to}` });
+ const amount = Number(sol);
+ if (!(amount > 0)) blockers.push({ code: 'invalid_amount', message: 'sol must be greater than zero.' });
+ const cap = capBlocker(amount, 'wallet_send');
+ if (cap) blockers.push(cap);
+ const allow = isValidPubkey(to) ? allowlistBlocker(to, 'wallet_send destination') : null;
+ if (allow) blockers.push(allow);
+
+ const from = signerAddress(secret, true);
+ const lamports = Math.floor(amount * LAMPORTS_PER_SOL);
+ const fee = BASE_FEE_LAMPORTS + priorityFeeLamports(priorityMicroLamports, 1000);
+ const balance = await balanceLamports(from);
+ if (balance < lamports + fee) {
+ blockers.push({
+ code: 'insufficient_funds',
+ message: `Sender holds ${toSol(balance)} SOL; this send needs ${toSol(lamports + fee)} SOL including fees.`,
+ });
+ }
+ return {
+ action: 'wallet_send',
+ chain: 'solana-mainnet',
+ token: 'SOL',
+ from,
+ to,
+ amount_sol: amount,
+ network_fee_sol: toSol(fee),
+ sender_balance_sol: toSol(balance),
+ sender_balance_after_sol: toSol(balance - lamports - fee),
+ spend_cap_sol: MAX_SOL_PER_TX,
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+}
+
+/** pump_buy: a live Jupiter quote for the exact SOL amount and slippage. */
+export async function quotePumpBuy({ target, buySol, buyerSecret, slippageBps = 500, jitoBundle = false, jitoTipSol = 0.005, priorityMicroLamports = 2_000_000 }) {
+ const blockers = [];
+ const cap = capBlocker(buySol, 'pump_buy');
+ if (cap) blockers.push(cap);
+ const buyer = signerAddress(buyerSecret, false);
+ const lamports = Math.floor(Number(buySol) * LAMPORTS_PER_SOL);
+ const quote = await fetchJupiterQuote({ outputMint: target, amount: lamports, slippageBps });
+ const tip = jitoBundle ? clampJitoTipSol(jitoTipSol) : 0;
+ const balance = await balanceLamports(buyer);
+ const fee = BASE_FEE_LAMPORTS + priorityFeeLamports(priorityMicroLamports, 200_000);
+ if (!jitoBundle && balance < lamports + fee) {
+ blockers.push({
+ code: 'insufficient_funds',
+ message: `Buyer holds ${toSol(balance)} SOL; this buy needs ${toSol(lamports + fee)} SOL including fees.`,
+ });
+ }
+ return {
+ action: 'pump_buy',
+ chain: 'solana-mainnet',
+ venue: 'jupiter',
+ buyer,
+ target,
+ spend_sol: Number(buySol),
+ expected_out_atomics: quote.outAmount,
+ min_out_atomics: quote.otherAmountThreshold,
+ slippage_bps: Number(quote.slippageBps ?? slippageBps),
+ price_impact_pct: Number(quote.priceImpactPct ?? 0) * 100,
+ route: Array.isArray(quote.routePlan) ? quote.routePlan.map((r) => r.swapInfo?.label).filter(Boolean) : [],
+ jito_tip_sol: tip,
+ estimated_network_fee_sol: toSol(fee),
+ buyer_balance_sol: toSol(balance),
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+}
+
+/** pump_launch: every SOL line the funder pays, checked against its balance. */
+export async function previewPumpLaunch({ name, symbol, funderSecret, creatorSecret, rentSol = 0.035, devBuySol = 0, jitoTipSol = 0.005 }) {
+ const blockers = [];
+ if (!name) blockers.push({ code: 'invalid_input', message: 'name is required.' });
+ if (!symbol) blockers.push({ code: 'invalid_input', message: 'symbol is required.' });
+ const devBuy = Number(devBuySol) > 0 ? Number(devBuySol) : 0;
+ const tip = clampJitoTipSol(jitoTipSol);
+ const outlay = Number(rentSol) + devBuy + tip;
+ for (const b of [
+ capBlocker(rentSol, 'pump_launch creator rent'),
+ devBuy ? capBlocker(devBuy, 'pump_launch dev buy') : null,
+ capBlocker(outlay, 'pump_launch funder total outlay'),
+ ]) {
+ if (b) blockers.push(b);
+ }
+ const funder = signerAddress(funderSecret, false);
+ const creator = signerAddress(creatorSecret, false);
+ const balance = await balanceLamports(funder);
+ const needed = (Number(rentSol) + devBuy + tip + BUNDLE_FEE_HEADROOM_SOL) * LAMPORTS_PER_SOL;
+ if (balance < needed) {
+ blockers.push({
+ code: 'insufficient_funds',
+ message: `Funder needs at least ${toSol(needed)} SOL; holds ${toSol(balance)} SOL.`,
+ });
+ }
+ return {
+ action: 'pump_launch',
+ chain: 'solana-mainnet',
+ venue: 'pump.fun',
+ name,
+ symbol,
+ funder,
+ creator,
+ creator_rent_sol: Number(rentSol),
+ dev_buy_sol: devBuy,
+ jito_tip_sol: tip,
+ fee_headroom_sol: BUNDLE_FEE_HEADROOM_SOL,
+ funder_total_outlay_sol: outlay + BUNDLE_FEE_HEADROOM_SOL,
+ funder_balance_sol: toSol(balance),
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+}
+
+/** pump_collect_fees: the vault balance and exactly what lands at the destination. */
+export async function previewPumpCollect({ funderSecret, creatorSecret, destination, jitoTipSol = 0.005, bufferLamports = RENT_EXEMPT_LAMPORTS, minVaultSol = 0.001 }) {
+ const blockers = [];
+ if (!isValidPubkey(destination)) {
+ blockers.push({ code: 'invalid_destination', message: `Not a valid Solana pubkey: ${destination}` });
+ } else {
+ const allow = allowlistBlocker(destination, 'pump_collect_fees destination');
+ if (allow) blockers.push(allow);
+ }
+ const funder = signerAddress(funderSecret, false);
+ const creatorKp = keypairFromSecret(creatorSecret);
+ const creator = creatorKp.publicKey.toBase58();
+ const tip = clampJitoTipSol(jitoTipSol);
+ const buffer = enforceMinBuffer(bufferLamports);
+
+ const pumpSdkPkg = await import('@nirholas/pump-sdk');
+ const OnlinePumpSdk = pumpSdkPkg.OnlinePumpSdk || pumpSdkPkg.default?.OnlinePumpSdk;
+ if (!OnlinePumpSdk) throw Object.assign(new Error('@nirholas/pump-sdk: OnlinePumpSdk export missing'), { code: 'sdk_missing' });
+ const conn = getConnection();
+ const vaultLamports = Number(await new OnlinePumpSdk(conn).getCreatorVaultBalance(creatorKp.publicKey));
+ const [creatorBal, funderBal] = await Promise.all([balanceLamports(creator), balanceLamports(funder)]);
+ const drain = creatorBal + vaultLamports - buffer;
+
+ if (vaultLamports < Math.floor(Number(minVaultSol) * LAMPORTS_PER_SOL)) {
+ blockers.push({ code: 'vault_too_small', message: `Vault holds ${toSol(vaultLamports)} SOL, under the ${minVaultSol} SOL minimum.` });
+ }
+ if (drain <= 0) blockers.push({ code: 'nothing_to_drain', message: 'Nothing would be left to move after the rent buffer.' });
+ if (drain > MAX_SOL_PER_TX * LAMPORTS_PER_SOL) {
+ blockers.push({ code: 'over_spend_cap', message: `The drain of ${toSol(drain)} SOL exceeds the per-tx cap of ${MAX_SOL_PER_TX} SOL.` });
+ }
+ if (funderBal < (tip + BUNDLE_FEE_HEADROOM_SOL) * LAMPORTS_PER_SOL) {
+ blockers.push({ code: 'insufficient_funds', message: `Funder needs ${tip + BUNDLE_FEE_HEADROOM_SOL} SOL for the tip and fees; holds ${toSol(funderBal)} SOL.` });
+ }
+ return {
+ action: 'pump_collect_fees',
+ chain: 'solana-mainnet',
+ venue: 'pump.fun',
+ creator,
+ funder,
+ destination,
+ vault_sol: toSol(vaultLamports),
+ creator_balance_sol: toSol(creatorBal),
+ rent_buffer_sol: toSol(buffer),
+ amount_to_destination_sol: toSol(Math.max(0, drain)),
+ jito_tip_sol: tip,
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+}
diff --git a/packages/avatar-agent-mcp/src/tools/pump-buy-quote.js b/packages/avatar-agent-mcp/src/tools/pump-buy-quote.js
new file mode 100644
index 000000000..61cafa001
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/tools/pump-buy-quote.js
@@ -0,0 +1,38 @@
+// `pump_buy_quote` — the live Jupiter quote that must run before pump_buy.
+// Same route, amount and slippage the buy will use; never signs.
+
+import { z } from 'zod';
+
+import { isValidPubkey } from '../lib/solana.js';
+import { quotePumpBuy } from '../lib/previews.js';
+import { THREE_MINT } from '../config.js';
+
+export const def = {
+ name: 'pump_buy_quote',
+ title: 'Quote a token buy via Jupiter (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Quote a pump_buy before it runs: the SOL spent, the expected and minimum tokens received, price impact, route, fees, and any rule that would refuse it. Uses the live Jupiter quote for the exact amount and slippage. Signs nothing. Show it to the user, get a clear yes, then call pump_buy with the returned quote_id and the same arguments.',
+ inputSchema: {
+ target: z.string().describe('Target mint (base58) or "three" to use the THREE_MINT env.'),
+ buySol: z.number().positive().describe('Amount of SOL to spend.'),
+ buyerSecret: z.string().describe('Base58 secret of the buyer wallet (only its public key is read).'),
+ slippageBps: z.number().int().min(1).max(10_000).optional().describe('Slippage in basis points (default 500 = 5%).'),
+ jitoBundle: z.boolean().optional().describe('Quote the bundled mode (adds the Jito tip). Default false.'),
+ jitoTipSol: z.number().min(0).optional().describe('Jito tip in SOL (default 0.005). Only used when jitoBundle=true.'),
+ priorityMicroLamports: z.number().int().min(0).max(20_000_000).optional().describe('Compute-unit price (default 2_000_000).'),
+ },
+ async handler(args) {
+ let target = args.target;
+ if (target === 'three' || target === '$three') {
+ if (!THREE_MINT) return { ok: false, error: 'three_mint_not_configured' };
+ target = THREE_MINT;
+ }
+ if (!isValidPubkey(target)) return { ok: false, error: 'invalid_target' };
+ try {
+ return { ok: true, quote: await quotePumpBuy({ ...args, target }) };
+ } catch (err) {
+ return { ok: false, error: err.code || 'quote_failed', message: err.message };
+ }
+ },
+};
diff --git a/packages/avatar-agent-mcp/src/tools/pump-collect-preview.js b/packages/avatar-agent-mcp/src/tools/pump-collect-preview.js
new file mode 100644
index 000000000..3540b375a
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/tools/pump-collect-preview.js
@@ -0,0 +1,29 @@
+// `pump_collect_preview` — reads the creator-fee vault and shows exactly how
+// much SOL pump_collect_fees would move to the destination.
+
+import { z } from 'zod';
+
+import { previewPumpCollect } from '../lib/previews.js';
+
+export const def = {
+ name: 'pump_collect_preview',
+ title: 'Preview a creator-fee collection (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Preview pump_collect_fees before it runs: the live creator-fee vault balance, the creator balance, the rent buffer kept behind, the exact SOL that would reach the destination, the Jito tip, and any rule that would refuse it. Signs nothing. Show it to the user, get a clear yes, then call pump_collect_fees with the returned preview_id and the same arguments.',
+ inputSchema: {
+ funderSecret: z.string().describe('Base58 secret of the funder (only its public key and balance are read).'),
+ creatorSecret: z.string().describe('Base58 secret of the coin creator (only its public key is read).'),
+ destination: z.string().min(32).max(64).describe('Where the collected SOL would go (base58).'),
+ jitoTipSol: z.number().min(0).optional().describe('Jito tip in SOL (default 0.005).'),
+ bufferLamports: z.number().int().min(0).optional().describe('Lamports left on the creator (floored at rent-exempt).'),
+ minVaultSol: z.number().min(0).optional().describe('Skip when the vault holds less than this (default 0.001).'),
+ },
+ async handler(args) {
+ try {
+ return { ok: true, preview: await previewPumpCollect(args) };
+ } catch (err) {
+ return { ok: false, error: err.code || 'preview_failed', message: err.message };
+ }
+ },
+};
diff --git a/packages/avatar-agent-mcp/src/tools/pump-launch-preview.js b/packages/avatar-agent-mcp/src/tools/pump-launch-preview.js
new file mode 100644
index 000000000..adce73059
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/tools/pump-launch-preview.js
@@ -0,0 +1,30 @@
+// `pump_launch_preview` — every SOL line a launch costs the funder, checked
+// against its live balance and the spend cap, before pump_launch runs.
+
+import { z } from 'zod';
+
+import { previewPumpLaunch } from '../lib/previews.js';
+
+export const def = {
+ name: 'pump_launch_preview',
+ title: 'Preview a coin launch (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Preview a pump_launch before it runs: the funder and creator addresses, the creator rent transfer, the dev buy, the Jito tip, the total the funder pays, its balance, and any rule that would refuse the launch. Signs nothing, uploads nothing, mints nothing. Show it to the user, get a clear yes, then call pump_launch with the returned preview_id and the same arguments.',
+ inputSchema: {
+ name: z.string().min(1).max(32).describe('Coin name.'),
+ symbol: z.string().min(1).max(10).describe('Coin symbol.'),
+ funderSecret: z.string().describe('Base58 secret of the funder (only its public key and balance are read).'),
+ creatorSecret: z.string().describe('Base58 secret of the creator (only its public key is read).'),
+ rentSol: z.number().min(0).optional().describe('SOL the funder sends the creator for rent (default 0.035).'),
+ devBuySol: z.number().min(0).optional().describe('SOL the creator spends on a dev buy (default 0).'),
+ jitoTipSol: z.number().min(0).optional().describe('Jito tip in SOL (default 0.005).'),
+ },
+ async handler(args) {
+ try {
+ return { ok: true, preview: await previewPumpLaunch(args) };
+ } catch (err) {
+ return { ok: false, error: err.code || 'preview_failed', message: err.message };
+ }
+ },
+};
diff --git a/packages/avatar-agent-mcp/src/tools/wallet-send-preview.js b/packages/avatar-agent-mcp/src/tools/wallet-send-preview.js
new file mode 100644
index 000000000..a967da963
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/tools/wallet-send-preview.js
@@ -0,0 +1,28 @@
+// `wallet_send_preview` — the spend-nothing preview that must run before
+// wallet_send. Reads the sender's live balance and applies the same cap and
+// allowlist checks the send applies, without signing anything.
+
+import { z } from 'zod';
+
+import { previewWalletSend } from '../lib/previews.js';
+
+export const def = {
+ name: 'wallet_send_preview',
+ title: 'Preview a SOL send (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Preview a wallet_send before it runs: the sender address, recipient, amount, network fee, the sender balance before and after, and any rule that would refuse it (spend cap, recipient allowlist, insufficient funds). Signs nothing and moves nothing. Show this to the user and get a clear yes before calling wallet_send with the returned preview_id.',
+ inputSchema: {
+ to: z.string().min(32).max(64).describe('Destination Solana pubkey (base58).'),
+ sol: z.number().positive().describe('Amount of SOL to send.'),
+ secret: z.string().optional().describe('Base58 secret of the sender. Falls back to SOLANA_SECRET_KEY env.'),
+ priorityMicroLamports: z.number().int().min(0).max(10_000_000).optional().describe('Compute-unit price (default 100000).'),
+ },
+ async handler(args) {
+ try {
+ return { ok: true, preview: await previewWalletSend(args) };
+ } catch (err) {
+ return { ok: false, error: err.code || 'preview_failed', message: err.message };
+ }
+ },
+};
diff --git a/packages/home-mcp/src/index.js b/packages/home-mcp/src/index.js
index e21fdfd07..0fe8bf779 100755
--- a/packages/home-mcp/src/index.js
+++ b/packages/home-mcp/src/index.js
@@ -38,12 +38,13 @@ import { def as listEntities } from './tools/list-entities.js';
import { def as listMacros } from './tools/list-macros.js';
import { def as callService } from './tools/call-service.js';
import { def as runMacro } from './tools/run-macro.js';
+import { def as previewMacro } from './tools/preview-macro.js';
import { closeHome, config } from './lib/home.js';
const require = createRequire(import.meta.url);
const { version: PKG_VERSION } = require('../package.json');
-export const TOOLS = [homeOverview, listEntities, listMacros, callService, runMacro];
+export const TOOLS = [homeOverview, listEntities, listMacros, callService, previewMacro, runMacro];
export const INSTRUCTIONS =
'three.ws Home MCP: safe control of a real Home Assistant house. Call home_overview first: it gives you ' +
diff --git a/packages/home-mcp/src/tools/preview-macro.js b/packages/home-mcp/src/tools/preview-macro.js
new file mode 100644
index 000000000..7c22daf4e
--- /dev/null
+++ b/packages/home-mcp/src/tools/preview-macro.js
@@ -0,0 +1,21 @@
+// `preview_macro`: resolve a phrase to the scene or script run_macro would fire,
+// without firing it. This is run_macro's own dry run exposed as a read-only
+// tool, so it stays callable while run_macro itself is off by default.
+
+import { z } from 'zod';
+
+import { def as runMacro } from './run-macro.js';
+
+export const def = {
+ name: 'preview_macro',
+ title: 'Preview which scene a phrase would run (nothing runs)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Resolve a phrase like "good night" to the scene or script this house would run, with the match confidence ' +
+ 'and a reason, and run NOTHING. A phrase with no match returns match:null. Show the match to the person, get ' +
+ 'a clear yes, then call run_macro with the same phrase, the returned preview_id and confirm_run: true.',
+ inputSchema: {
+ phrase: z.string().min(1).describe('What the person said, e.g. "good night".'),
+ },
+ handler: (args = {}) => runMacro.handler({ phrase: args.phrase, dry_run: true }),
+};
diff --git a/packages/mcp-policy/src/enablement.js b/packages/mcp-policy/src/enablement.js
new file mode 100644
index 000000000..6c3cc03c3
--- /dev/null
+++ b/packages/mcp-policy/src/enablement.js
@@ -0,0 +1,177 @@
+// Which tools a session may see and call.
+//
+// Enablement is described by a SPEC: a comma- or space-separated list of
+// tokens applied left to right on top of a base. The same grammar is read from
+// the X-Three-Tools header, the `tools` query parameter, the THREE_WS_TOOLS env
+// var of a stdio server, and the saved settings (which are converted to it), so
+// one mental model covers every surface.
+//
+// default read + write tiers on, financial off (the implicit base)
+// all every tier on
+// none everything off
+// readonly only the read tier on
+// write turn the write tier on -write turn it off
+// financial turn the financial tier on -financial turn it off
+// trading turn the whole trading group on, every tier included
+// -chat turn the whole chat group off
+// swap_execute turn one tool on -forget turn one tool off
+//
+// Precedence between tokens is tool over group over tier: `-trading,swap_quote`
+// hides the trading group except swap_quote.
+
+import { GROUP_IDS, TIERS, DEFAULT_TIERS } from './groups.js';
+
+const GROUP_SET = new Set(GROUP_IDS);
+const TIER_SET = new Set(TIERS);
+const BASES = { default: DEFAULT_TIERS, all: TIERS, none: [], readonly: ['read'] };
+const TOOL_NAME = /^[A-Za-z][\w.-]{0,79}$/;
+
+/**
+ * Parse a spec into ordered tokens. Unknown words that look like tool names are
+ * kept as tool tokens; anything else is reported so a typo is visible.
+ * @param {string|string[]|null|undefined} spec
+ * @returns {{ tokens: {kind:'base'|'tier'|'group'|'tool', id:string, on:boolean}[], invalid: string[] }}
+ */
+export function parseSpec(spec) {
+ const raw = Array.isArray(spec) ? spec.join(',') : String(spec ?? '');
+ const tokens = [];
+ const invalid = [];
+ for (const word of raw.split(/[\s,]+/).map((w) => w.trim()).filter(Boolean)) {
+ const on = !word.startsWith('-');
+ const id = word.replace(/^[+-]/, '');
+ const lower = id.toLowerCase();
+ if (on && Object.hasOwn(BASES, lower)) tokens.push({ kind: 'base', id: lower, on: true });
+ else if (TIER_SET.has(lower)) tokens.push({ kind: 'tier', id: lower, on });
+ else if (GROUP_SET.has(lower)) tokens.push({ kind: 'group', id: lower, on });
+ else if (TOOL_NAME.test(id)) tokens.push({ kind: 'tool', id, on });
+ else invalid.push(word);
+ }
+ return { tokens, invalid };
+}
+
+/**
+ * Fold tokens into an enablement. `source` records where it came from so an
+ * error can tell the user which setting to change.
+ * @param {{kind:string,id:string,on:boolean}[]} tokens
+ * @param {string} source
+ */
+export function enablementFromTokens(tokens, source) {
+ const tiers = new Set(DEFAULT_TIERS);
+ const groupsOn = new Set();
+ const groupsOff = new Set();
+ const toolsOn = new Set();
+ const toolsOff = new Set();
+ for (const t of tokens) {
+ if (t.kind === 'base') {
+ tiers.clear();
+ for (const tier of BASES[t.id]) tiers.add(tier);
+ groupsOn.clear();
+ groupsOff.clear();
+ toolsOn.clear();
+ toolsOff.clear();
+ } else if (t.kind === 'tier') {
+ if (t.on) tiers.add(t.id);
+ else tiers.delete(t.id);
+ } else if (t.kind === 'group') {
+ (t.on ? groupsOn : groupsOff).add(t.id);
+ (t.on ? groupsOff : groupsOn).delete(t.id);
+ } else {
+ (t.on ? toolsOn : toolsOff).add(t.id);
+ (t.on ? toolsOff : toolsOn).delete(t.id);
+ }
+ }
+ return { source, allowList: null, tiers, groupsOn, groupsOff, toolsOn, toolsOff };
+}
+
+/** The platform default: read and write on, financial off. */
+export function defaultEnablement() {
+ return enablementFromTokens([], 'default');
+}
+
+/** A client-supplied exact allow list: only these tool names exist for the session. */
+export function allowListEnablement(names, source = 'client') {
+ const list = new Set(
+ (Array.isArray(names) ? names : String(names ?? '').split(/[\s,]+/))
+ .map((n) => String(n).trim())
+ .filter(Boolean),
+ );
+ return { ...defaultEnablement(), source, allowList: list };
+}
+
+/**
+ * Convert saved settings ({ groups: {id: bool}, tools: {name: bool} }) to
+ * tokens. Unknown group ids are dropped rather than trusted.
+ * @param {{groups?: Record<string, boolean>, tools?: Record<string, boolean>}|null|undefined} settings
+ */
+export function settingsToTokens(settings) {
+ if (!settings || typeof settings !== 'object') return [];
+ const tokens = [];
+ for (const [id, on] of Object.entries(settings.groups || {})) {
+ if (GROUP_SET.has(id) && typeof on === 'boolean') tokens.push({ kind: 'group', id, on });
+ }
+ for (const [id, on] of Object.entries(settings.tools || {})) {
+ if (TOOL_NAME.test(id) && typeof on === 'boolean') tokens.push({ kind: 'tool', id, on });
+ }
+ return tokens;
+}
+
+/**
+ * Resolve the enablement for one session. The first source present wins, in
+ * this order: the client's own allowed-tools list, the spec the client sent
+ * (header, then query), the per-key setting, the account setting, the default.
+ * Per-key settings are layered over the account setting, so a key only needs
+ * to record where it differs.
+ *
+ * @param {{
+ * allowedTools?: string|string[]|null,
+ * headerSpec?: string|null,
+ * querySpec?: string|null,
+ * keySettings?: object|null,
+ * accountSettings?: object|null,
+ * }} input
+ */
+export function resolveEnablement({ allowedTools, headerSpec, querySpec, keySettings, accountSettings } = {}) {
+ if (allowedTools != null && String(allowedTools).trim() !== '') return allowListEnablement(allowedTools);
+ if (headerSpec != null && String(headerSpec).trim() !== '') {
+ return enablementFromTokens(parseSpec(headerSpec).tokens, 'header');
+ }
+ if (querySpec != null && String(querySpec).trim() !== '') {
+ return enablementFromTokens(parseSpec(querySpec).tokens, 'query');
+ }
+ const account = settingsToTokens(accountSettings);
+ const key = settingsToTokens(keySettings);
+ if (key.length) return enablementFromTokens([...account, ...key], 'key');
+ if (account.length) return enablementFromTokens(account, 'account');
+ return defaultEnablement();
+}
+
+/**
+ * Is this tool on for the session? A tool with no policy entry is treated as
+ * financial with no group: hidden unless named explicitly, so a tool nobody
+ * classified can never slip into a default session.
+ * @param {string} name
+ * @param {{group:string,tier:string}|null} entry
+ * @param {ReturnType<typeof defaultEnablement>} en
+ */
+export function isToolEnabled(name, entry, en) {
+ if (en.allowList) return en.allowList.has(name);
+ if (en.toolsOff.has(name)) return false;
+ if (en.toolsOn.has(name)) return true;
+ if (!entry) return false;
+ if (en.groupsOff.has(entry.group)) return false;
+ if (en.groupsOn.has(entry.group)) return true;
+ return en.tiers.has(entry.tier);
+}
+
+/** A compact, serializable description of an enablement (for logs and the settings API). */
+export function describeEnablement(en) {
+ return {
+ source: en.source,
+ allow_list: en.allowList ? [...en.allowList] : null,
+ tiers: [...en.tiers],
+ groups_on: [...en.groupsOn],
+ groups_off: [...en.groupsOff],
+ tools_on: [...en.toolsOn],
+ tools_off: [...en.toolsOff],
+ };
+}
diff --git a/packages/mcp-policy/src/groups.js b/packages/mcp-policy/src/groups.js
new file mode 100644
index 000000000..407cc82c9
--- /dev/null
+++ b/packages/mcp-policy/src/groups.js
@@ -0,0 +1,75 @@
+// The vocabulary every three.ws MCP tool is classified under.
+//
+// A tool belongs to exactly one GROUP (what it is about) and one TIER (what it
+// can do to the caller). Groups are what a user toggles; tiers decide what is
+// on before the user has toggled anything.
+
+/** How long a preview or quote stays usable by the financial tool that needs it. */
+export const PREVIEW_TTL_MS = 10 * 60 * 1000;
+
+/**
+ * Tiers, in increasing order of consequence.
+ * read changes nothing. On by default.
+ * write changes account state, but a follow-up call can undo it. On by default.
+ * financial moves funds or cannot be undone. Off until the user opts in, and
+ * every call needs a named confirm flag plus a fresh preview.
+ */
+export const TIERS = Object.freeze(['read', 'write', 'financial']);
+
+/** Tiers a fresh key sees with no settings at all. */
+export const DEFAULT_TIERS = Object.freeze(['read', 'write']);
+
+/**
+ * The confirm flags a financial tool may require. Each names the kind of
+ * consequence, so a model reading `confirm_transfer: true` in its own call knows
+ * what it is attesting to. `confirm_run` covers the tools that act on the
+ * physical world or execute arbitrary code, which move no money but cannot be
+ * taken back.
+ */
+export const CONFIRM_FLAGS = Object.freeze([
+ 'confirm_swap',
+ 'confirm_transfer',
+ 'confirm_launch',
+ 'confirm_spend',
+ 'confirm_payment',
+ 'confirm_deposit',
+ 'confirm_withdraw',
+ 'confirm_delete',
+ 'confirm_bid',
+ 'confirm_send',
+ 'confirm_run',
+]);
+
+/** The argument a financial tool takes to prove its preview ran. */
+export const PREVIEW_ARGS = Object.freeze(['quote_id', 'preview_id']);
+
+/**
+ * Every group, in the order the settings page and the skill document list them.
+ * `summary` is written for the person deciding whether to turn the group on.
+ */
+export const GROUPS = Object.freeze([
+ { id: 'agents', label: 'Agents', summary: 'Create, inspect, and remember things for your agents: identities, memory, provenance, on-chain registration.' },
+ { id: 'chat', label: 'Chat', summary: 'Run a model: chat completions, embeddings, tutoring sessions, and the model catalog.' },
+ { id: 'runs', label: 'Runs', summary: 'Autonomous work: autopilot proposals, their dry runs, and the log of what an agent did on its own.' },
+ { id: 'skills', label: 'Skills', summary: 'Author, list, and install the skills an agent can use.' },
+ { id: 'trading', label: 'Trading', summary: 'Quote and execute swaps from an agent wallet, copy trading, and signal subscriptions.' },
+ { id: 'orders', label: 'Orders', summary: 'Open orders, DCA strategies, and wallet intents that execute later.' },
+ { id: 'perps', label: 'Perps', summary: 'Perpetual futures positions.' },
+ { id: 'lending', label: 'Lending', summary: 'Supply, borrow, and repay on lending markets.' },
+ { id: 'predictions', label: 'Predictions', summary: 'Prediction market positions.' },
+ { id: 'launch', label: 'Launch', summary: 'Launch a coin: metadata upload, vanity mints, launch, and creator-fee collection.' },
+ { id: 'marketplace', label: 'Marketplace', summary: 'Browse and hire agents and skills, the job board, and bounty markets.' },
+ { id: 'cards', label: 'Cards', summary: 'Agent payment cards.' },
+ { id: 'mail', label: 'Mail', summary: 'Outward messages: paid knocks, announcements to a person, and agent mail.' },
+ { id: 'x402', label: 'x402', summary: 'Discover, price, and pay x402 services; payment sessions; publish your own paid endpoint.' },
+ { id: 'wallet', label: 'Wallet', summary: 'Agent wallets: balances, portfolio, provisioning, and transfers out.' },
+ { id: 'billing', label: 'Billing', summary: 'Plan, usage, receipts, and platform fees.' },
+ { id: 'intelligence', label: 'Intelligence', summary: 'Market data and research: token intel, holders, trades, smart money, KOLs, Oracle conviction, alerts.' },
+ { id: 'integrations', label: 'Integrations', summary: 'Embeds, widgets, and connected systems such as a Home Assistant house.' },
+ { id: 'account', label: 'Account', summary: 'Notifications, delivery preferences, and push devices.' },
+ { id: 'allowlist', label: 'Allowlist', summary: 'The destinations an agent wallet may send funds to.' },
+ { id: 'assets', label: 'Assets', summary: '3D generation, avatars, animation, rigging, rendering, and the asset catalog.' },
+ { id: 'utility', label: 'Utility', summary: 'Getting-started guides, name resolution, vision, speech, and other stateless helpers.' },
+]);
+
+export const GROUP_IDS = Object.freeze(GROUPS.map((g) => g.id));
diff --git a/packages/mcp-policy/src/runtime.js b/packages/mcp-policy/src/runtime.js
new file mode 100644
index 000000000..de2d3a795
--- /dev/null
+++ b/packages/mcp-policy/src/runtime.js
@@ -0,0 +1,308 @@
+// The policy runtime every three.ws MCP server runs its tools through.
+//
+// listTools hides tools the session has not enabled and teaches the model
+// the rules on the financial ones (extra arguments, a description
+// suffix, and a `_meta` block naming group, tier, confirm flag and
+// preview tool).
+// beforeCall refuses a disabled tool with instructions to enable it, and a
+// financial tool without its confirm flag or without a fresh
+// preview id bound to the same arguments.
+// afterCall stamps a preview id onto a preview tool's result, and burns the
+// preview id once the financial call it authorized has succeeded.
+//
+// Refusals are MCP tool results with isError, not JSON-RPC errors, because a
+// model reads a tool result and acts on it; most clients show a protocol error
+// only to the person.
+
+import { randomBytes } from 'node:crypto';
+
+import { PREVIEW_TTL_MS } from './groups.js';
+import { isToolEnabled } from './enablement.js';
+import { POLICY } from './table.js';
+
+export const SETTINGS_URL = 'https://three.ws/settings/mcp-tools';
+export const CLI_COMMAND = 'npx three-ws tools';
+
+// Preview arguments that must never be written to a preview store: signing
+// keys and bearer material stay in the call that needed them.
+const SECRET_ARG = /secret|password|private_?key|mnemonic|seed/i;
+
+/**
+ * Normalize one table entry. Table rows are terse; this is the shape every
+ * consumer reads.
+ * @param {string} name
+ * @param {object} row
+ */
+export function normalizeEntry(name, row) {
+ const entry = {
+ name,
+ group: row.group,
+ tier: row.tier || 'read',
+ confirmFlag: row.confirmFlag || null,
+ previewTool: row.previewTool || null,
+ previewArg: null,
+ bind: [],
+ };
+ if (entry.previewTool) {
+ entry.previewArg = /quote/.test(entry.previewTool) ? 'quote_id' : 'preview_id';
+ entry.bind = (row.bind || []).map((b) => {
+ const [from, to] = String(b).split('>');
+ return [from, to || from];
+ });
+ }
+ return entry;
+}
+
+/** A fresh, unguessable preview id. */
+function newPreviewId(arg) {
+ return `${arg === 'quote_id' ? 'q' : 'p'}_${randomBytes(18).toString('base64url')}`;
+}
+
+function textResult(text, structured) {
+ return { content: [{ type: 'text', text }], structuredContent: structured, isError: true };
+}
+
+function sameValue(a, b) {
+ if (a == null && b == null) return true;
+ if (typeof a === 'number' || typeof b === 'number') return Number(a) === Number(b);
+ if (typeof a === 'object' || typeof b === 'object') return JSON.stringify(a) === JSON.stringify(b);
+ return String(a).trim() === String(b).trim();
+}
+
+/** An in-process preview store: the right store for a stdio server, which is one process. */
+export function createMemoryPreviewStore() {
+ const map = new Map();
+ return {
+ async put(id, record, ttlMs) {
+ map.set(id, { record, expires: Date.now() + ttlMs });
+ },
+ async get(id) {
+ const hit = map.get(id);
+ if (!hit) return null;
+ if (hit.expires < Date.now()) {
+ map.delete(id);
+ return null;
+ }
+ return hit.record;
+ },
+ async del(id) {
+ map.delete(id);
+ },
+ };
+}
+
+/**
+ * Build the policy runtime for one server.
+ * @param {{
+ * serverId: string,
+ * table?: Record<string, Record<string, object>>,
+ * store?: ReturnType<typeof createMemoryPreviewStore>,
+ * settingsUrl?: string,
+ * now?: () => number,
+ * }} opts
+ */
+export function createPolicy({ serverId, table = POLICY, store = createMemoryPreviewStore(), settingsUrl = SETTINGS_URL, now = Date.now }) {
+ const rows = table[serverId];
+ if (!rows) throw new Error(`mcp-policy: no policy table for server "${serverId}"`);
+ const entries = new Map(Object.entries(rows).map(([name, row]) => [name, normalizeEntry(name, row)]));
+
+ // Reverse index: which financial tools each preview tool authorizes.
+ const authorizes = new Map();
+ for (const e of entries.values()) {
+ if (e.tier !== 'financial' || !e.previewTool) continue;
+ if (!authorizes.has(e.previewTool)) authorizes.set(e.previewTool, []);
+ authorizes.get(e.previewTool).push(e);
+ }
+
+ const entry = (name) => entries.get(name) || null;
+
+ /** A preview tool stays callable whenever a financial tool it unlocks is on. */
+ function enabled(name, en) {
+ if (isToolEnabled(name, entry(name), en)) return true;
+ return (authorizes.get(name) || []).some((f) => isToolEnabled(f.name, f, en));
+ }
+
+ function enableHint(e) {
+ const token = e ? e.group : null;
+ return {
+ cli: CLI_COMMAND,
+ settings: settingsUrl,
+ header: token ? `X-Three-Tools: ${token}` : null,
+ };
+ }
+
+ function disabledResult(name, en) {
+ const e = entry(name);
+ const where = e
+ ? `It is in the "${e.group}" group (${e.tier} tier)${e.tier === 'financial' ? ', which is off by default because it moves funds or cannot be undone' : ''}.`
+ : 'It has no policy classification, so it stays off until it is named explicitly.';
+ const how = e
+ ? `Turn the group on with \`${CLI_COMMAND}\`, on ${settingsUrl}, or by sending the header X-Three-Tools: ${e.group}.`
+ : `Name it in X-Three-Tools or on ${settingsUrl} to turn it on.`;
+ return textResult(`${name} is turned off for this connection. ${where} ${how}`, {
+ ok: false,
+ reason: 'tool_disabled',
+ tool: name,
+ group: e?.group ?? null,
+ tier: e?.tier ?? null,
+ enabled_by: en.source,
+ enable: enableHint(e),
+ });
+ }
+
+ /** The financial-rule sentence appended to a financial tool's description. */
+ function financialNote(e) {
+ return (
+ ` FINANCIAL: moves funds or cannot be undone. Call ${e.previewTool} first, show the user its result, ` +
+ `and call this tool only after the user clearly says yes, passing ${e.previewArg} from that result ` +
+ `(valid ${PREVIEW_TTL_MS / 60000} minutes) and ${e.confirmFlag}: true. Report the transaction signature it returns.`
+ );
+ }
+
+ function policyMeta(e) {
+ return e
+ ? { group: e.group, tier: e.tier, confirmFlag: e.confirmFlag, previewTool: e.previewTool, previewArg: e.previewArg }
+ : null;
+ }
+
+ /**
+ * Decorate a JSON-Schema tool list for tools/list: drop disabled tools, add
+ * the policy arguments and note to financial ones, and stamp `_meta`.
+ * @param {object[]} tools
+ * @param {object} en
+ */
+ function listTools(tools, en) {
+ const out = [];
+ for (const tool of tools) {
+ if (!enabled(tool.name, en)) continue;
+ const e = entry(tool.name);
+ const meta = { ...(tool._meta || {}), 'three.ws/policy': policyMeta(e) };
+ if (e?.tier !== 'financial' || !e.confirmFlag) {
+ out.push({ ...tool, _meta: meta });
+ continue;
+ }
+ const schema = tool.inputSchema && typeof tool.inputSchema === 'object' ? tool.inputSchema : { type: 'object' };
+ const properties = { ...(schema.properties || {}) };
+ properties[e.confirmFlag] ??= {
+ type: 'boolean',
+ description: `Must be true, and only after the user approved the ${e.previewTool} result.`,
+ };
+ if (e.previewArg) {
+ properties[e.previewArg] ??= {
+ type: 'string',
+ description: `The ${e.previewArg} returned by ${e.previewTool} within the last ${PREVIEW_TTL_MS / 60000} minutes.`,
+ };
+ }
+ out.push({
+ ...tool,
+ description: `${tool.description || ''}${financialNote(e)}`,
+ inputSchema: { ...schema, properties },
+ _meta: meta,
+ });
+ }
+ return out;
+ }
+
+ /**
+ * Gate one call. On success returns the arguments with the policy-only
+ * fields removed (unless the tool declares them itself), plus the preview
+ * record the call is spending, so afterCall can burn it.
+ *
+ * @param {{ name: string, args?: object, en: object, principal: string, ownArgs?: string[] }} call
+ * ownArgs: argument names the tool's own schema declares.
+ * @returns {Promise<{ ok: true, args: object, entry: object|null, preview: object|null }
+ * | { ok: false, result: object }>}
+ */
+ async function beforeCall({ name, args = {}, en, principal, ownArgs = [] }) {
+ if (!enabled(name, en)) return { ok: false, result: disabledResult(name, en) };
+ const e = entry(name);
+ if (!e || e.tier !== 'financial' || !e.confirmFlag) return { ok: true, args, entry: e, preview: null };
+
+ const own = new Set(ownArgs);
+ const strip = (a) => {
+ const copy = { ...a };
+ if (!own.has(e.confirmFlag)) delete copy[e.confirmFlag];
+ if (e.previewArg && !own.has(e.previewArg)) delete copy[e.previewArg];
+ // A tool with its own legacy confirm gate is satisfied by the policy flag.
+ if (own.has('confirm') && e.confirmFlag !== 'confirm') copy.confirm = true;
+ return copy;
+ };
+
+ if (args[e.confirmFlag] !== true) {
+ return {
+ ok: false,
+ result: textResult(
+ `${name} moves funds or cannot be undone, so it needs ${e.confirmFlag}: true. ` +
+ `First call ${e.previewTool}, show the user what it returns, and call ${name} with its ${e.previewArg} and ` +
+ `${e.confirmFlag}: true only after the user clearly says yes.`,
+ { ok: false, reason: 'confirmation_required', tool: name, confirm_flag: e.confirmFlag, preview_tool: e.previewTool, preview_arg: e.previewArg },
+ ),
+ };
+ }
+ if (!e.previewTool) return { ok: true, args: strip(args), entry: e, preview: null };
+
+ const id = args[e.previewArg];
+ const refuse = (reason, detail) =>
+ ({
+ ok: false,
+ result: textResult(`${detail} Call ${e.previewTool} again, show the user the fresh result, and retry ${name} with the new ${e.previewArg} after they approve.`, {
+ ok: false,
+ reason,
+ tool: name,
+ preview_tool: e.previewTool,
+ preview_arg: e.previewArg,
+ }),
+ });
+ if (typeof id !== 'string' || !id) return refuse('preview_required', `${name} needs the ${e.previewArg} returned by ${e.previewTool}.`);
+ const record = await store.get(id);
+ if (!record || record.server !== serverId) return refuse('preview_unknown', `${e.previewArg} ${id} is unknown or has expired.`);
+ if (now() - record.createdAt > PREVIEW_TTL_MS) {
+ await store.del(id);
+ return refuse('preview_stale', `${e.previewArg} ${id} is older than ${PREVIEW_TTL_MS / 60000} minutes, so it no longer reflects live prices and balances.`);
+ }
+ if (record.tool !== e.previewTool) return refuse('preview_mismatch', `${e.previewArg} ${id} came from ${record.tool}, not ${e.previewTool}.`);
+ if (record.principal !== principal) return refuse('preview_mismatch', `${e.previewArg} ${id} belongs to a different caller.`);
+ const differs = e.bind.filter(([from, to]) => !sameValue(record.args?.[from], args[to])).map(([, to]) => to);
+ if (differs.length) {
+ return refuse('preview_mismatch', `The ${differs.join(', ')} you passed differ from what ${e.previewTool} previewed.`);
+ }
+ return { ok: true, args: strip(args), entry: e, preview: { id, ...record } };
+ }
+
+ /**
+ * Finish one call: issue a preview id for a successful preview tool, burn
+ * the preview a successful financial call consumed.
+ * @param {{ name: string, args?: object, principal: string, result: object, preview?: object|null }} done
+ */
+ async function afterCall({ name, args = {}, principal, result, preview = null }) {
+ if (!result || result.isError) return result;
+ if (preview?.id) {
+ await store.del(preview.id);
+ return result;
+ }
+ const unlocks = authorizes.get(name);
+ if (!unlocks?.length) return result;
+
+ const arg = unlocks[0].previewArg;
+ const id = newPreviewId(arg);
+ const createdAt = now();
+ const kept = Object.fromEntries(Object.entries(args).filter(([k]) => !SECRET_ARG.test(k)));
+ await store.put(id, { server: serverId, tool: name, principal, args: kept, createdAt }, PREVIEW_TTL_MS);
+
+ const expiresAt = new Date(createdAt + PREVIEW_TTL_MS).toISOString();
+ const next = unlocks.map((f) => `${f.name} with ${f.previewArg}: "${id}" and ${f.confirmFlag}: true`).join(', or ');
+ const note =
+ `${arg}: ${id} (valid until ${expiresAt}). Show the user this result. Only after they clearly say yes, call ${next}. ` +
+ 'If they say no, or change anything, do not call it.';
+ return {
+ ...result,
+ content: [...(Array.isArray(result.content) ? result.content : []), { type: 'text', text: note }],
+ _meta: {
+ ...(result._meta || {}),
+ 'three.ws/preview': { [arg]: id, expires_at: expiresAt, unlocks: unlocks.map((f) => f.name) },
+ },
+ };
+ }
+
+ return { serverId, entry, entries, enabled, listTools, beforeCall, afterCall, disabledResult, policyMeta };
+}
diff --git a/packages/metaplex-agent-mcp/src/index.js b/packages/metaplex-agent-mcp/src/index.js
index 38c640763..bd6e07a56 100755
--- a/packages/metaplex-agent-mcp/src/index.js
+++ b/packages/metaplex-agent-mcp/src/index.js
@@ -29,10 +29,10 @@ import { pathToFileURL } from 'node:url';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import { def as mintOnchainAgent } from './tools/mint-onchain-agent.js';
+import { def as mintOnchainAgent, previewDef as previewAgentMint } from './tools/mint-onchain-agent.js';
import { def as prepareAgentMint } from './tools/prepare-agent-mint.js';
import { def as sendSignedTransaction } from './tools/send-signed-transaction.js';
-import { def as registerAgentIdentity } from './tools/register-agent-identity.js';
+import { def as registerAgentIdentity, previewDef as previewAgentIdentity } from './tools/register-agent-identity.js';
import { def as getOnchainAgent } from './tools/get-onchain-agent.js';
import { def as agentWallet } from './tools/agent-wallet.js';
import { def as buildRegistration } from './tools/build-registration.js';
@@ -43,9 +43,11 @@ const require = createRequire(import.meta.url);
const { version: PKG_VERSION } = require('../package.json');
export const TOOLS = [
+ previewAgentMint,
mintOnchainAgent,
prepareAgentMint,
sendSignedTransaction,
+ previewAgentIdentity,
registerAgentIdentity,
getOnchainAgent,
agentWallet,
diff --git a/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js b/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js
index 9af1425c2..73db3bc1b 100644
--- a/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js
+++ b/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js
@@ -55,7 +55,31 @@ export const def = {
secret: z.string().optional().describe('Per-call signing key (base58 secret key or JSON byte array). Overrides SOLANA_SECRET_KEY.'),
confirm: z.boolean().optional().describe('Must be true to broadcast. Anything else returns a spend-nothing preview.'),
},
- async handler(args) {
+ handler: (args) => runMint(args, { preview: REQUIRE_CONFIRM && args.confirm !== true }),
+};
+
+/**
+ * `preview_agent_mint`: the preview that must run before mint_onchain_agent.
+ * The same documents, paying wallet and cost lines the mint would use, plus the
+ * wallet's live balance, and nothing broadcast whatever REQUIRE_CONFIRM says.
+ */
+export const previewDef = {
+ name: 'preview_agent_mint',
+ title: 'Preview an on-chain agent mint (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Preview mint_onchain_agent before it runs: both JSON documents, the paying wallet and its live SOL balance, ' +
+ 'every cost line including the deploy fee and its recipient, and whether the balance covers it. Broadcasts ' +
+ 'nothing. Show it to the user, get a clear yes, then call mint_onchain_agent with the same arguments, the ' +
+ 'returned preview_id and confirm_spend: true.',
+ inputSchema: {
+ ...mintShape,
+ secret: z.string().optional().describe('Per-call signing key (base58 secret key or JSON byte array). Only its public key is read.'),
+ },
+ handler: (args) => runMint(args, { preview: true }),
+};
+
+async function runMint(args, { preview }) {
const network = args.network || NETWORK;
const umi = buildUmi({ network, secret: args.secret, requireSigner: true });
const wallet = umi.identity.publicKey.toString();
@@ -68,10 +92,13 @@ export const def = {
);
const asset = mint.assetSigner.publicKey.toString();
- if (REQUIRE_CONFIRM && args.confirm !== true) {
+ if (preview) {
+ const balance = await solBalance(umi, wallet);
return {
ok: true,
confirm_required: true,
+ wallet_balance_sol: balance,
+ balance_covers_cost: balance >= total,
message:
`Preview only. Re-issue with confirm:true to mint on ${network} for ~${total} SOL ` +
`(~${EST_NETWORK_SOL} rent + network fees${fee.sol > 0 ? `, ${fee.sol} SOL deploy fee to ${fee.wallet}` : ', no deploy fee'}).`,
@@ -113,5 +140,4 @@ export const def = {
links: agentLinks(asset, network),
note: 'The agent is live in the Metaplex Agent Registry. DAS indexers surface it within minutes; fund agent_wallet to let the asset act on-chain.',
};
- },
-};
+}
diff --git a/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js b/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js
index e7c8aa848..0f16d4721 100644
--- a/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js
+++ b/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js
@@ -58,7 +58,31 @@ export const def = {
secret: z.string().optional().describe('Per-call signing key. Overrides SOLANA_SECRET_KEY.'),
confirm: z.boolean().optional().describe('Must be true to broadcast. Anything else returns a preview.'),
},
- async handler(args) {
+ handler: (args) => runRegister(args, { preview: REQUIRE_CONFIRM && args.confirm !== true }),
+};
+
+const { confirm: _confirm, ...previewShape } = def.inputSchema;
+
+/**
+ * `preview_agent_identity`: the preview that must run before
+ * register_agent_identity. Resolves the identity PDA, reports an asset that is
+ * already registered, and renders the exact registration document, without
+ * broadcasting whatever REQUIRE_CONFIRM says.
+ */
+export const previewDef = {
+ name: 'preview_agent_identity',
+ title: 'Preview an Agent Identity registration (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Preview register_agent_identity before it runs: the identity PDA, whether the asset is already registered, ' +
+ 'the paying wallet, the cost, and the exact registration document that would be written. Broadcasts nothing. ' +
+ 'Show it to the user, get a clear yes, then call register_agent_identity with the same arguments, the ' +
+ 'returned preview_id and confirm_spend: true.',
+ inputSchema: previewShape,
+ handler: (args) => runRegister(args, { preview: true }),
+};
+
+async function runRegister(args, { preview }) {
const network = args.network || NETWORK;
const umi = buildUmi({ network, secret: args.secret, requireSigner: true });
const assetPk = umiPublicKey(args.asset);
@@ -95,7 +119,7 @@ export const def = {
});
const agentRegistrationUri = args.registration_uri || jsonDataUri(registration);
- if (REQUIRE_CONFIRM && args.confirm !== true) {
+ if (preview) {
return {
ok: true,
confirm_required: true,
@@ -104,6 +128,7 @@ export const def = {
asset: args.asset,
identity_pda: identityPda.toString(),
paying_wallet: umi.identity.publicKey.toString(),
+ estimated_cost_sol: EST_REGISTER_LAMPORTS / LAMPORTS_PER_SOL,
registration,
};
}
@@ -125,5 +150,4 @@ export const def = {
registration,
links: agentLinks(args.asset, network),
};
- },
-};
+}
diff --git a/packages/portfolio-mcp/src/index.js b/packages/portfolio-mcp/src/index.js
index 09e13c072..90d19a721 100755
--- a/packages/portfolio-mcp/src/index.js
+++ b/packages/portfolio-mcp/src/index.js
@@ -30,6 +30,7 @@ import { def as getPortfolioHistory } from './tools/portfolio-history.js';
import { def as getPortfolioAsset } from './tools/portfolio-asset.js';
import { def as getTradesFeed } from './tools/trades-feed.js';
import { def as getWalletBalances } from './tools/wallet-balances.js';
+import { def as previewTransfer } from './tools/preview-transfer.js';
import { def as sendTransfer } from './tools/send-transfer.js';
// Single source of truth for the advertised server version — package.json.
@@ -42,6 +43,7 @@ export const TOOLS = [
getPortfolioAsset,
getTradesFeed,
getWalletBalances,
+ previewTransfer,
sendTransfer,
];
diff --git a/packages/portfolio-mcp/src/lib/solana.js b/packages/portfolio-mcp/src/lib/solana.js
index b72cff478..c7aecadbd 100644
--- a/packages/portfolio-mcp/src/lib/solana.js
+++ b/packages/portfolio-mcp/src/lib/solana.js
@@ -290,3 +290,103 @@ export async function sendTransfer({ secret, to, amount, mint, priorityMicroLamp
explorer: `https://solscan.io/tx/${sig}`,
};
}
+
+// Rent for a new associated token account (165 bytes), paid by the sender when
+// the recipient has none yet. Read live when possible; this is the fallback.
+const ATA_RENT_LAMPORTS_FALLBACK = 2_039_280;
+const BASE_FEE_LAMPORTS = 5000;
+const TRANSFER_COMPUTE_UNITS = 200_000;
+
+/**
+ * Preview a send_transfer without signing: the sender address, what it holds of
+ * the asset, the exact base units that would move, whether the recipient needs
+ * a new token account (and the rent that costs), the network fee, and every
+ * rule that would refuse the transfer. Refusals are returned, never thrown.
+ */
+export async function previewTransfer({ secret, to, amount, mint, priorityMicroLamports = 100000 }, policy) {
+ const blockers = [];
+ if (!isValidPubkey(to)) blockers.push({ code: 'invalid_destination', message: `Not a valid Solana pubkey: ${to}` });
+ else if (policy.allowlist && !policy.allowlist.has(to)) {
+ blockers.push({ code: 'recipient_not_allowed', message: `${to} is not in RECIPIENT_ALLOWLIST.` });
+ }
+ const isNative = !mint || mint === 'native';
+ if (!isNative && !isValidPubkey(mint)) {
+ blockers.push({ code: 'invalid_mint', message: `mint must be a base58 SPL mint or "native" (got ${mint})` });
+ return { from: null, to, blockers, would_execute: false };
+ }
+
+ const signer = loadSigner(secret);
+ const from = signer.publicKey.toBase58();
+ const conn = getConnection();
+ const microLamports = clampPriorityMicroLamports(priorityMicroLamports);
+ const feeLamports = BASE_FEE_LAMPORTS + Math.ceil((microLamports * TRANSFER_COMPUTE_UNITS) / 1_000_000);
+ const solLamports = BigInt(await conn.getBalance(signer.publicKey, 'confirmed'));
+
+ if (isNative) {
+ const sol = Number(amount);
+ const lamports = BigInt(Math.round(sol * LAMPORTS_PER_SOL));
+ if (sol > policy.maxSolPerTx) {
+ blockers.push({ code: 'over_spend_cap', message: `${sol} SOL exceeds the per-tx cap of ${policy.maxSolPerTx} SOL.` });
+ }
+ if (solLamports < lamports + BigInt(feeLamports)) {
+ blockers.push({ code: 'insufficient_balance', message: `Sender holds ${Number(solLamports) / LAMPORTS_PER_SOL} SOL; this needs ${Number(lamports + BigInt(feeLamports)) / LAMPORTS_PER_SOL} SOL including the fee.` });
+ }
+ return {
+ action: 'send_transfer',
+ chain: 'solana-mainnet',
+ asset: 'SOL',
+ from,
+ to,
+ amount: String(amount),
+ base_units: String(lamports),
+ network_fee_sol: feeLamports / LAMPORTS_PER_SOL,
+ sender_sol: Number(solLamports) / LAMPORTS_PER_SOL,
+ sender_sol_after: Number(solLamports - lamports - BigInt(feeLamports)) / LAMPORTS_PER_SOL,
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+ }
+
+ const { getMint, getAssociatedTokenAddress, getAccount } = await splToken();
+ const mintPk = new PublicKey(mint);
+ const programId = await resolveTokenProgram(conn, mintPk);
+ const mintInfo = await getMint(conn, mintPk, 'confirmed', programId);
+ const baseUnits = parseAmountToBaseUnits(amount, mintInfo.decimals);
+ const senderAta = await getAssociatedTokenAddress(mintPk, signer.publicKey, false, programId);
+ let held = 0n;
+ try {
+ held = (await getAccount(conn, senderAta, 'confirmed', programId)).amount;
+ } catch {
+ held = 0n;
+ }
+ if (held < baseUnits) {
+ blockers.push({ code: 'insufficient_balance', message: `Sender holds ${held} base units of ${mint}; this needs ${baseUnits}.` });
+ }
+ let ataRent = 0;
+ if (isValidPubkey(to)) {
+ const recipientAta = await getAssociatedTokenAddress(mintPk, new PublicKey(to), false, programId);
+ if (!(await conn.getAccountInfo(recipientAta))) {
+ ataRent = await conn.getMinimumBalanceForRentExemption(165).catch(() => ATA_RENT_LAMPORTS_FALLBACK);
+ }
+ }
+ if (solLamports < BigInt(feeLamports + ataRent)) {
+ blockers.push({ code: 'insufficient_sol_for_fees', message: `Sender needs ${(feeLamports + ataRent) / LAMPORTS_PER_SOL} SOL for fees and rent; holds ${Number(solLamports) / LAMPORTS_PER_SOL}.` });
+ }
+ return {
+ action: 'send_transfer',
+ chain: 'solana-mainnet',
+ asset: mint,
+ decimals: mintInfo.decimals,
+ from,
+ to,
+ amount: String(amount),
+ base_units: String(baseUnits),
+ sender_token_base_units: String(held),
+ creates_recipient_token_account: ataRent > 0,
+ recipient_account_rent_sol: ataRent / LAMPORTS_PER_SOL,
+ network_fee_sol: feeLamports / LAMPORTS_PER_SOL,
+ sender_sol: Number(solLamports) / LAMPORTS_PER_SOL,
+ would_execute: blockers.length === 0,
+ blockers,
+ };
+}
diff --git a/packages/portfolio-mcp/src/tools/preview-transfer.js b/packages/portfolio-mcp/src/tools/preview-transfer.js
new file mode 100644
index 000000000..2ca41dc81
--- /dev/null
+++ b/packages/portfolio-mcp/src/tools/preview-transfer.js
@@ -0,0 +1,41 @@
+// `preview_transfer` — the preview that must run before send_transfer. Reads
+// the sender's live balances and applies the same cap and allowlist rules the
+// transfer applies, without signing.
+
+import { z } from 'zod';
+
+import { previewTransfer } from '../lib/solana.js';
+import { MAX_SOL_PER_TX, RECIPIENT_ALLOWLIST } from '../lib/spend-policy.js';
+
+export const def = {
+ name: 'preview_transfer',
+ title: 'Preview a SOL or SPL transfer (no funds move)',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Preview send_transfer before it runs: the sending wallet, the recipient, the asset and exact base units, what ' +
+ 'the sender holds, whether a recipient token account must be created and the rent that costs, the network fee, ' +
+ 'and every rule that would refuse the transfer (spend cap, allowlist, balance). Signs nothing. Show it to the ' +
+ 'user, get a clear yes, then call send_transfer with the same arguments, the returned preview_id and ' +
+ 'confirm_transfer: true.',
+ inputSchema: {
+ recipient: z.string().min(32).max(44).describe('Destination Solana pubkey (base58).'),
+ amount: z
+ .string()
+ .regex(/^(\d+(\.\d*)?|\.\d+)$/, 'amount must be a positive decimal string, e.g. "1.5"')
+ .describe('Amount in human units as a decimal string.'),
+ mint: z.string().optional().describe('SPL token mint (base58). Omit or "native" for SOL.'),
+ secret: z.string().optional().describe('Base58 secret of the sending wallet (only its public key is read). Falls back to SOLANA_SECRET_KEY.'),
+ priorityMicroLamports: z.number().int().min(0).max(50_000_000).optional().describe('Compute-unit price (default 100000).'),
+ },
+ async handler(args) {
+ try {
+ const preview = await previewTransfer(
+ { secret: args.secret, to: args.recipient, amount: args.amount, mint: args.mint, priorityMicroLamports: args.priorityMicroLamports },
+ { maxSolPerTx: MAX_SOL_PER_TX, allowlist: RECIPIENT_ALLOWLIST },
+ );
+ return { ok: true, preview };
+ } catch (err) {
+ return { ok: false, error: err.code || 'preview_failed', message: err.message };
+ }
+ },
+};