XChain Platform - Software Developer Kit (SDK)
Developer-facing SDK for the XChain Platform: generate XChain transactions and query blockchain data.
接入你的智能体
發布者自己的指令。不是 PlugMCP 端點。
用我們的金鑰與日誌託管一份副本。
npx -y [email protected]Claude Code 沒有本機指令的安裝連結。複製下方指令並在終端機中執行。
claude mcp add xchain-mcp -- npx -y xchain-mcp@0.27.0在終端機中執行。
{ "mcpServers": { "xchain-mcp": { "command": "npx", "args": [ "-y", "[email protected]" ] } }}claude_desktop_config.json
遠端 URL 還是本機指令? 兩種安裝方式的差異
來自發布者
Developer-facing SDK for the XChain Platform: generate XChain transactions and query blockchain data.
Model Context Protocol (MCP) stdio server for the XChain Platform: read chain/token/balance data on BTC, LTC and DOGE (mainnet/testnet/regtest), and optionally submit policy-gated actions, backed by the XChain SDK.
sdk.send(), sdk.issue(), sdk.mint(), sdk.stake(), and 27 more convenience methodssdk.submitAction() handles the full encode -> sign -> broadcast -> wait pipeline in one callsdk.session(wif) bundles address/key/UTXO state for repeated actions from one addresssdk.estimateFees() returns fee info without signing or broadcastingsdk.issueAndDistribute(), sdk.deployAndFund(), sdk.stakeAndDelegate(), and moresdk.waitForAction(txid) resolves when the indexer processes a transactionsdk.waitForContractState(index, { key: 'status', equals: 'FUNDED' }) and sdk.waitForContractBalance(index, tick, { minQuantity }) wait on the contract's own state, which is the only signal that cannot race the indexer; submitAction({ awaitContract: {...} }) runs the same gate inline, so a deposit does not hand control back before the contract has been creditednpm run repl drops into a live session with a pre-configured SDK instanceawait sdk.batch().send({...}).mint({...}).build() (build() is async)onBlock(), onAction(), onAddress(), onToken(), onMarket(), onDispenser(), onBetFeed(), onXcall(), onAttestation(), and more; sdk.ws exposes the low-level client (subscribe(), on(), listSubscriptions(), ...) directlymessaging.send() accepts a Buffer payload and getMessages() exposes msg.bytes for binary ECIESsdk.gatedFile.encryptFileBytes() and sdk.gatedFile.encryptPack() produce AES-256-GCM ciphertext + key for FILE v1 gated content; key handoff as a compact 33-byte binary payload via serializeKeyPayload() / parseKeyPayload() (sent through ECIES in binary mode). See Token-Gated ContentAttestationHelpers.llm({...}) builds the JSON envelope a VM contract passes to xchain.attestation.request(...) with provider_id 'llm'; AttestationHelpers.httpGet({url}) validates the URL and returns the payload string for 'http_get'; AttestationHelpers.requestOptions({redundancy, deadlineBlocks}) builds the gateway options object. By design these are envelope builders only: there is no user-submittable ATTEST action. ATTEST v0 (request) and v1 (response) are VM-emitted: a contract calls xchain.attestation.request(...) and validators emit the on-chain attestation. So the SDK helps you shape the request a contract makes, and you read the results via getAttestations(). It does not (and cannot) encode an ATTEST action directly, the same way XCALL is VM-emission-only.ORDER/SWAP/DISPENSER v0 carry GIVE_OWNERSHIP / GET_OWNERSHIP flags; SWEEP carries independent ORDERS / SWAPS / DISPENSERS flags (was a single ESCROWS flag)X402Client and X402Gateway implement an XChain-native, x402-shaped pay-per-call flow over on-chain SEND actions, with xchain-send (pay-per-call), xchain-dispenser (hold-to-access), and xchain-deposit (metered spend ledger) schemes; the client pays only ticks given a per-tick maxAmount ceiling and refuses every offer when none is set. See x402 Paymentssession.stakeToContract({ amount, signingPubkey, targetContractIndex, tick }), session.unstakeFromContract({...}), and session.delegateForContract({...}) emit STAKE v3 / UNSTAKE v1 / DELEGATE v1 against a smart contract deployed via DEPLOY v1 (with COOLDOWN_BLOCKS + SLASH_DESTINATION). High-level recipes: sdk.deployStakeableContract() and sdk.stakeToContractAndDelegate()sdk.nft.unique(), sdk.nft.edition(), sdk.nft.collectionItem(), sdk.nft.attachContentParams(), and sdk.nft.isNft() for building the NFT pattern (ISSUE with DECIMALS=0 + LOCK_MAX_SUPPLY=1) plus high-level sdk.issueNft(), sdk.issueNftEdition(), sdk.issueCollectionItem(), and sdk.attachContent() submit recipessdk.project.rosterParams() and sdk.project.rosterEditParams() build LIST actions for owner-attested token rosters; sdk.setRoster() runs LIST then LINK and waits for the indexer^id wire form via the explorer before encoding to shrink on-chain payload size; opt out with { compactTickers: false }npx xchain-mcp exposes all explorer query tools as Model Context Protocol tools for AI agent usemeta: { name, description, version } (CONTRACT_META_REQUIRED). sdk.deploy(), session.deploy(), session.deployChunk(), sdk.deployAndFund() and sdk.deployStakeableContract() read it statically before the action is composed and refuse with the chain's own verdict string, so a contract the indexer will reject never costs a fee. sdk.contracts.getExportedMeta(source) exposes the same readRetry-After headersonRequest, onResponse, onError, onRetry callbacks.d.ts for IDE autocompleteFull SDK developer guide is published at docs.xchain.io/components/sdk:
npm install @dankest-llc/xchain-sdk
Node 22 or newer. For development against the source, clone this repository and npm install inside it; the companion MCP server for AI agents is published separately as xchain-mcp.
const { XChainSDK } = require('@dankest-llc/xchain-sdk');
// Zero-config: a network alone targets the public XChain Platform.
// Mainnet/testnet default to the public hosts (hub.xchain.io discovers
// explorer/encoder, falling back to explorer.xchain.io / encoder.xchain.io);
// on any *-regtest network only the explorer defaults to localhost:8080. The
// encoder (needed for writes) needs ENCODER_URL or ENCODER_PORT, and the
// WebSocket needs a WEBSOCKET_* or EXPLORER_* URL or port (or the matching
// constructor options).
const sdk = new XChainSDK({ network: 'bitcoin-mainnet' });
// To point at your own services, pass full URLs (include the scheme; a
// bare host is treated as http://host:<dev-port>):
// const sdk = new XChainSDK({
// network: 'bitcoin-mainnet',
// explorerUrl: 'https://explorer.example.com',
// encoderUrl: 'https://encoder.example.com'
// });
// Generate an action string
const result = await sdk.send({
tick: 'MYTOKEN',
amount: '100',
destination: 'bc1q...',
memo: 'Payment'
});
console.log(result.actionString); // 'SEND|0|MYTOKEN|100|bc1q...|Payment'
// Multi-destination SEND: one entry per recipient. The wire format version
// is chosen from the legs (v1 shared tick, v2 per-leg tick, v3 per-leg memo).
// A flat {tick, amount, destination} map can only ever express ONE leg, so
// the SDK refuses one against a multi-leg format instead of repeating leg 1.
const multi = await sdk.send({
tick: 'MYTOKEN',
legs: [
{ amount: '100', destination: 'bc1qaddr1...' },
{ amount: '250', destination: 'bc1qaddr2...' }
]
});
console.log(multi.actionString); // 'SEND|1|MYTOKEN|100|bc1qaddr1...|250|bc1qaddr2...'
// Full lifecycle: create, encode, sign, broadcast, wait for indexer
const tx = await sdk.submitAction(
{ action: 'SEND', params: { tick: 'MYTOKEN', amount: '100', destination: 'bc1q...' } },
{ pubkey: '02abc123...' },
{ wif: 'your-wif-key' }
);
console.log(tx.txid); // transaction hash
console.log(tx.indexed); // action data from the indexer
// Wallet session: bind to a key and send multiple actions
const session = sdk.session('your-wif-key');
await session.send({ tick: 'MYTOKEN', amount: '50', destination: 'bc1q...' });
await session.send({ tick: 'MYTOKEN', amount: '50', destination: 'bc1q...' });
const balances = await session.getBalances();
// Workflow recipes: multi-step operations in one call
await sdk.issueAndDistribute('your-wif-key',
{ tick: 'NEWTOKEN', maxSupply: '1000000', decimals: 8 },
[
{ destination: 'bc1qaddr1...', amount: '500000' },
{ destination: 'bc1qaddr2...', amount: '300000' }
]
);
// Deploy a smart contract. Every contract must export its identity: `meta.name`
// and `meta.description` are consensus-required (CONTRACT_META_REQUIRED), and
// `meta.version` is optional but indexed. Use STRING LITERALS: the chain evaluates
// `meta` at deploy, so a computed name is not what you read in the source, and the
// pre-flight cannot check it for you.
const code = `module.exports = {
meta: {
name: 'Escrow', // 1..64 bytes
description: 'Two-party escrow with an arbiter', // 1..512 bytes
version: '1.0.0' // optional, 1..32 bytes
},
permissions: ['SEND'],
initialize(xchain) { xchain.state.set('status', 'OPEN'); }
};`;
await session.deploy({ code, gasLimit: 200000 });
// A contract with no conforming meta is refused BEFORE anything is composed,
// signed or broadcast, with the exact verdict the indexer would have written:
// SDKContractError: invalid: CONTRACT_MANIFEST (meta required)
// Pass { preflight: 'warn' | 'off' } (session/workflow seams) or
// { lint: 'warn' | 'off' } (sdk.deploy) to downgrade or skip the check; the
// deploy is still rejected on-chain. A computed or unreadable `meta` only warns.
sdk.contracts.getExportedMeta(code); // { status: 'present', name: 'Escrow', ... }
// Query blockchain data. The token record arrives NESTED under `info`:
const token = await sdk.getToken('MYTOKEN');
token.info.tick_id; // '42' <- the fields live here
token.tick_id; // undefined
// A tick that does not exist answers HTTP 404, so getToken() THROWS
// SDKExplorerError (code EXPLORER_HTTP_404) instead of answering an empty
// body. Use these for an existence check rather than a try/catch:
await sdk.tokenExists('MYTOKEN'); // true / false, never throws on absence
await sdk.findToken('MYTOKEN'); // the unwrapped info record, or null
// Both answer "absent" only for the 404. A timeout, network failure, 429 or
// 5xx still throws, because an explorer that could not answer is not proof
// that the ticker is free.
npm run api (node ./src/api/index.js) runs the JSON-RPC server as a standalone process, opening a listener on SDK_API_PORT at load. A consumer that wants to own the server instead, mounting it under an existing express app, choosing its own listen path, or starting and stopping it from a test, requires the module directly rather than shelling out to the script:
const { createApp, startApi } = require('@dankest-llc/xchain-sdk/src/api');
// createApp(sdk) is synchronous and listener-free: it wires the same guard
// stack (rate limit, auth gate, batch cap, /openrpc.json, JSON-RPC router)
// as the CLI entry and returns the express app to mount yourself.
const app = createApp(sdk);
// startApi({ port }) builds the SDK from the environment, runs hub discovery,
// and resolves to the listening http.Server (port 0 for an ephemeral port).
const server = await startApi({ port: 0 });
await new Promise((resolve) => server.close(resolve));
Requiring src/api never opens a socket; only the CLI entry (npm run api / node ./src/api/index.js) starts listening automatically.
Copyright © 2025-2026 Dankest, LLC
Based on XChain Platform by Dankest, LLC – https://dankest.llc
Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0-or-later) with a commercial license available for proprietary use.
You may use, modify, and distribute this material under the terms of the License. See LICENSE and NOTICE for full terms. See the licensing overview.
Model Context Protocol (MCP) stdio server for the XChain Platform: read chain/token/balance data on BTC, LTC and DOGE (mainnet/testnet/regtest), and optionally submit policy-gated actions, backed by t
{ "mcpServers": { "xchain-mcp": { "command": "npx", "args": [ "-y", "[email protected]" ] } }}總覽
Model Context Protocol (MCP) stdio server for the XChain Platform: read chain/token/balance data on BTC, LTC and DOGE (mainnet/testnet/regtest), and optionally submit policy-gated actions, backed by the XChain SDK.
工具
尚無工具清單。遠端伺服器會在首次健康檢查後取得工具清單。
常見問題
在本頁複製適用於 Cursor、Claude Desktop、Claude Code 或 VS Code 的 stdio 設定。它使用發布者的安裝方式,而不是 PlugMCP 代理伺服器。
這筆記錄未列出必要的環境變數。
Xchain 透過 stdio 在本機執行。
上次檢查時間:2026-11-16。 Model Context Protocol (MCP) stdio server for the XChain Platform: read chain/token/balance data on BTC, LTC and DOGE (mainnet/testnet/regtest), and optionally submit policy-gated actions, backed by the XChain SDK.