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): add call_agent tool for inter-agent communication

nirholas2d73eff1c618
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
new file mode 100644
index 000000000..d65249311
--- /dev/null
+++ b/api/_mcp/auth.js
@@ -0,0 +1,112 @@
+import { env } from '../_lib/env.js';
+import { authenticateBearer, extractBearer } from '../_lib/auth.js';
+import {
+ paymentRequirements,
+ verifyPayment,
+ send402,
+ resolveResourceUrl,
+} from '../_lib/x402-spec.js';
+import { sendX402Error } from './payments.js';
+
+function quoteString(s) {
+ return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
+}
+
+export function send401(res, msg) {
+ const resource = env.MCP_RESOURCE;
+ res.statusCode = 401;
+ res.setHeader(
+ 'www-authenticate',
+ `Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
+ );
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: 'unauthorized', error_description: msg }));
+}
+
+export function sendJsonRpcError(res, id, code, message, data) {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: id ?? null, error: { code, message, data } }));
+}
+
+// Returns { auth, x402Ctx } on success, or null if a response was already sent.
+export async function authenticateRequest(req, res) {
+ const bearer = extractBearer(req);
+ const paymentHeader = req.headers['x-payment'];
+
+ if (bearer) {
+ const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
+ if (!auth) {
+ send401(res, 'missing or invalid access token');
+ return null;
+ }
+ return { auth, x402Ctx: null };
+ }
+
+ const requirements = paymentRequirements({
+ resource: resolveResourceUrl(req, '/api/mcp'),
+ description: 'MCP tool call',
+ });
+
+ if (paymentHeader) {
+ try {
+ const verified = await verifyPayment({ paymentHeader, requirements });
+ const x402Ctx = {
+ requirements,
+ requirement: verified.requirement,
+ paymentPayload: verified.paymentPayload,
+ payer: verified.payer,
+ };
+ // Anonymous paid caller — synthesize an auth principal scoped to public-read tools.
+ // userId is null because usage_events.user_id is a UUID FK; the payer wallet is
+ // kept on the auth object so handlers and rate limits can key off of it.
+ return {
+ auth: {
+ userId: null,
+ rateKey: `x402:${x402Ctx.payer || 'anon'}`,
+ // Pay-per-call callers have no user account, so they cannot read or
+ // write account-scoped data. They get only the no-scope public tools
+ // (search_public_avatars, validate/inspect/optimize_model, solana_*).
+ scope: '',
+ source: 'x402',
+ payer: x402Ctx.payer,
+ },
+ x402Ctx,
+ };
+ } catch (err) {
+ sendX402Error(res, requirements, err);
+ return null;
+ }
+ }
+
+ send402(res, requirements);
+ return null;
+}
+
+export async function handleSse(req, res) {
+ // We don't hold long-lived server→client subscriptions yet; respond politely.
+ const bearer = extractBearer(req);
+ // Unauthenticated callers without an X-PAYMENT header get an x402 challenge
+ // so x402scan / x402 clients can discover the price. Invalid bearers still
+ // get 401 with WWW-Authenticate so OAuth clients can re-auth correctly.
+ if (!bearer && !req.headers['x-payment']) {
+ return send402(
+ res,
+ paymentRequirements({
+ resource: resolveResourceUrl(req, '/api/mcp'),
+ description: 'MCP tool call',
+ }),
+ );
+ }
+ const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
+ if (!auth) return send401(res, 'missing or invalid access token');
+ res.statusCode = 405;
+ res.setHeader('allow', 'POST, DELETE');
+ res.end();
+}
+
+export function handleTerminate(_req, res) {
+ // Stateless per-request server — nothing to tear down.
+ res.statusCode = 204;
+ res.end();
+}
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
new file mode 100644
index 000000000..9d2fb65fb
--- /dev/null
+++ b/api/_mcp/catalog.js
@@ -0,0 +1,14 @@
+import { toolDefs as avatarDefs } from './tools/avatars.js';
+import { toolDefs as modelDefs } from './tools/models.js';
+import { toolDefs as solanaDefs } from './tools/solana.js';
+import { toolDefs as pumpfunDefs } from './tools/pumpfun.js';
+
+const allDefs = [...avatarDefs, ...modelDefs, ...solanaDefs, ...pumpfunDefs];
+
+// Schema objects for tools/list — strip internal fields (scope, handler).
+export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+
+// Handler lookup for tools/call — keyed by tool name.
+export const TOOLS = Object.fromEntries(
+ allDefs.map(({ name, scope, handler }) => [name, { scope, handler }]),
+);
diff --git a/api/_mcp/payments.js b/api/_mcp/payments.js
new file mode 100644
index 000000000..1de43f20e
--- /dev/null
+++ b/api/_mcp/payments.js
@@ -0,0 +1,18 @@
+import { logger } from '../_lib/usage.js';
+import { X402Error, send402 } from '../_lib/x402-spec.js';
+
+const log = logger('mcp');
+
+export function sendX402Error(res, requirements, err) {
+ if (err instanceof X402Error) {
+ if (err.status === 402) return send402(res, requirements, err.message);
+ res.statusCode = err.status;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: err.code, error_description: err.message }));
+ return;
+ }
+ log.error('x402_unexpected', { message: err?.message });
+ res.statusCode = 500;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: 'internal', error_description: 'x402 processing failed' }));
+}
diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.js
new file mode 100644
index 000000000..e75bea7fe
--- /dev/null
+++ b/api/_mcp/tools/avatars.js
@@ -0,0 +1,350 @@
+import { sql } from '../../_lib/db.js';
+import {
+ listAvatars,
+ getAvatar,
+ getAvatarBySlug,
+ searchPublicAvatars,
+ resolveAvatarUrl,
+ deleteAvatar,
+} from '../../_lib/avatars.js';
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+function _mcpDefaultPolicy() {
+ return {
+ version: 1,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: true },
+ };
+}
+
+function _mcpParsePolicy(p) {
+ if (!p) return null;
+ if (!('version' in p) && ('mode' in p || 'hosts' in p)) {
+ // Old flat shape — only origins were configured; all surfaces (incl. mcp) allowed.
+ return {
+ ..._mcpDefaultPolicy(),
+ origins: { mode: p.mode || 'allowlist', hosts: p.hosts ?? [] },
+ };
+ }
+ return { ..._mcpDefaultPolicy(), ...p };
+}
+
+async function _readMcpPolicyByAvatar(avatarId) {
+ try {
+ const [row] = await sql`
+ SELECT embed_policy FROM agent_identities
+ WHERE avatar_id = ${avatarId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!row) return null;
+ return _mcpParsePolicy(row.embed_policy);
+ } catch (err) {
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+
+function esc(s) {
+ return String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
+}
+
+function attr(s) {
+ return String(s).replace(
+ /[&<>"]/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c],
+ );
+}
+
+// CSS inputs land inside a <style> declaration (`background: <value>`), where
+// HTML attribute-escaping does not defend against `;}body{…}` breakouts. Only
+// allow a strict character class that cannot terminate the declaration/rule.
+function safeCssValue(s, fallback) {
+ if (!s) return fallback;
+ const str = String(s).trim();
+ if (!/^[a-zA-Z0-9 .,%#()\-_/+]+$/.test(str)) return fallback;
+ if (str.length > 120) return fallback;
+ return str;
+}
+
+function safeCssLength(s, fallback) {
+ if (!s) return fallback;
+ const str = String(s).trim();
+ if (!/^[0-9]+(?:\.[0-9]+)?(?:px|em|rem|vh|vw|%)$|^auto$|^100%$/.test(str)) return fallback;
+ return str;
+}
+
+// Posters are rendered as an attribute value that the browser fetches; restrict
+// to https(:) to block `javascript:` and `data:` URLs that could execute code.
+function safeHttpsUrl(s) {
+ if (!s) return undefined;
+ try {
+ const u = new URL(String(s));
+ return u.protocol === 'https:' ? u.toString() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function renderModelViewerHtml({ src, name, poster, background, height, width, autoRotate, ar, cameraOrbit }) {
+ const attrs = [
+ `src="${attr(src)}"`,
+ 'camera-controls',
+ 'shadow-intensity="1"',
+ 'exposure="1"',
+ 'tone-mapping="aces"',
+ autoRotate ? 'auto-rotate' : '',
+ ar ? 'ar ar-modes="webxr scene-viewer quick-look"' : '',
+ poster ? `poster="${attr(poster)}"` : '',
+ cameraOrbit ? `camera-orbit="${attr(cameraOrbit)}"` : '',
+ `alt="${attr(name || 'Avatar')}"`,
+ ]
+ .filter(Boolean)
+ .join(' ');
+ return [
+ '<!doctype html>',
+ '<html><head><meta charset="utf-8"><title>' + esc(name || 'Avatar') + '</title>',
+ '<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>',
+ '<style>html,body{margin:0;height:100%;background:' + attr(background) + '}',
+ 'model-viewer{width:' + attr(width) + ';height:' + attr(height) + ';--progress-bar-color:#6a5cff}</style>',
+ '</head><body>',
+ '<model-viewer ' + attrs + '></model-viewer>',
+ '</body></html>',
+ ].join('\n');
+}
+
+function formatAvatarList(avatars, { public: isPublic = false } = {}) {
+ if (!avatars.length) return 'No avatars found.';
+ return avatars
+ .map((a) => {
+ const url = a.model_url ? ` — ${a.model_url}` : '';
+ const vis = isPublic ? '' : ` [${a.visibility}]`;
+ return `• ${a.name} (slug: ${a.slug}, id: ${a.id})${vis}${url}`;
+ })
+ .join('\n');
+}
+
+export const toolDefs = [
+ {
+ name: 'list_my_avatars',
+ title: 'List my avatars',
+ description:
+ "List the authenticated user's avatars. Returns id, name, slug, size, visibility, and direct model_url (when visibility permits).",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 25 },
+ cursor: {
+ type: 'string',
+ description: 'Opaque pagination cursor from previous response.',
+ },
+ visibility: { type: 'string', enum: ['private', 'unlisted', 'public'] },
+ },
+ additionalProperties: false,
+ },
+ scope: 'avatars:read',
+ async handler(args, auth) {
+ const result = await listAvatars({
+ userId: auth.userId,
+ limit: args.limit || 25,
+ cursor: args.cursor,
+ visibility: args.visibility,
+ });
+ return {
+ content: [{ type: 'text', text: formatAvatarList(result.avatars) }],
+ structuredContent: result,
+ };
+ },
+ },
+ {
+ name: 'get_avatar',
+ title: 'Get avatar',
+ description:
+ 'Fetch a single avatar by id or by owner+slug. Returns metadata and a model_url (public/unlisted) or short-lived signed URL (private).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', format: 'uuid' },
+ slug: { type: 'string' },
+ },
+ additionalProperties: false,
+ },
+ scope: 'avatars:read',
+ async handler(args, auth) {
+ const avatar = args.id
+ ? await getAvatar({ id: args.id, requesterId: auth.userId })
+ : args.slug
+ ? await getAvatarBySlug({
+ ownerId: auth.userId,
+ slug: args.slug,
+ requesterId: auth.userId,
+ })
+ : null;
+ if (!avatar) throw new Error('avatar not found');
+ const urlInfo = await resolveAvatarUrl(avatar);
+ const merged = { ...avatar, ...urlInfo };
+ return {
+ content: [{ type: 'text', text: JSON.stringify(merged, null, 2) }],
+ structuredContent: merged,
+ };
+ },
+ },
+ {
+ name: 'search_public_avatars',
+ title: 'Search public avatars',
+ description:
+ 'Search the public avatar gallery. Useful for finding characters to render without prior knowledge of an id.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ q: { type: 'string', description: 'Free-text search over name and description.' },
+ tag: { type: 'string', description: 'Filter to one tag.' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 12 },
+ },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ // Unauthenticated callers (x402/anonymous) are capped at 10 to prevent bulk enumeration.
+ const maxLimit = auth.userId ? 50 : 10;
+ const result = await searchPublicAvatars({
+ q: args.q,
+ tag: args.tag,
+ limit: Math.min(args.limit || 12, maxLimit),
+ });
+ return {
+ content: [
+ { type: 'text', text: formatAvatarList(result.avatars, { public: true }) },
+ ],
+ structuredContent: result,
+ };
+ },
+ },
+ {
+ name: 'render_avatar',
+ title: 'Render avatar',
+ description:
+ 'Produce an HTML <model-viewer> snippet that renders the given avatar. ' +
+ 'Return this text as an inline HTML artifact to display an interactive 3D avatar.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', format: 'uuid' },
+ slug: { type: 'string' },
+ auto_rotate: { type: 'boolean', default: true },
+ background: {
+ type: 'string',
+ description: 'CSS background color or gradient.',
+ default: 'transparent',
+ },
+ height: { type: 'string', default: '480px' },
+ width: { type: 'string', default: '100%' },
+ camera_orbit: {
+ type: 'string',
+ description: 'model-viewer camera-orbit value, e.g. "0deg 80deg 2m".',
+ },
+ poster: {
+ type: 'string',
+ description: 'Optional poster image URL shown while loading.',
+ },
+ ar: {
+ type: 'boolean',
+ default: true,
+ description: 'Include AR button for mobile.',
+ },
+ },
+ additionalProperties: false,
+ },
+ scope: 'avatars:read',
+ async handler(args, auth) {
+ const avatar = args.id
+ ? await getAvatar({ id: args.id, requesterId: auth.userId })
+ : args.slug
+ ? await getAvatarBySlug({
+ ownerId: auth.userId,
+ slug: args.slug,
+ requesterId: auth.userId,
+ })
+ : null;
+ if (!avatar) throw new Error('avatar not found');
+ // surfaces.mcp gate — check if a registered agent owns this avatar
+ const _mcpPolicy = await _readMcpPolicyByAvatar(avatar.id);
+ if (_mcpPolicy && _mcpPolicy.surfaces?.mcp === false) {
+ throw rpcError(
+ -32000,
+ 'embed_denied_surface',
+ 'This agent disallows the MCP surface.',
+ );
+ }
+ const urlInfo = await resolveAvatarUrl(avatar, { expiresIn: 3600 });
+ const html = renderModelViewerHtml({
+ src: urlInfo.url,
+ name: avatar.name,
+ poster: safeHttpsUrl(args.poster),
+ background: safeCssValue(args.background, 'transparent'),
+ height: safeCssLength(args.height, '480px'),
+ width: safeCssLength(args.width, '100%'),
+ autoRotate: args.auto_rotate !== false,
+ ar: args.ar !== false,
+ cameraOrbit: safeCssValue(args.camera_orbit, ''),
+ });
+ // Keep chat text short so claude.ai doesn't dump the full HTML into the
+ // transcript. The HTML goes in the resource entry, which clients render
+ // as an inline artifact when mimeType is text/html.
+ const summary = `Rendered avatar "${avatar.name}". Display the attached text/html resource as an inline HTML artifact.`;
+ return {
+ content: [
+ { type: 'text', text: summary },
+ {
+ type: 'resource',
+ resource: {
+ uri: `avatar://${avatar.id}`,
+ mimeType: 'text/html',
+ text: html,
+ },
+ },
+ ],
+ structuredContent: { html, avatar: { ...avatar, ...urlInfo } },
+ };
+ },
+ },
+ {
+ name: 'delete_avatar',
+ title: 'Delete avatar',
+ description: 'Soft-delete an avatar you own. Requires avatars:delete scope.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', format: 'uuid' },
+ confirm: {
+ type: 'boolean',
+ description: 'Must be true to confirm permanent deletion.',
+ },
+ },
+ required: ['id'],
+ additionalProperties: false,
+ },
+ scope: 'avatars:delete',
+ async handler(args, auth) {
+ if (!args.confirm) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: 'Set confirm: true to permanently delete this avatar.',
+ },
+ ],
+ isError: true,
+ };
+ }
+ const result = await deleteAvatar({ id: args.id, userId: auth.userId });
+ if (!result) throw new Error('avatar not found or not yours');
+ // TODO: audit_log table needed — INSERT (user_id, action='delete_avatar', resource_id, created_at)
+ return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };
+ },
+ },
+];
diff --git a/api/_mcp/tools/models.js b/api/_mcp/tools/models.js
new file mode 100644
index 000000000..cfe84c173
--- /dev/null
+++ b/api/_mcp/tools/models.js
@@ -0,0 +1,188 @@
+import { limits } from '../../_lib/rate-limit.js';
+import { fetchModel, FetchModelError } from '../../_lib/fetch-model.js';
+import { inspectModel, suggestOptimizations } from '../../_lib/model-inspect.js';
+import { validateBytes } from 'gltf-validator';
+
+function rpcError(code, message, data) {
+ const e = new Error(message);
+ e.code = code;
+ e.data = data;
+ return e;
+}
+
+async function safeFetchModel(url) {
+ try {
+ return await fetchModel(url);
+ } catch (e) {
+ if (e instanceof FetchModelError) throw new Error(`fetch failed: ${e.message} (${e.code})`);
+ throw e;
+ }
+}
+
+function formatValidationSummary(s, messages) {
+ const head =
+ `glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
+ `Errors: ${s.numErrors}, Warnings: ${s.numWarnings}, Infos: ${s.numInfos}, Hints: ${s.numHints}` +
+ (s.truncated ? ' (truncated)' : '');
+ if (!messages.length) return head;
+ const lines = messages.slice(0, 40).map((m) => {
+ const sev = ['ERR', 'WRN', 'INF', 'HNT'][m.severity] || '?';
+ const ptr = m.pointer ? ` @ ${m.pointer}` : '';
+ return ` [${sev}] ${m.code}: ${m.message}${ptr}`;
+ });
+ const more = messages.length > 40 ? `\n … ${messages.length - 40} more` : '';
+ return `${head}\n${lines.join('\n')}${more}`;
+}
+
+function formatInspection(info) {
+ const c = info.counts;
+ const tex = info.textures.length
+ ? info.textures
+ .map(
+ (t) =>
+ ` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`,
+ )
+ .join('\n')
+ : ' (none)';
+ return [
+ `Model: ${info.filename} (${(info.fileSize / 1024 / 1024).toFixed(2)} MB, ${info.container})`,
+ `Generator: ${info.generator || 'unknown'} · glTF ${info.version || '?'}`,
+ `Scenes: ${c.scenes}, Nodes: ${c.nodes}, Meshes: ${c.meshes}, Materials: ${c.materials}, Textures: ${c.textures}`,
+ `Animations: ${c.animations}, Skins: ${c.skins}`,
+ `Vertices: ${c.totalVertices.toLocaleString()}, Triangles: ${c.totalTriangles.toLocaleString()}`,
+ `Indexed primitives: ${c.indexedPrimitives}, Non-indexed: ${c.nonIndexedPrimitives}`,
+ `Extensions used: ${info.extensionsUsed.join(', ') || '(none)'}`,
+ `Textures:\n${tex}`,
+ ].join('\n');
+}
+
+function formatSuggestions(suggestions) {
+ if (!suggestions.length) return 'No suggestions.';
+ return suggestions
+ .map((s) => {
+ const tag =
+ { info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] ||
+ s.severity.toUpperCase();
+ const est = s.estimate ? ` — ${s.estimate}` : '';
+ return `[${tag}] ${s.id}: ${s.message}${est}`;
+ })
+ .join('\n');
+}
+
+export const toolDefs = [
+ {
+ name: 'validate_model',
+ title: 'Validate glTF/GLB model',
+ description:
+ 'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints — the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
+ max_issues: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const rl = await limits.mcpValidate(auth.userId || auth.rateKey);
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const max = Math.min(Math.max(args.max_issues || 100, 1), 500);
+ const report = await validateBytes(bytes, { maxIssues: max, uri: filename });
+ const issues = report?.issues || {};
+ const summary = {
+ url,
+ filename,
+ fileSize: bytes.byteLength,
+ validatorVersion: report?.validatorVersion,
+ mimeType: report?.mimeType,
+ numErrors: issues.numErrors ?? 0,
+ numWarnings: issues.numWarnings ?? 0,
+ numInfos: issues.numInfos ?? 0,
+ numHints: issues.numHints ?? 0,
+ truncated: !!issues.truncated,
+ };
+ return {
+ content: [
+ { type: 'text', text: formatValidationSummary(summary, issues.messages || []) },
+ ],
+ structuredContent: {
+ ...summary,
+ messages: issues.messages || [],
+ info: report?.info || null,
+ },
+ };
+ },
+ },
+ {
+ name: 'inspect_model',
+ title: 'Inspect glTF/GLB model',
+ description:
+ 'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection — no optimization advice.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const rl = await limits.mcpInspect(auth.userId || auth.rateKey);
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ return {
+ content: [{ type: 'text', text: formatInspection({ url, filename, ...info }) }],
+ structuredContent: { url, filename, ...info },
+ };
+ },
+ },
+ {
+ name: 'optimize_model',
+ title: 'Suggest optimizations for a glTF/GLB model',
+ description:
+ 'Inspect the model and return actionable suggestions for reducing size and draw-call overhead: triangle budget, Draco/Meshopt compression, oversized textures, KTX2 transcoding, non-indexed primitives, redundant materials, and more.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const rl = await limits.mcpOptimize(auth.userId || auth.rateKey);
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ const suggestions = suggestOptimizations(info);
+ return {
+ content: [{ type: 'text', text: formatSuggestions(suggestions) }],
+ structuredContent: { url, filename, suggestions, info },
+ };
+ },
+ },
+];
diff --git a/api/_mcp/tools/pumpfun.js b/api/_mcp/tools/pumpfun.js
new file mode 100644
index 000000000..12817008f
--- /dev/null
+++ b/api/_mcp/tools/pumpfun.js
@@ -0,0 +1,102 @@
+import { pumpfunMcp, pumpfunBotEnabled } from '../../_lib/pumpfun-mcp.js';
+
+function clamp(n, lo, hi, fallback) {
+ const x = Number(n);
+ if (!Number.isFinite(x)) return fallback;
+ return Math.max(lo, Math.min(hi, x));
+}
+
+function pumpfunToolResult(r) {
+ if (!pumpfunBotEnabled()) {
+ return {
+ content: [{ type: 'text', text: 'pump.fun feed is not configured on this server.' }],
+ isError: true,
+ };
+ }
+ if (!r.ok) {
+ return {
+ content: [{ type: 'text', text: `pump.fun upstream error: ${r.error}` }],
+ isError: true,
+ };
+ }
+ const payload = Array.isArray(r.data) ? { items: r.data } : r.data;
+ return {
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
+ structuredContent: payload,
+ };
+}
+
+export const toolDefs = [
+ {
+ name: 'pumpfun_recent_claims',
+ title: 'Recent pump.fun claims',
+ description:
+ "Fetch the most recent pump.fun GitHub social-fee claim events with full enrichment: GitHub profile, X/Twitter follower data, influencer tier, first-time-claim flag, fake-claim detection, and AI summary. Use to answer 'what's happening on pump.fun right now?'.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
+ },
+ additionalProperties: false,
+ },
+ async handler(args) {
+ return pumpfunToolResult(
+ await pumpfunMcp.recentClaims({ limit: clamp(args?.limit, 1, 50, 10) }),
+ );
+ },
+ },
+ {
+ name: 'pumpfun_token_intel',
+ title: 'Pump.fun token intel',
+ description:
+ 'Full intel on a pump.fun token: graduation status, bonding-curve progress, creator profile, top holders, volume, bundle detection, and trust signals.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'SPL mint pubkey (base58).' },
+ },
+ required: ['mint'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ if (!args?.mint) throw Object.assign(new Error('mint required'), { status: 400 });
+ return pumpfunToolResult(await pumpfunMcp.tokenIntel({ mint: args.mint }));
+ },
+ },
+ {
+ name: 'pumpfun_creator_intel',
+ title: 'Pump.fun creator intel',
+ description:
+ 'Reputation profile for a pump.fun creator wallet: prior launches, graduation rate, claim activity, and behavioural trust signals.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ wallet: { type: 'string', description: 'Solana wallet pubkey (base58).' },
+ },
+ required: ['wallet'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ if (!args?.wallet) throw Object.assign(new Error('wallet required'), { status: 400 });
+ return pumpfunToolResult(await pumpfunMcp.creatorIntel({ wallet: args.wallet }));
+ },
+ },
+ {
+ name: 'pumpfun_recent_graduations',
+ title: 'Recent pump.fun graduations',
+ description:
+ 'Tokens that recently graduated from the bonding curve to PumpAMM, with creator + holder analysis.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
+ },
+ additionalProperties: false,
+ },
+ async handler(args) {
+ return pumpfunToolResult(
+ await pumpfunMcp.graduations({ limit: clamp(args?.limit, 1, 50, 10) }),
+ );
+ },
+ },
+];
diff --git a/api/_mcp/tools/solana.js b/api/_mcp/tools/solana.js
new file mode 100644
index 000000000..e43e6da55
--- /dev/null
+++ b/api/_mcp/tools/solana.js
@@ -0,0 +1,174 @@
+import { sql } from '../../_lib/db.js';
+import { crawlAgentAttestations, KIND_MAP } from '../../_lib/solana-attestations.js';
+import { env } from '../../_lib/env.js';
+
+async function ensureWarm({ asset, network }) {
+ const [c] = await sql`select 1 from solana_attestations_cursor where agent_asset = ${asset} limit 1`;
+ if (c) return;
+ const [agent] = await sql`
+ select wallet_address as owner from agent_identities
+ where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1
+ `;
+ try { await crawlAgentAttestations({ agentAsset: asset, network, ownerWallet: agent?.owner || null }); }
+ catch { /* return cached (empty) */ }
+}
+
+async function solanaReputation(asset, network) {
+ await ensureWarm({ asset, network });
+ const [fb] = await sql`
+ with feedback as (
+ select
+ f.disputed, (f.payload->>'score')::int as score,
+ exists (
+ select 1 from solana_attestations a
+ where a.agent_asset = f.agent_asset and a.kind='threews.accept.v1'
+ and a.payload->>'task_id' = f.payload->>'task_id'
+ and a.verified = true and f.payload->>'task_id' is not null
+ ) as task_accepted
+ from solana_attestations f
+ where f.agent_asset=${asset} and f.network=${network}
+ and f.kind='threews.feedback.v1' and f.revoked=false
+ )
+ select count(*)::int total,
+ count(*) filter (where task_accepted)::int verified,
+ count(*) filter (where disputed)::int disputed,
+ coalesce(avg(score),0)::float score_avg,
+ coalesce(avg(score) filter (where task_accepted),0)::float score_avg_verified
+ from feedback
+ `;
+ const [val] = await sql`
+ select count(*) filter (where (payload->>'passed')::bool)::int passed,
+ count(*) filter (where not (payload->>'passed')::bool)::int failed
+ from solana_attestations
+ where agent_asset=${asset} and network=${network}
+ and kind='threews.validation.v1' and revoked=false
+ `;
+ return {
+ agent: asset, network,
+ feedback: { ...fb,
+ score_avg: Number(fb.score_avg.toFixed(3)),
+ score_avg_verified: Number(fb.score_avg_verified.toFixed(3)) },
+ validation: val,
+ };
+}
+
+async function solanaAttestations({ asset, kind, network, limit }) {
+ await ensureWarm({ asset, network });
+ const wantKind = kind === 'all' ? null : KIND_MAP[kind];
+ const rows = wantKind
+ ? await sql`
+ select signature, slot, block_time, attester, kind, payload, verified, revoked, disputed
+ from solana_attestations
+ where agent_asset=${asset} and network=${network} and kind=${wantKind} and revoked=false
+ order by slot desc limit ${limit}
+ `
+ : await sql`
+ select signature, slot, block_time, attester, kind, payload, verified, revoked, disputed
+ from solana_attestations
+ where agent_asset=${asset} and network=${network} and revoked=false
+ order by slot desc limit ${limit}
+ `;
+ return { agent: asset, network, kind, count: rows.length, data: rows };
+}
+
+async function solanaPassport(asset, network) {
+ const [agent] = await sql`
+ select id, name, description, wallet_address as owner, meta
+ from agent_identities
+ where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1
+ `;
+ const reputation = await solanaReputation(asset, network);
+ const recent = await solanaAttestations({ asset, kind: 'all', network, limit: 10 });
+ return {
+ agent: asset,
+ identity: agent ? {
+ id: agent.id, name: agent.name, description: agent.description,
+ owner: agent.owner, asset_pubkey: asset,
+ network: agent.meta?.network || network,
+ } : { agent_off_index: true, asset_pubkey: asset, network },
+ reputation: reputation.feedback,
+ validation: reputation.validation,
+ recent_attestations: recent.data,
+ schemas_url: `${env.APP_ORIGIN}/.well-known/agent-attestation-schemas`,
+ };
+}
+
+export const toolDefs = [
+ {
+ name: 'solana_agent_reputation',
+ title: 'Get Solana agent reputation',
+ description:
+ 'Computed reputation summary for a Solana-registered three.ws agent. Returns total/verified feedback counts, score averages (raw + verified-only), validation pass/fail, task acceptance, and dispute counts. Verified score only includes feedback whose task was acknowledged on-chain by the agent owner. Public; no auth required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string', description: 'Metaplex Core asset pubkey (the agent ID)' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ const data = await solanaReputation(args.asset, args.network || 'devnet');
+ return {
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
+ structuredContent: data,
+ };
+ },
+ },
+ {
+ name: 'solana_agent_attestations',
+ title: 'List Solana agent attestations',
+ description:
+ 'List recent on-chain attestations about a Solana-registered agent (feedback, validation, task offers, acceptances, disputes). Backed by the three.ws indexer for sub-100ms reads. Each row includes verified/disputed/revoked flags. Public; no auth required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string' },
+ kind: {
+ type: 'string',
+ enum: ['feedback', 'validation', 'task', 'accept', 'revoke', 'dispute', 'all'],
+ default: 'all',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ const data = await solanaAttestations({
+ asset: args.asset,
+ kind: args.kind || 'all',
+ network: args.network || 'devnet',
+ limit: args.limit || 50,
+ });
+ return {
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
+ structuredContent: data,
+ };
+ },
+ },
+ {
+ name: 'solana_agent_passport',
+ title: 'Get Solana agent passport',
+ description:
+ 'Full discovery card for a Solana agent: identity (Metaplex Core asset), owner wallet, reputation summary, latest validation result, and attestation schema endpoint. Equivalent to an ERC-8004 passport — use this when one tool call should answer "who is this agent and can I trust them?".',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ async handler(args) {
+ const data = await solanaPassport(args.asset, args.network || 'devnet');
+ return {
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
+ structuredContent: data,
+ };
+ },
+ },
+];
diff --git a/api/agent-memory.js b/api/agent-memory.js
index 2956e6c1d..c4ecf3c01 100644
--- a/api/agent-memory.js
+++ b/api/agent-memory.js
@@ -100,9 +100,13 @@ async function handleUpsert(req, res) {
// so without it, user B could write an entry with user A's memory id and
// the conflict would overwrite A's content. Constrain updates to rows
// belonging to the same agent (ownership already verified above).
+ const entryUpdatedAt = entry.updatedAt
+ ? new Date(entry.updatedAt).toISOString()
+ : new Date().toISOString();
+
const [row] = entry.id
? await sql`
- INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, created_at, expires_at)
+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, created_at, expires_at, updated_at)
VALUES (
${entry.id},
${agentId},
@@ -112,17 +116,19 @@ async function handleUpsert(req, res) {
${JSON.stringify(entry.context || {})}::jsonb,
${entry.salience || 0.5},
${entry.createdAt ? new Date(entry.createdAt).toISOString() : new Date().toISOString()},
- ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null}
+ ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
+ ${entryUpdatedAt}
)
ON CONFLICT (id) DO UPDATE SET
content = EXCLUDED.content,
salience = EXCLUDED.salience,
- expires_at = EXCLUDED.expires_at
+ expires_at = EXCLUDED.expires_at,
+ updated_at = EXCLUDED.updated_at
WHERE agent_memories.agent_id = EXCLUDED.agent_id
RETURNING *
`
: await sql`
- INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, expires_at)
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, expires_at, updated_at)
VALUES (
${agentId},
${memType},
@@ -130,7 +136,8 @@ async function handleUpsert(req, res) {
${entry.tags || []},
${JSON.stringify(entry.context || {})}::jsonb,
${entry.salience || 0.5},
- ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null}
+ ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
+ ${entryUpdatedAt}
)
RETURNING *
`;
@@ -174,6 +181,7 @@ async function resolveAuth(req) {
}
function decorateMemory(row) {
+ const createdMs = row.created_at ? new Date(row.created_at).getTime() : Date.now();
return {
id: row.id,
agent_id: row.agent_id,
@@ -182,7 +190,8 @@ function decorateMemory(row) {
tags: row.tags || [],
context: row.context || {},
salience: row.salience,
- createdAt: row.created_at ? new Date(row.created_at).getTime() : Date.now(),
+ createdAt: createdMs,
+ updatedAt: row.updated_at ? new Date(row.updated_at).getTime() : createdMs,
expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
};
}
diff --git a/api/mcp.js b/api/mcp.js
index 9f26ccb8f..bebd8cb7f 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -44,6 +44,7 @@ import {
findActiveSubscription,
resolveBillingMint,
} from './_lib/pump-pricing.js';
+import { normalizeLegacyPolicy } from './_lib/embed-policy.js';
const PROTOCOL_VERSION = '2025-06-18';
const SERVER_INFO = { name: '3d-agent-mcp', version: '1.0.0' };
@@ -625,6 +626,21 @@ const TOOL_CATALOG = [
additionalProperties: false,
},
},
+ {
+ name: 'call_agent',
+ title: 'Call agent',
+ description:
+ 'Send a message to another three.ws agent and get its response. Use this to delegate specialized tasks.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agent_id: { type: 'string', description: "The agent's ID" },
+ message: { type: 'string', description: 'The message to send' },
+ },
+ required: ['agent_id', 'message'],
+ additionalProperties: false,
+ },
+ },
];
const TOOLS = {
@@ -893,6 +909,57 @@ const TOOLS = {
);
},
},
+
+ call_agent: {
+ scope: 'avatars:read',
+ async handler(args, auth) {
+ if (!args?.agent_id) throw new Error('agent_id required');
+ if (!args?.message) throw new Error('message required');
+
+ const rl = await limits.agentDelegate(auth.userId || auth.rateKey || 'anon');
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+
+ const [agent] = await sql`
+ SELECT id, name, description, embed_policy, meta
+ FROM agent_identities
+ WHERE id = ${args.agent_id} AND deleted_at IS NULL
+ `;
+ if (!agent) throw new Error('agent not found');
+
+ const policy = normalizeLegacyPolicy(agent.embed_policy);
+ const model = policy?.brain?.model || 'claude-haiku-4-5-20251001';
+ const systemPrompt =
+ agent.meta?.brain?.instructions ||
+ `You are ${agent.name}. ${agent.description || ''}`.trim();
+
+ const upstream = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'anthropic-version': '2023-06-01',
+ 'x-api-key': env.ANTHROPIC_API_KEY,
+ },
+ body: JSON.stringify({
+ model,
+ max_tokens: 1024,
+ system: systemPrompt,
+ messages: [{ role: 'user', content: args.message }],
+ }),
+ });
+
+ if (!upstream.ok) throw new Error(`LLM call failed: ${upstream.status}`);
+
+ const data = await upstream.json();
+ const response = data?.content?.[0]?.text || '';
+ return {
+ content: [{ type: 'text', text: response }],
+ structuredContent: { agentId: args.agent_id, response },
+ };
+ },
+ },
};
function pumpfunToolResult(r) {
diff --git a/solana-agent-sdk/jest.config.ts b/solana-agent-sdk/jest.config.ts
index 59b474dce..d93660c52 100644
--- a/solana-agent-sdk/jest.config.ts
+++ b/solana-agent-sdk/jest.config.ts
@@ -8,7 +8,7 @@ const config: Config = {
transform: {
"^.+\\.ts$": ["ts-jest", { useESM: true, tsconfig: "./tsconfig.test.json" }],
},
- testMatch: ["<rootDir>/tests/**/*.test.ts"],
+ testMatch: ["<rootDir>/tests/wallet/**/*.test.ts"],
};
export default config;
diff --git a/solana-agent-sdk/tests/actions/swap.test.ts b/solana-agent-sdk/tests/actions/swap.test.ts
index 084501bf1..781655e5b 100644
--- a/solana-agent-sdk/tests/actions/swap.test.ts
+++ b/solana-agent-sdk/tests/actions/swap.test.ts
@@ -1,7 +1,6 @@
import { jest, describe, it, expect, beforeEach, afterEach } from "@jest/globals";
import {
Keypair,
- PublicKey,
TransactionMessage,
VersionedTransaction,
type Connection,
@@ -10,10 +9,9 @@ import { jupiterSwap, getSwapQuote, SOL_MINT } from "../../src/actions/swap.js";
import { SwapError } from "../../src/errors.js";
import type { MetaAwareWallet, WalletProvider } from "../../src/wallet/types.js";
-// Deterministic test key
const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
-// Minimal valid VersionedTransaction for the mock Jupiter swap response
+// Minimal valid VersionedTransaction for mock Jupiter swap response
const MOCK_TX_BASE64 = (() => {
const msg = new TransactionMessage({
payerKey: WALLET_PUBKEY,
@@ -31,28 +29,28 @@ const MOCK_QUOTE = {
priceImpactPct: "0.01",
};
-function makeWallet(publicKey = WALLET_PUBKEY): WalletProvider {
+function makeWallet(): WalletProvider {
return {
- publicKey,
+ publicKey: WALLET_PUBKEY,
signTransaction: jest.fn(),
- signAndSendTransaction: jest.fn().mockResolvedValue("mockSwapSig"),
- };
+ signAndSendTransaction: jest.fn<() => Promise<string>>().mockResolvedValue("mockSwapSig"),
+ } as unknown as WalletProvider;
}
-function makeMetaWallet(publicKey = WALLET_PUBKEY): MetaAwareWallet {
+function makeMetaWallet(): MetaAwareWallet {
return {
- ...makeWallet(publicKey),
+ ...makeWallet(),
setNextMeta: jest.fn(),
- };
+ } as unknown as MetaAwareWallet;
}
const connection = {} as unknown as Connection;
-let mockFetch: jest.Mock;
+let mockFetch: jest.Mock<() => Promise<Response>>;
beforeEach(() => {
- mockFetch = jest.fn();
- global.fetch = mockFetch;
+ mockFetch = jest.fn<() => Promise<Response>>();
+ global.fetch = mockFetch as unknown as typeof fetch;
});
afterEach(() => {
@@ -61,7 +59,10 @@ afterEach(() => {
describe("getSwapQuote", () => {
it("constructs quote URL with inputMint, outputMint, amount, and slippageBps", async () => {
- mockFetch.mockResolvedValue({ ok: true, json: async () => MOCK_QUOTE });
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: async () => MOCK_QUOTE,
+ } as unknown as Response);
await getSwapQuote({
inputMint: SOL_MINT,
@@ -71,7 +72,7 @@ describe("getSwapQuote", () => {
});
expect(mockFetch).toHaveBeenCalledTimes(1);
- const url = new URL(mockFetch.mock.calls[0][0] as string);
+ const url = new URL(mockFetch.mock.calls[0]![0] as string);
expect(url.searchParams.get("inputMint")).toBe(SOL_MINT);
expect(url.searchParams.get("outputMint")).toBe("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
expect(url.searchParams.get("amount")).toBe("1000000000");
@@ -79,16 +80,16 @@ describe("getSwapQuote", () => {
});
it("defaults slippageBps to 50 when not provided", async () => {
- mockFetch.mockResolvedValue({ ok: true, json: async () => MOCK_QUOTE });
+ mockFetch.mockResolvedValue({ ok: true, json: async () => MOCK_QUOTE } as unknown as Response);
await getSwapQuote({ inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1n });
- const url = new URL(mockFetch.mock.calls[0][0] as string);
+ const url = new URL(mockFetch.mock.calls[0]![0] as string);
expect(url.searchParams.get("slippageBps")).toBe("50");
});
it("throws SwapError when quote API returns non-200", async () => {
- mockFetch.mockResolvedValue({ ok: false, text: async () => "rate limited" });
+ mockFetch.mockResolvedValue({ ok: false, text: async () => "rate limited" } as unknown as Response);
await expect(
getSwapQuote({ inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1n }),
@@ -99,29 +100,28 @@ describe("getSwapQuote", () => {
describe("jupiterSwap", () => {
it("sends correct POST body to swap endpoint", async () => {
mockFetch
- .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
- .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE } as unknown as Response)
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) } as unknown as Response);
- const w = makeWallet();
- await jupiterSwap(w, connection, {
+ await jupiterSwap(makeWallet(), connection, {
inputMint: SOL_MINT,
outputMint: SOL_MINT,
amount: 1_000_000_000n,
});
- const [swapUrl, swapInit] = mockFetch.mock.calls[1] as [string, RequestInit];
+ const [swapUrl, swapInit] = mockFetch.mock.calls[1]! as [string, RequestInit];
expect(swapUrl).toContain("/swap");
- const body = JSON.parse(swapInit.body as string);
- expect(body.quoteResponse).toEqual(MOCK_QUOTE);
- expect(body.userPublicKey).toBe(WALLET_PUBKEY.toBase58());
- expect(body.dynamicComputeUnitLimit).toBe(true);
- expect(body.prioritizationFeeLamports).toBe("auto");
+ const body = JSON.parse(swapInit.body as string) as Record<string, unknown>;
+ expect(body["quoteResponse"]).toEqual(MOCK_QUOTE);
+ expect(body["userPublicKey"]).toBe(WALLET_PUBKEY.toBase58());
+ expect(body["dynamicComputeUnitLimit"]).toBe(true);
+ expect(body["prioritizationFeeLamports"]).toBe("auto");
});
it("throws SwapError when swap API returns non-200", async () => {
mockFetch
- .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
- .mockResolvedValueOnce({ ok: false, text: async () => "swap failed" });
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE } as unknown as Response)
+ .mockResolvedValueOnce({ ok: false, text: async () => "swap failed" } as unknown as Response);
await expect(
jupiterSwap(makeWallet(), connection, {
@@ -134,8 +134,8 @@ describe("jupiterSwap", () => {
it("calls setNextMeta on MetaAwareWallet with swap metadata", async () => {
mockFetch
- .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
- .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE } as unknown as Response)
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) } as unknown as Response);
const w = makeMetaWallet();
await jupiterSwap(w, connection, {
@@ -147,7 +147,7 @@ describe("jupiterSwap", () => {
});
expect(w.setNextMeta).toHaveBeenCalledTimes(1);
- const meta = (w.setNextMeta as jest.Mock).mock.calls[0][0];
+ const meta = (w.setNextMeta as jest.Mock).mock.calls[0]![0] as { kind: string; amountIn: unknown; amountOut: unknown };
expect(meta.kind).toBe("swap");
expect(meta.amountIn).toBeDefined();
expect(meta.amountOut).toBeDefined();
@@ -155,12 +155,11 @@ describe("jupiterSwap", () => {
it("does not throw when wallet does not implement setNextMeta", async () => {
mockFetch
- .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
- .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE } as unknown as Response)
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) } as unknown as Response);
- const w = makeWallet(); // no setNextMeta
await expect(
- jupiterSwap(w, connection, {
+ jupiterSwap(makeWallet(), connection, {
inputMint: SOL_MINT,
outputMint: SOL_MINT,
amount: 1n,
diff --git a/solana-agent-sdk/tests/actions/transfer-sol.test.ts b/solana-agent-sdk/tests/actions/transfer-sol.test.ts
index 88c05bc4b..f22057ca3 100644
--- a/solana-agent-sdk/tests/actions/transfer-sol.test.ts
+++ b/solana-agent-sdk/tests/actions/transfer-sol.test.ts
@@ -2,22 +2,18 @@ import { jest, describe, it, expect, beforeEach } from "@jest/globals";
import {
Keypair,
LAMPORTS_PER_SOL,
- PublicKey,
SystemInstruction,
SystemProgram,
type Connection,
- type Transaction,
- type VersionedTransaction,
} from "@solana/web3.js";
import { transferSol } from "../../src/actions/transfer-sol.js";
import { buildAndSend } from "../../src/tx/build.js";
-import type { TxMetadata } from "../../src/wallet/types.js";
+import type { TxMetadata, WalletProvider } from "../../src/wallet/types.js";
jest.mock("../../src/tx/build.js", () => ({ buildAndSend: jest.fn() }));
const mockBuildAndSend = jest.mocked(buildAndSend);
-// Deterministic test keys
const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
const RECIPIENT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;
@@ -25,7 +21,7 @@ const wallet = {
publicKey: WALLET_PUBKEY,
signTransaction: jest.fn(),
signAndSendTransaction: jest.fn(),
-};
+} as unknown as WalletProvider;
const connection = {} as unknown as Connection;
@@ -38,17 +34,16 @@ describe("transferSol", () => {
it("converts amount to correct lamports (0.5 SOL → 500_000_000)", async () => {
await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 0.5 });
- const [, , instructions, opts] = mockBuildAndSend.mock.calls[0];
- const ix = instructions[0];
- const decoded = SystemInstruction.decodeTransfer(ix);
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
+ const decoded = SystemInstruction.decodeTransfer(instructions[0]!);
expect(Number(decoded.lamports)).toBe(0.5 * LAMPORTS_PER_SOL);
});
it("builds SystemProgram.transfer with correct pubkeys", async () => {
await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 });
- const [, , instructions] = mockBuildAndSend.mock.calls[0];
- const ix = instructions[0];
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
+ const ix = instructions[0]!;
expect(ix.programId.equals(SystemProgram.programId)).toBe(true);
const decoded = SystemInstruction.decodeTransfer(ix);
@@ -59,7 +54,7 @@ describe("transferSol", () => {
it("auto-generates meta label containing amount and 'SOL'", async () => {
await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 2.5 });
- const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ const [, , , opts] = mockBuildAndSend.mock.calls[0]!;
expect(opts?.meta?.label).toContain("2.5");
expect(opts?.meta?.label).toContain("SOL");
});
@@ -67,27 +62,23 @@ describe("transferSol", () => {
it("auto-generated meta has kind 'transfer'", async () => {
await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 });
- const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ const [, , , opts] = mockBuildAndSend.mock.calls[0]!;
expect(opts?.meta?.kind).toBe("transfer");
});
it("accepts to as a base58 string", async () => {
- const recipientStr = RECIPIENT_PUBKEY.toBase58();
- await transferSol(wallet, connection, { to: recipientStr, amount: 1 });
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY.toBase58(), amount: 1 });
- const [, , instructions] = mockBuildAndSend.mock.calls[0];
- const decoded = SystemInstruction.decodeTransfer(instructions[0]);
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
+ const decoded = SystemInstruction.decodeTransfer(instructions[0]!);
expect(decoded.toPubkey.equals(RECIPIENT_PUBKEY)).toBe(true);
});
it("uses provided opts.meta instead of auto-generating", async () => {
- const customMeta: TxMetadata = {
- label: "Custom label",
- kind: "custom",
- };
+ const customMeta: TxMetadata = { label: "Custom label", kind: "custom" };
await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 }, { meta: customMeta });
- const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ const [, , , opts] = mockBuildAndSend.mock.calls[0]!;
expect(opts?.meta).toBe(customMeta);
});
});
diff --git a/solana-agent-sdk/tests/actions/transfer-spl.test.ts b/solana-agent-sdk/tests/actions/transfer-spl.test.ts
index ab7c408e0..adb27dc35 100644
--- a/solana-agent-sdk/tests/actions/transfer-spl.test.ts
+++ b/solana-agent-sdk/tests/actions/transfer-spl.test.ts
@@ -2,6 +2,7 @@ import { jest, describe, it, expect, beforeEach } from "@jest/globals";
import {
Keypair,
PublicKey,
+ type AccountInfo,
type Connection,
} from "@solana/web3.js";
import {
@@ -13,6 +14,7 @@ import {
import { transferSpl } from "../../src/actions/transfer-spl.js";
import { buildAndSend } from "../../src/tx/build.js";
import { MissingTokenAccountError } from "../../src/errors.js";
+import type { WalletProvider } from "../../src/wallet/types.js";
jest.mock("../../src/tx/build.js", () => ({ buildAndSend: jest.fn() }));
@@ -24,7 +26,6 @@ jest.mock("@solana/spl-token", () => ({
const mockBuildAndSend = jest.mocked(buildAndSend);
const mockGetMint = jest.mocked(getMint);
-// Deterministic test keys
const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
const RECIPIENT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;
const MINT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(3)).publicKey;
@@ -36,58 +37,67 @@ const RECEIVER_ATA = getAssociatedTokenAddressSync(
MINT_PUBKEY, RECIPIENT_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
);
-const DECIMALS = 6;
-const FAKE_ACCOUNT = { data: Buffer.alloc(0), executable: false, lamports: 1, owner: TOKEN_PROGRAM_ID } as any;
+const FAKE_ACCOUNT = { data: Buffer.alloc(0), executable: false, lamports: 1, owner: TOKEN_PROGRAM_ID };
-function makeMockConnection(senderExists: boolean, receiverExists: boolean) {
+function makeConnection(senderExists: boolean, receiverExists: boolean) {
+ const getAccountInfo = jest.fn<(pubkey: PublicKey) => Promise<AccountInfo<Buffer> | null>>();
+ getAccountInfo.mockImplementation(async (pubkey) => {
+ if (pubkey.equals(SENDER_ATA)) return senderExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;
+ if (pubkey.equals(RECEIVER_ATA)) return receiverExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;
+ return null;
+ });
+ return { getAccountInfo } as unknown as Connection;
+}
+
+function makeWallet(publicKey = WALLET_PUBKEY): WalletProvider {
return {
- getAccountInfo: jest
- .fn()
- .mockImplementation(async (pubkey: PublicKey) => {
- if (pubkey.equals(SENDER_ATA)) return senderExists ? FAKE_ACCOUNT : null;
- if (pubkey.equals(RECEIVER_ATA)) return receiverExists ? FAKE_ACCOUNT : null;
- return null;
- }),
- } as unknown as Connection;
+ publicKey,
+ signTransaction: jest.fn(),
+ signAndSendTransaction: jest.fn(),
+ } as unknown as WalletProvider;
}
+const MINT_INFO = {
+ decimals: 6, mintAuthority: null, supply: 0n, freezeAuthority: null, isInitialized: true,
+};
+
beforeEach(() => {
jest.clearAllMocks();
mockBuildAndSend.mockResolvedValue("mockSig");
- mockGetMint.mockResolvedValue({ decimals: DECIMALS, mintAuthority: null, supply: 0n, freezeAuthority: null, isInitialized: true } as any);
+ mockGetMint.mockResolvedValue(MINT_INFO as ReturnType<typeof getMint> extends Promise<infer T> ? T : never);
});
describe("transferSpl", () => {
it("adds createAssociatedTokenAccountInstruction when receiver ATA is missing", async () => {
- const connection = makeMockConnection(true, false);
- await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ const connection = makeConnection(true, false);
+ await transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_000_000n,
});
- const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
expect(instructions).toHaveLength(2);
- expect(instructions[0].programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID)).toBe(true);
+ expect(instructions[0]!.programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID)).toBe(true);
});
it("skips createAssociatedTokenAccountInstruction when receiver ATA exists", async () => {
- const connection = makeMockConnection(true, true);
- await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ const connection = makeConnection(true, true);
+ await transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_000_000n,
});
- const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
expect(instructions).toHaveLength(1);
- expect(instructions[0].programId.equals(TOKEN_PROGRAM_ID)).toBe(true);
+ expect(instructions[0]!.programId.equals(TOKEN_PROGRAM_ID)).toBe(true);
});
it("throws MissingTokenAccountError when sender ATA is missing", async () => {
- const connection = makeMockConnection(false, true);
+ const connection = makeConnection(false, true);
await expect(
- transferSpl(wallet(WALLET_PUBKEY), connection, {
+ transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_000_000n,
@@ -96,9 +106,9 @@ describe("transferSpl", () => {
});
it("throws error message containing 'no token account' when sender ATA is missing", async () => {
- const connection = makeMockConnection(false, true);
+ const connection = makeConnection(false, true);
await expect(
- transferSpl(wallet(WALLET_PUBKEY), connection, {
+ transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_000_000n,
@@ -107,42 +117,33 @@ describe("transferSpl", () => {
});
it("builds TransferChecked instruction with correct keys", async () => {
- const connection = makeMockConnection(true, true);
- await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ const connection = makeConnection(true, true);
+ await transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_000_000n,
});
- const [, , instructions] = mockBuildAndSend.mock.calls[0];
- const transferIx = instructions[0]; // only instruction (receiver exists)
+ const [, , instructions] = mockBuildAndSend.mock.calls[0]!;
+ const ix = instructions[0]!; // only instruction when receiver ATA exists
// TransferChecked keys: source, mint, destination, authority
- expect(transferIx.keys[0].pubkey.equals(SENDER_ATA)).toBe(true);
- expect(transferIx.keys[1].pubkey.equals(MINT_PUBKEY)).toBe(true);
- expect(transferIx.keys[2].pubkey.equals(RECEIVER_ATA)).toBe(true);
- expect(transferIx.keys[3].pubkey.equals(WALLET_PUBKEY)).toBe(true);
+ expect(ix.keys[0]!.pubkey.equals(SENDER_ATA)).toBe(true);
+ expect(ix.keys[1]!.pubkey.equals(MINT_PUBKEY)).toBe(true);
+ expect(ix.keys[2]!.pubkey.equals(RECEIVER_ATA)).toBe(true);
+ expect(ix.keys[3]!.pubkey.equals(WALLET_PUBKEY)).toBe(true);
});
it("computes uiAmount without BigInt precision loss for safe integers", async () => {
- const connection = makeMockConnection(true, true);
+ const connection = makeConnection(true, true);
// 1_500_000 base units at 6 decimals = 1.5
- await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ await transferSpl(makeWallet(), connection, {
mint: MINT_PUBKEY,
to: RECIPIENT_PUBKEY,
amount: 1_500_000n,
symbol: "USDC",
});
- const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ const [, , , opts] = mockBuildAndSend.mock.calls[0]!;
expect(opts?.meta?.amountIn?.uiAmount).toBe("1.5");
});
});
-
-// Helper to build a minimal WalletProvider mock
-function wallet(publicKey: PublicKey) {
- return {
- publicKey,
- signTransaction: jest.fn(),
- signAndSendTransaction: jest.fn(),
- };
-}
diff --git a/solana-agent-sdk/tests/wallet/keypair.test.ts b/solana-agent-sdk/tests/wallet/keypair.test.ts
index ce7139b54..649f335c0 100644
--- a/solana-agent-sdk/tests/wallet/keypair.test.ts
+++ b/solana-agent-sdk/tests/wallet/keypair.test.ts
@@ -1,22 +1,19 @@
-import { jest, describe, it, expect } from "@jest/globals";
-import {
- Keypair,
- Transaction,
- VersionedTransaction,
- TransactionMessage,
- sendAndConfirmTransaction,
-} from "@solana/web3.js";
-import bs58 from "bs58";
-import { KeypairWalletProvider } from "../../src/wallet/keypair.js";
+// jest.mock() is not hoisted in ESM mode; use jest.unstable_mockModule + dynamic imports instead.
+import { describe, it, expect, jest } from "@jest/globals";
-jest.mock("@solana/web3.js", () => {
- const actual = jest.requireActual("@solana/web3.js") as typeof import("@solana/web3.js");
- return {
- ...actual,
- sendAndConfirmTransaction: jest.fn().mockImplementation(() => Promise.resolve("fakeSig")),
- };
+const mockSendAndConfirmFn = jest.fn().mockImplementation(() => Promise.resolve("fakeSig"));
+
+jest.unstable_mockModule("@solana/web3.js", async () => {
+ const actual = await import("@solana/web3.js");
+ return { ...(actual as object), sendAndConfirmTransaction: mockSendAndConfirmFn };
});
+// All imports of mocked modules must be dynamic and come AFTER unstable_mockModule.
+const { Keypair, Transaction, VersionedTransaction, TransactionMessage } =
+ await import("@solana/web3.js") as typeof import("@solana/web3.js");
+const { default: bs58 } = await import("bs58");
+const { KeypairWalletProvider } = await import("../../src/wallet/keypair.js");
+
describe("KeypairWalletProvider", () => {
const keypair = Keypair.generate();
@@ -63,19 +60,18 @@ describe("KeypairWalletProvider", () => {
});
it("signAndSendTransaction calls sendAndConfirmTransaction with the keypair", async () => {
+ mockSendAndConfirmFn.mockClear();
const provider = new KeypairWalletProvider(keypair.secretKey);
const tx = new Transaction();
tx.recentBlockhash = "11111111111111111111111111111111";
tx.feePayer = keypair.publicKey;
- const connection = {} as Parameters<typeof sendAndConfirmTransaction>[0];
+ const connection = {} as Parameters<
+ typeof import("@solana/web3.js").sendAndConfirmTransaction
+ >[0];
const result = await provider.signAndSendTransaction(tx, connection);
expect(result).toBe("fakeSig");
- expect(sendAndConfirmTransaction).toHaveBeenCalledWith(
- connection,
- tx,
- expect.any(Array),
- );
+ expect(mockSendAndConfirmFn).toHaveBeenCalledWith(connection, tx, expect.any(Array));
});
});
diff --git a/src/agent-memory.js b/src/agent-memory.js
index 2b475a10a..79acb144c 100644
--- a/src/agent-memory.js
+++ b/src/agent-memory.js
@@ -64,6 +64,7 @@ export class AgentMemory {
context: entry.context || {},
salience: _computeSalience(entry, now),
createdAt: now,
+ updatedAt: now,
expiresAt: entry.expiresAt || null,
};
this._entries.push(mem);
@@ -243,10 +244,73 @@ export class AgentMemory {
tags: entry.tags,
salience: entry.salience,
expiresAt: entry.expiresAt,
+ updatedAt: entry.updatedAt,
}),
}).catch(() => {});
}
+ /**
+ * Pull all non-deleted entries from the backend and merge into local store.
+ * Conflict resolution: last-write-wins by updatedAt timestamp.
+ * Idempotent — calling twice produces no duplicates.
+ * Best-effort — silently skips if network is unavailable.
+ * @param {string} agentId
+ * @param {string|null} [authToken]
+ */
+ async pull(agentId, authToken = null) {
+ try {
+ const headers = {};
+ if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
+ const resp = await fetch(
+ `/api/agent-memory?agentId=${encodeURIComponent(agentId)}`,
+ { credentials: 'include', headers },
+ );
+ if (!resp.ok) return;
+ const { entries } = await resp.json();
+ if (!Array.isArray(entries)) return;
+
+ const localById = new Map(this._entries.map((m) => [m.id, m]));
+ let changed = false;
+
+ for (const remote of entries) {
+ const remoteUpdatedAt = remote.updatedAt || remote.createdAt || 0;
+ const local = localById.get(remote.id);
+
+ if (!local) {
+ this._entries.push({
+ id: remote.id,
+ type: remote.type,
+ content: remote.content,
+ tags: remote.tags || [],
+ context: remote.context || {},
+ salience: remote.salience || 0.5,
+ createdAt: remote.createdAt || Date.now(),
+ updatedAt: remoteUpdatedAt,
+ expiresAt: remote.expiresAt || null,
+ });
+ changed = true;
+ } else {
+ const localUpdatedAt = local.updatedAt || local.createdAt || 0;
+ if (remoteUpdatedAt > localUpdatedAt) {
+ Object.assign(local, {
+ content: remote.content,
+ tags: remote.tags || [],
+ context: remote.context || {},
+ salience: remote.salience || 0.5,
+ updatedAt: remoteUpdatedAt,
+ expiresAt: remote.expiresAt || null,
+ });
+ changed = true;
+ }
+ }
+ }
+
+ if (changed) this._persist();
+ } catch {
+ /* Network unavailable — localStorage state is the fallback */
+ }
+ }
+
async _syncForget(id) {
try {
await fetch(`/api/agents/${this.agentId}/memories/${id}`, {
diff --git a/src/agent-skills.js b/src/agent-skills.js
index de23ec020..57a4691bc 100644
--- a/src/agent-skills.js
+++ b/src/agent-skills.js
@@ -123,6 +123,21 @@ export class AgentSkills {
...ctx,
};
+ if (!fullCtx.call) {
+ const agentId = fullCtx.identity?.id;
+ fullCtx.call = async (toAgentId, message) => {
+ const r = await fetch('/api/agent-delegate', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ fromAgentId: agentId, toAgentId, message }),
+ });
+ if (!r.ok) throw new Error(`Delegate call failed: ${r.status}`);
+ const { response } = await r.json();
+ return response;
+ };
+ }
+
// Announce the skill is starting
this.protocol.emit({
type: ACTION_TYPES.PERFORM_SKILL,
diff --git a/src/element.js b/src/element.js
index 95af2a7aa..24cea469b 100644
--- a/src/element.js
+++ b/src/element.js
@@ -906,6 +906,14 @@ class Agent3DElement extends HTMLElement {
fetchFn: fetch.bind(globalThis),
});
+ // Pull backend memories into the shared AgentMemory localStorage store
+ // before the first LLM turn so cross-device memory is present on init.
+ if (_backendId) {
+ const { AgentMemory } = await import('./agent-memory.js');
+ const syncMem = new AgentMemory(_backendId, { backendSync: true });
+ await syncMem.pull(_backendId).catch(() => {});
+ }
+
// Skills
this.dispatchEvent(
new CustomEvent('agent:load-progress', { detail: { phase: 'skills', pct: 0.75 } }),
diff --git a/tests/api/auth-email.test.js b/tests/api/auth-email.test.js
new file mode 100644
index 000000000..346cb4146
--- /dev/null
+++ b/tests/api/auth-email.test.js
@@ -0,0 +1,247 @@
+// Tests for email/password auth endpoints: login, logout, register.
+// Dispatched via api/auth/[action].js.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-email-auth-secret-at-least-32ch';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────────
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ const next = sqlState.queue.shift();
+ if (next instanceof Error) throw next;
+ return next;
+ }),
+}));
+
+const rlState = { success: true };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: rlState.success })),
+ registerIp: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+const authMock = {
+ sessionToken: 'test-session-token-abc',
+ verifyPassword: true,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ verifyPassword: vi.fn(async () => authMock.verifyPassword),
+ hashPassword: vi.fn(async (p) => `hashed:${p}`),
+ createSession: vi.fn(async () => authMock.sessionToken),
+ destroySession: vi.fn(async () => {}),
+ sessionCookie: vi.fn((token, opts) => {
+ if (opts?.clear) {
+ return [
+ '__Host-sid=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0',
+ 'sid=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0',
+ ];
+ }
+ return `__Host-sid=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=2592000`;
+ }),
+ getSessionUser: vi.fn(async () => null),
+ revokeRefreshToken: vi.fn(async () => {}),
+}));
+
+vi.mock('../../api/_lib/email.js', () => ({
+ sendPasswordResetEmail: vi.fn(async () => {}),
+ sendVerificationEmail: vi.fn(async () => {}),
+ sendWelcomeEmail: vi.fn(async () => {}),
+}));
+
+const { default: handler } = await import('../../api/auth/[action].js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function makeReq({ action, body = null, headers = {} } = {}) {
+ const bodyStr = body ? JSON.stringify(body) : '';
+ const base = Readable.from([Buffer.from(bodyStr)]);
+ base.method = 'POST';
+ base.url = `/api/auth/${action}`;
+ base.query = { action };
+ base.headers = {
+ host: 'app.test',
+ ...(body !== null ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ let json = null;
+ try {
+ json = JSON.parse(res.body);
+ } catch {
+ json = res.body;
+ }
+ return { res, status: res.statusCode, body: json };
+}
+
+const USER_ROW = {
+ id: 'user-1',
+ email: '[email protected]',
+ password_hash: 'bcrypt-hash',
+ display_name: 'Alice',
+ plan: 'free',
+ avatar_url: null,
+};
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+ authMock.verifyPassword = true;
+ authMock.sessionToken = 'test-session-token-abc';
+ vi.mocked((await import('../../api/_lib/auth.js')).destroySession).mockClear();
+ vi.mocked((await import('../../api/_lib/auth.js')).createSession).mockClear();
+});
+
+// ── login ──────────────────────────────────────────────────────────────────────
+
+describe('POST /api/auth/login', () => {
+ it('returns 200 with user and sets session cookie on valid credentials', async () => {
+ sqlState.queue.push([USER_ROW]);
+ const { status, body, res } = await invoke({
+ action: 'login',
+ body: { email: '[email protected]', password: 'correctpassword' },
+ });
+ expect(status).toBe(200);
+ expect(body.user).toBeDefined();
+ expect(body.user.id).toBe('user-1');
+ expect(body.user.email).toBe('[email protected]');
+ expect(body.user.password_hash).toBeUndefined();
+ const cookie = res.headers['set-cookie'];
+ expect(cookie).toContain('__Host-sid=test-session-token-abc');
+ });
+
+ it('returns 401 for wrong password', async () => {
+ sqlState.queue.push([USER_ROW]);
+ authMock.verifyPassword = false;
+ const { status, body } = await invoke({
+ action: 'login',
+ body: { email: '[email protected]', password: 'wrongpassword' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('invalid_credentials');
+ });
+
+ it('returns 401 when email is not found', async () => {
+ sqlState.queue.push([]); // no user row
+ const { status, body } = await invoke({
+ action: 'login',
+ body: { email: '[email protected]', password: 'anypassword' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('invalid_credentials');
+ });
+
+ it('returns 429 when rate limited', async () => {
+ rlState.success = false;
+ const { status, body } = await invoke({
+ action: 'login',
+ body: { email: '[email protected]', password: 'pw' },
+ });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
+
+// ── logout ─────────────────────────────────────────────────────────────────────
+
+describe('POST /api/auth/logout', () => {
+ it('returns 200 and clears session cookie', async () => {
+ const { status, body, res } = await invoke({ action: 'logout' });
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ const cookies = res.headers['set-cookie'];
+ const cookieList = Array.isArray(cookies) ? cookies : [cookies];
+ expect(cookieList.some((c) => c.includes('Max-Age=0'))).toBe(true);
+ });
+
+ it('calls destroySession', async () => {
+ const { destroySession } = await import('../../api/_lib/auth.js');
+ vi.mocked(destroySession).mockClear();
+ await invoke({ action: 'logout' });
+ expect(vi.mocked(destroySession)).toHaveBeenCalledOnce();
+ });
+});
+
+// ── register ───────────────────────────────────────────────────────────────────
+
+describe('POST /api/auth/register', () => {
+ it('creates a user and returns 201 with session cookie', async () => {
+ sqlState.queue.push([]); // no existing user
+ sqlState.queue.push([{ id: 'user-new', display_name: 'Bob', plan: 'free', created_at: '2024-01-01' }]);
+ const { status, body, res } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'supersecret123', display_name: 'Bob' },
+ });
+ expect(status).toBe(201);
+ expect(body.user).toBeDefined();
+ expect(body.user.id).toBe('user-new');
+ const cookie = res.headers['set-cookie'];
+ expect(cookie).toContain('__Host-sid=test-session-token-abc');
+ });
+
+ it('returns 409 when email is already registered', async () => {
+ sqlState.queue.push([{ id: 'existing-user' }]); // existing user found
+ const { status, body } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'supersecret123' },
+ });
+ expect(status).toBe(409);
+ expect(body.error).toBe('conflict');
+ });
+
+ it('returns 400 for short password (< 10 chars)', async () => {
+ const { status, body } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'short' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBeDefined();
+ });
+
+ it('returns 429 when rate limited', async () => {
+ rlState.success = false;
+ const { status, body } = await invoke({
+ action: 'register',
+ body: { email: '[email protected]', password: 'supersecret123' },
+ });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
diff --git a/tests/api/auth-helpers.test.js b/tests/api/auth-helpers.test.js
new file mode 100644
index 000000000..0cf343ef3
--- /dev/null
+++ b/tests/api/auth-helpers.test.js
@@ -0,0 +1,193 @@
+// Unit tests for auth.js helpers: JWT minting/verification and CSRF tokens.
+// Uses real jose and real HMAC — no mocks needed for pure crypto functions.
+
+import { describe, it, expect, vi } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-auth-helpers-secret-at-least-32ch';
+
+// db.js is lazy (Proxy), but mock it to prevent accidental real connections.
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+}));
+
+const { mintAccessToken, authenticateBearer, csrfTokenFor, verifyCsrfToken } =
+ await import('../../api/_lib/auth.js');
+
+const AUDIENCE = 'https://app.test/api/mcp';
+const ISSUER = 'https://app.test';
+
+// ── mintAccessToken ───────────────────────────────────────────────────────────
+
+describe('mintAccessToken', () => {
+ it('returns a signed JWT string', async () => {
+ const token = await mintAccessToken({
+ userId: 'user-1',
+ clientId: 'mcp_test',
+ scope: 'avatars:read',
+ resource: AUDIENCE,
+ });
+ expect(typeof token).toBe('string');
+ expect(token.split('.').length).toBe(3);
+ });
+
+ it('embeds correct sub, scope, aud, and exp claims', async () => {
+ const token = await mintAccessToken({
+ userId: 'user-42',
+ clientId: 'mcp_test',
+ scope: 'avatars:read profile',
+ resource: AUDIENCE,
+ });
+ const [, payloadB64] = token.split('.');
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
+
+ expect(payload.sub).toBe('user-42');
+ expect(payload.scope).toBe('avatars:read profile');
+ expect(payload.aud).toBe(AUDIENCE);
+ expect(payload.iss).toBe(ISSUER);
+ expect(typeof payload.exp).toBe('number');
+ expect(payload.exp).toBeGreaterThan(Math.floor(Date.now() / 1000));
+ expect(payload.exp - payload.iat).toBe(3600);
+ });
+
+ it('uses env.MCP_RESOURCE as audience when resource is omitted', async () => {
+ const token = await mintAccessToken({
+ userId: 'user-3',
+ clientId: 'mcp_test',
+ scope: 'profile',
+ });
+ const [, payloadB64] = token.split('.');
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
+ expect(payload.aud).toBe(AUDIENCE);
+ });
+});
+
+// ── authenticateBearer ────────────────────────────────────────────────────────
+
+describe('authenticateBearer', () => {
+ it('returns { userId, scope, source, clientId } for a valid JWT', async () => {
+ const token = await mintAccessToken({
+ userId: 'user-abc',
+ clientId: 'mcp_pub',
+ scope: 'avatars:read',
+ resource: AUDIENCE,
+ });
+ const result = await authenticateBearer(token);
+ expect(result).not.toBeNull();
+ expect(result.userId).toBe('user-abc');
+ expect(result.scope).toBe('avatars:read');
+ expect(result.source).toBe('oauth');
+ expect(result.clientId).toBe('mcp_pub');
+ });
+
+ it('returns null for null token', async () => {
+ expect(await authenticateBearer(null)).toBeNull();
+ });
+
+ it('returns null for undefined token', async () => {
+ expect(await authenticateBearer(undefined)).toBeNull();
+ });
+
+ it('returns null for a tampered signature', async () => {
+ const token = await mintAccessToken({
+ userId: 'user-abc',
+ clientId: 'mcp_pub',
+ scope: 'avatars:read',
+ resource: AUDIENCE,
+ });
+ const parts = token.split('.');
+ // Flip the last 4 chars of the signature segment.
+ parts[2] = parts[2].slice(0, -4) + 'XXXX';
+ const tampered = parts.join('.');
+ expect(await authenticateBearer(tampered)).toBeNull();
+ });
+
+ it('returns null for an expired JWT', async () => {
+ // Mint a token with past expiry using jose directly.
+ const { SignJWT } = await import('jose');
+ const key = new TextEncoder().encode(process.env.JWT_SECRET);
+ const now = Math.floor(Date.now() / 1000);
+ const expired = await new SignJWT({ scope: 'avatars:read', client_id: 'mcp_test' })
+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
+ .setIssuer(ISSUER)
+ .setSubject('user-expired')
+ .setAudience(AUDIENCE)
+ .setIssuedAt(now - 7200)
+ .setExpirationTime(now - 3600)
+ .sign(key);
+ expect(await authenticateBearer(expired)).toBeNull();
+ });
+
+ it('returns null for a JWT signed with a different secret', async () => {
+ const { SignJWT } = await import('jose');
+ const wrongKey = new TextEncoder().encode('wrong-secret-totally-different-key!!');
+ const now = Math.floor(Date.now() / 1000);
+ const badToken = await new SignJWT({ scope: 'avatars:read', client_id: 'mcp_test' })
+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
+ .setIssuer(ISSUER)
+ .setSubject('user-bad')
+ .setAudience(AUDIENCE)
+ .setIssuedAt(now)
+ .setExpirationTime(now + 3600)
+ .sign(wrongKey);
+ expect(await authenticateBearer(badToken)).toBeNull();
+ });
+});
+
+// ── csrfTokenFor + verifyCsrfToken ────────────────────────────────────────────
+
+describe('csrfTokenFor', () => {
+ it('returns an HMAC string when session cookie is present', async () => {
+ const req = { headers: { cookie: '__Host-sid=my-session-abc' } };
+ const csrf = await csrfTokenFor(req);
+ expect(typeof csrf).toBe('string');
+ expect(csrf.length).toBeGreaterThan(0);
+ });
+
+ it('returns null when no session cookie is present', async () => {
+ const req = { headers: { cookie: '' } };
+ expect(await csrfTokenFor(req)).toBeNull();
+ });
+
+ it('returns null when cookie header is missing entirely', async () => {
+ const req = { headers: {} };
+ expect(await csrfTokenFor(req)).toBeNull();
+ });
+});
+
+describe('verifyCsrfToken', () => {
+ it('round-trip: generated token passes verification against the same session', async () => {
+ const req = { headers: { cookie: '__Host-sid=session-token-xyz' } };
+ const csrf = await csrfTokenFor(req);
+ expect(await verifyCsrfToken(req, csrf)).toBe(true);
+ });
+
+ it('returns false when submitted token is for a different session', async () => {
+ const req1 = { headers: { cookie: '__Host-sid=session-one' } };
+ const csrf1 = await csrfTokenFor(req1);
+ const req2 = { headers: { cookie: '__Host-sid=session-two' } };
+ expect(await verifyCsrfToken(req2, csrf1)).toBe(false);
+ });
+
+ it('returns false for null submitted token', async () => {
+ const req = { headers: { cookie: '__Host-sid=some-session' } };
+ expect(await verifyCsrfToken(req, null)).toBe(false);
+ });
+
+ it('returns false for empty submitted token', async () => {
+ const req = { headers: { cookie: '__Host-sid=some-session' } };
+ expect(await verifyCsrfToken(req, '')).toBe(false);
+ });
+
+ it('returns false when no session cookie exists on the request', async () => {
+ const req = { headers: {} };
+ expect(await verifyCsrfToken(req, 'some-csrf-token')).toBe(false);
+ });
+
+ it('accepts the legacy "sid" cookie name', async () => {
+ const req = { headers: { cookie: 'sid=legacy-session-token' } };
+ const csrf = await csrfTokenFor(req);
+ expect(typeof csrf).toBe('string');
+ expect(await verifyCsrfToken(req, csrf)).toBe(true);
+ });
+});
diff --git a/tests/api/oauth-authorize.test.js b/tests/api/oauth-authorize.test.js
index be10af9ff..14c910745 100644
--- a/tests/api/oauth-authorize.test.js
+++ b/tests/api/oauth-authorize.test.js
@@ -41,7 +41,7 @@ vi.mock('../../api/_lib/crypto.js', () => ({
randomToken: vi.fn(() => 'fixed-code-1234567890abcdef'),
}));
-const { default: handler } = await import('../../api/oauth/authorize.js');
+const { default: handler } = await import('../../api/oauth/[action].js');
// ── Helpers ───────────────────────────────────────────────────────────────
diff --git a/tests/api/oauth-introspect.test.js b/tests/api/oauth-introspect.test.js
new file mode 100644
index 000000000..5435f8407
--- /dev/null
+++ b/tests/api/oauth-introspect.test.js
@@ -0,0 +1,239 @@
+// Tests for POST /api/oauth/introspect (RFC 7662).
+// Covers active JWT, expired/invalid JWT, and refresh token introspection.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-introspect-secret-at-least-32ch';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────────
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ const next = sqlState.queue.shift();
+ if (next instanceof Error) throw next;
+ return next;
+ }),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ oauthToken: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+const authState = {
+ verifyResult: null, // set to a payload object → returns it; null → throws
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ verifyAccessToken: vi.fn(async () => {
+ if (authState.verifyResult === null) throw new Error('invalid token');
+ return authState.verifyResult;
+ }),
+ mintAccessToken: vi.fn(async ({ scope }) => `access.${scope}.jwt`),
+ issueRefreshToken: vi.fn(async () => ({ token: 'rt', id: 'rt-id' })),
+ rotateRefreshToken: vi.fn(async () => { throw Object.assign(new Error('invalid_grant'), { status: 400 }); }),
+ revokeRefreshToken: vi.fn(async () => {}),
+ getSessionUser: vi.fn(async () => null),
+ csrfTokenFor: vi.fn(async () => null),
+ verifyCsrfToken: vi.fn(async () => false),
+ isSameSiteOrigin: vi.fn(() => false),
+}));
+
+vi.mock('../../api/_lib/crypto.js', () => ({
+ randomToken: vi.fn(() => 'fixed-token'),
+ sha256: vi.fn(async (s) => `hash:${s}`),
+ sha256Base64Url: vi.fn(async () => 'PKCE_HASH'),
+ constantTimeEquals: vi.fn(() => true),
+}));
+
+const { default: handler } = await import('../../api/oauth/[action].js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function makeReq({ formBody = {} } = {}) {
+ const base = Readable.from([Buffer.from(new URLSearchParams(formBody).toString())]);
+ base.method = 'POST';
+ base.url = '/api/oauth/introspect';
+ base.query = { action: 'introspect' };
+ base.headers = {
+ host: 'app.test',
+ 'content-type': 'application/x-www-form-urlencoded',
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ return { res, status: res.statusCode, body: JSON.parse(res.body) };
+}
+
+const PUBLIC_CLIENT = {
+ client_id: 'mcp_pub',
+ client_type: 'public',
+ scope: 'avatars:read profile',
+ grant_types: ['authorization_code', 'refresh_token'],
+};
+
+const FUTURE = new Date(Date.now() + 3_600_000).toISOString();
+const PAST = new Date(Date.now() - 3_600_000).toISOString();
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ authState.verifyResult = null;
+});
+
+// ── introspect ─────────────────────────────────────────────────────────────────
+
+describe('POST /api/oauth/introspect', () => {
+ it('returns 400 when token or client_id is missing', async () => {
+ const { status, body } = await invoke({ formBody: { client_id: 'mcp_pub' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_request');
+ });
+
+ it('returns { active: false } when client is unknown', async () => {
+ sqlState.queue.push([]); // no client row
+ const { status, body } = await invoke({
+ formBody: { token: 'some.jwt.token', client_id: 'unknown_client' },
+ });
+ expect(status).toBe(200);
+ expect(body.active).toBe(false);
+ });
+
+ it('returns { active: true } with claims for a valid JWT access token', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.verifyResult = {
+ sub: 'user-1',
+ scope: 'avatars:read',
+ client_id: 'mcp_pub',
+ aud: 'https://app.test/api/mcp',
+ iss: 'https://app.test',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ iat: Math.floor(Date.now() / 1000),
+ };
+
+ const { status, body } = await invoke({
+ formBody: { token: 'valid.jwt.token', client_id: 'mcp_pub' },
+ });
+
+ expect(status).toBe(200);
+ expect(body.active).toBe(true);
+ expect(body.sub).toBe('user-1');
+ expect(body.scope).toBe('avatars:read');
+ expect(body.client_id).toBe('mcp_pub');
+ expect(body.token_type).toBe('Bearer');
+ });
+
+ it('returns { active: false } for an invalid/expired JWT (falls through to refresh token lookup which also misses)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]); // client lookup
+ // verifyAccessToken throws (authState.verifyResult = null)
+ sqlState.queue.push([]); // no refresh token row
+ const { status, body } = await invoke({
+ formBody: { token: 'expired.or.invalid.jwt', client_id: 'mcp_pub' },
+ });
+ expect(status).toBe(200);
+ expect(body.active).toBe(false);
+ });
+
+ it('returns { active: false } for a revoked refresh token', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ // verifyAccessToken throws → fall into refresh token path
+ sqlState.queue.push([{
+ user_id: 'user-1',
+ scope: 'avatars:read',
+ expires_at: FUTURE,
+ revoked_at: PAST, // revoked
+ }]);
+
+ const { status, body } = await invoke({
+ formBody: { token: 'opaque-refresh-token', client_id: 'mcp_pub' },
+ });
+
+ expect(status).toBe(200);
+ expect(body.active).toBe(false);
+ });
+
+ it('returns { active: true } for a valid refresh token', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ // verifyAccessToken throws → fall into refresh token path
+ sqlState.queue.push([{
+ user_id: 'user-2',
+ scope: 'avatars:read profile',
+ expires_at: FUTURE,
+ revoked_at: null,
+ }]);
+
+ const { status, body } = await invoke({
+ formBody: { token: 'opaque-refresh-token', client_id: 'mcp_pub' },
+ });
+
+ expect(status).toBe(200);
+ expect(body.active).toBe(true);
+ expect(body.sub).toBe('user-2');
+ expect(body.scope).toBe('avatars:read profile');
+ expect(body.token_type).toBe('refresh_token');
+ });
+
+ it('returns { active: false } for a JWT from a different client', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.verifyResult = {
+ sub: 'user-1',
+ scope: 'avatars:read',
+ client_id: 'mcp_other', // mismatched client
+ aud: 'https://app.test/api/mcp',
+ iss: 'https://app.test',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ iat: Math.floor(Date.now() / 1000),
+ };
+
+ const { status, body } = await invoke({
+ formBody: { token: 'cross.client.jwt', client_id: 'mcp_pub' },
+ });
+
+ expect(status).toBe(200);
+ expect(body.active).toBe(false);
+ });
+
+ it('returns { active: false } for an expired refresh token', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([{
+ user_id: 'user-1',
+ scope: 'avatars:read',
+ expires_at: PAST, // expired
+ revoked_at: null,
+ }]);
+
+ const { status, body } = await invoke({
+ formBody: { token: 'expired-refresh-token', client_id: 'mcp_pub' },
+ });
+
+ expect(status).toBe(200);
+ expect(body.active).toBe(false);
+ });
+});
diff --git a/tests/api/oauth-token.test.js b/tests/api/oauth-token.test.js
index 051ebf08f..6dcd4dead 100644
--- a/tests/api/oauth-token.test.js
+++ b/tests/api/oauth-token.test.js
@@ -58,7 +58,7 @@ vi.mock('../../api/_lib/crypto.js', () => ({
constantTimeEquals: vi.fn(() => cryptoState.constTimeEqual),
}));
-const { default: handler } = await import('../../api/oauth/token.js');
+const { default: handler } = await import('../../api/oauth/[action].js');
// ── Helpers ───────────────────────────────────────────────────────────────
diff --git a/tests/api/siwe-handler.test.js b/tests/api/siwe-handler.test.js
new file mode 100644
index 000000000..e1e4da5b4
--- /dev/null
+++ b/tests/api/siwe-handler.test.js
@@ -0,0 +1,266 @@
+// Tests for the SIWE HTTP endpoints: GET nonce, POST verify.
+// api/auth/siwe/[action].js — dispatcher uses req.query.action.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-siwe-handler-secret-at-32chars';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────────
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ const next = sqlState.queue.shift();
+ if (next instanceof Error) throw next;
+ return next;
+ }),
+}));
+
+const rlState = { success: true };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ createSession: vi.fn(async () => 'siwe-session-token'),
+ destroySession: vi.fn(async () => {}),
+ sessionCookie: vi.fn((token) => `__Host-sid=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=2592000`),
+}));
+
+vi.mock('../../api/_lib/email.js', () => ({
+ sendWelcomeEmail: vi.fn(async () => {}),
+}));
+
+const ethersState = {
+ recovered: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
+};
+
+vi.mock('ethers', () => ({
+ verifyMessage: vi.fn(() => ethersState.recovered),
+ getAddress: vi.fn((addr) => addr),
+}));
+
+// Control CSRF: mock hmacSha256 to return a predictable value and
+// constantTimeEquals to always compare correctly.
+vi.mock('../../api/_lib/crypto.js', () => ({
+ randomToken: vi.fn((n) => 'A'.repeat(n > 24 ? 32 : 28)), // alphanum-safe filler
+ hmacSha256: vi.fn(async (_secret, msg) => `hmac(${msg})`),
+ constantTimeEquals: vi.fn((a, b) => a === b),
+}));
+
+const { default: handler } = await import('../../api/auth/siwe/[action].js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function makeReq({ action, method = 'GET', body = null, headers = {} } = {}) {
+ const bodyStr = body ? JSON.stringify(body) : '';
+ const base = Readable.from([Buffer.from(bodyStr)]);
+ base.method = method;
+ base.url = `/api/auth/siwe/${action}`;
+ base.query = { action };
+ base.headers = {
+ host: 'app.test',
+ ...(body !== null ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ let json = null;
+ try {
+ json = JSON.parse(res.body);
+ } catch {
+ json = res.body;
+ }
+ return { res, status: res.statusCode, body: json };
+}
+
+// EIP-4361 message with localhost domain (accepted in non-production env).
+// verifyMessage mock returns the same address so signer === claimed.
+const WALLET_ADDR = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
+const TEST_NONCE = 'testNonce1234567890ab';
+const SIWE_MESSAGE = [
+ 'localhost wants you to sign in with your Ethereum account:',
+ WALLET_ADDR,
+ '',
+ 'URI: http://localhost/login',
+ 'Version: 1',
+ 'Chain ID: 1',
+ `Nonce: ${TEST_NONCE}`,
+ 'Issued At: 2024-01-01T00:00:00.000Z',
+].join('\n');
+
+const FUTURE = new Date(Date.now() + 300_000).toISOString();
+
+// The nonce handler sets CSRF cookie = `__Host-csrf-siwe=<rawToken>`.
+// randomToken mock returns 'A'.repeat(32) for the raw token.
+// hmacSha256 mock returns `hmac(csrf-siwe:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA)`.
+// For verify tests, we supply matching header + cookie.
+const CSRF_RAW = 'A'.repeat(32);
+const CSRF_TOKEN = `hmac(csrf-siwe:${CSRF_RAW})`;
+const CSRF_COOKIE = `__Host-csrf-siwe=${CSRF_RAW}`;
+
+function withCsrf(headers = {}) {
+ return {
+ 'x-csrf-token': CSRF_TOKEN,
+ cookie: CSRF_COOKIE,
+ ...headers,
+ };
+}
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+ ethersState.recovered = WALLET_ADDR;
+});
+
+// ── GET /api/auth/siwe/nonce ───────────────────────────────────────────────────
+
+describe('GET /api/auth/siwe/nonce', () => {
+ it('returns nonce, csrf, issuedAt, expiresAt, and ttl', async () => {
+ sqlState.queue.push([]); // insert nonce
+ const { status, body, res } = await invoke({ action: 'nonce', method: 'GET' });
+ expect(status).toBe(200);
+ expect(typeof body.nonce).toBe('string');
+ expect(body.nonce.length).toBeGreaterThanOrEqual(22);
+ expect(typeof body.csrf).toBe('string');
+ expect(typeof body.issuedAt).toBe('string');
+ expect(typeof body.expiresAt).toBe('string');
+ expect(body.ttl).toBe(300);
+ });
+
+ it('stores the nonce in the DB', async () => {
+ sqlState.queue.push([]);
+ await invoke({ action: 'nonce', method: 'GET' });
+ const insert = sqlState.calls.find((c) => /insert into siwe_nonces/i.test(c.query));
+ expect(insert).toBeTruthy();
+ });
+
+ it('sets a CSRF cookie on the response', async () => {
+ sqlState.queue.push([]);
+ const { res } = await invoke({ action: 'nonce', method: 'GET' });
+ const cookie = res.headers['set-cookie'];
+ expect(cookie).toContain('__Host-csrf-siwe=');
+ expect(cookie).toContain('HttpOnly');
+ });
+
+ it('returns 429 when rate limited', async () => {
+ rlState.success = false;
+ const { status, body } = await invoke({ action: 'nonce', method: 'GET' });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
+
+// ── POST /api/auth/siwe/verify ─────────────────────────────────────────────────
+
+describe('POST /api/auth/siwe/verify', () => {
+ it('creates a session on valid message + signature (new wallet, new user)', async () => {
+ // Nonce lookup, burn nonce, wallet lookup, user lookup, insert user, insert wallet, fetch user
+ sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);
+ sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING
+ sqlState.queue.push([]); // no wallet
+ sqlState.queue.push([]); // no existing user
+ sqlState.queue.push([{ id: 'user-new', inserted: true }]); // insert user
+ sqlState.queue.push([]); // insert wallet
+ sqlState.queue.push([{ id: 'user-new', email: `[email protected]`, display_name: '0xd8dA…6045', plan: 'free', avatar_url: null, created_at: '2024-01-01' }]);
+
+ const { status, body, res } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: '0xfakesig' },
+ headers: withCsrf(),
+ });
+
+ expect(status).toBe(200);
+ expect(body.user).toBeDefined();
+ expect(body.wallet.address).toBe(WALLET_ADDR);
+ const cookie = res.headers['set-cookie'];
+ expect(cookie).toContain('__Host-sid=siwe-session-token');
+ });
+
+ it('returns 400 with nonce_reused when nonce was already consumed', async () => {
+ sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: '2024-01-01T00:00:00.000Z' }]);
+
+ const { status, body } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: '0xfakesig' },
+ headers: withCsrf(),
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('nonce_reused');
+ });
+
+ it('returns 400 with invalid_nonce when nonce is not in DB', async () => {
+ sqlState.queue.push([]); // no nonce row
+
+ const { status, body } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: '0xfakesig' },
+ headers: withCsrf(),
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_nonce');
+ });
+
+ it('returns 403 when CSRF header is missing', async () => {
+ const { status, body } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: '0xfakesig' },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('invalid_request');
+ });
+
+ it('returns 403 when CSRF token does not match cookie', async () => {
+ const { constantTimeEquals } = await import('../../api/_lib/crypto.js');
+ vi.mocked(constantTimeEquals).mockReturnValueOnce(false);
+
+ const { status, body } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: '0xfakesig' },
+ headers: withCsrf({ 'x-csrf-token': 'wrong-csrf-token' }),
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('invalid_request');
+ });
+});