SDK Reference

The Mycelium SDK provides class interfaces for orchestrating on-chain transactions, verifying signatures, interacting with contracts, and connecting models.

AgentContext

The central class coordinating connections to Soroban RPC endpoints, tracking account sequence numbers, and signing transactions. It can be constructed in multiple ways:

AgentContext( keypair_path: str = ".mycelium/wallet.json", network_type: str = "testnet", passphrase: str = None, dry_run: bool = False )

Creates a local signing context. If dry_run is true, state-changing calls are simulated and logged but never submitted to the ledger.

AgentContext.read_only(network_type: str = 'testnet') → AgentContext

Builds a wallet-free context using a temporary random keypair as the simulation source account. Perfect for read-only view function calls.

AgentContext.from_keypair(keypair_path: str, network: StellarNetwork | str) → AgentContext

Legacy back-compatibility constructor utilizing the StellarNetwork enum (TESTNET, MAINNET, LOCAL).

ctx.call_contract(contract_id: str, function_name: str, args: list, read_only: bool = False) → Any | TxResult

Invokes a Soroban contract. If read_only=True, it performs a ledger simulation returning the decoded Python value. If read_only=False, it simulates, prepares resource fees/footprints, signs, submits, and polls until settled, returning a TxResult.

Returnsdecoded value if read_only else TxResult(hash: str, status: str, return_value: Any)

ctx.acall_contract(contract_id: str, function_name: str, args: list, read_only: bool = False) → Awaitable[Any | TxResult]

Asynchronous wrapper around call_contract running the blocking sync logic in a background worker thread via asyncio.to_thread.

Typed Contract Client

Generate a typed contract client interface mapped directly to your on-chain contract specs:

python
client = ctx.contract("CCW...")

# Execute on-chain function (signed transaction)
tx = client.increment()

# Read-only method
count = client.read.get_count()

# Async calls
tx_async = await client.aio.increment()
count_async = await client.aio.read.get_count()

HiveClient

Used for interacting with the global Hive registry. Resolve agents, check reputation metadata, or update registration records.

HiveClient(context: AgentContext, registry_address: str = None)

Constructs a registry client. The registry_address parameter is optional and defaults to the HIVEMIND_REGISTRY_ADDRESS constant.

hive.register(unique_name: str, capability_tags: list[str], endpoint: str, model: str = '', role: str = '', desc: str = '') → TxResult

Encrypts/packs capability tags into a SHA-256 hash and registers agent endpoints, model, role, and description on-chain. Returns the TxResult.

hive.resolve_agent(unique_name: str) → dict

Queries the registry on-chain metadata map. Returns resolved public_key, capability_hash, endpoint string, model, role, desc, and reputation.

Returnsdict containing { public_key, capability_hash, endpoint, model, role, desc, reputation }

hive.discover_agents(start_ledger: int = None, resolve: bool = True) → list[dict]

Queries the historic registry registration events starting from start_ledger using RPC event filter loops (window size: 16,000, page limit: 100, max windows: 64) and builds an active list.

EscrowPaymentRouter

Create and manage escrow payment channels with conditional settlement releases. Deploys the escrow.wasm binary under the hood:

EscrowPaymentRouter(context: AgentContext)

Constructs the escrow router utilizing the provided signing context.

router.create_locked_escrow(provider_id: str, amount_xlm: Decimal, task_hash: bytes, token: str = None, timeout_seconds: int = 86400) → str

Deploys an escrow contract instance on-chain and locks amount_xlm of token (defaults to native XLM SAC CDLZFC3...) for provider_id. Returns the contract ID of the escrow.

router.release_funds(escrow_contract_id: str, verification_proof: bytes) → TxResult

Disburses the locked funds by invoking claim_funds with the preimage verification proof. Returns TxResult.

router.refund(escrow_contract_id: str) → TxResult

Reclaims depositor funds on an expired escrow after its deadline timeout has passed. Returns TxResult.

Agent Loop

Automate LLM agent loops using `run_agent_loop`, mapping Soroban methods directly to AI tool choices:

run_agent_loop(goal: str, *, context: AgentContext, provider: str = 'anthropic', model: str = None, api_key: str = None, contract_id: str = None, tools: list = None, hive: HiveClient = None, system: str = None, max_steps: int = 8, max_tokens: int = 16000) → str

Runs a multi-turn reasoning agent loop (Gemini uses automatic function calling, Anthropic uses manual Claude tool use loops) mapped to contract tools. Returns the final text response from the model.

python
from mycelium import run_agent_loop, ContractTool

result = run_agent_loop(
    goal="Ensure the counter shows at least 5",
    context=ctx,
    provider="gemini",
    contract_id="CCW...",
    tools=[
        ContractTool("increment", description="Add 1 to count"),
        ContractTool("get_count", read_only=True, description="Query count")
    ]
)

AI Adapters

Integrate Mycelium with popular AI frameworks:

Google Gemini

Uses plain Python callables with docstrings and type hints. Auto-routing is enabled by default:

python
from mycelium_sdk.adapters.gemini import make_contract_function

tool_fn = make_contract_function(
    ctx, "increment", "CCW..."
)
model = genai.GenerativeModel(
    "gemini-2.0-flash", 
    tools=[tool_fn]
)

LangGraph

Exposes contract functions as standard LangChain @tool definitions:

python
from mycelium_sdk.adapters.langgraph import make_contract_tool

lg_tool = make_contract_tool(
    ctx, "increment", "CCW..."
)
# Add directly to a LangGraph node

Wallet Encryption

Wallet keys are encrypted on disk using PBKDF2-HMAC-SHA256 (600,000 rounds, 16-byte random salt) and AES-256-GCM (12-byte random nonce / IV). Filesystem permissions are set to 0600. Private keys are loaded into volatile system memory only during signing and are cleared immediately after execution.

Mycelium v0.1.0-alpha · Stellar Testnet