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.

fix(mcp): publish a forecast example that actually validates against its own schema

nirholasfbbe1e0375d0
diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.js
index bac695ba5..5887afa9e 100644
--- a/api/_mcpagent/catalog.js
+++ b/api/_mcpagent/catalog.js
@@ -4,8 +4,8 @@ import addFormats from 'ajv-formats';
import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs } from './tools.js';
-// Free, public entry point — listed first so discovery clients see it up top.
-// Annotations: a static, local overview built at module load — read-only,
+// Free, public entry point, listed first so discovery clients see it up top.
+// Annotations: a static, local overview built at module load: read-only,
// deterministic, closed-world (destructiveHint is explicit because the MCP
// spec defaults it to true when omitted).
const gettingStarted = {
@@ -15,7 +15,7 @@ const gettingStarted = {
tools: toolDefs,
access: [
'Sign in with your three.ws account (OAuth) to use your agent wallet.',
- 'pay_and_call spends USDC from your own three.ws agent wallet within your spend caps — check wallet_status first.',
+ 'pay_and_call spends USDC from your own three.ws agent wallet within your spend caps. Check wallet_status first.',
],
links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
}),
@@ -29,7 +29,7 @@ const gettingStarted = {
const allDefs = [gettingStarted, ...toolDefs];
-// Schema objects for tools/list — strip internal fields (scope, handler).
+// Schema objects for tools/list; strip internal fields (scope, handler).
export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.js
index 2c8dd7caa..0b9be3d2d 100644
--- a/api/_mcpagent/dispatch.js
+++ b/api/_mcpagent/dispatch.js
@@ -1,4 +1,4 @@
-// JSON-RPC dispatch for the threews-agent MCP server — thin binding of the
+// JSON-RPC dispatch for the threews-agent MCP server: a thin binding of the
// shared payment-free dispatcher (api/_lib/mcp-dispatch.js) to this catalog.
// (The "payment-free" refers to MCP-tool pricing; pay_and_call moves the
// USER's funds to external services, which is orthogonal to tool billing.)
diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.js
index 5f52c566e..e9860416e 100644
--- a/api/_mcpagent/tools.js
+++ b/api/_mcpagent/tools.js
@@ -1,10 +1,10 @@
-// threews-agent MCP — "add a wallet to Claude."
+// threews-agent MCP: "add a wallet to Claude."
//
// Three tools turn a Claude (or any MCP client) into an autonomous economic
// agent on the live x402 network:
-// • wallet_status — what the agent's wallet holds and is allowed to spend
-// • find_services — discover paid services it can call
-// • pay_and_call — pay an x402 endpoint in USDC from the user's own wallet
+// * wallet_status what the agent's wallet holds and is allowed to spend
+// * find_services discover paid services it can call
+// * pay_and_call pay an x402 endpoint in USDC from the user's own wallet
// and return the result, bounded by spending caps
//
// pay_and_call moves real money. It requires an authenticated (OAuth) user so
@@ -55,7 +55,7 @@ function payLink(resource) {
return u.toString();
}
-// Designed "sign in" result for the null x402 path — these tools write to the
+// Designed "sign in" result for the null x402 path. These tools write to the
// user's own account, so an anonymous pay-per-call caller can never use them.
function signInRequired(text) {
return {
@@ -113,7 +113,7 @@ async function loadOwnedAgent(agentId, auth) {
}
// Request a 1 SOL devnet airdrop for a freshly provisioned wallet. Devnet only;
-// never called on mainnet. Returns the signature or a reason on failure — an
+// never called on mainnet. Returns the signature or a reason on failure: an
// unavailable faucet must not fail the whole provision call.
async function requestDevnetAirdrop(address) {
const { solanaConnection } = await import('../_lib/agent-pumpfun.js');
@@ -145,7 +145,7 @@ export const toolDefs = [
openWorldHint: true,
},
description:
- "Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only — never moves funds. Call this before pay_and_call to confirm there's balance and headroom.",
+ "Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only, never moves funds. Call this before pay_and_call to confirm there's balance and headroom.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
async handler(args, auth) {
await enforce(limits.mcpAgent, auth);
@@ -193,7 +193,7 @@ export const toolDefs = [
openWorldHint: true,
},
description:
- 'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL — feed a resource into pay_and_call to actually use it.',
+ 'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. Feed a resource into pay_and_call to actually use it.',
inputSchema: {
type: 'object',
properties: {
@@ -235,7 +235,7 @@ export const toolDefs = [
? services
.map(
(s, i) =>
- `${i + 1}. ${s.name || s.resource}${s.price ? ` — ${s.price}` : ''}\n ${s.resource}`,
+ `${i + 1}. ${s.name || s.resource}${s.price ? ` - ${s.price}` : ''}\n ${s.resource}`,
)
.join('\n')
: `No services matched "${args.query}".`;
@@ -248,7 +248,7 @@ export const toolDefs = [
{
name: 'pay_and_call',
title: 'Pay an x402 service and return its result',
- // Spends the user's USDC — an irreversible transfer, so destructive.
+ // Spends the user's USDC: an irreversible transfer, so destructive.
annotations: {
readOnlyHint: false,
destructiveHint: true,
@@ -336,7 +336,7 @@ export const toolDefs = [
const friendly = {
spend_disabled: 'Autonomous spending is disabled on this server.',
auth_required: 'Sign in to pay from your wallet.',
- no_wallet: 'No agent wallet found for your account — create one on three.ws.',
+ no_wallet: 'No agent wallet found for your account. Create one on three.ws.',
no_solana_wallet: 'Your agent has no Solana wallet provisioned.',
invalid_url: 'That resource URL is not a permitted public https endpoint.',
blocked_url:
@@ -360,7 +360,7 @@ export const toolDefs = [
name: 'provision_wallet',
title: "Create the agent's wallet",
// Creates a wallet (idempotent for an existing one, but airdrop:true
- // re-requests the faucet each call — conservative hint is false).
+ // re-requests the faucet each call, so the conservative hint is false).
annotations: {
readOnlyHint: false,
destructiveHint: false,
@@ -368,7 +368,7 @@ export const toolDefs = [
openWorldHint: true,
},
description:
- 'Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent — if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.',
+ 'Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent: if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.',
inputSchema: {
type: 'object',
properties: {
@@ -381,7 +381,7 @@ export const toolDefs = [
airdrop: {
type: 'boolean',
default: false,
- description: 'Devnet only — request a 1 SOL faucet airdrop after provisioning.',
+ description: 'Devnet only: request a 1 SOL faucet airdrop after provisioning.',
},
},
required: ['agent_id'],
@@ -400,7 +400,7 @@ export const toolDefs = [
const { address, created } = await getOrCreateAgentSolanaWallet(args.agent_id);
- // Airdrop is devnet-only and best-effort — never on mainnet, never
+ // Airdrop is devnet-only and best-effort: never on mainnet, never
// fabricated. A faucet failure is surfaced as a note, not an error.
let airdrop = null;
if (cluster === 'devnet' && args.airdrop) {
@@ -444,7 +444,7 @@ export const toolDefs = [
{
name: 'monetize_endpoint',
title: 'Publish a paid endpoint to earn USDC',
- // Publishes a new listing each call — additive write, never destructive.
+ // Publishes a new listing each call: an additive write, never destructive.
annotations: {
readOnlyHint: false,
destructiveHint: false,
@@ -452,7 +452,7 @@ export const toolDefs = [
openWorldHint: true,
},
description:
- "Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network — run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.",
+ "Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network; run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.",
inputSchema: {
type: 'object',
properties: {
@@ -479,7 +479,7 @@ export const toolDefs = [
// fallback (`args.network === 'solana' ? 'solana' : 'base'`) and
// createPaidService's `network = 'base'`. The validator compiles with
// Ajv `useDefaults: true`, so this default is written into `args.network`
- // before the handler runs — a `'solana'` default here silently forced
+ // before the handler runs. A `'solana'` default here silently forced
// every default-network call onto the Solana payout path (reading the
// usually-empty meta.solana_address) and rejected it as no_payout_wallet,
// even for an agent with a Base EVM wallet.
@@ -547,18 +547,34 @@ export const toolDefs = [
};
}
- const row = await createPaidService({
- ownerUserId: auth.userId,
- agentId: args.agent_id,
- name: args.name,
- description: args.description,
- priceUsdc: args.price_usdc,
- targetUrl,
- method: args.method || 'POST',
- inputSchema: args.input_schema || null,
- network,
- payoutAddress,
- });
+ // A MonetizeError carries a designed, caller-safe message and code (e.g.
+ // slug_alloc_failed after four collisions), so it answers in the same
+ // { ok:false, reason } shape as every other refusal above rather than
+ // reaching the dispatcher as a bare "Error: ...". Anything else (a
+ // driver fault) is rethrown so the shared sanitizer strips its
+ // internals before the agent ever sees it.
+ let row;
+ try {
+ row = await createPaidService({
+ ownerUserId: auth.userId,
+ agentId: args.agent_id,
+ name: args.name,
+ description: args.description,
+ priceUsdc: args.price_usdc,
+ targetUrl,
+ method: args.method || 'POST',
+ inputSchema: args.input_schema || null,
+ network,
+ payoutAddress,
+ });
+ } catch (err) {
+ if (!(err instanceof MonetizeError)) throw err;
+ return {
+ content: [{ type: 'text', text: `Could not publish the service: ${err.message}` }],
+ structuredContent: { ok: false, reason: err.code || 'publish_failed', network },
+ isError: true,
+ };
+ }
const resourceUrl = serviceResourceUrl(row.slug);
const priceUsdc = atomicsToUsdc(priceAtomics);
@@ -567,7 +583,7 @@ export const toolDefs = [
{
type: 'text',
text: [
- `Published "${row.name}" — $${priceUsdc} USDC per call on ${network}.`,
+ `Published "${row.name}" for $${priceUsdc} USDC per call on ${network}.`,
`Resource: ${resourceUrl}`,
`Payouts settle to ${payoutAddress}.`,
'Other agents can now find it via find_services and pay it with pay_and_call.',
diff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.js
index 6d48bfcfd..518f6a1d0 100644
--- a/api/_mcpibm/tools.js
+++ b/api/_mcpibm/tools.js
@@ -601,6 +601,27 @@ const FORECAST_DESCRIPTION =
const FREQ_EXAMPLES = '1min, 5min, 15min, 30min, 1h, 2h, 4h, 12h, 1D, 1W, 1ME';
+// The published example has to satisfy the input schema, because it is what the
+// bazaar discovery extension hands facilitators and agents to copy: a shorter
+// stub reads as runnable and comes straight back as a -32602. The schema floor
+// is 64 points, so the example is a real 64-day daily series with a weekly
+// ripple and a mild uptrend, generated once at module load.
+const FORECAST_EXAMPLE_POINTS = 64;
+
+function forecastExampleSeries() {
+ const timestamps = [];
+ const values = [];
+ const start = Date.UTC(2025, 0, 1);
+ for (let i = 0; i < FORECAST_EXAMPLE_POINTS; i++) {
+ timestamps.push(new Date(start + i * 86_400_000).toISOString());
+ const weekly = 90 * Math.sin((2 * Math.PI * i) / 7);
+ values.push(Math.round(1200 + i * 6 + weekly));
+ }
+ return { timestamps, values };
+}
+
+const FORECAST_EXAMPLE = forecastExampleSeries();
+
const forecastTool = {
name: 'ibm_granite_forecast',
title: 'IBM Granite Forecast ($0.05)',
@@ -648,8 +669,8 @@ const forecastTool = {
additionalProperties: false,
},
example: {
- timestamps: ['2025-01-01T00:00:00Z', '2025-01-02T00:00:00Z'],
- values: [1200, 1350],
+ timestamps: FORECAST_EXAMPLE.timestamps,
+ values: FORECAST_EXAMPLE.values,
freq: '1D',
prediction_length: 7,
label: 'daily_revenue_usd',
diff --git a/packages/ibm-x402-mcp/src/tools/granite-forecast.js b/packages/ibm-x402-mcp/src/tools/granite-forecast.js
index 1cdc4d260..db68ac4b5 100644
--- a/packages/ibm-x402-mcp/src/tools/granite-forecast.js
+++ b/packages/ibm-x402-mcp/src/tools/granite-forecast.js
@@ -57,6 +57,28 @@ const inputZodShape = {
const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+// The published example has to satisfy the input schema, because it is what the
+// x402 discovery payload hands facilitators and agents to copy: a shorter stub
+// reads as runnable and comes straight back as a validation error. The schema
+// floor is 64 points, so the example is a real 64-day daily series with a
+// weekly ripple and a mild uptrend. Kept identical to the hosted transport in
+// api/_mcpibm/tools.js.
+const FORECAST_EXAMPLE_POINTS = 64;
+
+function forecastExampleSeries() {
+ const timestamps = [];
+ const values = [];
+ const start = Date.UTC(2025, 0, 1);
+ for (let i = 0; i < FORECAST_EXAMPLE_POINTS; i++) {
+ timestamps.push(new Date(start + i * 86_400_000).toISOString());
+ const weekly = 90 * Math.sin((2 * Math.PI * i) / 7);
+ values.push(Math.round(1200 + i * 6 + weekly));
+ }
+ return { timestamps, values };
+}
+
+const FORECAST_EXAMPLE = forecastExampleSeries();
+
export async function buildGraniteForecastTool(client) {
const handler = await paid(
{
@@ -65,8 +87,8 @@ export async function buildGraniteForecastTool(client) {
priceUsd: '$0.05',
inputSchema: inputJsonSchema,
example: {
- timestamps: ['2025-01-01T00:00:00Z', '2025-01-02T00:00:00Z'],
- values: [1200, 1350],
+ timestamps: FORECAST_EXAMPLE.timestamps,
+ values: FORECAST_EXAMPLE.values,
freq: '1D',
prediction_length: 7,
label: 'daily_revenue_usd',
diff --git a/tests/api/ibm-mcp.test.js b/tests/api/ibm-mcp.test.js
index 68f3168f5..c3230344c 100644
--- a/tests/api/ibm-mcp.test.js
+++ b/tests/api/ibm-mcp.test.js
@@ -7,6 +7,7 @@ process.env.WATSONX_PROJECT_ID ||= 'proj-123';
// ── watsonx.ai clients (no network, no real credentials) ────────────────────
const wx = {
+ config: vi.fn(() => ({ configured: true })),
chat: vi.fn(async () => ({
text: 'Granite says hello.',
finishReason: 'stop',
@@ -21,7 +22,7 @@ const wx = {
})),
};
vi.mock('../../api/_lib/watsonx.js', () => ({
- watsonxConfig: vi.fn(() => ({ configured: true })),
+ watsonxConfig: (...a) => wx.config(...a),
watsonxChatComplete: (...a) => wx.chat(...a),
watsonxEmbed: (...a) => wx.embed(...a),
}));
@@ -59,6 +60,8 @@ const { graniteX402Amount, priceFor, formatUsdPrice, TOOL_PRICING } = await impo
'../../api/_mcpibm/pricing.js'
);
const { isFreeTool, TOOL_CATALOG } = await import('../../api/_mcpibm/catalog.js');
+const { toolDefs } = await import('../../api/_mcpibm/tools.js');
+const { declareMcpDiscovery } = await import('../../api/_lib/x402/bazaar-helpers.js');
const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402', x402Paid: true };
const call = (name, args) =>
@@ -79,6 +82,8 @@ function makeSeries(n) {
}
beforeEach(() => {
+ wx.config.mockClear();
+ wx.config.mockReturnValue({ configured: true });
wx.chat.mockClear();
wx.embed.mockClear();
fc.forecast.mockClear();
@@ -291,6 +296,73 @@ describe('IBM Granite MCP — dispatch', () => {
expect(r.result.isError).toBe(true);
expect(r.result.content[0].text).toContain('Error:');
});
+
+ it('rejects a forecast whose values do not align with its timestamps', async () => {
+ const { timestamps, values } = makeSeries(64);
+ const r = await call('ibm_granite_forecast', {
+ timestamps,
+ values: [...values, 9999],
+ freq: '1D',
+ });
+ expect(r.error.code).toBe(-32602);
+ expect(r.error.message).toContain('equal length');
+ // The mismatch is caught before any billable watsonx inference runs.
+ expect(fc.forecast).not.toHaveBeenCalled();
+ });
+
+ it('tells the caller which credentials are missing instead of failing deep in watsonx', async () => {
+ wx.config.mockReturnValue({ configured: false });
+ // embed has no OpenRouter equivalent, so it needs real watsonx credentials.
+ const embed = await call('ibm_granite_embed', { inputs: ['hello'] });
+ expect(embed.result.isError).toBe(true);
+ expect(embed.result.content[0].text).toContain('WATSONX_API_KEY');
+ expect(wx.embed).not.toHaveBeenCalled();
+ });
+
+ it('lets the text tools fall over to the OpenRouter Granite backstop', async () => {
+ wx.config.mockReturnValue({ configured: false });
+ const prev = process.env.OPENROUTER_API_KEY;
+ process.env.OPENROUTER_API_KEY = 'or-test-key';
+ try {
+ const r = await call('ibm_granite_chat', { messages: [{ role: 'user', content: 'hi' }] });
+ expect(r.result.isError).toBeUndefined();
+ expect(wx.chat).toHaveBeenCalled();
+ } finally {
+ if (prev === undefined) delete process.env.OPENROUTER_API_KEY;
+ else process.env.OPENROUTER_API_KEY = prev;
+ }
+ });
+});
+
+// Each tool publishes an `example` arguments object, and for the priced tools
+// that object is what the v2 bazaar discovery extension hands x402 facilitators
+// and agents to copy. An example that fails the tool's own inputSchema reads as
+// runnable and comes straight back as a -32602, so every one of them is dialed
+// through the real dispatcher exactly as a client would send it.
+describe('IBM Granite MCP: every published example is a call that actually works', () => {
+ it('each tool example passes its own input schema through the real dispatcher', async () => {
+ for (const tool of toolDefs) {
+ const r = await call(tool.name, structuredClone(tool.example));
+ expect(r.error, `${tool.name}: ${JSON.stringify(r.error)}`).toBeUndefined();
+ expect(r.result.isError, tool.name).toBeUndefined();
+ }
+ });
+
+ it('the forecast example carries a full context window, not a two-point stub', () => {
+ const forecast = toolDefs.find((t) => t.name === 'ibm_granite_forecast');
+ const floor = forecast.inputSchema.properties.timestamps.minItems;
+ expect(forecast.example.timestamps.length).toBeGreaterThanOrEqual(floor);
+ expect(forecast.example.values).toHaveLength(forecast.example.timestamps.length);
+ });
+
+ it('the discovery extension publishes that same example for every priced tool', () => {
+ for (const name of Object.keys(TOOL_PRICING)) {
+ const def = toolDefs.find((t) => t.name === name);
+ const call = declareMcpDiscovery.mock.calls.find((c) => c[0].toolName === name);
+ expect(call, `${name}: no discovery declaration`).toBeTruthy();
+ expect(call[0].example, `${name}: discovery example`).toEqual(def.example);
+ }
+ });
});
describe('IBM Granite MCP — pricing', () => {
diff --git a/tests/mcp-trader-tools.test.js b/tests/mcp-trader-tools.test.js
index ff8ce4d49..38f93891b 100644
--- a/tests/mcp-trader-tools.test.js
+++ b/tests/mcp-trader-tools.test.js
@@ -98,6 +98,7 @@ const USER = { userId: 'u-1111-2222', rateKey: 'user:u-1111-2222', scope: 'agent
const LEADER_ID = '11111111-2222-4333-8444-555555555555';
const LEADER_WALLET = 'So11111111111111111111111111111111111111112';
const COPIER_WALLET = '3XmnvxYtNvbYYDkVfsMbrJyVJUxCFyAMBjsqFYPRZUFn';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
/** Parse the JSON payload an MCP ok-result carries. */
function payloadOf(result) {
@@ -121,7 +122,7 @@ function boardRow(over = {}) {
open_positions: 2,
wins: 21,
losses: 9,
- win_rate: 70,
+ win_rate: RATIO(70),
realized_pnl_sol: 12.5,
realized_pnl_usd: 2500,
roi_pct: 41.2,
@@ -133,6 +134,12 @@ function boardRow(over = {}) {
};
}
+// computeTraderMetrics publishes win_rate as `wins / closedCount`, a 0-to-1
+// ratio, and both handlers scale it into win_rate_pct on the way out. Fixtures
+// that state it as a percent make a flawless leader assert as 7000% and hide
+// whether the scaling is applied at all, so ratios go in and percents come out.
+const RATIO = (pct) => pct / 100;
+
beforeEach(() => {
queued = [];
executed = [];
@@ -175,7 +182,7 @@ describe('trader_leaderboard', () => {
sol_usd: 200,
leaderboard: [
boardRow(),
- boardRow({ rank: 2, agent_id: 'aaaa', agent_name: 'Rookie', score: 41, verified: false, win_rate: 30, closed: 3 }),
+ boardRow({ rank: 2, agent_id: 'aaaa', agent_name: 'Rookie', score: 41, verified: false, win_rate: RATIO(30), closed: 3 }),
],
});
@@ -234,16 +241,23 @@ describe('trader_profile', () => {
sol_usd: 200,
metrics: {
score: 82, verified: true, closed_count: 30, open_count: 1, wins: 21, losses: 9,
- win_rate: 70, realized_pnl_sol: 12.5, realized_pnl_usd: 2500, roi_pct: 41.2,
+ win_rate: RATIO(70), realized_pnl_sol: 12.5, realized_pnl_usd: 2500, roi_pct: 41.2,
profit_factor: 2.1, avg_pnl_pct: 8, best_pnl_pct: 120, max_drawdown_pct: 18,
avg_hold_seconds: 420, unique_coins: 14,
},
+ // Exactly the keys shapeClosed() emits. An earlier fixture invented
+ // realized_pnl_* / *_solscan / hold_seconds, which the handler never reads,
+ // so it asserted nothing about the P&L and proof links the tool advertises
+ // as its verifiable track record. The third row is the flat outcome with no
+ // timestamps: the only path where hold_seconds must come back null rather
+ // than NaN.
closed: [
- { symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', realized_pnl_pct: 42, realized_pnl_sol: 1.2, hold_seconds: 300, exit_reason: 'take_profit', closed_at: '2026-08-10T00:00:00.000Z', sell_solscan: 'https://solscan.io/tx/sell1', buy_solscan: 'https://solscan.io/tx/buy1' },
- { symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', realized_pnl_pct: -12, realized_pnl_sol: -0.3, hold_seconds: 120, exit_reason: 'stop_loss', closed_at: '2026-08-09T00:00:00.000Z', sell_solscan: null, buy_solscan: 'https://solscan.io/tx/buy2' },
+ { symbol: 'THREE', mint: THREE_MINT, pnl_pct: 42, pnl_sol: 1.2, exit_reason: 'take_profit', opened_at: '2026-08-09T23:55:00.000Z', closed_at: '2026-08-10T00:00:00.000Z', buy_url: 'https://solscan.io/tx/buy1', sell_url: 'https://solscan.io/tx/sell1', moonbag_held: true, self_dealing: false },
+ { symbol: 'THREE', mint: THREE_MINT, pnl_pct: -12, pnl_sol: -0.3, exit_reason: 'stop_loss', opened_at: '2026-08-08T23:58:00.000Z', closed_at: '2026-08-09T00:00:00.000Z', buy_url: 'https://solscan.io/tx/buy2', sell_url: null, moonbag_held: false, self_dealing: true },
+ { symbol: 'THREE', mint: THREE_MINT, pnl_pct: 2, pnl_sol: 0.01, exit_reason: 'manual', opened_at: null, closed_at: null, buy_url: null, sell_url: null, moonbag_held: false, self_dealing: false },
],
open: [
- { id: 'p-1', symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', entry_sol: 0.5, current_sol: 0.8, unrealized_pct: 60, opened_at: '2026-08-11T00:00:00.000Z', buy_url: 'https://solscan.io/tx/buy3' },
+ { id: 'p-1', symbol: 'THREE', mint: THREE_MINT, entry_sol: 0.5, current_sol: 0.8, unrealized_pct: 60, opened_at: '2026-08-11T00:00:00.000Z', buy_url: 'https://solscan.io/tx/buy3' },
],
oracle: null,
};
@@ -255,13 +269,24 @@ describe('trader_profile', () => {
expect(out.score).toBe(82);
expect(out.recommendation).toBe('copy');
expect(out.metrics.win_rate_pct).toBe(70);
- expect(out.recent_trades).toHaveLength(2);
- expect(out.recent_trades[0]).toMatchObject({ outcome: 'win', proof_url: 'https://solscan.io/tx/sell1' });
- expect(out.recent_trades[1]).toMatchObject({ outcome: 'loss', proof_url: 'https://solscan.io/tx/buy2' });
+ expect(out.recent_trades).toHaveLength(3);
+ // pnl_sol / pnl_pct and the Solscan proof are the whole point of this tool:
+ // an agent vets a leader on them before committing money to a copy.
+ expect(out.recent_trades[0]).toMatchObject({
+ outcome: 'win', pnl_sol: 1.2, pnl_pct: 42, hold_seconds: 300,
+ proof_url: 'https://solscan.io/tx/sell1', moonbag_held: true, self_dealing: false,
+ });
+ // Falls back to the buy proof when the sell carries no signature, and keeps
+ // the self-dealing flag so a self-launched coin cannot read as pure skill.
+ expect(out.recent_trades[1]).toMatchObject({
+ outcome: 'loss', pnl_sol: -0.3, pnl_pct: -12, hold_seconds: 120,
+ proof_url: 'https://solscan.io/tx/buy2', moonbag_held: false, self_dealing: true,
+ });
+ expect(out.recent_trades[2]).toMatchObject({ outcome: 'flat', hold_seconds: null, proof_url: null });
expect(out.open_positions).toEqual([
{
symbol: 'THREE',
- mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ mint: THREE_MINT,
entry_sol: 0.5,
current_sol: 0.8,
unrealized_pct: 60,