Skip to main content

Mech Client

PyPI PyPI - Python Version PyPI - Wheel License Downloads

Sanity checks and tests Coverage flake8 mypy Black bandit

A client to interact with Mechs - AI agents providing services - on the Olas Marketplace. It allows users to post requests for AI tasks on-chain, and get their result delivered.

Requirements

  • Python >=3.10, <3.12 (Python 3.10 or 3.11)

Developing, running and deploying Mechs and Mech tools

The easiest way to create, run, deploy and test your own Mech and Mech tools is to follow the Mech and Mech tool docs here. The Mech tools dev repo used in those docs greatly simplifies the development flow and dev experience.

Only continue reading this README if you know what you are doing and you are specifically interested in this repo.

Quickstart Guide

For a fast and straightforward setup, follow the instructions provided on the website here. This guide will walk you through the essential steps to get up and running without requiring an in-depth understanding of the system.

Installation

Find the latest available release on PyPi.

We recommend that you create a virtual Python environment using uv. Set up your virtual environment as follows:

uv init my_project
cd my_project
uv add mech-client

Alternatively, you can also install the Mech Client in your local Python installation:

pip install mech-client

If you require to use the Mech Client programmatically, please see this section below.

CLI Usage

Display the available options:

mechx --help
Usage: mechx [OPTIONS] COMMAND [ARGS]...

  Command-line tool for interacting with AI Mechs on-chain.

  Mech Client enables you to send AI task requests to on-chain AI agents
  (mechs) via the Olas (Mech) Marketplace. Supports multiple payment methods,
  tool discovery, and both agent mode (Safe multisig) and client mode (EOA).

Options:
  --version      Show the version and exit.
  --client-mode  Enables client mode (EOA-based). Default is agent mode (Safe-
                 based).
  --help         Show this message and exit.

Commands:
  deposit       Manage prepaid balance deposits.
  ipfs          IPFS utility operations.
  mech          Manage and query AI mechs on the marketplace.
  request       Send an AI task request to a mech on-chain.
  setup         Setup agent mode for on-chain interactions via Safe...
  subscription  Manage Nevermined (NVM) subscriptions.
  tool          Manage and query mech tools.

Mech Marketplace

Learn more about mech marketplace here

Terms

Each Mech is run by its own operator.

Mechs operated by Valory are subject to the Valory Mech Terms. When you send a request to one, mechx request states this before anything is signed. For a Mech run by someone else, or one the check could not identify, it shows the terms link that Mech's operator published, as published: those terms are that operator's to state, not ours. A check that could not complete is logged as a warning. The terms link a Mech publishes in the termsUrl field of its on-chain metadata is shown in the Terms column of mechx mech list, as published and not endorsed, when it is a plain https link.

Checking who operates a Mech. Valory creates one DNS record under mech.valory.xyz for each Mech it operates, so a Mech is operated by Valory if its own name there resolves. The name is the Mech address without 0x, a hyphen, then the chain id:

dig +short c05e7412439bd7e91730a6880e18d5d5873f632c-100.mech.valory.xyz

An address back means Valory operates that Mech, and no such name means it does not. The answer does not depend on the Mech being up. If a name you make up at random also resolves, the zone is answering every name and the result tells you nothing; mechx checks for this and treats it as a no. A lookup that fails or times out is also a no, and mechx logs a warning so it is not mistaken for a real answer. mechx mech list runs the check for you and marks the confirmed ones in its Operator column.

The check trusts your DNS resolver. The lookup is not DNSSEC-validated, so a resolver or network that forges the answer for that one name could make a Mech look Valory operated.

Who runs a Mech, and how it has behaved

Before paying a Mech you can ask who runs it and what its record is:

mechx mech info --chain-config gnosis --address 0xc05e7412439bd7e91730a6880e18d5d5873f632c

The report is built from the Mech's published manifest and the marketplace subgraph, and it fails closed: a manifest that cannot be read gives no report rather than a partial one, and anything not verified says so.

  • Operator. The manifest may name its operator (operator.domain and operator.name). The domain is the identity: it is marked verified only when https://<domain>/.well-known/agent-registration.json lists the Mech's ERC-8004 agent id for the chain's identity registry. The name is never checked and is reported as claimed_name, the operator's own words, so a verified valory-mechs.xyz calling itself "Valory AG" proves only the domain. The agent id comes from the service registry subgraph; it is not the Olas service id except by coincidence. The manifest must name the exact host that serves the proof: redirects are not followed, so a domain that redirects, as valory.xyz does to www.valory.xyz, is reported as redirecting and stays unverified. A proof that cannot be fetched leaves the domain unverified, with the reason, and is fetched again next time rather than remembered as a no. The domain must be a bare lowercase hostname and every link an https URL with a host, or the field is treated as unpublished.
  • Benchmarks. Each tool may carry a benchmark link (toolMetadata.<tool>.benchmark.url). The report passes the link on as the operator's claim. It never shows a figure, checked or not.
  • Delivery record. receivedRequests, selfDeliveredFromReceived and deliveredByOthersFromReceived from the marketplace subgraph, plus the Mech's age from its creation block. The counters cover requests made on-chain and off-chain requests the Mech settled on-chain, and cannot be split by path. An off-chain request that was never delivered appears nowhere on-chain.
  • Payment. The payment method (native, OLAS, USDC, or a subscription), with no price. The Mech contract quotes the charge at request time, and its maximum delivery rate is only a ceiling a Mech may charge less than.

mechx mech info prints the report as JSON. For library users, ToolManager.mech_report(mech_address, metadata) returns the same report as data, a superset of terms_report. ToolManager.mech_report_or_terms(mech_address, metadata) is the one to call before paying: it falls back to the terms alone, with report_note, when the manifest or the Mech's record cannot be read. The subgraph reads a report makes time out after 10 seconds each, and each read of the domain proof after 5.

Gnosis, Optimism and Robinhood have registry defaults. Base and Polygon require MECHX_REGISTRY_BASE_SQUID_URL / MECHX_REGISTRY_POLYGON_SQUID_URL. MECHX_REGISTRY_SUBGRAPH_URL overrides the endpoint but not its configured dialect.

Supported Chains

Supported chains: gnosis, base, polygon, optimism, robinhood

All commands require --chain-config with one of these five chain names.

Chain Marketplace Agent Mode Native Payment NVM Subscriptions OLAS Payments USDC Payments
Gnosis ✅ ✅ ✅ ✅ ✅ ❌
Base ✅ ✅ ✅ ✅ ✅ ✅
Polygon ✅ ✅ ✅ ❌ ✅ ✅
Optimism ✅ ✅ ✅ ❌ ✅ ✅
Robinhood ✅ ✅ ✅ ❌ ❌ ✅ (USDG)

Notes:

  • Marketplace: Chains with marketplace contracts deployed. All supported chains have marketplace support.
  • Agent Mode: Gnosis, Base, Polygon, Optimism and Robinhood support on-chain agent registration via setup.
  • Native Payment: Chains that support deposit native command for prepaid native token deposits.
  • NVM Subscriptions: Chains that support subscription purchase command for Nevermined subscription-based payments (Gnosis, Base only).
  • OLAS/USDC Payments: Chains that support deposit token command with OLAS or USDC tokens. On Robinhood the USDC payment type uses USDG, so --token-type usdc deposits USDG.
  • Subgraph: Gnosis, Optimism and Robinhood have default indexer URLs; Base and Polygon require MECHX_MARKETPLACE_BASE_SQUID_URL / MECHX_MARKETPLACE_POLYGON_SQUID_URL. Robinhood's is the marketplace squid (SQD), which takes a different query syntax that mech-client handles for you. The MECHX_SUBGRAPH_URL environment variable is optional and only needed to override defaults.

Set up agent mode for on-chain interactions

There are two modes you can use the mechx for on-chain interactions. Currently agent-mode is supported on Gnosis, Base, Polygon, Optimism and Robinhood.

  • agent mode (Recommended): This allows to register your on-chain interactions as agent on the olas protocol and allows for A2A activity to be reflected on the client
  • client mode: Simple on-chain interations using EOA
cp .example.env .env

📝 For better reliability, it is recommended to use a stable third-party RPC provider.

mechx setup --chain-config <chain_config>

⚠️ Note: Run setup for each chain you interact with, and ensure your .env file has the correct RPC endpoint.

Generate Mech requests

List marketplace mechs

To list the top marketplace mechs based on deliveries, use the mech list command. You can specify the chain you want to query. Please note that only the first 20 mechs sorted by number of deliveries will be shown.

Note: Gnosis, Optimism and Robinhood have default indexer URLs; Base and Polygon require MECHX_MARKETPLACE_BASE_SQUID_URL / MECHX_MARKETPLACE_POLYGON_SQUID_URL (on Robinhood, the marketplace squid). You can optionally override the default by setting:

export MECHX_SUBGRAPH_URL=<your-custom-subgraph-url>

Supported marketplace chains: gnosis, base, polygon, optimism

mechx mech list --chain-config gnosis

You can also find available Mechs here

Usage

The basic usage of the Mech Client is as follows.

mechx request --prompts <prompt> --priority-mech <priority mech address> --tools openai-gpt-3.5-turbo --chain-config <chain_config>

The Mech Client can also be used to send batch requests. There are couple of different ways to achieve this:

mechx request --prompts={<prompt-1>,<prompt-2>} --priority-mech <priority mech address> --tools={<tool-1>,<tool-2>} --chain-config <chain_config>

or

mechx request --prompts <prompt-1> --prompts <prompt-2> --priority-mech <priority mech address> --tools <tool-1> --tools <tool-2> --chain-config <chain_config>

Additionally other options are available and their usage is listed below:

--use-prepaid <bool>: use the prepaid method to send requests to a Mech via the Mech Marketplace. Defaults to False.
--use-offchain <bool>: use the off-chain method to send requests to a Mech via the Mech Marketplace. Defaults to False.

Understanding Payment Types

Important: The payment type is determined by the mech's smart contract, not by the user. When you send a request, the client automatically detects the mech's payment type and handles the appropriate payment flow.

There are 5 payment types supported:

Payment Type Description Payment Method
NATIVE Per-request native token payment Sends native tokens (xDAI, ETH, MATIC) with transaction
OLAS_TOKEN Per-request OLAS token payment Approves & transfers OLAS tokens
USDC_TOKEN Per-request USDC token payment Approves & transfers USDC tokens
NATIVE_NVM NVM subscription with native token Validates subscription NFT (no per-request payment)
TOKEN_NVM_USDC NVM subscription with USDC token Validates subscription NFT (no per-request payment)

How it works:

  1. Request command detects mech's payment type - The client queries the mech's contract to determine how it accepts payment
  2. Client handles payment automatically - Based on the payment type, the client either:
    • Sends native tokens with the transaction (NATIVE)
    • Approves and transfers ERC20 tokens (OLAS_TOKEN, USDC_TOKEN)
    • Validates your subscription NFT (NATIVE_NVM, TOKEN_NVM_USDC)
  3. You can use prepaid balance - With --use-prepaid flag, the marketplace deducts from your prepaid balance instead of per-request payment (works for non-subscription mechs)

Payment flow examples:

# NATIVE payment mech (detected automatically)
mechx request --prompts "test" --tools openai-gpt-4 --chain-config gnosis
# → Sends xDAI with transaction

# OLAS_TOKEN payment mech (detected automatically)
mechx request --prompts "test" --tools openai-gpt-4 --chain-config gnosis
# → Approves OLAS → Sends request

# Using prepaid balance (any non-subscription mech)
mechx request --prompts "test" --tools openai-gpt-4 --use-prepaid --chain-config gnosis
# → Deducts from prepaid balance

# NVM subscription mech (detected automatically)
# First purchase subscription:
mechx subscription purchase --chain-config gnosis
# Then make unlimited requests:
mechx request --prompts "test" --tools openai-gpt-4 --chain-config gnosis
# → Validates subscription NFT
Prepaid Requests

You can deposit funds to your prepaid balance on the marketplace, then use --use-prepaid flag to pay from this balance instead of per-request payments. This works for non-subscription mechs only.

Deposit native tokens (for NATIVE payment mechs):

mechx deposit native <amount> --chain-config <chain_config>

Deposit ERC20 tokens (for OLAS_TOKEN or USDC_TOKEN payment mechs):

# Deposit OLAS tokens (amount in wei, 18 decimals)
mechx deposit token <amount> --chain-config <chain_config> --token-type olas

# Deposit USDC tokens (amount in smallest unit, 6 decimals)
mechx deposit token <amount> --chain-config <chain_config> --token-type usdc

Note: The --token-type parameter is required and must be explicitly specified.

NVM Subscriptions (for NATIVE_NVM or TOKEN_NVM_USDC payment mechs):

For mechs using NVM subscriptions, purchase a subscription upfront to enable unlimited requests during the subscription period:

mechx subscription purchase --chain-config <chain_config>

After purchasing, you can make requests without per-request payments. The marketplace validates your subscription NFT automatically.

⚠️ To ensure optimal performance and reliability when using subscription purchase, it is advisable to use a custom RPC provider as public RPC endpoints may be rate-limited or unreliable under high usage. You can configure your custom RPC URL in your environment variables using

export MECHX_CHAIN_RPC=
Offchain Requests

The offchain URL is automatically discovered from the mech's on-chain metadata. No additional configuration is required — simply use the --use-offchain flag:

mechx request --prompts "test" --tools openai-gpt-4 --use-offchain true --chain-config gnosis

The client queries the mech's ComplementaryServiceMetadata contract to find the url field published by the mech operator, then sends requests to that endpoint.

List tools available for a mech

To list the tools available for a specific marketplace mech, use the tool list command. You can specify an AI Agent ID to get tools for a specific mech.

mechx tool list 1722 --chain-config gnosis
You will see an output like this:
+---------------------------------------------+-----------------------------------------------+
| Tool Name                                   | Unique Identifier                             |
+=============================================+===============================================+
| claude-prediction-offline                   | 1722-claude-prediction-offline                |
+---------------------------------------------+-----------------------------------------------+
| claude-prediction-online                    | 1722-claude-prediction-online                 |
+---------------------------------------------+-----------------------------------------------+
| deepmind-optimization                       | 1722-deepmind-optimization                    |
+---------------------------------------------+-----------------------------------------------+

Get Tool Description

To get the description of a specific tool, use the tool describe command. You need to specify the unique identifier of the tool.

mechx  tool describe <unique_identifier> --chain-config <chain_config>

Example usage:

mechx  tool describe 1722-openai-gpt-4 --chain-config gnosis

You will see an output like this:

Description for tool 1722-openai-gpt-4: Performs a request to OpenAI's GPT-4 model.

Get Tool Input/Output Schema

To get the input/output schema of a specific tool, use the tool schema command. You need to specify the unique identifier of the tool.

mechx tool schema <unique_identifier> --chain-config <chain_config>

Example usage:

mechx tool schema 1722-openai-gpt-4 --chain-config gnosis

You will see an output like this:

Tool Details:
Tool Details:
+------------------------+---------------------------------------------+
| Tool Name              | Tool Description                            |
+========================+=============================================+
| OpenAI Request (GPT-4) | Performs a request to OpenAI's GPT-4 model. |
+------------------------+---------------------------------------------+
Input Schema:
+-------------+-----------------------------------------------+
| Field       | Value                                         |
+=============+===============================================+
| type        | text                                          |
+-------------+-----------------------------------------------+
| description | The request to relay to OpenAI's GPT-4 model. |
+-------------+-----------------------------------------------+
Output Schema:
+-----------+---------+-----------------------------------+
| Field     | Type    | Description                       |
+===========+=========+===================================+
| requestId | integer | Unique identifier for the request |
+-----------+---------+-----------------------------------+
| result    | string  | Response from OpenAI              |
+-----------+---------+-----------------------------------+
| prompt    | string  | User prompt to send to OpenAI     |
+-----------+---------+-----------------------------------+

Set up the EOA and private key

To use the Mech Client using client mode, you need an EOA account and its associated private key stored in a text file ethereum_private_key.txt. You can set it up in two ways:

  • Use any software of your choice (e.g., Metamask) and copy the private key:

    echo -n YOUR_PRIVATE_KEY > ethereum_private_key.txt
    

    Do not include any leading or trailing spaces, tabs or newlines, or any other character in the file ethereum_private_key.txt.

  • Alternatively, use the Open AEA command generate-key (you'll need to install Open AEA and its Ethereum ledger plugin):

    aea generate-key ethereum
    

    and display the corresponding EOA:

    python -c "from web3 import Web3; print(Web3().eth.account.from_key(open('ethereum_private_key.txt').read()).address)"
    

The EOA you use must have enough funds to pay for the Mech requests, or alternatively, use a Nevermined subscription.

⚠️ Warning

  • If the generated EOA account is for development purposes, make sure it does not contain large amounts of funds.

  • If you store the key file in a local Git repository, we recommend that you add it to .gitignore in order to avoid publishing it unintentionally:

    echo ethereum_private_key.txt >> .gitignore
    

To use client-mode for cli commands, simply supply --client-mode flag before the cli commands.

mechx --client-mode <rest of the cli command>

✏️ Note
> If you encounter an "Out of gas" error when executing the Mech Client, you will need to increase the gas limit, e.g.,

export MECHX_GAS_LIMIT=200000

Chain configuration

Default configurations for different chains are stored in the file configs/mechs.json. If --chain-config parameter is not specified, the Mech Client will choose the first configuration on the JSON.

Additionally, you can override any configuration parameter by exporting any of the following environment variables:

MECHX_CHAIN_RPC
MECHX_SUBGRAPH_URL
MECHX_GAS_LIMIT
MECHX_TRANSACTION_URL

MECHX_LEDGER_CHAIN_ID
MECHX_LEDGER_POA_CHAIN
MECHX_LEDGER_DEFAULT_GAS_PRICE_STRATEGY
MECHX_LEDGER_IS_GAS_ESTIMATION_ENABLED

Programmatic usage

You can also use the Mech Client as a library on your Python project.

  1. Set up the private key as specified above. Store the resulting key file (e.g., ethereum_private_key.txt) in a convenient and secure location.

  2. Create Python script my_script.py:

    touch my_script.py
    
  3. Edit my_script.py as follows:

    import json
    
    from mech_client.services import MarketplaceService
    from mech_client.domain.payment import PaymentType
    from mech_client.infrastructure.config import get_mech_config
    from aea_ledger_ethereum import EthereumApi, EthereumCrypto
    
    # Configuration
    PRIORITY_MECH_ADDRESS = "0x77af31De935740567Cf4fF1986D04B2c964A786a"
    PROMPT_TEXT = "Will Gnosis pay reach 100k cards in 2024?"
    TOOL_NAME = "openai-gpt-4o-2024-05-13"
    CHAIN_CONFIG = "gnosis"
    MODE = "client"  # Use "agent" for agent mode (Safe multisig)
    SAFE_ADDRESS = ""  # Required if MODE is "agent"
    
    # Setup ledger and crypto
    config = get_mech_config(CHAIN_CONFIG)
    crypto = EthereumCrypto("ethereum_private_key.txt")
    ledger_api = EthereumApi(**config.ledger_config.__dict__)
    
    # Create service
    service = MarketplaceService(
        chain_config=CHAIN_CONFIG,
        ledger_api=ledger_api,
        payer_address=crypto.address,
        mode=MODE,
        safe_address=SAFE_ADDRESS if MODE == "agent" else None,
    )
    
    # Send request
    result = service.send_request(
        priority_mech=PRIORITY_MECH_ADDRESS,
        tools=[TOOL_NAME],
        prompts=[PROMPT_TEXT],
        payment_type=PaymentType.NATIVE,  # or PaymentType.TOKEN, PaymentType.NATIVE_NVM
    )
    
    print(f"Transaction hash: {result['tx_hash']}")
    
    # `deliveries` maps each request ID to a DeliveryResult: `.data` is the
    # parsed content the mech delivered, `.url` the IPFS URL it was read from.
    # Same shape whether delivery was on-chain or off-chain.
    for request_id, delivery in result["deliveries"].items():
        print(f"Request {request_id}: {delivery.url}")
        payload = delivery.data
        if payload is None:
            print("  result file could not be read")
            continue
        # Mechs typically put the answer in a `result` field, JSON-encoded as a
        # string. That is a convention rather than a guarantee, so fall back to
        # the payload itself for tools that do not follow it.
        answer = payload.get("result") if isinstance(payload, dict) else None
        print(f"  {json.loads(answer) if isinstance(answer, str) else payload}")
    

    Note: See docs/ARCHITECTURE.md for architecture details and more examples.

Using an external signer (no private key in-process)

If key custody lives outside your process (e.g., a local signer service that only exposes sign/send capabilities over an API), implement the Signer protocol and pass it as signer= instead of crypto=. The raw private key never enters the mech-client process:

from mech_client import MarketplaceService, Signer


class MySigner:
    """Adapter for an external signer service (satisfies the Signer protocol)."""

    address = "0xYourEOA..."  # the EOA the service signs for

    def send_transaction(self, unsigned_tx: dict) -> str:
        # Forward to your signer service; it fills nonce/gas if absent,
        # signs, broadcasts, and returns the tx hash.
        ...

    def sign_message(self, message: bytes) -> bytes:
        # Sign the raw 32-byte digest directly (no EIP-191 prefix) and
        # return the 65-byte signature. See Signer.sign_message docs.
        ...


signer: Signer = MySigner()  # structural typing — no inheritance needed

service = MarketplaceService(
    chain_config="gnosis",
    agent_mode=False,  # agent mode (Safe) is supported too
    signer=signer,
)

This works for on-chain requests (client and agent mode), deposits (DepositService), and offchain prepaid requests. In agent mode the Safe transaction is approved via the pre-validated signature encoding, so only ordinary transaction signing is required from the signer. Passing crypto= keeps working unchanged (it wraps the key in the default LocalSigner).

Choosing offchain nonces

A caller that tracks its own marketplace nonces (e.g. to keep several offchain requests from one requester in flight) can pass them, and see each request id before it is signed:

from mech_client import OffchainRequestRejected

def approve(request_id: bytes, nonce: int) -> None:
    ...  # raise to stop this request before it is signed

try:
    result = await service.send_request(
        prompts=("What is 2+2?",),
        tools=("openai-gpt-4o-2024-05-13",),
        use_offchain=True,
        nonces=[next_nonce],
        on_request_id=approve,
        extra_attributes={"nonce": salt},
    )
    print(result["nonces"])
except OffchainRequestRejected as e:
    ...

OffchainTopUpFailed means the auto top-up after the mech's 402 failed on your side, so the request was not accepted. The hook gets the raw 32-byte request id; request_ids and OffchainRequestRejected.request_id are hex strings. The mech accepts only the requester's next nonce, so requests must reach it in nonce order. A transport error stays a plain ValueError: whether the mech stored the request is unknown.

extra_attributes["nonce"] is unrelated to the marketplace nonce: it fixes the metadata salt, which is otherwise random. A resend signs the same request id only with the same salt, prompt, tool, marketplace nonce, mech, rate and requester.

The request id that is hooked, signed and sent is always derived locally from the marketplace's domainSeparator() (mech_client.request_digest). getRequestId is still called over the RPC as a cross-check; if it answers anything else, RequestIdMismatch (a ValueError with expected, reported and nonce) is raised before on_request_id and before signing, so a lying RPC can only cause a refusal.

Allocating offchain nonces

mapNonces(requester) only moves when a delivery settles, and the mech admits only the requester's next slot (mapNonces + accepted + settling). NonceAllocator keeps that queue for you, one per requester and chain, and only one allocator may use a store at a time, across processes too (it locks mech_nonces.lock and refuses a second one as mech-queue-locked until the first is closed or its process exits; a closed allocator refuses as mech-queue-closed and writes nothing): one mech in flight, requests posted in nonce order, a slot held until mapNonces passes it. One mech in flight is forced by settlement, which rebuilds every id from one counter per requester: while one mech holds a slot, a request to another mech waits, and is refused as mech-in-flight when its wait runs out, so a requester whose traffic to one mech never pauses cannot reach a second mech; treat mech-in-flight as back off and retry. It persists its slots in mech_nonces.json under the directory you give it (created if missing), fsynced before each POST, so a restart never reissues a held nonce; a store that cannot be read or written refuses requests (mech-queue-unreadable, mech-queue-unwritable).

import asyncio
from pathlib import Path

from mech_client import NonceAllocator, NonceRefused, send_with_nonce
from mech_client.domain.delivery import OffchainDeliveryWatcher

allocator = NonceAllocator(Path("~/.my-app").expanduser(), settle_timeout=1800, gap_retries=3)
contract = service.marketplace_contract()
sender = service.requester()  # the Safe in agent mode, else the signer's EOA, as send_request signs

def send(nonce: int, hook):
    # The queue lock is held until send returns, so keep the delivery wait
    # short here and watch for the delivery outside the allocator.
    return asyncio.run(service.send_request(
        prompts=(prompt,), tools=(tool,), priority_mech=mech, use_offchain=True,
        nonces=[nonce], on_request_id=hook, extra_attributes={"nonce": salt},
        max_price=cap, timeout=1,
    ))

try:
    result = send_with_nonce(
        allocator, chain="gnosis", sender=sender, mech=mech, salt=salt,
        read_map_nonces=lambda: contract.functions.mapNonces(sender).call(),
        send=send, not_sent=(), timeout=60,
    )
except NonceRefused as e:
    print(e.rule, e)  # one of the RULE_* constants, e.g. RULE_IN_FLIGHT, RULE_NONCE_GAP
else:
    # Outside the lock: the next request from this requester can go out now.
    url = service.tool_manager.get_offchain_url(service.mech_info(mech).service_id)
    deliveries = asyncio.run(OffchainDeliveryWatcher(url, timeout=300).watch(result["request_ids"]))
    allocator.delivered("gnosis", sender, [
        n for rid, n in zip(result["request_ids"], result["nonces"]) if rid in deliveries
    ])

The allocator's lock covers whatever send does, so send should only send. send(nonce, hook) must pass hook (a PreSignHook) to send_request as on_request_id; a caller's own pre-sign hook goes to send_with_nonce(on_request_id=...), which runs it inside hook. send_request calls the hook's mark_received() on entry and mark_posting() right before the POST, after signing: a failure after it was received but before posting (an unknown tool, a missing offchain URL, an RPC error, a refused or async hook, a signer error) reached no mech and frees the nonce. If send never passes the hook on, nothing tells those failures apart, so a failure holds the nonce as unknown and is logged. A 503 resends the same nonce and id up to gap_retries times. outcome_of(error) maps OffchainRequestRejected / OffchainTopUpFailed to what the answer means for the nonce: retry (503), taken (the 401 for a stale or duplicate nonce), not_accepted (any other 4xx but 401, or a failed top-up) or unknown (any other 401, and other 5xx). A slot is freed only when nothing left the process for it: a request that was posted keeps its nonce held until mapNonces passes it whatever the answer, so a not_accepted rejection or a failed top-up after the POST is refused as mech-request-rejected with the nonce held as unknown. The one exception is a 503 that still stands after gap_retries resends, which frees the nonce, because the mech admitted nothing. A Reservation you drive yourself is answered once, with a terminal outcome: answering retry leaves it open for the resend's answer. answered(outcome, mech=..., salt=..., posted=...) requires posted, whether the request's payload left the process, so an answer cannot free a posted slot by leaving it out: with posted=True, not_accepted holds the nonce. A taken with no slot of ours keeps the answering mech in flight at that nonce until mapNonces passes it. send_with_nonce sends a new request, never a held one: the store keeps a held slot's salt, not its prompt or tool, so a stalled queue's probe has its own id. An exception listed in not_sent (a failure that reached no mech) frees the nonce only when the hook is not posting; once posting, it and any other failure hold the nonce as unknown, a warning names the nonce and its queue, and the exception is re-raised as itself, so a caller classifying by type still can. Call allocator.delivered(chain, sender, nonces) when deliveries arrive. A slot's settle_timeout counts from its delivery, or, when no delivery was seen, from the end of the request's response timeout; a slot mapNonces has not passed by then stalls the queue, which then only probes at mapNonces until one is accepted. Once that probe is accepted, or answered taken over a slot of ours that is not itself overdue (the mech holds that request, and mapNonces has moved on to it), the stall clears and the later slots' settle clocks restart. A taken over the overdue slot mapNonces is stuck on leaves the stall and its clock as they are, so hard_cancel becomes allowed. An on-chain request from the same requester goes inside allocator.exclusive(...). As a last resort, allocator.hard_cancel(chain, sender, read_map_nonces, stalled_for=...) yields mapNonces for one on-chain request once the queue has been stalled (stalled_since) at least that long, and restarts the stall clock (and the later slots' settle clocks) when it exits, so each cancel needs its own window; you decide who confirms that payment.

Price cap, mech info and RPC

  • send_request(..., max_price=p) raises MechPriceExceeded (price, max_price) before any deposit, signature or POST when the mech's max_delivery_rate times the number of prompts exceeds p, in the payment asset's base units. It also bounds the call's auto-deposits after a 402, on top of the ratio bound below: together they never exceed p, counting what earlier send_with_nonce resends of the same request deposited, and a shortfall that would take them past p raises OffchainTopUpFailed before that deposit is sent. With max_price=None an auto-deposit is bounded only by _MAX_AUTO_DEPOSIT_RATIO times the mech's max_delivery_rate.
  • service.mech_info(mech) returns MechInfo(mech, service_id, payment_type, max_delivery_rate); service.marketplace_contract() returns the marketplace contract, and service.requester() the requester of record.
  • payment_token(payment_type, chain) names the token a mech is paid in (None for native), and balance_tracker(chain, payment_type) the tracker a prepaid top-up pays (None for NVM subscriptions). Both use the chain id payments use, MECHX_LEDGER_CHAIN_ID included, and raise ValueError for an unknown chain or a token or tracker not deployed on it.
  • MarketplaceService, DepositService, SubscriptionService, ToolService and ToolManager take rpc_url=... (a blank one is refused), so a process can talk to several chains without setting the process-wide MECHX_CHAIN_RPC. Left out, the RPC comes from MECHX_CHAIN_RPC, then the operate config (agent mode), then the default.

Offchain capability and chat

ToolManager.read_tools_metadata(service_id) returns MetadataRead(document, error) and never raises for an unreadable document (a gateway error status, or a chain with no metadata contract, is a cause too; causes are redacted). A MetadataRead holds exactly one of the two (MetadataRead.ok(document), MetadataRead.failed(error)). offchain_blocker(read) gives a short reason, naming the cause, why a mech cannot take offchain requests, or None.

For chat tools the prompt is an OpenAI-style messages list as JSON (is_chat_prompt(prompt)), and chat_report(delivery) returns {"completion", "usage"} from a delivery, or None; None also covers a delivery that could not be fetched, so check delivery.data first to tell the two apart.

You can also use the Mech Client to programmatically fetch tools for marketplace mechs in your Python project, as well as retrieve descriptions and input/output schemas for specific tools given their unique identifier.

  1. Set up the private key as specified above. Store the resulting key file (e.g., ethereum_private_key.txt) in a convenient and secure location.

  2. Create a Python script fetch_tools_script.py:

    touch fetch_tools_script.py
    
  3. Edit fetch_tools_script.py as follows:

    from mech_client.services import ToolService
    from mech_client.infrastructure.config import get_mech_config
    from aea_ledger_ethereum import EthereumApi
    
    # Configuration
    service_id = 1722  # Specify the service ID
    chain_config = "gnosis"  # Specify the chain configuration
    
    # Setup ledger API
    config = get_mech_config(chain_config)
    ledger_api = EthereumApi(**config.ledger_config.__dict__)
    
    # Create tool service
    tool_service = ToolService(
        chain_config=chain_config,
        ledger_api=ledger_api,
    )
    
    # Fetch tools for a specific marketplace mech
    tools = tool_service.list_tools(service_id=service_id)
    print(f"Tools for marketplace mech {service_id}:")
    for tool_name, tool_id in tools:
        print(f"  {tool_name}: {tool_id}")
    
    # Get description for a specific tool
    tool_name = "openai-gpt-4o-2024-05-13"  # Example tool name
    unique_identifier = f"{service_id}-{tool_name}"  # Format: serviceId-toolName
    
    description = tool_service.get_description(unique_identifier)
    print(f"\nDescription for {unique_identifier}:")
    print(f"  {description}")
    
    # Get input/output schema for a specific tool
    tools_info = tool_service.get_tools_info(service_id)
    input_schema = tool_service.format_input_schema(tools_info["input"])
    output_schema = tool_service.format_output_schema(tools_info["output"])
    
    print(f"\nInput schema: {input_schema}")
    print(f"Output schema: {output_schema}")
    

    Note: This example demonstrates the service-based API introduced in v0.17.0.

Architecture & Documentation

Architecture Overview

Version 0.17.0 introduced a comprehensive architectural refactoring that separates concerns into distinct layers:

┌──────────────────────────────────────┐
│         CLI Layer                    │  User interface & command routing
├──────────────────────────────────────┤
│         Service Layer                │  Business workflow orchestration
├──────────────────────────────────────┤
│         Domain Layer                 │  Core business logic & strategies
├──────────────────────────────────────┤
│      Infrastructure Layer            │  External system adapters
└──────────────────────────────────────┘

Key improvements:

  • ✅ Separation of concerns: Each layer has a specific responsibility
  • ✅ Strategy pattern: Flexible payment, execution, and delivery strategies
  • ✅ Dependency injection: Better testability and modularity
  • ✅ Type safety: Comprehensive type hints throughout
  • ✅ Comprehensive tests: 288 unit tests with ~50% coverage

Documentation

For detailed information about the architecture and development:

  • docs/ARCHITECTURE.md - Comprehensive architecture guide

    • Layer descriptions and responsibilities
    • Data flow diagrams
    • Key patterns (Factory, Strategy, Repository)
    • Component reference
    • Best practices
  • docs/TESTING.md - Testing guide for contributors

    • Test structure and organization
    • Running tests and coverage reports
    • Writing tests (patterns, fixtures, mocking)
    • Testing async components
    • Best practices
  • CLAUDE.md - Development guidelines for Claude Code

    • Command dependency diagrams
    • Common issues and solutions
    • Environment variables reference
    • Development commands

For Library Users

If you use mech-client as a library (not just the CLI), see:

For Contributors

If you want to contribute to mech-client development:

  1. Read docs/ARCHITECTURE.md to understand the structure
  2. Follow docs/TESTING.md for writing tests
  3. Review CLAUDE.md for development guidelines
  4. See Developer installation below

Developer installation

To setup the development environment for this project, clone the repository and run the following commands:

uv sync
source .venv/bin/activate

Release guide

  • Bump versions in pyproject.toml.mech_client/__init__.py and SECURITY.md
  • uv lock
  • rm -rf dist
  • autonomy packages sync --update-packages
  • make dist
  • Then, create a release PR and tag the release.

FAQ

On which chains are AI Mechs deployed?

The Mech repository contains the latest information on deployed Mechs.

Are AI Mechs deployed on testnets?

No. AI Mechs are currently deployed only on mainnets.

Where can I find the agent blueprint ID?

You can find the agent blueprint IDs for each chain on the Marketplace or on the Mech repository.

How do I access an AI Mech on a different chain?

Use the --chain-config <name> parameter together with a valid --priority-mech address, for example:

mechx request --prompts "write a short poem" --priority-mech 0x77af31De935740567Cf4fF1986D04B2c964A786a --key ./ethereum_private_key.txt --tools openai-gpt-4o-2024-05-13 --chain-config gnosis

Base and Polygon Marketplace squid configuration

Set MECHX_MARKETPLACE_BASE_SQUID_URL and MECHX_MARKETPLACE_POLYGON_SQUID_URL in the runtime environment. Both chains now use the squid query dialect. MECHX_SUBGRAPH_URL remains the explicit per-process override and must point to a compatible squid on these chains. Registry endpoints retain their independently configured dialect. Release this package before upgrading downstream clients such as Connect.

Base and Polygon registry reads also use squids. Set MECHX_REGISTRY_BASE_SQUID_URL and MECHX_REGISTRY_POLYGON_SQUID_URL; the ERC-8004 service lookup uses the existing serviceById adapter. Marketplace and registry endpoints/dialects stay independent. MECHX_REGISTRY_SUBGRAPH_URL remains a per-process endpoint override, and must use the chain's configured registry dialect.

Base/Polygon indexer endpoints are supplied by your deployment operator. Ask the Olas deployment maintainer for the Marketplace and service-registry squid URLs before using these chains; no default endpoints are bundled.

Metadata

Release files for mech-client 0.26.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mech-client 0.26.0
File Size Uploaded Provenance Actions
mech_client-0.26.0.tar.gz 284.0 kB Without provenance Details for mech_client-0.26.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mech-client 0.26.0
File Interpreter ABI Platform Actions
mech_client-0.26.0-py3-none-any.whl Python 3 none any Details for mech_client-0.26.0-py3-none-any.whl

Total release size: 647.8 kB

Release files / mech_client-0.26.0.tar.gz

Download URL mech_client-0.26.0.tar.gz
Size 284.0 kB
Tags Source
SHA-256 checksum
How to use checksums
efd59e08c4c2a4b120d9fb53a0c849651d840e8930ced01349f84abad754a0c9
BLAKE2b-256 checksum
How to use checksums
c3efaebed31b64fad9a90938988fe53dc351eda9733fe8eed1de06bc25554b33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mech_client-0.26.0-py3-none-any.whl

Download URL mech_client-0.26.0-py3-none-any.whl
Size 363.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9040870110ab469a07721be8a31900b7b42d9886ec083b63ff8f3366a4eda63e
BLAKE2b-256 checksum
How to use checksums
3365e7ab43cb4d655155ecb6b1cfba48fad4f47c98fa95af11a9657711e7c046
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for mech-client 0.26.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.26.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page