@aibtc/mcp-server 1.69.0 → 1.70.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,20 @@
1
1
  /**
2
- * AIBTC Trading Competition Tools
2
+ * AIBTC Trading Competition Tools (read-only, NOT REGISTERED)
3
3
  *
4
- * Agents registered on aibtc.com (and indexed via ERC-8004) compete on a
5
- * time-bound track scored by P&L from on-chain trades. The competition service
6
- * monitors registered addresses passively, but agents can also submit txids
7
- * as a fast-path hint to skip indexer lag.
4
+ * The competition has concluded. Trade submission and the DEX allowlist were
5
+ * removed, and these two remaining read tools are no longer exposed over MCP:
6
+ * `registerCompetitionTools` is intentionally not called from `src/tools/index.ts`.
7
+ *
8
+ * The module is kept because the standing/history endpoints still exist and the
9
+ * P&L math (`computeCampaignStats`) is the reference implementation. Re-expose by
10
+ * restoring the import + call in `src/tools/index.ts`; the tests here exercise the
11
+ * module directly, so it stays compiled and verified while unwired.
8
12
  *
9
13
  * Tools:
10
- * - competition_submit_trade — Submit a trade txid for verification
11
- * - competition_status — Get current standing for an agent address
12
- * - competition_list_trades — Paginated trade history (submitted + indexed)
14
+ * - competition_status — Standing + mark-to-current P&L for an address
15
+ * - competition_list_trades — Paginated trade history
13
16
  *
14
- * No request signing in v1: txids are self-attesting (the on-chain tx
15
- * already carries the agent's signature and sender), and status/list reads
16
- * are over public addresses. Rate-limited per IP server-side.
17
+ * Reads are over public addresses, no signing. Rate-limited per IP server-side.
17
18
  *
18
19
  * API spec + verifier implementation: aibtcdev/landing-page#734 (Phase 3.1).
19
20
  * Schema source of truth: docs/rfc-d1-schema.md §swaps (migration 005).
@@ -1,20 +1,9 @@
1
1
  import { z } from "zod";
2
2
  import { AIBTC_CAMPAIGN_API_URL } from "../config/competition.js";
3
- import { NETWORK } from "../config/networks.js";
4
- import { getTransactionStatus } from "../services/hiro-api.js";
5
3
  import { getTokenInfo } from "../services/tenero-api.js";
6
4
  import { getWalletManager } from "../services/wallet-manager.js";
7
5
  import { createJsonResponse } from "../utils/formatting.js";
8
6
  import { createErrorResponse } from "../utils/errors.js";
9
- /**
10
- * Stacks tx_status values from Hiro's /extended/v1/tx endpoint.
11
- * `pending` = in mempool, not confirmed. Everything else is terminal:
12
- * `success`, `abort_by_response`, `abort_by_post_condition`, and the
13
- * five `dropped_*` codes. The verifier records terminal failures too
14
- * (migration 005's CHECK allows all 8 terminal codes) so we only block
15
- * submission when status is `pending`.
16
- */
17
- const PENDING_TX_STATUS = "pending";
18
7
  const stacksAddressSchema = z
19
8
  .string()
20
9
  .regex(/^S[PTM][0-9A-HJKMNP-TV-Z]{38,40}$/, "Expected a Stacks address (SP… mainnet, ST… testnet, SM… contract)");
@@ -33,14 +22,6 @@ async function resolveAddress(provided) {
33
22
  }
34
23
  return meta.address;
35
24
  }
36
- function normalizeTxid(txid) {
37
- const trimmed = txid.trim();
38
- const withPrefix = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
39
- if (!/^0x[0-9a-fA-F]{64}$/.test(withPrefix)) {
40
- throw new Error(`Invalid Stacks txid: expected 64 hex chars (with optional 0x prefix), got ${JSON.stringify(txid)}`);
41
- }
42
- return withPrefix.toLowerCase();
43
- }
44
25
  const COMPETITION_FETCH_TIMEOUT_MS = 10_000;
45
26
  /**
46
27
  * Cap on `/trades` pagination when computing campaign stats. 10 pages × 200
@@ -290,66 +271,8 @@ async function resolveTokenPricesViaTenero(swaps) {
290
271
  return prices;
291
272
  }
292
273
  export function registerCompetitionTools(server) {
293
- server.registerTool("competition_submit_trade", {
294
- description: `Submit a trade txid to the AIBTC trading competition for verification and P&L scoring.
295
-
296
- **Two-step registration prerequisite** (both required, both one-time):
297
- 1. Register on aibtc.com via the website's dual-sig flow (BIP-322 + SIP-018). This is not an MCP tool — agents go to https://aibtc.com to complete it.
298
- 2. Register on the ERC-8004 identity contract via the \`identity_register\` MCP tool. This mints the on-chain agent ID that the campaign joins against.
299
-
300
- Mainnet-only in v1.
301
-
302
- The competition service fetches the tx from the Stacks chain and validates:
303
- - sender is registered on aibtc.com AND has an ERC-8004 agent_id
304
- - contract+function is on the campaign allowlist (e.g. Bitflow swap helpers, ALEX, Zest)
305
- - transaction status is terminal (success or any of the 7 terminal-failure codes)
306
-
307
- **No additional signed message is needed** — the txid itself is the agent's signed intent. The on-chain tx already carries their address (= identity) and the trade (= the on-chain effect). Tx history is the ledger.
308
-
309
- Submission is a fast-path hint — the backend also indexes registered agent addresses passively via a frequent catch-up cron, so a missed submission still gets picked up before final scoring. Submitting the same txid twice is idempotent (\`(txid)\` is the DB primary key; first writer wins).
310
-
311
- **Pre-flight:** This tool checks tx status on Stacks via Hiro before forwarding to the verifier. If the tx is still \`pending\` (in mempool), the call returns \`{ accepted: false, tx_status: "pending", message: "..." }\` without hitting the verifier — wait ~30s for confirmation and retry. Use \`get_transaction_status\` to poll explicitly.
312
-
313
- Response shapes:
314
- - \`{ accepted: false, txid, tx_status: "pending", message }\` (pre-flight gate): tx not yet confirmed. Retry after ~30s.
315
- - \`200 OK\` with the swap row once verified: \`{ txid, sender, contract_id, function_name, token_in, amount_in, token_out, amount_out, burn_block_time, tx_status, source, ... }\`. Field names follow on-chain vocabulary (migration 005). \`tx_status\` is one of \`success\` or 7 terminal-failure codes (verifier records terminal failures too); \`source\` is \`"agent" | "cron"\`.
316
- - Permanent rejection (HTTP 4xx, thrown as error): sender not registered, contract not on allowlist, or txid malformed. Do not retry — fix the inputs.
317
- - Transient failure (HTTP 5xx or timeout, thrown as error): retry with backoff.`,
318
- inputSchema: {
319
- txid: z
320
- .string()
321
- .min(1)
322
- .describe("Stacks transaction id (with or without 0x prefix)"),
323
- },
324
- }, async ({ txid }) => {
325
- try {
326
- const normalized = normalizeTxid(txid);
327
- // Pre-flight: confirm the tx is terminal on Stacks before forwarding
328
- // to the verifier. Stacks blocks settle in ~30s, so a "pending" status
329
- // means the agent submitted too early — we tell them to wait and
330
- // resubmit rather than burning a backend round-trip.
331
- const txStatus = await getTransactionStatus(normalized, NETWORK);
332
- if (txStatus.status === PENDING_TX_STATUS) {
333
- return createJsonResponse({
334
- accepted: false,
335
- txid: normalized,
336
- tx_status: PENDING_TX_STATUS,
337
- message: "Transaction is still pending on Stacks. Wait ~30s for confirmation and resubmit. Use get_transaction_status to poll.",
338
- });
339
- }
340
- const parsed = await competitionFetch("/trades", {
341
- method: "POST",
342
- headers: { "content-type": "application/json" },
343
- body: JSON.stringify({ txid: normalized }),
344
- });
345
- return createJsonResponse(parsed);
346
- }
347
- catch (error) {
348
- return createErrorResponse(error);
349
- }
350
- });
351
274
  server.registerTool("competition_status", {
352
- description: `Get the current AIBTC trading competition standing for an agent, with mark-to-current P&L computed locally.
275
+ description: `Get an agent's final AIBTC trading competition standing, with mark-to-current P&L computed locally. The competition has concluded; this reads the historical record.
353
276
 
354
277
  **Latency note:** by default this call also paginates the agent's trade history and parallel-fetches Tenero prices to compute live P&L. That adds a few seconds to the round-trip for agents with many trades or many distinct tokens. Pass \`include_pnl: false\` to skip that path and get only the cheap registration/count fields back.
355
278
 
@@ -399,9 +322,9 @@ To be eligible for scoring, the agent needs **both** an aibtc.com website regist
399
322
  }
400
323
  });
401
324
  server.registerTool("competition_list_trades", {
402
- description: `List trades for an agent in the current AIBTC trading competition.
325
+ description: `List an agent's trades from the concluded AIBTC trading competition.
403
326
 
404
- Includes txids the agent submitted directly (via \`competition_submit_trade\`) and txids discovered via passive address monitoring (nightly cron). Each entry is a swap row from migration 005: \`{ txid, sender, contract_id, function_name, token_in, amount_in, token_out, amount_out, burn_block_time, tx_status, source, scored_value, scored_at }\`. \`source\` distinguishes \`"agent"\` (your submission) from \`"cron"\` (nightly catch-up). Response: \`{ trades, next_cursor }\` — opaque cursor for pagination. If no address is provided, uses the active wallet's Stacks address.`,
327
+ Covers txids the agent submitted while the competition ran and txids discovered via passive address monitoring. Each entry is a swap row from migration 005: \`{ txid, sender, contract_id, function_name, token_in, amount_in, token_out, amount_out, burn_block_time, tx_status, source, scored_value, scored_at }\`. \`source\` distinguishes \`"agent"\` (your submission) from \`"cron"\` (nightly catch-up). Response: \`{ trades, next_cursor }\` — opaque cursor for pagination. If no address is provided, uses the active wallet's Stacks address.`,
405
328
  inputSchema: {
406
329
  address: stacksAddressSchema
407
330
  .optional()
@@ -432,40 +355,5 @@ Includes txids the agent submitted directly (via \`competition_submit_trade\`) a
432
355
  return createErrorResponse(error);
433
356
  }
434
357
  });
435
- server.registerTool("competition_allowlist", {
436
- description: `Get the set of \`(contract_id, function_name)\` tuples the AIBTC trading-competition verifier will accept. Swaps against any contract/function not in this list are rejected with \`contract_not_allowlisted\` at \`POST /api/competition/trades\`.
437
-
438
- Use this **before submitting a txid** to confirm the swap you just made will score, or as discovery for "what protocols / pools can I trade for the competition right now?"
439
-
440
- Returns the payload from \`GET /api/competition/allowlist\` verbatim:
441
-
442
- \`\`\`
443
- {
444
- entries: [
445
- { contract_id: "SP….contract-name", functions: ["swap-x-for-y", ...] },
446
- ...
447
- ],
448
- total_contracts: number, // count of distinct contract_ids
449
- total_functions: number, // sum of allowed function names across entries
450
- provider_address: string, // AIBTC attribution string (audit-only)
451
- protocols: { bitflow: number }, // per-protocol entry count
452
- }
453
- \`\`\`
454
-
455
- **Notes:**
456
- - Source of truth: \`lib/competition/allowlist.ts\` in landing-page. Reviewed per PR; no runtime mutation surface.
457
- - Current scope is **Bitflow only** (stableswap, XYK, DLMM router, cross-DEX routers, wrappers). ALEX direct and Zest are NOT yet in scope — \`alex_swap\` / \`zest_*\` calls land on-chain but get rejected as \`contract_not_allowlisted\`.
458
- - \`provider_address\` is the AIBTC attribution tag Bitflow's optional \`provider\` clarity arg can carry — it's recorded for audit but does NOT gate acceptance. Only the \`(contract, function)\` tuple match matters.
459
- - The list is cached server-side; tool returns whatever the live endpoint reports at call time.`,
460
- inputSchema: {},
461
- }, async () => {
462
- try {
463
- const parsed = await competitionFetch("/allowlist");
464
- return createJsonResponse(parsed);
465
- }
466
- catch (error) {
467
- return createErrorResponse(error);
468
- }
469
- });
470
358
  }
471
359
  //# sourceMappingURL=competition.tools.js.map
@@ -12,7 +12,7 @@ export function registerDefiTools(server) {
12
12
  description: `Get a swap quote from ALEX DEX.
13
13
 
14
14
  Returns the expected output amount for swapping tokenX to tokenY.
15
- Use full contract IDs for tokens (e.g., 'SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9.token-wstx-v2').
15
+ Use full contract IDs for tokens (e.g., 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.token-wstx-v2').
16
16
 
17
17
  Note: ALEX DEX is only available on mainnet.`,
18
18
  inputSchema: {
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { createApiClient, API_URL, probeEndpoint, formatPaymentAmount, checkSufficientBalance, generateDedupKey, checkDedupCache, recordTransaction, X402_DEDUP_TTL_MS, NETWORK } from "../services/x402.service.js";
3
3
  import { ALL_ENDPOINTS, searchEndpoints, formatEndpointsTable, getEndpointsBySource, getCategories, } from "../endpoints/registry.js";
4
4
  import { createJsonResponse, createErrorResponse } from "../utils/index.js";
5
- import { X402_HEADERS } from "../utils/x402-protocol.js";
5
+ import { X402_HEADERS, decodePaymentResponse } from "../utils/x402-protocol.js";
6
6
  import { extractPaymentIdFromPaymentSignature, extractTxidFromPaymentSignature, pollTransactionConfirmation, } from "../utils/x402-recovery.js";
7
7
  import { formatCanonicalPaymentStatus } from "../utils/x402-payment-state.js";
8
8
  import { emitPaymentLog } from "../utils/x402-payment-logging.js";
@@ -317,8 +317,13 @@ For aibtc.com inbox messages, use send_inbox_message_direct instead — it signs
317
317
  },
318
318
  });
319
319
  const response = await api.request({ method, url: parsed.requestPath, params, data });
320
+ const paymentResponseTxid = decodePaymentResponse(response.headers?.[X402_HEADERS.PAYMENT_RESPONSE])?.transaction ||
321
+ undefined;
322
+ const paymentBodyTxid = response.data?.payment?.txid;
320
323
  const rawTxid = response.data?.txid ||
321
324
  response.data?.payment_txid ||
325
+ paymentResponseTxid ||
326
+ (typeof paymentBodyTxid === "string" ? paymentBodyTxid : undefined) ||
322
327
  response.headers?.['x-transaction-id'] ||
323
328
  undefined;
324
329
  // Detect whether a payment was made by checking for the payment-signature
@@ -32,11 +32,15 @@ import { registerTeneroTools } from "./tenero.tools.js";
32
32
  import { registerOrdinalsP2PTools } from "./ordinals-p2p.tools.js";
33
33
  import { registerOrdinalsMarketplaceTools } from "./ordinals-marketplace.tools.js";
34
34
  import { registerTaprootMultisigTools } from "./taproot-multisig.tools.js";
35
+ import { registerPsbtTools } from "./psbt.tools.js";
36
+ import { registerSettingsTools } from "./settings.tools.js";
35
37
  import { registerJingswapTools } from "./jingswap.tools.js";
36
38
  import { registerSigningTools } from "./signing.tools.js";
37
39
  import { registerInferenceMarketplaceTools } from "./inference-marketplace.tools.js";
38
40
  import { registerNewsTools } from "./news.tools.js";
39
41
  import { registerLegionTools } from "./legion.tools.js";
42
+ import { registerAtStakeTools } from "./at-stake.tools.js";
43
+ import { registerAtStakeLegionTools } from "./at-stake-legion.tools.js";
40
44
  import { registerIdentityTools } from "./identity.tools.js";
41
45
  import { registerCredentialsTools } from "./credentials.tools.js";
42
46
  import { registerSouldinalsTools } from "./souldinals.tools.js";
@@ -47,7 +51,6 @@ import { registerRunesTools } from "./runes.tools.js";
47
51
  import { registerInboxTools } from "./inbox.tools.js";
48
52
  import { registerInboxX402Tools } from "./inbox-x402.tools.js";
49
53
  import { registerArxivResearchTools } from "./arxiv-research.tools.js";
50
- import { registerCompetitionTools } from "./competition.tools.js";
51
54
  import { registerEarningTools } from "./earning.tools.js";
52
55
  import { getSkillForTool } from "./skill-mappings.js";
53
56
  /**
@@ -160,16 +163,24 @@ export function registerAllTools(server) {
160
163
  registerOrdinalsMarketplaceTools(server);
161
164
  // Taproot Multisig (M-of-N coordination via OP_CHECKSIGADD, BIP-341/342)
162
165
  registerTaprootMultisigTools(server);
166
+ // PSBT sign/broadcast/decode (used by the ordinals marketplace, P2P and taproot multisig flows)
167
+ registerPsbtTools(server);
168
+ // Settings (Hiro API key, custom Stacks API URL, server version)
169
+ registerSettingsTools(server);
163
170
  // Jingswap Auction (blind batch auctions for STX/sBTC)
164
171
  registerJingswapTools(server);
165
172
  // Message Signing (BTC BIP-322, Stacks SIWS, SIP-018 structured data, Nostr NIP-01)
166
173
  registerSigningTools(server);
167
174
  // AIBTC Inference Marketplace (list/manage a paid model endpoint via wallet signature)
168
175
  registerInferenceMarketplaceTools(server);
169
- // AIBTC News (signal feed, leaderboard, file signals)
176
+ // AIBTC News (deprecated — API retired; each tool redirects to legion_*)
170
177
  registerNewsTools(server);
171
178
  // AIBTC News Legion (mainnet aibtc-news-gov — inscribe, propose, vote, conclude)
172
179
  registerLegionTools(server);
180
+ // At Stake (elsalvadorstakesbtc.com — complete-set prediction market)
181
+ registerAtStakeTools(server);
182
+ // At Stake side legions (aibtc.com/legions — weight is the share balance)
183
+ registerAtStakeLegionTools(server);
173
184
  // Identity (ERC-8004 on-chain agent identity management)
174
185
  registerIdentityTools(server);
175
186
  // Credentials (encrypted credential store — list, get, set, delete, unlock)
@@ -190,8 +201,6 @@ export function registerAllTools(server) {
190
201
  registerInboxX402Tools(server);
191
202
  // arXiv Research (public arXiv Atom API — paper search and digest compilation)
192
203
  registerArxivResearchTools(server);
193
- // AIBTC Trading Competition (submit trade txids, check standing, list trades)
194
- registerCompetitionTools(server);
195
204
  // Earning Opportunities (static "how to put your assets to work" menu)
196
205
  registerEarningTools(server);
197
206
  restoreRegisterTool();
@@ -1,36 +1,10 @@
1
1
  /**
2
- * AIBTC News Tools
2
+ * AIBTC News tools — deprecated.
3
3
  *
4
- * Tools for interacting with the aibtc.news decentralized intelligence network.
5
- * Agents can read signal feeds, check correspondent standings, and file signals
6
- * authenticated via BIP-322 signatures (bc1q P2WPKH addresses only).
7
- *
8
- * Correspondent tools (read-only, no auth required):
9
- * - news_list_signals — Browse the signal feed with optional filters
10
- * - news_front_page — Get the latest compiled intelligence brief
11
- * - news_leaderboard — Ranked correspondents with signal counts and streaks
12
- * - news_check_status — Signal counts, streak, and earnings for a BTC address
13
- * - news_list_beats — List all registered beats
14
- * - news_list_editors — List editors registered on a beat
15
- *
16
- * Authenticated tools (require unlocked wallet with bc1q/tb1q address):
17
- * - news_file_signal — File a signal on a beat (BIP-322 signed)
18
- * - news_claim_beat — Create or join a beat (BIP-322 signed)
19
- * - news_editor_review_signal — Approve or reject a signal (editor or publisher)
20
- * - news_editor_file_review — Submit structured editorial review for a signal
21
- * - news_editor_check_earnings — Check editor earnings for an address
22
- * - news_register_editor — Register an editor on a beat (publisher only)
23
- * - news_deactivate_editor — Deactivate an editor on a beat (publisher only)
24
- * - news_file_correction — File a correction on a signal
25
- * - news_publisher_compile_brief — Compile the daily intelligence brief (publisher only)
26
- * - news_publisher_set_beat_config — Update beat details and config (publisher only)
27
- * - news_record_editor_payout — Record payout txid for an editor earning (publisher only)
28
- *
29
- * Authentication: BIP-322 simple signature (P2WPKH, bc1q mainnet / tb1q testnet).
30
- * Message format: "METHOD /path:unix_timestamp"
31
- * Headers: X-BTC-Address, X-BTC-Signature, X-BTC-Timestamp
32
- *
33
- * Reference: https://aibtc.news/api (GET /api for full spec)
4
+ * aibtc.news migrated from an off-chain newsroom API to on-chain governance, and
5
+ * every endpoint these tools called now answers 410 Gone. The tool names stay
6
+ * registered so an agent that still calls one is told where the workflow moved
7
+ * (the legion_* tools) instead of getting "unknown tool".
34
8
  */
35
9
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
36
10
  export declare function registerNewsTools(server: McpServer): void;